Advertisement
LittleFox94

LinuxTap.c for UEFI emulator

Jun 6th, 2021
605
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 41.58 KB | None | 0 0
  1. /**@file
  2.  Linux Tap Network implementation of the EMU_SNP_PROTOCOL that allows the
  3.  emulator to get on real networks.
  4.  
  5. Copyright (c) 2004 - 2009, Intel Corporation. All rights reserved.<BR>
  6. Portions copyright (c) 2011, Apple Inc. All rights reserved.
  7. Most implementation copyright (c) 2021, Mara Sophie Grosch <littlefox@lf-net.org>
  8.  
  9. SPDX-License-Identifier: BSD-2-Clause-Patent
  10.  
  11. **/
  12.  
  13. #ifdef __linux__
  14.  
  15. #define _GNU_SOURCE
  16. #include <fcntl.h>
  17. #include <unistd.h>
  18.  
  19. #include <pthread.h>
  20. #include <poll.h>
  21. #include <arpa/inet.h>
  22. #include <linux/if_tun.h>
  23.  
  24. #include "Host.h"
  25.  
  26. typedef struct {
  27.   UINT8 *Buffer;
  28.   UINT64 Size;
  29.   UINTN  Enq;
  30.   UINTN  Deq;
  31.  
  32.   pthread_mutex_t Mutex;
  33.   int             DoorbellFd;
  34. } TAP_RING_BUFFER;
  35.  
  36. static
  37. EFI_STATUS
  38. TapRingBufferPush (
  39.   IN  TAP_RING_BUFFER *Ring,
  40.   IN  VOID            *Buffer,
  41.   IN  UINTN            BufferSize
  42.   )
  43. {
  44.   pthread_mutex_lock (&Ring->Mutex);
  45.  
  46.   if ((Ring->Size - Ring->Enq) + Ring->Deq < BufferSize + 2) {
  47.     pthread_mutex_unlock (&Ring->Mutex);
  48.     return EFI_NOT_READY;
  49.   }
  50.   else if (!Buffer) {
  51.     pthread_mutex_unlock (&Ring->Mutex);
  52.     return EFI_INVALID_PARAMETER;
  53.   }
  54.  
  55.   // we store the size of the packet right before the buffer
  56.   // so we can read whole packets. Ethernet frames do not
  57.   // include a size field themself.
  58.   ((UINT8*)Ring->Buffer)[Ring->Enq++]              = BufferSize >> 8;
  59.   ((UINT8*)Ring->Buffer)[Ring->Enq++ % Ring->Size] = BufferSize & 0xFF;
  60.  
  61.   UINTN rightChunkSize = (Ring->Size - Ring->Enq);
  62.  
  63.   if (rightChunkSize > BufferSize) {
  64.     rightChunkSize = BufferSize;
  65.   }
  66.  
  67.   memcpy (&Ring->Buffer[Ring->Enq], Buffer, rightChunkSize);
  68.   Ring->Enq += rightChunkSize;
  69.  
  70.   if (Ring->Enq == Ring->Size) {
  71.     Ring->Enq = 0;
  72.  
  73.     UINTN leftChunkSize = Ring->Deq - 1;
  74.  
  75.     if (leftChunkSize > BufferSize - rightChunkSize) {
  76.       leftChunkSize = BufferSize - rightChunkSize;
  77.     }
  78.  
  79.     memcpy (&Ring->Buffer[Ring->Enq], Buffer + rightChunkSize, leftChunkSize);
  80.     Ring->Enq += leftChunkSize;
  81.   }
  82.  
  83.   if (Ring->DoorbellFd >= 0) {
  84.     if (write (Ring->DoorbellFd, "P", 1) != 1) {
  85.       printf (
  86.         "SNP: error ringing doorbell: %s (%d).\n",
  87.         strerror(errno), errno
  88.         );
  89.     }
  90.   }
  91.  
  92.   pthread_mutex_unlock (&Ring->Mutex);
  93.   return EFI_SUCCESS;
  94. }
  95.  
  96. static
  97. EFI_STATUS
  98. TapRingBufferPop (
  99.   IN     TAP_RING_BUFFER *Ring,
  100.   OUT    VOID            *Buffer,
  101.   IN OUT UINTN           *BufferSize
  102.   )
  103. {
  104.   if (!BufferSize || !Ring) {
  105.     return EFI_INVALID_PARAMETER;
  106.   }
  107.  
  108.   pthread_mutex_lock (&Ring->Mutex);
  109.  
  110.   UINTN sizeInBuffer = Ring->Enq - Ring->Deq;
  111.  
  112.   if (sizeInBuffer >= 2) {
  113.     UINT16 packetSize = (UINT16)Ring->Buffer[ Ring->Deq                  ] << 8
  114.                       |         Ring->Buffer[(Ring->Deq + 1) % Ring->Size];
  115.     if (packetSize > *BufferSize) {
  116.       *BufferSize = packetSize;
  117.       pthread_mutex_unlock (&Ring->Mutex);
  118.       return EFI_BUFFER_TOO_SMALL;
  119.     }
  120.     else if (!Buffer) {
  121.       pthread_mutex_unlock (&Ring->Mutex);
  122.       return EFI_INVALID_PARAMETER;
  123.     }
  124.  
  125.     // we have checked everything, lets increase Deq by the packet size
  126.     // do not add failure-returns here without caring for Deq!
  127.     Ring->Deq += 2;
  128.  
  129.     UINTN rightChunkSize = Ring->Deq  < Ring->Enq
  130.                          ? Ring->Enq  - Ring->Deq
  131.                          : Ring->Size - Ring->Deq;
  132.  
  133.     if (rightChunkSize > packetSize) {
  134.       rightChunkSize = packetSize;
  135.     }
  136.  
  137.     memcpy (Buffer, &Ring->Buffer[Ring->Deq], rightChunkSize);
  138.     Ring->Deq += rightChunkSize;
  139.  
  140.     if (Ring->Deq == Ring->Size) {
  141.       Ring->Deq = 0;
  142.  
  143.       UINTN leftChunkSize = Ring->Enq;
  144.  
  145.       if (leftChunkSize > packetSize - rightChunkSize) {
  146.         leftChunkSize = packetSize - rightChunkSize;
  147.       }
  148.  
  149.       if (leftChunkSize) {
  150.         memcpy (Buffer + rightChunkSize, Ring->Buffer, leftChunkSize);
  151.         Ring->Deq += leftChunkSize;
  152.       }
  153.     }
  154.  
  155.     pthread_mutex_unlock (&Ring->Mutex);
  156.     return EFI_SUCCESS;
  157.   }
  158.   else {
  159.     pthread_mutex_unlock (&Ring->Mutex);
  160.     return EFI_NOT_READY;
  161.   }
  162. }
  163.  
  164. #define EMU_SNP_PRIVATE_SIGNATURE SIGNATURE_32('L', 'T', 's', 'n') // Linux Tap simple network
  165. typedef struct {
  166.   UINTN                       Signature;
  167.  
  168.   EMU_IO_THUNK_PROTOCOL       *Thunk;
  169.  
  170.  
  171.   EMU_SNP_PROTOCOL            EmuSnp;
  172.   EFI_SIMPLE_NETWORK_MODE     *Mode;
  173.  
  174.   int                         TapFd;
  175.   int                         TapWorkerDoorbell[2];
  176.   pthread_t                   WorkerThread;
  177.  
  178.   TAP_RING_BUFFER             TxBuffer;
  179.   TAP_RING_BUFFER             RxBuffer;
  180.  
  181. } EMU_SNP_PRIVATE;
  182.  
  183. #define EMU_SNP_PRIVATE_DATA_FROM_THIS(a) \
  184.          CR(a, EMU_SNP_PRIVATE, EmuSnp, EMU_SNP_PRIVATE_SIGNATURE)
  185.  
  186. static
  187. VOID*
  188. TapWorker (
  189.   IN VOID* PrivatePtr
  190.   )
  191. {
  192.   // first we have to disable the alarm signal,
  193.   // UEFI timers will be executed on this thread otherwise
  194.   sigset_t signals;
  195.   sigemptyset (&signals);
  196.   sigaddset (&signals, SIGALRM);
  197.   pthread_sigmask (SIG_BLOCK, &signals, NULL);
  198.  
  199.   EMU_SNP_PRIVATE *Private = (EMU_SNP_PRIVATE*)PrivatePtr;
  200.  
  201.   int packetsToTransmit = 0;
  202.  
  203.   // packets to and from the tap interface are stored here
  204.   // so we don't have to enqueue them in the same loop
  205.   UINT8 *readPacket     = 0, *writePacket     = 0;
  206.   UINTN  readPacketSize = 0,  writePacketSize = 0;
  207.  
  208.   struct pollfd pfds[] = {
  209.     { .fd = Private->TapFd,                .events = POLLIN | POLLOUT },
  210.     { .fd = Private->TapWorkerDoorbell[0], .events = POLLIN },
  211.   };
  212.  
  213.   while(1) {
  214.     int error = poll(pfds, sizeof(pfds) / sizeof(struct pollfd), -1);
  215.  
  216.     if(error < 0) {
  217.       printf (
  218.         "SNP: received an error while polling for work: %s (%d).\n",
  219.         strerror(errno), errno
  220.         );
  221.     }
  222.  
  223.     if (pfds[1].revents & POLLIN  || 1) {
  224.       char command;
  225.       while(read (Private->TapWorkerDoorbell[0], &command, 1) == 1) {
  226.         switch (command) {
  227.           case 'E':
  228.             return NULL;
  229.           case 'P':
  230.             ++packetsToTransmit;
  231.             break;
  232.         }
  233.       }
  234.     }
  235.  
  236.     if (pfds[0].revents & POLLIN && !readPacket) {
  237.       readPacketSize = 9000;
  238.       readPacket     = malloc(readPacketSize);
  239.       ssize_t size   = read (Private->TapFd, readPacket, readPacketSize);
  240.  
  241.       if (size < 0) {
  242.         printf (
  243.           "SNP: error read()ing packet: %s (%d).\n",
  244.           strerror(errno), errno
  245.           );
  246.       }
  247.       else {
  248.         readPacketSize = size;
  249.       }
  250.     }
  251.  
  252.     if (pfds[0].revents & POLLOUT && writePacket) {
  253.       ssize_t sendSize = write (Private->TapFd, writePacket, writePacketSize);
  254.  
  255.       if (sendSize < 0) {
  256.         printf (
  257.           "SNP: error write()ing packet: %s (%d).\n",
  258.           strerror(errno), errno
  259.           );
  260.       }
  261.       else {
  262.         if (sendSize < writePacketSize) {
  263.           printf (
  264.             "SNP: write() packet shorter (%ld B) than the size we wanted to send(%llu B).\n",
  265.             sendSize, writePacketSize
  266.             );
  267.         }
  268.  
  269.         free(writePacket);
  270.         writePacket     = 0;
  271.         writePacketSize = 0;
  272.       }
  273.     }
  274.  
  275.     EFI_STATUS status = TapRingBufferPush (&Private->RxBuffer, readPacket, readPacketSize);
  276.  
  277.     if (status == EFI_SUCCESS) {
  278.       free (readPacket);
  279.       readPacket     = 0;
  280.       readPacketSize = 0;
  281.     }
  282.  
  283.     if (packetsToTransmit && !writePacket) {
  284.       status = TapRingBufferPop (&Private->TxBuffer, NULL, &writePacketSize);
  285.  
  286.       if (status == EFI_BUFFER_TOO_SMALL) {
  287.         writePacket = malloc (writePacketSize);
  288.         status      = TapRingBufferPop (&Private->TxBuffer, writePacket, &writePacketSize);
  289.  
  290.         if (status == EFI_SUCCESS) {
  291.           --packetsToTransmit;
  292.         }
  293.         else {
  294.           printf (
  295.             "SNP: error dequeueing packet from Tx buffer: %llu.\n",
  296.             status
  297.             );
  298.         }
  299.       }
  300.     }
  301.   }
  302. }
  303.  
  304. /**
  305.   Register storage for SNP Mode.
  306.  
  307.   @param  This Protocol instance pointer.
  308.   @param  Mode SimpleNetworkProtocol Mode structure passed into driver.
  309.  
  310.   @retval EFI_SUCCESS           The network interface was started.
  311.   @retval EFI_INVALID_PARAMETER One or more of the parameters has an unsupported value.
  312.  
  313. **/
  314. EFI_STATUS
  315. EmuSnpCreateMapping (
  316.   IN     EMU_SNP_PROTOCOL         *This,
  317.   IN     EFI_SIMPLE_NETWORK_MODE  *Mode
  318.   )
  319. {
  320.   EMU_SNP_PRIVATE    *Private;
  321.  
  322.   Private = EMU_SNP_PRIVATE_DATA_FROM_THIS (This);
  323.  
  324.   char* ifname = "uefiEmu";
  325.   Private->TapFd = open ("/dev/net/tun", O_RDWR | O_NONBLOCK);
  326.  
  327.   if (Private->TapFd < 0) {
  328.     printf (
  329.       "SNP: Could not open '/dev/net/tun': %s (%d). Trying older kernel interface.\n",
  330.       strerror(-Private->TapFd), -Private->TapFd
  331.       );
  332.  
  333.     char fname[IFNAMSIZ];
  334.     snprintf (fname, IFNAMSIZ - 1, "/dev/%s", ifname);
  335.  
  336.     Private->TapFd = open (fname, O_RDWR | O_NONBLOCK);
  337.  
  338.     if (Private->TapFd < 0) {
  339.       printf (
  340.         "SNP: Could not open '%s': %s (%d).\n",
  341.         fname,
  342.         strerror(-Private->TapFd), -Private->TapFd
  343.         );
  344.  
  345.       return EFI_DEVICE_ERROR;
  346.     }
  347.   }
  348.   else {
  349.     struct ifreq ifr;
  350.     ZeroMem (&ifr, sizeof(ifr));
  351.  
  352.     ifr.ifr_flags = IFF_TAP;
  353.     strncpy (ifr.ifr_name, ifname, IFNAMSIZ);
  354.  
  355.     int err = ioctl (Private->TapFd, TUNSETIFF, &ifr);
  356.  
  357.     if(err < 0) {
  358.       close (Private->TapFd);
  359.       printf (
  360.         "SNP: Could not open tap interface '%s': %s (%d).\n",
  361.         ifname,
  362.         strerror (-err),- err
  363.         );
  364.  
  365.       return EFI_DEVICE_ERROR;
  366.     }
  367.   }
  368.  
  369.   struct ifreq ifr;
  370.   ZeroMem (&ifr, sizeof (ifr));
  371.   int error = ioctl (Private->TapFd, SIOCGIFHWADDR, &ifr);
  372.  
  373.   if(error < 0) {
  374.     printf (
  375.       "SNP: error retrieving interface info: %s (%d). Will continue with dummy mac.\n",
  376.       strerror (errno), errno
  377.       );
  378.  
  379.     CopyMem(&ifr.ifr_addr.sa_data, (UINT8[]){ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55 }, ETH_ALEN);
  380.   }
  381.   else {
  382.       // prevent MAC conflict: use Host-side of TAP + 1
  383.       ifr.ifr_addr.sa_data[ETH_ALEN - 1]++;
  384.   }
  385.  
  386. //  error = pipe2(Private->TapWorkerDoorbell, O_DIRECT);
  387. //
  388. //  if (error) {
  389. //    printf(
  390. //      "SNP: Failed to create doorbell pipe: %s (%d).\n",
  391. //      strerror(errno), errno
  392. //      );
  393. //
  394. //    return EFI_DEVICE_ERROR;
  395. //  }
  396. //
  397. //  Private->TxBuffer.DoorbellFd = Private->TapWorkerDoorbell[1];
  398. //  Private->RxBuffer.DoorbellFd = -1;
  399. //
  400.   printf (
  401.     "SNP: opened tap interface '%s' as endpoint for emulator network device.\n",
  402.     ifname
  403.     );
  404.  
  405.   Private->Mode = Mode;
  406.  
  407.   Private->Mode->HwAddressSize = ETH_ALEN;
  408.   SetMem  (&Private->Mode->BroadcastAddress, ETH_ALEN, 0xFF);
  409.   CopyMem (&Private->Mode->CurrentAddress,   &ifr.ifr_addr.sa_data, ETH_ALEN);
  410.   CopyMem (&Private->Mode->PermanentAddress, &ifr.ifr_addr.sa_data, ETH_ALEN);
  411.  
  412.   Private->TxBuffer.Size = Private->TxBuffer.Enq = Private->TxBuffer.Deq = 0;
  413.   Private->RxBuffer.Size = Private->RxBuffer.Enq = Private->RxBuffer.Deq = 0;
  414.  
  415. //  if ((error = pthread_mutex_init(&Private->TxBuffer.Mutex, NULL)) != 0) {
  416. //   printf (
  417. //     "SNP: error initializing mutex for tx buffer: %s (%d).\n",
  418. //     strerror(error), error
  419. //     );
  420. //  }
  421. //
  422. //  if ((error = pthread_mutex_init(&Private->RxBuffer.Mutex, NULL)) != 0) {
  423. //   printf (
  424. //     "SNP: error initializing mutex for rx buffer: %s (%d).\n",
  425. //     strerror(error), error
  426. //     );
  427. //  }
  428.  
  429.   return EFI_SUCCESS;
  430. }
  431.  
  432. /**
  433.   Changes the state of a network interface from "stopped" to "started".
  434.  
  435.   @param  This Protocol instance pointer.
  436.  
  437.   @retval EFI_SUCCESS           The network interface was started.
  438.   @retval EFI_ALREADY_STARTED   The network interface is already in the started state.
  439.   @retval EFI_INVALID_PARAMETER One or more of the parameters has an unsupported value.
  440.   @retval EFI_DEVICE_ERROR      The command could not be sent to the network interface.
  441.   @retval EFI_UNSUPPORTED       This function is not supported by the network interface.
  442.  
  443. **/
  444. EFI_STATUS
  445. EmuSnpStart (
  446.   IN EMU_SNP_PROTOCOL  *This
  447.   )
  448. {
  449.   EMU_SNP_PRIVATE    *Private;
  450.  
  451.   Private = EMU_SNP_PRIVATE_DATA_FROM_THIS (This);
  452.  
  453.   if(Private->Mode->State != EfiSimpleNetworkStopped) {
  454.     return EFI_ALREADY_STARTED;
  455.   }
  456.  
  457.   struct ifreq ifr;
  458.   ZeroMem (&ifr, sizeof (ifr));
  459.   ifr.ifr_flags = IFF_UP;
  460.  
  461.   int error = ioctl (Private->TapFd, TUNSETLINK, &ifr);
  462.  
  463.   // EBUSY means it's already up, maybe from a previous run
  464.   if (error == -1 && errno != EBUSY) {
  465.     printf (
  466.       "SNP: failed to set link up: %s (%d)",
  467.       strerror (errno), errno
  468.       );
  469.  
  470.     return EFI_DEVICE_ERROR;
  471.   }
  472.  
  473. //  error = pthread_create (&Private->WorkerThread, NULL, TapWorker, Private);
  474. //
  475. //  if(error) {
  476. //    printf (
  477. //      "SNP: failed to start worker thread: %s (%d)",
  478. //      strerror (error), error
  479. //      );
  480. //
  481. //    return EFI_DEVICE_ERROR;
  482. //  }
  483.  
  484.   Private->Mode->State = EfiSimpleNetworkStarted;
  485.  
  486.   return EFI_SUCCESS;
  487. }
  488.  
  489. /**
  490.   Changes the state of a network interface from "started" to "stopped".
  491.  
  492.   @param  This Protocol instance pointer.
  493.  
  494.   @retval EFI_SUCCESS           The network interface was stopped.
  495.   @retval EFI_ALREADY_STARTED   The network interface is already in the stopped state.
  496.   @retval EFI_INVALID_PARAMETER One or more of the parameters has an unsupported value.
  497.   @retval EFI_DEVICE_ERROR      The command could not be sent to the network interface.
  498.   @retval EFI_UNSUPPORTED       This function is not supported by the network interface.
  499.  
  500. **/
  501. EFI_STATUS
  502. EmuSnpStop (
  503.   IN EMU_SNP_PROTOCOL  *This
  504.   )
  505. {
  506.   EMU_SNP_PRIVATE    *Private;
  507.  
  508.   Private = EMU_SNP_PRIVATE_DATA_FROM_THIS (This);
  509.  
  510.   if(Private->Mode->State == EfiSimpleNetworkStopped) {
  511.     return EFI_ALREADY_STARTED;
  512.   }
  513.  
  514.   struct ifreq ifr;
  515.   ZeroMem (&ifr, sizeof (ifr));
  516.  
  517.   int error = ioctl (Private->TapFd, TUNSETLINK, &ifr);
  518.  
  519.   if (error == -1) {
  520.     printf (
  521.       "SNP: failed to set link down: %s (%d)",
  522.       strerror (errno), errno
  523.       );
  524.  
  525.     return EFI_DEVICE_ERROR;
  526.   }
  527.  
  528. //  if (write (Private->TapWorkerDoorbell[1], "E", 1) != 1) {
  529. //    printf (
  530. //      "SNP: error ringing for stop: %s (%d).\n",
  531. //      strerror(errno), errno
  532. //      );
  533. //  }
  534. //
  535. //  pthread_join (Private->WorkerThread, NULL);
  536. //
  537. //  Private->TxBuffer.Size = Private->TxBuffer.Enq = Private->TxBuffer.Deq = 0;
  538. //  Private->RxBuffer.Size = Private->RxBuffer.Enq = Private->RxBuffer.Deq = 0;
  539. //
  540.   Private->Mode->State = EfiSimpleNetworkStopped;
  541.  
  542.   return EFI_SUCCESS;
  543. }
  544.  
  545. /**
  546.   Resets a network adapter and allocates the transmit and receive buffers
  547.   required by the network interface; optionally, also requests allocation
  548.   of additional transmit and receive buffers.
  549.  
  550.   @param  This              The protocol instance pointer.
  551.   @param  ExtraRxBufferSize The size, in bytes, of the extra receive buffer space
  552.                             that the driver should allocate for the network interface.
  553.                             Some network interfaces will not be able to use the extra
  554.                             buffer, and the caller will not know if it is actually
  555.                             being used.
  556.   @param  ExtraTxBufferSize The size, in bytes, of the extra transmit buffer space
  557.                             that the driver should allocate for the network interface.
  558.                             Some network interfaces will not be able to use the extra
  559.                             buffer, and the caller will not know if it is actually
  560.                             being used.
  561.  
  562.   @retval EFI_SUCCESS           The network interface was initialized.
  563.   @retval EFI_NOT_STARTED       The network interface has not been started.
  564.   @retval EFI_OUT_OF_RESOURCES  There was not enough memory for the transmit and
  565.                                 receive buffers.
  566.   @retval EFI_INVALID_PARAMETER One or more of the parameters has an unsupported value.
  567.   @retval EFI_DEVICE_ERROR      The command could not be sent to the network interface.
  568.   @retval EFI_UNSUPPORTED       This function is not supported by the network interface.
  569.  
  570. **/
  571. EFI_STATUS
  572. EmuSnpInitialize (
  573.   IN EMU_SNP_PROTOCOL                    *This,
  574.   IN UINTN                               ExtraRxBufferSize  OPTIONAL,
  575.   IN UINTN                               ExtraTxBufferSize  OPTIONAL
  576.   )
  577. {
  578.   EMU_SNP_PRIVATE    *Private;
  579.  
  580.   Private = EMU_SNP_PRIVATE_DATA_FROM_THIS (This);
  581.  
  582.   switch(Private->Mode->State) {
  583.     case EfiSimpleNetworkStarted:
  584.       break;
  585.  
  586.     case EfiSimpleNetworkStopped:
  587.       return EFI_NOT_STARTED;
  588.       break;
  589.  
  590.     default:
  591.       return EFI_DEVICE_ERROR;
  592.       break;
  593.   }
  594.  
  595. //  Private->TxBuffer.Size = Private->TxBuffer.Enq = Private->TxBuffer.Deq = 0;
  596. //  Private->RxBuffer.Size = Private->RxBuffer.Enq = Private->RxBuffer.Deq = 0;
  597. //
  598. //  static const UINTN bufferSizeMin = 65536;
  599. //
  600. //  if (ExtraRxBufferSize < bufferSizeMin) {
  601. //      ExtraRxBufferSize = bufferSizeMin;
  602. //  }
  603. //
  604. //  if (ExtraTxBufferSize < bufferSizeMin) {
  605. //      ExtraTxBufferSize = bufferSizeMin;
  606. //  }
  607. //
  608. //  Private->TxBuffer.Buffer = malloc (ExtraTxBufferSize);
  609. //  Private->TxBuffer.Size = ExtraTxBufferSize;
  610. //
  611. //  Private->RxBuffer.Buffer = malloc (ExtraRxBufferSize);
  612. //  Private->RxBuffer.Size = ExtraRxBufferSize;
  613.  
  614.   Private->Mode->State = EfiSimpleNetworkInitialized;
  615.  
  616.   return EFI_SUCCESS;
  617. }
  618.  
  619. /**
  620.   Resets a network adapter and re-initializes it with the parameters that were
  621.   provided in the previous call to Initialize().
  622.  
  623.   @param  This                 The protocol instance pointer.
  624.   @param  ExtendedVerification Indicates that the driver may perform a more
  625.                                exhaustive verification operation of the device
  626.                                during reset.
  627.  
  628.   @retval EFI_SUCCESS           The network interface was reset.
  629.   @retval EFI_NOT_STARTED       The network interface has not been started.
  630.   @retval EFI_INVALID_PARAMETER One or more of the parameters has an unsupported value.
  631.   @retval EFI_DEVICE_ERROR      The command could not be sent to the network interface.
  632.   @retval EFI_UNSUPPORTED       This function is not supported by the network interface.
  633.  
  634. **/
  635. EFI_STATUS
  636. EmuSnpReset (
  637.   IN EMU_SNP_PROTOCOL   *This,
  638.   IN BOOLEAN            ExtendedVerification
  639.   )
  640. {
  641.   EMU_SNP_PRIVATE    *Private;
  642.  
  643.   Private = EMU_SNP_PRIVATE_DATA_FROM_THIS (This);
  644.  
  645.   switch(Private->Mode->State) {
  646.     case EfiSimpleNetworkInitialized:
  647.       break;
  648.  
  649.     case EfiSimpleNetworkStopped:
  650.       return EFI_NOT_STARTED;
  651.       break;
  652.  
  653.     default:
  654.       return EFI_DEVICE_ERROR;
  655.       break;
  656.   }
  657.  
  658. //  Private->TxBuffer.Deq = Private->TxBuffer.Enq = 0;
  659. //  Private->RxBuffer.Deq = Private->RxBuffer.Enq = 0;
  660. //
  661. //  ZeroMem(Private->TxBuffer.Buffer, Private->TxBuffer.Size);
  662. //  ZeroMem(Private->RxBuffer.Buffer, Private->RxBuffer.Size);
  663. //
  664.   Private->Mode->State = EfiSimpleNetworkStarted;
  665.  
  666.   return EFI_SUCCESS;
  667. }
  668.  
  669. /**
  670.   Resets a network adapter and leaves it in a state that is safe for
  671.   another driver to initialize.
  672.  
  673.   @param  This Protocol instance pointer.
  674.  
  675.   @retval EFI_SUCCESS           The network interface was shutdown.
  676.   @retval EFI_NOT_STARTED       The network interface has not been started.
  677.   @retval EFI_INVALID_PARAMETER One or more of the parameters has an unsupported value.
  678.   @retval EFI_DEVICE_ERROR      The command could not be sent to the network interface.
  679.   @retval EFI_UNSUPPORTED       This function is not supported by the network interface.
  680.  
  681. **/
  682. EFI_STATUS
  683. EmuSnpShutdown (
  684.   IN EMU_SNP_PROTOCOL  *This
  685.   )
  686. {
  687.   EMU_SNP_PRIVATE    *Private;
  688.  
  689.   Private = EMU_SNP_PRIVATE_DATA_FROM_THIS (This);
  690.  
  691.   switch(Private->Mode->State) {
  692.     case EfiSimpleNetworkInitialized:
  693.       break;
  694.  
  695.     case EfiSimpleNetworkStopped:
  696.       return EFI_NOT_STARTED;
  697.       break;
  698.  
  699.     default:
  700.       return EFI_DEVICE_ERROR;
  701.       break;
  702.   }
  703.  
  704. //  if (write (Private->TapWorkerDoorbell[1], "E", 1) != 1) {
  705. //    printf (
  706. //      "SNP: error ringing for stop: %s (%d).\n",
  707. //      strerror(errno), errno
  708. //      );
  709. //  }
  710. //
  711. //  pthread_join (Private->WorkerThread, NULL);
  712. //
  713. //  Private->TxBuffer.Size = Private->TxBuffer.Deq = Private->TxBuffer.Enq = 0;
  714. //  Private->RxBuffer.Size = Private->RxBuffer.Deq = Private->RxBuffer.Enq = 0;
  715. //
  716. //  free (Private->TxBuffer.Buffer);
  717. //  free (Private->RxBuffer.Buffer);
  718.  
  719.   Private->Mode->ReceiveFilterSetting = 0;
  720.   Private->Mode->MCastFilterCount = 0;
  721.   ZeroMem (Private->Mode->MCastFilter, sizeof (Private->Mode->MCastFilter));
  722.  
  723.   Private->Mode->State = EfiSimpleNetworkStarted;
  724.  
  725.   return EFI_SUCCESS;
  726. }
  727.  
  728. /**
  729.   Manages the multicast receive filters of a network interface.
  730.  
  731.   @param  This             The protocol instance pointer.
  732.   @param  Enable           A bit mask of receive filters to enable on the network interface.
  733.   @param  Disable          A bit mask of receive filters to disable on the network interface.
  734.   @param  ResetMCastFilter Set to TRUE to reset the contents of the multicast receive
  735.                            filters on the network interface to their default values.
  736.   @param  McastFilterCnt   Number of multicast HW MAC addresses in the new
  737.                            MCastFilter list. This value must be less than or equal to
  738.                            the MCastFilterCnt field of EMU_SNP_MODE. This
  739.                            field is optional if ResetMCastFilter is TRUE.
  740.   @param  MCastFilter      A pointer to a list of new multicast receive filter HW MAC
  741.                            addresses. This list will replace any existing multicast
  742.                            HW MAC address list. This field is optional if
  743.                            ResetMCastFilter is TRUE.
  744.  
  745.   @retval EFI_SUCCESS           The multicast receive filter list was updated.
  746.   @retval EFI_NOT_STARTED       The network interface has not been started.
  747.   @retval EFI_INVALID_PARAMETER One or more of the parameters has an unsupported value.
  748.   @retval EFI_DEVICE_ERROR      The command could not be sent to the network interface.
  749.   @retval EFI_UNSUPPORTED       This function is not supported by the network interface.
  750.  
  751. **/
  752. EFI_STATUS
  753. EmuSnpReceiveFilters (
  754.   IN EMU_SNP_PROTOCOL                             *This,
  755.   IN UINT32                                       Enable,
  756.   IN UINT32                                       Disable,
  757.   IN BOOLEAN                                      ResetMCastFilter,
  758.   IN UINTN                                        MCastFilterCnt     OPTIONAL,
  759.   IN EFI_MAC_ADDRESS                              *MCastFilter OPTIONAL
  760.   )
  761. {
  762.   EMU_SNP_PRIVATE    *Private;
  763.  
  764.   Private = EMU_SNP_PRIVATE_DATA_FROM_THIS (This);
  765.  
  766.   return EFI_SUCCESS;
  767. }
  768.  
  769. /**
  770.   Modifies or resets the current station address, if supported.
  771.  
  772.   @param  This  The protocol instance pointer.
  773.   @param  Reset Flag used to reset the station address to the network interfaces
  774.                 permanent address.
  775.   @param  New   The new station address to be used for the network interface.
  776.  
  777.   @retval EFI_SUCCESS           The network interfaces station address was updated.
  778.   @retval EFI_NOT_STARTED       The network interface has not been started.
  779.   @retval EFI_INVALID_PARAMETER One or more of the parameters has an unsupported value.
  780.   @retval EFI_DEVICE_ERROR      The command could not be sent to the network interface.
  781.   @retval EFI_UNSUPPORTED       This function is not supported by the network interface.
  782.  
  783. **/
  784. EFI_STATUS
  785. EmuSnpStationAddress (
  786.   IN EMU_SNP_PROTOCOL            *This,
  787.   IN BOOLEAN                     Reset,
  788.   IN EFI_MAC_ADDRESS             *New OPTIONAL
  789.   )
  790. {
  791.   EMU_SNP_PRIVATE    *Private;
  792.  
  793.   Private = EMU_SNP_PRIVATE_DATA_FROM_THIS (This);
  794.  
  795.   switch(Private->Mode->State) {
  796.     case EfiSimpleNetworkInitialized:
  797.       break;
  798.  
  799.     case EfiSimpleNetworkStopped:
  800.       return EFI_NOT_STARTED;
  801.       break;
  802.  
  803.     default:
  804.       return EFI_DEVICE_ERROR;
  805.       break;
  806.   }
  807.  
  808.   struct ifreq ifr;
  809.   SetMem (&ifr, sizeof (ifr), 0);
  810.  
  811.   if ((New && Reset) || (!New && !Reset)) {
  812.       return EFI_INVALID_PARAMETER;
  813.   }
  814.   else if (New) {
  815.     CopyMem(&ifr.ifr_hwaddr, New, ETH_ALEN);
  816.   }
  817.   else if (Reset) {
  818.     CopyMem(&ifr.ifr_hwaddr, &Private->Mode->PermanentAddress, ETH_ALEN);
  819.   }
  820.  
  821.   int error = ioctl (Private->TapFd, SIOCSIFHWADDR, &ifr);
  822.  
  823.   if(error) {
  824.     return EFI_DEVICE_ERROR;
  825.   }
  826.  
  827.   return EFI_SUCCESS;
  828. }
  829.  
  830. /**
  831.   Resets or collects the statistics on a network interface.
  832.  
  833.   @param  This            Protocol instance pointer.
  834.   @param  Reset           Set to TRUE to reset the statistics for the network interface.
  835.   @param  StatisticsSize  On input the size, in bytes, of StatisticsTable. On
  836.                           output the size, in bytes, of the resulting table of
  837.                           statistics.
  838.   @param  StatisticsTable A pointer to the EFI_NETWORK_STATISTICS structure that
  839.                           contains the statistics.
  840.  
  841.   @retval EFI_SUCCESS           The statistics were collected from the network interface.
  842.   @retval EFI_NOT_STARTED       The network interface has not been started.
  843.   @retval EFI_BUFFER_TOO_SMALL  The Statistics buffer was too small. The current buffer
  844.                                 size needed to hold the statistics is returned in
  845.                                 StatisticsSize.
  846.   @retval EFI_INVALID_PARAMETER One or more of the parameters has an unsupported value.
  847.   @retval EFI_DEVICE_ERROR      The command could not be sent to the network interface.
  848.   @retval EFI_UNSUPPORTED       This function is not supported by the network interface.
  849.  
  850. **/
  851. EFI_STATUS
  852. EmuSnpStatistics (
  853.   IN EMU_SNP_PROTOCOL                     *This,
  854.   IN BOOLEAN                              Reset,
  855.   IN OUT UINTN                            *StatisticsSize   OPTIONAL,
  856.   OUT EFI_NETWORK_STATISTICS              *StatisticsTable  OPTIONAL
  857.   )
  858. {
  859.   EMU_SNP_PRIVATE    *Private;
  860.  
  861.   Private = EMU_SNP_PRIVATE_DATA_FROM_THIS (This);
  862.  
  863.   return EFI_UNSUPPORTED;
  864. }
  865.  
  866. /**
  867.   Converts a multicast IP address to a multicast HW MAC address.
  868.  
  869.   @param  This The protocol instance pointer.
  870.   @param  IPv6 Set to TRUE if the multicast IP address is IPv6 [RFC 2460]. Set
  871.                to FALSE if the multicast IP address is IPv4 [RFC 791].
  872.   @param  IP   The multicast IP address that is to be converted to a multicast
  873.                HW MAC address.
  874.   @param  MAC  The multicast HW MAC address that is to be generated from IP.
  875.  
  876.   @retval EFI_SUCCESS           The multicast IP address was mapped to the multicast
  877.                                 HW MAC address.
  878.   @retval EFI_NOT_STARTED       The network interface has not been started.
  879.   @retval EFI_BUFFER_TOO_SMALL  The Statistics buffer was too small. The current buffer
  880.                                 size needed to hold the statistics is returned in
  881.                                 StatisticsSize.
  882.   @retval EFI_INVALID_PARAMETER One or more of the parameters has an unsupported value.
  883.   @retval EFI_DEVICE_ERROR      The command could not be sent to the network interface.
  884.   @retval EFI_UNSUPPORTED       This function is not supported by the network interface.
  885.  
  886. **/
  887. EFI_STATUS
  888. EmuSnpMCastIpToMac (
  889.   IN EMU_SNP_PROTOCOL                     *This,
  890.   IN BOOLEAN                              IPv6,
  891.   IN EFI_IP_ADDRESS                       *IP,
  892.   OUT EFI_MAC_ADDRESS                     *MAC
  893.   )
  894. {
  895.   EMU_SNP_PRIVATE    *Private;
  896.  
  897.   Private = EMU_SNP_PRIVATE_DATA_FROM_THIS (This);
  898.  
  899.   return EFI_UNSUPPORTED;
  900. }
  901.  
  902. /**
  903.   Performs read and write operations on the NVRAM device attached to a
  904.   network interface.
  905.  
  906.   @param  This       The protocol instance pointer.
  907.   @param  ReadWrite  TRUE for read operations, FALSE for write operations.
  908.   @param  Offset     Byte offset in the NVRAM device at which to start the read or
  909.                      write operation. This must be a multiple of NvRamAccessSize and
  910.                      less than NvRamSize.
  911.   @param  BufferSize The number of bytes to read or write from the NVRAM device.
  912.                      This must also be a multiple of NvramAccessSize.
  913.   @param  Buffer     A pointer to the data buffer.
  914.  
  915.   @retval EFI_SUCCESS           The NVRAM access was performed.
  916.   @retval EFI_NOT_STARTED       The network interface has not been started.
  917.   @retval EFI_INVALID_PARAMETER One or more of the parameters has an unsupported value.
  918.   @retval EFI_DEVICE_ERROR      The command could not be sent to the network interface.
  919.   @retval EFI_UNSUPPORTED       This function is not supported by the network interface.
  920.  
  921. **/
  922. EFI_STATUS
  923. EmuSnpNvData (
  924.   IN EMU_SNP_PROTOCOL                     *This,
  925.   IN BOOLEAN                              ReadWrite,
  926.   IN UINTN                                Offset,
  927.   IN UINTN                                BufferSize,
  928.   IN OUT VOID                             *Buffer
  929.   )
  930. {
  931.   EMU_SNP_PRIVATE    *Private;
  932.  
  933.   Private = EMU_SNP_PRIVATE_DATA_FROM_THIS (This);
  934.  
  935.   return EFI_UNSUPPORTED;
  936. }
  937.  
  938. /**
  939.   Reads the current interrupt status and recycled transmit buffer status from
  940.   a network interface.
  941.  
  942.   @param  This            The protocol instance pointer.
  943.   @param  InterruptStatus A pointer to the bit mask of the currently active interrupts
  944.                           If this is NULL, the interrupt status will not be read from
  945.                           the device. If this is not NULL, the interrupt status will
  946.                           be read from the device. When the  interrupt status is read,
  947.                           it will also be cleared. Clearing the transmit  interrupt
  948.                           does not empty the recycled transmit buffer array.
  949.   @param  TxBuf           Recycled transmit buffer address. The network interface will
  950.                           not transmit if its internal recycled transmit buffer array
  951.                           is full. Reading the transmit buffer does not clear the
  952.                           transmit interrupt. If this is NULL, then the transmit buffer
  953.                           status will not be read. If there are no transmit buffers to
  954.                           recycle and TxBuf is not NULL, * TxBuf will be set to NULL.
  955.  
  956.   @retval EFI_SUCCESS           The status of the network interface was retrieved.
  957.   @retval EFI_NOT_STARTED       The network interface has not been started.
  958.   @retval EFI_INVALID_PARAMETER One or more of the parameters has an unsupported value.
  959.   @retval EFI_DEVICE_ERROR      The command could not be sent to the network interface.
  960.   @retval EFI_UNSUPPORTED       This function is not supported by the network interface.
  961.  
  962. **/
  963. EFI_STATUS
  964. EmuSnpGetStatus (
  965.   IN EMU_SNP_PROTOCOL                     *This,
  966.   OUT UINT32                              *InterruptStatus OPTIONAL,
  967.   OUT VOID                                **TxBuf OPTIONAL
  968.   )
  969. {
  970.   EMU_SNP_PRIVATE    *Private;
  971.  
  972.   Private = EMU_SNP_PRIVATE_DATA_FROM_THIS (This);
  973.  
  974.   if ( InterruptStatus != NULL ) {
  975.     *InterruptStatus = EFI_SIMPLE_NETWORK_TRANSMIT_INTERRUPT;
  976.   }
  977.  
  978.   return EFI_SUCCESS;
  979. }
  980.  
  981. /**
  982.   Places a packet in the transmit queue of a network interface.
  983.  
  984.   @param  This       The protocol instance pointer.
  985.   @param  HeaderSize The size, in bytes, of the media header to be filled in by
  986.                      the Transmit() function. If HeaderSize is non-zero, then it
  987.                      must be equal to This->Mode->MediaHeaderSize and the DestAddr
  988.                      and Protocol parameters must not be NULL.
  989.   @param  BufferSize The size, in bytes, of the entire packet (media header and
  990.                      data) to be transmitted through the network interface.
  991.   @param  Buffer     A pointer to the packet (media header followed by data) to be
  992.                      transmitted. This parameter cannot be NULL. If HeaderSize is zero,
  993.                      then the media header in Buffer must already be filled in by the
  994.                      caller. If HeaderSize is non-zero, then the media header will be
  995.                      filled in by the Transmit() function.
  996.   @param  SrcAddr    The source HW MAC address. If HeaderSize is zero, then this parameter
  997.                      is ignored. If HeaderSize is non-zero and SrcAddr is NULL, then
  998.                      This->Mode->CurrentAddress is used for the source HW MAC address.
  999.   @param  DestAddr   The destination HW MAC address. If HeaderSize is zero, then this
  1000.                      parameter is ignored.
  1001.   @param  Protocol   The type of header to build. If HeaderSize is zero, then this
  1002.                      parameter is ignored. See RFC 1700, section "Ether Types", for
  1003.                      examples.
  1004.  
  1005.   @retval EFI_SUCCESS           The packet was placed on the transmit queue.
  1006.   @retval EFI_NOT_STARTED       The network interface has not been started.
  1007.   @retval EFI_NOT_READY         The network interface is too busy to accept this transmit request.
  1008.   @retval EFI_BUFFER_TOO_SMALL  The BufferSize parameter is too small.
  1009.   @retval EFI_INVALID_PARAMETER One or more of the parameters has an unsupported value.
  1010.   @retval EFI_DEVICE_ERROR      The command could not be sent to the network interface.
  1011.   @retval EFI_UNSUPPORTED       This function is not supported by the network interface.
  1012.  
  1013. **/
  1014. EFI_STATUS
  1015. EmuSnpTransmit (
  1016.   IN EMU_SNP_PROTOCOL                     *This,
  1017.   IN UINTN                                HeaderSize,
  1018.   IN UINTN                                BufferSize,
  1019.   IN VOID                                 *Buffer,
  1020.   IN EFI_MAC_ADDRESS                      *SrcAddr  OPTIONAL,
  1021.   IN EFI_MAC_ADDRESS                      *DestAddr OPTIONAL,
  1022.   IN UINT16                               *Protocol OPTIONAL
  1023.   )
  1024. {
  1025.   EMU_SNP_PRIVATE    *Private;
  1026.  
  1027.   Private = EMU_SNP_PRIVATE_DATA_FROM_THIS (This);
  1028.  
  1029.   if (Private->Mode->State < EfiSimpleNetworkStarted) {
  1030.     return EFI_NOT_STARTED;
  1031.   }
  1032.  
  1033.   if ( HeaderSize != 0 ) {
  1034.     if ((DestAddr == NULL) || (Protocol == NULL) || (HeaderSize != Private->Mode->MediaHeaderSize)) {
  1035.       return EFI_INVALID_PARAMETER;
  1036.     }
  1037.  
  1038.     if (SrcAddr == NULL) {
  1039.       SrcAddr = &Private->Mode->CurrentAddress;
  1040.     }
  1041.  
  1042.     struct ethhdr *header = (struct ethhdr*)Buffer;
  1043.     CopyMem (header->h_dest,   DestAddr, ETH_ALEN);
  1044.     CopyMem (header->h_source, SrcAddr,  ETH_ALEN);
  1045.  
  1046.     header->h_proto = htons(*Protocol);
  1047.   }
  1048.  
  1049.   VOID* buffer = malloc (BufferSize + 4);
  1050.   ZeroMem(buffer, BufferSize + 4);
  1051.   CopyMem(buffer + 4, Buffer, BufferSize);
  1052.  
  1053.   ssize_t writeSize = write (Private->TapFd, buffer, BufferSize + 4);
  1054.  
  1055.   if (writeSize < 0) {
  1056.     printf (
  1057.       "SNP: error writing to tap device: %s (%d).\n",
  1058.       strerror(errno), errno
  1059.       );
  1060.     return EFI_DEVICE_ERROR;
  1061.   }
  1062.   else if (writeSize < BufferSize + 4) {
  1063.     printf (
  1064.       "SNP: short write to tap device, trying to transmit whats left.\n",
  1065.       strerror(errno), errno
  1066.       );
  1067.  
  1068.     ssize_t writeSize2 = write (Private->TapFd, buffer + writeSize, BufferSize + 4 - writeSize);
  1069.  
  1070.     if (writeSize2 + writeSize < BufferSize + 4) {
  1071.       if (writeSize2 < 0) {
  1072.         printf (
  1073.           "SNP: error writing to tap device (while recovering from a short write): %s (%d).\n",
  1074.           strerror(errno), errno
  1075.         );
  1076.         // no error return here since we wrote some ...
  1077.       }
  1078.       if (writeSize2 + writeSize < BufferSize + 4) {
  1079.         printf (
  1080.           "SNP: short write on second try, giving up.\n",
  1081.           strerror(errno), errno
  1082.           );
  1083.       }
  1084.  
  1085.       free(buffer);
  1086.       return EFI_WARN_WRITE_FAILURE;
  1087.     }
  1088.   }
  1089.  
  1090.   free(buffer);
  1091.   return EFI_SUCCESS;
  1092.  
  1093.   //return TapRingBufferPush (&Private->TxBuffer, Buffer, BufferSize);
  1094. }
  1095.  
  1096. /**
  1097.   Receives a packet from a network interface.
  1098.  
  1099.   @param  This       The protocol instance pointer.
  1100.   @param  HeaderSize The size, in bytes, of the media header received on the network
  1101.                      interface. If this parameter is NULL, then the media header size
  1102.                      will not be returned.
  1103.   @param  BufferSize On entry, the size, in bytes, of Buffer. On exit, the size, in
  1104.                      bytes, of the packet that was received on the network interface.
  1105.   @param  Buffer     A pointer to the data buffer to receive both the media header and
  1106.                      the data.
  1107.   @param  SrcAddr    The source HW MAC address. If this parameter is NULL, the
  1108.                      HW MAC source address will not be extracted from the media
  1109.                      header.
  1110.   @param  DestAddr   The destination HW MAC address. If this parameter is NULL,
  1111.                      the HW MAC destination address will not be extracted from the
  1112.                      media header.
  1113.   @param  Protocol   The media header type. If this parameter is NULL, then the
  1114.                      protocol will not be extracted from the media header. See
  1115.                      RFC 1700 section "Ether Types" for examples.
  1116.  
  1117.   @retval  EFI_SUCCESS           The received data was stored in Buffer, and BufferSize has
  1118.                                  been updated to the number of bytes received.
  1119.   @retval  EFI_NOT_STARTED       The network interface has not been started.
  1120.   @retval  EFI_NOT_READY         The network interface is too busy to accept this transmit
  1121.                                  request.
  1122.   @retval  EFI_BUFFER_TOO_SMALL  The BufferSize parameter is too small.
  1123.   @retval  EFI_INVALID_PARAMETER One or more of the parameters has an unsupported value.
  1124.   @retval  EFI_DEVICE_ERROR      The command could not be sent to the network interface.
  1125.   @retval  EFI_UNSUPPORTED       This function is not supported by the network interface.
  1126.  
  1127. **/
  1128. EFI_STATUS
  1129. EmuSnpReceive (
  1130.   IN EMU_SNP_PROTOCOL                     *This,
  1131.   OUT UINTN                               *HeaderSize OPTIONAL,
  1132.   IN OUT UINTN                            *BufferSize,
  1133.   OUT VOID                                *Buffer,
  1134.   OUT EFI_MAC_ADDRESS                     *SrcAddr    OPTIONAL,
  1135.   OUT EFI_MAC_ADDRESS                     *DestAddr   OPTIONAL,
  1136.   OUT UINT16                              *Protocol   OPTIONAL
  1137.   )
  1138. {
  1139.   EMU_SNP_PRIVATE    *Private;
  1140.   EFI_STATUS status;
  1141.  
  1142.   Private = EMU_SNP_PRIVATE_DATA_FROM_THIS (This);
  1143.  
  1144.   if (!BufferSize) {
  1145.     return EFI_INVALID_PARAMETER;
  1146.   }
  1147.  
  1148.   static UINTN packetSize = 0;
  1149.   static UINT8 *packet    = 0;
  1150.  
  1151.   if (!packetSize) {
  1152.     packetSize = 9000;
  1153.     packet     = malloc (9000);
  1154.  
  1155.     ssize_t readSize = read(Private->TapFd, packet, packetSize);
  1156.  
  1157.     if (readSize < 0) {
  1158.       free(packet);
  1159.       packet     = 0;
  1160.       packetSize = 0;
  1161.  
  1162.       if (errno == EAGAIN || errno == EINTR) {
  1163.         return EFI_NOT_READY;
  1164.       }
  1165.  
  1166.       printf (
  1167.         "SNP: error reading from tap device: %s (%d).\n",
  1168.         strerror(errno), errno
  1169.         );
  1170.       return EFI_DEVICE_ERROR;
  1171.     }
  1172.  
  1173.     packetSize = readSize;
  1174.   }
  1175.  
  1176.   if (packetSize) {
  1177.     if (packetSize - 4 <= *BufferSize) {
  1178.       *BufferSize = packetSize - 4;
  1179.  
  1180.       if (!Buffer) {
  1181.         return EFI_INVALID_PARAMETER;
  1182.       }
  1183.       else {
  1184.         CopyMem(Buffer, packet + 4, packetSize - 4);
  1185.         free(packet);
  1186.         packetSize = 0;
  1187.  
  1188.         struct ethhdr *header = (struct ethhdr*)Buffer;
  1189.         printf("received packet from %02x:%02x:%02x:%02x:%02x:%02x\n",
  1190.           header->h_source[0], header->h_source[1], header->h_source[2],
  1191.           header->h_source[3], header->h_source[4], header->h_source[5]
  1192.           );
  1193.  
  1194.         UINTN headerSize;
  1195.         // ethernet frames have two possible sizes, depending on
  1196.         // if there is a VLAN tag - we check for the VLAN tag here
  1197.         if (header->h_proto == htons(0x8100)) {
  1198.           headerSize = 18;
  1199.         }
  1200.         else {
  1201.           headerSize = 14;
  1202.         }
  1203.  
  1204.         if (HeaderSize) {
  1205.             *HeaderSize = headerSize;
  1206.         }
  1207.  
  1208.         if (SrcAddr) {
  1209.           CopyMem(SrcAddr, header->h_source, ETH_ALEN);
  1210.         }
  1211.  
  1212.         if (DestAddr) {
  1213.           CopyMem(SrcAddr, header->h_source, ETH_ALEN);
  1214.         }
  1215.  
  1216.         if (Protocol) {
  1217.             if (headerSize == 14) {
  1218.                 *Protocol = ntohs(header->h_proto);
  1219.             }
  1220.             else {
  1221.                 *Protocol = ntohs(*(&header->h_proto + 2));
  1222.             }
  1223.         }
  1224.  
  1225.         return EFI_SUCCESS;
  1226.       }
  1227.     }
  1228.     else {
  1229.       *BufferSize = packetSize - 4;
  1230.       return EFI_BUFFER_TOO_SMALL;
  1231.     }
  1232.   }
  1233.   else {
  1234.     free(packet);
  1235.     packet = 0;
  1236.     return EFI_NOT_READY;
  1237.   }
  1238.  
  1239.  
  1240. //  UINTN packetSize = 0;
  1241. //  status = TapRingBufferPop(&Private->RxBuffer, NULL, &packetSize);
  1242. //
  1243. //  if (status == EFI_BUFFER_TOO_SMALL) {
  1244. //    if (packetSize > *BufferSize) {
  1245. //      return status;
  1246. //    }
  1247. //  }
  1248. //  else {
  1249. //    return status;
  1250. //  }
  1251. //
  1252. //  *BufferSize = packetSize;
  1253. //  status = TapRingBufferPop(&Private->RxBuffer, Buffer, BufferSize);
  1254. //
  1255. }
  1256.  
  1257.  
  1258. EMU_SNP_PROTOCOL gEmuSnpProtocol = {
  1259.   GasketSnpCreateMapping,
  1260.   GasketSnpStart,
  1261.   GasketSnpStop,
  1262.   GasketSnpInitialize,
  1263.   GasketSnpReset,
  1264.   GasketSnpShutdown,
  1265.   GasketSnpReceiveFilters,
  1266.   GasketSnpStationAddress,
  1267.   GasketSnpStatistics,
  1268.   GasketSnpMCastIpToMac,
  1269.   GasketSnpNvData,
  1270.   GasketSnpGetStatus,
  1271.   GasketSnpTransmit,
  1272.   GasketSnpReceive
  1273. };
  1274.  
  1275. EFI_STATUS
  1276. EmuSnpThunkOpen (
  1277.   IN  EMU_IO_THUNK_PROTOCOL   *This
  1278.   )
  1279. {
  1280.   EMU_SNP_PRIVATE  *Private;
  1281.  
  1282.   if (This->Private != NULL) {
  1283.     return EFI_ALREADY_STARTED;
  1284.   }
  1285.  
  1286.   if (!CompareGuid (This->Protocol, &gEmuSnpProtocolGuid)) {
  1287.     return EFI_UNSUPPORTED;
  1288.   }
  1289.  
  1290.   Private = malloc (sizeof (EMU_SNP_PRIVATE));
  1291.   if (Private == NULL) {
  1292.     return EFI_OUT_OF_RESOURCES;
  1293.   }
  1294.  
  1295.  
  1296.   Private->Signature = EMU_SNP_PRIVATE_SIGNATURE;
  1297.   Private->Thunk     = This;
  1298.   CopyMem (&Private->EmuSnp, &gEmuSnpProtocol, sizeof (gEmuSnpProtocol));
  1299.  
  1300.   This->Interface = &Private->EmuSnp;
  1301.   This->Private   = Private;
  1302.   return EFI_SUCCESS;
  1303. }
  1304.  
  1305.  
  1306. EFI_STATUS
  1307. EmuSnpThunkClose (
  1308.   IN  EMU_IO_THUNK_PROTOCOL   *This
  1309.   )
  1310. {
  1311.   EMU_SNP_PRIVATE  *Private;
  1312.  
  1313.   if (!CompareGuid (This->Protocol, &gEmuSnpProtocolGuid)) {
  1314.     return EFI_UNSUPPORTED;
  1315.   }
  1316.  
  1317.   Private = This->Private;
  1318.   free (Private);
  1319.  
  1320.   return EFI_SUCCESS;
  1321. }
  1322.  
  1323.  
  1324.  
  1325. EMU_IO_THUNK_PROTOCOL gSnpThunkIo = {
  1326.   &gEmuSnpProtocolGuid,
  1327.   NULL,
  1328.   NULL,
  1329.   0,
  1330.   GasketSnpThunkOpen,
  1331.   GasketSnpThunkClose,
  1332.   NULL
  1333. };
  1334.  
  1335. #endif
  1336.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement