usb_crc.v 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * usb_crc.v
  3. *
  4. * vim: ts=4 sw=4
  5. *
  6. * Copyright (C) 2019 Sylvain Munaut
  7. * All rights reserved.
  8. *
  9. * LGPL v3+, see LICENSE.lgpl3
  10. *
  11. * This program is free software; you can redistribute it and/or
  12. * modify it under the terms of the GNU Lesser General Public
  13. * License as published by the Free Software Foundation; either
  14. * version 3 of the License, or (at your option) any later version.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  19. * Lesser General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Lesser General Public License
  22. * along with this program; if not, write to the Free Software Foundation,
  23. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  24. */
  25. `default_nettype none
  26. module usb_crc #(
  27. parameter integer WIDTH = 5,
  28. parameter POLY = 5'b00011,
  29. parameter MATCH = 5'b00000
  30. )(
  31. // Input
  32. input wire in_bit,
  33. input wire in_first,
  34. input wire in_valid,
  35. // Output (updated 1 cycle after input)
  36. output wire [WIDTH-1:0] crc,
  37. output wire crc_match,
  38. // Common
  39. input wire clk,
  40. input wire rst
  41. );
  42. reg [WIDTH-1:0] state;
  43. wire [WIDTH-1:0] state_fb_mux;
  44. wire [WIDTH-1:0] state_upd_mux;
  45. wire [WIDTH-1:0] state_nxt;
  46. assign state_fb_mux = state & { WIDTH{~in_first} };
  47. assign state_upd_mux = (state_fb_mux[WIDTH-1] == in_bit) ? POLY : 0;
  48. assign state_nxt = { state_fb_mux[WIDTH-2:0], 1'b1 } ^ state_upd_mux;
  49. always @(posedge clk)
  50. if (in_valid)
  51. state <= state_nxt;
  52. assign crc_match = (state == ~MATCH);
  53. genvar i;
  54. generate
  55. for (i=0; i<WIDTH; i=i+1)
  56. assign crc[i] = state[WIDTH-1-i];
  57. endgenerate
  58. endmodule // usb_crc