1 /** @file
2 
3 Copyright (c) 2005 - 2014, Intel Corporation. All rights reserved.<BR>
4 This program and the accompanying materials
5 are licensed and made available under the terms and conditions of the BSD License
6 which accompanies this distribution.  The full text of the license may be found at
7 http://opensource.org/licenses/bsd-license.php
8 
9 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
10 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
11 
12 **/
13 
14 #include "Ip4Impl.h"
15 
16 EFI_IPSEC2_PROTOCOL    *mIpSec = NULL;
17 
18 /**
19   Gets the current operational settings for this instance of the EFI IPv4 Protocol driver.
20 
21   The GetModeData() function returns the current operational mode data for this
22   driver instance. The data fields in EFI_IP4_MODE_DATA are read only. This
23   function is used optionally to retrieve the operational mode data of underlying
24   networks or drivers.
25 
26   @param[in]   This          Pointer to the EFI_IP4_PROTOCOL instance.
27   @param[out]  Ip4ModeData   Pointer to the EFI IPv4 Protocol mode data structure.
28   @param[out]  MnpConfigData Pointer to the managed network configuration data structure.
29   @param[out]  SnpModeData   Pointer to the simple network mode data structure.
30 
31   @retval EFI_SUCCESS           The operation completed successfully.
32   @retval EFI_INVALID_PARAMETER This is NULL.
33   @retval EFI_OUT_OF_RESOURCES  The required mode data could not be allocated.
34 
35 **/
36 EFI_STATUS
37 EFIAPI
38 EfiIp4GetModeData (
39   IN  CONST EFI_IP4_PROTOCOL                *This,
40   OUT       EFI_IP4_MODE_DATA               *Ip4ModeData     OPTIONAL,
41   OUT       EFI_MANAGED_NETWORK_CONFIG_DATA *MnpConfigData   OPTIONAL,
42   OUT       EFI_SIMPLE_NETWORK_MODE         *SnpModeData     OPTIONAL
43   );
44 
45 /**
46   Assigns an IPv4 address and subnet mask to this EFI IPv4 Protocol driver instance.
47 
48   The Configure() function is used to set, change, or reset the operational
49   parameters and filter settings for this EFI IPv4 Protocol instance. Until these
50   parameters have been set, no network traffic can be sent or received by this
51   instance. Once the parameters have been reset (by calling this function with
52   IpConfigData set to NULL), no more traffic can be sent or received until these
53   parameters have been set again. Each EFI IPv4 Protocol instance can be started
54   and stopped independently of each other by enabling or disabling their receive
55   filter settings with the Configure() function.
56 
57   When IpConfigData.UseDefaultAddress is set to FALSE, the new station address will
58   be appended as an alias address into the addresses list in the EFI IPv4 Protocol
59   driver. While set to TRUE, Configure() will trigger the EFI_IP4_CONFIG_PROTOCOL
60   to retrieve the default IPv4 address if it is not available yet. Clients could
61   frequently call GetModeData() to check the status to ensure that the default IPv4
62   address is ready.
63 
64   If operational parameters are reset or changed, any pending transmit and receive
65   requests will be cancelled. Their completion token status will be set to EFI_ABORTED
66   and their events will be signaled.
67 
68   @param[in]  This              Pointer to the EFI_IP4_PROTOCOL instance.
69   @param[in]  IpConfigData      Pointer to the EFI IPv4 Protocol configuration data structure.
70 
71   @retval EFI_SUCCESS           The driver instance was successfully opened.
72   @retval EFI_NO_MAPPING        When using the default address, configuration (DHCP, BOOTP,
73                                 RARP, etc.) is not finished yet.
74   @retval EFI_INVALID_PARAMETER One or more of the following conditions is TRUE:
75   @retval EFI_UNSUPPORTED       One or more of the following conditions is TRUE:
76                                 A configuration protocol (DHCP, BOOTP, RARP, etc.) could
77                                 not be located when clients choose to use the default IPv4
78                                 address. This EFI IPv4 Protocol implementation does not
79                                 support this requested filter or timeout setting.
80   @retval EFI_OUT_OF_RESOURCES  The EFI IPv4 Protocol driver instance data could not be allocated.
81   @retval EFI_ALREADY_STARTED   The interface is already open and must be stopped before the
82                                 IPv4 address or subnet mask can be changed. The interface must
83                                 also be stopped when switching to/from raw packet mode.
84   @retval EFI_DEVICE_ERROR      An unexpected system or network error occurred. The EFI IPv4
85                                 Protocol driver instance is not opened.
86 
87 **/
88 EFI_STATUS
89 EFIAPI
90 EfiIp4Configure (
91   IN EFI_IP4_PROTOCOL       *This,
92   IN EFI_IP4_CONFIG_DATA    *IpConfigData       OPTIONAL
93   );
94 
95 /**
96   Joins and leaves multicast groups.
97 
98   The Groups() function is used to join and leave multicast group sessions. Joining
99   a group will enable reception of matching multicast packets. Leaving a group will
100   disable the multicast packet reception.
101 
102   If JoinFlag is FALSE and GroupAddress is NULL, all joined groups will be left.
103 
104   @param[in]  This                  Pointer to the EFI_IP4_PROTOCOL instance.
105   @param[in]  JoinFlag              Set to TRUE to join the multicast group session and FALSE to leave.
106   @param[in]  GroupAddress          Pointer to the IPv4 multicast address.
107 
108   @retval EFI_SUCCESS           The operation completed successfully.
109   @retval EFI_INVALID_PARAMETER One or more of the following is TRUE:
110                                 - This is NULL.
111                                 - JoinFlag is TRUE and GroupAddress is NULL.
112                                 - GroupAddress is not NULL and *GroupAddress is
113                                 not a multicast IPv4 address.
114   @retval EFI_NOT_STARTED       This instance has not been started.
115   @retval EFI_NO_MAPPING        When using the default address, configuration (DHCP, BOOTP,
116                                 RARP, etc.) is not finished yet.
117   @retval EFI_OUT_OF_RESOURCES  System resources could not be allocated.
118   @retval EFI_UNSUPPORTED       This EFI IPv4 Protocol implementation does not support multicast groups.
119   @retval EFI_ALREADY_STARTED   The group address is already in the group table (when
120                                 JoinFlag is TRUE).
121   @retval EFI_NOT_FOUND         The group address is not in the group table (when JoinFlag is FALSE).
122   @retval EFI_DEVICE_ERROR      An unexpected system or network error occurred.
123 
124 **/
125 EFI_STATUS
126 EFIAPI
127 EfiIp4Groups (
128   IN EFI_IP4_PROTOCOL       *This,
129   IN BOOLEAN                JoinFlag,
130   IN EFI_IPv4_ADDRESS       *GroupAddress     OPTIONAL
131   );
132 
133 /**
134   Adds and deletes routing table entries.
135 
136   The Routes() function adds a route to or deletes a route from the routing table.
137 
138   Routes are determined by comparing the SubnetAddress with the destination IPv4
139   address arithmetically AND-ed with the SubnetMask. The gateway address must be
140   on the same subnet as the configured station address.
141 
142   The default route is added with SubnetAddress and SubnetMask both set to 0.0.0.0.
143   The default route matches all destination IPv4 addresses that do not match any
144   other routes.
145 
146   A GatewayAddress that is zero is a nonroute. Packets are sent to the destination
147   IP address if it can be found in the ARP cache or on the local subnet. One automatic
148   nonroute entry will be inserted into the routing table for outgoing packets that
149   are addressed to a local subnet (gateway address of 0.0.0.0).
150 
151   Each EFI IPv4 Protocol instance has its own independent routing table. Those EFI
152   IPv4 Protocol instances that use the default IPv4 address will also have copies
153   of the routing table that was provided by the EFI_IP4_CONFIG_PROTOCOL, and these
154   copies will be updated whenever the EIF IPv4 Protocol driver reconfigures its
155   instances. As a result, client modification to the routing table will be lost.
156 
157   @param[in]  This                   Pointer to the EFI_IP4_PROTOCOL instance.
158   @param[in]  DeleteRoute            Set to TRUE to delete this route from the routing table. Set to
159                                      FALSE to add this route to the routing table. SubnetAddress
160                                      and SubnetMask are used as the key to each route entry.
161   @param[in]  SubnetAddress          The address of the subnet that needs to be routed.
162   @param[in]  SubnetMask             The subnet mask of SubnetAddress.
163   @param[in]  GatewayAddress         The unicast gateway IPv4 address for this route.
164 
165   @retval EFI_SUCCESS            The operation completed successfully.
166   @retval EFI_NOT_STARTED        The driver instance has not been started.
167   @retval EFI_NO_MAPPING         When using the default address, configuration (DHCP, BOOTP,
168                                  RARP, etc.) is not finished yet.
169   @retval EFI_INVALID_PARAMETER  One or more of the following conditions is TRUE:
170                                  - This is NULL.
171                                  - SubnetAddress is NULL.
172                                  - SubnetMask is NULL.
173                                  - GatewayAddress is NULL.
174                                  - *SubnetAddress is not a valid subnet address.
175                                  - *SubnetMask is not a valid subnet mask.
176                                  - *GatewayAddress is not a valid unicast IPv4 address.
177   @retval EFI_OUT_OF_RESOURCES   Could not add the entry to the routing table.
178   @retval EFI_NOT_FOUND          This route is not in the routing table (when DeleteRoute is TRUE).
179   @retval EFI_ACCESS_DENIED      The route is already defined in the routing table (when
180                                   DeleteRoute is FALSE).
181 
182 **/
183 EFI_STATUS
184 EFIAPI
185 EfiIp4Routes (
186   IN EFI_IP4_PROTOCOL       *This,
187   IN BOOLEAN                DeleteRoute,
188   IN EFI_IPv4_ADDRESS       *SubnetAddress,
189   IN EFI_IPv4_ADDRESS       *SubnetMask,
190   IN EFI_IPv4_ADDRESS       *GatewayAddress
191   );
192 
193 /**
194   Places outgoing data packets into the transmit queue.
195 
196   The Transmit() function places a sending request in the transmit queue of this
197   EFI IPv4 Protocol instance. Whenever the packet in the token is sent out or some
198   errors occur, the event in the token will be signaled and the status is updated.
199 
200   @param[in]  This  Pointer to the EFI_IP4_PROTOCOL instance.
201   @param[in]  Token Pointer to the transmit token.
202 
203   @retval  EFI_SUCCESS           The data has been queued for transmission.
204   @retval  EFI_NOT_STARTED       This instance has not been started.
205   @retval  EFI_NO_MAPPING        When using the default address, configuration (DHCP, BOOTP,
206                                  RARP, etc.) is not finished yet.
207   @retval  EFI_INVALID_PARAMETER One or more pameters are invalid.
208   @retval  EFI_ACCESS_DENIED     The transmit completion token with the same Token.Event
209                                  was already in the transmit queue.
210   @retval  EFI_NOT_READY         The completion token could not be queued because the transmit
211                                  queue is full.
212   @retval  EFI_NOT_FOUND         Not route is found to destination address.
213   @retval  EFI_OUT_OF_RESOURCES  Could not queue the transmit data.
214   @retval  EFI_BUFFER_TOO_SMALL  Token.Packet.TxData.TotalDataLength is too
215                                  short to transmit.
216   @retval  EFI_BAD_BUFFER_SIZE   The length of the IPv4 header + option length + total data length is
217                                  greater than MTU (or greater than the maximum packet size if
218                                  Token.Packet.TxData.OverrideData.
219                                  DoNotFragment is TRUE.)
220 
221 **/
222 EFI_STATUS
223 EFIAPI
224 EfiIp4Transmit (
225   IN EFI_IP4_PROTOCOL         *This,
226   IN EFI_IP4_COMPLETION_TOKEN *Token
227   );
228 
229 /**
230   Places a receiving request into the receiving queue.
231 
232   The Receive() function places a completion token into the receive packet queue.
233   This function is always asynchronous.
234 
235   The Token.Event field in the completion token must be filled in by the caller
236   and cannot be NULL. When the receive operation completes, the EFI IPv4 Protocol
237   driver updates the Token.Status and Token.Packet.RxData fields and the Token.Event
238   is signaled.
239 
240   @param[in]  This  Pointer to the EFI_IP4_PROTOCOL instance.
241   @param[in]  Token Pointer to a token that is associated with the receive data descriptor.
242 
243   @retval EFI_SUCCESS           The receive completion token was cached.
244   @retval EFI_NOT_STARTED       This EFI IPv4 Protocol instance has not been started.
245   @retval EFI_NO_MAPPING        When using the default address, configuration (DHCP, BOOTP, RARP, etc.)
246                                 is not finished yet.
247   @retval EFI_INVALID_PARAMETER One or more of the following conditions is TRUE:
248                                 - This is NULL.
249                                 - Token is NULL.
250                                 - Token.Event is NULL.
251   @retval EFI_OUT_OF_RESOURCES  The receive completion token could not be queued due to a lack of system
252                                 resources (usually memory).
253   @retval EFI_DEVICE_ERROR      An unexpected system or network error occurred.
254                                 The EFI IPv4 Protocol instance has been reset to startup defaults.
255                                 EFI_ACCESS_DENIED The receive completion token with the same Token.Event was already
256                                 in the receive queue.
257   @retval EFI_NOT_READY         The receive request could not be queued because the receive queue is full.
258   @retval EFI_ICMP_ERROR        An ICMP error packet was received.
259 
260 **/
261 EFI_STATUS
262 EFIAPI
263 EfiIp4Receive (
264   IN EFI_IP4_PROTOCOL         *This,
265   IN EFI_IP4_COMPLETION_TOKEN *Token
266   );
267 
268 /**
269   Abort an asynchronous transmit or receive request.
270 
271   The Cancel() function is used to abort a pending transmit or receive request.
272   If the token is in the transmit or receive request queues, after calling this
273   function, Token->Status will be set to EFI_ABORTED and then Token->Event will
274   be signaled. If the token is not in one of the queues, which usually means the
275   asynchronous operation has completed, this function will not signal the token
276   and EFI_NOT_FOUND is returned.
277 
278   @param[in]  This  Pointer to the EFI_IP4_PROTOCOL instance.
279   @param[in]  Token Pointer to a token that has been issued by
280                     EFI_IP4_PROTOCOL.Transmit() or
281                     EFI_IP4_PROTOCOL.Receive(). If NULL, all pending
282                     tokens are aborted. Type EFI_IP4_COMPLETION_TOKEN is
283                     defined in EFI_IP4_PROTOCOL.Transmit().
284 
285   @retval EFI_SUCCESS           The asynchronous I/O request was aborted and
286                                 Token.->Event was signaled. When Token is NULL, all
287                                 pending requests were aborted and their events were signaled.
288   @retval EFI_INVALID_PARAMETER This is NULL.
289   @retval EFI_NOT_STARTED       This instance has not been started.
290   @retval EFI_NO_MAPPING        When using the default address, configuration (DHCP, BOOTP,
291                                 RARP, etc.) is not finished yet.
292   @retval EFI_NOT_FOUND         When Token is not NULL, the asynchronous I/O request was
293                                 not found in the transmit or receive queue. It has either completed
294                                 or was not issued by Transmit() and Receive().
295 
296 **/
297 EFI_STATUS
298 EFIAPI
299 EfiIp4Cancel (
300   IN EFI_IP4_PROTOCOL         *This,
301   IN EFI_IP4_COMPLETION_TOKEN *Token    OPTIONAL
302   );
303 
304 /**
305   Polls for incoming data packets and processes outgoing data packets.
306 
307   The Poll() function polls for incoming data packets and processes outgoing data
308   packets. Network drivers and applications can call the EFI_IP4_PROTOCOL.Poll()
309   function to increase the rate that data packets are moved between the communications
310   device and the transmit and receive queues.
311 
312   In some systems the periodic timer event may not poll the underlying communications
313   device fast enough to transmit and/or receive all data packets without missing
314   incoming packets or dropping outgoing packets. Drivers and applications that are
315   experiencing packet loss should try calling the EFI_IP4_PROTOCOL.Poll() function
316   more often.
317 
318   @param[in]  This               Pointer to the EFI_IP4_PROTOCOL instance.
319 
320   @retval  EFI_SUCCESS           Incoming or outgoing data was processed.
321   @retval  EFI_NOT_STARTED       This EFI IPv4 Protocol instance has not been started.
322   @retval  EFI_NO_MAPPING        When using the default address, configuration (DHCP, BOOTP,
323                                  RARP, etc.) is not finished yet.
324   @retval  EFI_INVALID_PARAMETER This is NULL.
325   @retval  EFI_DEVICE_ERROR      An unexpected system or network error occurred.
326   @retval  EFI_NOT_READY         No incoming or outgoing data is processed.
327   @retval  EFI_TIMEOUT           Data was dropped out of the transmit and/or receive queue.
328                                  Consider increasing the polling rate.
329 
330 **/
331 EFI_STATUS
332 EFIAPI
333 EfiIp4Poll (
334   IN EFI_IP4_PROTOCOL       *This
335   );
336 
337 EFI_IP4_PROTOCOL
338 mEfiIp4ProtocolTemplete = {
339   EfiIp4GetModeData,
340   EfiIp4Configure,
341   EfiIp4Groups,
342   EfiIp4Routes,
343   EfiIp4Transmit,
344   EfiIp4Receive,
345   EfiIp4Cancel,
346   EfiIp4Poll
347 };
348 
349 /**
350   Gets the current operational settings for this instance of the EFI IPv4 Protocol driver.
351 
352   The GetModeData() function returns the current operational mode data for this
353   driver instance. The data fields in EFI_IP4_MODE_DATA are read only. This
354   function is used optionally to retrieve the operational mode data of underlying
355   networks or drivers.
356 
357   @param[in]   This          Pointer to the EFI_IP4_PROTOCOL instance.
358   @param[out]  Ip4ModeData   Pointer to the EFI IPv4 Protocol mode data structure.
359   @param[out]  MnpConfigData Pointer to the managed network configuration data structure.
360   @param[out]  SnpModeData   Pointer to the simple network mode data structure.
361 
362   @retval EFI_SUCCESS           The operation completed successfully.
363   @retval EFI_INVALID_PARAMETER This is NULL.
364   @retval EFI_OUT_OF_RESOURCES  The required mode data could not be allocated.
365 
366 **/
367 EFI_STATUS
368 EFIAPI
EfiIp4GetModeData(IN CONST EFI_IP4_PROTOCOL * This,OUT EFI_IP4_MODE_DATA * Ip4ModeData OPTIONAL,OUT EFI_MANAGED_NETWORK_CONFIG_DATA * MnpConfigData OPTIONAL,OUT EFI_SIMPLE_NETWORK_MODE * SnpModeData OPTIONAL)369 EfiIp4GetModeData (
370   IN  CONST EFI_IP4_PROTOCOL                *This,
371   OUT       EFI_IP4_MODE_DATA               *Ip4ModeData     OPTIONAL,
372   OUT       EFI_MANAGED_NETWORK_CONFIG_DATA *MnpConfigData   OPTIONAL,
373   OUT       EFI_SIMPLE_NETWORK_MODE         *SnpModeData     OPTIONAL
374   )
375 {
376   IP4_PROTOCOL              *IpInstance;
377   IP4_SERVICE               *IpSb;
378   EFI_IP4_CONFIG_DATA       *Config;
379   EFI_STATUS                Status;
380   EFI_TPL                   OldTpl;
381   IP4_ADDR                  Ip;
382 
383   if (This == NULL) {
384     return EFI_INVALID_PARAMETER;
385   }
386 
387   OldTpl     = gBS->RaiseTPL (TPL_CALLBACK);
388   IpInstance = IP4_INSTANCE_FROM_PROTOCOL (This);
389   IpSb       = IpInstance->Service;
390 
391   if (Ip4ModeData != NULL) {
392     //
393     // IsStarted is "whether the EfiIp4Configure has been called".
394     // IsConfigured is "whether the station address has been configured"
395     //
396     Ip4ModeData->IsStarted     = (BOOLEAN)(IpInstance->State == IP4_STATE_CONFIGED);
397     CopyMem (&Ip4ModeData->ConfigData, &IpInstance->ConfigData, sizeof (Ip4ModeData->ConfigData));
398     Ip4ModeData->IsConfigured  = FALSE;
399 
400     Ip4ModeData->GroupCount    = IpInstance->GroupCount;
401     Ip4ModeData->GroupTable    = (EFI_IPv4_ADDRESS *) IpInstance->Groups;
402 
403     Ip4ModeData->IcmpTypeCount = 23;
404     Ip4ModeData->IcmpTypeList  = mIp4SupportedIcmp;
405 
406     Ip4ModeData->RouteTable    = NULL;
407     Ip4ModeData->RouteCount    = 0;
408 
409     Ip4ModeData->MaxPacketSize = IpSb->MaxPacketSize;
410 
411     //
412     // return the current station address for this IP child. So,
413     // the user can get the default address through this. Some
414     // application wants to know it station address even it is
415     // using the default one, such as a ftp server.
416     //
417     if (Ip4ModeData->IsStarted) {
418       Config  = &Ip4ModeData->ConfigData;
419 
420       Ip = HTONL (IpInstance->Interface->Ip);
421       CopyMem (&Config->StationAddress, &Ip, sizeof (EFI_IPv4_ADDRESS));
422 
423       Ip = HTONL (IpInstance->Interface->SubnetMask);
424       CopyMem (&Config->SubnetMask, &Ip, sizeof (EFI_IPv4_ADDRESS));
425 
426       Ip4ModeData->IsConfigured = IpInstance->Interface->Configured;
427 
428       //
429       // Build a EFI route table for user from the internal route table.
430       //
431       Status = Ip4BuildEfiRouteTable (IpInstance);
432 
433       if (EFI_ERROR (Status)) {
434         gBS->RestoreTPL (OldTpl);
435         return Status;
436       }
437 
438       Ip4ModeData->RouteTable = IpInstance->EfiRouteTable;
439       Ip4ModeData->RouteCount = IpInstance->EfiRouteCount;
440     }
441   }
442 
443   //
444   // Get fresh mode data from MNP, since underlying media status may change
445   //
446   Status = IpSb->Mnp->GetModeData (IpSb->Mnp, MnpConfigData, SnpModeData);
447 
448   gBS->RestoreTPL (OldTpl);
449   return Status;
450 }
451 
452 
453 /**
454   Config the MNP parameter used by IP. The IP driver use one MNP
455   child to transmit/receive frames. By default, it configures MNP
456   to receive unicast/multicast/broadcast. And it will enable/disable
457   the promiscous receive according to whether there is IP child
458   enable that or not. If Force is FALSE, it will iterate through
459   all the IP children to check whether the promiscuous receive
460   setting has been changed. If it hasn't been changed, it won't
461   reconfigure the MNP. If Force is TRUE, the MNP is configured no
462   matter whether that is changed or not.
463 
464   @param[in]  IpSb               The IP4 service instance that is to be changed.
465   @param[in]  Force              Force the configuration or not.
466 
467   @retval EFI_SUCCESS            The MNP is successfully configured/reconfigured.
468   @retval Others                 Configuration failed.
469 
470 **/
471 EFI_STATUS
Ip4ServiceConfigMnp(IN IP4_SERVICE * IpSb,IN BOOLEAN Force)472 Ip4ServiceConfigMnp (
473   IN IP4_SERVICE            *IpSb,
474   IN BOOLEAN                Force
475   )
476 {
477   LIST_ENTRY                *Entry;
478   LIST_ENTRY                *ProtoEntry;
479   IP4_INTERFACE             *IpIf;
480   IP4_PROTOCOL              *IpInstance;
481   BOOLEAN                   Reconfig;
482   BOOLEAN                   PromiscReceive;
483   EFI_STATUS                Status;
484 
485   Reconfig       = FALSE;
486   PromiscReceive = FALSE;
487 
488   if (!Force) {
489     //
490     // Iterate through the IP children to check whether promiscuous
491     // receive setting has been changed. Update the interface's receive
492     // filter also.
493     //
494     NET_LIST_FOR_EACH (Entry, &IpSb->Interfaces) {
495 
496       IpIf              = NET_LIST_USER_STRUCT (Entry, IP4_INTERFACE, Link);
497       IpIf->PromiscRecv = FALSE;
498 
499       NET_LIST_FOR_EACH (ProtoEntry, &IpIf->IpInstances) {
500         IpInstance = NET_LIST_USER_STRUCT (ProtoEntry, IP4_PROTOCOL, AddrLink);
501 
502         if (IpInstance->ConfigData.AcceptPromiscuous) {
503           IpIf->PromiscRecv = TRUE;
504           PromiscReceive    = TRUE;
505         }
506       }
507     }
508 
509     //
510     // If promiscuous receive isn't changed, it isn't necessary to reconfigure.
511     //
512     if (PromiscReceive == IpSb->MnpConfigData.EnablePromiscuousReceive) {
513       return EFI_SUCCESS;
514     }
515 
516     Reconfig  = TRUE;
517     IpSb->MnpConfigData.EnablePromiscuousReceive = PromiscReceive;
518   }
519 
520   Status = IpSb->Mnp->Configure (IpSb->Mnp, &IpSb->MnpConfigData);
521 
522   //
523   // recover the original configuration if failed to set the configure.
524   //
525   if (EFI_ERROR (Status) && Reconfig) {
526     IpSb->MnpConfigData.EnablePromiscuousReceive = (BOOLEAN) !PromiscReceive;
527   }
528 
529   return Status;
530 }
531 
532 
533 /**
534   The event handle for IP4 auto configuration. If IP is asked
535   to reconfigure the default address. The original default
536   interface and route table are removed as the default. If there
537   is active IP children using the default address, the interface
538   will remain valid until all the children have freed their
539   references. If IP is signalled when auto configuration is done,
540   it will configure the default interface and default route table
541   with the configuration information retrieved by IP4_CONFIGURE.
542 
543   @param[in]  Context                The IP4 service binding instance.
544 
545 **/
546 VOID
547 EFIAPI
Ip4AutoConfigCallBackDpc(IN VOID * Context)548 Ip4AutoConfigCallBackDpc (
549   IN VOID                   *Context
550   )
551 {
552   EFI_IP4_CONFIG_PROTOCOL   *Ip4Config;
553   EFI_IP4_IPCONFIG_DATA     *Data;
554   EFI_IP4_ROUTE_TABLE       *RouteEntry;
555   IP4_SERVICE               *IpSb;
556   IP4_ROUTE_TABLE           *RouteTable;
557   IP4_INTERFACE             *IpIf;
558   EFI_STATUS                Status;
559   UINTN                     Len;
560   UINT32                    Index;
561   IP4_ADDR                  StationAddress;
562   IP4_ADDR                  SubnetMask;
563   IP4_ADDR                  SubnetAddress;
564   IP4_ADDR                  GatewayAddress;
565   IP4_PROTOCOL              *Ip4Instance;
566   EFI_ARP_PROTOCOL          *Arp;
567   LIST_ENTRY                *Entry;
568 
569   IpSb      = (IP4_SERVICE *) Context;
570   NET_CHECK_SIGNATURE (IpSb, IP4_SERVICE_SIGNATURE);
571 
572   Ip4Config = IpSb->Ip4Config;
573 
574   //
575   // IP is asked to do the reconfiguration. If the default interface
576   // has been configured, release the default interface and route
577   // table, then create a new one. If there are some IP children
578   // using it, the interface won't be physically freed until all the
579   // children have released their reference to it. Also remember to
580   // restart the receive on the default address. IP4 driver only receive
581   // frames on the default address, and when the default interface is
582   // freed, Ip4AcceptFrame won't be informed.
583   //
584   if (IpSb->ActiveEvent == IpSb->ReconfigEvent) {
585 
586     if (IpSb->DefaultInterface->Configured) {
587       IpIf = Ip4CreateInterface (IpSb->Mnp, IpSb->Controller, IpSb->Image);
588 
589       if (IpIf == NULL) {
590         return;
591       }
592 
593       RouteTable = Ip4CreateRouteTable ();
594 
595       if (RouteTable == NULL) {
596         Ip4FreeInterface (IpIf, NULL);
597         return;
598       }
599 
600       Ip4CancelReceive (IpSb->DefaultInterface);
601       Ip4FreeInterface (IpSb->DefaultInterface, NULL);
602       Ip4FreeRouteTable (IpSb->DefaultRouteTable);
603 
604       IpSb->DefaultInterface  = IpIf;
605       InsertHeadList (&IpSb->Interfaces, &IpIf->Link);
606 
607       IpSb->DefaultRouteTable = RouteTable;
608       Ip4ReceiveFrame (IpIf, NULL, Ip4AccpetFrame, IpSb);
609     }
610 
611     Ip4Config->Stop (Ip4Config);
612     Ip4Config->Start (Ip4Config, IpSb->DoneEvent, IpSb->ReconfigEvent);
613     return ;
614   }
615 
616   //
617   // Get the configure data in two steps: get the length then the data.
618   //
619   Len = 0;
620 
621   if (Ip4Config->GetData (Ip4Config, &Len, NULL) != EFI_BUFFER_TOO_SMALL) {
622     return ;
623   }
624 
625   Data = AllocatePool (Len);
626 
627   if (Data == NULL) {
628     return ;
629   }
630 
631   Status = Ip4Config->GetData (Ip4Config, &Len, Data);
632 
633   if (EFI_ERROR (Status)) {
634     goto ON_EXIT;
635   }
636 
637   IpIf = IpSb->DefaultInterface;
638 
639   //
640   // If the default address has been configured don't change it.
641   // This is unlikely to happen if EFI_IP4_CONFIG protocol has
642   // informed us to reconfigure each time it wants to change the
643   // configuration parameters.
644   //
645   if (IpIf->Configured) {
646     goto ON_EXIT;
647   }
648 
649   //
650   // Set the default interface's address, then add a directed
651   // route for it, that is, the route whose nexthop is zero.
652   //
653   StationAddress = EFI_NTOHL (Data->StationAddress);
654   SubnetMask = EFI_NTOHL (Data->SubnetMask);
655   Status = Ip4SetAddress (IpIf, StationAddress, SubnetMask);
656   if (EFI_ERROR (Status)) {
657     goto ON_EXIT;
658   }
659 
660   if (IpIf->Arp != NULL) {
661     //
662     // A non-NULL IpIf->Arp here means a new ARP child is created when setting default address,
663     // but some IP children may have referenced the default interface before it is configured,
664     // these IP instances also consume this ARP protocol so they need to open it BY_CHILD_CONTROLLER.
665     //
666     Arp = NULL;
667     NET_LIST_FOR_EACH (Entry, &IpIf->IpInstances) {
668       Ip4Instance = NET_LIST_USER_STRUCT_S (Entry, IP4_PROTOCOL, AddrLink, IP4_PROTOCOL_SIGNATURE);
669       Status = gBS->OpenProtocol (
670                       IpIf->ArpHandle,
671                       &gEfiArpProtocolGuid,
672                       (VOID **) &Arp,
673                       gIp4DriverBinding.DriverBindingHandle,
674                       Ip4Instance->Handle,
675                       EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER
676                       );
677       if (EFI_ERROR (Status)) {
678         goto ON_EXIT;
679       }
680     }
681   }
682 
683   Ip4AddRoute (
684     IpSb->DefaultRouteTable,
685     StationAddress,
686     SubnetMask,
687     IP4_ALLZERO_ADDRESS
688     );
689 
690   //
691   // Add routes returned by EFI_IP4_CONFIG protocol.
692   //
693   for (Index = 0; Index < Data->RouteTableSize; Index++) {
694     RouteEntry = &Data->RouteTable[Index];
695 
696     SubnetAddress = EFI_NTOHL (RouteEntry->SubnetAddress);
697     SubnetMask = EFI_NTOHL (RouteEntry->SubnetMask);
698     GatewayAddress = EFI_NTOHL (RouteEntry->GatewayAddress);
699     Ip4AddRoute (IpSb->DefaultRouteTable, SubnetAddress, SubnetMask, GatewayAddress);
700   }
701 
702   IpSb->State = IP4_SERVICE_CONFIGED;
703 
704 ON_EXIT:
705   FreePool (Data);
706 }
707 
708 /**
709   Request Ip4AutoConfigCallBackDpc as a DPC at TPL_CALLBACK.
710 
711   @param Event     The event that is signalled.
712   @param Context   The IP4 service binding instance.
713 
714 **/
715 VOID
716 EFIAPI
Ip4AutoConfigCallBack(IN EFI_EVENT Event,IN VOID * Context)717 Ip4AutoConfigCallBack (
718   IN EFI_EVENT              Event,
719   IN VOID                   *Context
720   )
721 {
722   IP4_SERVICE  *IpSb;
723 
724   IpSb              = (IP4_SERVICE *) Context;
725   IpSb->ActiveEvent = Event;
726 
727   //
728   // Request Ip4AutoConfigCallBackDpc as a DPC at TPL_CALLBACK
729   //
730   QueueDpc (TPL_CALLBACK, Ip4AutoConfigCallBackDpc, Context);
731 }
732 
733 
734 /**
735   Start the auto configuration for this IP service instance.
736   It will locates the EFI_IP4_CONFIG_PROTOCOL, then start the
737   auto configuration.
738 
739   @param[in]  IpSb               The IP4 service instance to configure
740 
741   @retval EFI_SUCCESS            The auto configuration is successfull started
742   @retval Others                 Failed to start auto configuration.
743 
744 **/
745 EFI_STATUS
Ip4StartAutoConfig(IN IP4_SERVICE * IpSb)746 Ip4StartAutoConfig (
747   IN IP4_SERVICE            *IpSb
748   )
749 {
750   EFI_IP4_CONFIG_PROTOCOL   *Ip4Config;
751   EFI_STATUS                Status;
752 
753   if (IpSb->State > IP4_SERVICE_UNSTARTED) {
754     return EFI_SUCCESS;
755   }
756 
757   //
758   // Create the DoneEvent and ReconfigEvent to call EFI_IP4_CONFIG
759   //
760   Status = gBS->CreateEvent (
761                   EVT_NOTIFY_SIGNAL,
762                   TPL_CALLBACK,
763                   Ip4AutoConfigCallBack,
764                   IpSb,
765                   &IpSb->DoneEvent
766                   );
767 
768   if (EFI_ERROR (Status)) {
769     return Status;
770   }
771 
772   Status = gBS->CreateEvent (
773                   EVT_NOTIFY_SIGNAL,
774                   TPL_NOTIFY,
775                   Ip4AutoConfigCallBack,
776                   IpSb,
777                   &IpSb->ReconfigEvent
778                   );
779 
780   if (EFI_ERROR (Status)) {
781     goto CLOSE_DONE_EVENT;
782   }
783 
784   //
785   // Open the EFI_IP4_CONFIG protocol then start auto configure
786   //
787   Status = gBS->OpenProtocol (
788                   IpSb->Controller,
789                   &gEfiIp4ConfigProtocolGuid,
790                   (VOID **) &Ip4Config,
791                   IpSb->Image,
792                   IpSb->Controller,
793                   EFI_OPEN_PROTOCOL_BY_DRIVER | EFI_OPEN_PROTOCOL_EXCLUSIVE
794                   );
795 
796   if (EFI_ERROR (Status)) {
797     Status = EFI_UNSUPPORTED;
798     goto CLOSE_RECONFIG_EVENT;
799   }
800 
801   Status = Ip4Config->Start (Ip4Config, IpSb->DoneEvent, IpSb->ReconfigEvent);
802 
803   if (EFI_ERROR (Status)) {
804     gBS->CloseProtocol (
805            IpSb->Controller,
806            &gEfiIp4ConfigProtocolGuid,
807            IpSb->Image,
808            IpSb->Controller
809            );
810 
811     goto CLOSE_RECONFIG_EVENT;
812   }
813 
814   IpSb->Ip4Config = Ip4Config;
815   IpSb->State     = IP4_SERVICE_STARTED;
816   return Status;
817 
818 CLOSE_RECONFIG_EVENT:
819   gBS->CloseEvent (IpSb->ReconfigEvent);
820   IpSb->ReconfigEvent = NULL;
821 
822 CLOSE_DONE_EVENT:
823   gBS->CloseEvent (IpSb->DoneEvent);
824   IpSb->DoneEvent = NULL;
825 
826   return Status;
827 }
828 
829 
830 /**
831   Intiialize the IP4_PROTOCOL structure to the unconfigured states.
832 
833   @param  IpSb                   The IP4 service instance.
834   @param  IpInstance             The IP4 child instance.
835 
836 **/
837 VOID
Ip4InitProtocol(IN IP4_SERVICE * IpSb,IN OUT IP4_PROTOCOL * IpInstance)838 Ip4InitProtocol (
839   IN     IP4_SERVICE            *IpSb,
840   IN OUT IP4_PROTOCOL           *IpInstance
841   )
842 {
843   ASSERT ((IpSb != NULL) && (IpInstance != NULL));
844 
845   ZeroMem (IpInstance, sizeof (IP4_PROTOCOL));
846 
847   IpInstance->Signature = IP4_PROTOCOL_SIGNATURE;
848   CopyMem (&IpInstance->Ip4Proto, &mEfiIp4ProtocolTemplete, sizeof (IpInstance->Ip4Proto));
849   IpInstance->State     = IP4_STATE_UNCONFIGED;
850   IpInstance->Service   = IpSb;
851 
852   InitializeListHead (&IpInstance->Link);
853   NetMapInit  (&IpInstance->RxTokens);
854   NetMapInit  (&IpInstance->TxTokens);
855   InitializeListHead (&IpInstance->Received);
856   InitializeListHead (&IpInstance->Delivered);
857   InitializeListHead (&IpInstance->AddrLink);
858 
859   EfiInitializeLock (&IpInstance->RecycleLock, TPL_NOTIFY);
860 }
861 
862 
863 /**
864   Configure the IP4 child. If the child is already configured,
865   change the configuration parameter. Otherwise configure it
866   for the first time. The caller should validate the configuration
867   before deliver them to it. It also don't do configure NULL.
868 
869   @param[in, out]  IpInstance         The IP4 child to configure.
870   @param[in]       Config             The configure data.
871 
872   @retval EFI_SUCCESS            The IP4 child is successfully configured.
873   @retval EFI_DEVICE_ERROR       Failed to free the pending transive or to
874                                  configure  underlying MNP or other errors.
875   @retval EFI_NO_MAPPING         The IP4 child is configured to use default
876                                  address, but the default address hasn't been
877                                  configured. The IP4 child doesn't need to be
878                                  reconfigured when default address is configured.
879   @retval EFI_OUT_OF_RESOURCES   No more memory space is available.
880   @retval other                  Other error occurs.
881 
882 **/
883 EFI_STATUS
Ip4ConfigProtocol(IN OUT IP4_PROTOCOL * IpInstance,IN EFI_IP4_CONFIG_DATA * Config)884 Ip4ConfigProtocol (
885   IN OUT IP4_PROTOCOL         *IpInstance,
886   IN     EFI_IP4_CONFIG_DATA  *Config
887   )
888 {
889   IP4_SERVICE               *IpSb;
890   IP4_INTERFACE             *IpIf;
891   EFI_STATUS                Status;
892   IP4_ADDR                  Ip;
893   IP4_ADDR                  Netmask;
894   EFI_ARP_PROTOCOL          *Arp;
895 
896   IpSb = IpInstance->Service;
897 
898   //
899   // User is changing packet filters. It must be stopped
900   // before the station address can be changed.
901   //
902   if (IpInstance->State == IP4_STATE_CONFIGED) {
903     //
904     // Cancel all the pending transmit/receive from upper layer
905     //
906     Status = Ip4Cancel (IpInstance, NULL);
907 
908     if (EFI_ERROR (Status)) {
909       return EFI_DEVICE_ERROR;
910     }
911 
912     CopyMem (&IpInstance->ConfigData, Config, sizeof (IpInstance->ConfigData));
913     return EFI_SUCCESS;
914   }
915 
916   //
917   // Configure a fresh IP4 protocol instance. Create a route table.
918   // Each IP child has its own route table, which may point to the
919   // default table if it is using default address.
920   //
921   Status                 = EFI_OUT_OF_RESOURCES;
922   IpInstance->RouteTable = Ip4CreateRouteTable ();
923 
924   if (IpInstance->RouteTable == NULL) {
925     return Status;
926   }
927 
928   //
929   // Set up the interface.
930   //
931   CopyMem (&Ip, &Config->StationAddress, sizeof (IP4_ADDR));
932   CopyMem (&Netmask, &Config->SubnetMask, sizeof (IP4_ADDR));
933 
934   Ip      = NTOHL (Ip);
935   Netmask = NTOHL (Netmask);
936 
937   if (!Config->UseDefaultAddress) {
938     //
939     // Find whether there is already an interface with the same
940     // station address. All the instances with the same station
941     // address shares one interface.
942     //
943     IpIf = Ip4FindStationAddress (IpSb, Ip, Netmask);
944 
945     if (IpIf != NULL) {
946       NET_GET_REF (IpIf);
947 
948     } else {
949       IpIf = Ip4CreateInterface (IpSb->Mnp, IpSb->Controller, IpSb->Image);
950 
951       if (IpIf == NULL) {
952         goto ON_ERROR;
953       }
954 
955       Status = Ip4SetAddress (IpIf, Ip, Netmask);
956 
957       if (EFI_ERROR (Status)) {
958         Status = EFI_DEVICE_ERROR;
959         Ip4FreeInterface (IpIf, IpInstance);
960         goto ON_ERROR;
961       }
962 
963       InsertTailList (&IpSb->Interfaces, &IpIf->Link);
964     }
965 
966     //
967     // Add a route to this connected network in the route table
968     //
969     Ip4AddRoute (IpInstance->RouteTable, Ip, Netmask, IP4_ALLZERO_ADDRESS);
970 
971   } else {
972     //
973     // Use the default address. If the default configuration hasn't
974     // been started, start it.
975     //
976     if (IpSb->State == IP4_SERVICE_UNSTARTED) {
977       Status = Ip4StartAutoConfig (IpSb);
978 
979       if (EFI_ERROR (Status)) {
980         goto ON_ERROR;
981       }
982     }
983 
984     IpIf = IpSb->DefaultInterface;
985     NET_GET_REF (IpSb->DefaultInterface);
986 
987     //
988     // If default address is used, so is the default route table.
989     // Any route set by the instance has the precedence over the
990     // routes in the default route table. Link the default table
991     // after the instance's table. Routing will search the local
992     // table first.
993     //
994     NET_GET_REF (IpSb->DefaultRouteTable);
995     IpInstance->RouteTable->Next = IpSb->DefaultRouteTable;
996   }
997 
998   IpInstance->Interface = IpIf;
999   if (IpIf->Arp != NULL) {
1000     Arp = NULL;
1001     Status = gBS->OpenProtocol (
1002                     IpIf->ArpHandle,
1003                     &gEfiArpProtocolGuid,
1004                     (VOID **) &Arp,
1005                     gIp4DriverBinding.DriverBindingHandle,
1006                     IpInstance->Handle,
1007                     EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER
1008                     );
1009     if (EFI_ERROR (Status)) {
1010       goto ON_ERROR;
1011     }
1012   }
1013   InsertTailList (&IpIf->IpInstances, &IpInstance->AddrLink);
1014 
1015   CopyMem (&IpInstance->ConfigData, Config, sizeof (IpInstance->ConfigData));
1016   IpInstance->State       = IP4_STATE_CONFIGED;
1017 
1018   //
1019   // Although EFI_NO_MAPPING is an error code, the IP child has been
1020   // successfully configured and doesn't need reconfiguration when
1021   // default address is acquired.
1022   //
1023   if (Config->UseDefaultAddress && IP4_NO_MAPPING (IpInstance)) {
1024     return EFI_NO_MAPPING;
1025   }
1026 
1027   return EFI_SUCCESS;
1028 
1029 ON_ERROR:
1030   Ip4FreeRouteTable (IpInstance->RouteTable);
1031   IpInstance->RouteTable = NULL;
1032   return Status;
1033 }
1034 
1035 
1036 /**
1037   Clean up the IP4 child, release all the resources used by it.
1038 
1039   @param[in]  IpInstance         The IP4 child to clean up.
1040 
1041   @retval EFI_SUCCESS            The IP4 child is cleaned up
1042   @retval EFI_DEVICE_ERROR       Some resources failed to be released
1043 
1044 **/
1045 EFI_STATUS
Ip4CleanProtocol(IN IP4_PROTOCOL * IpInstance)1046 Ip4CleanProtocol (
1047   IN  IP4_PROTOCOL          *IpInstance
1048   )
1049 {
1050   if (EFI_ERROR (Ip4Cancel (IpInstance, NULL))) {
1051     return EFI_DEVICE_ERROR;
1052   }
1053 
1054   if (EFI_ERROR (Ip4Groups (IpInstance, FALSE, NULL))) {
1055     return EFI_DEVICE_ERROR;
1056   }
1057 
1058   //
1059   // Some packets haven't been recycled. It is because either the
1060   // user forgets to recycle the packets, or because the callback
1061   // hasn't been called. Just leave it alone.
1062   //
1063   if (!IsListEmpty (&IpInstance->Delivered)) {
1064     ;
1065   }
1066 
1067   if (IpInstance->Interface != NULL) {
1068     RemoveEntryList (&IpInstance->AddrLink);
1069     if (IpInstance->Interface->Arp != NULL) {
1070       gBS->CloseProtocol (
1071              IpInstance->Interface->ArpHandle,
1072              &gEfiArpProtocolGuid,
1073              gIp4DriverBinding.DriverBindingHandle,
1074              IpInstance->Handle
1075              );
1076     }
1077     Ip4FreeInterface (IpInstance->Interface, IpInstance);
1078     IpInstance->Interface = NULL;
1079   }
1080 
1081   if (IpInstance->RouteTable != NULL) {
1082     if (IpInstance->RouteTable->Next != NULL) {
1083       Ip4FreeRouteTable (IpInstance->RouteTable->Next);
1084     }
1085 
1086     Ip4FreeRouteTable (IpInstance->RouteTable);
1087     IpInstance->RouteTable = NULL;
1088   }
1089 
1090   if (IpInstance->EfiRouteTable != NULL) {
1091     FreePool (IpInstance->EfiRouteTable);
1092     IpInstance->EfiRouteTable = NULL;
1093     IpInstance->EfiRouteCount = 0;
1094   }
1095 
1096   if (IpInstance->Groups != NULL) {
1097     FreePool (IpInstance->Groups);
1098     IpInstance->Groups      = NULL;
1099     IpInstance->GroupCount  = 0;
1100   }
1101 
1102   NetMapClean (&IpInstance->TxTokens);
1103 
1104   NetMapClean (&IpInstance->RxTokens);
1105 
1106   return EFI_SUCCESS;
1107 }
1108 
1109 
1110 /**
1111   Validate that Ip/Netmask pair is OK to be used as station
1112   address. Only continuous netmasks are supported. and check
1113   that StationAddress is a unicast address on the newtwork.
1114 
1115   @param[in]  Ip                 The IP address to validate
1116   @param[in]  Netmask            The netmaks of the IP
1117 
1118   @retval TRUE                   The Ip/Netmask pair is valid
1119   @retval FALSE                  The Ip/Netmask pair is invalid
1120 
1121 **/
1122 BOOLEAN
Ip4StationAddressValid(IN IP4_ADDR Ip,IN IP4_ADDR Netmask)1123 Ip4StationAddressValid (
1124   IN IP4_ADDR               Ip,
1125   IN IP4_ADDR               Netmask
1126   )
1127 {
1128   IP4_ADDR                  NetBrdcastMask;
1129   INTN                      Len;
1130   INTN                      Type;
1131 
1132   //
1133   // Only support the station address with 0.0.0.0/0 to enable DHCP client.
1134   //
1135   if (Netmask == IP4_ALLZERO_ADDRESS) {
1136     return (BOOLEAN) (Ip == IP4_ALLZERO_ADDRESS);
1137   }
1138 
1139   //
1140   // Only support the continuous net masks
1141   //
1142   if ((Len = NetGetMaskLength (Netmask)) == IP4_MASK_NUM) {
1143     return FALSE;
1144   }
1145 
1146   //
1147   // Station address can't be class D or class E address
1148   //
1149   if ((Type = NetGetIpClass (Ip)) > IP4_ADDR_CLASSC) {
1150     return FALSE;
1151   }
1152 
1153   //
1154   // Station address can't be subnet broadcast/net broadcast address
1155   //
1156   if ((Ip == (Ip & Netmask)) || (Ip == (Ip | ~Netmask))) {
1157     return FALSE;
1158   }
1159 
1160   NetBrdcastMask = gIp4AllMasks[MIN (Len, Type << 3)];
1161 
1162   if (Ip == (Ip | ~NetBrdcastMask)) {
1163     return FALSE;
1164   }
1165 
1166   return TRUE;
1167 }
1168 
1169 
1170 /**
1171   Assigns an IPv4 address and subnet mask to this EFI IPv4 Protocol driver instance.
1172 
1173   The Configure() function is used to set, change, or reset the operational
1174   parameters and filter settings for this EFI IPv4 Protocol instance. Until these
1175   parameters have been set, no network traffic can be sent or received by this
1176   instance. Once the parameters have been reset (by calling this function with
1177   IpConfigData set to NULL), no more traffic can be sent or received until these
1178   parameters have been set again. Each EFI IPv4 Protocol instance can be started
1179   and stopped independently of each other by enabling or disabling their receive
1180   filter settings with the Configure() function.
1181 
1182   When IpConfigData.UseDefaultAddress is set to FALSE, the new station address will
1183   be appended as an alias address into the addresses list in the EFI IPv4 Protocol
1184   driver. While set to TRUE, Configure() will trigger the EFI_IP4_CONFIG_PROTOCOL
1185   to retrieve the default IPv4 address if it is not available yet. Clients could
1186   frequently call GetModeData() to check the status to ensure that the default IPv4
1187   address is ready.
1188 
1189   If operational parameters are reset or changed, any pending transmit and receive
1190   requests will be cancelled. Their completion token status will be set to EFI_ABORTED
1191   and their events will be signaled.
1192 
1193   @param[in]  This              Pointer to the EFI_IP4_PROTOCOL instance.
1194   @param[in]  IpConfigData      Pointer to the EFI IPv4 Protocol configuration data structure.
1195 
1196   @retval EFI_SUCCESS           The driver instance was successfully opened.
1197   @retval EFI_NO_MAPPING        When using the default address, configuration (DHCP, BOOTP,
1198                                 RARP, etc.) is not finished yet.
1199   @retval EFI_INVALID_PARAMETER One or more of the following conditions is TRUE:
1200   @retval EFI_UNSUPPORTED       One or more of the following conditions is TRUE:
1201                                 A configuration protocol (DHCP, BOOTP, RARP, etc.) could
1202                                 not be located when clients choose to use the default IPv4
1203                                 address. This EFI IPv4 Protocol implementation does not
1204                                 support this requested filter or timeout setting.
1205   @retval EFI_OUT_OF_RESOURCES  The EFI IPv4 Protocol driver instance data could not be allocated.
1206   @retval EFI_ALREADY_STARTED   The interface is already open and must be stopped before the
1207                                 IPv4 address or subnet mask can be changed. The interface must
1208                                 also be stopped when switching to/from raw packet mode.
1209   @retval EFI_DEVICE_ERROR      An unexpected system or network error occurred. The EFI IPv4
1210                                 Protocol driver instance is not opened.
1211 
1212 **/
1213 EFI_STATUS
1214 EFIAPI
EfiIp4Configure(IN EFI_IP4_PROTOCOL * This,IN EFI_IP4_CONFIG_DATA * IpConfigData OPTIONAL)1215 EfiIp4Configure (
1216   IN EFI_IP4_PROTOCOL       *This,
1217   IN EFI_IP4_CONFIG_DATA    *IpConfigData       OPTIONAL
1218   )
1219 {
1220   IP4_PROTOCOL              *IpInstance;
1221   EFI_IP4_CONFIG_DATA       *Current;
1222   EFI_TPL                   OldTpl;
1223   EFI_STATUS                Status;
1224   BOOLEAN                   AddrOk;
1225   IP4_ADDR                  IpAddress;
1226   IP4_ADDR                  SubnetMask;
1227 
1228   //
1229   // First, validate the parameters
1230   //
1231   if (This == NULL) {
1232     return EFI_INVALID_PARAMETER;
1233   }
1234 
1235   IpInstance = IP4_INSTANCE_FROM_PROTOCOL (This);
1236   OldTpl     = gBS->RaiseTPL (TPL_CALLBACK);
1237 
1238   //
1239   // Validate the configuration first.
1240   //
1241   if (IpConfigData != NULL) {
1242 
1243     CopyMem (&IpAddress, &IpConfigData->StationAddress, sizeof (IP4_ADDR));
1244     CopyMem (&SubnetMask, &IpConfigData->SubnetMask, sizeof (IP4_ADDR));
1245 
1246     IpAddress  = NTOHL (IpAddress);
1247     SubnetMask = NTOHL (SubnetMask);
1248 
1249     //
1250     // Check whether the station address is a valid unicast address
1251     //
1252     if (!IpConfigData->UseDefaultAddress) {
1253       AddrOk = Ip4StationAddressValid (IpAddress, SubnetMask);
1254 
1255       if (!AddrOk) {
1256         Status = EFI_INVALID_PARAMETER;
1257         goto ON_EXIT;
1258       }
1259     }
1260 
1261     //
1262     // User can only update packet filters when already configured.
1263     // If it wants to change the station address, it must configure(NULL)
1264     // the instance first.
1265     //
1266     if (IpInstance->State == IP4_STATE_CONFIGED) {
1267       Current = &IpInstance->ConfigData;
1268 
1269       if (Current->UseDefaultAddress != IpConfigData->UseDefaultAddress) {
1270         Status = EFI_ALREADY_STARTED;
1271         goto ON_EXIT;
1272       }
1273 
1274       if (!Current->UseDefaultAddress &&
1275          (!EFI_IP4_EQUAL (&Current->StationAddress, &IpConfigData->StationAddress) ||
1276           !EFI_IP4_EQUAL (&Current->SubnetMask, &IpConfigData->SubnetMask))) {
1277         Status = EFI_ALREADY_STARTED;
1278         goto ON_EXIT;
1279       }
1280 
1281       if (Current->UseDefaultAddress && IP4_NO_MAPPING (IpInstance)) {
1282         Status = EFI_NO_MAPPING;
1283         goto ON_EXIT;
1284       }
1285     }
1286   }
1287 
1288   //
1289   // Configure the instance or clean it up.
1290   //
1291   if (IpConfigData != NULL) {
1292     Status = Ip4ConfigProtocol (IpInstance, IpConfigData);
1293   } else {
1294     Status = Ip4CleanProtocol (IpInstance);
1295 
1296     //
1297     // Don't change the state if it is DESTROY, consider the following
1298     // valid sequence: Mnp is unloaded-->Ip Stopped-->Udp Stopped,
1299     // Configure (ThisIp, NULL). If the state is changed to UNCONFIGED,
1300     // the unload fails miserably.
1301     //
1302     if (IpInstance->State == IP4_STATE_CONFIGED) {
1303       IpInstance->State = IP4_STATE_UNCONFIGED;
1304     }
1305   }
1306 
1307   //
1308   // Update the MNP's configure data. Ip4ServiceConfigMnp will check
1309   // whether it is necessary to reconfigure the MNP.
1310   //
1311   Ip4ServiceConfigMnp (IpInstance->Service, FALSE);
1312 
1313 ON_EXIT:
1314   gBS->RestoreTPL (OldTpl);
1315   return Status;
1316 
1317 }
1318 
1319 
1320 /**
1321   Change the IP4 child's multicast setting. The caller
1322   should make sure that the parameters is valid.
1323 
1324   @param[in]  IpInstance             The IP4 child to change the setting.
1325   @param[in]  JoinFlag               TRUE to join the group, otherwise leave it
1326   @param[in]  GroupAddress           The target group address
1327 
1328   @retval EFI_ALREADY_STARTED    Want to join the group, but already a member of it
1329   @retval EFI_OUT_OF_RESOURCES   Failed to allocate some resources.
1330   @retval EFI_DEVICE_ERROR       Failed to set the group configuraton
1331   @retval EFI_SUCCESS            Successfully updated the group setting.
1332   @retval EFI_NOT_FOUND          Try to leave the group which it isn't a member.
1333 
1334 **/
1335 EFI_STATUS
Ip4Groups(IN IP4_PROTOCOL * IpInstance,IN BOOLEAN JoinFlag,IN EFI_IPv4_ADDRESS * GroupAddress OPTIONAL)1336 Ip4Groups (
1337   IN IP4_PROTOCOL           *IpInstance,
1338   IN BOOLEAN                JoinFlag,
1339   IN EFI_IPv4_ADDRESS       *GroupAddress       OPTIONAL
1340   )
1341 {
1342   IP4_ADDR                  *Members;
1343   IP4_ADDR                  Group;
1344   UINT32                    Index;
1345 
1346   //
1347   // Add it to the instance's Groups, and join the group by IGMP.
1348   // IpInstance->Groups is in network byte order. IGMP operates in
1349   // host byte order
1350   //
1351   if (JoinFlag) {
1352     //
1353     // When JoinFlag is TRUE, GroupAddress shouldn't be NULL.
1354     //
1355     ASSERT (GroupAddress != NULL);
1356     CopyMem (&Group, GroupAddress, sizeof (IP4_ADDR));
1357 
1358     for (Index = 0; Index < IpInstance->GroupCount; Index++) {
1359       if (IpInstance->Groups[Index] == Group) {
1360         return EFI_ALREADY_STARTED;
1361       }
1362     }
1363 
1364     Members = Ip4CombineGroups (IpInstance->Groups, IpInstance->GroupCount, Group);
1365 
1366     if (Members == NULL) {
1367       return EFI_OUT_OF_RESOURCES;
1368     }
1369 
1370     if (EFI_ERROR (Ip4JoinGroup (IpInstance, NTOHL (Group)))) {
1371       FreePool (Members);
1372       return EFI_DEVICE_ERROR;
1373     }
1374 
1375     if (IpInstance->Groups != NULL) {
1376       FreePool (IpInstance->Groups);
1377     }
1378 
1379     IpInstance->Groups = Members;
1380     IpInstance->GroupCount++;
1381 
1382     return EFI_SUCCESS;
1383   }
1384 
1385   //
1386   // Leave the group. Leave all the groups if GroupAddress is NULL.
1387   // Must iterate from the end to the beginning because the GroupCount
1388   // is decreamented each time an address is removed..
1389   //
1390   for (Index = IpInstance->GroupCount; Index > 0 ; Index--) {
1391     Group = IpInstance->Groups[Index - 1];
1392 
1393     if ((GroupAddress == NULL) || EFI_IP4_EQUAL (&Group, GroupAddress)) {
1394       if (EFI_ERROR (Ip4LeaveGroup (IpInstance, NTOHL (Group)))) {
1395         return EFI_DEVICE_ERROR;
1396       }
1397 
1398       Ip4RemoveGroupAddr (IpInstance->Groups, IpInstance->GroupCount, Group);
1399       IpInstance->GroupCount--;
1400 
1401       if (IpInstance->GroupCount == 0) {
1402         ASSERT (Index == 1);
1403 
1404         FreePool (IpInstance->Groups);
1405         IpInstance->Groups = NULL;
1406       }
1407 
1408       if (GroupAddress != NULL) {
1409         return EFI_SUCCESS;
1410       }
1411     }
1412   }
1413 
1414   return ((GroupAddress != NULL) ? EFI_NOT_FOUND : EFI_SUCCESS);
1415 }
1416 
1417 
1418 /**
1419   Joins and leaves multicast groups.
1420 
1421   The Groups() function is used to join and leave multicast group sessions. Joining
1422   a group will enable reception of matching multicast packets. Leaving a group will
1423   disable the multicast packet reception.
1424 
1425   If JoinFlag is FALSE and GroupAddress is NULL, all joined groups will be left.
1426 
1427   @param[in]  This                  Pointer to the EFI_IP4_PROTOCOL instance.
1428   @param[in]  JoinFlag              Set to TRUE to join the multicast group session and FALSE to leave.
1429   @param[in]  GroupAddress          Pointer to the IPv4 multicast address.
1430 
1431   @retval EFI_SUCCESS           The operation completed successfully.
1432   @retval EFI_INVALID_PARAMETER One or more of the following is TRUE:
1433                                 - This is NULL.
1434                                 - JoinFlag is TRUE and GroupAddress is NULL.
1435                                 - GroupAddress is not NULL and *GroupAddress is
1436                                 not a multicast IPv4 address.
1437   @retval EFI_NOT_STARTED       This instance has not been started.
1438   @retval EFI_NO_MAPPING        When using the default address, configuration (DHCP, BOOTP,
1439                                 RARP, etc.) is not finished yet.
1440   @retval EFI_OUT_OF_RESOURCES  System resources could not be allocated.
1441   @retval EFI_UNSUPPORTED       This EFI IPv4 Protocol implementation does not support multicast groups.
1442   @retval EFI_ALREADY_STARTED   The group address is already in the group table (when
1443                                 JoinFlag is TRUE).
1444   @retval EFI_NOT_FOUND         The group address is not in the group table (when JoinFlag is FALSE).
1445   @retval EFI_DEVICE_ERROR      An unexpected system or network error occurred.
1446 
1447 **/
1448 EFI_STATUS
1449 EFIAPI
EfiIp4Groups(IN EFI_IP4_PROTOCOL * This,IN BOOLEAN JoinFlag,IN EFI_IPv4_ADDRESS * GroupAddress OPTIONAL)1450 EfiIp4Groups (
1451   IN EFI_IP4_PROTOCOL       *This,
1452   IN BOOLEAN                JoinFlag,
1453   IN EFI_IPv4_ADDRESS       *GroupAddress     OPTIONAL
1454   )
1455 {
1456   IP4_PROTOCOL              *IpInstance;
1457   EFI_STATUS                Status;
1458   EFI_TPL                   OldTpl;
1459   IP4_ADDR                  McastIp;
1460 
1461   if ((This == NULL) || (JoinFlag && (GroupAddress == NULL))) {
1462     return EFI_INVALID_PARAMETER;
1463   }
1464 
1465   if (GroupAddress != NULL) {
1466     CopyMem (&McastIp, GroupAddress, sizeof (IP4_ADDR));
1467 
1468     if (!IP4_IS_MULTICAST (NTOHL (McastIp))) {
1469       return EFI_INVALID_PARAMETER;
1470     }
1471   }
1472 
1473   IpInstance = IP4_INSTANCE_FROM_PROTOCOL (This);
1474   OldTpl     = gBS->RaiseTPL (TPL_CALLBACK);
1475 
1476   if (IpInstance->State != IP4_STATE_CONFIGED) {
1477     Status = EFI_NOT_STARTED;
1478     goto ON_EXIT;
1479   }
1480 
1481   if (IpInstance->ConfigData.UseDefaultAddress && IP4_NO_MAPPING (IpInstance)) {
1482     Status = EFI_NO_MAPPING;
1483     goto ON_EXIT;
1484   }
1485 
1486   Status = Ip4Groups (IpInstance, JoinFlag, GroupAddress);
1487 
1488 ON_EXIT:
1489   gBS->RestoreTPL (OldTpl);
1490   return Status;
1491 }
1492 
1493 
1494 /**
1495   Adds and deletes routing table entries.
1496 
1497   The Routes() function adds a route to or deletes a route from the routing table.
1498 
1499   Routes are determined by comparing the SubnetAddress with the destination IPv4
1500   address arithmetically AND-ed with the SubnetMask. The gateway address must be
1501   on the same subnet as the configured station address.
1502 
1503   The default route is added with SubnetAddress and SubnetMask both set to 0.0.0.0.
1504   The default route matches all destination IPv4 addresses that do not match any
1505   other routes.
1506 
1507   A GatewayAddress that is zero is a nonroute. Packets are sent to the destination
1508   IP address if it can be found in the ARP cache or on the local subnet. One automatic
1509   nonroute entry will be inserted into the routing table for outgoing packets that
1510   are addressed to a local subnet (gateway address of 0.0.0.0).
1511 
1512   Each EFI IPv4 Protocol instance has its own independent routing table. Those EFI
1513   IPv4 Protocol instances that use the default IPv4 address will also have copies
1514   of the routing table that was provided by the EFI_IP4_CONFIG_PROTOCOL, and these
1515   copies will be updated whenever the EIF IPv4 Protocol driver reconfigures its
1516   instances. As a result, client modification to the routing table will be lost.
1517 
1518   @param[in]  This                   Pointer to the EFI_IP4_PROTOCOL instance.
1519   @param[in]  DeleteRoute            Set to TRUE to delete this route from the routing table. Set to
1520                                      FALSE to add this route to the routing table. SubnetAddress
1521                                      and SubnetMask are used as the key to each route entry.
1522   @param[in]  SubnetAddress          The address of the subnet that needs to be routed.
1523   @param[in]  SubnetMask             The subnet mask of SubnetAddress.
1524   @param[in]  GatewayAddress         The unicast gateway IPv4 address for this route.
1525 
1526   @retval EFI_SUCCESS            The operation completed successfully.
1527   @retval EFI_NOT_STARTED        The driver instance has not been started.
1528   @retval EFI_NO_MAPPING         When using the default address, configuration (DHCP, BOOTP,
1529                                  RARP, etc.) is not finished yet.
1530   @retval EFI_INVALID_PARAMETER  One or more of the following conditions is TRUE:
1531                                  - This is NULL.
1532                                  - SubnetAddress is NULL.
1533                                  - SubnetMask is NULL.
1534                                  - GatewayAddress is NULL.
1535                                  - *SubnetAddress is not a valid subnet address.
1536                                  - *SubnetMask is not a valid subnet mask.
1537                                  - *GatewayAddress is not a valid unicast IPv4 address.
1538   @retval EFI_OUT_OF_RESOURCES   Could not add the entry to the routing table.
1539   @retval EFI_NOT_FOUND          This route is not in the routing table (when DeleteRoute is TRUE).
1540   @retval EFI_ACCESS_DENIED      The route is already defined in the routing table (when
1541                                   DeleteRoute is FALSE).
1542 
1543 **/
1544 EFI_STATUS
1545 EFIAPI
EfiIp4Routes(IN EFI_IP4_PROTOCOL * This,IN BOOLEAN DeleteRoute,IN EFI_IPv4_ADDRESS * SubnetAddress,IN EFI_IPv4_ADDRESS * SubnetMask,IN EFI_IPv4_ADDRESS * GatewayAddress)1546 EfiIp4Routes (
1547   IN EFI_IP4_PROTOCOL       *This,
1548   IN BOOLEAN                DeleteRoute,
1549   IN EFI_IPv4_ADDRESS       *SubnetAddress,
1550   IN EFI_IPv4_ADDRESS       *SubnetMask,
1551   IN EFI_IPv4_ADDRESS       *GatewayAddress
1552   )
1553 {
1554   IP4_PROTOCOL              *IpInstance;
1555   IP4_INTERFACE             *IpIf;
1556   IP4_ADDR                  Dest;
1557   IP4_ADDR                  Netmask;
1558   IP4_ADDR                  Nexthop;
1559   EFI_STATUS                Status;
1560   EFI_TPL                   OldTpl;
1561 
1562   //
1563   // First, validate the parameters
1564   //
1565   if ((This == NULL) || (SubnetAddress == NULL) ||
1566       (SubnetMask == NULL) || (GatewayAddress == NULL)) {
1567     return EFI_INVALID_PARAMETER;
1568   }
1569 
1570   IpInstance = IP4_INSTANCE_FROM_PROTOCOL (This);
1571   OldTpl     = gBS->RaiseTPL (TPL_CALLBACK);
1572 
1573   if (IpInstance->State != IP4_STATE_CONFIGED) {
1574     Status = EFI_NOT_STARTED;
1575     goto ON_EXIT;
1576   }
1577 
1578   if (IpInstance->ConfigData.UseDefaultAddress && IP4_NO_MAPPING (IpInstance)) {
1579     Status = EFI_NO_MAPPING;
1580     goto ON_EXIT;
1581   }
1582 
1583   CopyMem (&Dest, SubnetAddress, sizeof (IP4_ADDR));
1584   CopyMem (&Netmask, SubnetMask, sizeof (IP4_ADDR));
1585   CopyMem (&Nexthop, GatewayAddress, sizeof (IP4_ADDR));
1586 
1587   Dest    = NTOHL (Dest);
1588   Netmask = NTOHL (Netmask);
1589   Nexthop = NTOHL (Nexthop);
1590 
1591   IpIf    = IpInstance->Interface;
1592 
1593   if (!IP4_IS_VALID_NETMASK (Netmask)) {
1594     Status = EFI_INVALID_PARAMETER;
1595     goto ON_EXIT;
1596   }
1597 
1598   //
1599   // the gateway address must be a unicast on the connected network if not zero.
1600   //
1601   if ((Nexthop != IP4_ALLZERO_ADDRESS) &&
1602       (!IP4_NET_EQUAL (Nexthop, IpIf->Ip, IpIf->SubnetMask) ||
1603         IP4_IS_BROADCAST (Ip4GetNetCast (Nexthop, IpIf)))) {
1604 
1605     Status = EFI_INVALID_PARAMETER;
1606     goto ON_EXIT;
1607   }
1608 
1609   if (DeleteRoute) {
1610     Status = Ip4DelRoute (IpInstance->RouteTable, Dest, Netmask, Nexthop);
1611   } else {
1612     Status = Ip4AddRoute (IpInstance->RouteTable, Dest, Netmask, Nexthop);
1613   }
1614 
1615 ON_EXIT:
1616   gBS->RestoreTPL (OldTpl);
1617   return Status;
1618 }
1619 
1620 
1621 /**
1622   Check whether the user's token or event has already
1623   been enqueued on IP4's list.
1624 
1625   @param[in]  Map                    The container of either user's transmit or receive
1626                                      token.
1627   @param[in]  Item                   Current item to check against
1628   @param[in]  Context                The Token to check againist.
1629 
1630   @retval EFI_ACCESS_DENIED      The token or event has already been enqueued in IP
1631   @retval EFI_SUCCESS            The current item isn't the same token/event as the
1632                                  context.
1633 
1634 **/
1635 EFI_STATUS
1636 EFIAPI
Ip4TokenExist(IN NET_MAP * Map,IN NET_MAP_ITEM * Item,IN VOID * Context)1637 Ip4TokenExist (
1638   IN NET_MAP                *Map,
1639   IN NET_MAP_ITEM           *Item,
1640   IN VOID                   *Context
1641   )
1642 {
1643   EFI_IP4_COMPLETION_TOKEN  *Token;
1644   EFI_IP4_COMPLETION_TOKEN  *TokenInItem;
1645 
1646   Token       = (EFI_IP4_COMPLETION_TOKEN *) Context;
1647   TokenInItem = (EFI_IP4_COMPLETION_TOKEN *) Item->Key;
1648 
1649   if ((Token == TokenInItem) || (Token->Event == TokenInItem->Event)) {
1650     return EFI_ACCESS_DENIED;
1651   }
1652 
1653   return EFI_SUCCESS;
1654 }
1655 
1656 /**
1657   Validate the user's token against current station address.
1658 
1659   @param[in]  Token              User's token to validate.
1660   @param[in]  IpIf               The IP4 child's interface.
1661   @param[in]  RawData            Set to TRUE to send unformatted packets.
1662 
1663   @retval EFI_INVALID_PARAMETER  Some parameters are invalid.
1664   @retval EFI_BAD_BUFFER_SIZE    The user's option/data is too long.
1665   @retval EFI_SUCCESS            The token is valid.
1666 
1667 **/
1668 EFI_STATUS
Ip4TxTokenValid(IN EFI_IP4_COMPLETION_TOKEN * Token,IN IP4_INTERFACE * IpIf,IN BOOLEAN RawData)1669 Ip4TxTokenValid (
1670   IN EFI_IP4_COMPLETION_TOKEN   *Token,
1671   IN IP4_INTERFACE              *IpIf,
1672   IN BOOLEAN                    RawData
1673   )
1674 {
1675   EFI_IP4_TRANSMIT_DATA     *TxData;
1676   EFI_IP4_OVERRIDE_DATA     *Override;
1677   IP4_ADDR                  Src;
1678   IP4_ADDR                  Gateway;
1679   UINT32                    Offset;
1680   UINT32                    Index;
1681   UINT32                    HeadLen;
1682 
1683   if ((Token == NULL) || (Token->Event == NULL) || (Token->Packet.TxData == NULL)) {
1684     return EFI_INVALID_PARAMETER;
1685   }
1686 
1687   TxData = Token->Packet.TxData;
1688 
1689   //
1690   // Check the fragment table: no empty fragment, and length isn't bogus.
1691   //
1692   if ((TxData->TotalDataLength == 0) || (TxData->FragmentCount == 0)) {
1693     return EFI_INVALID_PARAMETER;
1694   }
1695 
1696   Offset = TxData->TotalDataLength;
1697 
1698   if (Offset > IP4_MAX_PACKET_SIZE) {
1699     return EFI_BAD_BUFFER_SIZE;
1700   }
1701 
1702   for (Index = 0; Index < TxData->FragmentCount; Index++) {
1703     if ((TxData->FragmentTable[Index].FragmentBuffer == NULL) ||
1704         (TxData->FragmentTable[Index].FragmentLength == 0)) {
1705 
1706       return EFI_INVALID_PARAMETER;
1707     }
1708 
1709     Offset -= TxData->FragmentTable[Index].FragmentLength;
1710   }
1711 
1712   if (Offset != 0) {
1713     return EFI_INVALID_PARAMETER;
1714   }
1715 
1716   //
1717   // NOTE that OptionsLength/OptionsBuffer/OverrideData are ignored if RawData
1718   // is TRUE.
1719   //
1720   if (RawData) {
1721     return EFI_SUCCESS;
1722   }
1723 
1724   //
1725   // Check the IP options: no more than 40 bytes and format is OK
1726   //
1727   if (TxData->OptionsLength != 0) {
1728     if ((TxData->OptionsLength > 40) || (TxData->OptionsBuffer == NULL)) {
1729       return EFI_INVALID_PARAMETER;
1730     }
1731 
1732     if (!Ip4OptionIsValid (TxData->OptionsBuffer, TxData->OptionsLength, FALSE)) {
1733       return EFI_INVALID_PARAMETER;
1734     }
1735   }
1736 
1737   //
1738   // Check the source and gateway: they must be a valid unicast.
1739   // Gateway must also be on the connected network.
1740   //
1741   if (TxData->OverrideData != NULL) {
1742     Override = TxData->OverrideData;
1743 
1744     CopyMem (&Src, &Override->SourceAddress, sizeof (IP4_ADDR));
1745     CopyMem (&Gateway, &Override->GatewayAddress, sizeof (IP4_ADDR));
1746 
1747     Src     = NTOHL (Src);
1748     Gateway = NTOHL (Gateway);
1749 
1750     if ((NetGetIpClass (Src) > IP4_ADDR_CLASSC) ||
1751         (Src == IP4_ALLONE_ADDRESS) ||
1752         IP4_IS_BROADCAST (Ip4GetNetCast (Src, IpIf))) {
1753 
1754       return EFI_INVALID_PARAMETER;
1755     }
1756 
1757     //
1758     // If gateway isn't zero, it must be a unicast address, and
1759     // on the connected network.
1760     //
1761     if ((Gateway != IP4_ALLZERO_ADDRESS) &&
1762         ((NetGetIpClass (Gateway) > IP4_ADDR_CLASSC) ||
1763          !IP4_NET_EQUAL (Gateway, IpIf->Ip, IpIf->SubnetMask) ||
1764          IP4_IS_BROADCAST (Ip4GetNetCast (Gateway, IpIf)))) {
1765 
1766       return EFI_INVALID_PARAMETER;
1767     }
1768   }
1769 
1770   //
1771   // Check the packet length: Head length and packet length all has a limit
1772   //
1773   HeadLen = sizeof (IP4_HEAD) + ((TxData->OptionsLength + 3) &~0x03);
1774 
1775   if ((HeadLen > IP4_MAX_HEADLEN) ||
1776       (TxData->TotalDataLength + HeadLen > IP4_MAX_PACKET_SIZE)) {
1777 
1778     return EFI_BAD_BUFFER_SIZE;
1779   }
1780 
1781   return EFI_SUCCESS;
1782 }
1783 
1784 
1785 /**
1786   The callback function for the net buffer which wraps the user's
1787   transmit token. Although it seems this function is pretty simple,
1788   there are some subtle things.
1789   When user requests the IP to transmit a packet by passing it a
1790   token, the token is wrapped in an IP4_TXTOKEN_WRAP and the data
1791   is wrapped in an net buffer. the net buffer's Free function is
1792   set to Ip4FreeTxToken. The Token and token wrap are added to the
1793   IP child's TxToken map. Then the buffer is passed to Ip4Output for
1794   transmission. If something error happened before that, the buffer
1795   is freed, which in turn will free the token wrap. The wrap may
1796   have been added to the TxToken map or not, and the user's event
1797   shouldn't be fired because we are still in the EfiIp4Transmit. If
1798   the buffer has been sent by Ip4Output, it should be removed from
1799   the TxToken map and user's event signaled. The token wrap and buffer
1800   are bound together. Check the comments in Ip4Output for information
1801   about IP fragmentation.
1802 
1803   @param[in]  Context                The token's wrap
1804 
1805 **/
1806 VOID
1807 EFIAPI
Ip4FreeTxToken(IN VOID * Context)1808 Ip4FreeTxToken (
1809   IN VOID                   *Context
1810   )
1811 {
1812   IP4_TXTOKEN_WRAP          *Wrap;
1813   NET_MAP_ITEM              *Item;
1814 
1815   Wrap = (IP4_TXTOKEN_WRAP *) Context;
1816 
1817   //
1818   // Signal IpSecRecycleEvent to inform IPsec free the memory
1819   //
1820   if (Wrap->IpSecRecycleSignal != NULL) {
1821     gBS->SignalEvent (Wrap->IpSecRecycleSignal);
1822   }
1823 
1824   //
1825   // Find the token in the instance's map. EfiIp4Transmit put the
1826   // token to the map. If that failed, NetMapFindKey will return NULL.
1827   //
1828   Item = NetMapFindKey (&Wrap->IpInstance->TxTokens, Wrap->Token);
1829 
1830   if (Item != NULL) {
1831     NetMapRemoveItem (&Wrap->IpInstance->TxTokens, Item, NULL);
1832   }
1833 
1834   if (Wrap->Sent) {
1835     gBS->SignalEvent (Wrap->Token->Event);
1836 
1837     //
1838     // Dispatch the DPC queued by the NotifyFunction of Token->Event.
1839     //
1840     DispatchDpc ();
1841   }
1842 
1843   FreePool (Wrap);
1844 }
1845 
1846 
1847 /**
1848   The callback function to Ip4Output to update the transmit status.
1849 
1850   @param  Ip4Instance            The Ip4Instance that request the transmit.
1851   @param  Packet                 The user's transmit request
1852   @param  IoStatus               The result of the transmission
1853   @param  Flag                   Not used during transmission
1854   @param  Context                The token's wrap.
1855 
1856 **/
1857 VOID
Ip4OnPacketSent(IP4_PROTOCOL * Ip4Instance,NET_BUF * Packet,EFI_STATUS IoStatus,UINT32 Flag,VOID * Context)1858 Ip4OnPacketSent (
1859   IP4_PROTOCOL              *Ip4Instance,
1860   NET_BUF                   *Packet,
1861   EFI_STATUS                IoStatus,
1862   UINT32                    Flag,
1863   VOID                      *Context
1864   )
1865 {
1866   IP4_TXTOKEN_WRAP          *Wrap;
1867 
1868   //
1869   // This is the transmission request from upper layer,
1870   // not the IP4 driver itself.
1871   //
1872   ASSERT (Ip4Instance != NULL);
1873 
1874   //
1875   // The first fragment of the packet has been sent. Update
1876   // the token's status. That is, if fragmented, the transmit's
1877   // status is the first fragment's status. The Wrap will be
1878   // release when all the fragments are release. Check the comments
1879   // in Ip4FreeTxToken and Ip4Output for information.
1880   //
1881   Wrap                = (IP4_TXTOKEN_WRAP *) Context;
1882   Wrap->Token->Status = IoStatus;
1883 
1884   NetbufFree (Wrap->Packet);
1885 }
1886 
1887 
1888 /**
1889   Places outgoing data packets into the transmit queue.
1890 
1891   The Transmit() function places a sending request in the transmit queue of this
1892   EFI IPv4 Protocol instance. Whenever the packet in the token is sent out or some
1893   errors occur, the event in the token will be signaled and the status is updated.
1894 
1895   @param[in]  This  Pointer to the EFI_IP4_PROTOCOL instance.
1896   @param[in]  Token Pointer to the transmit token.
1897 
1898   @retval  EFI_SUCCESS           The data has been queued for transmission.
1899   @retval  EFI_NOT_STARTED       This instance has not been started.
1900   @retval  EFI_NO_MAPPING        When using the default address, configuration (DHCP, BOOTP,
1901                                  RARP, etc.) is not finished yet.
1902   @retval  EFI_INVALID_PARAMETER One or more pameters are invalid.
1903   @retval  EFI_ACCESS_DENIED     The transmit completion token with the same Token.Event
1904                                  was already in the transmit queue.
1905   @retval  EFI_NOT_READY         The completion token could not be queued because the transmit
1906                                  queue is full.
1907   @retval  EFI_NOT_FOUND         Not route is found to destination address.
1908   @retval  EFI_OUT_OF_RESOURCES  Could not queue the transmit data.
1909   @retval  EFI_BUFFER_TOO_SMALL  Token.Packet.TxData.TotalDataLength is too
1910                                  short to transmit.
1911   @retval  EFI_BAD_BUFFER_SIZE   The length of the IPv4 header + option length + total data length is
1912                                  greater than MTU (or greater than the maximum packet size if
1913                                  Token.Packet.TxData.OverrideData.
1914                                  DoNotFragment is TRUE.)
1915 
1916 **/
1917 EFI_STATUS
1918 EFIAPI
EfiIp4Transmit(IN EFI_IP4_PROTOCOL * This,IN EFI_IP4_COMPLETION_TOKEN * Token)1919 EfiIp4Transmit (
1920   IN EFI_IP4_PROTOCOL         *This,
1921   IN EFI_IP4_COMPLETION_TOKEN *Token
1922   )
1923 {
1924   IP4_SERVICE               *IpSb;
1925   IP4_PROTOCOL              *IpInstance;
1926   IP4_INTERFACE             *IpIf;
1927   IP4_TXTOKEN_WRAP          *Wrap;
1928   EFI_IP4_TRANSMIT_DATA     *TxData;
1929   EFI_IP4_CONFIG_DATA       *Config;
1930   EFI_IP4_OVERRIDE_DATA     *Override;
1931   IP4_HEAD                  Head;
1932   IP4_ADDR                  GateWay;
1933   EFI_STATUS                Status;
1934   EFI_TPL                   OldTpl;
1935   BOOLEAN                   DontFragment;
1936   UINT32                    HeadLen;
1937   UINT8                     RawHdrLen;
1938   UINT32                    OptionsLength;
1939   UINT8                     *OptionsBuffer;
1940   VOID                      *FirstFragment;
1941 
1942   if (This == NULL) {
1943     return EFI_INVALID_PARAMETER;
1944   }
1945 
1946   IpInstance = IP4_INSTANCE_FROM_PROTOCOL (This);
1947 
1948   if (IpInstance->State != IP4_STATE_CONFIGED) {
1949     return EFI_NOT_STARTED;
1950   }
1951 
1952   OldTpl  = gBS->RaiseTPL (TPL_CALLBACK);
1953 
1954   IpSb    = IpInstance->Service;
1955   IpIf    = IpInstance->Interface;
1956   Config  = &IpInstance->ConfigData;
1957 
1958   if (Config->UseDefaultAddress && IP4_NO_MAPPING (IpInstance)) {
1959     Status = EFI_NO_MAPPING;
1960     goto ON_EXIT;
1961   }
1962 
1963   //
1964   // make sure that token is properly formated
1965   //
1966   Status = Ip4TxTokenValid (Token, IpIf, Config->RawData);
1967 
1968   if (EFI_ERROR (Status)) {
1969     goto ON_EXIT;
1970   }
1971 
1972   //
1973   // Check whether the token or signal already existed.
1974   //
1975   if (EFI_ERROR (NetMapIterate (&IpInstance->TxTokens, Ip4TokenExist, Token))) {
1976     Status = EFI_ACCESS_DENIED;
1977     goto ON_EXIT;
1978   }
1979 
1980   //
1981   // Build the IP header, need to fill in the Tos, TotalLen, Id,
1982   // fragment, Ttl, protocol, Src, and Dst.
1983   //
1984   TxData = Token->Packet.TxData;
1985 
1986   FirstFragment = NULL;
1987 
1988   if (Config->RawData) {
1989     //
1990     // When RawData is TRUE, first buffer in FragmentTable points to a raw
1991     // IPv4 fragment including IPv4 header and options.
1992     //
1993     FirstFragment = TxData->FragmentTable[0].FragmentBuffer;
1994     CopyMem (&RawHdrLen, FirstFragment, sizeof (UINT8));
1995 
1996     RawHdrLen = (UINT8) (RawHdrLen & 0x0f);
1997     if (RawHdrLen < 5) {
1998       Status = EFI_INVALID_PARAMETER;
1999       goto ON_EXIT;
2000     }
2001 
2002     RawHdrLen = (UINT8) (RawHdrLen << 2);
2003 
2004     CopyMem (&Head, FirstFragment, IP4_MIN_HEADLEN);
2005 
2006     Ip4NtohHead (&Head);
2007     HeadLen      = 0;
2008     DontFragment = IP4_DO_NOT_FRAGMENT (Head.Fragment);
2009 
2010     if (!DontFragment) {
2011       Status = EFI_INVALID_PARAMETER;
2012       goto ON_EXIT;
2013     }
2014 
2015     GateWay = IP4_ALLZERO_ADDRESS;
2016 
2017     //
2018     // Get IPv4 options from first fragment.
2019     //
2020     if (RawHdrLen == IP4_MIN_HEADLEN) {
2021       OptionsLength = 0;
2022       OptionsBuffer = NULL;
2023     } else {
2024       OptionsLength = RawHdrLen - IP4_MIN_HEADLEN;
2025       OptionsBuffer = (UINT8 *) FirstFragment + IP4_MIN_HEADLEN;
2026     }
2027 
2028     //
2029     // Trim off IPv4 header and options from first fragment.
2030     //
2031     TxData->FragmentTable[0].FragmentBuffer = (UINT8 *) FirstFragment + RawHdrLen;
2032     TxData->FragmentTable[0].FragmentLength = TxData->FragmentTable[0].FragmentLength - RawHdrLen;
2033   } else {
2034     CopyMem (&Head.Dst, &TxData->DestinationAddress, sizeof (IP4_ADDR));
2035     Head.Dst = NTOHL (Head.Dst);
2036 
2037     if (TxData->OverrideData != NULL) {
2038       Override      = TxData->OverrideData;
2039       Head.Protocol = Override->Protocol;
2040       Head.Tos      = Override->TypeOfService;
2041       Head.Ttl      = Override->TimeToLive;
2042       DontFragment  = Override->DoNotFragment;
2043 
2044       CopyMem (&Head.Src, &Override->SourceAddress, sizeof (IP4_ADDR));
2045       CopyMem (&GateWay, &Override->GatewayAddress, sizeof (IP4_ADDR));
2046 
2047       Head.Src = NTOHL (Head.Src);
2048       GateWay  = NTOHL (GateWay);
2049     } else {
2050       Head.Src      = IpIf->Ip;
2051       GateWay       = IP4_ALLZERO_ADDRESS;
2052       Head.Protocol = Config->DefaultProtocol;
2053       Head.Tos      = Config->TypeOfService;
2054       Head.Ttl      = Config->TimeToLive;
2055       DontFragment  = Config->DoNotFragment;
2056     }
2057 
2058     Head.Fragment = IP4_HEAD_FRAGMENT_FIELD (DontFragment, FALSE, 0);
2059     HeadLen       = (TxData->OptionsLength + 3) & (~0x03);
2060 
2061     OptionsLength = TxData->OptionsLength;
2062     OptionsBuffer = (UINT8 *) (TxData->OptionsBuffer);
2063   }
2064 
2065   //
2066   // If don't fragment and fragment needed, return error
2067   //
2068   if (DontFragment && (TxData->TotalDataLength + HeadLen > IpSb->MaxPacketSize)) {
2069     Status = EFI_BAD_BUFFER_SIZE;
2070     goto ON_EXIT;
2071   }
2072 
2073   //
2074   // OK, it survives all the validation check. Wrap the token in
2075   // a IP4_TXTOKEN_WRAP and the data in a netbuf
2076   //
2077   Status = EFI_OUT_OF_RESOURCES;
2078   Wrap   = AllocateZeroPool (sizeof (IP4_TXTOKEN_WRAP));
2079   if (Wrap == NULL) {
2080     goto ON_EXIT;
2081   }
2082 
2083   Wrap->IpInstance  = IpInstance;
2084   Wrap->Token       = Token;
2085   Wrap->Sent        = FALSE;
2086   Wrap->Life        = IP4_US_TO_SEC (Config->TransmitTimeout);
2087   Wrap->Packet      = NetbufFromExt (
2088                         (NET_FRAGMENT *) TxData->FragmentTable,
2089                         TxData->FragmentCount,
2090                         IP4_MAX_HEADLEN,
2091                         0,
2092                         Ip4FreeTxToken,
2093                         Wrap
2094                         );
2095 
2096   if (Wrap->Packet == NULL) {
2097     FreePool (Wrap);
2098     goto ON_EXIT;
2099   }
2100 
2101   Token->Status = EFI_NOT_READY;
2102 
2103   if (EFI_ERROR (NetMapInsertTail (&IpInstance->TxTokens, Token, Wrap))) {
2104     //
2105     // NetbufFree will call Ip4FreeTxToken, which in turn will
2106     // free the IP4_TXTOKEN_WRAP. Now, the token wrap hasn't been
2107     // enqueued.
2108     //
2109     if (Config->RawData) {
2110       //
2111       // Restore pointer of first fragment in RawData mode.
2112       //
2113       TxData->FragmentTable[0].FragmentBuffer = (UINT8 *) FirstFragment;
2114     }
2115 
2116     NetbufFree (Wrap->Packet);
2117     goto ON_EXIT;
2118   }
2119 
2120   //
2121   // Mark the packet sent before output it. Mark it not sent again if the
2122   // returned status is not EFI_SUCCESS;
2123   //
2124   Wrap->Sent = TRUE;
2125 
2126   Status = Ip4Output (
2127              IpSb,
2128              IpInstance,
2129              Wrap->Packet,
2130              &Head,
2131              OptionsBuffer,
2132              OptionsLength,
2133              GateWay,
2134              Ip4OnPacketSent,
2135              Wrap
2136              );
2137 
2138   if (EFI_ERROR (Status)) {
2139     Wrap->Sent = FALSE;
2140 
2141     if (Config->RawData) {
2142       //
2143       // Restore pointer of first fragment in RawData mode.
2144       //
2145       TxData->FragmentTable[0].FragmentBuffer = (UINT8 *) FirstFragment;
2146     }
2147 
2148     NetbufFree (Wrap->Packet);
2149   }
2150 
2151   if (Config->RawData) {
2152     //
2153     // Restore pointer of first fragment in RawData mode.
2154     //
2155     TxData->FragmentTable[0].FragmentBuffer = (UINT8 *) FirstFragment;
2156   }
2157 
2158 ON_EXIT:
2159   gBS->RestoreTPL (OldTpl);
2160   return Status;
2161 }
2162 
2163 
2164 /**
2165   Places a receiving request into the receiving queue.
2166 
2167   The Receive() function places a completion token into the receive packet queue.
2168   This function is always asynchronous.
2169 
2170   The Token.Event field in the completion token must be filled in by the caller
2171   and cannot be NULL. When the receive operation completes, the EFI IPv4 Protocol
2172   driver updates the Token.Status and Token.Packet.RxData fields and the Token.Event
2173   is signaled.
2174 
2175   @param[in]  This  Pointer to the EFI_IP4_PROTOCOL instance.
2176   @param[in]  Token Pointer to a token that is associated with the receive data descriptor.
2177 
2178   @retval EFI_SUCCESS           The receive completion token was cached.
2179   @retval EFI_NOT_STARTED       This EFI IPv4 Protocol instance has not been started.
2180   @retval EFI_NO_MAPPING        When using the default address, configuration (DHCP, BOOTP, RARP, etc.)
2181                                 is not finished yet.
2182   @retval EFI_INVALID_PARAMETER One or more of the following conditions is TRUE:
2183                                 - This is NULL.
2184                                 - Token is NULL.
2185                                 - Token.Event is NULL.
2186   @retval EFI_OUT_OF_RESOURCES  The receive completion token could not be queued due to a lack of system
2187                                 resources (usually memory).
2188   @retval EFI_DEVICE_ERROR      An unexpected system or network error occurred.
2189                                 The EFI IPv4 Protocol instance has been reset to startup defaults.
2190                                 EFI_ACCESS_DENIED The receive completion token with the same Token.Event was already
2191                                 in the receive queue.
2192   @retval EFI_NOT_READY         The receive request could not be queued because the receive queue is full.
2193   @retval EFI_ICMP_ERROR        An ICMP error packet was received.
2194 
2195 **/
2196 EFI_STATUS
2197 EFIAPI
EfiIp4Receive(IN EFI_IP4_PROTOCOL * This,IN EFI_IP4_COMPLETION_TOKEN * Token)2198 EfiIp4Receive (
2199   IN EFI_IP4_PROTOCOL         *This,
2200   IN EFI_IP4_COMPLETION_TOKEN *Token
2201   )
2202 {
2203   IP4_PROTOCOL              *IpInstance;
2204   EFI_STATUS                Status;
2205   EFI_TPL                   OldTpl;
2206 
2207   //
2208   // First validate the parameters
2209   //
2210   if ((This == NULL) || (Token == NULL) || (Token->Event == NULL)) {
2211     return EFI_INVALID_PARAMETER;
2212   }
2213 
2214   IpInstance = IP4_INSTANCE_FROM_PROTOCOL (This);
2215 
2216   OldTpl = gBS->RaiseTPL (TPL_CALLBACK);
2217 
2218   if (IpInstance->State != IP4_STATE_CONFIGED) {
2219     Status = EFI_NOT_STARTED;
2220     goto ON_EXIT;
2221   }
2222 
2223   //
2224   // Check whether the toke is already on the receive queue.
2225   //
2226   Status = NetMapIterate (&IpInstance->RxTokens, Ip4TokenExist, Token);
2227 
2228   if (EFI_ERROR (Status)) {
2229     Status = EFI_ACCESS_DENIED;
2230     goto ON_EXIT;
2231   }
2232 
2233   //
2234   // Queue the token then check whether there is pending received packet.
2235   //
2236   Status = NetMapInsertTail (&IpInstance->RxTokens, Token, NULL);
2237 
2238   if (EFI_ERROR (Status)) {
2239     goto ON_EXIT;
2240   }
2241 
2242   Status = Ip4InstanceDeliverPacket (IpInstance);
2243 
2244   //
2245   // Dispatch the DPC queued by the NotifyFunction of this instane's receive
2246   // event.
2247   //
2248   DispatchDpc ();
2249 
2250 ON_EXIT:
2251   gBS->RestoreTPL (OldTpl);
2252   return Status;
2253 }
2254 
2255 
2256 /**
2257   Cancel the transmitted but not recycled packet. If a matching
2258   token is found, it will call Ip4CancelPacket to cancel the
2259   packet. Ip4CancelPacket will cancel all the fragments of the
2260   packet. When all the fragments are freed, the IP4_TXTOKEN_WRAP
2261   will be deleted from the Map, and user's event signalled.
2262   Because Ip4CancelPacket and other functions are all called in
2263   line, so, after Ip4CancelPacket returns, the Item has been freed.
2264 
2265   @param[in]  Map                    The IP4 child's transmit queue
2266   @param[in]  Item                   The current transmitted packet to test.
2267   @param[in]  Context                The user's token to cancel.
2268 
2269   @retval EFI_SUCCESS            Continue to check the next Item.
2270   @retval EFI_ABORTED            The user's Token (Token != NULL) is cancelled.
2271 
2272 **/
2273 EFI_STATUS
2274 EFIAPI
Ip4CancelTxTokens(IN NET_MAP * Map,IN NET_MAP_ITEM * Item,IN VOID * Context)2275 Ip4CancelTxTokens (
2276   IN NET_MAP                *Map,
2277   IN NET_MAP_ITEM           *Item,
2278   IN VOID                   *Context
2279   )
2280 {
2281   EFI_IP4_COMPLETION_TOKEN  *Token;
2282   IP4_TXTOKEN_WRAP          *Wrap;
2283 
2284   Token = (EFI_IP4_COMPLETION_TOKEN *) Context;
2285 
2286   //
2287   // Return EFI_SUCCESS to check the next item in the map if
2288   // this one doesn't match.
2289   //
2290   if ((Token != NULL) && (Token != Item->Key)) {
2291     return EFI_SUCCESS;
2292   }
2293 
2294   Wrap = (IP4_TXTOKEN_WRAP *) Item->Value;
2295   ASSERT (Wrap != NULL);
2296 
2297   //
2298   // Don't access the Item, Wrap and Token's members after this point.
2299   // Item and wrap has been freed. And we no longer own the Token.
2300   //
2301   Ip4CancelPacket (Wrap->IpInstance->Interface, Wrap->Packet, EFI_ABORTED);
2302 
2303   //
2304   // If only one item is to be cancel, return EFI_ABORTED to stop
2305   // iterating the map any more.
2306   //
2307   if (Token != NULL) {
2308     return EFI_ABORTED;
2309   }
2310 
2311   return EFI_SUCCESS;
2312 }
2313 
2314 
2315 /**
2316   Cancel the receive request. This is quiet simple, because
2317   it is only enqueued in our local receive map.
2318 
2319   @param[in]  Map                    The IP4 child's receive queue
2320   @param[in]  Item                   Current receive request to cancel.
2321   @param[in]  Context                The user's token to cancel
2322 
2323   @retval EFI_SUCCESS            Continue to check the next receive request on the
2324                                  queue.
2325   @retval EFI_ABORTED            The user's token (token != NULL) has been
2326                                  cancelled.
2327 
2328 **/
2329 EFI_STATUS
2330 EFIAPI
Ip4CancelRxTokens(IN NET_MAP * Map,IN NET_MAP_ITEM * Item,IN VOID * Context)2331 Ip4CancelRxTokens (
2332   IN NET_MAP                *Map,
2333   IN NET_MAP_ITEM           *Item,
2334   IN VOID                   *Context
2335   )
2336 {
2337   EFI_IP4_COMPLETION_TOKEN  *Token;
2338   EFI_IP4_COMPLETION_TOKEN  *This;
2339 
2340   Token = (EFI_IP4_COMPLETION_TOKEN *) Context;
2341   This  = Item->Key;
2342 
2343   if ((Token != NULL) && (Token != This)) {
2344     return EFI_SUCCESS;
2345   }
2346 
2347   NetMapRemoveItem (Map, Item, NULL);
2348 
2349   This->Status        = EFI_ABORTED;
2350   This->Packet.RxData = NULL;
2351   gBS->SignalEvent (This->Event);
2352 
2353   if (Token != NULL) {
2354     return EFI_ABORTED;
2355   }
2356 
2357   return EFI_SUCCESS;
2358 }
2359 
2360 
2361 /**
2362   Cancel the user's receive/transmit request.
2363 
2364   @param[in]  IpInstance         The IP4 child
2365   @param[in]  Token              The token to cancel. If NULL, all token will be
2366                                  cancelled.
2367 
2368   @retval EFI_SUCCESS            The token is cancelled
2369   @retval EFI_NOT_FOUND          The token isn't found on either the
2370                                  transmit/receive queue
2371   @retval EFI_DEVICE_ERROR       Not all token is cancelled when Token is NULL.
2372 
2373 **/
2374 EFI_STATUS
Ip4Cancel(IN IP4_PROTOCOL * IpInstance,IN EFI_IP4_COMPLETION_TOKEN * Token OPTIONAL)2375 Ip4Cancel (
2376   IN IP4_PROTOCOL             *IpInstance,
2377   IN EFI_IP4_COMPLETION_TOKEN *Token          OPTIONAL
2378   )
2379 {
2380   EFI_STATUS                Status;
2381 
2382   //
2383   // First check the transmitted packet. Ip4CancelTxTokens returns
2384   // EFI_ABORTED to mean that the token has been cancelled when
2385   // token != NULL. So, return EFI_SUCCESS for this condition.
2386   //
2387   Status = NetMapIterate (&IpInstance->TxTokens, Ip4CancelTxTokens, Token);
2388 
2389   if (EFI_ERROR (Status)) {
2390     if ((Token != NULL) && (Status == EFI_ABORTED)) {
2391       return EFI_SUCCESS;
2392     }
2393 
2394     return Status;
2395   }
2396 
2397   //
2398   // Check the receive queue. Ip4CancelRxTokens also returns EFI_ABORT
2399   // for Token!=NULL and it is cancelled.
2400   //
2401   Status = NetMapIterate (&IpInstance->RxTokens, Ip4CancelRxTokens, Token);
2402   //
2403   // Dispatch the DPCs queued by the NotifyFunction of the canceled rx token's
2404   // events.
2405   //
2406   DispatchDpc ();
2407   if (EFI_ERROR (Status)) {
2408     if ((Token != NULL) && (Status == EFI_ABORTED)) {
2409       return EFI_SUCCESS;
2410     }
2411 
2412     return Status;
2413   }
2414 
2415   //
2416   // OK, if the Token is found when Token != NULL, the NetMapIterate
2417   // will return EFI_ABORTED, which has been interrupted as EFI_SUCCESS.
2418   //
2419   if (Token != NULL) {
2420     return EFI_NOT_FOUND;
2421   }
2422 
2423   //
2424   // If Token == NULL, cancel all the tokens. return error if no
2425   // all of them are cancelled.
2426   //
2427   if (!NetMapIsEmpty (&IpInstance->TxTokens) ||
2428       !NetMapIsEmpty (&IpInstance->RxTokens)) {
2429 
2430     return EFI_DEVICE_ERROR;
2431   }
2432 
2433   return EFI_SUCCESS;
2434 }
2435 
2436 
2437 /**
2438   Abort an asynchronous transmit or receive request.
2439 
2440   The Cancel() function is used to abort a pending transmit or receive request.
2441   If the token is in the transmit or receive request queues, after calling this
2442   function, Token->Status will be set to EFI_ABORTED and then Token->Event will
2443   be signaled. If the token is not in one of the queues, which usually means the
2444   asynchronous operation has completed, this function will not signal the token
2445   and EFI_NOT_FOUND is returned.
2446 
2447   @param[in]  This  Pointer to the EFI_IP4_PROTOCOL instance.
2448   @param[in]  Token Pointer to a token that has been issued by
2449                     EFI_IP4_PROTOCOL.Transmit() or
2450                     EFI_IP4_PROTOCOL.Receive(). If NULL, all pending
2451                     tokens are aborted. Type EFI_IP4_COMPLETION_TOKEN is
2452                     defined in EFI_IP4_PROTOCOL.Transmit().
2453 
2454   @retval EFI_SUCCESS           The asynchronous I/O request was aborted and
2455                                 Token.->Event was signaled. When Token is NULL, all
2456                                 pending requests were aborted and their events were signaled.
2457   @retval EFI_INVALID_PARAMETER This is NULL.
2458   @retval EFI_NOT_STARTED       This instance has not been started.
2459   @retval EFI_NO_MAPPING        When using the default address, configuration (DHCP, BOOTP,
2460                                 RARP, etc.) is not finished yet.
2461   @retval EFI_NOT_FOUND         When Token is not NULL, the asynchronous I/O request was
2462                                 not found in the transmit or receive queue. It has either completed
2463                                 or was not issued by Transmit() and Receive().
2464 
2465 **/
2466 EFI_STATUS
2467 EFIAPI
EfiIp4Cancel(IN EFI_IP4_PROTOCOL * This,IN EFI_IP4_COMPLETION_TOKEN * Token OPTIONAL)2468 EfiIp4Cancel (
2469   IN EFI_IP4_PROTOCOL         *This,
2470   IN EFI_IP4_COMPLETION_TOKEN *Token    OPTIONAL
2471   )
2472 {
2473   IP4_PROTOCOL              *IpInstance;
2474   EFI_STATUS                Status;
2475   EFI_TPL                   OldTpl;
2476 
2477   if (This == NULL) {
2478     return EFI_INVALID_PARAMETER;
2479   }
2480 
2481   IpInstance = IP4_INSTANCE_FROM_PROTOCOL (This);
2482 
2483   OldTpl = gBS->RaiseTPL (TPL_CALLBACK);
2484 
2485   if (IpInstance->State != IP4_STATE_CONFIGED) {
2486     Status = EFI_NOT_STARTED;
2487     goto ON_EXIT;
2488   }
2489 
2490   if (IpInstance->ConfigData.UseDefaultAddress && IP4_NO_MAPPING (IpInstance)) {
2491     Status = EFI_NO_MAPPING;
2492     goto ON_EXIT;
2493   }
2494 
2495   Status = Ip4Cancel (IpInstance, Token);
2496 
2497 ON_EXIT:
2498   gBS->RestoreTPL (OldTpl);
2499   return Status;
2500 }
2501 
2502 
2503 /**
2504   Polls for incoming data packets and processes outgoing data packets.
2505 
2506   The Poll() function polls for incoming data packets and processes outgoing data
2507   packets. Network drivers and applications can call the EFI_IP4_PROTOCOL.Poll()
2508   function to increase the rate that data packets are moved between the communications
2509   device and the transmit and receive queues.
2510 
2511   In some systems the periodic timer event may not poll the underlying communications
2512   device fast enough to transmit and/or receive all data packets without missing
2513   incoming packets or dropping outgoing packets. Drivers and applications that are
2514   experiencing packet loss should try calling the EFI_IP4_PROTOCOL.Poll() function
2515   more often.
2516 
2517   @param[in]  This               Pointer to the EFI_IP4_PROTOCOL instance.
2518 
2519   @retval  EFI_SUCCESS           Incoming or outgoing data was processed.
2520   @retval  EFI_NOT_STARTED       This EFI IPv4 Protocol instance has not been started.
2521   @retval  EFI_NO_MAPPING        When using the default address, configuration (DHCP, BOOTP,
2522                                  RARP, etc.) is not finished yet.
2523   @retval  EFI_INVALID_PARAMETER This is NULL.
2524   @retval  EFI_DEVICE_ERROR      An unexpected system or network error occurred.
2525   @retval  EFI_NOT_READY         No incoming or outgoing data is processed.
2526   @retval  EFI_TIMEOUT           Data was dropped out of the transmit and/or receive queue.
2527                                  Consider increasing the polling rate.
2528 
2529 **/
2530 EFI_STATUS
2531 EFIAPI
EfiIp4Poll(IN EFI_IP4_PROTOCOL * This)2532 EfiIp4Poll (
2533   IN EFI_IP4_PROTOCOL       *This
2534   )
2535 {
2536   IP4_PROTOCOL                  *IpInstance;
2537   EFI_MANAGED_NETWORK_PROTOCOL  *Mnp;
2538 
2539   if (This == NULL) {
2540     return EFI_INVALID_PARAMETER;
2541   }
2542 
2543   IpInstance = IP4_INSTANCE_FROM_PROTOCOL (This);
2544 
2545   if (IpInstance->State == IP4_STATE_UNCONFIGED) {
2546     return EFI_NOT_STARTED;
2547   }
2548 
2549   Mnp = IpInstance->Service->Mnp;
2550 
2551   //
2552   // Don't lock the Poll function to enable the deliver of
2553   // the packet polled up.
2554   //
2555   return Mnp->Poll (Mnp);
2556 }
2557 
2558 /**
2559   Decrease the life of the transmitted packets. If it is
2560   decreased to zero, cancel the packet. This function is
2561   called by Ip4PacketTimerTicking which time out both the
2562   received-but-not-delivered and transmitted-but-not-recycle
2563   packets.
2564 
2565   @param[in]  Map                    The IP4 child's transmit map.
2566   @param[in]  Item                   Current transmitted packet
2567   @param[in]  Context                Not used.
2568 
2569   @retval EFI_SUCCESS            Always returns EFI_SUCCESS
2570 
2571 **/
2572 EFI_STATUS
2573 EFIAPI
Ip4SentPacketTicking(IN NET_MAP * Map,IN NET_MAP_ITEM * Item,IN VOID * Context)2574 Ip4SentPacketTicking (
2575   IN NET_MAP                *Map,
2576   IN NET_MAP_ITEM           *Item,
2577   IN VOID                   *Context
2578   )
2579 {
2580   IP4_TXTOKEN_WRAP          *Wrap;
2581 
2582   Wrap = (IP4_TXTOKEN_WRAP *) Item->Value;
2583   ASSERT (Wrap != NULL);
2584 
2585   if ((Wrap->Life > 0) && (--Wrap->Life == 0)) {
2586     Ip4CancelPacket (Wrap->IpInstance->Interface, Wrap->Packet, EFI_ABORTED);
2587   }
2588 
2589   return EFI_SUCCESS;
2590 }
2591 
2592 
2593 /**
2594   The heart beat timer of IP4 service instance. It times out
2595   all of its IP4 children's received-but-not-delivered and
2596   transmitted-but-not-recycle packets, and provides time input
2597   for its IGMP protocol.
2598 
2599   @param[in]  Event                  The IP4 service instance's heart beat timer.
2600   @param[in]  Context                The IP4 service instance.
2601 
2602 **/
2603 VOID
2604 EFIAPI
Ip4TimerTicking(IN EFI_EVENT Event,IN VOID * Context)2605 Ip4TimerTicking (
2606   IN EFI_EVENT              Event,
2607   IN VOID                   *Context
2608   )
2609 {
2610   IP4_SERVICE               *IpSb;
2611 
2612   IpSb = (IP4_SERVICE *) Context;
2613   NET_CHECK_SIGNATURE (IpSb, IP4_SERVICE_SIGNATURE);
2614 
2615   Ip4PacketTimerTicking (IpSb);
2616   Ip4IgmpTicking (IpSb);
2617 }
2618