]> git.proxmox.com Git - mirror_edk2.git/blob - OvmfPkg/VirtioScsiDxe/VirtioScsi.c
b836fb3e6ab2e4101202243a28b4b18c193c6959
[mirror_edk2.git] / OvmfPkg / VirtioScsiDxe / VirtioScsi.c
1 /** @file
2
3 This driver produces Extended SCSI Pass Thru Protocol instances for
4 virtio-scsi devices.
5
6 The implementation is basic:
7
8 - No hotplug / hot-unplug.
9
10 - Although EFI_EXT_SCSI_PASS_THRU_PROTOCOL.PassThru() could be a good match
11 for multiple in-flight virtio-scsi requests, we stick to synchronous
12 requests for now.
13
14 - Timeouts are not supported for EFI_EXT_SCSI_PASS_THRU_PROTOCOL.PassThru().
15
16 - Only one channel is supported. (At the time of this writing, host-side
17 virtio-scsi supports a single channel too.)
18
19 - Only one request queue is used (for the one synchronous request).
20
21 - The ResetChannel() and ResetTargetLun() functions of
22 EFI_EXT_SCSI_PASS_THRU_PROTOCOL are not supported (which is allowed by the
23 UEFI 2.3.1 Errata C specification), although
24 VIRTIO_SCSI_T_TMF_LOGICAL_UNIT_RESET could be a good match. That would
25 however require client code for the control queue, which is deemed
26 unreasonable for now.
27
28 Copyright (C) 2012, Red Hat, Inc.
29 Copyright (c) 2012, Intel Corporation. All rights reserved.<BR>
30
31 This program and the accompanying materials are licensed and made available
32 under the terms and conditions of the BSD License which accompanies this
33 distribution. The full text of the license may be found at
34 http://opensource.org/licenses/bsd-license.php
35
36 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT
37 WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
38
39 **/
40
41 #include <IndustryStandard/Pci.h>
42 #include <IndustryStandard/VirtioScsi.h>
43 #include <Library/BaseMemoryLib.h>
44 #include <Library/DebugLib.h>
45 #include <Library/MemoryAllocationLib.h>
46 #include <Library/UefiBootServicesTableLib.h>
47 #include <Library/UefiLib.h>
48 #include <Library/VirtioLib.h>
49
50 #include "VirtioScsi.h"
51
52 /**
53
54 Convenience macros to read and write region 0 IO space elements of the
55 virtio-scsi PCI device, for configuration purposes.
56
57 The following macros make it possible to specify only the "core parameters"
58 for such accesses and to derive the rest. By the time VIRTIO_CFG_WRITE()
59 returns, the transaction will have been completed.
60
61 @param[in] Dev Pointer to the VSCSI_DEV structure whose PCI IO space
62 we're accessing. Dev->PciIo must be valid.
63
64 @param[in] Field A field name from VSCSI_HDR, identifying the virtio-scsi
65 configuration item to access.
66
67 @param[in] Value (VIRTIO_CFG_WRITE() only.) The value to write to the
68 selected configuration item.
69
70 @param[out] Pointer (VIRTIO_CFG_READ() only.) The object to receive the
71 value read from the configuration item. Its type must be
72 one of UINT8, UINT16, UINT32, UINT64.
73
74
75 @return Status codes returned by VirtioWrite() / VirtioRead().
76
77 **/
78
79 #define VIRTIO_CFG_WRITE(Dev, Field, Value) (VirtioWrite ( \
80 (Dev)->PciIo, \
81 OFFSET_OF_VSCSI (Field), \
82 SIZE_OF_VSCSI (Field), \
83 (Value) \
84 ))
85
86 #define VIRTIO_CFG_READ(Dev, Field, Pointer) (VirtioRead ( \
87 (Dev)->PciIo, \
88 OFFSET_OF_VSCSI (Field), \
89 SIZE_OF_VSCSI (Field), \
90 sizeof *(Pointer), \
91 (Pointer) \
92 ))
93
94
95 //
96 // UEFI Spec 2.3.1 + Errata C, 14.7 Extended SCSI Pass Thru Protocol specifies
97 // the PassThru() interface. Beside returning a status code, the function must
98 // set some fields in the EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET in/out
99 // parameter on return. The following is a full list of those fields, for
100 // easier validation of PopulateRequest(), ParseResponse(), and
101 // VirtioScsiPassThru() below.
102 //
103 // - InTransferLength
104 // - OutTransferLength
105 // - HostAdapterStatus
106 // - TargetStatus
107 // - SenseDataLength
108 // - SenseData
109 //
110 // On any return from the PassThru() interface, these fields must be set,
111 // except if the returned status code is explicitly exempt. (Actually the
112 // implementation here conservatively sets these fields even in case not all
113 // of them would be required by the specification.)
114 //
115
116 /**
117
118 Populate a virtio-scsi request from the Extended SCSI Pass Thru Protocol
119 packet.
120
121 The caller is responsible for pre-zeroing the virtio-scsi request. The
122 Extended SCSI Pass Thru Protocol packet is modified, to be forwarded outwards
123 by VirtioScsiPassThru(), if invalid or unsupported parameters are detected.
124
125 @param[in] Dev The virtio-scsi host device the packet targets.
126
127 @param[in] Target The SCSI target controlled by the virtio-scsi host
128 device.
129
130 @param[in] Lun The Logical Unit Number under the SCSI target.
131
132 @param[in out] Packet The Extended SCSI Pass Thru Protocol packet the
133 function translates to a virtio-scsi request. On
134 failure this parameter relays error contents.
135
136 @param[out] Request The pre-zeroed virtio-scsi request to populate. This
137 parameter is volatile-qualified because we expect the
138 caller to append it to a virtio ring, thus
139 assignments to Request must be visible when the
140 function returns.
141
142
143 @retval EFI_SUCCESS The Extended SCSI Pass Thru Protocol packet was valid,
144 Request has been populated.
145
146 @return Otherwise, invalid or unsupported parameters were
147 detected. Status codes are meant for direct forwarding
148 by the EFI_EXT_SCSI_PASS_THRU_PROTOCOL.PassThru()
149 implementation.
150
151 **/
152 STATIC
153 EFI_STATUS
154 EFIAPI
155 PopulateRequest (
156 IN CONST VSCSI_DEV *Dev,
157 IN UINT16 Target,
158 IN UINT64 Lun,
159 IN OUT EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *Packet,
160 OUT volatile VIRTIO_SCSI_REQ *Request
161 )
162 {
163 UINTN Idx;
164
165 if (
166 //
167 // bidirectional transfer was requested, but the host doesn't support it
168 //
169 (Packet->InTransferLength > 0 && Packet->OutTransferLength > 0 &&
170 !Dev->InOutSupported) ||
171
172 //
173 // a target / LUN was addressed that's impossible to encode for the host
174 //
175 Target > 0xFF || Lun >= 0x4000 ||
176
177 //
178 // Command Descriptor Block bigger than VIRTIO_SCSI_CDB_SIZE
179 //
180 Packet->CdbLength > VIRTIO_SCSI_CDB_SIZE ||
181
182 //
183 // From virtio-0.9.5, 2.3.2 Descriptor Table:
184 // "no descriptor chain may be more than 2^32 bytes long in total".
185 //
186 (UINT64) Packet->InTransferLength + Packet->OutTransferLength > SIZE_1GB
187 ) {
188
189 //
190 // this error code doesn't require updates to the Packet output fields
191 //
192 return EFI_UNSUPPORTED;
193 }
194
195 if (
196 //
197 // addressed invalid device
198 //
199 Target > Dev->MaxTarget || Lun > Dev->MaxLun ||
200
201 //
202 // invalid direction (there doesn't seem to be a macro for the "no data
203 // transferred" "direction", eg. for TEST UNIT READY)
204 //
205 Packet->DataDirection > EFI_EXT_SCSI_DATA_DIRECTION_BIDIRECTIONAL ||
206
207 //
208 // trying to receive, but destination pointer is NULL, or contradicting
209 // transfer direction
210 //
211 (Packet->InTransferLength > 0 &&
212 (Packet->InDataBuffer == NULL ||
213 Packet->DataDirection == EFI_EXT_SCSI_DATA_DIRECTION_WRITE
214 )
215 ) ||
216
217 //
218 // trying to send, but source pointer is NULL, or contradicting transfer
219 // direction
220 //
221 (Packet->OutTransferLength > 0 &&
222 (Packet->OutDataBuffer == NULL ||
223 Packet->DataDirection == EFI_EXT_SCSI_DATA_DIRECTION_READ
224 )
225 )
226 ) {
227
228 //
229 // this error code doesn't require updates to the Packet output fields
230 //
231 return EFI_INVALID_PARAMETER;
232 }
233
234 //
235 // Catch oversized requests eagerly. If this condition evaluates to false,
236 // then the combined size of a bidirectional request will not exceed the
237 // virtio-scsi device's transfer limit either.
238 //
239 if (ALIGN_VALUE (Packet->OutTransferLength, 512) / 512
240 > Dev->MaxSectors / 2 ||
241 ALIGN_VALUE (Packet->InTransferLength, 512) / 512
242 > Dev->MaxSectors / 2) {
243 Packet->InTransferLength = (Dev->MaxSectors / 2) * 512;
244 Packet->OutTransferLength = (Dev->MaxSectors / 2) * 512;
245 Packet->HostAdapterStatus =
246 EFI_EXT_SCSI_STATUS_HOST_ADAPTER_DATA_OVERRUN_UNDERRUN;
247 Packet->TargetStatus = EFI_EXT_SCSI_STATUS_TARGET_GOOD;
248 Packet->SenseDataLength = 0;
249 return EFI_BAD_BUFFER_SIZE;
250 }
251
252 //
253 // target & LUN encoding: see virtio-0.9.5, Appendix I: SCSI Host Device,
254 // Device Operation: request queues
255 //
256 Request->Lun[0] = 1;
257 Request->Lun[1] = (UINT8) Target;
258 Request->Lun[2] = (UINT8) ((Lun >> 8) | 0x40);
259 Request->Lun[3] = (UINT8) Lun;
260
261 //
262 // CopyMem() would cast away the "volatile" qualifier before access, which is
263 // undefined behavior (ISO C99 6.7.3p5)
264 //
265 for (Idx = 0; Idx < Packet->CdbLength; ++Idx) {
266 Request->Cdb[Idx] = ((UINT8 *) Packet->Cdb)[Idx];
267 }
268
269 return EFI_SUCCESS;
270 }
271
272
273 /**
274
275 Parse the virtio-scsi device's response, translate it to an EFI status code,
276 and update the Extended SCSI Pass Thru Protocol packet, to be returned by
277 the EFI_EXT_SCSI_PASS_THRU_PROTOCOL.PassThru() implementation.
278
279 @param[in out] Packet The Extended SCSI Pass Thru Protocol packet that has
280 been translated to a virtio-scsi request with
281 PopulateRequest(), and processed by the host. On
282 output this parameter is updated with response or
283 error contents.
284
285 @param[in] Response The virtio-scsi response structure to parse. We expect
286 it to come from a virtio ring, thus it is qualified
287 volatile.
288
289
290 @return PassThru() status codes mandated by UEFI Spec 2.3.1 + Errata C, 14.7
291 Extended SCSI Pass Thru Protocol.
292
293 **/
294 STATIC
295 EFI_STATUS
296 EFIAPI
297 ParseResponse (
298 IN OUT EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *Packet,
299 IN CONST volatile VIRTIO_SCSI_RESP *Response
300 )
301 {
302 UINTN ResponseSenseLen;
303 UINTN Idx;
304
305 //
306 // return sense data (length and contents) in all cases, truncated if needed
307 //
308 ResponseSenseLen = MIN (Response->SenseLen, VIRTIO_SCSI_SENSE_SIZE);
309 if (Packet->SenseDataLength > ResponseSenseLen) {
310 Packet->SenseDataLength = (UINT8) ResponseSenseLen;
311 }
312 for (Idx = 0; Idx < Packet->SenseDataLength; ++Idx) {
313 ((UINT8 *) Packet->SenseData)[Idx] = Response->Sense[Idx];
314 }
315
316 //
317 // Report actual transfer lengths. The logic below covers all three
318 // DataDirections (read, write, bidirectional).
319 //
320 // -+- @ 0
321 // |
322 // | write ^ @ Residual (unprocessed)
323 // | |
324 // -+- @ OutTransferLength -+- @ InTransferLength
325 // | |
326 // | read |
327 // | |
328 // V @ OutTransferLength + InTransferLength -+- @ 0
329 //
330 if (Response->Residual <= Packet->InTransferLength) {
331 Packet->InTransferLength -= Response->Residual;
332 }
333 else {
334 Packet->OutTransferLength -= Response->Residual - Packet->InTransferLength;
335 Packet->InTransferLength = 0;
336 }
337
338 //
339 // report target status in all cases
340 //
341 Packet->TargetStatus = Response->Status;
342
343 //
344 // host adapter status and function return value depend on virtio-scsi
345 // response code
346 //
347 switch (Response->Response) {
348 case VIRTIO_SCSI_S_OK:
349 Packet->HostAdapterStatus = EFI_EXT_SCSI_STATUS_HOST_ADAPTER_OK;
350 return EFI_SUCCESS;
351
352 case VIRTIO_SCSI_S_OVERRUN:
353 Packet->HostAdapterStatus =
354 EFI_EXT_SCSI_STATUS_HOST_ADAPTER_DATA_OVERRUN_UNDERRUN;
355 break;
356
357 case VIRTIO_SCSI_S_BAD_TARGET:
358 //
359 // This is non-intuitive but explicitly required by the
360 // EFI_EXT_SCSI_PASS_THRU_PROTOCOL.PassThru() specification for
361 // disconnected (but otherwise valid) target / LUN addresses.
362 //
363 Packet->HostAdapterStatus =
364 EFI_EXT_SCSI_STATUS_HOST_ADAPTER_TIMEOUT_COMMAND;
365 return EFI_TIMEOUT;
366
367 case VIRTIO_SCSI_S_RESET:
368 Packet->HostAdapterStatus = EFI_EXT_SCSI_STATUS_HOST_ADAPTER_BUS_RESET;
369 break;
370
371 case VIRTIO_SCSI_S_BUSY:
372 Packet->HostAdapterStatus = EFI_EXT_SCSI_STATUS_HOST_ADAPTER_OK;
373 return EFI_NOT_READY;
374
375 //
376 // Lump together the rest. The mapping for VIRTIO_SCSI_S_ABORTED is
377 // intentional as well, not an oversight.
378 //
379 case VIRTIO_SCSI_S_ABORTED:
380 case VIRTIO_SCSI_S_TRANSPORT_FAILURE:
381 case VIRTIO_SCSI_S_TARGET_FAILURE:
382 case VIRTIO_SCSI_S_NEXUS_FAILURE:
383 case VIRTIO_SCSI_S_FAILURE:
384 default:
385 Packet->HostAdapterStatus = EFI_EXT_SCSI_STATUS_HOST_ADAPTER_OTHER;
386 }
387
388 return EFI_DEVICE_ERROR;
389 }
390
391
392 //
393 // The next seven functions implement EFI_EXT_SCSI_PASS_THRU_PROTOCOL
394 // for the virtio-scsi HBA. Refer to UEFI Spec 2.3.1 + Errata C, sections
395 // - 14.1 SCSI Driver Model Overview,
396 // - 14.7 Extended SCSI Pass Thru Protocol.
397 //
398
399 EFI_STATUS
400 EFIAPI
401 VirtioScsiPassThru (
402 IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This,
403 IN UINT8 *Target,
404 IN UINT64 Lun,
405 IN OUT EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *Packet,
406 IN EFI_EVENT Event OPTIONAL
407 )
408 {
409 VSCSI_DEV *Dev;
410 UINT16 TargetValue;
411 EFI_STATUS Status;
412 volatile VIRTIO_SCSI_REQ Request;
413 volatile VIRTIO_SCSI_RESP Response;
414 DESC_INDICES Indices;
415
416 ZeroMem ((VOID*) &Request, sizeof (Request));
417 ZeroMem ((VOID*) &Response, sizeof (Response));
418
419 Dev = VIRTIO_SCSI_FROM_PASS_THRU (This);
420 CopyMem (&TargetValue, Target, sizeof TargetValue);
421
422 Status = PopulateRequest (Dev, TargetValue, Lun, Packet, &Request);
423 if (EFI_ERROR (Status)) {
424 return Status;
425 }
426
427 VirtioPrepare (&Dev->Ring, &Indices);
428
429 //
430 // preset a host status for ourselves that we do not accept as success
431 //
432 Response.Response = VIRTIO_SCSI_S_FAILURE;
433
434 //
435 // ensured by VirtioScsiInit() -- this predicate, in combination with the
436 // lock-step progress, ensures we don't have to track free descriptors.
437 //
438 ASSERT (Dev->Ring.QueueSize >= 4);
439
440 //
441 // enqueue Request
442 //
443 VirtioAppendDesc (&Dev->Ring, (UINTN) &Request, sizeof Request,
444 VRING_DESC_F_NEXT, &Indices);
445
446 //
447 // enqueue "dataout" if any
448 //
449 if (Packet->OutTransferLength > 0) {
450 VirtioAppendDesc (&Dev->Ring, (UINTN) Packet->OutDataBuffer,
451 Packet->OutTransferLength, VRING_DESC_F_NEXT, &Indices);
452 }
453
454 //
455 // enqueue Response, to be written by the host
456 //
457 VirtioAppendDesc (&Dev->Ring, (UINTN) &Response, sizeof Response,
458 VRING_DESC_F_WRITE | (Packet->InTransferLength > 0 ?
459 VRING_DESC_F_NEXT : 0),
460 &Indices);
461
462 //
463 // enqueue "datain" if any, to be written by the host
464 //
465 if (Packet->InTransferLength > 0) {
466 VirtioAppendDesc (&Dev->Ring, (UINTN) Packet->InDataBuffer,
467 Packet->InTransferLength, VRING_DESC_F_WRITE, &Indices);
468 }
469
470 // If kicking the host fails, we must fake a host adapter error.
471 // EFI_NOT_READY would save us the effort, but it would also suggest that the
472 // caller retry.
473 //
474 if (VirtioFlush (Dev->PciIo, VIRTIO_SCSI_REQUEST_QUEUE, &Dev->Ring,
475 &Indices) != EFI_SUCCESS) {
476 Packet->InTransferLength = 0;
477 Packet->OutTransferLength = 0;
478 Packet->HostAdapterStatus = EFI_EXT_SCSI_STATUS_HOST_ADAPTER_OTHER;
479 Packet->TargetStatus = EFI_EXT_SCSI_STATUS_TARGET_GOOD;
480 Packet->SenseDataLength = 0;
481 return EFI_DEVICE_ERROR;
482 }
483
484 return ParseResponse (Packet, &Response);
485 }
486
487
488 EFI_STATUS
489 EFIAPI
490 VirtioScsiGetNextTargetLun (
491 IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This,
492 IN OUT UINT8 **TargetPointer,
493 IN OUT UINT64 *Lun
494 )
495 {
496 UINT8 *Target;
497 UINTN Idx;
498 UINT16 LastTarget;
499 VSCSI_DEV *Dev;
500
501 //
502 // the TargetPointer input parameter is unnecessarily a pointer-to-pointer
503 //
504 Target = *TargetPointer;
505
506 //
507 // Search for first non-0xFF byte. If not found, return first target & LUN.
508 //
509 for (Idx = 0; Idx < TARGET_MAX_BYTES && Target[Idx] == 0xFF; ++Idx)
510 ;
511 if (Idx == TARGET_MAX_BYTES) {
512 SetMem (Target, TARGET_MAX_BYTES, 0x00);
513 *Lun = 0;
514 return EFI_SUCCESS;
515 }
516
517 //
518 // see the TARGET_MAX_BYTES check in "VirtioScsi.h"
519 //
520 CopyMem (&LastTarget, Target, sizeof LastTarget);
521
522 //
523 // increment (target, LUN) pair if valid on input
524 //
525 Dev = VIRTIO_SCSI_FROM_PASS_THRU (This);
526 if (LastTarget > Dev->MaxTarget || *Lun > Dev->MaxLun) {
527 return EFI_INVALID_PARAMETER;
528 }
529
530 if (*Lun < Dev->MaxLun) {
531 ++*Lun;
532 return EFI_SUCCESS;
533 }
534
535 if (LastTarget < Dev->MaxTarget) {
536 *Lun = 0;
537 ++LastTarget;
538 CopyMem (Target, &LastTarget, sizeof LastTarget);
539 return EFI_SUCCESS;
540 }
541
542 return EFI_NOT_FOUND;
543 }
544
545
546 EFI_STATUS
547 EFIAPI
548 VirtioScsiBuildDevicePath (
549 IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This,
550 IN UINT8 *Target,
551 IN UINT64 Lun,
552 IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath
553 )
554 {
555 UINT16 TargetValue;
556 VSCSI_DEV *Dev;
557 SCSI_DEVICE_PATH *ScsiDevicePath;
558
559 if (DevicePath == NULL) {
560 return EFI_INVALID_PARAMETER;
561 }
562
563 CopyMem (&TargetValue, Target, sizeof TargetValue);
564 Dev = VIRTIO_SCSI_FROM_PASS_THRU (This);
565 if (TargetValue > Dev->MaxTarget || Lun > Dev->MaxLun || Lun > 0xFFFF) {
566 return EFI_NOT_FOUND;
567 }
568
569 ScsiDevicePath = AllocatePool (sizeof *ScsiDevicePath);
570 if (ScsiDevicePath == NULL) {
571 return EFI_OUT_OF_RESOURCES;
572 }
573
574 ScsiDevicePath->Header.Type = MESSAGING_DEVICE_PATH;
575 ScsiDevicePath->Header.SubType = MSG_SCSI_DP;
576 ScsiDevicePath->Header.Length[0] = (UINT8) sizeof *ScsiDevicePath;
577 ScsiDevicePath->Header.Length[1] = (UINT8) (sizeof *ScsiDevicePath >> 8);
578 ScsiDevicePath->Pun = TargetValue;
579 ScsiDevicePath->Lun = (UINT16) Lun;
580
581 *DevicePath = &ScsiDevicePath->Header;
582 return EFI_SUCCESS;
583 }
584
585
586 EFI_STATUS
587 EFIAPI
588 VirtioScsiGetTargetLun (
589 IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This,
590 IN EFI_DEVICE_PATH_PROTOCOL *DevicePath,
591 OUT UINT8 **TargetPointer,
592 OUT UINT64 *Lun
593 )
594 {
595 SCSI_DEVICE_PATH *ScsiDevicePath;
596 VSCSI_DEV *Dev;
597 UINT8 *Target;
598
599 if (DevicePath == NULL || TargetPointer == NULL || *TargetPointer == NULL ||
600 Lun == NULL) {
601 return EFI_INVALID_PARAMETER;
602 }
603
604 if (DevicePath->Type != MESSAGING_DEVICE_PATH ||
605 DevicePath->SubType != MSG_SCSI_DP) {
606 return EFI_UNSUPPORTED;
607 }
608
609 ScsiDevicePath = (SCSI_DEVICE_PATH *) DevicePath;
610 Dev = VIRTIO_SCSI_FROM_PASS_THRU (This);
611 if (ScsiDevicePath->Pun > Dev->MaxTarget ||
612 ScsiDevicePath->Lun > Dev->MaxLun) {
613 return EFI_NOT_FOUND;
614 }
615
616 //
617 // a) the TargetPointer input parameter is unnecessarily a pointer-to-pointer
618 // b) see the TARGET_MAX_BYTES check in "VirtioScsi.h"
619 // c) ScsiDevicePath->Pun is an UINT16
620 //
621 Target = *TargetPointer;
622 CopyMem (Target, &ScsiDevicePath->Pun, 2);
623 SetMem (Target + 2, TARGET_MAX_BYTES - 2, 0x00);
624
625 *Lun = ScsiDevicePath->Lun;
626 return EFI_SUCCESS;
627 }
628
629
630 EFI_STATUS
631 EFIAPI
632 VirtioScsiResetChannel (
633 IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This
634 )
635 {
636 return EFI_UNSUPPORTED;
637 }
638
639
640 EFI_STATUS
641 EFIAPI
642 VirtioScsiResetTargetLun (
643 IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This,
644 IN UINT8 *Target,
645 IN UINT64 Lun
646 )
647 {
648 return EFI_UNSUPPORTED;
649 }
650
651
652 EFI_STATUS
653 EFIAPI
654 VirtioScsiGetNextTarget (
655 IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This,
656 IN OUT UINT8 **TargetPointer
657 )
658 {
659 UINT8 *Target;
660 UINTN Idx;
661 UINT16 LastTarget;
662 VSCSI_DEV *Dev;
663
664 //
665 // the TargetPointer input parameter is unnecessarily a pointer-to-pointer
666 //
667 Target = *TargetPointer;
668
669 //
670 // Search for first non-0xFF byte. If not found, return first target.
671 //
672 for (Idx = 0; Idx < TARGET_MAX_BYTES && Target[Idx] == 0xFF; ++Idx)
673 ;
674 if (Idx == TARGET_MAX_BYTES) {
675 SetMem (Target, TARGET_MAX_BYTES, 0x00);
676 return EFI_SUCCESS;
677 }
678
679 //
680 // see the TARGET_MAX_BYTES check in "VirtioScsi.h"
681 //
682 CopyMem (&LastTarget, Target, sizeof LastTarget);
683
684 //
685 // increment target if valid on input
686 //
687 Dev = VIRTIO_SCSI_FROM_PASS_THRU (This);
688 if (LastTarget > Dev->MaxTarget) {
689 return EFI_INVALID_PARAMETER;
690 }
691
692 if (LastTarget < Dev->MaxTarget) {
693 ++LastTarget;
694 CopyMem (Target, &LastTarget, sizeof LastTarget);
695 return EFI_SUCCESS;
696 }
697
698 return EFI_NOT_FOUND;
699 }
700
701
702 STATIC
703 EFI_STATUS
704 EFIAPI
705 VirtioScsiInit (
706 IN OUT VSCSI_DEV *Dev
707 )
708 {
709 UINT8 NextDevStat;
710 EFI_STATUS Status;
711
712 UINT32 Features;
713 UINT16 MaxChannel; // for validation only
714 UINT32 NumQueues; // for validation only
715 UINT16 QueueSize;
716
717 //
718 // Execute virtio-0.9.5, 2.2.1 Device Initialization Sequence.
719 //
720 NextDevStat = 0; // step 1 -- reset device
721 Status = VIRTIO_CFG_WRITE (Dev, Generic.VhdrDeviceStatus, NextDevStat);
722 if (EFI_ERROR (Status)) {
723 goto Failed;
724 }
725
726 NextDevStat |= VSTAT_ACK; // step 2 -- acknowledge device presence
727 Status = VIRTIO_CFG_WRITE (Dev, Generic.VhdrDeviceStatus, NextDevStat);
728 if (EFI_ERROR (Status)) {
729 goto Failed;
730 }
731
732 NextDevStat |= VSTAT_DRIVER; // step 3 -- we know how to drive it
733 Status = VIRTIO_CFG_WRITE (Dev, Generic.VhdrDeviceStatus, NextDevStat);
734 if (EFI_ERROR (Status)) {
735 goto Failed;
736 }
737
738 //
739 // step 4a -- retrieve and validate features
740 //
741 Status = VIRTIO_CFG_READ (Dev, Generic.VhdrDeviceFeatureBits, &Features);
742 if (EFI_ERROR (Status)) {
743 goto Failed;
744 }
745 Dev->InOutSupported = !!(Features & VIRTIO_SCSI_F_INOUT);
746
747 Status = VIRTIO_CFG_READ (Dev, VhdrMaxChannel, &MaxChannel);
748 if (EFI_ERROR (Status)) {
749 goto Failed;
750 }
751 if (MaxChannel != 0) {
752 //
753 // this driver is for a single-channel virtio-scsi HBA
754 //
755 Status = EFI_UNSUPPORTED;
756 goto Failed;
757 }
758
759 Status = VIRTIO_CFG_READ (Dev, VhdrNumQueues, &NumQueues);
760 if (EFI_ERROR (Status)) {
761 goto Failed;
762 }
763 if (NumQueues < 1) {
764 Status = EFI_UNSUPPORTED;
765 goto Failed;
766 }
767
768 Status = VIRTIO_CFG_READ (Dev, VhdrMaxTarget, &Dev->MaxTarget);
769 if (EFI_ERROR (Status)) {
770 goto Failed;
771 }
772 if (Dev->MaxTarget > PcdGet16 (PcdVirtioScsiMaxTargetLimit)) {
773 Dev->MaxTarget = PcdGet16 (PcdVirtioScsiMaxTargetLimit);
774 }
775
776 Status = VIRTIO_CFG_READ (Dev, VhdrMaxLun, &Dev->MaxLun);
777 if (EFI_ERROR (Status)) {
778 goto Failed;
779 }
780 if (Dev->MaxLun > PcdGet32 (PcdVirtioScsiMaxLunLimit)) {
781 Dev->MaxLun = PcdGet32 (PcdVirtioScsiMaxLunLimit);
782 }
783
784 Status = VIRTIO_CFG_READ (Dev, VhdrMaxSectors, &Dev->MaxSectors);
785 if (EFI_ERROR (Status)) {
786 goto Failed;
787 }
788 if (Dev->MaxSectors < 2) {
789 //
790 // We must be able to halve it for bidirectional transfers
791 // (see EFI_BAD_BUFFER_SIZE in PopulateRequest()).
792 //
793 Status = EFI_UNSUPPORTED;
794 goto Failed;
795 }
796
797 //
798 // step 4b -- allocate request virtqueue
799 //
800 Status = VIRTIO_CFG_WRITE (Dev, Generic.VhdrQueueSelect,
801 VIRTIO_SCSI_REQUEST_QUEUE);
802 if (EFI_ERROR (Status)) {
803 goto Failed;
804 }
805 Status = VIRTIO_CFG_READ (Dev, Generic.VhdrQueueSize, &QueueSize);
806 if (EFI_ERROR (Status)) {
807 goto Failed;
808 }
809 //
810 // VirtioScsiPassThru() uses at most four descriptors
811 //
812 if (QueueSize < 4) {
813 Status = EFI_UNSUPPORTED;
814 goto Failed;
815 }
816
817 Status = VirtioRingInit (QueueSize, &Dev->Ring);
818 if (EFI_ERROR (Status)) {
819 goto Failed;
820 }
821
822 //
823 // step 4c -- Report GPFN (guest-physical frame number) of queue. If anything
824 // fails from here on, we must release the ring resources.
825 //
826 Status = VIRTIO_CFG_WRITE (Dev, Generic.VhdrQueueAddress,
827 (UINTN) Dev->Ring.Base >> EFI_PAGE_SHIFT);
828 if (EFI_ERROR (Status)) {
829 goto ReleaseQueue;
830 }
831
832 //
833 // step 5 -- Report understood features and guest-tuneables. We want none of
834 // the known (or unknown) VIRTIO_SCSI_F_* or VIRTIO_F_* capabilities (see
835 // virtio-0.9.5, Appendices B and I), except bidirectional transfers.
836 //
837 Status = VIRTIO_CFG_WRITE (Dev, Generic.VhdrGuestFeatureBits,
838 Features & VIRTIO_SCSI_F_INOUT);
839 if (EFI_ERROR (Status)) {
840 goto ReleaseQueue;
841 }
842
843 //
844 // We expect these maximum sizes from the host. Since they are
845 // guest-negotiable, ask for them rather than just checking them.
846 //
847 Status = VIRTIO_CFG_WRITE (Dev, VhdrCdbSize, VIRTIO_SCSI_CDB_SIZE);
848 if (EFI_ERROR (Status)) {
849 goto ReleaseQueue;
850 }
851 Status = VIRTIO_CFG_WRITE (Dev, VhdrSenseSize, VIRTIO_SCSI_SENSE_SIZE);
852 if (EFI_ERROR (Status)) {
853 goto ReleaseQueue;
854 }
855
856 //
857 // step 6 -- initialization complete
858 //
859 NextDevStat |= VSTAT_DRIVER_OK;
860 Status = VIRTIO_CFG_WRITE (Dev, Generic.VhdrDeviceStatus, NextDevStat);
861 if (EFI_ERROR (Status)) {
862 goto ReleaseQueue;
863 }
864
865 //
866 // populate the exported interface's attributes
867 //
868 Dev->PassThru.Mode = &Dev->PassThruMode;
869 Dev->PassThru.PassThru = &VirtioScsiPassThru;
870 Dev->PassThru.GetNextTargetLun = &VirtioScsiGetNextTargetLun;
871 Dev->PassThru.BuildDevicePath = &VirtioScsiBuildDevicePath;
872 Dev->PassThru.GetTargetLun = &VirtioScsiGetTargetLun;
873 Dev->PassThru.ResetChannel = &VirtioScsiResetChannel;
874 Dev->PassThru.ResetTargetLun = &VirtioScsiResetTargetLun;
875 Dev->PassThru.GetNextTarget = &VirtioScsiGetNextTarget;
876
877 //
878 // AdapterId is a target for which no handle will be created during bus scan.
879 // Prevent any conflict with real devices.
880 //
881 Dev->PassThruMode.AdapterId = 0xFFFFFFFF;
882
883 //
884 // Set both physical and logical attributes for non-RAID SCSI channel. See
885 // Driver Writer's Guide for UEFI 2.3.1 v1.01, 20.1.5 Implementing Extended
886 // SCSI Pass Thru Protocol.
887 //
888 Dev->PassThruMode.Attributes = EFI_EXT_SCSI_PASS_THRU_ATTRIBUTES_PHYSICAL |
889 EFI_EXT_SCSI_PASS_THRU_ATTRIBUTES_LOGICAL;
890
891 //
892 // no restriction on transfer buffer alignment
893 //
894 Dev->PassThruMode.IoAlign = 0;
895
896 return EFI_SUCCESS;
897
898 ReleaseQueue:
899 VirtioRingUninit (&Dev->Ring);
900
901 Failed:
902 //
903 // Notify the host about our failure to setup: virtio-0.9.5, 2.2.2.1 Device
904 // Status. PCI IO access failure here should not mask the original error.
905 //
906 NextDevStat |= VSTAT_FAILED;
907 VIRTIO_CFG_WRITE (Dev, Generic.VhdrDeviceStatus, NextDevStat);
908
909 Dev->InOutSupported = FALSE;
910 Dev->MaxTarget = 0;
911 Dev->MaxLun = 0;
912 Dev->MaxSectors = 0;
913
914 return Status; // reached only via Failed above
915 }
916
917
918
919 STATIC
920 VOID
921 EFIAPI
922 VirtioScsiUninit (
923 IN OUT VSCSI_DEV *Dev
924 )
925 {
926 //
927 // Reset the virtual device -- see virtio-0.9.5, 2.2.2.1 Device Status. When
928 // VIRTIO_CFG_WRITE() returns, the host will have learned to stay away from
929 // the old comms area.
930 //
931 VIRTIO_CFG_WRITE (Dev, Generic.VhdrDeviceStatus, 0);
932
933 Dev->InOutSupported = FALSE;
934 Dev->MaxTarget = 0;
935 Dev->MaxLun = 0;
936 Dev->MaxSectors = 0;
937
938 VirtioRingUninit (&Dev->Ring);
939
940 SetMem (&Dev->PassThru, sizeof Dev->PassThru, 0x00);
941 SetMem (&Dev->PassThruMode, sizeof Dev->PassThruMode, 0x00);
942 }
943
944
945 //
946 // Probe, start and stop functions of this driver, called by the DXE core for
947 // specific devices.
948 //
949 // The following specifications document these interfaces:
950 // - Driver Writer's Guide for UEFI 2.3.1 v1.01, 9 Driver Binding Protocol
951 // - UEFI Spec 2.3.1 + Errata C, 10.1 EFI Driver Binding Protocol
952 //
953 // The implementation follows:
954 // - Driver Writer's Guide for UEFI 2.3.1 v1.01
955 // - 5.1.3.4 OpenProtocol() and CloseProtocol()
956 // - 18 PCI Driver Design Guidelines
957 // - 18.3 PCI drivers
958 // - UEFI Spec 2.3.1 + Errata C
959 // - 6.3 Protocol Handler Services
960 // - 13.4 EFI PCI I/O Protocol
961 //
962
963 EFI_STATUS
964 EFIAPI
965 VirtioScsiDriverBindingSupported (
966 IN EFI_DRIVER_BINDING_PROTOCOL *This,
967 IN EFI_HANDLE DeviceHandle,
968 IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath
969 )
970 {
971 EFI_STATUS Status;
972 EFI_PCI_IO_PROTOCOL *PciIo;
973 PCI_TYPE00 Pci;
974
975 //
976 // Attempt to open the device with the PciIo set of interfaces. On success,
977 // the protocol is "instantiated" for the PCI device. Covers duplicate open
978 // attempts (EFI_ALREADY_STARTED).
979 //
980 Status = gBS->OpenProtocol (
981 DeviceHandle, // candidate device
982 &gEfiPciIoProtocolGuid, // for generic PCI access
983 (VOID **)&PciIo, // handle to instantiate
984 This->DriverBindingHandle, // requestor driver identity
985 DeviceHandle, // ControllerHandle, according to
986 // the UEFI Driver Model
987 EFI_OPEN_PROTOCOL_BY_DRIVER // get exclusive PciIo access to
988 // the device; to be released
989 );
990 if (EFI_ERROR (Status)) {
991 return Status;
992 }
993
994 //
995 // Read entire PCI configuration header for more extensive check ahead.
996 //
997 Status = PciIo->Pci.Read (
998 PciIo, // (protocol, device)
999 // handle
1000 EfiPciIoWidthUint32, // access width & copy
1001 // mode
1002 0, // Offset
1003 sizeof Pci / sizeof (UINT32), // Count
1004 &Pci // target buffer
1005 );
1006
1007 if (Status == EFI_SUCCESS) {
1008 //
1009 // virtio-0.9.5, 2.1 PCI Discovery
1010 //
1011 Status = (Pci.Hdr.VendorId == 0x1AF4 &&
1012 Pci.Hdr.DeviceId >= 0x1000 && Pci.Hdr.DeviceId <= 0x103F &&
1013 Pci.Hdr.RevisionID == 0x00 &&
1014 Pci.Device.SubsystemID == VIRTIO_SUBSYSTEM_SCSI_HOST) ? EFI_SUCCESS : EFI_UNSUPPORTED;
1015 }
1016
1017 //
1018 // We needed PCI IO access only transitorily, to see whether we support the
1019 // device or not.
1020 //
1021 gBS->CloseProtocol (DeviceHandle, &gEfiPciIoProtocolGuid,
1022 This->DriverBindingHandle, DeviceHandle);
1023 return Status;
1024 }
1025
1026
1027 EFI_STATUS
1028 EFIAPI
1029 VirtioScsiDriverBindingStart (
1030 IN EFI_DRIVER_BINDING_PROTOCOL *This,
1031 IN EFI_HANDLE DeviceHandle,
1032 IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath
1033 )
1034 {
1035 VSCSI_DEV *Dev;
1036 EFI_STATUS Status;
1037
1038 Dev = (VSCSI_DEV *) AllocateZeroPool (sizeof *Dev);
1039 if (Dev == NULL) {
1040 return EFI_OUT_OF_RESOURCES;
1041 }
1042
1043 Status = gBS->OpenProtocol (DeviceHandle, &gEfiPciIoProtocolGuid,
1044 (VOID **)&Dev->PciIo, This->DriverBindingHandle,
1045 DeviceHandle, EFI_OPEN_PROTOCOL_BY_DRIVER);
1046 if (EFI_ERROR (Status)) {
1047 goto FreeVirtioScsi;
1048 }
1049
1050 //
1051 // We must retain and ultimately restore the original PCI attributes of the
1052 // device. See Driver Writer's Guide for UEFI 2.3.1 v1.01, 18.3 PCI drivers /
1053 // 18.3.2 Start() and Stop().
1054 //
1055 // The third parameter ("Attributes", input) is ignored by the Get operation.
1056 // The fourth parameter ("Result", output) is ignored by the Enable and Set
1057 // operations.
1058 //
1059 // For virtio-scsi we only need IO space access.
1060 //
1061 Status = Dev->PciIo->Attributes (Dev->PciIo, EfiPciIoAttributeOperationGet,
1062 0, &Dev->OriginalPciAttributes);
1063 if (EFI_ERROR (Status)) {
1064 goto ClosePciIo;
1065 }
1066
1067 Status = Dev->PciIo->Attributes (Dev->PciIo,
1068 EfiPciIoAttributeOperationEnable,
1069 EFI_PCI_IO_ATTRIBUTE_IO, NULL);
1070 if (EFI_ERROR (Status)) {
1071 goto ClosePciIo;
1072 }
1073
1074 //
1075 // PCI IO access granted, configure virtio-scsi device.
1076 //
1077 Status = VirtioScsiInit (Dev);
1078 if (EFI_ERROR (Status)) {
1079 goto RestorePciAttributes;
1080 }
1081
1082 //
1083 // Setup complete, attempt to export the driver instance's PassThru
1084 // interface.
1085 //
1086 Dev->Signature = VSCSI_SIG;
1087 Status = gBS->InstallProtocolInterface (&DeviceHandle,
1088 &gEfiExtScsiPassThruProtocolGuid, EFI_NATIVE_INTERFACE,
1089 &Dev->PassThru);
1090 if (EFI_ERROR (Status)) {
1091 goto UninitDev;
1092 }
1093
1094 return EFI_SUCCESS;
1095
1096 UninitDev:
1097 VirtioScsiUninit (Dev);
1098
1099 RestorePciAttributes:
1100 Dev->PciIo->Attributes (Dev->PciIo, EfiPciIoAttributeOperationSet,
1101 Dev->OriginalPciAttributes, NULL);
1102
1103 ClosePciIo:
1104 gBS->CloseProtocol (DeviceHandle, &gEfiPciIoProtocolGuid,
1105 This->DriverBindingHandle, DeviceHandle);
1106
1107 FreeVirtioScsi:
1108 FreePool (Dev);
1109
1110 return Status;
1111 }
1112
1113
1114 EFI_STATUS
1115 EFIAPI
1116 VirtioScsiDriverBindingStop (
1117 IN EFI_DRIVER_BINDING_PROTOCOL *This,
1118 IN EFI_HANDLE DeviceHandle,
1119 IN UINTN NumberOfChildren,
1120 IN EFI_HANDLE *ChildHandleBuffer
1121 )
1122 {
1123 EFI_STATUS Status;
1124 EFI_EXT_SCSI_PASS_THRU_PROTOCOL *PassThru;
1125 VSCSI_DEV *Dev;
1126
1127 Status = gBS->OpenProtocol (
1128 DeviceHandle, // candidate device
1129 &gEfiExtScsiPassThruProtocolGuid, // retrieve the SCSI iface
1130 (VOID **)&PassThru, // target pointer
1131 This->DriverBindingHandle, // requestor driver ident.
1132 DeviceHandle, // lookup req. for dev.
1133 EFI_OPEN_PROTOCOL_GET_PROTOCOL // lookup only, no new ref.
1134 );
1135 if (EFI_ERROR (Status)) {
1136 return Status;
1137 }
1138
1139 Dev = VIRTIO_SCSI_FROM_PASS_THRU (PassThru);
1140
1141 //
1142 // Handle Stop() requests for in-use driver instances gracefully.
1143 //
1144 Status = gBS->UninstallProtocolInterface (DeviceHandle,
1145 &gEfiExtScsiPassThruProtocolGuid, &Dev->PassThru);
1146 if (EFI_ERROR (Status)) {
1147 return Status;
1148 }
1149
1150 VirtioScsiUninit (Dev);
1151
1152 Dev->PciIo->Attributes (Dev->PciIo, EfiPciIoAttributeOperationSet,
1153 Dev->OriginalPciAttributes, NULL);
1154
1155 gBS->CloseProtocol (DeviceHandle, &gEfiPciIoProtocolGuid,
1156 This->DriverBindingHandle, DeviceHandle);
1157
1158 FreePool (Dev);
1159
1160 return EFI_SUCCESS;
1161 }
1162
1163
1164 //
1165 // The static object that groups the Supported() (ie. probe), Start() and
1166 // Stop() functions of the driver together. Refer to UEFI Spec 2.3.1 + Errata
1167 // C, 10.1 EFI Driver Binding Protocol.
1168 //
1169 STATIC EFI_DRIVER_BINDING_PROTOCOL gDriverBinding = {
1170 &VirtioScsiDriverBindingSupported,
1171 &VirtioScsiDriverBindingStart,
1172 &VirtioScsiDriverBindingStop,
1173 0x10, // Version, must be in [0x10 .. 0xFFFFFFEF] for IHV-developed drivers
1174 NULL, // ImageHandle, to be overwritten by
1175 // EfiLibInstallDriverBindingComponentName2() in VirtioScsiEntryPoint()
1176 NULL // DriverBindingHandle, ditto
1177 };
1178
1179
1180 //
1181 // The purpose of the following scaffolding (EFI_COMPONENT_NAME_PROTOCOL and
1182 // EFI_COMPONENT_NAME2_PROTOCOL implementation) is to format the driver's name
1183 // in English, for display on standard console devices. This is recommended for
1184 // UEFI drivers that follow the UEFI Driver Model. Refer to the Driver Writer's
1185 // Guide for UEFI 2.3.1 v1.01, 11 UEFI Driver and Controller Names.
1186 //
1187 // Device type names ("Virtio SCSI Host Device") are not formatted because the
1188 // driver supports only that device type. Therefore the driver name suffices
1189 // for unambiguous identification.
1190 //
1191
1192 STATIC
1193 EFI_UNICODE_STRING_TABLE mDriverNameTable[] = {
1194 { "eng;en", L"Virtio SCSI Host Driver" },
1195 { NULL, NULL }
1196 };
1197
1198 STATIC
1199 EFI_COMPONENT_NAME_PROTOCOL gComponentName;
1200
1201 EFI_STATUS
1202 EFIAPI
1203 VirtioScsiGetDriverName (
1204 IN EFI_COMPONENT_NAME_PROTOCOL *This,
1205 IN CHAR8 *Language,
1206 OUT CHAR16 **DriverName
1207 )
1208 {
1209 return LookupUnicodeString2 (
1210 Language,
1211 This->SupportedLanguages,
1212 mDriverNameTable,
1213 DriverName,
1214 (BOOLEAN)(This == &gComponentName) // Iso639Language
1215 );
1216 }
1217
1218 EFI_STATUS
1219 EFIAPI
1220 VirtioScsiGetDeviceName (
1221 IN EFI_COMPONENT_NAME_PROTOCOL *This,
1222 IN EFI_HANDLE DeviceHandle,
1223 IN EFI_HANDLE ChildHandle,
1224 IN CHAR8 *Language,
1225 OUT CHAR16 **ControllerName
1226 )
1227 {
1228 return EFI_UNSUPPORTED;
1229 }
1230
1231 STATIC
1232 EFI_COMPONENT_NAME_PROTOCOL gComponentName = {
1233 &VirtioScsiGetDriverName,
1234 &VirtioScsiGetDeviceName,
1235 "eng" // SupportedLanguages, ISO 639-2 language codes
1236 };
1237
1238 STATIC
1239 EFI_COMPONENT_NAME2_PROTOCOL gComponentName2 = {
1240 (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) &VirtioScsiGetDriverName,
1241 (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) &VirtioScsiGetDeviceName,
1242 "en" // SupportedLanguages, RFC 4646 language codes
1243 };
1244
1245
1246 //
1247 // Entry point of this driver.
1248 //
1249 EFI_STATUS
1250 EFIAPI
1251 VirtioScsiEntryPoint (
1252 IN EFI_HANDLE ImageHandle,
1253 IN EFI_SYSTEM_TABLE *SystemTable
1254 )
1255 {
1256 return EfiLibInstallDriverBindingComponentName2 (
1257 ImageHandle,
1258 SystemTable,
1259 &gDriverBinding,
1260 ImageHandle,
1261 &gComponentName,
1262 &gComponentName2
1263 );
1264 }