]> git.proxmox.com Git - mirror_edk2.git/blob - EmbeddedPkg/Drivers/AndroidFastbootTransportTcpDxe/FastbootTransportTcp.c
EmbeddedPkg: Replace BSD License with BSD+Patent License
[mirror_edk2.git] / EmbeddedPkg / Drivers / AndroidFastbootTransportTcpDxe / FastbootTransportTcp.c
1 /** @file
2 #
3 # Copyright (c) 2014, ARM Ltd. All rights reserved.<BR>
4 #
5 # SPDX-License-Identifier: BSD-2-Clause-Patent
6 #
7 #
8 #**/
9
10 #include <Protocol/AndroidFastbootTransport.h>
11 #include <Protocol/Dhcp4.h>
12 #include <Protocol/Tcp4.h>
13 #include <Protocol/ServiceBinding.h>
14 #include <Protocol/SimpleTextOut.h>
15
16 #include <Library/BaseLib.h>
17 #include <Library/BaseMemoryLib.h>
18 #include <Library/DebugLib.h>
19 #include <Library/MemoryAllocationLib.h>
20 #include <Library/PrintLib.h>
21 #include <Library/UefiBootServicesTableLib.h>
22 #include <Library/UefiDriverEntryPoint.h>
23 #include <Library/UefiRuntimeServicesTableLib.h>
24
25 #define IP4_ADDR_TO_STRING(IpAddr, IpAddrString) UnicodeSPrint ( \
26 IpAddrString, \
27 16 * 2, \
28 L"%d.%d.%d.%d", \
29 IpAddr.Addr[0], \
30 IpAddr.Addr[1], \
31 IpAddr.Addr[2], \
32 IpAddr.Addr[3] \
33 );
34
35 // Fastboot says max packet size is 512, but FASTBOOT_TRANSPORT_PROTOCOL
36 // doesn't place a limit on the size of buffers returned by Receive.
37 // (This isn't actually a packet size - it's just the size of the buffers we
38 // pass to the TCP driver to fill with received data.)
39 // We can achieve much better performance by doing this in larger chunks.
40 #define RX_FRAGMENT_SIZE 2048
41
42 STATIC EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *mTextOut;
43
44 STATIC EFI_TCP4_PROTOCOL *mTcpConnection;
45 STATIC EFI_TCP4_PROTOCOL *mTcpListener;
46
47 STATIC EFI_EVENT mReceiveEvent;
48
49 STATIC EFI_SERVICE_BINDING_PROTOCOL *mTcpServiceBinding;
50 STATIC EFI_HANDLE mTcpHandle = NULL;
51
52 // We only ever use one IO token for receive and one for transmit. To save
53 // repeatedly allocating and freeing, just allocate statically and re-use.
54 #define NUM_RX_TOKENS 16
55 #define TOKEN_NEXT(Index) (((Index) + 1) % NUM_RX_TOKENS)
56
57 STATIC UINTN mNextSubmitIndex;
58 STATIC UINTN mNextReceiveIndex;
59 STATIC EFI_TCP4_IO_TOKEN mReceiveToken[NUM_RX_TOKENS];
60 STATIC EFI_TCP4_RECEIVE_DATA mRxData[NUM_RX_TOKENS];
61 STATIC EFI_TCP4_IO_TOKEN mTransmitToken;
62 STATIC EFI_TCP4_TRANSMIT_DATA mTxData;
63 // We also reuse the accept token
64 STATIC EFI_TCP4_LISTEN_TOKEN mAcceptToken;
65 // .. and the close token
66 STATIC EFI_TCP4_CLOSE_TOKEN mCloseToken;
67
68 // List type for queued received packets
69 typedef struct _FASTBOOT_TCP_PACKET_LIST {
70 LIST_ENTRY Link;
71 VOID *Buffer;
72 UINTN BufferSize;
73 } FASTBOOT_TCP_PACKET_LIST;
74
75 STATIC LIST_ENTRY mPacketListHead;
76
77 STATIC
78 VOID
79 EFIAPI
80 DataReceived (
81 IN EFI_EVENT Event,
82 IN VOID *Context
83 );
84
85 /*
86 Helper function to set up a receive IO token and call Tcp->Receive
87 */
88 STATIC
89 EFI_STATUS
90 SubmitRecieveToken (
91 VOID
92 )
93 {
94 EFI_STATUS Status;
95 VOID *FragmentBuffer;
96
97 Status = EFI_SUCCESS;
98
99 FragmentBuffer = AllocatePool (RX_FRAGMENT_SIZE);
100 ASSERT (FragmentBuffer != NULL);
101 if (FragmentBuffer == NULL) {
102 DEBUG ((EFI_D_ERROR, "TCP Fastboot out of resources"));
103 return EFI_OUT_OF_RESOURCES;
104 }
105
106 mRxData[mNextSubmitIndex].DataLength = RX_FRAGMENT_SIZE;
107 mRxData[mNextSubmitIndex].FragmentTable[0].FragmentLength = RX_FRAGMENT_SIZE;
108 mRxData[mNextSubmitIndex].FragmentTable[0].FragmentBuffer = FragmentBuffer;
109
110 Status = mTcpConnection->Receive (mTcpConnection, &mReceiveToken[mNextSubmitIndex]);
111 if (EFI_ERROR (Status)) {
112 DEBUG ((EFI_D_ERROR, "TCP Receive: %r\n", Status));
113 FreePool (FragmentBuffer);
114 }
115
116 mNextSubmitIndex = TOKEN_NEXT (mNextSubmitIndex);
117 return Status;
118 }
119
120 /*
121 Event notify function for when we have closed our TCP connection.
122 We can now start listening for another connection.
123 */
124 STATIC
125 VOID
126 ConnectionClosed (
127 IN EFI_EVENT Event,
128 IN VOID *Context
129 )
130 {
131 EFI_STATUS Status;
132
133 // Possible bug in EDK2 TCP4 driver: closing a connection doesn't remove its
134 // PCB from the list of live connections. Subsequent attempts to Configure()
135 // a TCP instance with the same local port will fail with INVALID_PARAMETER.
136 // Calling Configure with NULL is a workaround for this issue.
137 Status = mTcpConnection->Configure (mTcpConnection, NULL);
138
139 mTcpConnection = NULL;
140
141 Status = mTcpListener->Accept (mTcpListener, &mAcceptToken);
142 if (EFI_ERROR (Status)) {
143 DEBUG ((EFI_D_ERROR, "TCP Accept: %r\n", Status));
144 }
145 }
146
147 STATIC
148 VOID
149 CloseReceiveEvents (
150 VOID
151 )
152 {
153 UINTN Index;
154
155 for (Index = 0; Index < NUM_RX_TOKENS; Index++) {
156 gBS->CloseEvent (mReceiveToken[Index].CompletionToken.Event);
157 }
158 }
159
160 /*
161 Event notify function to be called when we receive TCP data.
162 */
163 STATIC
164 VOID
165 EFIAPI
166 DataReceived (
167 IN EFI_EVENT Event,
168 IN VOID *Context
169 )
170 {
171 EFI_STATUS Status;
172 FASTBOOT_TCP_PACKET_LIST *NewEntry;
173 EFI_TCP4_IO_TOKEN *ReceiveToken;
174
175 ReceiveToken = &mReceiveToken[mNextReceiveIndex];
176
177 Status = ReceiveToken->CompletionToken.Status;
178
179 if (Status == EFI_CONNECTION_FIN) {
180 //
181 // Remote host closed connection. Close our end.
182 //
183
184 CloseReceiveEvents ();
185
186 Status = mTcpConnection->Close (mTcpConnection, &mCloseToken);
187 ASSERT_EFI_ERROR (Status);
188
189 return;
190 }
191
192 //
193 // Add an element to the receive queue
194 //
195
196 NewEntry = AllocatePool (sizeof (FASTBOOT_TCP_PACKET_LIST));
197 if (NewEntry == NULL) {
198 DEBUG ((EFI_D_ERROR, "TCP Fastboot: Out of resources\n"));
199 return;
200 }
201
202 mNextReceiveIndex = TOKEN_NEXT (mNextReceiveIndex);
203
204 if (!EFI_ERROR (Status)) {
205 NewEntry->Buffer
206 = ReceiveToken->Packet.RxData->FragmentTable[0].FragmentBuffer;
207 NewEntry->BufferSize
208 = ReceiveToken->Packet.RxData->FragmentTable[0].FragmentLength;
209
210 // Prepare to receive more data
211 SubmitRecieveToken();
212 } else {
213 // Fatal receive error. Put an entry with NULL in the queue, signifying
214 // to return EFI_DEVICE_ERROR from TcpFastbootTransportReceive.
215 NewEntry->Buffer = NULL;
216 NewEntry->BufferSize = 0;
217
218 DEBUG ((EFI_D_ERROR, "\nTCP Fastboot Receive error: %r\n", Status));
219 }
220
221 InsertTailList (&mPacketListHead, &NewEntry->Link);
222
223 Status = gBS->SignalEvent (mReceiveEvent);
224 ASSERT_EFI_ERROR (Status);
225 }
226
227
228 /*
229 Event notify function to be called when we accept an incoming TCP connection.
230 */
231 STATIC
232 VOID
233 EFIAPI
234 ConnectionAccepted (
235 IN EFI_EVENT Event,
236 IN VOID *Context
237 )
238 {
239 EFI_TCP4_LISTEN_TOKEN *AcceptToken;
240 EFI_STATUS Status;
241 UINTN Index;
242
243 AcceptToken = (EFI_TCP4_LISTEN_TOKEN *) Context;
244 Status = AcceptToken->CompletionToken.Status;
245
246 if (EFI_ERROR (Status)) {
247 DEBUG ((EFI_D_ERROR, "TCP Fastboot: Connection Error: %r\n", Status));
248 return;
249 }
250 DEBUG ((EFI_D_ERROR, "TCP Fastboot: Connection Received.\n"));
251
252 //
253 // Accepting a new TCP connection creates a new instance of the TCP protocol.
254 // Open it and prepare to receive on it.
255 //
256
257 Status = gBS->OpenProtocol (
258 AcceptToken->NewChildHandle,
259 &gEfiTcp4ProtocolGuid,
260 (VOID **) &mTcpConnection,
261 gImageHandle,
262 NULL,
263 EFI_OPEN_PROTOCOL_GET_PROTOCOL
264 );
265 if (EFI_ERROR (Status)) {
266 DEBUG ((EFI_D_ERROR, "Open TCP Connection: %r\n", Status));
267 return;
268 }
269
270 mNextSubmitIndex = 0;
271 mNextReceiveIndex = 0;
272
273 for (Index = 0; Index < NUM_RX_TOKENS; Index++) {
274 Status = gBS->CreateEvent (
275 EVT_NOTIFY_SIGNAL,
276 TPL_CALLBACK,
277 DataReceived,
278 NULL,
279 &(mReceiveToken[Index].CompletionToken.Event)
280 );
281 ASSERT_EFI_ERROR (Status);
282 }
283
284 for (Index = 0; Index < NUM_RX_TOKENS; Index++) {
285 SubmitRecieveToken();
286 }
287 }
288
289 /*
290 Set up TCP Fastboot transport: Configure the network device via DHCP then
291 start waiting for a TCP connection on the Fastboot port.
292 */
293 EFI_STATUS
294 TcpFastbootTransportStart (
295 EFI_EVENT ReceiveEvent
296 )
297 {
298 EFI_STATUS Status;
299 EFI_HANDLE NetDeviceHandle;
300 EFI_HANDLE *HandleBuffer;
301 EFI_IP4_MODE_DATA Ip4ModeData;
302 UINTN NumHandles;
303 CHAR16 IpAddrString[16];
304 UINTN Index;
305
306 EFI_TCP4_CONFIG_DATA TcpConfigData = {
307 0x00, // IPv4 Type of Service
308 255, // IPv4 Time to Live
309 { // AccessPoint:
310 TRUE, // Use default address
311 { {0, 0, 0, 0} }, // IP Address (ignored - use default)
312 { {0, 0, 0, 0} }, // Subnet mask (ignored - use default)
313 FixedPcdGet32 (PcdAndroidFastbootTcpPort), // Station port
314 { {0, 0, 0, 0} }, // Remote address: accept any
315 0, // Remote Port: accept any
316 FALSE // ActiveFlag: be a "server"
317 },
318 NULL // Default advanced TCP options
319 };
320
321 mReceiveEvent = ReceiveEvent;
322 InitializeListHead (&mPacketListHead);
323
324 mTextOut->OutputString (mTextOut, L"Initialising TCP Fastboot transport...\r\n");
325
326 //
327 // Open a passive TCP instance
328 //
329
330 Status = gBS->LocateHandleBuffer (
331 ByProtocol,
332 &gEfiTcp4ServiceBindingProtocolGuid,
333 NULL,
334 &NumHandles,
335 &HandleBuffer
336 );
337 if (EFI_ERROR (Status)) {
338 DEBUG ((EFI_D_ERROR, "Find TCP Service Binding: %r\n", Status));
339 return Status;
340 }
341
342 // We just use the first network device
343 NetDeviceHandle = HandleBuffer[0];
344
345 Status = gBS->OpenProtocol (
346 NetDeviceHandle,
347 &gEfiTcp4ServiceBindingProtocolGuid,
348 (VOID **) &mTcpServiceBinding,
349 gImageHandle,
350 NULL,
351 EFI_OPEN_PROTOCOL_GET_PROTOCOL
352 );
353 if (EFI_ERROR (Status)) {
354 DEBUG ((EFI_D_ERROR, "Open TCP Service Binding: %r\n", Status));
355 return Status;
356 }
357
358 Status = mTcpServiceBinding->CreateChild (mTcpServiceBinding, &mTcpHandle);
359 if (EFI_ERROR (Status)) {
360 DEBUG ((EFI_D_ERROR, "TCP ServiceBinding Create: %r\n", Status));
361 return Status;
362 }
363
364 Status = gBS->OpenProtocol (
365 mTcpHandle,
366 &gEfiTcp4ProtocolGuid,
367 (VOID **) &mTcpListener,
368 gImageHandle,
369 NULL,
370 EFI_OPEN_PROTOCOL_GET_PROTOCOL
371 );
372 if (EFI_ERROR (Status)) {
373 DEBUG ((EFI_D_ERROR, "Open TCP Protocol: %r\n", Status));
374 }
375
376 //
377 // Set up re-usable tokens
378 //
379
380 for (Index = 0; Index < NUM_RX_TOKENS; Index++) {
381 mRxData[Index].UrgentFlag = FALSE;
382 mRxData[Index].FragmentCount = 1;
383 mReceiveToken[Index].Packet.RxData = &mRxData[Index];
384 }
385
386 mTxData.Push = TRUE;
387 mTxData.Urgent = FALSE;
388 mTxData.FragmentCount = 1;
389 mTransmitToken.Packet.TxData = &mTxData;
390
391 Status = gBS->CreateEvent (
392 EVT_NOTIFY_SIGNAL,
393 TPL_CALLBACK,
394 ConnectionAccepted,
395 &mAcceptToken,
396 &mAcceptToken.CompletionToken.Event
397 );
398 ASSERT_EFI_ERROR (Status);
399
400 Status = gBS->CreateEvent (
401 EVT_NOTIFY_SIGNAL,
402 TPL_CALLBACK,
403 ConnectionClosed,
404 &mCloseToken,
405 &mCloseToken.CompletionToken.Event
406 );
407 ASSERT_EFI_ERROR (Status);
408
409 //
410 // Configure the TCP instance
411 //
412
413 Status = mTcpListener->Configure (mTcpListener, &TcpConfigData);
414 if (Status == EFI_NO_MAPPING) {
415 // Wait until the IP configuration process (probably DHCP) has finished
416 do {
417 Status = mTcpListener->GetModeData (mTcpListener,
418 NULL, NULL,
419 &Ip4ModeData,
420 NULL, NULL
421 );
422 ASSERT_EFI_ERROR (Status);
423 } while (!Ip4ModeData.IsConfigured);
424 Status = mTcpListener->Configure (mTcpListener, &TcpConfigData);
425 } else if (EFI_ERROR (Status)) {
426 DEBUG ((EFI_D_ERROR, "TCP Configure: %r\n", Status));
427 return Status;
428 }
429
430 //
431 // Tell the user our address and hostname
432 //
433 IP4_ADDR_TO_STRING (Ip4ModeData.ConfigData.StationAddress, IpAddrString);
434
435 mTextOut->OutputString (mTextOut, L"TCP Fastboot transport configured.");
436 mTextOut->OutputString (mTextOut, L"\r\nIP address: ");
437 mTextOut->OutputString (mTextOut ,IpAddrString);
438 mTextOut->OutputString (mTextOut, L"\r\n");
439
440 //
441 // Start listening for a connection
442 //
443
444 Status = mTcpListener->Accept (mTcpListener, &mAcceptToken);
445 if (EFI_ERROR (Status)) {
446 DEBUG ((EFI_D_ERROR, "TCP Accept: %r\n", Status));
447 return Status;
448 }
449
450 mTextOut->OutputString (mTextOut, L"TCP Fastboot transport initialised.\r\n");
451
452 FreePool (HandleBuffer);
453
454 return EFI_SUCCESS;
455 }
456
457 EFI_STATUS
458 TcpFastbootTransportStop (
459 VOID
460 )
461 {
462 EFI_TCP4_CLOSE_TOKEN CloseToken;
463 EFI_STATUS Status;
464 UINTN EventIndex;
465 FASTBOOT_TCP_PACKET_LIST *Entry;
466 FASTBOOT_TCP_PACKET_LIST *NextEntry;
467
468 // Close any existing TCP connection, blocking until it's done.
469 if (mTcpConnection != NULL) {
470 CloseReceiveEvents ();
471
472 CloseToken.AbortOnClose = FALSE;
473
474 Status = gBS->CreateEvent (0, 0, NULL, NULL, &CloseToken.CompletionToken.Event);
475 ASSERT_EFI_ERROR (Status);
476
477 Status = mTcpConnection->Close (mTcpConnection, &CloseToken);
478 ASSERT_EFI_ERROR (Status);
479
480 Status = gBS->WaitForEvent (
481 1,
482 &CloseToken.CompletionToken.Event,
483 &EventIndex
484 );
485 ASSERT_EFI_ERROR (Status);
486
487 ASSERT_EFI_ERROR (CloseToken.CompletionToken.Status);
488
489 // Possible bug in EDK2 TCP4 driver: closing a connection doesn't remove its
490 // PCB from the list of live connections. Subsequent attempts to Configure()
491 // a TCP instance with the same local port will fail with INVALID_PARAMETER.
492 // Calling Configure with NULL is a workaround for this issue.
493 Status = mTcpConnection->Configure (mTcpConnection, NULL);
494 ASSERT_EFI_ERROR (Status);
495 }
496
497
498 gBS->CloseEvent (mAcceptToken.CompletionToken.Event);
499
500 // Stop listening for connections.
501 // Ideally we would do this with Cancel, but it isn't implemented by EDK2.
502 // So we just "reset this TCPv4 instance brutally".
503 Status = mTcpListener->Configure (mTcpListener, NULL);
504 ASSERT_EFI_ERROR (Status);
505
506 Status = mTcpServiceBinding->DestroyChild (mTcpServiceBinding, &mTcpHandle);
507
508 // Free any data the user didn't pick up
509 Entry = (FASTBOOT_TCP_PACKET_LIST *) GetFirstNode (&mPacketListHead);
510 while (!IsNull (&mPacketListHead, &Entry->Link)) {
511 NextEntry = (FASTBOOT_TCP_PACKET_LIST *) GetNextNode (&mPacketListHead, &Entry->Link);
512
513 RemoveEntryList (&Entry->Link);
514 if (Entry->Buffer) {
515 FreePool (Entry->Buffer);
516 }
517 FreePool (Entry);
518
519 Entry = NextEntry;
520 }
521
522 return EFI_SUCCESS;
523 }
524
525 /*
526 Event notify function for when data has been sent. Free resources and report
527 errors.
528 Context should point to the transmit IO token passed to
529 TcpConnection->Transmit.
530 */
531 STATIC
532 VOID
533 DataSent (
534 EFI_EVENT Event,
535 VOID *Context
536 )
537 {
538 EFI_STATUS Status;
539
540 Status = mTransmitToken.CompletionToken.Status;
541 if (EFI_ERROR (Status)) {
542 DEBUG ((EFI_D_ERROR, "TCP Fastboot transmit result: %r\n", Status));
543 gBS->SignalEvent (*(EFI_EVENT *) Context);
544 }
545
546 FreePool (mTransmitToken.Packet.TxData->FragmentTable[0].FragmentBuffer);
547 }
548
549 EFI_STATUS
550 TcpFastbootTransportSend (
551 IN UINTN BufferSize,
552 IN CONST VOID *Buffer,
553 IN EFI_EVENT *FatalErrorEvent
554 )
555 {
556 EFI_STATUS Status;
557
558 if (BufferSize > 512) {
559 return EFI_INVALID_PARAMETER;
560 }
561
562 //
563 // Build transmit IO token
564 //
565
566 // Create an event so we are notified when a transmission is complete.
567 // We use this to free resources and report errors.
568 Status = gBS->CreateEvent (
569 EVT_NOTIFY_SIGNAL,
570 TPL_CALLBACK,
571 DataSent,
572 FatalErrorEvent,
573 &mTransmitToken.CompletionToken.Event
574 );
575 ASSERT_EFI_ERROR (Status);
576
577 mTxData.DataLength = BufferSize;
578
579 mTxData.FragmentTable[0].FragmentLength = BufferSize;
580 mTxData.FragmentTable[0].FragmentBuffer = AllocateCopyPool (
581 BufferSize,
582 Buffer
583 );
584
585 Status = mTcpConnection->Transmit (mTcpConnection, &mTransmitToken);
586 if (EFI_ERROR (Status)) {
587 DEBUG ((EFI_D_ERROR, "TCP Transmit: %r\n", Status));
588 return Status;
589 }
590
591 return EFI_SUCCESS;
592 }
593
594
595 EFI_STATUS
596 TcpFastbootTransportReceive (
597 OUT UINTN *BufferSize,
598 OUT VOID **Buffer
599 )
600 {
601 FASTBOOT_TCP_PACKET_LIST *Entry;
602
603 if (IsListEmpty (&mPacketListHead)) {
604 return EFI_NOT_READY;
605 }
606
607 Entry = (FASTBOOT_TCP_PACKET_LIST *) GetFirstNode (&mPacketListHead);
608
609 if (Entry->Buffer == NULL) {
610 // There was an error receiving this packet.
611 return EFI_DEVICE_ERROR;
612 }
613
614 *Buffer = Entry->Buffer;
615 *BufferSize = Entry->BufferSize;
616
617 RemoveEntryList (&Entry->Link);
618 FreePool (Entry);
619
620 return EFI_SUCCESS;
621 }
622
623 FASTBOOT_TRANSPORT_PROTOCOL mTransportProtocol = {
624 TcpFastbootTransportStart,
625 TcpFastbootTransportStop,
626 TcpFastbootTransportSend,
627 TcpFastbootTransportReceive
628 };
629
630 EFI_STATUS
631 TcpFastbootTransportEntryPoint (
632 IN EFI_HANDLE ImageHandle,
633 IN EFI_SYSTEM_TABLE *SystemTable
634 )
635 {
636 EFI_STATUS Status;
637
638
639 Status = gBS->LocateProtocol(
640 &gEfiSimpleTextOutProtocolGuid,
641 NULL,
642 (VOID **) &mTextOut
643 );
644 if (EFI_ERROR (Status)) {
645 DEBUG ((EFI_D_ERROR, "Fastboot: Open Text Output Protocol: %r\n", Status));
646 return Status;
647 }
648
649 Status = gBS->InstallProtocolInterface (
650 &ImageHandle,
651 &gAndroidFastbootTransportProtocolGuid,
652 EFI_NATIVE_INTERFACE,
653 &mTransportProtocol
654 );
655 if (EFI_ERROR (Status)) {
656 DEBUG ((EFI_D_ERROR, "Fastboot: Install transport Protocol: %r\n", Status));
657 }
658
659 return Status;
660 }