ethernetBridge.c 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdint.h>
  4. #include <pcilib.h>
  5. #include <pcilib/bar.h>
  6. #include <libsocket/libinetsocket.h>
  7. #define REG_FREQ_7BIT 0x91A0
  8. #define REG_BUSY_1BIT 0x91A4
  9. #pragma inline
  10. void write_reg_32(volatile void *bar, int addr, uint32_t value) {
  11. *((volatile uint32_t *) (((char*)bar) + addr)) = value;
  12. }
  13. #pragma inline
  14. uint32_t read_reg_32(volatile void *bar, int addr) {
  15. return *((volatile uint32_t *) (((char*)bar) + addr));
  16. }
  17. int main(int argc, char *argv[]) {
  18. pcilib_t *pci;
  19. pci = pcilib_open("/dev/fpga0", PCILIB_MODEL_DETECT);
  20. if (!pci) {
  21. printf("pcilib_open failed\n");
  22. exit(-1);
  23. }
  24. volatile void *bar = pcilib_resolve_bar_address(pci, PCILIB_BAR0, 0);
  25. if (!bar) {
  26. printf("Failed to map PCI BAR for access\n");
  27. pcilib_close(pci);
  28. exit(-1);
  29. }
  30. int socket;
  31. int ret;
  32. socket = create_inet_server_socket("0.0.0.0", "56000", LIBSOCKET_TCP, LIBSOCKET_IPv4, 0);
  33. if (socket < 0) {
  34. printf("Failed to create server listening socket\n");
  35. exit(-1);
  36. }
  37. printf("Ethernet socket created on port 56000.\n");
  38. while (1) {
  39. int peer_socket;
  40. char *peer_addr = calloc(16,1);
  41. printf("Waiting for incoming connection...\n");
  42. peer_socket = accept_inet_stream_socket(socket, peer_addr, 16, 0, 0, 0, 0);
  43. if (peer_socket < 0) {
  44. printf("Failed to accpet client connection\n");
  45. destroy_inet_socket(socket);
  46. exit(-1);
  47. }
  48. printf("Got connection from: %s\n", peer_addr);
  49. unsigned char *buf = calloc(1, 1);
  50. uint32_t val = 0;
  51. //We use 7-bit encoding. So any value larger than 127 is "invalid"
  52. //and can be used it for signalling.
  53. //We use 0xFF as the disconnect signal
  54. while (val != 0xFF) {
  55. //read() returns 0 in case of error
  56. ret = read (peer_socket, buf, 1);
  57. val = (*buf)&0xFF;
  58. if ((val == 0xFF) || (ret == 0)) {
  59. break;
  60. }
  61. printf("Received: %u\n", val);
  62. uint32_t busy = read_reg_32(bar, REG_BUSY_1BIT);
  63. if ((busy&0x1) == 0) {
  64. //Value needs to be stored in bits 1 - 7, because bit 0 is
  65. //used as a busy-bit
  66. uint32_t write_val = val << 1;
  67. write_val = write_val & 0xFF;
  68. write_reg_32(bar, REG_FREQ_7BIT, val);
  69. }
  70. }
  71. printf("Client disconnected.\n");
  72. destroy_inet_socket(peer_socket);
  73. free(buf);
  74. free(peer_addr);
  75. }
  76. destroy_inet_socket(socket);
  77. printf("All went well\n");
  78. pcilib_close(pci);
  79. return 0;
  80. }