1 /** @file
2   This file implements protocol interfaces for ATA bus driver.
3 
4   This file implements protocol interfaces: Driver Binding protocol,
5   Block IO protocol and DiskInfo protocol.
6 
7   Copyright (c) 2009 - 2015, Intel Corporation. All rights reserved.<BR>
8   SPDX-License-Identifier: BSD-2-Clause-Patent
9 
10 
11 **/
12 
13 #include "AtaBus.h"
14 
15 //
16 // ATA Bus Driver Binding Protocol Instance
17 //
18 EFI_DRIVER_BINDING_PROTOCOL gAtaBusDriverBinding = {
19   AtaBusDriverBindingSupported,
20   AtaBusDriverBindingStart,
21   AtaBusDriverBindingStop,
22   0x10,
23   NULL,
24   NULL
25 };
26 
27 //
28 // Template for ATA Child Device.
29 //
30 ATA_DEVICE gAtaDeviceTemplate = {
31   ATA_DEVICE_SIGNATURE,        // Signature
32   NULL,                        // Handle
33   {                            // BlockIo
34     EFI_BLOCK_IO_PROTOCOL_REVISION,
35     NULL,
36     AtaBlockIoReset,
37     AtaBlockIoReadBlocks,
38     AtaBlockIoWriteBlocks,
39     AtaBlockIoFlushBlocks
40   },
41   {                            // BlockIo2
42     NULL,
43     AtaBlockIoResetEx,
44     AtaBlockIoReadBlocksEx,
45     AtaBlockIoWriteBlocksEx,
46     AtaBlockIoFlushBlocksEx
47   },
48   {                            // BlockMedia
49     0,                         // MediaId
50     FALSE,                     // RemovableMedia
51     TRUE,                      // MediaPresent
52     FALSE,                     // LogicPartition
53     FALSE,                     // ReadOnly
54     FALSE,                     // WritingCache
55     0x200,                     // BlockSize
56     0,                         // IoAlign
57     0,                         // LastBlock
58     0,                         // LowestAlignedLba
59     1                          // LogicalBlocksPerPhysicalBlock
60   },
61   {                            // DiskInfo
62     EFI_DISK_INFO_IDE_INTERFACE_GUID,
63     AtaDiskInfoInquiry,
64     AtaDiskInfoIdentify,
65     AtaDiskInfoSenseData,
66     AtaDiskInfoWhichIde
67   },
68   NULL,                        // DevicePath
69   {
70     AtaStorageSecurityReceiveData,
71     AtaStorageSecuritySendData
72   },
73   NULL,                        // AtaBusDriverData
74   0,                           // Port
75   0,                           // PortMultiplierPort
76   { 0, },                      // Packet
77   {{ 0}, },                    // Acb
78   NULL,                        // Asb
79   FALSE,                       // UdmaValid
80   FALSE,                       // Lba48Bit
81   NULL,                        // IdentifyData
82   NULL,                        // ControllerNameTable
83   {L'\0', },                   // ModelName
84   {NULL, NULL},                // AtaTaskList
85   {NULL, NULL},                // AtaSubTaskList
86   FALSE                        // Abort
87 };
88 
89 /**
90   Allocates an aligned buffer for ATA device.
91 
92   This function allocates an aligned buffer for the ATA device to perform
93   ATA pass through operations. The alignment requirement is from ATA pass
94   through interface.
95 
96   @param  AtaDevice         The ATA child device involved for the operation.
97   @param  BufferSize        The request buffer size.
98 
99   @return A pointer to the aligned buffer or NULL if the allocation fails.
100 
101 **/
102 VOID *
AllocateAlignedBuffer(IN ATA_DEVICE * AtaDevice,IN UINTN BufferSize)103 AllocateAlignedBuffer (
104   IN ATA_DEVICE               *AtaDevice,
105   IN UINTN                    BufferSize
106   )
107 {
108   return AllocateAlignedPages (EFI_SIZE_TO_PAGES (BufferSize), AtaDevice->AtaBusDriverData->AtaPassThru->Mode->IoAlign);
109 }
110 
111 /**
112   Frees an aligned buffer for ATA device.
113 
114   This function frees an aligned buffer for the ATA device to perform
115   ATA pass through operations.
116 
117   @param  Buffer            The aligned buffer to be freed.
118   @param  BufferSize        The request buffer size.
119 
120 **/
121 VOID
FreeAlignedBuffer(IN VOID * Buffer,IN UINTN BufferSize)122 FreeAlignedBuffer (
123   IN VOID                     *Buffer,
124   IN UINTN                    BufferSize
125   )
126 {
127   if (Buffer != NULL) {
128     FreeAlignedPages (Buffer, EFI_SIZE_TO_PAGES (BufferSize));
129   }
130 }
131 
132 
133 /**
134   Release all the resources allocated for the ATA device.
135 
136   This function releases all the resources allocated for the ATA device.
137 
138   @param  AtaDevice         The ATA child device involved for the operation.
139 
140 **/
141 VOID
ReleaseAtaResources(IN ATA_DEVICE * AtaDevice)142 ReleaseAtaResources (
143   IN ATA_DEVICE  *AtaDevice
144   )
145 {
146   ATA_BUS_ASYN_SUB_TASK *SubTask;
147   ATA_BUS_ASYN_TASK     *AtaTask;
148   LIST_ENTRY            *Entry;
149   LIST_ENTRY            *DelEntry;
150   EFI_TPL               OldTpl;
151 
152   FreeUnicodeStringTable (AtaDevice->ControllerNameTable);
153   FreeAlignedBuffer (AtaDevice->Asb, sizeof (EFI_ATA_STATUS_BLOCK));
154   FreeAlignedBuffer (AtaDevice->IdentifyData, sizeof (ATA_IDENTIFY_DATA));
155   if (AtaDevice->DevicePath != NULL) {
156     FreePool (AtaDevice->DevicePath);
157   }
158   OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
159   if (!IsListEmpty (&AtaDevice->AtaSubTaskList)) {
160     //
161     // Free the Subtask list.
162     //
163     for(Entry = AtaDevice->AtaSubTaskList.ForwardLink;
164         Entry != (&AtaDevice->AtaSubTaskList);
165        ) {
166       DelEntry = Entry;
167       Entry    = Entry->ForwardLink;
168       SubTask  = ATA_ASYN_SUB_TASK_FROM_ENTRY (DelEntry);
169 
170       RemoveEntryList (DelEntry);
171       FreeAtaSubTask (SubTask);
172     }
173   }
174   if (!IsListEmpty (&AtaDevice->AtaTaskList)) {
175     //
176     // Free the Subtask list.
177     //
178     for(Entry = AtaDevice->AtaTaskList.ForwardLink;
179         Entry != (&AtaDevice->AtaTaskList);
180        ) {
181       DelEntry = Entry;
182       Entry    = Entry->ForwardLink;
183       AtaTask  = ATA_ASYN_TASK_FROM_ENTRY (DelEntry);
184 
185       RemoveEntryList (DelEntry);
186       FreePool (AtaTask);
187     }
188   }
189   gBS->RestoreTPL (OldTpl);
190   FreePool (AtaDevice);
191 }
192 
193 
194 /**
195   Registers an ATA device.
196 
197   This function allocates an ATA device structure for the ATA device specified by
198   Port and PortMultiplierPort if the ATA device is identified as a valid one.
199   Then it will create child handle and install Block IO and Disk Info protocol on
200   it.
201 
202   @param  AtaBusDriverData      The parent ATA bus driver data structure.
203   @param  Port                  The port number of the ATA device.
204   @param  PortMultiplierPort    The port multiplier port number of the ATA device.
205 
206   @retval EFI_SUCCESS           The ATA device is successfully registered.
207   @retval EFI_OUT_OF_RESOURCES  There is not enough memory to allocate the ATA device
208                                 and related data structures.
209   @return Others                Some error occurs when registering the ATA device.
210 **/
211 EFI_STATUS
RegisterAtaDevice(IN OUT ATA_BUS_DRIVER_DATA * AtaBusDriverData,IN UINT16 Port,IN UINT16 PortMultiplierPort)212 RegisterAtaDevice (
213   IN OUT ATA_BUS_DRIVER_DATA        *AtaBusDriverData,
214   IN     UINT16                     Port,
215   IN     UINT16                     PortMultiplierPort
216   )
217 {
218   EFI_STATUS                        Status;
219   ATA_DEVICE                        *AtaDevice;
220   EFI_ATA_PASS_THRU_PROTOCOL        *AtaPassThru;
221   EFI_DEVICE_PATH_PROTOCOL          *NewDevicePathNode;
222   EFI_DEVICE_PATH_PROTOCOL          *DevicePath;
223   EFI_DEVICE_PATH_PROTOCOL          *RemainingDevicePath;
224   EFI_HANDLE                        DeviceHandle;
225 
226   AtaDevice         = NULL;
227   NewDevicePathNode = NULL;
228   DevicePath        = NULL;
229   RemainingDevicePath = NULL;
230 
231   //
232   // Build device path
233   //
234   AtaPassThru = AtaBusDriverData->AtaPassThru;
235   Status = AtaPassThru->BuildDevicePath (AtaPassThru, Port, PortMultiplierPort, &NewDevicePathNode);
236   if (EFI_ERROR (Status)) {
237     goto Done;
238   }
239 
240   DevicePath = AppendDevicePathNode (AtaBusDriverData->ParentDevicePath, NewDevicePathNode);
241   if (DevicePath == NULL) {
242     Status = EFI_OUT_OF_RESOURCES;
243     goto Done;
244   }
245 
246   DeviceHandle = NULL;
247   RemainingDevicePath = DevicePath;
248   Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &RemainingDevicePath, &DeviceHandle);
249   if (!EFI_ERROR (Status) && (DeviceHandle != NULL) && IsDevicePathEnd(RemainingDevicePath)) {
250     Status = EFI_ALREADY_STARTED;
251     FreePool (DevicePath);
252     goto Done;
253   }
254 
255   //
256   // Allocate ATA device from the template.
257   //
258   AtaDevice = AllocateCopyPool (sizeof (ATA_DEVICE), &gAtaDeviceTemplate);
259   if (AtaDevice == NULL) {
260     Status = EFI_OUT_OF_RESOURCES;
261     goto Done;
262   }
263 
264   //
265   // Initializes ATA device structures and allocates the required buffer.
266   //
267   AtaDevice->BlockIo.Media      = &AtaDevice->BlockMedia;
268   AtaDevice->BlockIo2.Media     = &AtaDevice->BlockMedia;
269   AtaDevice->AtaBusDriverData   = AtaBusDriverData;
270   AtaDevice->DevicePath         = DevicePath;
271   AtaDevice->Port               = Port;
272   AtaDevice->PortMultiplierPort = PortMultiplierPort;
273   AtaDevice->Asb = AllocateAlignedBuffer (AtaDevice, sizeof (EFI_ATA_STATUS_BLOCK));
274   if (AtaDevice->Asb == NULL) {
275     Status = EFI_OUT_OF_RESOURCES;
276     goto Done;
277   }
278   AtaDevice->IdentifyData = AllocateAlignedBuffer (AtaDevice, sizeof (ATA_IDENTIFY_DATA));
279   if (AtaDevice->IdentifyData == NULL) {
280     Status = EFI_OUT_OF_RESOURCES;
281     goto Done;
282   }
283 
284   //
285   // Initial Ata Task List
286   //
287   InitializeListHead (&AtaDevice->AtaTaskList);
288   InitializeListHead (&AtaDevice->AtaSubTaskList);
289 
290   //
291   // Report Status Code to indicate the ATA device will be enabled
292   //
293   REPORT_STATUS_CODE_WITH_DEVICE_PATH (
294     EFI_PROGRESS_CODE,
295     (EFI_IO_BUS_ATA_ATAPI | EFI_IOB_PC_ENABLE),
296     AtaBusDriverData->ParentDevicePath
297     );
298 
299   //
300   // Try to identify the ATA device via the ATA pass through command.
301   //
302   Status = DiscoverAtaDevice (AtaDevice);
303   if (EFI_ERROR (Status)) {
304     goto Done;
305   }
306 
307   //
308   // Build controller name for Component Name (2) protocol.
309   //
310   Status = AddUnicodeString2 (
311              "eng",
312              gAtaBusComponentName.SupportedLanguages,
313              &AtaDevice->ControllerNameTable,
314              AtaDevice->ModelName,
315              TRUE
316              );
317   if (EFI_ERROR (Status)) {
318     goto Done;
319   }
320 
321   Status = AddUnicodeString2 (
322              "en",
323              gAtaBusComponentName2.SupportedLanguages,
324              &AtaDevice->ControllerNameTable,
325              AtaDevice->ModelName,
326              FALSE
327              );
328   if (EFI_ERROR (Status)) {
329     goto Done;
330   }
331 
332   //
333   // Update to AHCI interface GUID based on device path node. The default one
334   // is IDE interface GUID copied from template.
335   //
336   if (NewDevicePathNode->SubType == MSG_SATA_DP) {
337     CopyGuid (&AtaDevice->DiskInfo.Interface, &gEfiDiskInfoAhciInterfaceGuid);
338   }
339 
340   Status = gBS->InstallMultipleProtocolInterfaces (
341                   &AtaDevice->Handle,
342                   &gEfiDevicePathProtocolGuid,
343                   AtaDevice->DevicePath,
344                   &gEfiBlockIoProtocolGuid,
345                   &AtaDevice->BlockIo,
346                   &gEfiBlockIo2ProtocolGuid,
347                   &AtaDevice->BlockIo2,
348                   &gEfiDiskInfoProtocolGuid,
349                   &AtaDevice->DiskInfo,
350                   NULL
351                   );
352   if (EFI_ERROR (Status)) {
353     goto Done;
354   }
355 
356   //
357   // See if the ata device support trust computing feature or not.
358   // If yes, then install Storage Security Protocol at the ata device handle.
359   //
360   if ((AtaDevice->IdentifyData->trusted_computing_support & BIT0) != 0) {
361     DEBUG ((EFI_D_INFO, "Found TCG support in Port %x PortMultiplierPort %x\n", Port, PortMultiplierPort));
362     Status = gBS->InstallProtocolInterface (
363                     &AtaDevice->Handle,
364                     &gEfiStorageSecurityCommandProtocolGuid,
365                     EFI_NATIVE_INTERFACE,
366                     &AtaDevice->StorageSecurity
367                     );
368     if (EFI_ERROR (Status)) {
369       goto Done;
370     }
371     DEBUG ((EFI_D_INFO, "Successfully Install Storage Security Protocol on the ATA device\n"));
372   }
373 
374   gBS->OpenProtocol (
375          AtaBusDriverData->Controller,
376          &gEfiAtaPassThruProtocolGuid,
377          (VOID **) &AtaPassThru,
378          AtaBusDriverData->DriverBindingHandle,
379          AtaDevice->Handle,
380          EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER
381          );
382 
383 Done:
384   if (NewDevicePathNode != NULL) {
385     FreePool (NewDevicePathNode);
386   }
387 
388   if (EFI_ERROR (Status) && (AtaDevice != NULL)) {
389     ReleaseAtaResources (AtaDevice);
390     DEBUG ((EFI_D_ERROR | EFI_D_INIT, "Failed to initialize Port %x PortMultiplierPort %x, status = %r\n", Port, PortMultiplierPort, Status));
391   }
392   return Status;
393 }
394 
395 
396 /**
397   Unregisters an ATA device.
398 
399   This function removes the protocols installed on the controller handle and
400   frees the resources allocated for the ATA device.
401 
402   @param  This                  The pointer to EFI_DRIVER_BINDING_PROTOCOL instance.
403   @param  Controller            The controller handle of the ATA device.
404   @param  Handle                The child handle.
405 
406   @retval EFI_SUCCESS           The ATA device is successfully unregistered.
407   @return Others                Some error occurs when unregistering the ATA device.
408 
409 **/
410 EFI_STATUS
UnregisterAtaDevice(IN EFI_DRIVER_BINDING_PROTOCOL * This,IN EFI_HANDLE Controller,IN EFI_HANDLE Handle)411 UnregisterAtaDevice (
412   IN  EFI_DRIVER_BINDING_PROTOCOL    *This,
413   IN  EFI_HANDLE                     Controller,
414   IN  EFI_HANDLE                     Handle
415   )
416 {
417   EFI_STATUS                               Status;
418   EFI_BLOCK_IO_PROTOCOL                    *BlockIo;
419   EFI_BLOCK_IO2_PROTOCOL                   *BlockIo2;
420   ATA_DEVICE                               *AtaDevice;
421   EFI_ATA_PASS_THRU_PROTOCOL               *AtaPassThru;
422   EFI_STORAGE_SECURITY_COMMAND_PROTOCOL    *StorageSecurity;
423 
424   BlockIo2             =     NULL;
425   BlockIo              =     NULL;
426 
427   Status = gBS->OpenProtocol (
428                   Handle,
429                   &gEfiBlockIoProtocolGuid,
430                   (VOID **) &BlockIo,
431                   This->DriverBindingHandle,
432                   Controller,
433                   EFI_OPEN_PROTOCOL_GET_PROTOCOL
434                   );
435   if (EFI_ERROR (Status)) {
436     //
437     // Locate BlockIo2 protocol
438     //
439     Status = gBS->OpenProtocol (
440                     Handle,
441                     &gEfiBlockIo2ProtocolGuid,
442                     (VOID **) &BlockIo2,
443                     This->DriverBindingHandle,
444                     Controller,
445                     EFI_OPEN_PROTOCOL_GET_PROTOCOL
446                     );
447     if (EFI_ERROR (Status)) {
448       return Status;
449     }
450   }
451 
452   //
453   // Get AtaDevice data.
454   //
455   if (BlockIo != NULL) {
456     AtaDevice = ATA_DEVICE_FROM_BLOCK_IO (BlockIo);
457   } else {
458     ASSERT (BlockIo2 != NULL);
459     AtaDevice = ATA_DEVICE_FROM_BLOCK_IO2 (BlockIo2);
460   }
461 
462   //
463   // Close the child handle
464   //
465   gBS->CloseProtocol (
466          Controller,
467          &gEfiAtaPassThruProtocolGuid,
468          This->DriverBindingHandle,
469          Handle
470          );
471 
472   //
473   // The Ata Bus driver installs the BlockIo and BlockIo2 in the DriverBindingStart().
474   // Here should uninstall both of them.
475   //
476   Status = gBS->UninstallMultipleProtocolInterfaces (
477                   Handle,
478                   &gEfiDevicePathProtocolGuid,
479                   AtaDevice->DevicePath,
480                   &gEfiBlockIoProtocolGuid,
481                   &AtaDevice->BlockIo,
482                   &gEfiBlockIo2ProtocolGuid,
483                   &AtaDevice->BlockIo2,
484                   &gEfiDiskInfoProtocolGuid,
485                   &AtaDevice->DiskInfo,
486                   NULL
487                   );
488 
489   if (EFI_ERROR (Status)) {
490     gBS->OpenProtocol (
491           Controller,
492           &gEfiAtaPassThruProtocolGuid,
493           (VOID **) &AtaPassThru,
494           This->DriverBindingHandle,
495           Handle,
496           EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER
497           );
498     return Status;
499   }
500 
501   //
502   // If Storage Security Command Protocol is installed, then uninstall this protocol.
503   //
504   Status = gBS->OpenProtocol (
505                   Handle,
506                   &gEfiStorageSecurityCommandProtocolGuid,
507                   (VOID **) &StorageSecurity,
508                   This->DriverBindingHandle,
509                   Controller,
510                   EFI_OPEN_PROTOCOL_GET_PROTOCOL
511                   );
512 
513   if (!EFI_ERROR (Status)) {
514     Status = gBS->UninstallProtocolInterface (
515                     Handle,
516                     &gEfiStorageSecurityCommandProtocolGuid,
517                     &AtaDevice->StorageSecurity
518                     );
519     if (EFI_ERROR (Status)) {
520       gBS->OpenProtocol (
521         Controller,
522         &gEfiAtaPassThruProtocolGuid,
523         (VOID **) &AtaPassThru,
524         This->DriverBindingHandle,
525         Handle,
526         EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER
527         );
528       return Status;
529     }
530   }
531 
532   ReleaseAtaResources (AtaDevice);
533   return EFI_SUCCESS;
534 }
535 
536 
537 
538 /**
539   Tests to see if this driver supports a given controller. If a child device is provided,
540   it further tests to see if this driver supports creating a handle for the specified child device.
541 
542   This function checks to see if the driver specified by This supports the device specified by
543   ControllerHandle. Drivers will typically use the device path attached to
544   ControllerHandle and/or the services from the bus I/O abstraction attached to
545   ControllerHandle to determine if the driver supports ControllerHandle. This function
546   may be called many times during platform initialization. In order to reduce boot times, the tests
547   performed by this function must be very small, and take as little time as possible to execute. This
548   function must not change the state of any hardware devices, and this function must be aware that the
549   device specified by ControllerHandle may already be managed by the same driver or a
550   different driver. This function must match its calls to AllocatePages() with FreePages(),
551   AllocatePool() with FreePool(), and OpenProtocol() with CloseProtocol().
552   Since ControllerHandle may have been previously started by the same driver, if a protocol is
553   already in the opened state, then it must not be closed with CloseProtocol(). This is required
554   to guarantee the state of ControllerHandle is not modified by this function.
555 
556   @param[in]  This                 A pointer to the EFI_DRIVER_BINDING_PROTOCOL instance.
557   @param[in]  ControllerHandle     The handle of the controller to test. This handle
558                                    must support a protocol interface that supplies
559                                    an I/O abstraction to the driver.
560   @param[in]  RemainingDevicePath  A pointer to the remaining portion of a device path.  This
561                                    parameter is ignored by device drivers, and is optional for bus
562                                    drivers. For bus drivers, if this parameter is not NULL, then
563                                    the bus driver must determine if the bus controller specified
564                                    by ControllerHandle and the child controller specified
565                                    by RemainingDevicePath are both supported by this
566                                    bus driver.
567 
568   @retval EFI_SUCCESS              The device specified by ControllerHandle and
569                                    RemainingDevicePath is supported by the driver specified by This.
570   @retval EFI_ALREADY_STARTED      The device specified by ControllerHandle and
571                                    RemainingDevicePath is already being managed by the driver
572                                    specified by This.
573   @retval EFI_ACCESS_DENIED        The device specified by ControllerHandle and
574                                    RemainingDevicePath is already being managed by a different
575                                    driver or an application that requires exclusive access.
576                                    Currently not implemented.
577   @retval EFI_UNSUPPORTED          The device specified by ControllerHandle and
578                                    RemainingDevicePath is not supported by the driver specified by This.
579 **/
580 EFI_STATUS
581 EFIAPI
AtaBusDriverBindingSupported(IN EFI_DRIVER_BINDING_PROTOCOL * This,IN EFI_HANDLE Controller,IN EFI_DEVICE_PATH_PROTOCOL * RemainingDevicePath)582 AtaBusDriverBindingSupported (
583   IN EFI_DRIVER_BINDING_PROTOCOL  *This,
584   IN EFI_HANDLE                   Controller,
585   IN EFI_DEVICE_PATH_PROTOCOL     *RemainingDevicePath
586   )
587 {
588   EFI_STATUS                        Status;
589   EFI_DEVICE_PATH_PROTOCOL          *ParentDevicePath;
590   EFI_ATA_PASS_THRU_PROTOCOL        *AtaPassThru;
591   UINT16                            Port;
592   UINT16                            PortMultiplierPort;
593 
594   //
595   // Test EFI_ATA_PASS_THRU_PROTOCOL on controller handle.
596   //
597   Status = gBS->OpenProtocol (
598                   Controller,
599                   &gEfiAtaPassThruProtocolGuid,
600                   (VOID **) &AtaPassThru,
601                   This->DriverBindingHandle,
602                   Controller,
603                   EFI_OPEN_PROTOCOL_BY_DRIVER
604                   );
605 
606   if (Status == EFI_ALREADY_STARTED) {
607     return EFI_SUCCESS;
608   }
609 
610   if (EFI_ERROR (Status)) {
611     return Status;
612   }
613 
614   //
615   // Test to see if this ATA Pass Thru Protocol is for a LOGICAL channel
616   //
617   if ((AtaPassThru->Mode->Attributes & EFI_ATA_PASS_THRU_ATTRIBUTES_LOGICAL) == 0) {
618     //
619     // Close the I/O Abstraction(s) used to perform the supported test
620     //
621     gBS->CloseProtocol (
622           Controller,
623           &gEfiAtaPassThruProtocolGuid,
624           This->DriverBindingHandle,
625           Controller
626           );
627     return EFI_UNSUPPORTED;
628   }
629 
630   //
631   // Test RemainingDevicePath is valid or not.
632   //
633   if ((RemainingDevicePath != NULL) && !IsDevicePathEnd (RemainingDevicePath)) {
634     Status = AtaPassThru->GetDevice (AtaPassThru, RemainingDevicePath, &Port, &PortMultiplierPort);
635     if (EFI_ERROR (Status)) {
636       //
637       // Close the I/O Abstraction(s) used to perform the supported test
638       //
639       gBS->CloseProtocol (
640             Controller,
641             &gEfiAtaPassThruProtocolGuid,
642             This->DriverBindingHandle,
643             Controller
644             );
645       return Status;
646     }
647   }
648 
649   //
650   // Close the I/O Abstraction(s) used to perform the supported test
651   //
652   gBS->CloseProtocol (
653         Controller,
654         &gEfiAtaPassThruProtocolGuid,
655         This->DriverBindingHandle,
656         Controller
657         );
658 
659   //
660   // Open the EFI Device Path protocol needed to perform the supported test
661   //
662   Status = gBS->OpenProtocol (
663                   Controller,
664                   &gEfiDevicePathProtocolGuid,
665                   (VOID **) &ParentDevicePath,
666                   This->DriverBindingHandle,
667                   Controller,
668                   EFI_OPEN_PROTOCOL_GET_PROTOCOL
669                   );
670   return Status;
671 }
672 
673 
674 /**
675   Starts a device controller or a bus controller.
676 
677   The Start() function is designed to be invoked from the EFI boot service ConnectController().
678   As a result, much of the error checking on the parameters to Start() has been moved into this
679   common boot service. It is legal to call Start() from other locations,
680   but the following calling restrictions must be followed or the system behavior will not be deterministic.
681   1. ControllerHandle must be a valid EFI_HANDLE.
682   2. If RemainingDevicePath is not NULL, then it must be a pointer to a naturally aligned
683      EFI_DEVICE_PATH_PROTOCOL.
684   3. Prior to calling Start(), the Supported() function for the driver specified by This must
685      have been called with the same calling parameters, and Supported() must have returned EFI_SUCCESS.
686 
687   @param[in]  This                 A pointer to the EFI_DRIVER_BINDING_PROTOCOL instance.
688   @param[in]  ControllerHandle     The handle of the controller to start. This handle
689                                    must support a protocol interface that supplies
690                                    an I/O abstraction to the driver.
691   @param[in]  RemainingDevicePath  A pointer to the remaining portion of a device path.  This
692                                    parameter is ignored by device drivers, and is optional for bus
693                                    drivers. For a bus driver, if this parameter is NULL, then handles
694                                    for all the children of Controller are created by this driver.
695                                    If this parameter is not NULL and the first Device Path Node is
696                                    not the End of Device Path Node, then only the handle for the
697                                    child device specified by the first Device Path Node of
698                                    RemainingDevicePath is created by this driver.
699                                    If the first Device Path Node of RemainingDevicePath is
700                                    the End of Device Path Node, no child handle is created by this
701                                    driver.
702 
703   @retval EFI_SUCCESS              The device was started.
704   @retval EFI_DEVICE_ERROR         The device could not be started due to a device error.Currently not implemented.
705   @retval EFI_OUT_OF_RESOURCES     The request could not be completed due to a lack of resources.
706   @retval Others                   The driver failded to start the device.
707 
708 **/
709 EFI_STATUS
710 EFIAPI
AtaBusDriverBindingStart(IN EFI_DRIVER_BINDING_PROTOCOL * This,IN EFI_HANDLE Controller,IN EFI_DEVICE_PATH_PROTOCOL * RemainingDevicePath)711 AtaBusDriverBindingStart (
712   IN EFI_DRIVER_BINDING_PROTOCOL  *This,
713   IN EFI_HANDLE                   Controller,
714   IN EFI_DEVICE_PATH_PROTOCOL     *RemainingDevicePath
715   )
716 {
717   EFI_STATUS                        Status;
718   EFI_ATA_PASS_THRU_PROTOCOL        *AtaPassThru;
719   EFI_DEVICE_PATH_PROTOCOL          *ParentDevicePath;
720   ATA_BUS_DRIVER_DATA               *AtaBusDriverData;
721   UINT16                            Port;
722   UINT16                            PortMultiplierPort;
723 
724   AtaBusDriverData = NULL;
725 
726   Status = gBS->OpenProtocol (
727                   Controller,
728                   &gEfiDevicePathProtocolGuid,
729                   (VOID **) &ParentDevicePath,
730                   This->DriverBindingHandle,
731                   Controller,
732                   EFI_OPEN_PROTOCOL_GET_PROTOCOL
733                   );
734   if (EFI_ERROR (Status)) {
735     return Status;
736   }
737 
738   //
739   // Report Status Code to indicate ATA bus starts
740   //
741   REPORT_STATUS_CODE_WITH_DEVICE_PATH (
742     EFI_PROGRESS_CODE,
743     (EFI_IO_BUS_ATA_ATAPI | EFI_IOB_PC_INIT),
744     ParentDevicePath
745     );
746 
747   Status = gBS->OpenProtocol (
748                   Controller,
749                   &gEfiAtaPassThruProtocolGuid,
750                   (VOID **) &AtaPassThru,
751                   This->DriverBindingHandle,
752                   Controller,
753                   EFI_OPEN_PROTOCOL_BY_DRIVER
754                   );
755   if ((EFI_ERROR (Status)) && (Status != EFI_ALREADY_STARTED)) {
756     goto ErrorExit;
757   }
758 
759   //
760   // Check EFI_ALREADY_STARTED to reuse the original ATA_BUS_DRIVER_DATA.
761   //
762   if (Status != EFI_ALREADY_STARTED) {
763     AtaBusDriverData = AllocateZeroPool (sizeof (ATA_BUS_DRIVER_DATA));
764     if (AtaBusDriverData == NULL) {
765       Status = EFI_OUT_OF_RESOURCES;
766       goto ErrorExit;
767     }
768 
769     AtaBusDriverData->AtaPassThru = AtaPassThru;
770     AtaBusDriverData->Controller  = Controller;
771     AtaBusDriverData->ParentDevicePath = ParentDevicePath;
772     AtaBusDriverData->DriverBindingHandle = This->DriverBindingHandle;
773 
774     Status = gBS->InstallMultipleProtocolInterfaces (
775                     &Controller,
776                     &gEfiCallerIdGuid,
777                     AtaBusDriverData,
778                     NULL
779                     );
780     if (EFI_ERROR (Status)) {
781       goto ErrorExit;
782     }
783 
784   } else {
785     Status = gBS->OpenProtocol (
786                     Controller,
787                     &gEfiCallerIdGuid,
788                     (VOID **) &AtaBusDriverData,
789                     This->DriverBindingHandle,
790                     Controller,
791                     EFI_OPEN_PROTOCOL_GET_PROTOCOL
792                     );
793     if (EFI_ERROR (Status)) {
794       AtaBusDriverData = NULL;
795       goto ErrorExit;
796     }
797   }
798 
799   //
800   // Report Status Code to indicate detecting devices on bus
801   //
802   REPORT_STATUS_CODE_WITH_DEVICE_PATH (
803     EFI_PROGRESS_CODE,
804     (EFI_IO_BUS_ATA_ATAPI | EFI_IOB_PC_DETECT),
805     ParentDevicePath
806     );
807 
808   if (RemainingDevicePath == NULL) {
809     Port = 0xFFFF;
810     while (TRUE) {
811       Status = AtaPassThru->GetNextPort (AtaPassThru, &Port);
812       if (EFI_ERROR (Status)) {
813         //
814         // We cannot find more legal port then we are done.
815         //
816         break;
817       }
818 
819       PortMultiplierPort = 0xFFFF;
820       while (TRUE) {
821         Status = AtaPassThru->GetNextDevice (AtaPassThru, Port, &PortMultiplierPort);
822         if (EFI_ERROR (Status)) {
823           //
824           // We cannot find more legal port multiplier port number for ATA device
825           // on the port, then we are done.
826           //
827           break;
828         }
829         RegisterAtaDevice (AtaBusDriverData, Port, PortMultiplierPort);
830       }
831     }
832     Status = EFI_SUCCESS;
833   } else if (!IsDevicePathEnd (RemainingDevicePath)) {
834     Status = AtaPassThru->GetDevice (AtaPassThru, RemainingDevicePath, &Port, &PortMultiplierPort);
835     if (!EFI_ERROR (Status)) {
836       Status = RegisterAtaDevice (AtaBusDriverData,Port, PortMultiplierPort);
837     }
838   }
839 
840   return Status;
841 
842 ErrorExit:
843 
844   if (AtaBusDriverData != NULL) {
845     gBS->UninstallMultipleProtocolInterfaces (
846            Controller,
847            &gEfiCallerIdGuid,
848            AtaBusDriverData,
849            NULL
850            );
851     FreePool (AtaBusDriverData);
852   }
853 
854   gBS->CloseProtocol (
855         Controller,
856         &gEfiAtaPassThruProtocolGuid,
857         This->DriverBindingHandle,
858         Controller
859         );
860 
861   return Status;
862 
863 }
864 
865 
866 /**
867   Stops a device controller or a bus controller.
868 
869   The Stop() function is designed to be invoked from the EFI boot service DisconnectController().
870   As a result, much of the error checking on the parameters to Stop() has been moved
871   into this common boot service. It is legal to call Stop() from other locations,
872   but the following calling restrictions must be followed or the system behavior will not be deterministic.
873   1. ControllerHandle must be a valid EFI_HANDLE that was used on a previous call to this
874      same driver's Start() function.
875   2. The first NumberOfChildren handles of ChildHandleBuffer must all be a valid
876      EFI_HANDLE. In addition, all of these handles must have been created in this driver's
877      Start() function, and the Start() function must have called OpenProtocol() on
878      ControllerHandle with an Attribute of EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER.
879 
880   @param[in]  This              A pointer to the EFI_DRIVER_BINDING_PROTOCOL instance.
881   @param[in]  ControllerHandle  A handle to the device being stopped. The handle must
882                                 support a bus specific I/O protocol for the driver
883                                 to use to stop the device.
884   @param[in]  NumberOfChildren  The number of child device handles in ChildHandleBuffer.
885   @param[in]  ChildHandleBuffer An array of child handles to be freed. May be NULL
886                                 if NumberOfChildren is 0.
887 
888   @retval EFI_SUCCESS           The device was stopped.
889   @retval EFI_DEVICE_ERROR      The device could not be stopped due to a device error.
890 
891 **/
892 EFI_STATUS
893 EFIAPI
AtaBusDriverBindingStop(IN EFI_DRIVER_BINDING_PROTOCOL * This,IN EFI_HANDLE Controller,IN UINTN NumberOfChildren,IN EFI_HANDLE * ChildHandleBuffer)894 AtaBusDriverBindingStop (
895   IN  EFI_DRIVER_BINDING_PROTOCOL     *This,
896   IN  EFI_HANDLE                      Controller,
897   IN  UINTN                           NumberOfChildren,
898   IN  EFI_HANDLE                      *ChildHandleBuffer
899   )
900 {
901   EFI_STATUS                  Status;
902   BOOLEAN                     AllChildrenStopped;
903   UINTN                       Index;
904   ATA_BUS_DRIVER_DATA         *AtaBusDriverData;
905 
906   if (NumberOfChildren == 0) {
907     Status = gBS->OpenProtocol (
908                     Controller,
909                     &gEfiCallerIdGuid,
910                     (VOID **) &AtaBusDriverData,
911                     This->DriverBindingHandle,
912                     Controller,
913                     EFI_OPEN_PROTOCOL_GET_PROTOCOL
914                     );
915     if (!EFI_ERROR (Status)) {
916       gBS->UninstallMultipleProtocolInterfaces (
917             Controller,
918             &gEfiCallerIdGuid,
919             AtaBusDriverData,
920             NULL
921             );
922       FreePool (AtaBusDriverData);
923     }
924 
925     gBS->CloseProtocol (
926           Controller,
927           &gEfiAtaPassThruProtocolGuid,
928           This->DriverBindingHandle,
929           Controller
930           );
931 
932     return EFI_SUCCESS;
933   }
934 
935   AllChildrenStopped = TRUE;
936 
937   for (Index = 0; Index < NumberOfChildren; Index++) {
938 
939     Status = UnregisterAtaDevice (This, Controller, ChildHandleBuffer[Index]);
940     if (EFI_ERROR (Status)) {
941       AllChildrenStopped = FALSE;
942     }
943   }
944 
945   if (!AllChildrenStopped) {
946     return EFI_DEVICE_ERROR;
947   }
948 
949   return EFI_SUCCESS;
950 }
951 
952 
953 /**
954   Reset the Block Device.
955 
956   @param  This                 Indicates a pointer to the calling context.
957   @param  ExtendedVerification Driver may perform diagnostics on reset.
958 
959   @retval EFI_SUCCESS          The device was reset.
960   @retval EFI_DEVICE_ERROR     The device is not functioning properly and could
961                                not be reset.
962 
963 **/
964 EFI_STATUS
965 EFIAPI
AtaBlockIoReset(IN EFI_BLOCK_IO_PROTOCOL * This,IN BOOLEAN ExtendedVerification)966 AtaBlockIoReset (
967   IN  EFI_BLOCK_IO_PROTOCOL   *This,
968   IN  BOOLEAN                 ExtendedVerification
969   )
970 {
971   EFI_STATUS      Status;
972   ATA_DEVICE      *AtaDevice;
973   EFI_TPL         OldTpl;
974 
975   OldTpl = gBS->RaiseTPL (TPL_CALLBACK);
976 
977   AtaDevice = ATA_DEVICE_FROM_BLOCK_IO (This);
978 
979   Status = ResetAtaDevice (AtaDevice);
980 
981   if (EFI_ERROR (Status)) {
982     Status = EFI_DEVICE_ERROR;
983   }
984 
985   gBS->RestoreTPL (OldTpl);
986   return Status;
987 }
988 
989 
990 /**
991   Read/Write BufferSize bytes from Lba from/into Buffer.
992 
993   @param[in]       This       Indicates a pointer to the calling context. Either be
994                               block I/O or block I/O2.
995   @param[in]       MediaId    The media ID that the read/write request is for.
996   @param[in]       Lba        The starting logical block address to be read/written.
997                               The caller is responsible for reading/writing to only
998                               legitimate locations.
999   @param[in, out]  Token      A pointer to the token associated with the transaction.
1000   @param[in]       BufferSize Size of Buffer, must be a multiple of device block size.
1001   @param[out]      Buffer     A pointer to the destination/source buffer for the data.
1002   @param[in]       IsBlockIo2 Indicate the calling is from BlockIO or BlockIO2. TRUE is
1003                               from BlockIO2, FALSE is for BlockIO.
1004   @param[in]       IsWrite    Indicates whether it is a write operation.
1005 
1006   @retval EFI_SUCCESS           The data was read/written correctly to the device.
1007   @retval EFI_WRITE_PROTECTED   The device can not be read/written to.
1008   @retval EFI_DEVICE_ERROR      The device reported an error while performing the read/write.
1009   @retval EFI_NO_MEDIA          There is no media in the device.
1010   @retval EFI_MEDIA_CHNAGED     The MediaId does not matched the current device.
1011   @retval EFI_BAD_BUFFER_SIZE   The Buffer was not a multiple of the block size of the device.
1012   @retval EFI_INVALID_PARAMETER The read/write request contains LBAs that are not valid,
1013                                 or the buffer is not on proper alignment.
1014 
1015 **/
1016 EFI_STATUS
BlockIoReadWrite(IN VOID * This,IN UINT32 MediaId,IN EFI_LBA Lba,IN OUT EFI_BLOCK_IO2_TOKEN * Token,IN UINTN BufferSize,OUT VOID * Buffer,IN BOOLEAN IsBlockIo2,IN BOOLEAN IsWrite)1017 BlockIoReadWrite (
1018   IN     VOID                    *This,
1019   IN     UINT32                  MediaId,
1020   IN     EFI_LBA                 Lba,
1021   IN OUT EFI_BLOCK_IO2_TOKEN     *Token,
1022   IN     UINTN                   BufferSize,
1023   OUT    VOID                    *Buffer,
1024   IN     BOOLEAN                 IsBlockIo2,
1025   IN     BOOLEAN                 IsWrite
1026   )
1027 {
1028   ATA_DEVICE                        *AtaDevice;
1029   EFI_STATUS                        Status;
1030   EFI_TPL                           OldTpl;
1031   EFI_BLOCK_IO_MEDIA                *Media;
1032   UINTN                             BlockSize;
1033   UINTN                             NumberOfBlocks;
1034   UINTN                             IoAlign;
1035 
1036   if (IsBlockIo2) {
1037    Media     = ((EFI_BLOCK_IO2_PROTOCOL *) This)->Media;
1038    AtaDevice = ATA_DEVICE_FROM_BLOCK_IO2 (This);
1039   } else {
1040    Media     = ((EFI_BLOCK_IO_PROTOCOL *) This)->Media;
1041    AtaDevice = ATA_DEVICE_FROM_BLOCK_IO (This);
1042   }
1043 
1044   if (MediaId != Media->MediaId) {
1045     return EFI_MEDIA_CHANGED;
1046   }
1047 
1048   //
1049   // Check parameters.
1050   //
1051   if (Buffer == NULL) {
1052     return EFI_INVALID_PARAMETER;
1053   }
1054 
1055   if (BufferSize == 0) {
1056     if ((Token != NULL) && (Token->Event != NULL)) {
1057       Token->TransactionStatus = EFI_SUCCESS;
1058       gBS->SignalEvent (Token->Event);
1059     }
1060     return EFI_SUCCESS;
1061   }
1062 
1063   BlockSize = Media->BlockSize;
1064   if ((BufferSize % BlockSize) != 0) {
1065     return EFI_BAD_BUFFER_SIZE;
1066   }
1067 
1068   NumberOfBlocks  = BufferSize / BlockSize;
1069   if ((Lba + NumberOfBlocks - 1) > Media->LastBlock) {
1070     return EFI_INVALID_PARAMETER;
1071   }
1072 
1073   IoAlign = Media->IoAlign;
1074   if (IoAlign > 0 && (((UINTN) Buffer & (IoAlign - 1)) != 0)) {
1075     return EFI_INVALID_PARAMETER;
1076   }
1077 
1078   OldTpl = gBS->RaiseTPL (TPL_CALLBACK);
1079 
1080   //
1081   // Invoke low level AtaDevice Access Routine.
1082   //
1083   Status = AccessAtaDevice (AtaDevice, Buffer, Lba, NumberOfBlocks, IsWrite, Token);
1084 
1085   gBS->RestoreTPL (OldTpl);
1086 
1087   return Status;
1088 }
1089 
1090 
1091 /**
1092   Read BufferSize bytes from Lba into Buffer.
1093 
1094   @param  This       Indicates a pointer to the calling context.
1095   @param  MediaId    Id of the media, changes every time the media is replaced.
1096   @param  Lba        The starting Logical Block Address to read from
1097   @param  BufferSize Size of Buffer, must be a multiple of device block size.
1098   @param  Buffer     A pointer to the destination buffer for the data. The caller is
1099                      responsible for either having implicit or explicit ownership of the buffer.
1100 
1101   @retval EFI_SUCCESS           The data was read correctly from the device.
1102   @retval EFI_DEVICE_ERROR      The device reported an error while performing the read.
1103   @retval EFI_NO_MEDIA          There is no media in the device.
1104   @retval EFI_MEDIA_CHANGED     The MediaId does not matched the current device.
1105   @retval EFI_BAD_BUFFER_SIZE   The Buffer was not a multiple of the block size of the device.
1106   @retval EFI_INVALID_PARAMETER The read request contains LBAs that are not valid,
1107                                 or the buffer is not on proper alignment.
1108 
1109 **/
1110 EFI_STATUS
1111 EFIAPI
AtaBlockIoReadBlocks(IN EFI_BLOCK_IO_PROTOCOL * This,IN UINT32 MediaId,IN EFI_LBA Lba,IN UINTN BufferSize,OUT VOID * Buffer)1112 AtaBlockIoReadBlocks (
1113   IN  EFI_BLOCK_IO_PROTOCOL   *This,
1114   IN  UINT32                  MediaId,
1115   IN  EFI_LBA                 Lba,
1116   IN  UINTN                   BufferSize,
1117   OUT VOID                    *Buffer
1118   )
1119 {
1120   return BlockIoReadWrite ((VOID *) This, MediaId, Lba, NULL, BufferSize, Buffer, FALSE, FALSE);
1121 }
1122 
1123 
1124 /**
1125   Write BufferSize bytes from Lba into Buffer.
1126 
1127   @param  This       Indicates a pointer to the calling context.
1128   @param  MediaId    The media ID that the write request is for.
1129   @param  Lba        The starting logical block address to be written. The caller is
1130                      responsible for writing to only legitimate locations.
1131   @param  BufferSize Size of Buffer, must be a multiple of device block size.
1132   @param  Buffer     A pointer to the source buffer for the data.
1133 
1134   @retval EFI_SUCCESS           The data was written correctly to the device.
1135   @retval EFI_WRITE_PROTECTED   The device can not be written to.
1136   @retval EFI_DEVICE_ERROR      The device reported an error while performing the write.
1137   @retval EFI_NO_MEDIA          There is no media in the device.
1138   @retval EFI_MEDIA_CHNAGED     The MediaId does not matched the current device.
1139   @retval EFI_BAD_BUFFER_SIZE   The Buffer was not a multiple of the block size of the device.
1140   @retval EFI_INVALID_PARAMETER The write request contains LBAs that are not valid,
1141                                 or the buffer is not on proper alignment.
1142 
1143 **/
1144 EFI_STATUS
1145 EFIAPI
AtaBlockIoWriteBlocks(IN EFI_BLOCK_IO_PROTOCOL * This,IN UINT32 MediaId,IN EFI_LBA Lba,IN UINTN BufferSize,IN VOID * Buffer)1146 AtaBlockIoWriteBlocks (
1147   IN  EFI_BLOCK_IO_PROTOCOL   *This,
1148   IN  UINT32                  MediaId,
1149   IN  EFI_LBA                 Lba,
1150   IN  UINTN                   BufferSize,
1151   IN  VOID                    *Buffer
1152   )
1153 {
1154   return BlockIoReadWrite ((VOID *) This, MediaId, Lba, NULL, BufferSize, Buffer, FALSE, TRUE);
1155 }
1156 
1157 
1158 /**
1159   Flush the Block Device.
1160 
1161   @param  This              Indicates a pointer to the calling context.
1162 
1163   @retval EFI_SUCCESS       All outstanding data was written to the device
1164   @retval EFI_DEVICE_ERROR  The device reported an error while writing back the data
1165   @retval EFI_NO_MEDIA      There is no media in the device.
1166 
1167 **/
1168 EFI_STATUS
1169 EFIAPI
AtaBlockIoFlushBlocks(IN EFI_BLOCK_IO_PROTOCOL * This)1170 AtaBlockIoFlushBlocks (
1171   IN  EFI_BLOCK_IO_PROTOCOL   *This
1172   )
1173 {
1174   //
1175   // return directly
1176   //
1177   return EFI_SUCCESS;
1178 }
1179 
1180 /**
1181   Reset the Block Device.
1182 
1183   @param[in]  This                 Indicates a pointer to the calling context.
1184   @param[in]  ExtendedVerification Driver may perform diagnostics on reset.
1185 
1186   @retval EFI_SUCCESS          The device was reset.
1187   @retval EFI_DEVICE_ERROR     The device is not functioning properly and could
1188                                not be reset.
1189 
1190 **/
1191 EFI_STATUS
1192 EFIAPI
AtaBlockIoResetEx(IN EFI_BLOCK_IO2_PROTOCOL * This,IN BOOLEAN ExtendedVerification)1193 AtaBlockIoResetEx (
1194   IN  EFI_BLOCK_IO2_PROTOCOL  *This,
1195   IN  BOOLEAN                 ExtendedVerification
1196   )
1197 {
1198   EFI_STATUS      Status;
1199   ATA_DEVICE      *AtaDevice;
1200   EFI_TPL         OldTpl;
1201 
1202   OldTpl = gBS->RaiseTPL (TPL_CALLBACK);
1203 
1204   AtaDevice = ATA_DEVICE_FROM_BLOCK_IO2 (This);
1205 
1206   AtaTerminateNonBlockingTask (AtaDevice);
1207 
1208   Status = ResetAtaDevice (AtaDevice);
1209 
1210   if (EFI_ERROR (Status)) {
1211     Status = EFI_DEVICE_ERROR;
1212   }
1213 
1214   gBS->RestoreTPL (OldTpl);
1215   return Status;
1216 }
1217 
1218 /**
1219   Read BufferSize bytes from Lba into Buffer.
1220 
1221   @param[in]       This       Indicates a pointer to the calling context.
1222   @param[in]       MediaId    Id of the media, changes every time the media is replaced.
1223   @param[in]       Lba        The starting Logical Block Address to read from.
1224   @param[in, out]  Token      A pointer to the token associated with the transaction.
1225   @param[in]       BufferSize Size of Buffer, must be a multiple of device block size.
1226   @param[out]      Buffer     A pointer to the destination buffer for the data. The caller is
1227                               responsible for either having implicit or explicit ownership of the buffer.
1228 
1229   @retval EFI_SUCCESS           The read request was queued if Event is not NULL.
1230                                 The data was read correctly from the device if
1231                                 the Event is NULL.
1232   @retval EFI_DEVICE_ERROR      The device reported an error while performing
1233                                 the read.
1234   @retval EFI_NO_MEDIA          There is no media in the device.
1235   @retval EFI_MEDIA_CHANGED     The MediaId is not for the current media.
1236   @retval EFI_BAD_BUFFER_SIZE   The BufferSize parameter is not a multiple of the
1237                                 intrinsic block size of the device.
1238   @retval EFI_INVALID_PARAMETER The read request contains LBAs that are not valid,
1239                                 or the buffer is not on proper alignment.
1240   @retval EFI_OUT_OF_RESOURCES  The request could not be completed due to a lack
1241                                 of resources.
1242 
1243 **/
1244 EFI_STATUS
1245 EFIAPI
AtaBlockIoReadBlocksEx(IN EFI_BLOCK_IO2_PROTOCOL * This,IN UINT32 MediaId,IN EFI_LBA Lba,IN OUT EFI_BLOCK_IO2_TOKEN * Token,IN UINTN BufferSize,OUT VOID * Buffer)1246 AtaBlockIoReadBlocksEx (
1247   IN  EFI_BLOCK_IO2_PROTOCOL  *This,
1248   IN  UINT32                  MediaId,
1249   IN  EFI_LBA                 Lba,
1250   IN OUT EFI_BLOCK_IO2_TOKEN  *Token,
1251   IN  UINTN                   BufferSize,
1252   OUT VOID                    *Buffer
1253   )
1254 {
1255   return BlockIoReadWrite ((VOID *) This, MediaId, Lba, Token, BufferSize, Buffer, TRUE, FALSE);
1256 }
1257 
1258 
1259 /**
1260   Write BufferSize bytes from Lba into Buffer.
1261 
1262   @param[in]       This       Indicates a pointer to the calling context.
1263   @param[in]       MediaId    The media ID that the write request is for.
1264   @param[in]       Lba        The starting logical block address to be written. The
1265                               caller is responsible for writing to only legitimate
1266                               locations.
1267   @param[in, out]  Token      A pointer to the token associated with the transaction.
1268   @param[in]       BufferSize Size of Buffer, must be a multiple of device block size.
1269   @param[in]       Buffer     A pointer to the source buffer for the data.
1270 
1271   @retval EFI_SUCCESS           The data was written correctly to the device.
1272   @retval EFI_WRITE_PROTECTED   The device can not be written to.
1273   @retval EFI_DEVICE_ERROR      The device reported an error while performing the write.
1274   @retval EFI_NO_MEDIA          There is no media in the device.
1275   @retval EFI_MEDIA_CHNAGED     The MediaId does not matched the current device.
1276   @retval EFI_BAD_BUFFER_SIZE   The Buffer was not a multiple of the block size of the device.
1277   @retval EFI_INVALID_PARAMETER The write request contains LBAs that are not valid,
1278                                 or the buffer is not on proper alignment.
1279 
1280 **/
1281 EFI_STATUS
1282 EFIAPI
AtaBlockIoWriteBlocksEx(IN EFI_BLOCK_IO2_PROTOCOL * This,IN UINT32 MediaId,IN EFI_LBA Lba,IN OUT EFI_BLOCK_IO2_TOKEN * Token,IN UINTN BufferSize,IN VOID * Buffer)1283 AtaBlockIoWriteBlocksEx (
1284   IN  EFI_BLOCK_IO2_PROTOCOL  *This,
1285   IN  UINT32                  MediaId,
1286   IN  EFI_LBA                 Lba,
1287   IN OUT EFI_BLOCK_IO2_TOKEN  *Token,
1288   IN  UINTN                   BufferSize,
1289   IN  VOID                    *Buffer
1290   )
1291 {
1292   return BlockIoReadWrite ((VOID *) This, MediaId, Lba, Token, BufferSize, Buffer, TRUE, TRUE);
1293 }
1294 
1295 
1296 /**
1297   Flush the Block Device.
1298 
1299   @param[in]       This       Indicates a pointer to the calling context.
1300   @param[in, out]  Token      A pointer to the token associated with the transaction.
1301 
1302   @retval EFI_SUCCESS       All outstanding data was written to the device
1303   @retval EFI_DEVICE_ERROR  The device reported an error while writing back the data
1304   @retval EFI_NO_MEDIA      There is no media in the device.
1305 
1306 **/
1307 EFI_STATUS
1308 EFIAPI
AtaBlockIoFlushBlocksEx(IN EFI_BLOCK_IO2_PROTOCOL * This,IN OUT EFI_BLOCK_IO2_TOKEN * Token)1309 AtaBlockIoFlushBlocksEx (
1310   IN  EFI_BLOCK_IO2_PROTOCOL  *This,
1311   IN OUT EFI_BLOCK_IO2_TOKEN  *Token
1312   )
1313 {
1314   //
1315   // Signal event and return directly.
1316   //
1317   if (Token != NULL && Token->Event != NULL) {
1318     Token->TransactionStatus = EFI_SUCCESS;
1319     gBS->SignalEvent (Token->Event);
1320   }
1321   return EFI_SUCCESS;
1322 }
1323 /**
1324   Provides inquiry information for the controller type.
1325 
1326   This function is used by the IDE bus driver to get inquiry data.  Data format
1327   of Identify data is defined by the Interface GUID.
1328 
1329   @param[in]      This             Pointer to the EFI_DISK_INFO_PROTOCOL instance.
1330   @param[in, out] InquiryData      Pointer to a buffer for the inquiry data.
1331   @param[in, out] InquiryDataSize  Pointer to the value for the inquiry data size.
1332 
1333   @retval EFI_SUCCESS            The command was accepted without any errors.
1334   @retval EFI_NOT_FOUND          Device does not support this data class
1335   @retval EFI_DEVICE_ERROR       Error reading InquiryData from device
1336   @retval EFI_BUFFER_TOO_SMALL   InquiryDataSize not big enough
1337 
1338 **/
1339 EFI_STATUS
1340 EFIAPI
AtaDiskInfoInquiry(IN EFI_DISK_INFO_PROTOCOL * This,IN OUT VOID * InquiryData,IN OUT UINT32 * InquiryDataSize)1341 AtaDiskInfoInquiry (
1342   IN     EFI_DISK_INFO_PROTOCOL   *This,
1343   IN OUT VOID                     *InquiryData,
1344   IN OUT UINT32                   *InquiryDataSize
1345   )
1346 {
1347   return EFI_NOT_FOUND;
1348 }
1349 
1350 
1351 /**
1352   Provides identify information for the controller type.
1353 
1354   This function is used by the IDE bus driver to get identify data.  Data format
1355   of Identify data is defined by the Interface GUID.
1356 
1357   @param[in]      This              Pointer to the EFI_DISK_INFO_PROTOCOL
1358                                     instance.
1359   @param[in, out] IdentifyData      Pointer to a buffer for the identify data.
1360   @param[in, out] IdentifyDataSize  Pointer to the value for the identify data
1361                                     size.
1362 
1363   @retval EFI_SUCCESS            The command was accepted without any errors.
1364   @retval EFI_NOT_FOUND          Device does not support this data class
1365   @retval EFI_DEVICE_ERROR       Error reading IdentifyData from device
1366   @retval EFI_BUFFER_TOO_SMALL   IdentifyDataSize not big enough
1367 
1368 **/
1369 EFI_STATUS
1370 EFIAPI
AtaDiskInfoIdentify(IN EFI_DISK_INFO_PROTOCOL * This,IN OUT VOID * IdentifyData,IN OUT UINT32 * IdentifyDataSize)1371 AtaDiskInfoIdentify (
1372   IN     EFI_DISK_INFO_PROTOCOL   *This,
1373   IN OUT VOID                     *IdentifyData,
1374   IN OUT UINT32                   *IdentifyDataSize
1375   )
1376 {
1377   EFI_STATUS                      Status;
1378   ATA_DEVICE                      *AtaDevice;
1379 
1380   AtaDevice = ATA_DEVICE_FROM_DISK_INFO (This);
1381 
1382   Status = EFI_BUFFER_TOO_SMALL;
1383   if (*IdentifyDataSize >= sizeof (ATA_IDENTIFY_DATA)) {
1384     Status = EFI_SUCCESS;
1385     CopyMem (IdentifyData, AtaDevice->IdentifyData, sizeof (ATA_IDENTIFY_DATA));
1386   }
1387   *IdentifyDataSize = sizeof (ATA_IDENTIFY_DATA);
1388 
1389   return Status;
1390 }
1391 
1392 
1393 /**
1394   Provides sense data information for the controller type.
1395 
1396   This function is used by the IDE bus driver to get sense data.
1397   Data format of Sense data is defined by the Interface GUID.
1398 
1399   @param[in]      This             Pointer to the EFI_DISK_INFO_PROTOCOL instance.
1400   @param[in, out] SenseData        Pointer to the SenseData.
1401   @param[in, out] SenseDataSize    Size of SenseData in bytes.
1402   @param[out]     SenseDataNumber  Pointer to the value for the sense data size.
1403 
1404   @retval EFI_SUCCESS            The command was accepted without any errors.
1405   @retval EFI_NOT_FOUND          Device does not support this data class.
1406   @retval EFI_DEVICE_ERROR       Error reading SenseData from device.
1407   @retval EFI_BUFFER_TOO_SMALL   SenseDataSize not big enough.
1408 
1409 **/
1410 EFI_STATUS
1411 EFIAPI
AtaDiskInfoSenseData(IN EFI_DISK_INFO_PROTOCOL * This,IN OUT VOID * SenseData,IN OUT UINT32 * SenseDataSize,OUT UINT8 * SenseDataNumber)1412 AtaDiskInfoSenseData (
1413   IN     EFI_DISK_INFO_PROTOCOL   *This,
1414   IN OUT VOID                     *SenseData,
1415   IN OUT UINT32                   *SenseDataSize,
1416   OUT    UINT8                    *SenseDataNumber
1417   )
1418 {
1419   return EFI_NOT_FOUND;
1420 }
1421 
1422 
1423 /**
1424   This function is used by the IDE bus driver to get controller information.
1425 
1426   @param[in]  This         Pointer to the EFI_DISK_INFO_PROTOCOL instance.
1427   @param[out] IdeChannel   Pointer to the Ide Channel number.  Primary or secondary.
1428   @param[out] IdeDevice    Pointer to the Ide Device number.  Master or slave.
1429 
1430   @retval EFI_SUCCESS       IdeChannel and IdeDevice are valid.
1431   @retval EFI_UNSUPPORTED   This is not an IDE device.
1432 
1433 **/
1434 EFI_STATUS
1435 EFIAPI
AtaDiskInfoWhichIde(IN EFI_DISK_INFO_PROTOCOL * This,OUT UINT32 * IdeChannel,OUT UINT32 * IdeDevice)1436 AtaDiskInfoWhichIde (
1437   IN  EFI_DISK_INFO_PROTOCOL   *This,
1438   OUT UINT32                   *IdeChannel,
1439   OUT UINT32                   *IdeDevice
1440   )
1441 {
1442   ATA_DEVICE                   *AtaDevice;
1443 
1444   AtaDevice       = ATA_DEVICE_FROM_DISK_INFO (This);
1445   *IdeChannel     = AtaDevice->Port;
1446   *IdeDevice      = AtaDevice->PortMultiplierPort;
1447 
1448   return EFI_SUCCESS;
1449 }
1450 
1451 /**
1452   Send a security protocol command to a device that receives data and/or the result
1453   of one or more commands sent by SendData.
1454 
1455   The ReceiveData function sends a security protocol command to the given MediaId.
1456   The security protocol command sent is defined by SecurityProtocolId and contains
1457   the security protocol specific data SecurityProtocolSpecificData. The function
1458   returns the data from the security protocol command in PayloadBuffer.
1459 
1460   For devices supporting the SCSI command set, the security protocol command is sent
1461   using the SECURITY PROTOCOL IN command defined in SPC-4.
1462 
1463   For devices supporting the ATA command set, the security protocol command is sent
1464   using one of the TRUSTED RECEIVE commands defined in ATA8-ACS if PayloadBufferSize
1465   is non-zero.
1466 
1467   If the PayloadBufferSize is zero, the security protocol command is sent using the
1468   Trusted Non-Data command defined in ATA8-ACS.
1469 
1470   If PayloadBufferSize is too small to store the available data from the security
1471   protocol command, the function shall copy PayloadBufferSize bytes into the
1472   PayloadBuffer and return EFI_WARN_BUFFER_TOO_SMALL.
1473 
1474   If PayloadBuffer or PayloadTransferSize is NULL and PayloadBufferSize is non-zero,
1475   the function shall return EFI_INVALID_PARAMETER.
1476 
1477   If the given MediaId does not support security protocol commands, the function shall
1478   return EFI_UNSUPPORTED. If there is no media in the device, the function returns
1479   EFI_NO_MEDIA. If the MediaId is not the ID for the current media in the device,
1480   the function returns EFI_MEDIA_CHANGED.
1481 
1482   If the security protocol fails to complete within the Timeout period, the function
1483   shall return EFI_TIMEOUT.
1484 
1485   If the security protocol command completes without an error, the function shall
1486   return EFI_SUCCESS. If the security protocol command completes with an error, the
1487   function shall return EFI_DEVICE_ERROR.
1488 
1489   @param  This                         Indicates a pointer to the calling context.
1490   @param  MediaId                      ID of the medium to receive data from.
1491   @param  Timeout                      The timeout, in 100ns units, to use for the execution
1492                                        of the security protocol command. A Timeout value of 0
1493                                        means that this function will wait indefinitely for the
1494                                        security protocol command to execute. If Timeout is greater
1495                                        than zero, then this function will return EFI_TIMEOUT
1496                                        if the time required to execute the receive data command
1497                                        is greater than Timeout.
1498   @param  SecurityProtocolId           The value of the "Security Protocol" parameter of
1499                                        the security protocol command to be sent.
1500   @param  SecurityProtocolSpecificData The value of the "Security Protocol Specific" parameter
1501                                        of the security protocol command to be sent.
1502   @param  PayloadBufferSize            Size in bytes of the payload data buffer.
1503   @param  PayloadBuffer                A pointer to a destination buffer to store the security
1504                                        protocol command specific payload data for the security
1505                                        protocol command. The caller is responsible for having
1506                                        either implicit or explicit ownership of the buffer.
1507   @param  PayloadTransferSize          A pointer to a buffer to store the size in bytes of the
1508                                        data written to the payload data buffer.
1509 
1510   @retval EFI_SUCCESS                  The security protocol command completed successfully.
1511   @retval EFI_WARN_BUFFER_TOO_SMALL    The PayloadBufferSize was too small to store the available
1512                                        data from the device. The PayloadBuffer contains the truncated data.
1513   @retval EFI_UNSUPPORTED              The given MediaId does not support security protocol commands.
1514   @retval EFI_DEVICE_ERROR             The security protocol command completed with an error.
1515   @retval EFI_NO_MEDIA                 There is no media in the device.
1516   @retval EFI_MEDIA_CHANGED            The MediaId is not for the current media.
1517   @retval EFI_INVALID_PARAMETER        The PayloadBuffer or PayloadTransferSize is NULL and
1518                                        PayloadBufferSize is non-zero.
1519   @retval EFI_TIMEOUT                  A timeout occurred while waiting for the security
1520                                        protocol command to execute.
1521 
1522 **/
1523 EFI_STATUS
1524 EFIAPI
AtaStorageSecurityReceiveData(IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL * This,IN UINT32 MediaId,IN UINT64 Timeout,IN UINT8 SecurityProtocolId,IN UINT16 SecurityProtocolSpecificData,IN UINTN PayloadBufferSize,OUT VOID * PayloadBuffer,OUT UINTN * PayloadTransferSize)1525 AtaStorageSecurityReceiveData (
1526   IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL    *This,
1527   IN UINT32                                   MediaId,
1528   IN UINT64                                   Timeout,
1529   IN UINT8                                    SecurityProtocolId,
1530   IN UINT16                                   SecurityProtocolSpecificData,
1531   IN UINTN                                    PayloadBufferSize,
1532   OUT VOID                                    *PayloadBuffer,
1533   OUT UINTN                                   *PayloadTransferSize
1534   )
1535 {
1536   EFI_STATUS                       Status;
1537   ATA_DEVICE                       *Private;
1538   EFI_TPL                          OldTpl;
1539 
1540   DEBUG ((EFI_D_INFO, "EFI Storage Security Protocol - Read\n"));
1541   if ((PayloadBuffer == NULL || PayloadTransferSize == NULL) && PayloadBufferSize != 0) {
1542     return EFI_INVALID_PARAMETER;
1543   }
1544 
1545   Status  = EFI_SUCCESS;
1546   Private = ATA_DEVICE_FROM_STORAGE_SECURITY (This);
1547 
1548   if (MediaId != Private->BlockIo.Media->MediaId) {
1549     return EFI_MEDIA_CHANGED;
1550   }
1551 
1552   if (!Private->BlockIo.Media->MediaPresent) {
1553     return EFI_NO_MEDIA;
1554   }
1555 
1556   OldTpl = gBS->RaiseTPL (TPL_CALLBACK);
1557 
1558   Status = TrustTransferAtaDevice (
1559              Private,
1560              PayloadBuffer,
1561              SecurityProtocolId,
1562              SecurityProtocolSpecificData,
1563              PayloadBufferSize,
1564              FALSE,
1565              Timeout,
1566              PayloadTransferSize
1567              );
1568 
1569   gBS->RestoreTPL (OldTpl);
1570   return Status;
1571 }
1572 
1573 /**
1574   Send a security protocol command to a device.
1575 
1576   The SendData function sends a security protocol command containing the payload
1577   PayloadBuffer to the given MediaId. The security protocol command sent is
1578   defined by SecurityProtocolId and contains the security protocol specific data
1579   SecurityProtocolSpecificData. If the underlying protocol command requires a
1580   specific padding for the command payload, the SendData function shall add padding
1581   bytes to the command payload to satisfy the padding requirements.
1582 
1583   For devices supporting the SCSI command set, the security protocol command is sent
1584   using the SECURITY PROTOCOL OUT command defined in SPC-4.
1585 
1586   For devices supporting the ATA command set, the security protocol command is sent
1587   using one of the TRUSTED SEND commands defined in ATA8-ACS if PayloadBufferSize
1588   is non-zero. If the PayloadBufferSize is zero, the security protocol command is
1589   sent using the Trusted Non-Data command defined in ATA8-ACS.
1590 
1591   If PayloadBuffer is NULL and PayloadBufferSize is non-zero, the function shall
1592   return EFI_INVALID_PARAMETER.
1593 
1594   If the given MediaId does not support security protocol commands, the function
1595   shall return EFI_UNSUPPORTED. If there is no media in the device, the function
1596   returns EFI_NO_MEDIA. If the MediaId is not the ID for the current media in the
1597   device, the function returns EFI_MEDIA_CHANGED.
1598 
1599   If the security protocol fails to complete within the Timeout period, the function
1600   shall return EFI_TIMEOUT.
1601 
1602   If the security protocol command completes without an error, the function shall return
1603   EFI_SUCCESS. If the security protocol command completes with an error, the function
1604   shall return EFI_DEVICE_ERROR.
1605 
1606   @param  This                         Indicates a pointer to the calling context.
1607   @param  MediaId                      ID of the medium to receive data from.
1608   @param  Timeout                      The timeout, in 100ns units, to use for the execution
1609                                        of the security protocol command. A Timeout value of 0
1610                                        means that this function will wait indefinitely for the
1611                                        security protocol command to execute. If Timeout is greater
1612                                        than zero, then this function will return EFI_TIMEOUT
1613                                        if the time required to execute the receive data command
1614                                        is greater than Timeout.
1615   @param  SecurityProtocolId           The value of the "Security Protocol" parameter of
1616                                        the security protocol command to be sent.
1617   @param  SecurityProtocolSpecificData The value of the "Security Protocol Specific" parameter
1618                                        of the security protocol command to be sent.
1619   @param  PayloadBufferSize            Size in bytes of the payload data buffer.
1620   @param  PayloadBuffer                A pointer to a destination buffer to store the security
1621                                        protocol command specific payload data for the security
1622                                        protocol command.
1623 
1624   @retval EFI_SUCCESS                  The security protocol command completed successfully.
1625   @retval EFI_UNSUPPORTED              The given MediaId does not support security protocol commands.
1626   @retval EFI_DEVICE_ERROR             The security protocol command completed with an error.
1627   @retval EFI_NO_MEDIA                 There is no media in the device.
1628   @retval EFI_MEDIA_CHANGED            The MediaId is not for the current media.
1629   @retval EFI_INVALID_PARAMETER        The PayloadBuffer is NULL and PayloadBufferSize is non-zero.
1630   @retval EFI_TIMEOUT                  A timeout occurred while waiting for the security
1631                                        protocol command to execute.
1632 
1633 **/
1634 EFI_STATUS
1635 EFIAPI
AtaStorageSecuritySendData(IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL * This,IN UINT32 MediaId,IN UINT64 Timeout,IN UINT8 SecurityProtocolId,IN UINT16 SecurityProtocolSpecificData,IN UINTN PayloadBufferSize,IN VOID * PayloadBuffer)1636 AtaStorageSecuritySendData (
1637   IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL    *This,
1638   IN UINT32                                   MediaId,
1639   IN UINT64                                   Timeout,
1640   IN UINT8                                    SecurityProtocolId,
1641   IN UINT16                                   SecurityProtocolSpecificData,
1642   IN UINTN                                    PayloadBufferSize,
1643   IN VOID                                     *PayloadBuffer
1644   )
1645 {
1646   EFI_STATUS                       Status;
1647   ATA_DEVICE                       *Private;
1648   EFI_TPL                          OldTpl;
1649 
1650   DEBUG ((EFI_D_INFO, "EFI Storage Security Protocol - Send\n"));
1651   if ((PayloadBuffer == NULL) && (PayloadBufferSize != 0)) {
1652     return EFI_INVALID_PARAMETER;
1653   }
1654 
1655   Status  = EFI_SUCCESS;
1656   Private = ATA_DEVICE_FROM_STORAGE_SECURITY (This);
1657 
1658   if (MediaId != Private->BlockIo.Media->MediaId) {
1659     return EFI_MEDIA_CHANGED;
1660   }
1661 
1662   OldTpl = gBS->RaiseTPL (TPL_CALLBACK);
1663   Status = TrustTransferAtaDevice (
1664              Private,
1665              PayloadBuffer,
1666              SecurityProtocolId,
1667              SecurityProtocolSpecificData,
1668              PayloadBufferSize,
1669              TRUE,
1670              Timeout,
1671              NULL
1672              );
1673 
1674   gBS->RestoreTPL (OldTpl);
1675   return Status;
1676 }
1677 
1678 /**
1679   The user Entry Point for module AtaBus. The user code starts with this function.
1680 
1681   @param[in] ImageHandle    The firmware allocated handle for the EFI image.
1682   @param[in] SystemTable    A pointer to the EFI System Table.
1683 
1684   @retval EFI_SUCCESS       The entry point is executed successfully.
1685   @retval other             Some error occurs when executing this entry point.
1686 
1687 **/
1688 EFI_STATUS
1689 EFIAPI
InitializeAtaBus(IN EFI_HANDLE ImageHandle,IN EFI_SYSTEM_TABLE * SystemTable)1690 InitializeAtaBus(
1691   IN EFI_HANDLE           ImageHandle,
1692   IN EFI_SYSTEM_TABLE     *SystemTable
1693   )
1694 {
1695   EFI_STATUS              Status;
1696 
1697   //
1698   // Install driver model protocol(s).
1699   //
1700   Status = EfiLibInstallDriverBindingComponentName2 (
1701              ImageHandle,
1702              SystemTable,
1703              &gAtaBusDriverBinding,
1704              ImageHandle,
1705              &gAtaBusComponentName,
1706              &gAtaBusComponentName2
1707              );
1708   ASSERT_EFI_ERROR (Status);
1709 
1710   return Status;
1711 }
1712 
1713