summaryrefslogtreecommitdiff
path: root/NetworkPkg/Ip4Dxe/Ip4Input.c
blob: 868f04812c8bb238ee0a6f40fc911648ab03919d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
/** @file
  IP4 input process.

Copyright (c) 2005 - 2020, Intel Corporation. All rights reserved.<BR>
(C) Copyright 2015 Hewlett-Packard Development Company, L.P.<BR>

SPDX-License-Identifier: BSD-2-Clause-Patent

**/

#include "Ip4Impl.h"


/**
  Create an empty assemble entry for the packet identified by
  (Dst, Src, Id, Protocol). The default life for the packet is
  120 seconds.

  @param[in]  Dst                    The destination address
  @param[in]  Src                    The source address
  @param[in]  Id                     The ID field in IP header
  @param[in]  Protocol               The protocol field in IP header

  @return NULL if failed to allocate memory for the entry, otherwise
          the point to just created reassemble entry.

**/
IP4_ASSEMBLE_ENTRY *
Ip4CreateAssembleEntry (
  IN IP4_ADDR               Dst,
  IN IP4_ADDR               Src,
  IN UINT16                 Id,
  IN UINT8                  Protocol
  )
{

  IP4_ASSEMBLE_ENTRY        *Assemble;

  Assemble = AllocatePool (sizeof (IP4_ASSEMBLE_ENTRY));

  if (Assemble == NULL) {
    return NULL;
  }

  InitializeListHead (&Assemble->Link);
  InitializeListHead (&Assemble->Fragments);

  Assemble->Dst      = Dst;
  Assemble->Src      = Src;
  Assemble->Id       = Id;
  Assemble->Protocol = Protocol;
  Assemble->TotalLen = 0;
  Assemble->CurLen   = 0;
  Assemble->Head     = NULL;
  Assemble->Info     = NULL;
  Assemble->Life     = IP4_FRAGMENT_LIFE;

  return Assemble;
}


/**
  Release all the fragments of a packet, then free the assemble entry.

  @param[in]  Assemble               The assemble entry to free

**/
VOID
Ip4FreeAssembleEntry (
  IN IP4_ASSEMBLE_ENTRY     *Assemble
  )
{
  LIST_ENTRY                *Entry;
  LIST_ENTRY                *Next;
  NET_BUF                   *Fragment;

  NET_LIST_FOR_EACH_SAFE (Entry, Next, &Assemble->Fragments) {
    Fragment = NET_LIST_USER_STRUCT (Entry, NET_BUF, List);

    RemoveEntryList (Entry);
    NetbufFree (Fragment);
  }

  FreePool (Assemble);
}


/**
  Initialize an already allocated assemble table. This is generally
  the assemble table embedded in the IP4 service instance.

  @param[in, out]  Table                  The assemble table to initialize.

**/
VOID
Ip4InitAssembleTable (
  IN OUT IP4_ASSEMBLE_TABLE     *Table
  )
{
  UINT32                    Index;

  for (Index = 0; Index < IP4_ASSEMLE_HASH_SIZE; Index++) {
    InitializeListHead (&Table->Bucket[Index]);
  }
}


/**
  Clean up the assemble table: remove all the fragments
  and assemble entries.

  @param[in]  Table                  The assemble table to clean up

**/
VOID
Ip4CleanAssembleTable (
  IN IP4_ASSEMBLE_TABLE     *Table
  )
{
  LIST_ENTRY                *Entry;
  LIST_ENTRY                *Next;
  IP4_ASSEMBLE_ENTRY        *Assemble;
  UINT32                    Index;

  for (Index = 0; Index < IP4_ASSEMLE_HASH_SIZE; Index++) {
    NET_LIST_FOR_EACH_SAFE (Entry, Next, &Table->Bucket[Index]) {
      Assemble = NET_LIST_USER_STRUCT (Entry, IP4_ASSEMBLE_ENTRY, Link);

      RemoveEntryList (Entry);
      Ip4FreeAssembleEntry (Assemble);
    }
  }
}


/**
  Trim the packet to fit in [Start, End), and update the per
  packet information.

  @param  Packet                 Packet to trim
  @param  Start                  The sequence of the first byte to fit in
  @param  End                    One beyond the sequence of last byte to fit in.

**/
VOID
Ip4TrimPacket (
  IN OUT NET_BUF                *Packet,
  IN     INTN                   Start,
  IN     INTN                   End
  )
{
  IP4_CLIP_INFO             *Info;
  INTN                      Len;

  Info = IP4_GET_CLIP_INFO (Packet);

  ASSERT (Info->Start + Info->Length == Info->End);
  ASSERT ((Info->Start < End) && (Start < Info->End));

   if (Info->Start < Start) {
    Len = Start - Info->Start;

    NetbufTrim (Packet, (UINT32) Len, NET_BUF_HEAD);
    Info->Start   = Start;
    Info->Length -= Len;
  }

  if (End < Info->End) {
    Len = End - Info->End;

    NetbufTrim (Packet, (UINT32) Len, NET_BUF_TAIL);
    Info->End     = End;
    Info->Length -= Len;
  }
}


/**
  Release all the fragments of the packet. This is the callback for
  the assembled packet's OnFree. It will free the assemble entry,
  which in turn will free all the fragments of the packet.

  @param[in]  Arg                    The assemble entry to free

**/
VOID
EFIAPI
Ip4OnFreeFragments (
  IN VOID                   *Arg
  )
{
  Ip4FreeAssembleEntry ((IP4_ASSEMBLE_ENTRY *) Arg);
}


/**
  Reassemble the IP fragments. If all the fragments of the packet
  have been received, it will wrap the packet in a net buffer then
  return it to caller. If the packet can't be assembled, NULL is
  return.

  @param  Table     The assemble table used. New assemble entry will be created
                    if the Packet is from a new chain of fragments.
  @param  Packet    The fragment to assemble. It might be freed if the fragment
                    can't be re-assembled.

  @return NULL if the packet can't be reassemble. The point to just assembled
          packet if all the fragments of the packet have arrived.

**/
NET_BUF *
Ip4Reassemble (
  IN OUT IP4_ASSEMBLE_TABLE     *Table,
  IN OUT NET_BUF                *Packet
  )
{
  IP4_HEAD                  *IpHead;
  IP4_CLIP_INFO             *This;
  IP4_CLIP_INFO             *Node;
  IP4_ASSEMBLE_ENTRY        *Assemble;
  LIST_ENTRY                *Head;
  LIST_ENTRY                *Prev;
  LIST_ENTRY                *Cur;
  NET_BUF                   *Fragment;
  NET_BUF                   *NewPacket;
  INTN                      Index;

  IpHead  = Packet->Ip.Ip4;
  This    = IP4_GET_CLIP_INFO (Packet);

  ASSERT (IpHead != NULL);

  //
  // First: find the related assemble entry
  //
  Assemble  = NULL;
  Index     = IP4_ASSEMBLE_HASH (IpHead->Dst, IpHead->Src, IpHead->Id, IpHead->Protocol);

  NET_LIST_FOR_EACH (Cur, &Table->Bucket[Index]) {
    Assemble = NET_LIST_USER_STRUCT (Cur, IP4_ASSEMBLE_ENTRY, Link);

    if ((Assemble->Dst == IpHead->Dst) && (Assemble->Src == IpHead->Src) &&
        (Assemble->Id == IpHead->Id)   && (Assemble->Protocol == IpHead->Protocol)) {
      break;
    }
  }

  //
  // Create a new assemble entry if no assemble entry is related to this packet
  //
  if (Cur == &Table->Bucket[Index]) {
    Assemble = Ip4CreateAssembleEntry (
                 IpHead->Dst,
                 IpHead->Src,
                 IpHead->Id,
                 IpHead->Protocol
                 );

    if (Assemble == NULL) {
      goto DROP;
    }

    InsertHeadList (&Table->Bucket[Index], &Assemble->Link);
  }
  //
  // Assemble shouldn't be NULL here
  //
  ASSERT (Assemble != NULL);

  //
  // Find the point to insert the packet: before the first
  // fragment with THIS.Start < CUR.Start. the previous one
  // has PREV.Start <= THIS.Start < CUR.Start.
  //
  Head = &Assemble->Fragments;

  NET_LIST_FOR_EACH (Cur, Head) {
    Fragment = NET_LIST_USER_STRUCT (Cur, NET_BUF, List);

    if (This->Start < IP4_GET_CLIP_INFO (Fragment)->Start) {
      break;
    }
  }

  //
  // Check whether the current fragment overlaps with the previous one.
  // It holds that: PREV.Start <= THIS.Start < THIS.End. Only need to
  // check whether THIS.Start < PREV.End for overlap. If two fragments
  // overlaps, trim the overlapped part off THIS fragment.
  //
  if ((Prev = Cur->BackLink) != Head) {
    Fragment  = NET_LIST_USER_STRUCT (Prev, NET_BUF, List);
    Node      = IP4_GET_CLIP_INFO (Fragment);

    if (This->Start < Node->End) {
      if (This->End <= Node->End) {
        NetbufFree (Packet);
        return NULL;
      }

      Ip4TrimPacket (Packet, Node->End, This->End);
    }
  }

  //
  // Insert the fragment into the packet. The fragment may be removed
  // from the list by the following checks.
  //
  NetListInsertBefore (Cur, &Packet->List);

  //
  // Check the packets after the insert point. It holds that:
  // THIS.Start <= NODE.Start < NODE.End. The equality holds
  // if PREV and NEXT are continuous. THIS fragment may fill
  // several holes. Remove the completely overlapped fragments
  //
  while (Cur != Head) {
    Fragment = NET_LIST_USER_STRUCT (Cur, NET_BUF, List);
    Node     = IP4_GET_CLIP_INFO (Fragment);

    //
    // Remove fragments completely overlapped by this fragment
    //
    if (Node->End <= This->End) {
      Cur = Cur->ForwardLink;

      RemoveEntryList (&Fragment->List);
      Assemble->CurLen -= Node->Length;

      NetbufFree (Fragment);
      continue;
    }

    //
    // The conditions are: THIS.Start <= NODE.Start, and THIS.End <
    // NODE.End. Two fragments overlaps if NODE.Start < THIS.End.
    // If two fragments start at the same offset, remove THIS fragment
    // because ((THIS.Start == NODE.Start) && (THIS.End < NODE.End)).
    //
    if (Node->Start < This->End) {
      if (This->Start == Node->Start) {
        RemoveEntryList (&Packet->List);
        goto DROP;
      }

      Ip4TrimPacket (Packet, This->Start, Node->Start);
    }

    break;
  }

  //
  // Update the assemble info: increase the current length. If it is
  // the frist fragment, update the packet's IP head and per packet
  // info. If it is the last fragment, update the total length.
  //
  Assemble->CurLen += This->Length;

  if (This->Start == 0) {
    //
    // Once the first fragment is enqueued, it can't be removed
    // from the fragment list. So, Assemble->Head always point
    // to valid memory area.
    //
    ASSERT (Assemble->Head == NULL);

    Assemble->Head  = IpHead;
    Assemble->Info  = IP4_GET_CLIP_INFO (Packet);
  }

  //
  // Don't update the length more than once.
  //
  if (IP4_LAST_FRAGMENT (IpHead->Fragment) && (Assemble->TotalLen == 0)) {
    Assemble->TotalLen = This->End;
  }

  //
  // Deliver the whole packet if all the fragments received.
  // All fragments received if:
  //  1. received the last one, so, the total length is know
  //  2. received all the data. If the last fragment on the
  //     queue ends at the total length, all data is received.
  //
  if ((Assemble->TotalLen != 0) && (Assemble->CurLen >= Assemble->TotalLen)) {

    RemoveEntryList (&Assemble->Link);

    //
    // If the packet is properly formatted, the last fragment's End
    // equals to the packet's total length. Otherwise, the packet
    // is a fake, drop it now.
    //
    Fragment = NET_LIST_USER_STRUCT (Head->BackLink, NET_BUF, List);

    if (IP4_GET_CLIP_INFO (Fragment)->End != Assemble->TotalLen) {
      Ip4FreeAssembleEntry (Assemble);
      return NULL;
    }

    //
    // Wrap the packet in a net buffer then deliver it up
    //
    NewPacket = NetbufFromBufList (
                  &Assemble->Fragments,
                  0,
                  0,
                  Ip4OnFreeFragments,
                  Assemble
                  );

    if (NewPacket == NULL) {
      Ip4FreeAssembleEntry (Assemble);
      return NULL;
    }

    NewPacket->Ip.Ip4 = Assemble->Head;

    ASSERT (Assemble->Info != NULL);

    CopyMem (
      IP4_GET_CLIP_INFO (NewPacket),
      Assemble->Info,
      sizeof (*IP4_GET_CLIP_INFO (NewPacket))
      );

    return NewPacket;
  }

  return NULL;

DROP:
  NetbufFree (Packet);
  return NULL;
}

/**
  The callback function for the net buffer which wraps the packet processed by
  IPsec. It releases the wrap packet and also signals IPsec to free the resources.

  @param[in]  Arg       The wrap context

**/
VOID
EFIAPI
Ip4IpSecFree (
  IN VOID                   *Arg
  )
{
  IP4_IPSEC_WRAP            *Wrap;

  Wrap = (IP4_IPSEC_WRAP *) Arg;

  if (Wrap->IpSecRecycleSignal != NULL) {
    gBS->SignalEvent (Wrap->IpSecRecycleSignal);
  }

  NetbufFree (Wrap->Packet);

  FreePool (Wrap);

  return;
}

/**
  The work function to locate IPsec protocol to process the inbound or
  outbound IP packets. The process routine handls the packet with following
  actions: bypass the packet, discard the packet, or protect the packet.

  @param[in]       IpSb          The IP4 service instance.
  @param[in, out]  Head          The caller supplied IP4 header.
  @param[in, out]  Netbuf        The IP4 packet to be processed by IPsec.
  @param[in, out]  Options       The caller supplied options.
  @param[in, out]  OptionsLen    The length of the option.
  @param[in]       Direction     The directionality in an SPD entry,
                                 EfiIPsecInBound or EfiIPsecOutBound.
  @param[in]       Context       The token's wrap.

  @retval EFI_SUCCESS            The IPsec protocol is not available or disabled.
  @retval EFI_SUCCESS            The packet was bypassed and all buffers remain the same.
  @retval EFI_SUCCESS            The packet was protected.
  @retval EFI_ACCESS_DENIED      The packet was discarded.
  @retval EFI_OUT_OF_RESOURCES   There is no sufficient resource to complete the operation.
  @retval EFI_BUFFER_TOO_SMALL   The number of non-empty block is bigger than the
                                 number of input data blocks when build a fragment table.

**/
EFI_STATUS
Ip4IpSecProcessPacket (
  IN     IP4_SERVICE            *IpSb,
  IN OUT IP4_HEAD               **Head,
  IN OUT NET_BUF                **Netbuf,
  IN OUT UINT8                  **Options,
  IN OUT UINT32                 *OptionsLen,
  IN     EFI_IPSEC_TRAFFIC_DIR  Direction,
  IN     VOID                   *Context
  )
{
  NET_FRAGMENT              *FragmentTable;
  NET_FRAGMENT              *OriginalFragmentTable;
  UINT32                    FragmentCount;
  UINT32                    OriginalFragmentCount;
  EFI_EVENT                 RecycleEvent;
  NET_BUF                   *Packet;
  IP4_TXTOKEN_WRAP          *TxWrap;
  IP4_IPSEC_WRAP            *IpSecWrap;
  EFI_STATUS                Status;
  IP4_HEAD                  ZeroHead;

  Status        = EFI_SUCCESS;

  if (!mIpSec2Installed) {
    goto ON_EXIT;
  }
  ASSERT (mIpSec != NULL);

  Packet        = *Netbuf;
  RecycleEvent  = NULL;
  IpSecWrap     = NULL;
  FragmentTable = NULL;
  TxWrap        = (IP4_TXTOKEN_WRAP *) Context;
  FragmentCount = Packet->BlockOpNum;

  ZeroMem (&ZeroHead, sizeof (IP4_HEAD));

  //
  // Check whether the IPsec enable variable is set.
  //
  if (mIpSec->DisabledFlag) {
    //
    // If IPsec is disabled, restore the original MTU
    //
    IpSb->MaxPacketSize = IpSb->OldMaxPacketSize;
    goto ON_EXIT;
  } else {
    //
    // If IPsec is enabled, use the MTU which reduce the IPsec header length.
    //
    IpSb->MaxPacketSize = IpSb->OldMaxPacketSize - IP4_MAX_IPSEC_HEADLEN;
  }

  //
  // Rebuild fragment table from netbuf to ease IPsec process.
  //
  FragmentTable = AllocateZeroPool (FragmentCount * sizeof (NET_FRAGMENT));

  if (FragmentTable == NULL) {
    Status = EFI_OUT_OF_RESOURCES;
    goto ON_EXIT;
  }

  Status = NetbufBuildExt (Packet, FragmentTable, &FragmentCount);

  //
  // Record the original FragmentTable and count.
  //
  OriginalFragmentTable = FragmentTable;
  OriginalFragmentCount = FragmentCount;

  if (EFI_ERROR (Status)) {
    FreePool (FragmentTable);
    goto ON_EXIT;
  }

  //
  // Convert host byte order to network byte order
  //
  Ip4NtohHead (*Head);

  Status = mIpSec->ProcessExt (
                     mIpSec,
                     IpSb->Controller,
                     IP_VERSION_4,
                     (VOID *) (*Head),
                     &(*Head)->Protocol,
                     (VOID **) Options,
                     OptionsLen,
                     (EFI_IPSEC_FRAGMENT_DATA **) (&FragmentTable),
                     &FragmentCount,
                     Direction,
                     &RecycleEvent
                     );
  //
  // Convert back to host byte order
  //
  Ip4NtohHead (*Head);

  if (EFI_ERROR (Status)) {
    FreePool (OriginalFragmentTable);
    goto ON_EXIT;
  }

  if (OriginalFragmentTable == FragmentTable && OriginalFragmentCount == FragmentCount) {
    //
    // For ByPass Packet
    //
    FreePool (FragmentTable);
    goto ON_EXIT;
  } else {
    //
    // Free the FragmentTable which allocated before calling the IPsec.
    //
    FreePool (OriginalFragmentTable);
  }

  if (Direction == EfiIPsecOutBound && TxWrap != NULL) {

    TxWrap->IpSecRecycleSignal = RecycleEvent;
    TxWrap->Packet             = NetbufFromExt (
                                   FragmentTable,
                                   FragmentCount,
                                   IP4_MAX_HEADLEN,
                                   0,
                                   Ip4FreeTxToken,
                                   TxWrap
                                   );
    if (TxWrap->Packet == NULL) {
      //
      // Recover the TxWrap->Packet, if meet a error, and the caller will free
      // the TxWrap.
      //
      TxWrap->Packet = *Netbuf;
      Status = EFI_OUT_OF_RESOURCES;
      goto ON_EXIT;
    }

    //
    // Free original Netbuf.
    //
    NetIpSecNetbufFree (*Netbuf);
    *Netbuf = TxWrap->Packet;

  } else {

    IpSecWrap = AllocateZeroPool (sizeof (IP4_IPSEC_WRAP));

    if (IpSecWrap == NULL) {
      Status = EFI_OUT_OF_RESOURCES;
      gBS->SignalEvent (RecycleEvent);
      goto ON_EXIT;
    }

    IpSecWrap->IpSecRecycleSignal = RecycleEvent;
    IpSecWrap->Packet             = Packet;
    Packet                        = NetbufFromExt (
                                      FragmentTable,
                                      FragmentCount,
                                      IP4_MAX_HEADLEN,
                                      0,
                                      Ip4IpSecFree,
                                      IpSecWrap
                                      );

    if (Packet == NULL) {
      Packet = IpSecWrap->Packet;
      gBS->SignalEvent (RecycleEvent);
      FreePool (IpSecWrap);
      Status = EFI_OUT_OF_RESOURCES;
      goto ON_EXIT;
    }

    if (Direction == EfiIPsecInBound && 0 != CompareMem (*Head, &ZeroHead, sizeof (IP4_HEAD))) {
      Ip4PrependHead (Packet, *Head, *Options, *OptionsLen);
      Ip4NtohHead (Packet->Ip.Ip4);
      NetbufTrim (Packet, ((*Head)->HeadLen << 2), TRUE);

      CopyMem (
        IP4_GET_CLIP_INFO (Packet),
        IP4_GET_CLIP_INFO (IpSecWrap->Packet),
        sizeof (IP4_CLIP_INFO)
        );
    }
    *Netbuf = Packet;
  }

ON_EXIT:
  return Status;
}

/**
  Pre-process the IPv4 packet. First validates the IPv4 packet, and
  then reassembles packet if it is necessary.

  @param[in]       IpSb            Pointer to IP4_SERVICE.
  @param[in, out]  Packet          Pointer to the Packet to be processed.
  @param[in]       Head            Pointer to the IP4_HEAD.
  @param[in]       Option          Pointer to a buffer which contains the IPv4 option.
  @param[in]       OptionLen       The length of Option in bytes.
  @param[in]       Flag            The link layer flag for the packet received, such
                                   as multicast.

  @retval     EFI_SUCCESS                The received packet is in well form.
  @retval     EFI_INVALID_PARAMETER      The received packet is malformed.

**/
EFI_STATUS
Ip4PreProcessPacket (
  IN     IP4_SERVICE    *IpSb,
  IN OUT NET_BUF        **Packet,
  IN     IP4_HEAD       *Head,
  IN     UINT8          *Option,
  IN     UINT32         OptionLen,
  IN     UINT32         Flag
  )
{
  IP4_CLIP_INFO             *Info;
  UINT32                    HeadLen;
  UINT32                    TotalLen;
  UINT16                    Checksum;

  //
  // Check if the IP4 header is correctly formatted.
  //
  HeadLen  = (Head->HeadLen << 2);
  TotalLen = NTOHS (Head->TotalLen);

  //
  // Mnp may deliver frame trailer sequence up, trim it off.
  //
  if (TotalLen < (*Packet)->TotalSize) {
    NetbufTrim (*Packet, (*Packet)->TotalSize - TotalLen, FALSE);
  }

  if ((Head->Ver != 4) || (HeadLen < IP4_MIN_HEADLEN) ||
      (TotalLen < HeadLen) || (TotalLen != (*Packet)->TotalSize)) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Some OS may send IP packets without checksum.
  //
  Checksum = (UINT16) (~NetblockChecksum ((UINT8 *) Head, HeadLen));

  if ((Head->Checksum != 0) && (Checksum != 0)) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Convert the IP header to host byte order, then get the per packet info.
  //
  (*Packet)->Ip.Ip4  = Ip4NtohHead (Head);

  Info            = IP4_GET_CLIP_INFO (*Packet);
  Info->LinkFlag  = Flag;
  Info->CastType  = Ip4GetHostCast (IpSb, Head->Dst, Head->Src);
  Info->Start     = (Head->Fragment & IP4_HEAD_OFFSET_MASK) << 3;
  Info->Length    = Head->TotalLen - HeadLen;
  Info->End       = Info->Start + Info->Length;
  Info->Status    = EFI_SUCCESS;

  //
  // The packet is destinated to us if the CastType is non-zero.
  //
  if ((Info->CastType == 0) || (Info->End > IP4_MAX_PACKET_SIZE)) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Validate the options. Don't call the Ip4OptionIsValid if
  // there is no option to save some CPU process.
  //

  if ((OptionLen > 0) && !Ip4OptionIsValid (Option, OptionLen, TRUE)) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Trim the head off, after this point, the packet is headless,
  // and Packet->TotalLen == Info->Length.
  //
  NetbufTrim (*Packet, HeadLen, TRUE);

  //
  // Reassemble the packet if this is a fragment. The packet is a
  // fragment if its head has MF (more fragment) set, or it starts
  // at non-zero byte.
  //
  if (((Head->Fragment & IP4_HEAD_MF_MASK) != 0) || (Info->Start != 0)) {
    //
    // Drop the fragment if DF is set but it is fragmented. Gateway
    // need to send a type 4 destination unreache ICMP message here.
    //
    if ((Head->Fragment & IP4_HEAD_DF_MASK) != 0) {
      return EFI_INVALID_PARAMETER;
    }

    //
    // The length of all but the last fragments is in the unit of 8 bytes.
    //
    if (((Head->Fragment & IP4_HEAD_MF_MASK) != 0) && (Info->Length % 8 != 0)) {
      return EFI_INVALID_PARAMETER;
    }

    *Packet = Ip4Reassemble (&IpSb->Assemble, *Packet);

    //
    // Packet assembly isn't complete, start receive more packet.
    //
    if (*Packet == NULL) {
      return EFI_INVALID_PARAMETER;
    }
  }

  return EFI_SUCCESS;
}

/**
  This function checks the IPv4 packet length.

  @param[in]       Packet          Pointer to the IPv4 Packet to be checked.

  @retval TRUE                   The input IPv4 packet length is valid.
  @retval FALSE                  The input IPv4 packet length is invalid.

**/
BOOLEAN
Ip4IsValidPacketLength (
  IN NET_BUF        *Packet
  )
{
  //
  // Check the IP4 packet length.
  //
  if (Packet->TotalSize < IP4_MIN_HEADLEN) {
    return FALSE;
  }

  return TRUE;
}

/**
  The IP4 input routine. It is called by the IP4_INTERFACE when a
  IP4 fragment is received from MNP.

  @param[in]  Ip4Instance        The IP4 child that request the receive, most like
                                 it is NULL.
  @param[in]  Packet             The IP4 packet received.
  @param[in]  IoStatus           The return status of receive request.
  @param[in]  Flag               The link layer flag for the packet received, such
                                 as multicast.
  @param[in]  Context            The IP4 service instance that own the MNP.

**/
VOID
Ip4AccpetFrame (
  IN IP4_PROTOCOL           *Ip4Instance,
  IN NET_BUF                *Packet,
  IN EFI_STATUS             IoStatus,
  IN UINT32                 Flag,
  IN VOID                   *Context
  )
{
  IP4_SERVICE               *IpSb;
  IP4_HEAD                  *Head;
  EFI_STATUS                Status;
  IP4_HEAD                  ZeroHead;
  UINT8                     *Option;
  UINT32                    OptionLen;

  IpSb   = (IP4_SERVICE *) Context;
  Option = NULL;

  if (EFI_ERROR (IoStatus) || (IpSb->State == IP4_SERVICE_DESTROY)) {
    goto DROP;
  }

  if (!Ip4IsValidPacketLength (Packet)) {
    goto RESTART;
  }

  Head      = (IP4_HEAD *) NetbufGetByte (Packet, 0, NULL);
  ASSERT (Head != NULL);
  OptionLen = (Head->HeadLen << 2) - IP4_MIN_HEADLEN;
  if (OptionLen > 0) {
    Option = (UINT8 *) (Head + 1);
  }

  //
  // Validate packet format and reassemble packet if it is necessary.
  //
  Status = Ip4PreProcessPacket (
             IpSb,
             &Packet,
             Head,
             Option,
             OptionLen,
             Flag
             );

  if (EFI_ERROR (Status)) {
    goto RESTART;
  }

  //
  // After trim off, the packet is a esp/ah/udp/tcp/icmp6 net buffer,
  // and no need consider any other ahead ext headers.
  //
  Status = Ip4IpSecProcessPacket (
             IpSb,
             &Head,
             &Packet,
             &Option,
             &OptionLen,
             EfiIPsecInBound,
             NULL
             );

  if (EFI_ERROR (Status)) {
    goto RESTART;
  }

  //
  // If the packet is protected by tunnel mode, parse the inner Ip Packet.
  //
  ZeroMem (&ZeroHead, sizeof (IP4_HEAD));
  if (0 == CompareMem (Head, &ZeroHead, sizeof (IP4_HEAD))) {
    // Packet may have been changed. Head, HeadLen, TotalLen, and
    // info must be reloaded before use. The ownership of the packet
    // is transferred to the packet process logic.
    //
    if (!Ip4IsValidPacketLength (Packet)) {
      goto RESTART;
    }

    Head = (IP4_HEAD *) NetbufGetByte (Packet, 0, NULL);
    ASSERT (Head != NULL);
    Status = Ip4PreProcessPacket (
               IpSb,
               &Packet,
               Head,
               Option,
               OptionLen,
               Flag
               );
    if (EFI_ERROR (Status)) {
      goto RESTART;
    }
  }

  ASSERT (Packet != NULL);
  Head  = Packet->Ip.Ip4;
  IP4_GET_CLIP_INFO (Packet)->Status = EFI_SUCCESS;

  switch (Head->Protocol) {
  case EFI_IP_PROTO_ICMP:
    Ip4IcmpHandle (IpSb, Head, Packet);
    break;

  case IP4_PROTO_IGMP:
    Ip4IgmpHandle (IpSb, Head, Packet);
    break;

  default:
    Ip4Demultiplex (IpSb, Head, Packet, Option, OptionLen);
  }

  Packet = NULL;

  //
  // Dispatch the DPCs queued by the NotifyFunction of the rx token's events
  // which are signaled with received data.
  //
  DispatchDpc ();

RESTART:
  Ip4ReceiveFrame (IpSb->DefaultInterface, NULL, Ip4AccpetFrame, IpSb);

DROP:
  if (Packet != NULL) {
    NetbufFree (Packet);
  }

  return ;
}


/**
  Check whether this IP child accepts the packet.

  @param[in]  IpInstance             The IP child to check
  @param[in]  Head                   The IP header of the packet
  @param[in]  Packet                 The data of the packet

  @retval TRUE   If the child wants to receive the packet.
  @retval FALSE  Otherwise.

**/
BOOLEAN
Ip4InstanceFrameAcceptable (
  IN IP4_PROTOCOL           *IpInstance,
  IN IP4_HEAD               *Head,
  IN NET_BUF                *Packet
  )
{
  IP4_ICMP_ERROR_HEAD       Icmp;
  EFI_IP4_CONFIG_DATA       *Config;
  IP4_CLIP_INFO             *Info;
  UINT16                    Proto;
  UINT32                    Index;

  Config = &IpInstance->ConfigData;

  //
  // Dirty trick for the Tiano UEFI network stack implementation. If
  // ReceiveTimeout == -1, the receive of the packet for this instance
  // is disabled. The UEFI spec don't have such capability. We add
  // this to improve the performance because IP will make a copy of
  // the received packet for each accepting instance. Some IP instances
  // used by UDP/TCP only send packets, they don't wants to receive.
  //
  if (Config->ReceiveTimeout == (UINT32)(-1)) {
    return FALSE;
  }

  if (Config->AcceptPromiscuous) {
    return TRUE;
  }

  //
  // Use protocol from the IP header embedded in the ICMP error
  // message to filter, instead of ICMP itself. ICMP handle will
  // call Ip4Demultiplex to deliver ICMP errors.
  //
  Proto = Head->Protocol;

  if ((Proto == EFI_IP_PROTO_ICMP) && (!Config->AcceptAnyProtocol) && (Proto != Config->DefaultProtocol)) {
    NetbufCopy (Packet, 0, sizeof (Icmp.Head), (UINT8 *) &Icmp.Head);

    if (mIcmpClass[Icmp.Head.Type].IcmpClass == ICMP_ERROR_MESSAGE) {
      if (!Config->AcceptIcmpErrors) {
        return FALSE;
      }

      NetbufCopy (Packet, 0, sizeof (Icmp), (UINT8 *) &Icmp);
      Proto = Icmp.IpHead.Protocol;
    }
  }

  //
  // Match the protocol
  //
  if (!Config->AcceptAnyProtocol && (Proto != Config->DefaultProtocol)) {
    return FALSE;
  }

  //
  // Check for broadcast, the caller has computed the packet's
  // cast type for this child's interface.
  //
  Info = IP4_GET_CLIP_INFO (Packet);

  if (IP4_IS_BROADCAST (Info->CastType)) {
    return Config->AcceptBroadcast;
  }

  //
  // If it is a multicast packet, check whether we are in the group.
  //
  if (Info->CastType == IP4_MULTICAST) {
    //
    // Receive the multicast if the instance wants to receive all packets.
    //
    if (!IpInstance->ConfigData.UseDefaultAddress && (IpInstance->Interface->Ip == 0)) {
      return TRUE;
    }

    for (Index = 0; Index < IpInstance->GroupCount; Index++) {
      if (IpInstance->Groups[Index] == HTONL (Head->Dst)) {
        break;
      }
    }

    return (BOOLEAN)(Index < IpInstance->GroupCount);
  }

  return TRUE;
}


/**
  Enqueue a shared copy of the packet to the IP4 child if the
  packet is acceptable to it. Here the data of the packet is
  shared, but the net buffer isn't.

  @param[in]  IpInstance             The IP4 child to enqueue the packet to
  @param[in]  Head                   The IP header of the received packet
  @param[in]  Packet                 The data of the received packet

  @retval EFI_NOT_STARTED        The IP child hasn't been configured.
  @retval EFI_INVALID_PARAMETER  The child doesn't want to receive the packet
  @retval EFI_OUT_OF_RESOURCES   Failed to allocate some resource
  @retval EFI_SUCCESS            A shared copy the packet is enqueued to the child.

**/
EFI_STATUS
Ip4InstanceEnquePacket (
  IN IP4_PROTOCOL           *IpInstance,
  IN IP4_HEAD               *Head,
  IN NET_BUF                *Packet
  )
{
  IP4_CLIP_INFO             *Info;
  NET_BUF                   *Clone;

  //
  // Check whether the packet is acceptable to this instance.
  //
  if (IpInstance->State != IP4_STATE_CONFIGED) {
    return EFI_NOT_STARTED;
  }

  if (!Ip4InstanceFrameAcceptable (IpInstance, Head, Packet)) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Enqueue a shared copy of the packet.
  //
  Clone = NetbufClone (Packet);

  if (Clone == NULL) {
    return EFI_OUT_OF_RESOURCES;
  }

  //
  // Set the receive time out for the assembled packet. If it expires,
  // packet will be removed from the queue.
  //
  Info        = IP4_GET_CLIP_INFO (Clone);
  Info->Life  = IP4_US_TO_SEC (IpInstance->ConfigData.ReceiveTimeout);

  InsertTailList (&IpInstance->Received, &Clone->List);
  return EFI_SUCCESS;
}


/**
  The signal handle of IP4's recycle event. It is called back
  when the upper layer release the packet.

  @param  Event              The IP4's recycle event.
  @param  Context            The context of the handle, which is a
                             IP4_RXDATA_WRAP

**/
VOID
EFIAPI
Ip4OnRecyclePacket (
  IN EFI_EVENT              Event,
  IN VOID                   *Context
  )
{
  IP4_RXDATA_WRAP           *Wrap;

  Wrap = (IP4_RXDATA_WRAP *) Context;

  EfiAcquireLockOrFail (&Wrap->IpInstance->RecycleLock);
  RemoveEntryList (&Wrap->Link);
  EfiReleaseLock (&Wrap->IpInstance->RecycleLock);

  ASSERT (!NET_BUF_SHARED (Wrap->Packet));
  NetbufFree (Wrap->Packet);

  gBS->CloseEvent (Wrap->RxData.RecycleSignal);
  FreePool (Wrap);
}


/**
  Wrap the received packet to a IP4_RXDATA_WRAP, which will be
  delivered to the upper layer. Each IP4 child that accepts the
  packet will get a not-shared copy of the packet which is wrapped
  in the IP4_RXDATA_WRAP. The IP4_RXDATA_WRAP->RxData is passed
  to the upper layer. Upper layer will signal the recycle event in
  it when it is done with the packet.

  @param[in]  IpInstance    The IP4 child to receive the packet.
  @param[in]  Packet        The packet to deliver up.

  @retval Wrap              if warp the packet succeed.
  @retval NULL              failed to wrap the packet .

**/
IP4_RXDATA_WRAP *
Ip4WrapRxData (
  IN IP4_PROTOCOL           *IpInstance,
  IN NET_BUF                *Packet
  )
{
  IP4_RXDATA_WRAP           *Wrap;
  EFI_IP4_RECEIVE_DATA      *RxData;
  EFI_STATUS                Status;
  BOOLEAN                   RawData;

  Wrap = AllocatePool (IP4_RXDATA_WRAP_SIZE (Packet->BlockOpNum));

  if (Wrap == NULL) {
    return NULL;
  }

  InitializeListHead (&Wrap->Link);

  Wrap->IpInstance  = IpInstance;
  Wrap->Packet      = Packet;
  RxData            = &Wrap->RxData;

  ZeroMem (RxData, sizeof (EFI_IP4_RECEIVE_DATA));

  Status = gBS->CreateEvent (
                  EVT_NOTIFY_SIGNAL,
                  TPL_NOTIFY,
                  Ip4OnRecyclePacket,
                  Wrap,
                  &RxData->RecycleSignal
                  );

  if (EFI_ERROR (Status)) {
    FreePool (Wrap);
    return NULL;
  }

  ASSERT (Packet->Ip.Ip4 != NULL);

  ASSERT (IpInstance != NULL);
  RawData = IpInstance->ConfigData.RawData;

  //
  // The application expects a network byte order header.
  //
  if (!RawData) {
    RxData->HeaderLength  = (Packet->Ip.Ip4->HeadLen << 2);
    RxData->Header        = (EFI_IP4_HEADER *) Ip4NtohHead (Packet->Ip.Ip4);
    RxData->OptionsLength = RxData->HeaderLength - IP4_MIN_HEADLEN;
    RxData->Options       = NULL;

    if (RxData->OptionsLength != 0) {
      RxData->Options = (VOID *) (RxData->Header + 1);
    }
  }

  RxData->DataLength  = Packet->TotalSize;

  //
  // Build the fragment table to be delivered up.
  //
  RxData->FragmentCount = Packet->BlockOpNum;
  NetbufBuildExt (Packet, (NET_FRAGMENT *) RxData->FragmentTable, &RxData->FragmentCount);

  return Wrap;
}


/**
  Deliver the received packets to upper layer if there are both received
  requests and enqueued packets. If the enqueued packet is shared, it will
  duplicate it to a non-shared packet, release the shared packet, then
  deliver the non-shared packet up.

  @param[in]  IpInstance         The IP child to deliver the packet up.

  @retval EFI_OUT_OF_RESOURCES   Failed to allocate resources to deliver the
                                 packets.
  @retval EFI_SUCCESS            All the enqueued packets that can be delivered
                                 are delivered up.

**/
EFI_STATUS
Ip4InstanceDeliverPacket (
  IN IP4_PROTOCOL           *IpInstance
  )
{
  EFI_IP4_COMPLETION_TOKEN  *Token;
  IP4_RXDATA_WRAP           *Wrap;
  NET_BUF                   *Packet;
  NET_BUF                   *Dup;
  UINT8                     *Head;
  UINT32                    HeadLen;

  //
  // Deliver a packet if there are both a packet and a receive token.
  //
  while (!IsListEmpty (&IpInstance->Received) &&
         !NetMapIsEmpty (&IpInstance->RxTokens)) {

    Packet = NET_LIST_HEAD (&IpInstance->Received, NET_BUF, List);

    if (!NET_BUF_SHARED (Packet)) {
      //
      // If this is the only instance that wants the packet, wrap it up.
      //
      Wrap = Ip4WrapRxData (IpInstance, Packet);

      if (Wrap == NULL) {
        return EFI_OUT_OF_RESOURCES;
      }

      RemoveEntryList (&Packet->List);

    } else {
      //
      // Create a duplicated packet if this packet is shared
      //
      if (IpInstance->ConfigData.RawData) {
        HeadLen = 0;
      } else {
        HeadLen = IP4_MAX_HEADLEN;
      }

      Dup = NetbufDuplicate (Packet, NULL, HeadLen);

      if (Dup == NULL) {
        return EFI_OUT_OF_RESOURCES;
      }

      if (!IpInstance->ConfigData.RawData) {
        //
        // Copy the IP head over. The packet to deliver up is
        // headless. Trim the head off after copy. The IP head
        // may be not continuous before the data.
        //
        Head = NetbufAllocSpace (Dup, IP4_MAX_HEADLEN, NET_BUF_HEAD);
        ASSERT (Head != NULL);

        Dup->Ip.Ip4 = (IP4_HEAD *) Head;

        CopyMem (Head, Packet->Ip.Ip4, Packet->Ip.Ip4->HeadLen << 2);
        NetbufTrim (Dup, IP4_MAX_HEADLEN, TRUE);
      }

      Wrap = Ip4WrapRxData (IpInstance, Dup);

      if (Wrap == NULL) {
        NetbufFree (Dup);
        return EFI_OUT_OF_RESOURCES;
      }

      RemoveEntryList (&Packet->List);
      NetbufFree (Packet);

      Packet = Dup;
    }

    //
    // Insert it into the delivered packet, then get a user's
    // receive token, pass the wrapped packet up.
    //
    EfiAcquireLockOrFail (&IpInstance->RecycleLock);
    InsertHeadList (&IpInstance->Delivered, &Wrap->Link);
    EfiReleaseLock (&IpInstance->RecycleLock);

    Token                = NetMapRemoveHead (&IpInstance->RxTokens, NULL);
    Token->Status        = IP4_GET_CLIP_INFO (Packet)->Status;
    Token->Packet.RxData = &Wrap->RxData;

    gBS->SignalEvent (Token->Event);
  }

  return EFI_SUCCESS;
}


/**
  Enqueue a received packet to all the IP children that share
  the same interface.

  @param[in]  IpSb               The IP4 service instance that receive the packet.
  @param[in]  Head               The header of the received packet.
  @param[in]  Packet             The data of the received packet.
  @param[in]  Option             Point to the IP4 packet header options.
  @param[in]  OptionLen          Length of the IP4 packet header options.
  @param[in]  IpIf               The interface to enqueue the packet to.

  @return The number of the IP4 children that accepts the packet

**/
INTN
Ip4InterfaceEnquePacket (
  IN IP4_SERVICE            *IpSb,
  IN IP4_HEAD               *Head,
  IN NET_BUF                *Packet,
  IN UINT8                  *Option,
  IN UINT32                 OptionLen,
  IN IP4_INTERFACE          *IpIf
  )
{
  IP4_PROTOCOL              *IpInstance;
  IP4_CLIP_INFO             *Info;
  LIST_ENTRY                *Entry;
  INTN                      Enqueued;
  INTN                      LocalType;
  INTN                      SavedType;

  //
  // First, check that the packet is acceptable to this interface
  // and find the local cast type for the interface. A packet sent
  // to say 192.168.1.1 should NOT be deliver to 10.0.0.1 unless
  // promiscuous receiving.
  //
  LocalType = 0;
  Info      = IP4_GET_CLIP_INFO (Packet);

  if ((Info->CastType == IP4_MULTICAST) || (Info->CastType == IP4_LOCAL_BROADCAST)) {
    //
    // If the CastType is multicast, don't need to filter against
    // the group address here, Ip4InstanceFrameAcceptable will do
    // that later.
    //
    LocalType = Info->CastType;

  } else {
    //
    // Check the destination against local IP. If the station
    // address is 0.0.0.0, it means receiving all the IP destined
    // to local non-zero IP. Otherwise, it is necessary to compare
    // the destination to the interface's IP address.
    //
    if (IpIf->Ip == IP4_ALLZERO_ADDRESS) {
      LocalType = IP4_LOCAL_HOST;

    } else {
      LocalType = Ip4GetNetCast (Head->Dst, IpIf);

      if ((LocalType == 0) && IpIf->PromiscRecv) {
        LocalType = IP4_PROMISCUOUS;
      }
    }
  }

  if (LocalType == 0) {
    return 0;
  }

  //
  // Iterate through the ip instances on the interface, enqueue
  // the packet if filter passed. Save the original cast type,
  // and pass the local cast type to the IP children on the
  // interface. The global cast type will be restored later.
  //
  SavedType       = Info->CastType;
  Info->CastType  = LocalType;

  Enqueued        = 0;

  NET_LIST_FOR_EACH (Entry, &IpIf->IpInstances) {
    IpInstance = NET_LIST_USER_STRUCT (Entry, IP4_PROTOCOL, AddrLink);
    NET_CHECK_SIGNATURE (IpInstance, IP4_PROTOCOL_SIGNATURE);

    //
    // In RawData mode, add IPv4 headers and options back to packet.
    //
    if ((IpInstance->ConfigData.RawData) && (Option != NULL) && (OptionLen != 0)){
      Ip4PrependHead (Packet, Head, Option, OptionLen);
    }

    if (Ip4InstanceEnquePacket (IpInstance, Head, Packet) == EFI_SUCCESS) {
      Enqueued++;
    }
  }

  Info->CastType = SavedType;
  return Enqueued;
}


/**
  Deliver the packet for each IP4 child on the interface.

  @param[in]  IpSb               The IP4 service instance that received the packet
  @param[in]  IpIf               The IP4 interface to deliver the packet.

  @retval EFI_SUCCESS            It always returns EFI_SUCCESS now

**/
EFI_STATUS
Ip4InterfaceDeliverPacket (
  IN IP4_SERVICE            *IpSb,
  IN IP4_INTERFACE          *IpIf
  )
{
  IP4_PROTOCOL              *Ip4Instance;
  LIST_ENTRY                *Entry;

  NET_LIST_FOR_EACH (Entry, &IpIf->IpInstances) {
    Ip4Instance = NET_LIST_USER_STRUCT (Entry, IP4_PROTOCOL, AddrLink);
    Ip4InstanceDeliverPacket (Ip4Instance);
  }

  return EFI_SUCCESS;
}


/**
  Demultiple the packet. the packet delivery is processed in two
  passes. The first pass will enqueue a shared copy of the packet
  to each IP4 child that accepts the packet. The second pass will
  deliver a non-shared copy of the packet to each IP4 child that
  has pending receive requests. Data is copied if more than one
  child wants to consume the packet because each IP child needs
  its own copy of the packet to make changes.

  @param[in]  IpSb               The IP4 service instance that received the packet.
  @param[in]  Head               The header of the received packet.
  @param[in]  Packet             The data of the received packet.
  @param[in]  Option             Point to the IP4 packet header options.
  @param[in]  OptionLen          Length of the IP4 packet header options.

  @retval EFI_NOT_FOUND          No IP child accepts the packet.
  @retval EFI_SUCCESS            The packet is enqueued or delivered to some IP
                                 children.

**/
EFI_STATUS
Ip4Demultiplex (
  IN IP4_SERVICE            *IpSb,
  IN IP4_HEAD               *Head,
  IN NET_BUF                *Packet,
  IN UINT8                  *Option,
  IN UINT32                 OptionLen
  )
{
  LIST_ENTRY                *Entry;
  IP4_INTERFACE             *IpIf;
  INTN                      Enqueued;

  //
  // Two pass delivery: first, enqueue a shared copy of the packet
  // to each instance that accept the packet.
  //
  Enqueued = 0;

  NET_LIST_FOR_EACH (Entry, &IpSb->Interfaces) {
    IpIf = NET_LIST_USER_STRUCT (Entry, IP4_INTERFACE, Link);

    if (IpIf->Configured) {
      Enqueued += Ip4InterfaceEnquePacket (
                    IpSb,
                    Head,
                    Packet,
                    Option,
                    OptionLen,
                    IpIf
                    );
    }
  }

  //
  // Second: deliver a duplicate of the packet to each instance.
  // Release the local reference first, so that the last instance
  // getting the packet will not copy the data.
  //
  NetbufFree (Packet);

  if (Enqueued == 0) {
    return EFI_NOT_FOUND;
  }

  NET_LIST_FOR_EACH (Entry, &IpSb->Interfaces) {
    IpIf = NET_LIST_USER_STRUCT (Entry, IP4_INTERFACE, Link);

    if (IpIf->Configured) {
      Ip4InterfaceDeliverPacket (IpSb, IpIf);
    }
  }

  return EFI_SUCCESS;
}


/**
  Timeout the fragment and enqueued packets.

  @param[in]  IpSb                   The IP4 service instance to timeout

**/
VOID
Ip4PacketTimerTicking (
  IN IP4_SERVICE            *IpSb
  )
{
  LIST_ENTRY                *InstanceEntry;
  LIST_ENTRY                *Entry;
  LIST_ENTRY                *Next;
  IP4_PROTOCOL              *IpInstance;
  IP4_ASSEMBLE_ENTRY        *Assemble;
  NET_BUF                   *Packet;
  IP4_CLIP_INFO             *Info;
  UINT32                    Index;

  //
  // First, time out the fragments. The packet's life is counting down
  // once the first-arrived fragment was received.
  //
  for (Index = 0; Index < IP4_ASSEMLE_HASH_SIZE; Index++) {
    NET_LIST_FOR_EACH_SAFE (Entry, Next, &IpSb->Assemble.Bucket[Index]) {
      Assemble = NET_LIST_USER_STRUCT (Entry, IP4_ASSEMBLE_ENTRY, Link);

      if ((Assemble->Life > 0) && (--Assemble->Life == 0)) {
        RemoveEntryList (Entry);
        Ip4FreeAssembleEntry (Assemble);
      }
    }
  }

  NET_LIST_FOR_EACH (InstanceEntry, &IpSb->Children) {
    IpInstance = NET_LIST_USER_STRUCT (InstanceEntry, IP4_PROTOCOL, Link);

    //
    // Second, time out the assembled packets enqueued on each IP child.
    //
    NET_LIST_FOR_EACH_SAFE (Entry, Next, &IpInstance->Received) {
      Packet = NET_LIST_USER_STRUCT (Entry, NET_BUF, List);
      Info   = IP4_GET_CLIP_INFO (Packet);

      if ((Info->Life > 0) && (--Info->Life == 0)) {
        RemoveEntryList (Entry);
        NetbufFree (Packet);
      }
    }

    //
    // Third: time out the transmitted packets.
    //
    NetMapIterate (&IpInstance->TxTokens, Ip4SentPacketTicking, NULL);
  }
}