summaryrefslogtreecommitdiff
path: root/NetworkPkg/Mtftp6Dxe/Mtftp6Support.c
blob: 20888e8525e8d154258272e3732a9fd2733aeb6a (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
/** @file
  Mtftp6 support functions implementation.

  Copyright (c) 2009 - 2015, Intel Corporation. All rights reserved.<BR>

  This program and the accompanying materials
  are licensed and made available under the terms and conditions of the BSD License
  which accompanies this distribution.  The full text of the license may be found at
  http://opensource.org/licenses/bsd-license.php.

  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.

**/

#include "Mtftp6Impl.h"


/**
  Allocate a MTFTP block range, then init it to the range of [Start, End].

  @param[in]  Start                  The start block number.
  @param[in]  End                    The last block number in the range.

  @return Range                      The range of the allocated block buffer.

**/
MTFTP6_BLOCK_RANGE *
Mtftp6AllocateRange (
  IN UINT16                 Start,
  IN UINT16                 End
  )
{
  MTFTP6_BLOCK_RANGE        *Range;

  Range = AllocateZeroPool (sizeof (MTFTP6_BLOCK_RANGE));

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

  InitializeListHead (&Range->Link);
  Range->Start  = Start;
  Range->End    = End;
  Range->Bound  = End;

  return Range;
}


/**
  Initialize the block range for either RRQ or WRQ. RRQ and WRQ have
  different requirements for Start and End. For example, during startup,
  WRQ initializes its whole valid block range to [0, 0xffff]. This
  is bacause the server will send an ACK0 to inform the user to start the
  upload. When the client receives an ACK0, it will remove 0 from the range,
  get the next block number, which is 1, then upload the BLOCK1. For RRQ
  without option negotiation, the server will directly send the BLOCK1
  in response to the client's RRQ. When received BLOCK1, the client will
  remove it from the block range and send an ACK. It also works if there
  is option negotiation.

  @param[in]  Head                   The block range head to initialize.
  @param[in]  Start                  The Start block number.
  @param[in]  End                    The last block number.

  @retval EFI_OUT_OF_RESOURCES   Failed to allocate memory for initial block range.
  @retval EFI_SUCCESS            The initial block range is created.

**/
EFI_STATUS
Mtftp6InitBlockRange (
  IN LIST_ENTRY             *Head,
  IN UINT16                 Start,
  IN UINT16                 End
  )
{
  MTFTP6_BLOCK_RANGE        *Range;

  Range = Mtftp6AllocateRange (Start, End);

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

  InsertTailList (Head, &Range->Link);
  return EFI_SUCCESS;
}


/**
  Get the first valid block number on the range list.

  @param[in]  Head                   The block range head.

  @retval     ==-1                   If the block range is empty.
  @retval     >-1                    The first valid block number.

**/
INTN
Mtftp6GetNextBlockNum (
  IN LIST_ENTRY              *Head
  )
{
  MTFTP6_BLOCK_RANGE  *Range;

  if (IsListEmpty (Head)) {
    return -1;
  }

  Range = NET_LIST_HEAD (Head, MTFTP6_BLOCK_RANGE, Link);
  return Range->Start;
}


/**
  Set the last block number of the block range list. It
  removes all the blocks after the Last. MTFTP initialize the
  block range to the maximum possible range, such as [0, 0xffff]
  for WRQ. When it gets the last block number, it calls
  this function to set the last block number.

  @param[in]  Head                   The block range list.
  @param[in]  Last                   The last block number.

**/
VOID
Mtftp6SetLastBlockNum (
  IN LIST_ENTRY             *Head,
  IN UINT16                 Last
  )
{
  MTFTP6_BLOCK_RANGE        *Range;

  //
  // Iterate from the tail to head to remove the block number
  // after the last.
  //
  while (!IsListEmpty (Head)) {
    Range = NET_LIST_TAIL (Head, MTFTP6_BLOCK_RANGE, Link);

    if (Range->Start > Last) {
      RemoveEntryList (&Range->Link);
      FreePool (Range);
      continue;
    }

    if (Range->End > Last) {
      Range->End = Last;
    }
    return ;
  }
}


/**
  Remove the block number from the block range list.

  @param[in]  Head                   The block range list to remove from.
  @param[in]  Num                    The block number to remove.
  @param[in]  Completed              Whether Num is the last block number
  @param[out] TotalBlock             The continuous block number in all

  @retval EFI_NOT_FOUND          The block number isn't in the block range list.
  @retval EFI_SUCCESS            The block number has been removed from the list.
  @retval EFI_OUT_OF_RESOURCES   Failed to allocate resources.

**/
EFI_STATUS
Mtftp6RemoveBlockNum (
  IN LIST_ENTRY             *Head,
  IN UINT16                 Num,
  IN BOOLEAN                Completed,
  OUT UINT64                *TotalBlock
  )
{
  MTFTP6_BLOCK_RANGE        *Range;
  MTFTP6_BLOCK_RANGE        *NewRange;
  LIST_ENTRY                *Entry;

  NET_LIST_FOR_EACH (Entry, Head) {

    //
    // Each block represents a hole [Start, End] in the file,
    // skip to the first range with End >= Num
    //
    Range = NET_LIST_USER_STRUCT (Entry, MTFTP6_BLOCK_RANGE, Link);

    if (Range->End < Num) {
      continue;
    }

    //
    // There are three different cases for Start
    // 1. (Start > Num) && (End >= Num):
    //    because all the holes before this one has the condition of
    //    End < Num, so this block number has been removed.
    //
    // 2. (Start == Num) && (End >= Num):
    //    Need to increase the Start by one, and if End == Num, this
    //    hole has been removed completely, remove it.
    //
    // 3. (Start < Num) && (End >= Num):
    //    if End == Num, only need to decrease the End by one because
    //    we have (Start < Num) && (Num == End), so (Start <= End - 1).
    //    if (End > Num), the hold is splited into two holes, with
    //    [Start, Num - 1] and [Num + 1, End].
    //
    if (Range->Start > Num) {
      return EFI_NOT_FOUND;

    } else if (Range->Start == Num) {
      Range->Start++;

      //
      // Note that: RFC 1350 does not mention block counter roll-over,
      // but several TFTP hosts implement the roll-over be able to accept
      // transfers of unlimited size. There is no consensus, however, whether
      // the counter should wrap around to zero or to one. Many implementations
      // wrap to zero, because this is the simplest to implement. Here we choose
      // this solution.
      //
      *TotalBlock  = Num;

      if (Range->Round > 0) {
        *TotalBlock += Range->Bound +  MultU64x32 ((UINT64) (Range->Round -1), (UINT32)(Range->Bound + 1)) + 1;
      }

      if (Range->Start > Range->Bound) {
        Range->Start = 0;
        Range->Round ++;
      }

      if ((Range->Start > Range->End) || Completed) {
        RemoveEntryList (&Range->Link);
        FreePool (Range);
      }

      return EFI_SUCCESS;

    } else {
      if (Range->End == Num) {
        Range->End--;
      } else {
        NewRange = Mtftp6AllocateRange ((UINT16) (Num + 1), (UINT16) Range->End);

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

        Range->End = Num - 1;
        NetListInsertAfter (&Range->Link, &NewRange->Link);
      }

      return EFI_SUCCESS;
    }
  }

  return EFI_NOT_FOUND;
}


/**
  Configure the opened Udp6 instance until the corresponding Ip6 instance
  has been configured.

  @param[in]  UdpIo                  The pointer to the Udp6 Io.
  @param[in]  UdpCfgData             The pointer to the Udp6 configure data.

  @retval EFI_SUCCESS            Configure the Udp6 instance successfully.
  @retval EFI_NO_MAPPING         The corresponding Ip6 instance has not
                                 been configured yet.

**/
EFI_STATUS
Mtftp6GetMapping (
  IN UDP_IO                 *UdpIo,
  IN EFI_UDP6_CONFIG_DATA   *UdpCfgData
  )
{
  EFI_IP6_MODE_DATA         Ip6Mode;
  EFI_UDP6_PROTOCOL         *Udp6;
  EFI_STATUS                Status;
  EFI_EVENT                 Event;

  Event  = NULL;
  Udp6   = UdpIo->Protocol.Udp6;

  //
  // Create a timer to check whether the Ip6 instance configured or not.
  //
  Status = gBS->CreateEvent (
                  EVT_TIMER,
                  TPL_CALLBACK,
                  NULL,
                  NULL,
                  &Event
                  );
  if (EFI_ERROR (Status)) {
    goto ON_EXIT;
  }

  Status = gBS->SetTimer (
                  Event,
                  TimerRelative,
                  MTFTP6_GET_MAPPING_TIMEOUT * MTFTP6_TICK_PER_SECOND
                  );
  if (EFI_ERROR (Status)) {
    goto ON_EXIT;
  }

  //
  // Check the Ip6 mode data till timeout.
  //
  while (EFI_ERROR (gBS->CheckEvent (Event))) {

    Udp6->Poll (Udp6);

    Status = Udp6->GetModeData (Udp6, NULL, &Ip6Mode, NULL, NULL);

    if (!EFI_ERROR (Status)) {

      if  (Ip6Mode.IsConfigured) {
        //
        // Continue to configure the Udp6 instance.
        //
        Status = Udp6->Configure (Udp6, UdpCfgData);
      } else {
        Status = EFI_NO_MAPPING;
      }
    }
  }

ON_EXIT:

  if (Event != NULL) {
    gBS->CloseEvent (Event);
  }

  return Status;
}


/**
  The dummy configure routine for create a new Udp6 Io.

  @param[in]  UdpIo                  The pointer to the Udp6 Io.
  @param[in]  Context                The pointer to the context.

  @retval EFI_SUCCESS                This value is always returned.

**/
EFI_STATUS
EFIAPI
Mtftp6ConfigDummyUdpIo (
  IN UDP_IO                 *UdpIo,
  IN VOID                   *Context
  )
{
  return EFI_SUCCESS;
}


/**
  The configure routine for Mtftp6 instance to transmit/receive.

  @param[in]  UdpIo                  The pointer to the Udp6 Io.
  @param[in]  ServerIp               The pointer to the server address.
  @param[in]  ServerPort             The pointer to the server port.
  @param[in]  LocalIp                The pointer to the local address.
  @param[in]  LocalPort              The pointer to the local port.

  @retval EFI_SUCCESS            Configured the Udp6 Io for Mtftp6 successfully.
  @retval EFI_NO_MAPPING         The corresponding Ip6 instance has not been
                                 configured yet.

**/
EFI_STATUS
Mtftp6ConfigUdpIo (
  IN UDP_IO                 *UdpIo,
  IN EFI_IPv6_ADDRESS       *ServerIp,
  IN UINT16                 ServerPort,
  IN EFI_IPv6_ADDRESS       *LocalIp,
  IN UINT16                 LocalPort
  )
{
  EFI_STATUS                Status;
  EFI_UDP6_PROTOCOL         *Udp6;
  EFI_UDP6_CONFIG_DATA      *Udp6Cfg;

  Udp6    = UdpIo->Protocol.Udp6;
  Udp6Cfg = &(UdpIo->Config.Udp6);

  ZeroMem (Udp6Cfg, sizeof (EFI_UDP6_CONFIG_DATA));

  //
  // Set the Udp6 Io configure data.
  //
  Udp6Cfg->AcceptPromiscuous  = FALSE;
  Udp6Cfg->AcceptAnyPort      = FALSE;
  Udp6Cfg->AllowDuplicatePort = FALSE;
  Udp6Cfg->TrafficClass       = 0;
  Udp6Cfg->HopLimit           = 128;
  Udp6Cfg->ReceiveTimeout     = 0;
  Udp6Cfg->TransmitTimeout    = 0;
  Udp6Cfg->StationPort        = LocalPort;
  Udp6Cfg->RemotePort         = ServerPort;

  CopyMem (
    &Udp6Cfg->StationAddress,
    LocalIp,
    sizeof (EFI_IPv6_ADDRESS)
    );

  CopyMem (
    &Udp6Cfg->RemoteAddress,
    ServerIp,
    sizeof (EFI_IPv6_ADDRESS)
    );

  //
  // Configure the Udp6 instance with current configure data.
  //
  Status = Udp6->Configure (Udp6, Udp6Cfg);

  if (Status == EFI_NO_MAPPING) {

    return Mtftp6GetMapping (UdpIo, Udp6Cfg);
  }

  return Status;
}


/**
  Build and transmit the request packet for the Mtftp6 instance.

  @param[in]  Instance               The pointer to the Mtftp6 instance.
  @param[in]  Operation              The operation code of this packet.

  @retval EFI_OUT_OF_RESOURCES   Failed to allocate memory for the request.
  @retval EFI_SUCCESS            The request is built and sent.
  @retval Others                 Failed to transmit the packet.

**/
EFI_STATUS
Mtftp6SendRequest (
  IN MTFTP6_INSTANCE        *Instance,
  IN UINT16                 Operation
  )
{
  EFI_MTFTP6_PACKET         *Packet;
  EFI_MTFTP6_OPTION         *Options;
  EFI_MTFTP6_TOKEN          *Token;
  RETURN_STATUS             Status;
  NET_BUF                   *Nbuf;
  UINT8                     *Mode;
  UINT8                     *Cur;
  UINTN                     Index;
  UINT32                    BufferLength;
  UINTN                     FileNameLength;
  UINTN                     ModeLength;
  UINTN                     OptionStrLength;
  UINTN                     ValueStrLength;

  Token   = Instance->Token;
  Options = Token->OptionList;
  Mode    = Token->ModeStr;

  if (Mode == NULL) {
    Mode = (UINT8 *) "octet";
  }

  //
  // The header format of RRQ/WRQ packet is:
  //
  //   2 bytes     string    1 byte     string   1 byte
  //   ------------------------------------------------
  //  | Opcode |  Filename  |   0  |    Mode    |   0  |
  //   ------------------------------------------------
  //
  // The common option format is:
  //
  //    string     1 byte     string   1 byte
  //   ---------------------------------------
  //  | OptionStr |   0  |  ValueStr  |   0   |
  //   ---------------------------------------
  //

  //
  // Compute the size of new Mtftp6 packet.
  //
  FileNameLength = AsciiStrLen ((CHAR8 *) Token->Filename);
  ModeLength     = AsciiStrLen ((CHAR8 *) Mode);
  BufferLength   = (UINT32) FileNameLength + (UINT32) ModeLength + 4;

  for (Index = 0; Index < Token->OptionCount; Index++) {
    OptionStrLength = AsciiStrLen ((CHAR8 *) Options[Index].OptionStr);
    ValueStrLength  = AsciiStrLen ((CHAR8 *) Options[Index].ValueStr);
    BufferLength   += (UINT32) OptionStrLength + (UINT32) ValueStrLength + 2;
  }

  //
  // Allocate a packet then copy the data.
  //
  if ((Nbuf = NetbufAlloc (BufferLength)) == NULL) {
    return EFI_OUT_OF_RESOURCES;
  }

  //
  // Copy the opcode, filename and mode into packet.
  //
  Packet         = (EFI_MTFTP6_PACKET *) NetbufAllocSpace (Nbuf, BufferLength, FALSE);
  ASSERT (Packet != NULL);

  Packet->OpCode = HTONS (Operation);
  BufferLength  -= sizeof (Packet->OpCode);
  
  Cur            = Packet->Rrq.Filename;
  Status         = AsciiStrCpyS ((CHAR8 *) Cur, BufferLength, (CHAR8 *) Token->Filename);
  ASSERT_EFI_ERROR (Status);
  BufferLength  -= (UINT32) (FileNameLength + 1);
  Cur           += FileNameLength + 1;
  Status         = AsciiStrCpyS ((CHAR8 *) Cur, BufferLength, (CHAR8 *) Mode);
  ASSERT_EFI_ERROR (Status);
  BufferLength  -= (UINT32) (ModeLength + 1);
  Cur           += ModeLength + 1;

  //
  // Copy all the extension options into the packet.
  //
  for (Index = 0; Index < Token->OptionCount; ++Index) {
    OptionStrLength = AsciiStrLen ((CHAR8 *) Options[Index].OptionStr);
    ValueStrLength  = AsciiStrLen ((CHAR8 *) Options[Index].ValueStr);
    
    Status          = AsciiStrCpyS ((CHAR8 *) Cur, BufferLength, (CHAR8 *) Options[Index].OptionStr);
    ASSERT_EFI_ERROR (Status);
    BufferLength   -= (UINT32) (OptionStrLength + 1);
    Cur            += OptionStrLength + 1;
    
    Status          = AsciiStrCpyS ((CHAR8 *) Cur, BufferLength, (CHAR8 *) Options[Index].ValueStr);
    ASSERT_EFI_ERROR (Status);
    BufferLength   -= (UINT32) (ValueStrLength + 1);
    Cur            += ValueStrLength + 1;
    
  }

  //
  // Save the packet buf for retransmit
  //
  if (Instance->LastPacket != NULL) {
    NetbufFree (Instance->LastPacket);
  }

  Instance->LastPacket = Nbuf;
  Instance->CurRetry   = 0;

  return Mtftp6TransmitPacket (Instance, Nbuf);
}


/**
  Build and send an error packet.

  @param[in]  Instance               The pointer to the Mtftp6 instance.
  @param[in]  ErrCode                The error code in the packet.
  @param[in]  ErrInfo                The error message in the packet.

  @retval EFI_OUT_OF_RESOURCES   Failed to allocate memory for the error packet.
  @retval EFI_SUCCESS            The error packet is transmitted.
  @retval Others                 Failed to transmit the packet.

**/
EFI_STATUS
Mtftp6SendError (
  IN MTFTP6_INSTANCE        *Instance,
  IN UINT16                 ErrCode,
  IN UINT8*                 ErrInfo
  )
{
  NET_BUF                   *Nbuf;
  EFI_MTFTP6_PACKET         *TftpError;
  UINT32                    Len;

  //
  // Allocate a packet then copy the data.
  //
  Len  = (UINT32) (AsciiStrLen ((CHAR8 *) ErrInfo) + sizeof (EFI_MTFTP6_ERROR_HEADER));
  Nbuf = NetbufAlloc (Len);

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

  TftpError = (EFI_MTFTP6_PACKET *) NetbufAllocSpace (Nbuf, Len, FALSE);

  if (TftpError == NULL) {
    NetbufFree (Nbuf);
    return EFI_OUT_OF_RESOURCES;
  }

  TftpError->OpCode          = HTONS (EFI_MTFTP6_OPCODE_ERROR);
  TftpError->Error.ErrorCode = HTONS (ErrCode);

  AsciiStrCpyS ((CHAR8 *) TftpError->Error.ErrorMessage, sizeof (TftpError->Error.ErrorMessage) / sizeof (TftpError->Error.ErrorMessage[0]), (CHAR8 *) ErrInfo);

  //
  // Save the packet buf for retransmit
  //
  if (Instance->LastPacket != NULL) {
    NetbufFree (Instance->LastPacket);
  }

  Instance->LastPacket = Nbuf;
  Instance->CurRetry   = 0;

  return Mtftp6TransmitPacket (Instance, Nbuf);
}


/**
  The callback function called when the packet is transmitted.

  @param[in]  Packet                 The pointer to the packet.
  @param[in]  UdpEpt                 The pointer to the Udp6 access point.
  @param[in]  IoStatus               The result of the transmission.
  @param[in]  Context                The pointer to the context.

**/
VOID
EFIAPI
Mtftp6OnPacketSent (
  IN NET_BUF                   *Packet,
  IN UDP_END_POINT             *UdpEpt,
  IN EFI_STATUS                IoStatus,
  IN VOID                      *Context
  )
{
  NetbufFree (Packet);
  *(BOOLEAN *) Context = TRUE;
}


/**
  Send the packet for the Mtftp6 instance.

  @param[in]  Instance               The pointer to the Mtftp6 instance.
  @param[in]  Packet                 The pointer to the packet to be sent.

  @retval EFI_SUCCESS            The packet was sent out
  @retval Others                 Failed to transmit the packet.

**/
EFI_STATUS
Mtftp6TransmitPacket (
  IN MTFTP6_INSTANCE        *Instance,
  IN NET_BUF                *Packet
  )
{
  EFI_UDP6_PROTOCOL         *Udp6;
  EFI_UDP6_CONFIG_DATA      Udp6CfgData;
  EFI_STATUS                Status;
  UINT16                    *Temp;
  UINT16                    Value;
  UINT16                    OpCode;

  ZeroMem (&Udp6CfgData, sizeof(EFI_UDP6_CONFIG_DATA));
  Udp6 = Instance->UdpIo->Protocol.Udp6;

  //
  // Set the live time of the packet.
  //
  Instance->PacketToLive = Instance->IsMaster ? Instance->Timeout : (Instance->Timeout * 2);

  Temp   = (UINT16 *) NetbufGetByte (Packet, 0, NULL);
  ASSERT (Temp != NULL);

  Value  = *Temp;
  OpCode = NTOHS (Value);

  if (OpCode == EFI_MTFTP6_OPCODE_RRQ || OpCode == EFI_MTFTP6_OPCODE_DIR || OpCode == EFI_MTFTP6_OPCODE_WRQ) {
    //
    // For the Rrq, Dir, Wrq requests of the operation, configure the Udp6Io as
    // (serverip, 69, localip, localport) to send.
    // Usually local address and local port are both default as zero.
    //
    Status = Udp6->Configure (Udp6, NULL);

    if (EFI_ERROR (Status)) {
      return Status;
    }

    Status = Mtftp6ConfigUdpIo (
               Instance->UdpIo,
               &Instance->ServerIp,
               Instance->ServerCmdPort,
               &Instance->Config->StationIp,
               Instance->Config->LocalPort
               );

    if (EFI_ERROR (Status)) {
      return Status;
    }

    //
    // Get the current local address and port by get Udp6 mode data.
    //
    Status = Udp6->GetModeData (Udp6, &Udp6CfgData, NULL, NULL, NULL);
    if (EFI_ERROR (Status)) {
      return Status;
    }

    NET_GET_REF (Packet);

    Instance->IsTransmitted = FALSE;

    Status = UdpIoSendDatagram (
               Instance->UdpIo,
               Packet,
               NULL,
               NULL,
               Mtftp6OnPacketSent,
               &Instance->IsTransmitted
               );

    if (EFI_ERROR (Status)) {
      NET_PUT_REF (Packet);
      return Status;
    }

    //
    // Poll till the packet sent out from the ip6 queue.
    //
    gBS->RestoreTPL (Instance->OldTpl);

    while (!Instance->IsTransmitted) {
      Udp6->Poll (Udp6);
    }

    Instance->OldTpl = gBS->RaiseTPL (TPL_CALLBACK);

    //
    // For the subsequent exchange of such requests, reconfigure the Udp6Io as
    // (serverip, 0, localip, localport) to receive.
    // Currently local address and local port are specified by Udp6 mode data.
    //
    Status = Udp6->Configure (Udp6, NULL);

    if (EFI_ERROR (Status)) {
      return Status;
    }

    Status = Mtftp6ConfigUdpIo (
               Instance->UdpIo,
               &Instance->ServerIp,
               Instance->ServerDataPort,
               &Udp6CfgData.StationAddress,
               Udp6CfgData.StationPort
               );
  } else {
    //
    // For the data exchange, configure the Udp6Io as (serverip, dataport,
    // localip, localport) to send/receive.
    // Currently local address and local port are specified by Udp6 mode data.
    //
    Status = Udp6->GetModeData (Udp6, &Udp6CfgData, NULL, NULL, NULL);
    if (EFI_ERROR (Status)) {
      return Status;
    }

    if (Udp6CfgData.RemotePort != Instance->ServerDataPort) {

      Status = Udp6->Configure (Udp6, NULL);

      if (EFI_ERROR (Status)) {
        return Status;
      }

      Status = Mtftp6ConfigUdpIo (
                 Instance->UdpIo,
                 &Instance->ServerIp,
                 Instance->ServerDataPort,
                 &Udp6CfgData.StationAddress,
                 Udp6CfgData.StationPort
                 );

      if (EFI_ERROR (Status)) {
        return Status;
      }
    }

    NET_GET_REF (Packet);

    Instance->IsTransmitted = FALSE;

    Status = UdpIoSendDatagram (
               Instance->UdpIo,
               Packet,
               NULL,
               NULL,
               Mtftp6OnPacketSent,
               &Instance->IsTransmitted
               );

    if (EFI_ERROR (Status)) {
      NET_PUT_REF (Packet);
    }

    //
    // Poll till the packet sent out from the ip6 queue.
    //
    gBS->RestoreTPL (Instance->OldTpl);

    while (!Instance->IsTransmitted) {
      Udp6->Poll (Udp6);
    }

    Instance->OldTpl = gBS->RaiseTPL (TPL_CALLBACK);
  }

  return Status;
}


/**
  Check packet for GetInfo callback routine.

  GetInfo is implemented with EfiMtftp6ReadFile. It's used to inspect
  the first packet from server, then abort the session.

  @param[in]  This                   The pointer to the Mtftp6 protocol.
  @param[in]  Token                  The pointer to the Mtftp6 token.
  @param[in]  PacketLen              The length of the packet.
  @param[in]  Packet                 The pointer to the received packet.

  @retval EFI_ABORTED            Abort the Mtftp6 operation.

**/
EFI_STATUS
EFIAPI
Mtftp6CheckPacket (
  IN EFI_MTFTP6_PROTOCOL    *This,
  IN EFI_MTFTP6_TOKEN       *Token,
  IN UINT16                 PacketLen,
  IN EFI_MTFTP6_PACKET      *Packet
  )
{
  MTFTP6_GETINFO_CONTEXT    *Context;
  UINT16                    OpCode;

  Context = (MTFTP6_GETINFO_CONTEXT *) Token->Context;
  OpCode  = NTOHS (Packet->OpCode);

  //
  // Set the GetInfo's return status according to the OpCode.
  //
  switch (OpCode) {
  case EFI_MTFTP6_OPCODE_ERROR:
    Context->Status = EFI_TFTP_ERROR;
    break;

  case EFI_MTFTP6_OPCODE_OACK:
    Context->Status = EFI_SUCCESS;
    break;

  default:
    Context->Status = EFI_PROTOCOL_ERROR;
  }

  //
  // Allocate buffer then copy the packet over. Use gBS->AllocatePool
  // in case NetAllocatePool will implements something tricky.
  //
  *(Context->Packet) = AllocateZeroPool (PacketLen);

  if (*(Context->Packet) == NULL) {
    Context->Status = EFI_OUT_OF_RESOURCES;
    return EFI_ABORTED;
  }

  *(Context->PacketLen) = PacketLen;
  CopyMem (*(Context->Packet), Packet, PacketLen);

  return EFI_ABORTED;
}


/**
  Clean up the current Mtftp6 operation.

  @param[in]  Instance               The pointer to the Mtftp6 instance.
  @param[in]  Result                 The result to be returned to the user.

**/
VOID
Mtftp6OperationClean (
  IN MTFTP6_INSTANCE        *Instance,
  IN EFI_STATUS             Result
  )
{
  LIST_ENTRY                *Entry;
  LIST_ENTRY                *Next;
  MTFTP6_BLOCK_RANGE        *Block;

  //
  // Clean up the current token and event.
  //
  if (Instance->Token != NULL) {
    Instance->Token->Status = Result;
    if (Instance->Token->Event != NULL) {
      gBS->SignalEvent (Instance->Token->Event);
    }
    Instance->Token = NULL;
  }

  //
  // Clean up the corresponding Udp6Io.
  //
  if (Instance->UdpIo != NULL) {
    UdpIoCleanIo (Instance->UdpIo);
  }

  if (Instance->McastUdpIo != NULL) {
    gBS->CloseProtocol (
           Instance->McastUdpIo->UdpHandle,
           &gEfiUdp6ProtocolGuid,
           Instance->McastUdpIo->Image,
           Instance->Handle
           );
    UdpIoFreeIo (Instance->McastUdpIo);
    Instance->McastUdpIo = NULL;
  }

  //
  // Clean up the stored last packet.
  //
  if (Instance->LastPacket != NULL) {
    NetbufFree (Instance->LastPacket);
    Instance->LastPacket = NULL;
  }

  NET_LIST_FOR_EACH_SAFE (Entry, Next, &Instance->BlkList) {
    Block = NET_LIST_USER_STRUCT (Entry, MTFTP6_BLOCK_RANGE, Link);
    RemoveEntryList (Entry);
    FreePool (Block);
  }

  //
  // Reinitialize the corresponding fields of the Mtftp6 operation.
  //
  ZeroMem (&Instance->ExtInfo, sizeof (MTFTP6_EXT_OPTION_INFO));
  ZeroMem (&Instance->ServerIp, sizeof (EFI_IPv6_ADDRESS));
  ZeroMem (&Instance->McastIp, sizeof (EFI_IPv6_ADDRESS));

  Instance->ServerCmdPort  = 0;
  Instance->ServerDataPort = 0;
  Instance->McastPort      = 0;
  Instance->BlkSize        = 0;
  Instance->LastBlk        = 0;
  Instance->PacketToLive   = 0;
  Instance->MaxRetry       = 0;
  Instance->CurRetry       = 0;
  Instance->Timeout        = 0;
  Instance->IsMaster       = TRUE;
}


/**
  Start the Mtftp6 instance to perform the operation, such as read file,
  write file, and read directory.

  @param[in]  This                   The MTFTP session.
  @param[in]  Token                  The token than encapsues the user's request.
  @param[in]  OpCode                 The operation to perform.

  @retval EFI_INVALID_PARAMETER  Some of the parameters are invalid.
  @retval EFI_NOT_STARTED        The MTFTP session hasn't been configured.
  @retval EFI_ALREADY_STARTED    There is pending operation for the session.
  @retval EFI_SUCCESS            The operation is successfully started.

**/
EFI_STATUS
Mtftp6OperationStart (
  IN EFI_MTFTP6_PROTOCOL    *This,
  IN EFI_MTFTP6_TOKEN       *Token,
  IN UINT16                 OpCode
  )
{
  MTFTP6_INSTANCE           *Instance;
  EFI_STATUS                Status;

  if (This == NULL ||
      Token == NULL ||
      Token->Filename == NULL ||
      (Token->OptionCount != 0 && Token->OptionList == NULL) ||
      (Token->OverrideData != NULL && !NetIp6IsValidUnicast (&Token->OverrideData->ServerIp))
      ) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // At least define one method to collect the data for download.
  //
  if ((OpCode == EFI_MTFTP6_OPCODE_RRQ || OpCode == EFI_MTFTP6_OPCODE_DIR) &&
      Token->Buffer == NULL &&
      Token->CheckPacket == NULL
      ) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // At least define one method to provide the data for upload.
  //
  if (OpCode == EFI_MTFTP6_OPCODE_WRQ && Token->Buffer == NULL && Token->PacketNeeded == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  Instance = MTFTP6_INSTANCE_FROM_THIS (This);

  if (Instance->Config == NULL) {
    return EFI_NOT_STARTED;
  }

  if (Instance->Token != NULL) {
    return EFI_ACCESS_DENIED;
  }

  Status           = EFI_SUCCESS;
  Instance->OldTpl = gBS->RaiseTPL (TPL_CALLBACK);

  //
  // Parse the extension options in the request packet.
  //
  if (Token->OptionCount != 0) {

    Status = Mtftp6ParseExtensionOption (
               Token->OptionList,
               Token->OptionCount,
               TRUE,
               &Instance->ExtInfo
               );

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

  //
  // Initialize runtime data from config data or override data.
  //
  Instance->Token           = Token;
  Instance->ServerCmdPort   = Instance->Config->InitialServerPort;
  Instance->ServerDataPort  = 0;
  Instance->MaxRetry        = Instance->Config->TryCount;
  Instance->Timeout         = Instance->Config->TimeoutValue;
  Instance->IsMaster        = TRUE;

  CopyMem (
    &Instance->ServerIp,
    &Instance->Config->ServerIp,
    sizeof (EFI_IPv6_ADDRESS)
    );

  if (Token->OverrideData != NULL) {
    Instance->ServerCmdPort = Token->OverrideData->ServerPort;
    Instance->MaxRetry      = Token->OverrideData->TryCount;
    Instance->Timeout       = Token->OverrideData->TimeoutValue;

    CopyMem (
      &Instance->ServerIp,
      &Token->OverrideData->ServerIp,
      sizeof (EFI_IPv6_ADDRESS)
      );
  }

  //
  // Set default value for undefined parameters.
  //
  if (Instance->ServerCmdPort == 0) {
    Instance->ServerCmdPort = MTFTP6_DEFAULT_SERVER_CMD_PORT;
  }
  if (Instance->BlkSize == 0) {
    Instance->BlkSize = MTFTP6_DEFAULT_BLK_SIZE;
  }
  if (Instance->MaxRetry == 0) {
    Instance->MaxRetry = MTFTP6_DEFAULT_MAX_RETRY;
  }
  if (Instance->Timeout == 0) {
    Instance->Timeout = MTFTP6_DEFAULT_TIMEOUT;
  }

  Token->Status = EFI_NOT_READY;

  //
  // Switch the routines by the operation code.
  //
  switch (OpCode) {
  case EFI_MTFTP6_OPCODE_RRQ:
    Status = Mtftp6RrqStart (Instance, OpCode);
    break;

  case EFI_MTFTP6_OPCODE_DIR:
    Status = Mtftp6RrqStart (Instance, OpCode);
    break;

  case EFI_MTFTP6_OPCODE_WRQ:
    Status = Mtftp6WrqStart (Instance, OpCode);
    break;

  default:
    Status = EFI_DEVICE_ERROR;
    goto ON_ERROR;
  }

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

  //
  // Return immediately for asynchronous or poll the instance for synchronous.
  //
  gBS->RestoreTPL (Instance->OldTpl);

  if (Token->Event == NULL) {
    while (Token->Status == EFI_NOT_READY) {
      This->Poll (This);
    }
    return Token->Status;
  }

  return EFI_SUCCESS;

ON_ERROR:

  Mtftp6OperationClean (Instance, Status);
  gBS->RestoreTPL (Instance->OldTpl);

  return Status;
}


/**
  The timer ticking routine for the Mtftp6 instance.

  @param[in]  Event                  The pointer to the ticking event.
  @param[in]  Context                The pointer to the context.

**/
VOID
EFIAPI
Mtftp6OnTimerTick (
  IN EFI_EVENT              Event,
  IN VOID                   *Context
  )
{
  MTFTP6_SERVICE            *Service;
  MTFTP6_INSTANCE           *Instance;
  LIST_ENTRY                *Entry;
  LIST_ENTRY                *Next;
  EFI_MTFTP6_TOKEN          *Token;
  EFI_STATUS                Status;

  Service = (MTFTP6_SERVICE *) Context;

  //
  // Iterate through all the children of the Mtftp service instance. Time
  // out the packet. If maximum retries reached, clean the session up.
  //
  NET_LIST_FOR_EACH_SAFE (Entry, Next, &Service->Children) {

    Instance = NET_LIST_USER_STRUCT (Entry, MTFTP6_INSTANCE, Link);

    if (Instance->Token == NULL) {
      continue;
    }

    if (Instance->PacketToLive > 0) {
      Instance->PacketToLive--;
      continue;
    }

    Instance->CurRetry++;
    Token = Instance->Token;

    if (Token->TimeoutCallback != NULL) {
      //
      // Call the timeout callback routine if has.
      //
      Status = Token->TimeoutCallback (&Instance->Mtftp6, Token);

      if (EFI_ERROR (Status)) {
        Mtftp6SendError (
           Instance,
           EFI_MTFTP6_ERRORCODE_REQUEST_DENIED,
           (UINT8 *) "User aborted the transfer in time out"
           );
        Mtftp6OperationClean (Instance, EFI_ABORTED);
        continue;
      }
    }

    //
    // Retransmit the packet if haven't reach the maxmium retry count,
    // otherwise exit the transfer.
    //
    if (Instance->CurRetry < Instance->MaxRetry) {
      Mtftp6TransmitPacket (Instance, Instance->LastPacket);
    } else {
      Mtftp6OperationClean (Instance, EFI_TIMEOUT);
      continue;
    }
  }
}