2 Rewrite the BootOrder NvVar based on QEMU's "bootorder" fw_cfg file.
4 Copyright (C) 2012 - 2014, Red Hat, Inc.
5 Copyright (c) 2013, Intel Corporation. All rights reserved.<BR>
7 This program and the accompanying materials are licensed and made available
8 under the terms and conditions of the BSD License which accompanies this
9 distribution. The full text of the license may be found at
10 http://opensource.org/licenses/bsd-license.php
12 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT
13 WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
16 #include <Library/QemuFwCfgLib.h>
17 #include <Library/DebugLib.h>
18 #include <Library/MemoryAllocationLib.h>
19 #include <Library/GenericBdsLib.h>
20 #include <Library/UefiBootServicesTableLib.h>
21 #include <Library/UefiRuntimeServicesTableLib.h>
22 #include <Library/BaseLib.h>
23 #include <Library/PrintLib.h>
24 #include <Library/DevicePathLib.h>
25 #include <Library/QemuBootOrderLib.h>
26 #include <Library/BaseMemoryLib.h>
27 #include <Guid/GlobalVariable.h>
28 #include <Guid/VirtioMmioTransport.h>
32 OpenFirmware to UEFI device path translation output buffer size in CHAR16's.
34 #define TRANSLATION_OUTPUT_SIZE 0x100
38 Numbers of nodes in OpenFirmware device paths that are required and examined.
40 #define REQUIRED_PCI_OFW_NODES 2
41 #define REQUIRED_MMIO_OFW_NODES 1
42 #define EXAMINED_OFW_NODES 4
46 Simple character classification routines, corresponding to POSIX class names
55 return (('0' <= Chr
&& Chr
<= '9') ||
56 ('A' <= Chr
&& Chr
<= 'Z') ||
57 ('a' <= Chr
&& Chr
<= 'z')
68 return (Chr
== ',' || Chr
== '.' || Chr
== '_' ||
69 Chr
== '+' || Chr
== '-'
80 return (32 <= Chr
&& Chr
<= 126 &&
81 Chr
!= '/' && Chr
!= '@' && Chr
!= ':');
86 Utility types and functions.
89 CONST CHAR8
*Ptr
; // not necessarily NUL-terminated
90 UINTN Len
; // number of non-NUL characters
96 Check if Substring and String have identical contents.
98 The function relies on the restriction that a SUBSTRING cannot have embedded
101 @param[in] Substring The SUBSTRING input to the comparison.
103 @param[in] String The ASCII string input to the comparison.
106 @return Whether the inputs have identical contents.
112 IN SUBSTRING Substring
,
113 IN CONST CHAR8
*String
122 while (Pos
< Substring
.Len
&& Substring
.Ptr
[Pos
] == *Chr
) {
127 return (BOOLEAN
)(Pos
== Substring
.Len
&& *Chr
== '\0');
133 Parse a comma-separated list of hexadecimal integers into the elements of an
136 Whitespace, "0x" prefixes, leading or trailing commas, sequences of commas,
137 or an empty string are not allowed; they are rejected.
139 The function relies on ASCII encoding.
141 @param[in] UnitAddress The substring to parse.
143 @param[out] Result The array, allocated by the caller, to receive
144 the parsed values. This parameter may be NULL if
145 NumResults is zero on input.
147 @param[in out] NumResults On input, the number of elements allocated for
148 Result. On output, the number of elements it has
149 taken (or would have taken) to parse the string
153 @retval RETURN_SUCCESS UnitAddress has been fully parsed.
154 NumResults is set to the number of parsed
155 values; the corresponding elements have
156 been set in Result. The rest of Result's
157 elements are unchanged.
159 @retval RETURN_BUFFER_TOO_SMALL UnitAddress has been fully parsed.
160 NumResults is set to the number of parsed
161 values, but elements have been stored only
162 up to the input value of NumResults, which
163 is less than what has been parsed.
165 @retval RETURN_INVALID_PARAMETER Parse error. The contents of Results is
166 indeterminate. NumResults has not been
172 ParseUnitAddressHexList (
173 IN SUBSTRING UnitAddress
,
175 IN OUT UINTN
*NumResults
178 UINTN Entry
; // number of entry currently being parsed
179 UINT64 EntryVal
; // value being constructed for current entry
180 CHAR8 PrevChr
; // UnitAddress character previously checked
181 UINTN Pos
; // current position within UnitAddress
182 RETURN_STATUS Status
;
188 for (Pos
= 0; Pos
< UnitAddress
.Len
; ++Pos
) {
192 Chr
= UnitAddress
.Ptr
[Pos
];
193 Val
= ('a' <= Chr
&& Chr
<= 'f') ? (Chr
- 'a' + 10) :
194 ('A' <= Chr
&& Chr
<= 'F') ? (Chr
- 'A' + 10) :
195 ('0' <= Chr
&& Chr
<= '9') ? (Chr
- '0' ) :
199 if (EntryVal
> 0xFFFFFFFFFFFFFFFull
) {
200 return RETURN_INVALID_PARAMETER
;
202 EntryVal
= LShiftU64 (EntryVal
, 4) | Val
;
203 } else if (Chr
== ',') {
204 if (PrevChr
== ',') {
205 return RETURN_INVALID_PARAMETER
;
207 if (Entry
< *NumResults
) {
208 Result
[Entry
] = EntryVal
;
213 return RETURN_INVALID_PARAMETER
;
219 if (PrevChr
== ',') {
220 return RETURN_INVALID_PARAMETER
;
222 if (Entry
< *NumResults
) {
223 Result
[Entry
] = EntryVal
;
224 Status
= RETURN_SUCCESS
;
226 Status
= RETURN_BUFFER_TOO_SMALL
;
236 A simple array of Boot Option ID's.
246 Array element tracking an enumerated boot option that has the
247 LOAD_OPTION_ACTIVE attribute.
250 CONST BDS_COMMON_OPTION
*BootOption
; // reference only, no ownership
251 BOOLEAN Appended
; // has been added to a BOOT_ORDER?
257 Append an active boot option to BootOrder, reallocating the latter if needed.
259 @param[in out] BootOrder The structure pointing to the array and holding
260 allocation and usage counters.
262 @param[in] ActiveOption The active boot option whose ID should be
263 appended to the array.
266 @retval RETURN_SUCCESS ID of ActiveOption appended.
268 @retval RETURN_OUT_OF_RESOURCES Memory reallocation failed.
274 IN OUT BOOT_ORDER
*BootOrder
,
275 IN OUT ACTIVE_OPTION
*ActiveOption
278 if (BootOrder
->Produced
== BootOrder
->Allocated
) {
282 ASSERT (BootOrder
->Allocated
> 0);
283 AllocatedNew
= BootOrder
->Allocated
* 2;
284 DataNew
= ReallocatePool (
285 BootOrder
->Allocated
* sizeof (*BootOrder
->Data
),
286 AllocatedNew
* sizeof (*DataNew
),
289 if (DataNew
== NULL
) {
290 return RETURN_OUT_OF_RESOURCES
;
292 BootOrder
->Allocated
= AllocatedNew
;
293 BootOrder
->Data
= DataNew
;
296 BootOrder
->Data
[BootOrder
->Produced
++] =
297 ActiveOption
->BootOption
->BootCurrent
;
298 ActiveOption
->Appended
= TRUE
;
299 return RETURN_SUCCESS
;
305 Create an array of ACTIVE_OPTION elements for a boot option list.
307 @param[in] BootOptionList A boot option list, created with
308 BdsLibEnumerateAllBootOption().
310 @param[out] ActiveOption Pointer to the first element in the new array.
311 The caller is responsible for freeing the array
312 with FreePool() after use.
314 @param[out] Count Number of elements in the new array.
317 @retval RETURN_SUCCESS The ActiveOption array has been created.
319 @retval RETURN_NOT_FOUND No active entry has been found in
322 @retval RETURN_OUT_OF_RESOURCES Memory allocation failed.
327 CollectActiveOptions (
328 IN CONST LIST_ENTRY
*BootOptionList
,
329 OUT ACTIVE_OPTION
**ActiveOption
,
335 *ActiveOption
= NULL
;
338 // Scan the list twice:
339 // - count active entries,
340 // - store links to active entries.
342 for (ScanMode
= 0; ScanMode
< 2; ++ScanMode
) {
343 CONST LIST_ENTRY
*Link
;
345 Link
= BootOptionList
->ForwardLink
;
347 while (Link
!= BootOptionList
) {
348 CONST BDS_COMMON_OPTION
*Current
;
350 Current
= CR (Link
, BDS_COMMON_OPTION
, Link
, BDS_LOAD_OPTION_SIGNATURE
);
351 if (IS_LOAD_OPTION_TYPE (Current
->Attribute
, LOAD_OPTION_ACTIVE
)) {
353 (*ActiveOption
)[*Count
].BootOption
= Current
;
354 (*ActiveOption
)[*Count
].Appended
= FALSE
;
358 Link
= Link
->ForwardLink
;
363 return RETURN_NOT_FOUND
;
365 *ActiveOption
= AllocatePool (*Count
* sizeof **ActiveOption
);
366 if (*ActiveOption
== NULL
) {
367 return RETURN_OUT_OF_RESOURCES
;
371 return RETURN_SUCCESS
;
376 OpenFirmware device path node
379 SUBSTRING DriverName
;
380 SUBSTRING UnitAddress
;
381 SUBSTRING DeviceArguments
;
387 Parse an OpenFirmware device path node into the caller-allocated OFW_NODE
388 structure, and advance in the input string.
390 The node format is mostly parsed after IEEE 1275-1994, 3.2.1.1 "Node names"
391 (a leading slash is expected and not returned):
393 /driver-name@unit-address[:device-arguments][<LF>]
395 A single trailing <LF> character is consumed but not returned. A trailing
396 <LF> or NUL character terminates the device path.
398 The function relies on ASCII encoding.
400 @param[in out] Ptr Address of the pointer pointing to the start of the
401 node string. After successful parsing *Ptr is set to
402 the byte immediately following the consumed
403 characters. On error it points to the byte that
404 caused the error. The input string is never modified.
406 @param[out] OfwNode The members of this structure point into the input
407 string, designating components of the node.
408 Separators are never included. If "device-arguments"
409 is missing, then DeviceArguments.Ptr is set to NULL.
410 All components that are present have nonzero length.
412 If the call doesn't succeed, the contents of this
413 structure is indeterminate.
415 @param[out] IsFinal In case of successul parsing, this parameter signals
416 whether the node just parsed is the final node in the
417 device path. The call after a final node will attempt
418 to start parsing the next path. If the call doesn't
419 succeed, then this parameter is not changed.
422 @retval RETURN_SUCCESS Parsing successful.
424 @retval RETURN_NOT_FOUND Parsing terminated. *Ptr was (and is)
425 pointing to an empty string.
427 @retval RETURN_INVALID_PARAMETER Parse error.
433 IN OUT CONST CHAR8
**Ptr
,
434 OUT OFW_NODE
*OfwNode
,
439 // A leading slash is expected. End of string is tolerated.
443 return RETURN_NOT_FOUND
;
450 return RETURN_INVALID_PARAMETER
;
456 OfwNode
->DriverName
.Ptr
= *Ptr
;
457 OfwNode
->DriverName
.Len
= 0;
458 while (OfwNode
->DriverName
.Len
< 32 &&
459 (IsAlnum (**Ptr
) || IsDriverNamePunct (**Ptr
))
462 ++OfwNode
->DriverName
.Len
;
465 if (OfwNode
->DriverName
.Len
== 0 || OfwNode
->DriverName
.Len
== 32) {
466 return RETURN_INVALID_PARAMETER
;
474 return RETURN_INVALID_PARAMETER
;
478 OfwNode
->UnitAddress
.Ptr
= *Ptr
;
479 OfwNode
->UnitAddress
.Len
= 0;
480 while (IsPrintNotDelim (**Ptr
)) {
482 ++OfwNode
->UnitAddress
.Len
;
485 if (OfwNode
->UnitAddress
.Len
== 0) {
486 return RETURN_INVALID_PARAMETER
;
491 // device-arguments, may be omitted
493 OfwNode
->DeviceArguments
.Len
= 0;
496 OfwNode
->DeviceArguments
.Ptr
= *Ptr
;
498 while (IsPrintNotDelim (**Ptr
)) {
500 ++OfwNode
->DeviceArguments
.Len
;
503 if (OfwNode
->DeviceArguments
.Len
== 0) {
504 return RETURN_INVALID_PARAMETER
;
508 OfwNode
->DeviceArguments
.Ptr
= NULL
;
527 return RETURN_INVALID_PARAMETER
;
532 "%a: DriverName=\"%.*a\" UnitAddress=\"%.*a\" DeviceArguments=\"%.*a\"\n",
534 OfwNode
->DriverName
.Len
, OfwNode
->DriverName
.Ptr
,
535 OfwNode
->UnitAddress
.Len
, OfwNode
->UnitAddress
.Ptr
,
536 OfwNode
->DeviceArguments
.Len
,
537 OfwNode
->DeviceArguments
.Ptr
== NULL
? "" : OfwNode
->DeviceArguments
.Ptr
539 return RETURN_SUCCESS
;
545 Translate a PCI-like array of OpenFirmware device nodes to a UEFI device path
548 @param[in] OfwNode Array of OpenFirmware device nodes to
549 translate, constituting the beginning of an
550 OpenFirmware device path.
552 @param[in] NumNodes Number of elements in OfwNode.
554 @param[out] Translated Destination array receiving the UEFI path
555 fragment, allocated by the caller. If the
556 return value differs from RETURN_SUCCESS, its
557 contents is indeterminate.
559 @param[in out] TranslatedSize On input, the number of CHAR16's in
560 Translated. On RETURN_SUCCESS this parameter
561 is assigned the number of non-NUL CHAR16's
562 written to Translated. In case of other return
563 values, TranslatedSize is indeterminate.
566 @retval RETURN_SUCCESS Translation successful.
568 @retval RETURN_BUFFER_TOO_SMALL The translation does not fit into the number
571 @retval RETURN_UNSUPPORTED The array of OpenFirmware device nodes can't
572 be translated in the current implementation.
577 TranslatePciOfwNodes (
578 IN CONST OFW_NODE
*OfwNode
,
580 OUT CHAR16
*Translated
,
581 IN OUT UINTN
*TranslatedSize
589 // Get PCI device and optional PCI function. Assume a single PCI root.
591 if (NumNodes
< REQUIRED_PCI_OFW_NODES
||
592 !SubstringEq (OfwNode
[0].DriverName
, "pci")
594 return RETURN_UNSUPPORTED
;
597 NumEntries
= sizeof (PciDevFun
) / sizeof (PciDevFun
[0]);
598 if (ParseUnitAddressHexList (
599 OfwNode
[1].UnitAddress
,
604 return RETURN_UNSUPPORTED
;
608 SubstringEq (OfwNode
[1].DriverName
, "ide") &&
609 SubstringEq (OfwNode
[2].DriverName
, "drive") &&
610 SubstringEq (OfwNode
[3].DriverName
, "disk")
613 // OpenFirmware device path (IDE disk, IDE CD-ROM):
615 // /pci@i0cf8/ide@1,1/drive@0/disk@0
617 // | | | | master or slave
618 // | | | primary or secondary
619 // | PCI slot & function holding IDE controller
620 // PCI root at system bus port, PIO
624 // PciRoot(0x0)/Pci(0x1,0x1)/Ata(Primary,Master,0x0)
632 if (ParseUnitAddressHexList (
633 OfwNode
[2].UnitAddress
,
636 ) != RETURN_SUCCESS
||
638 ParseUnitAddressHexList (
639 OfwNode
[3].UnitAddress
,
641 &NumEntries
// reuse after previous single-element call
642 ) != RETURN_SUCCESS
||
645 return RETURN_UNSUPPORTED
;
648 Written
= UnicodeSPrintAsciiFormat (
650 *TranslatedSize
* sizeof (*Translated
), // BufferSize in bytes
651 "PciRoot(0x0)/Pci(0x%Lx,0x%Lx)/Ata(%a,%a,0x0)",
654 Secondary
? "Secondary" : "Primary",
655 Slave
? "Slave" : "Master"
657 } else if (NumNodes
>= 4 &&
658 SubstringEq (OfwNode
[1].DriverName
, "isa") &&
659 SubstringEq (OfwNode
[2].DriverName
, "fdc") &&
660 SubstringEq (OfwNode
[3].DriverName
, "floppy")
663 // OpenFirmware device path (floppy disk):
665 // /pci@i0cf8/isa@1/fdc@03f0/floppy@0
668 // | | ISA controller io-port (hex)
669 // | PCI slot holding ISA controller
670 // PCI root at system bus port, PIO
674 // PciRoot(0x0)/Pci(0x1,0x0)/Floppy(0x0)
681 if (ParseUnitAddressHexList (
682 OfwNode
[3].UnitAddress
,
685 ) != RETURN_SUCCESS
||
688 return RETURN_UNSUPPORTED
;
691 Written
= UnicodeSPrintAsciiFormat (
693 *TranslatedSize
* sizeof (*Translated
), // BufferSize in bytes
694 "PciRoot(0x0)/Pci(0x%Lx,0x%Lx)/Floppy(0x%Lx)",
699 } else if (NumNodes
>= 3 &&
700 SubstringEq (OfwNode
[1].DriverName
, "scsi") &&
701 SubstringEq (OfwNode
[2].DriverName
, "disk")
704 // OpenFirmware device path (virtio-blk disk):
706 // /pci@i0cf8/scsi@6[,3]/disk@0,0
709 // | | PCI function corresponding to disk (optional)
710 // | PCI slot holding disk
711 // PCI root at system bus port, PIO
713 // UEFI device path prefix:
715 // PciRoot(0x0)/Pci(0x6,0x0)/HD( -- if PCI function is 0 or absent
716 // PciRoot(0x0)/Pci(0x6,0x3)/HD( -- if PCI function is present and nonzero
718 Written
= UnicodeSPrintAsciiFormat (
720 *TranslatedSize
* sizeof (*Translated
), // BufferSize in bytes
721 "PciRoot(0x0)/Pci(0x%Lx,0x%Lx)/HD(",
725 } else if (NumNodes
>= 4 &&
726 SubstringEq (OfwNode
[1].DriverName
, "scsi") &&
727 SubstringEq (OfwNode
[2].DriverName
, "channel") &&
728 SubstringEq (OfwNode
[3].DriverName
, "disk")
731 // OpenFirmware device path (virtio-scsi disk):
733 // /pci@i0cf8/scsi@7[,3]/channel@0/disk@2,3
737 // | | channel (unused, fixed 0)
738 // | PCI slot[, function] holding SCSI controller
739 // PCI root at system bus port, PIO
741 // UEFI device path prefix:
743 // PciRoot(0x0)/Pci(0x7,0x0)/Scsi(0x2,0x3)
744 // -- if PCI function is 0 or absent
745 // PciRoot(0x0)/Pci(0x7,0x3)/Scsi(0x2,0x3)
746 // -- if PCI function is present and nonzero
751 NumEntries
= sizeof (TargetLun
) / sizeof (TargetLun
[0]);
752 if (ParseUnitAddressHexList (
753 OfwNode
[3].UnitAddress
,
758 return RETURN_UNSUPPORTED
;
761 Written
= UnicodeSPrintAsciiFormat (
763 *TranslatedSize
* sizeof (*Translated
), // BufferSize in bytes
764 "PciRoot(0x0)/Pci(0x%Lx,0x%Lx)/Scsi(0x%Lx,0x%Lx)",
772 // Generic OpenFirmware device path for PCI devices:
774 // /pci@i0cf8/ethernet@3[,2]
776 // | PCI slot[, function] holding Ethernet card
777 // PCI root at system bus port, PIO
779 // UEFI device path prefix (dependent on presence of nonzero PCI function):
781 // PciRoot(0x0)/Pci(0x3,0x0)
782 // PciRoot(0x0)/Pci(0x3,0x2)
784 Written
= UnicodeSPrintAsciiFormat (
786 *TranslatedSize
* sizeof (*Translated
), // BufferSize in bytes
787 "PciRoot(0x0)/Pci(0x%Lx,0x%Lx)",
794 // There's no way to differentiate between "completely used up without
795 // truncation" and "truncated", so treat the former as the latter, and return
796 // success only for "some room left unused".
798 if (Written
+ 1 < *TranslatedSize
) {
799 *TranslatedSize
= Written
;
800 return RETURN_SUCCESS
;
803 return RETURN_BUFFER_TOO_SMALL
;
808 // A type providing easy raw access to the base address of a virtio-mmio
814 } VIRTIO_MMIO_BASE_ADDRESS
;
819 Translate an MMIO-like array of OpenFirmware device nodes to a UEFI device
822 @param[in] OfwNode Array of OpenFirmware device nodes to
823 translate, constituting the beginning of an
824 OpenFirmware device path.
826 @param[in] NumNodes Number of elements in OfwNode.
828 @param[out] Translated Destination array receiving the UEFI path
829 fragment, allocated by the caller. If the
830 return value differs from RETURN_SUCCESS, its
831 contents is indeterminate.
833 @param[in out] TranslatedSize On input, the number of CHAR16's in
834 Translated. On RETURN_SUCCESS this parameter
835 is assigned the number of non-NUL CHAR16's
836 written to Translated. In case of other return
837 values, TranslatedSize is indeterminate.
840 @retval RETURN_SUCCESS Translation successful.
842 @retval RETURN_BUFFER_TOO_SMALL The translation does not fit into the number
845 @retval RETURN_UNSUPPORTED The array of OpenFirmware device nodes can't
846 be translated in the current implementation.
851 TranslateMmioOfwNodes (
852 IN CONST OFW_NODE
*OfwNode
,
854 OUT CHAR16
*Translated
,
855 IN OUT UINTN
*TranslatedSize
858 VIRTIO_MMIO_BASE_ADDRESS VirtioMmioBase
;
859 CHAR16 VenHwString
[60 + 1];
864 // Get the base address of the virtio-mmio transport.
866 if (NumNodes
< REQUIRED_MMIO_OFW_NODES
||
867 !SubstringEq (OfwNode
[0].DriverName
, "virtio-mmio")
869 return RETURN_UNSUPPORTED
;
872 if (ParseUnitAddressHexList (
873 OfwNode
[0].UnitAddress
,
874 &VirtioMmioBase
.Uint64
,
878 return RETURN_UNSUPPORTED
;
881 UnicodeSPrintAsciiFormat (VenHwString
, sizeof VenHwString
,
882 "VenHw(%g,%02X%02X%02X%02X%02X%02X%02X%02X)", &gVirtioMmioTransportGuid
,
883 VirtioMmioBase
.Raw
[0], VirtioMmioBase
.Raw
[1], VirtioMmioBase
.Raw
[2],
884 VirtioMmioBase
.Raw
[3], VirtioMmioBase
.Raw
[4], VirtioMmioBase
.Raw
[5],
885 VirtioMmioBase
.Raw
[6], VirtioMmioBase
.Raw
[7]);
888 SubstringEq (OfwNode
[1].DriverName
, "disk")) {
890 // OpenFirmware device path (virtio-blk disk):
892 // /virtio-mmio@000000000a003c00/disk@0,0
895 // base address of virtio-mmio register block
897 // UEFI device path prefix:
901 Written
= UnicodeSPrintAsciiFormat (
903 *TranslatedSize
* sizeof (*Translated
), // BufferSize in bytes
907 } else if (NumNodes
>= 3 &&
908 SubstringEq (OfwNode
[1].DriverName
, "channel") &&
909 SubstringEq (OfwNode
[2].DriverName
, "disk")) {
911 // OpenFirmware device path (virtio-scsi disk):
913 // /virtio-mmio@000000000a003a00/channel@0/disk@2,3
917 // | channel (unused, fixed 0)
918 // base address of virtio-mmio register block
920 // UEFI device path prefix:
922 // <VenHwString>/Scsi(0x2,0x3)
927 NumEntries
= sizeof (TargetLun
) / sizeof (TargetLun
[0]);
928 if (ParseUnitAddressHexList (
929 OfwNode
[2].UnitAddress
,
934 return RETURN_UNSUPPORTED
;
937 Written
= UnicodeSPrintAsciiFormat (
939 *TranslatedSize
* sizeof (*Translated
), // BufferSize in bytes
940 "%s/Scsi(0x%Lx,0x%Lx)",
945 } else if (NumNodes
>= 2 &&
946 SubstringEq (OfwNode
[1].DriverName
, "ethernet-phy")) {
948 // OpenFirmware device path (virtio-net NIC):
950 // /virtio-mmio@000000000a003e00/ethernet-phy@0
953 // base address of virtio-mmio register block
955 // UEFI device path prefix (dependent on presence of nonzero PCI function):
957 // <VenHwString>/MAC(
959 Written
= UnicodeSPrintAsciiFormat (
961 *TranslatedSize
* sizeof (*Translated
), // BufferSize in bytes
966 return RETURN_UNSUPPORTED
;
970 // There's no way to differentiate between "completely used up without
971 // truncation" and "truncated", so treat the former as the latter, and return
972 // success only for "some room left unused".
974 if (Written
+ 1 < *TranslatedSize
) {
975 *TranslatedSize
= Written
;
976 return RETURN_SUCCESS
;
979 return RETURN_BUFFER_TOO_SMALL
;
985 Translate an array of OpenFirmware device nodes to a UEFI device path
988 @param[in] OfwNode Array of OpenFirmware device nodes to
989 translate, constituting the beginning of an
990 OpenFirmware device path.
992 @param[in] NumNodes Number of elements in OfwNode.
994 @param[out] Translated Destination array receiving the UEFI path
995 fragment, allocated by the caller. If the
996 return value differs from RETURN_SUCCESS, its
997 contents is indeterminate.
999 @param[in out] TranslatedSize On input, the number of CHAR16's in
1000 Translated. On RETURN_SUCCESS this parameter
1001 is assigned the number of non-NUL CHAR16's
1002 written to Translated. In case of other return
1003 values, TranslatedSize is indeterminate.
1006 @retval RETURN_SUCCESS Translation successful.
1008 @retval RETURN_BUFFER_TOO_SMALL The translation does not fit into the number
1011 @retval RETURN_UNSUPPORTED The array of OpenFirmware device nodes can't
1012 be translated in the current implementation.
1018 IN CONST OFW_NODE
*OfwNode
,
1020 OUT CHAR16
*Translated
,
1021 IN OUT UINTN
*TranslatedSize
1024 RETURN_STATUS Status
;
1026 Status
= RETURN_UNSUPPORTED
;
1028 if (FeaturePcdGet (PcdQemuBootOrderPciTranslation
)) {
1029 Status
= TranslatePciOfwNodes (OfwNode
, NumNodes
, Translated
,
1032 if (Status
== RETURN_UNSUPPORTED
&&
1033 FeaturePcdGet (PcdQemuBootOrderMmioTranslation
)) {
1034 Status
= TranslateMmioOfwNodes (OfwNode
, NumNodes
, Translated
,
1042 Translate an OpenFirmware device path fragment to a UEFI device path
1043 fragment, and advance in the input string.
1045 @param[in out] Ptr Address of the pointer pointing to the start
1046 of the path string. After successful
1047 translation (RETURN_SUCCESS) or at least
1048 successful parsing (RETURN_UNSUPPORTED,
1049 RETURN_BUFFER_TOO_SMALL), *Ptr is set to the
1050 byte immediately following the consumed
1051 characters. In other error cases, it points to
1052 the byte that caused the error.
1054 @param[out] Translated Destination array receiving the UEFI path
1055 fragment, allocated by the caller. If the
1056 return value differs from RETURN_SUCCESS, its
1057 contents is indeterminate.
1059 @param[in out] TranslatedSize On input, the number of CHAR16's in
1060 Translated. On RETURN_SUCCESS this parameter
1061 is assigned the number of non-NUL CHAR16's
1062 written to Translated. In case of other return
1063 values, TranslatedSize is indeterminate.
1066 @retval RETURN_SUCCESS Translation successful.
1068 @retval RETURN_BUFFER_TOO_SMALL The OpenFirmware device path was parsed
1069 successfully, but its translation did not
1070 fit into the number of bytes provided.
1071 Further calls to this function are
1074 @retval RETURN_UNSUPPORTED The OpenFirmware device path was parsed
1075 successfully, but it can't be translated in
1076 the current implementation. Further calls
1077 to this function are possible.
1079 @retval RETURN_NOT_FOUND Translation terminated. On input, *Ptr was
1080 pointing to the empty string or "HALT". On
1081 output, *Ptr points to the empty string
1082 (ie. "HALT" is consumed transparently when
1085 @retval RETURN_INVALID_PARAMETER Parse error. This is a permanent error.
1091 IN OUT CONST CHAR8
**Ptr
,
1092 OUT CHAR16
*Translated
,
1093 IN OUT UINTN
*TranslatedSize
1097 RETURN_STATUS Status
;
1098 OFW_NODE Node
[EXAMINED_OFW_NODES
];
1104 if (AsciiStrCmp (*Ptr
, "HALT") == 0) {
1106 Status
= RETURN_NOT_FOUND
;
1108 Status
= ParseOfwNode (Ptr
, &Node
[NumNodes
], &IsFinal
);
1111 if (Status
== RETURN_NOT_FOUND
) {
1112 DEBUG ((DEBUG_VERBOSE
, "%a: no more nodes\n", __FUNCTION__
));
1113 return RETURN_NOT_FOUND
;
1116 while (Status
== RETURN_SUCCESS
&& !IsFinal
) {
1118 Status
= ParseOfwNode (
1120 (NumNodes
< EXAMINED_OFW_NODES
) ? &Node
[NumNodes
] : &Skip
,
1126 case RETURN_SUCCESS
:
1130 case RETURN_INVALID_PARAMETER
:
1131 DEBUG ((DEBUG_VERBOSE
, "%a: parse error\n", __FUNCTION__
));
1132 return RETURN_INVALID_PARAMETER
;
1138 Status
= TranslateOfwNodes (
1140 NumNodes
< EXAMINED_OFW_NODES
? NumNodes
: EXAMINED_OFW_NODES
,
1144 case RETURN_SUCCESS
:
1145 DEBUG ((DEBUG_VERBOSE
, "%a: success: \"%s\"\n", __FUNCTION__
, Translated
));
1148 case RETURN_BUFFER_TOO_SMALL
:
1149 DEBUG ((DEBUG_VERBOSE
, "%a: buffer too small\n", __FUNCTION__
));
1152 case RETURN_UNSUPPORTED
:
1153 DEBUG ((DEBUG_VERBOSE
, "%a: unsupported\n", __FUNCTION__
));
1165 Convert the UEFI DevicePath to full text representation with DevPathToText,
1166 then match the UEFI device path fragment in Translated against it.
1168 @param[in] Translated UEFI device path fragment, translated from
1169 OpenFirmware format, to search for.
1171 @param[in] TranslatedLength The length of Translated in CHAR16's.
1173 @param[in] DevicePath Boot option device path whose textual rendering
1176 @param[in] DevPathToText Binary-to-text conversion protocol for DevicePath.
1179 @retval TRUE If Translated was found at the beginning of DevicePath after
1180 converting the latter to text.
1182 @retval FALSE If DevicePath was NULL, or it could not be converted, or there
1189 IN CONST CHAR16
*Translated
,
1190 IN UINTN TranslatedLength
,
1191 IN CONST EFI_DEVICE_PATH_PROTOCOL
*DevicePath
1197 Converted
= ConvertDevicePathToText (
1199 FALSE
, // DisplayOnly
1200 FALSE
// AllowShortcuts
1202 if (Converted
== NULL
) {
1207 // Attempt to expand any relative UEFI device path starting with HD() to an
1208 // absolute device path first. The logic imitates BdsLibBootViaBootOption().
1209 // We don't have to free the absolute device path,
1210 // BdsExpandPartitionPartialDevicePathToFull() has internal caching.
1213 if (DevicePathType (DevicePath
) == MEDIA_DEVICE_PATH
&&
1214 DevicePathSubType (DevicePath
) == MEDIA_HARDDRIVE_DP
) {
1215 EFI_DEVICE_PATH_PROTOCOL
*AbsDevicePath
;
1216 CHAR16
*AbsConverted
;
1218 AbsDevicePath
= BdsExpandPartitionPartialDevicePathToFull (
1219 (HARDDRIVE_DEVICE_PATH
*) DevicePath
);
1220 if (AbsDevicePath
== NULL
) {
1223 AbsConverted
= ConvertDevicePathToText (AbsDevicePath
, FALSE
, FALSE
);
1224 if (AbsConverted
== NULL
) {
1227 DEBUG ((DEBUG_VERBOSE
,
1228 "%a: expanded relative device path \"%s\" for prefix matching\n",
1229 __FUNCTION__
, Converted
));
1230 FreePool (Converted
);
1231 Converted
= AbsConverted
;
1235 // Is Translated a prefix of Converted?
1237 Result
= (BOOLEAN
)(StrnCmp (Converted
, Translated
, TranslatedLength
) == 0);
1240 "%a: against \"%s\": %a\n",
1243 Result
? "match" : "no match"
1246 FreePool (Converted
);
1252 Append some of the unselected active boot options to the boot order.
1254 This function should accommodate any further policy changes in "boot option
1255 survival". Currently we're adding back everything that starts with neither
1256 PciRoot() nor HD() nor a virtio-mmio VenHw() node.
1258 @param[in,out] BootOrder The structure holding the boot order to
1259 complete. The caller is responsible for
1260 initializing (and potentially populating) it
1261 before calling this function.
1263 @param[in,out] ActiveOption The array of active boot options to scan.
1264 Entries marked as Appended will be skipped.
1265 Those of the rest that satisfy the survival
1266 policy will be added to BootOrder with
1269 @param[in] ActiveCount Number of elements in ActiveOption.
1272 @retval RETURN_SUCCESS BootOrder has been extended with any eligible boot
1275 @return Error codes returned by BootOrderAppend().
1280 IN OUT BOOT_ORDER
*BootOrder
,
1281 IN OUT ACTIVE_OPTION
*ActiveOption
,
1282 IN UINTN ActiveCount
1285 RETURN_STATUS Status
;
1288 Status
= RETURN_SUCCESS
;
1290 while (!RETURN_ERROR (Status
) && Idx
< ActiveCount
) {
1291 if (!ActiveOption
[Idx
].Appended
) {
1292 CONST BDS_COMMON_OPTION
*Current
;
1293 CONST EFI_DEVICE_PATH_PROTOCOL
*FirstNode
;
1295 Current
= ActiveOption
[Idx
].BootOption
;
1296 FirstNode
= Current
->DevicePath
;
1297 if (FirstNode
!= NULL
) {
1299 STATIC CHAR16 ConvFallBack
[] = L
"<unable to convert>";
1302 Converted
= ConvertDevicePathToText (FirstNode
, FALSE
, FALSE
);
1303 if (Converted
== NULL
) {
1304 Converted
= ConvFallBack
;
1308 if (DevicePathType(FirstNode
) == MEDIA_DEVICE_PATH
&&
1309 DevicePathSubType(FirstNode
) == MEDIA_HARDDRIVE_DP
) {
1314 } else if (DevicePathType(FirstNode
) == ACPI_DEVICE_PATH
&&
1315 DevicePathSubType(FirstNode
) == ACPI_DP
) {
1316 ACPI_HID_DEVICE_PATH
*Acpi
;
1318 Acpi
= (ACPI_HID_DEVICE_PATH
*) FirstNode
;
1319 if ((Acpi
->HID
& PNP_EISA_ID_MASK
) == PNP_EISA_ID_CONST
&&
1320 EISA_ID_TO_NUM (Acpi
->HID
) == 0x0a03) {
1322 // drop PciRoot() if we enabled the user to select PCI-like boot
1323 // options, by providing translation for such OFW device path
1326 Keep
= !FeaturePcdGet (PcdQemuBootOrderPciTranslation
);
1328 } else if (DevicePathType(FirstNode
) == HARDWARE_DEVICE_PATH
&&
1329 DevicePathSubType(FirstNode
) == HW_VENDOR_DP
) {
1330 VENDOR_DEVICE_PATH
*VenHw
;
1332 VenHw
= (VENDOR_DEVICE_PATH
*)FirstNode
;
1333 if (CompareGuid (&VenHw
->Guid
, &gVirtioMmioTransportGuid
)) {
1335 // drop virtio-mmio if we enabled the user to select boot options
1336 // referencing such device paths
1338 Keep
= !FeaturePcdGet (PcdQemuBootOrderMmioTranslation
);
1343 Status
= BootOrderAppend (BootOrder
, &ActiveOption
[Idx
]);
1344 if (!RETURN_ERROR (Status
)) {
1345 DEBUG ((DEBUG_VERBOSE
, "%a: keeping \"%s\"\n", __FUNCTION__
,
1349 DEBUG ((DEBUG_VERBOSE
, "%a: dropping \"%s\"\n", __FUNCTION__
,
1353 if (Converted
!= ConvFallBack
) {
1354 FreePool (Converted
);
1365 Delete Boot#### variables that stand for such active boot options that have
1366 been dropped (ie. have not been selected by either matching or "survival
1369 @param[in] ActiveOption The array of active boot options to scan. Each
1370 entry not marked as appended will trigger the
1371 deletion of the matching Boot#### variable.
1373 @param[in] ActiveCount Number of elements in ActiveOption.
1377 PruneBootVariables (
1378 IN CONST ACTIVE_OPTION
*ActiveOption
,
1379 IN UINTN ActiveCount
1384 for (Idx
= 0; Idx
< ActiveCount
; ++Idx
) {
1385 if (!ActiveOption
[Idx
].Appended
) {
1386 CHAR16 VariableName
[9];
1388 UnicodeSPrintAsciiFormat (VariableName
, sizeof VariableName
, "Boot%04x",
1389 ActiveOption
[Idx
].BootOption
->BootCurrent
);
1392 // "The space consumed by the deleted variable may not be available until
1393 // the next power cycle", but that's good enough.
1395 gRT
->SetVariable (VariableName
, &gEfiGlobalVariableGuid
,
1396 0, // Attributes, 0 means deletion
1397 0, // DataSize, 0 means deletion
1407 Set the boot order based on configuration retrieved from QEMU.
1409 Attempt to retrieve the "bootorder" fw_cfg file from QEMU. Translate the
1410 OpenFirmware device paths therein to UEFI device path fragments. Match the
1411 translated fragments against BootOptionList, and rewrite the BootOrder NvVar
1412 so that it corresponds to the order described in fw_cfg.
1414 @param[in] BootOptionList A boot option list, created with
1415 BdsLibEnumerateAllBootOption ().
1418 @retval RETURN_SUCCESS BootOrder NvVar rewritten.
1420 @retval RETURN_UNSUPPORTED QEMU's fw_cfg is not supported.
1422 @retval RETURN_NOT_FOUND Empty or nonexistent "bootorder" fw_cfg
1423 file, or no match found between the
1424 "bootorder" fw_cfg file and BootOptionList.
1426 @retval RETURN_INVALID_PARAMETER Parse error in the "bootorder" fw_cfg file.
1428 @retval RETURN_OUT_OF_RESOURCES Memory allocation failed.
1430 @return Values returned by gBS->LocateProtocol ()
1431 or gRT->SetVariable ().
1435 SetBootOrderFromQemu (
1436 IN CONST LIST_ENTRY
*BootOptionList
1439 RETURN_STATUS Status
;
1440 FIRMWARE_CONFIG_ITEM FwCfgItem
;
1443 CONST CHAR8
*FwCfgPtr
;
1445 BOOT_ORDER BootOrder
;
1446 ACTIVE_OPTION
*ActiveOption
;
1449 UINTN TranslatedSize
;
1450 CHAR16 Translated
[TRANSLATION_OUTPUT_SIZE
];
1452 Status
= QemuFwCfgFindFile ("bootorder", &FwCfgItem
, &FwCfgSize
);
1453 if (Status
!= RETURN_SUCCESS
) {
1457 if (FwCfgSize
== 0) {
1458 return RETURN_NOT_FOUND
;
1461 FwCfg
= AllocatePool (FwCfgSize
);
1462 if (FwCfg
== NULL
) {
1463 return RETURN_OUT_OF_RESOURCES
;
1466 QemuFwCfgSelectItem (FwCfgItem
);
1467 QemuFwCfgReadBytes (FwCfgSize
, FwCfg
);
1468 if (FwCfg
[FwCfgSize
- 1] != '\0') {
1469 Status
= RETURN_INVALID_PARAMETER
;
1470 goto ErrorFreeFwCfg
;
1473 DEBUG ((DEBUG_VERBOSE
, "%a: FwCfg:\n", __FUNCTION__
));
1474 DEBUG ((DEBUG_VERBOSE
, "%a\n", FwCfg
));
1475 DEBUG ((DEBUG_VERBOSE
, "%a: FwCfg: <end>\n", __FUNCTION__
));
1478 BootOrder
.Produced
= 0;
1479 BootOrder
.Allocated
= 1;
1480 BootOrder
.Data
= AllocatePool (
1481 BootOrder
.Allocated
* sizeof (*BootOrder
.Data
)
1483 if (BootOrder
.Data
== NULL
) {
1484 Status
= RETURN_OUT_OF_RESOURCES
;
1485 goto ErrorFreeFwCfg
;
1488 Status
= CollectActiveOptions (BootOptionList
, &ActiveOption
, &ActiveCount
);
1489 if (RETURN_ERROR (Status
)) {
1490 goto ErrorFreeBootOrder
;
1494 // translate each OpenFirmware path
1496 TranslatedSize
= sizeof (Translated
) / sizeof (Translated
[0]);
1497 Status
= TranslateOfwPath (&FwCfgPtr
, Translated
, &TranslatedSize
);
1498 while (Status
== RETURN_SUCCESS
||
1499 Status
== RETURN_UNSUPPORTED
||
1500 Status
== RETURN_BUFFER_TOO_SMALL
) {
1501 if (Status
== RETURN_SUCCESS
) {
1505 // match translated OpenFirmware path against all active boot options
1507 for (Idx
= 0; Idx
< ActiveCount
; ++Idx
) {
1510 TranslatedSize
, // contains length, not size, in CHAR16's here
1511 ActiveOption
[Idx
].BootOption
->DevicePath
1515 // match found, store ID and continue with next OpenFirmware path
1517 Status
= BootOrderAppend (&BootOrder
, &ActiveOption
[Idx
]);
1518 if (Status
!= RETURN_SUCCESS
) {
1519 goto ErrorFreeActiveOption
;
1523 } // scanned all active boot options
1524 } // translation successful
1526 TranslatedSize
= sizeof (Translated
) / sizeof (Translated
[0]);
1527 Status
= TranslateOfwPath (&FwCfgPtr
, Translated
, &TranslatedSize
);
1528 } // scanning of OpenFirmware paths done
1530 if (Status
== RETURN_NOT_FOUND
&& BootOrder
.Produced
> 0) {
1532 // No more OpenFirmware paths, some matches found: rewrite BootOrder NvVar.
1533 // Some of the active boot options that have not been selected over fw_cfg
1534 // should be preserved at the end of the boot order.
1536 Status
= BootOrderComplete (&BootOrder
, ActiveOption
, ActiveCount
);
1537 if (RETURN_ERROR (Status
)) {
1538 goto ErrorFreeActiveOption
;
1542 // See Table 10 in the UEFI Spec 2.3.1 with Errata C for the required
1545 Status
= gRT
->SetVariable (
1547 &gEfiGlobalVariableGuid
,
1548 EFI_VARIABLE_NON_VOLATILE
|
1549 EFI_VARIABLE_BOOTSERVICE_ACCESS
|
1550 EFI_VARIABLE_RUNTIME_ACCESS
,
1551 BootOrder
.Produced
* sizeof (*BootOrder
.Data
),
1554 if (EFI_ERROR (Status
)) {
1555 DEBUG ((DEBUG_ERROR
, "%a: setting BootOrder: %r\n", __FUNCTION__
, Status
));
1556 goto ErrorFreeActiveOption
;
1559 DEBUG ((DEBUG_INFO
, "%a: setting BootOrder: success\n", __FUNCTION__
));
1560 PruneBootVariables (ActiveOption
, ActiveCount
);
1563 ErrorFreeActiveOption
:
1564 FreePool (ActiveOption
);
1567 FreePool (BootOrder
.Data
);
1577 Calculate the number of seconds we should be showing the FrontPage progress
1580 @return The TimeoutDefault argument for PlatformBdsEnterFrontPage().
1583 GetFrontPageTimeoutFromQemu (
1587 FIRMWARE_CONFIG_ITEM BootMenuWaitItem
;
1588 UINTN BootMenuWaitSize
;
1590 QemuFwCfgSelectItem (QemuFwCfgItemBootMenu
);
1591 if (QemuFwCfgRead16 () == 0) {
1593 // The user specified "-boot menu=off", or didn't specify "-boot
1594 // menu=(on|off)" at all. Return the platform default.
1596 return PcdGet16 (PcdPlatformBootTimeOut
);
1599 if (RETURN_ERROR (QemuFwCfgFindFile ("etc/boot-menu-wait", &BootMenuWaitItem
,
1600 &BootMenuWaitSize
)) ||
1601 BootMenuWaitSize
!= sizeof (UINT16
)) {
1603 // "-boot menu=on" was specified without "splash-time=N". In this case,
1604 // return three seconds if the platform default would cause us to skip the
1605 // front page, and return the platform default otherwise.
1609 Timeout
= PcdGet16 (PcdPlatformBootTimeOut
);
1617 // "-boot menu=on,splash-time=N" was specified, where N is in units of
1618 // milliseconds. The Intel BDS Front Page progress bar only supports whole
1619 // seconds, round N up.
1621 QemuFwCfgSelectItem (BootMenuWaitItem
);
1622 return (UINT16
)((QemuFwCfgRead16 () + 999) / 1000);