]> git.proxmox.com Git - mirror_edk2.git/blob - OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.c
OvmfPkg: QemuBootOrderLib: widen ParseUnitAddressHexList() to UINT64
[mirror_edk2.git] / OvmfPkg / Library / QemuBootOrderLib / QemuBootOrderLib.c
1 /** @file
2 Rewrite the BootOrder NvVar based on QEMU's "bootorder" fw_cfg file.
3
4 Copyright (C) 2012 - 2014, Red Hat, Inc.
5 Copyright (c) 2013, Intel Corporation. All rights reserved.<BR>
6
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
11
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.
14 **/
15
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 <Guid/GlobalVariable.h>
27
28
29 /**
30 OpenFirmware to UEFI device path translation output buffer size in CHAR16's.
31 **/
32 #define TRANSLATION_OUTPUT_SIZE 0x100
33
34
35 /**
36 Numbers of nodes in OpenFirmware device paths that are required and examined.
37 **/
38 #define REQUIRED_PCI_OFW_NODES 2
39 #define EXAMINED_OFW_NODES 4
40
41
42 /**
43 Simple character classification routines, corresponding to POSIX class names
44 and ASCII encoding.
45 **/
46 STATIC
47 BOOLEAN
48 IsAlnum (
49 IN CHAR8 Chr
50 )
51 {
52 return (('0' <= Chr && Chr <= '9') ||
53 ('A' <= Chr && Chr <= 'Z') ||
54 ('a' <= Chr && Chr <= 'z')
55 );
56 }
57
58
59 STATIC
60 BOOLEAN
61 IsDriverNamePunct (
62 IN CHAR8 Chr
63 )
64 {
65 return (Chr == ',' || Chr == '.' || Chr == '_' ||
66 Chr == '+' || Chr == '-'
67 );
68 }
69
70
71 STATIC
72 BOOLEAN
73 IsPrintNotDelim (
74 IN CHAR8 Chr
75 )
76 {
77 return (32 <= Chr && Chr <= 126 &&
78 Chr != '/' && Chr != '@' && Chr != ':');
79 }
80
81
82 /**
83 Utility types and functions.
84 **/
85 typedef struct {
86 CONST CHAR8 *Ptr; // not necessarily NUL-terminated
87 UINTN Len; // number of non-NUL characters
88 } SUBSTRING;
89
90
91 /**
92
93 Check if Substring and String have identical contents.
94
95 The function relies on the restriction that a SUBSTRING cannot have embedded
96 NULs either.
97
98 @param[in] Substring The SUBSTRING input to the comparison.
99
100 @param[in] String The ASCII string input to the comparison.
101
102
103 @return Whether the inputs have identical contents.
104
105 **/
106 STATIC
107 BOOLEAN
108 SubstringEq (
109 IN SUBSTRING Substring,
110 IN CONST CHAR8 *String
111 )
112 {
113 UINTN Pos;
114 CONST CHAR8 *Chr;
115
116 Pos = 0;
117 Chr = String;
118
119 while (Pos < Substring.Len && Substring.Ptr[Pos] == *Chr) {
120 ++Pos;
121 ++Chr;
122 }
123
124 return (BOOLEAN)(Pos == Substring.Len && *Chr == '\0');
125 }
126
127
128 /**
129
130 Parse a comma-separated list of hexadecimal integers into the elements of an
131 UINT64 array.
132
133 Whitespace, "0x" prefixes, leading or trailing commas, sequences of commas,
134 or an empty string are not allowed; they are rejected.
135
136 The function relies on ASCII encoding.
137
138 @param[in] UnitAddress The substring to parse.
139
140 @param[out] Result The array, allocated by the caller, to receive
141 the parsed values. This parameter may be NULL if
142 NumResults is zero on input.
143
144 @param[in out] NumResults On input, the number of elements allocated for
145 Result. On output, the number of elements it has
146 taken (or would have taken) to parse the string
147 fully.
148
149
150 @retval RETURN_SUCCESS UnitAddress has been fully parsed.
151 NumResults is set to the number of parsed
152 values; the corresponding elements have
153 been set in Result. The rest of Result's
154 elements are unchanged.
155
156 @retval RETURN_BUFFER_TOO_SMALL UnitAddress has been fully parsed.
157 NumResults is set to the number of parsed
158 values, but elements have been stored only
159 up to the input value of NumResults, which
160 is less than what has been parsed.
161
162 @retval RETURN_INVALID_PARAMETER Parse error. The contents of Results is
163 indeterminate. NumResults has not been
164 changed.
165
166 **/
167 STATIC
168 RETURN_STATUS
169 ParseUnitAddressHexList (
170 IN SUBSTRING UnitAddress,
171 OUT UINT64 *Result,
172 IN OUT UINTN *NumResults
173 )
174 {
175 UINTN Entry; // number of entry currently being parsed
176 UINT64 EntryVal; // value being constructed for current entry
177 CHAR8 PrevChr; // UnitAddress character previously checked
178 UINTN Pos; // current position within UnitAddress
179 RETURN_STATUS Status;
180
181 Entry = 0;
182 EntryVal = 0;
183 PrevChr = ',';
184
185 for (Pos = 0; Pos < UnitAddress.Len; ++Pos) {
186 CHAR8 Chr;
187 INT8 Val;
188
189 Chr = UnitAddress.Ptr[Pos];
190 Val = ('a' <= Chr && Chr <= 'f') ? (Chr - 'a' + 10) :
191 ('A' <= Chr && Chr <= 'F') ? (Chr - 'A' + 10) :
192 ('0' <= Chr && Chr <= '9') ? (Chr - '0' ) :
193 -1;
194
195 if (Val >= 0) {
196 if (EntryVal > 0xFFFFFFFFFFFFFFFull) {
197 return RETURN_INVALID_PARAMETER;
198 }
199 EntryVal = LShiftU64 (EntryVal, 4) | Val;
200 } else if (Chr == ',') {
201 if (PrevChr == ',') {
202 return RETURN_INVALID_PARAMETER;
203 }
204 if (Entry < *NumResults) {
205 Result[Entry] = EntryVal;
206 }
207 ++Entry;
208 EntryVal = 0;
209 } else {
210 return RETURN_INVALID_PARAMETER;
211 }
212
213 PrevChr = Chr;
214 }
215
216 if (PrevChr == ',') {
217 return RETURN_INVALID_PARAMETER;
218 }
219 if (Entry < *NumResults) {
220 Result[Entry] = EntryVal;
221 Status = RETURN_SUCCESS;
222 } else {
223 Status = RETURN_BUFFER_TOO_SMALL;
224 }
225 ++Entry;
226
227 *NumResults = Entry;
228 return Status;
229 }
230
231
232 /**
233 A simple array of Boot Option ID's.
234 **/
235 typedef struct {
236 UINT16 *Data;
237 UINTN Allocated;
238 UINTN Produced;
239 } BOOT_ORDER;
240
241
242 /**
243 Array element tracking an enumerated boot option that has the
244 LOAD_OPTION_ACTIVE attribute.
245 **/
246 typedef struct {
247 CONST BDS_COMMON_OPTION *BootOption; // reference only, no ownership
248 BOOLEAN Appended; // has been added to a BOOT_ORDER?
249 } ACTIVE_OPTION;
250
251
252 /**
253
254 Append an active boot option to BootOrder, reallocating the latter if needed.
255
256 @param[in out] BootOrder The structure pointing to the array and holding
257 allocation and usage counters.
258
259 @param[in] ActiveOption The active boot option whose ID should be
260 appended to the array.
261
262
263 @retval RETURN_SUCCESS ID of ActiveOption appended.
264
265 @retval RETURN_OUT_OF_RESOURCES Memory reallocation failed.
266
267 **/
268 STATIC
269 RETURN_STATUS
270 BootOrderAppend (
271 IN OUT BOOT_ORDER *BootOrder,
272 IN OUT ACTIVE_OPTION *ActiveOption
273 )
274 {
275 if (BootOrder->Produced == BootOrder->Allocated) {
276 UINTN AllocatedNew;
277 UINT16 *DataNew;
278
279 ASSERT (BootOrder->Allocated > 0);
280 AllocatedNew = BootOrder->Allocated * 2;
281 DataNew = ReallocatePool (
282 BootOrder->Allocated * sizeof (*BootOrder->Data),
283 AllocatedNew * sizeof (*DataNew),
284 BootOrder->Data
285 );
286 if (DataNew == NULL) {
287 return RETURN_OUT_OF_RESOURCES;
288 }
289 BootOrder->Allocated = AllocatedNew;
290 BootOrder->Data = DataNew;
291 }
292
293 BootOrder->Data[BootOrder->Produced++] =
294 ActiveOption->BootOption->BootCurrent;
295 ActiveOption->Appended = TRUE;
296 return RETURN_SUCCESS;
297 }
298
299
300 /**
301
302 Create an array of ACTIVE_OPTION elements for a boot option list.
303
304 @param[in] BootOptionList A boot option list, created with
305 BdsLibEnumerateAllBootOption().
306
307 @param[out] ActiveOption Pointer to the first element in the new array.
308 The caller is responsible for freeing the array
309 with FreePool() after use.
310
311 @param[out] Count Number of elements in the new array.
312
313
314 @retval RETURN_SUCCESS The ActiveOption array has been created.
315
316 @retval RETURN_NOT_FOUND No active entry has been found in
317 BootOptionList.
318
319 @retval RETURN_OUT_OF_RESOURCES Memory allocation failed.
320
321 **/
322 STATIC
323 RETURN_STATUS
324 CollectActiveOptions (
325 IN CONST LIST_ENTRY *BootOptionList,
326 OUT ACTIVE_OPTION **ActiveOption,
327 OUT UINTN *Count
328 )
329 {
330 UINTN ScanMode;
331
332 *ActiveOption = NULL;
333
334 //
335 // Scan the list twice:
336 // - count active entries,
337 // - store links to active entries.
338 //
339 for (ScanMode = 0; ScanMode < 2; ++ScanMode) {
340 CONST LIST_ENTRY *Link;
341
342 Link = BootOptionList->ForwardLink;
343 *Count = 0;
344 while (Link != BootOptionList) {
345 CONST BDS_COMMON_OPTION *Current;
346
347 Current = CR (Link, BDS_COMMON_OPTION, Link, BDS_LOAD_OPTION_SIGNATURE);
348 if (IS_LOAD_OPTION_TYPE (Current->Attribute, LOAD_OPTION_ACTIVE)) {
349 if (ScanMode == 1) {
350 (*ActiveOption)[*Count].BootOption = Current;
351 (*ActiveOption)[*Count].Appended = FALSE;
352 }
353 ++*Count;
354 }
355 Link = Link->ForwardLink;
356 }
357
358 if (ScanMode == 0) {
359 if (*Count == 0) {
360 return RETURN_NOT_FOUND;
361 }
362 *ActiveOption = AllocatePool (*Count * sizeof **ActiveOption);
363 if (*ActiveOption == NULL) {
364 return RETURN_OUT_OF_RESOURCES;
365 }
366 }
367 }
368 return RETURN_SUCCESS;
369 }
370
371
372 /**
373 OpenFirmware device path node
374 **/
375 typedef struct {
376 SUBSTRING DriverName;
377 SUBSTRING UnitAddress;
378 SUBSTRING DeviceArguments;
379 } OFW_NODE;
380
381
382 /**
383
384 Parse an OpenFirmware device path node into the caller-allocated OFW_NODE
385 structure, and advance in the input string.
386
387 The node format is mostly parsed after IEEE 1275-1994, 3.2.1.1 "Node names"
388 (a leading slash is expected and not returned):
389
390 /driver-name@unit-address[:device-arguments][<LF>]
391
392 A single trailing <LF> character is consumed but not returned. A trailing
393 <LF> or NUL character terminates the device path.
394
395 The function relies on ASCII encoding.
396
397 @param[in out] Ptr Address of the pointer pointing to the start of the
398 node string. After successful parsing *Ptr is set to
399 the byte immediately following the consumed
400 characters. On error it points to the byte that
401 caused the error. The input string is never modified.
402
403 @param[out] OfwNode The members of this structure point into the input
404 string, designating components of the node.
405 Separators are never included. If "device-arguments"
406 is missing, then DeviceArguments.Ptr is set to NULL.
407 All components that are present have nonzero length.
408
409 If the call doesn't succeed, the contents of this
410 structure is indeterminate.
411
412 @param[out] IsFinal In case of successul parsing, this parameter signals
413 whether the node just parsed is the final node in the
414 device path. The call after a final node will attempt
415 to start parsing the next path. If the call doesn't
416 succeed, then this parameter is not changed.
417
418
419 @retval RETURN_SUCCESS Parsing successful.
420
421 @retval RETURN_NOT_FOUND Parsing terminated. *Ptr was (and is)
422 pointing to an empty string.
423
424 @retval RETURN_INVALID_PARAMETER Parse error.
425
426 **/
427 STATIC
428 RETURN_STATUS
429 ParseOfwNode (
430 IN OUT CONST CHAR8 **Ptr,
431 OUT OFW_NODE *OfwNode,
432 OUT BOOLEAN *IsFinal
433 )
434 {
435 //
436 // A leading slash is expected. End of string is tolerated.
437 //
438 switch (**Ptr) {
439 case '\0':
440 return RETURN_NOT_FOUND;
441
442 case '/':
443 ++*Ptr;
444 break;
445
446 default:
447 return RETURN_INVALID_PARAMETER;
448 }
449
450 //
451 // driver-name
452 //
453 OfwNode->DriverName.Ptr = *Ptr;
454 OfwNode->DriverName.Len = 0;
455 while (OfwNode->DriverName.Len < 32 &&
456 (IsAlnum (**Ptr) || IsDriverNamePunct (**Ptr))
457 ) {
458 ++*Ptr;
459 ++OfwNode->DriverName.Len;
460 }
461
462 if (OfwNode->DriverName.Len == 0 || OfwNode->DriverName.Len == 32) {
463 return RETURN_INVALID_PARAMETER;
464 }
465
466
467 //
468 // unit-address
469 //
470 if (**Ptr != '@') {
471 return RETURN_INVALID_PARAMETER;
472 }
473 ++*Ptr;
474
475 OfwNode->UnitAddress.Ptr = *Ptr;
476 OfwNode->UnitAddress.Len = 0;
477 while (IsPrintNotDelim (**Ptr)) {
478 ++*Ptr;
479 ++OfwNode->UnitAddress.Len;
480 }
481
482 if (OfwNode->UnitAddress.Len == 0) {
483 return RETURN_INVALID_PARAMETER;
484 }
485
486
487 //
488 // device-arguments, may be omitted
489 //
490 OfwNode->DeviceArguments.Len = 0;
491 if (**Ptr == ':') {
492 ++*Ptr;
493 OfwNode->DeviceArguments.Ptr = *Ptr;
494
495 while (IsPrintNotDelim (**Ptr)) {
496 ++*Ptr;
497 ++OfwNode->DeviceArguments.Len;
498 }
499
500 if (OfwNode->DeviceArguments.Len == 0) {
501 return RETURN_INVALID_PARAMETER;
502 }
503 }
504 else {
505 OfwNode->DeviceArguments.Ptr = NULL;
506 }
507
508 switch (**Ptr) {
509 case '\n':
510 ++*Ptr;
511 //
512 // fall through
513 //
514
515 case '\0':
516 *IsFinal = TRUE;
517 break;
518
519 case '/':
520 *IsFinal = FALSE;
521 break;
522
523 default:
524 return RETURN_INVALID_PARAMETER;
525 }
526
527 DEBUG ((
528 DEBUG_VERBOSE,
529 "%a: DriverName=\"%.*a\" UnitAddress=\"%.*a\" DeviceArguments=\"%.*a\"\n",
530 __FUNCTION__,
531 OfwNode->DriverName.Len, OfwNode->DriverName.Ptr,
532 OfwNode->UnitAddress.Len, OfwNode->UnitAddress.Ptr,
533 OfwNode->DeviceArguments.Len,
534 OfwNode->DeviceArguments.Ptr == NULL ? "" : OfwNode->DeviceArguments.Ptr
535 ));
536 return RETURN_SUCCESS;
537 }
538
539
540 /**
541
542 Translate a PCI-like array of OpenFirmware device nodes to a UEFI device path
543 fragment.
544
545 @param[in] OfwNode Array of OpenFirmware device nodes to
546 translate, constituting the beginning of an
547 OpenFirmware device path.
548
549 @param[in] NumNodes Number of elements in OfwNode.
550
551 @param[out] Translated Destination array receiving the UEFI path
552 fragment, allocated by the caller. If the
553 return value differs from RETURN_SUCCESS, its
554 contents is indeterminate.
555
556 @param[in out] TranslatedSize On input, the number of CHAR16's in
557 Translated. On RETURN_SUCCESS this parameter
558 is assigned the number of non-NUL CHAR16's
559 written to Translated. In case of other return
560 values, TranslatedSize is indeterminate.
561
562
563 @retval RETURN_SUCCESS Translation successful.
564
565 @retval RETURN_BUFFER_TOO_SMALL The translation does not fit into the number
566 of bytes provided.
567
568 @retval RETURN_UNSUPPORTED The array of OpenFirmware device nodes can't
569 be translated in the current implementation.
570
571 **/
572 STATIC
573 RETURN_STATUS
574 TranslatePciOfwNodes (
575 IN CONST OFW_NODE *OfwNode,
576 IN UINTN NumNodes,
577 OUT CHAR16 *Translated,
578 IN OUT UINTN *TranslatedSize
579 )
580 {
581 UINT64 PciDevFun[2];
582 UINTN NumEntries;
583 UINTN Written;
584
585 //
586 // Get PCI device and optional PCI function. Assume a single PCI root.
587 //
588 if (NumNodes < REQUIRED_PCI_OFW_NODES ||
589 !SubstringEq (OfwNode[0].DriverName, "pci")
590 ) {
591 return RETURN_UNSUPPORTED;
592 }
593 PciDevFun[1] = 0;
594 NumEntries = sizeof (PciDevFun) / sizeof (PciDevFun[0]);
595 if (ParseUnitAddressHexList (
596 OfwNode[1].UnitAddress,
597 PciDevFun,
598 &NumEntries
599 ) != RETURN_SUCCESS
600 ) {
601 return RETURN_UNSUPPORTED;
602 }
603
604 if (NumNodes >= 4 &&
605 SubstringEq (OfwNode[1].DriverName, "ide") &&
606 SubstringEq (OfwNode[2].DriverName, "drive") &&
607 SubstringEq (OfwNode[3].DriverName, "disk")
608 ) {
609 //
610 // OpenFirmware device path (IDE disk, IDE CD-ROM):
611 //
612 // /pci@i0cf8/ide@1,1/drive@0/disk@0
613 // ^ ^ ^ ^ ^
614 // | | | | master or slave
615 // | | | primary or secondary
616 // | PCI slot & function holding IDE controller
617 // PCI root at system bus port, PIO
618 //
619 // UEFI device path:
620 //
621 // PciRoot(0x0)/Pci(0x1,0x1)/Ata(Primary,Master,0x0)
622 // ^
623 // fixed LUN
624 //
625 UINT64 Secondary;
626 UINT64 Slave;
627
628 NumEntries = 1;
629 if (ParseUnitAddressHexList (
630 OfwNode[2].UnitAddress,
631 &Secondary,
632 &NumEntries
633 ) != RETURN_SUCCESS ||
634 Secondary > 1 ||
635 ParseUnitAddressHexList (
636 OfwNode[3].UnitAddress,
637 &Slave,
638 &NumEntries // reuse after previous single-element call
639 ) != RETURN_SUCCESS ||
640 Slave > 1
641 ) {
642 return RETURN_UNSUPPORTED;
643 }
644
645 Written = UnicodeSPrintAsciiFormat (
646 Translated,
647 *TranslatedSize * sizeof (*Translated), // BufferSize in bytes
648 "PciRoot(0x0)/Pci(0x%Lx,0x%Lx)/Ata(%a,%a,0x0)",
649 PciDevFun[0],
650 PciDevFun[1],
651 Secondary ? "Secondary" : "Primary",
652 Slave ? "Slave" : "Master"
653 );
654 } else if (NumNodes >= 4 &&
655 SubstringEq (OfwNode[1].DriverName, "isa") &&
656 SubstringEq (OfwNode[2].DriverName, "fdc") &&
657 SubstringEq (OfwNode[3].DriverName, "floppy")
658 ) {
659 //
660 // OpenFirmware device path (floppy disk):
661 //
662 // /pci@i0cf8/isa@1/fdc@03f0/floppy@0
663 // ^ ^ ^ ^
664 // | | | A: or B:
665 // | | ISA controller io-port (hex)
666 // | PCI slot holding ISA controller
667 // PCI root at system bus port, PIO
668 //
669 // UEFI device path:
670 //
671 // PciRoot(0x0)/Pci(0x1,0x0)/Floppy(0x0)
672 // ^
673 // ACPI UID
674 //
675 UINT64 AcpiUid;
676
677 NumEntries = 1;
678 if (ParseUnitAddressHexList (
679 OfwNode[3].UnitAddress,
680 &AcpiUid,
681 &NumEntries
682 ) != RETURN_SUCCESS ||
683 AcpiUid > 1
684 ) {
685 return RETURN_UNSUPPORTED;
686 }
687
688 Written = UnicodeSPrintAsciiFormat (
689 Translated,
690 *TranslatedSize * sizeof (*Translated), // BufferSize in bytes
691 "PciRoot(0x0)/Pci(0x%Lx,0x%Lx)/Floppy(0x%Lx)",
692 PciDevFun[0],
693 PciDevFun[1],
694 AcpiUid
695 );
696 } else if (NumNodes >= 3 &&
697 SubstringEq (OfwNode[1].DriverName, "scsi") &&
698 SubstringEq (OfwNode[2].DriverName, "disk")
699 ) {
700 //
701 // OpenFirmware device path (virtio-blk disk):
702 //
703 // /pci@i0cf8/scsi@6[,3]/disk@0,0
704 // ^ ^ ^ ^ ^
705 // | | | fixed
706 // | | PCI function corresponding to disk (optional)
707 // | PCI slot holding disk
708 // PCI root at system bus port, PIO
709 //
710 // UEFI device path prefix:
711 //
712 // PciRoot(0x0)/Pci(0x6,0x0)/HD( -- if PCI function is 0 or absent
713 // PciRoot(0x0)/Pci(0x6,0x3)/HD( -- if PCI function is present and nonzero
714 //
715 Written = UnicodeSPrintAsciiFormat (
716 Translated,
717 *TranslatedSize * sizeof (*Translated), // BufferSize in bytes
718 "PciRoot(0x0)/Pci(0x%Lx,0x%Lx)/HD(",
719 PciDevFun[0],
720 PciDevFun[1]
721 );
722 } else if (NumNodes >= 4 &&
723 SubstringEq (OfwNode[1].DriverName, "scsi") &&
724 SubstringEq (OfwNode[2].DriverName, "channel") &&
725 SubstringEq (OfwNode[3].DriverName, "disk")
726 ) {
727 //
728 // OpenFirmware device path (virtio-scsi disk):
729 //
730 // /pci@i0cf8/scsi@7[,3]/channel@0/disk@2,3
731 // ^ ^ ^ ^ ^
732 // | | | | LUN
733 // | | | target
734 // | | channel (unused, fixed 0)
735 // | PCI slot[, function] holding SCSI controller
736 // PCI root at system bus port, PIO
737 //
738 // UEFI device path prefix:
739 //
740 // PciRoot(0x0)/Pci(0x7,0x0)/Scsi(0x2,0x3)
741 // -- if PCI function is 0 or absent
742 // PciRoot(0x0)/Pci(0x7,0x3)/Scsi(0x2,0x3)
743 // -- if PCI function is present and nonzero
744 //
745 UINT64 TargetLun[2];
746
747 TargetLun[1] = 0;
748 NumEntries = sizeof (TargetLun) / sizeof (TargetLun[0]);
749 if (ParseUnitAddressHexList (
750 OfwNode[3].UnitAddress,
751 TargetLun,
752 &NumEntries
753 ) != RETURN_SUCCESS
754 ) {
755 return RETURN_UNSUPPORTED;
756 }
757
758 Written = UnicodeSPrintAsciiFormat (
759 Translated,
760 *TranslatedSize * sizeof (*Translated), // BufferSize in bytes
761 "PciRoot(0x0)/Pci(0x%Lx,0x%Lx)/Scsi(0x%Lx,0x%Lx)",
762 PciDevFun[0],
763 PciDevFun[1],
764 TargetLun[0],
765 TargetLun[1]
766 );
767 } else {
768 //
769 // Generic OpenFirmware device path for PCI devices:
770 //
771 // /pci@i0cf8/ethernet@3[,2]
772 // ^ ^
773 // | PCI slot[, function] holding Ethernet card
774 // PCI root at system bus port, PIO
775 //
776 // UEFI device path prefix (dependent on presence of nonzero PCI function):
777 //
778 // PciRoot(0x0)/Pci(0x3,0x0)
779 // PciRoot(0x0)/Pci(0x3,0x2)
780 //
781 Written = UnicodeSPrintAsciiFormat (
782 Translated,
783 *TranslatedSize * sizeof (*Translated), // BufferSize in bytes
784 "PciRoot(0x0)/Pci(0x%Lx,0x%Lx)",
785 PciDevFun[0],
786 PciDevFun[1]
787 );
788 }
789
790 //
791 // There's no way to differentiate between "completely used up without
792 // truncation" and "truncated", so treat the former as the latter, and return
793 // success only for "some room left unused".
794 //
795 if (Written + 1 < *TranslatedSize) {
796 *TranslatedSize = Written;
797 return RETURN_SUCCESS;
798 }
799
800 return RETURN_BUFFER_TOO_SMALL;
801 }
802
803
804 /**
805
806 Translate an array of OpenFirmware device nodes to a UEFI device path
807 fragment.
808
809 @param[in] OfwNode Array of OpenFirmware device nodes to
810 translate, constituting the beginning of an
811 OpenFirmware device path.
812
813 @param[in] NumNodes Number of elements in OfwNode.
814
815 @param[out] Translated Destination array receiving the UEFI path
816 fragment, allocated by the caller. If the
817 return value differs from RETURN_SUCCESS, its
818 contents is indeterminate.
819
820 @param[in out] TranslatedSize On input, the number of CHAR16's in
821 Translated. On RETURN_SUCCESS this parameter
822 is assigned the number of non-NUL CHAR16's
823 written to Translated. In case of other return
824 values, TranslatedSize is indeterminate.
825
826
827 @retval RETURN_SUCCESS Translation successful.
828
829 @retval RETURN_BUFFER_TOO_SMALL The translation does not fit into the number
830 of bytes provided.
831
832 @retval RETURN_UNSUPPORTED The array of OpenFirmware device nodes can't
833 be translated in the current implementation.
834
835 **/
836 STATIC
837 RETURN_STATUS
838 TranslateOfwNodes (
839 IN CONST OFW_NODE *OfwNode,
840 IN UINTN NumNodes,
841 OUT CHAR16 *Translated,
842 IN OUT UINTN *TranslatedSize
843 )
844 {
845 RETURN_STATUS Status;
846
847 Status = RETURN_UNSUPPORTED;
848
849 if (FeaturePcdGet (PcdQemuBootOrderPciTranslation)) {
850 Status = TranslatePciOfwNodes (OfwNode, NumNodes, Translated,
851 TranslatedSize);
852 }
853 return Status;
854 }
855
856 /**
857
858 Translate an OpenFirmware device path fragment to a UEFI device path
859 fragment, and advance in the input string.
860
861 @param[in out] Ptr Address of the pointer pointing to the start
862 of the path string. After successful
863 translation (RETURN_SUCCESS) or at least
864 successful parsing (RETURN_UNSUPPORTED,
865 RETURN_BUFFER_TOO_SMALL), *Ptr is set to the
866 byte immediately following the consumed
867 characters. In other error cases, it points to
868 the byte that caused the error.
869
870 @param[out] Translated Destination array receiving the UEFI path
871 fragment, allocated by the caller. If the
872 return value differs from RETURN_SUCCESS, its
873 contents is indeterminate.
874
875 @param[in out] TranslatedSize On input, the number of CHAR16's in
876 Translated. On RETURN_SUCCESS this parameter
877 is assigned the number of non-NUL CHAR16's
878 written to Translated. In case of other return
879 values, TranslatedSize is indeterminate.
880
881
882 @retval RETURN_SUCCESS Translation successful.
883
884 @retval RETURN_BUFFER_TOO_SMALL The OpenFirmware device path was parsed
885 successfully, but its translation did not
886 fit into the number of bytes provided.
887 Further calls to this function are
888 possible.
889
890 @retval RETURN_UNSUPPORTED The OpenFirmware device path was parsed
891 successfully, but it can't be translated in
892 the current implementation. Further calls
893 to this function are possible.
894
895 @retval RETURN_NOT_FOUND Translation terminated. On input, *Ptr was
896 pointing to the empty string or "HALT". On
897 output, *Ptr points to the empty string
898 (ie. "HALT" is consumed transparently when
899 present).
900
901 @retval RETURN_INVALID_PARAMETER Parse error. This is a permanent error.
902
903 **/
904 STATIC
905 RETURN_STATUS
906 TranslateOfwPath (
907 IN OUT CONST CHAR8 **Ptr,
908 OUT CHAR16 *Translated,
909 IN OUT UINTN *TranslatedSize
910 )
911 {
912 UINTN NumNodes;
913 RETURN_STATUS Status;
914 OFW_NODE Node[EXAMINED_OFW_NODES];
915 BOOLEAN IsFinal;
916 OFW_NODE Skip;
917
918 IsFinal = FALSE;
919 NumNodes = 0;
920 if (AsciiStrCmp (*Ptr, "HALT") == 0) {
921 *Ptr += 4;
922 Status = RETURN_NOT_FOUND;
923 } else {
924 Status = ParseOfwNode (Ptr, &Node[NumNodes], &IsFinal);
925 }
926
927 if (Status == RETURN_NOT_FOUND) {
928 DEBUG ((DEBUG_VERBOSE, "%a: no more nodes\n", __FUNCTION__));
929 return RETURN_NOT_FOUND;
930 }
931
932 while (Status == RETURN_SUCCESS && !IsFinal) {
933 ++NumNodes;
934 Status = ParseOfwNode (
935 Ptr,
936 (NumNodes < EXAMINED_OFW_NODES) ? &Node[NumNodes] : &Skip,
937 &IsFinal
938 );
939 }
940
941 switch (Status) {
942 case RETURN_SUCCESS:
943 ++NumNodes;
944 break;
945
946 case RETURN_INVALID_PARAMETER:
947 DEBUG ((DEBUG_VERBOSE, "%a: parse error\n", __FUNCTION__));
948 return RETURN_INVALID_PARAMETER;
949
950 default:
951 ASSERT (0);
952 }
953
954 Status = TranslateOfwNodes (
955 Node,
956 NumNodes < EXAMINED_OFW_NODES ? NumNodes : EXAMINED_OFW_NODES,
957 Translated,
958 TranslatedSize);
959 switch (Status) {
960 case RETURN_SUCCESS:
961 DEBUG ((DEBUG_VERBOSE, "%a: success: \"%s\"\n", __FUNCTION__, Translated));
962 break;
963
964 case RETURN_BUFFER_TOO_SMALL:
965 DEBUG ((DEBUG_VERBOSE, "%a: buffer too small\n", __FUNCTION__));
966 break;
967
968 case RETURN_UNSUPPORTED:
969 DEBUG ((DEBUG_VERBOSE, "%a: unsupported\n", __FUNCTION__));
970 break;
971
972 default:
973 ASSERT (0);
974 }
975 return Status;
976 }
977
978
979 /**
980
981 Convert the UEFI DevicePath to full text representation with DevPathToText,
982 then match the UEFI device path fragment in Translated against it.
983
984 @param[in] Translated UEFI device path fragment, translated from
985 OpenFirmware format, to search for.
986
987 @param[in] TranslatedLength The length of Translated in CHAR16's.
988
989 @param[in] DevicePath Boot option device path whose textual rendering
990 to search in.
991
992 @param[in] DevPathToText Binary-to-text conversion protocol for DevicePath.
993
994
995 @retval TRUE If Translated was found at the beginning of DevicePath after
996 converting the latter to text.
997
998 @retval FALSE If DevicePath was NULL, or it could not be converted, or there
999 was no match.
1000
1001 **/
1002 STATIC
1003 BOOLEAN
1004 Match (
1005 IN CONST CHAR16 *Translated,
1006 IN UINTN TranslatedLength,
1007 IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePath
1008 )
1009 {
1010 CHAR16 *Converted;
1011 BOOLEAN Result;
1012
1013 Converted = ConvertDevicePathToText (
1014 DevicePath,
1015 FALSE, // DisplayOnly
1016 FALSE // AllowShortcuts
1017 );
1018 if (Converted == NULL) {
1019 return FALSE;
1020 }
1021
1022 //
1023 // Attempt to expand any relative UEFI device path starting with HD() to an
1024 // absolute device path first. The logic imitates BdsLibBootViaBootOption().
1025 // We don't have to free the absolute device path,
1026 // BdsExpandPartitionPartialDevicePathToFull() has internal caching.
1027 //
1028 Result = FALSE;
1029 if (DevicePathType (DevicePath) == MEDIA_DEVICE_PATH &&
1030 DevicePathSubType (DevicePath) == MEDIA_HARDDRIVE_DP) {
1031 EFI_DEVICE_PATH_PROTOCOL *AbsDevicePath;
1032 CHAR16 *AbsConverted;
1033
1034 AbsDevicePath = BdsExpandPartitionPartialDevicePathToFull (
1035 (HARDDRIVE_DEVICE_PATH *) DevicePath);
1036 if (AbsDevicePath == NULL) {
1037 goto Exit;
1038 }
1039 AbsConverted = ConvertDevicePathToText (AbsDevicePath, FALSE, FALSE);
1040 if (AbsConverted == NULL) {
1041 goto Exit;
1042 }
1043 DEBUG ((DEBUG_VERBOSE,
1044 "%a: expanded relative device path \"%s\" for prefix matching\n",
1045 __FUNCTION__, Converted));
1046 FreePool (Converted);
1047 Converted = AbsConverted;
1048 }
1049
1050 //
1051 // Is Translated a prefix of Converted?
1052 //
1053 Result = (BOOLEAN)(StrnCmp (Converted, Translated, TranslatedLength) == 0);
1054 DEBUG ((
1055 DEBUG_VERBOSE,
1056 "%a: against \"%s\": %a\n",
1057 __FUNCTION__,
1058 Converted,
1059 Result ? "match" : "no match"
1060 ));
1061 Exit:
1062 FreePool (Converted);
1063 return Result;
1064 }
1065
1066
1067 /**
1068 Append some of the unselected active boot options to the boot order.
1069
1070 This function should accommodate any further policy changes in "boot option
1071 survival". Currently we're adding back everything that starts with neither
1072 PciRoot() nor HD().
1073
1074 @param[in,out] BootOrder The structure holding the boot order to
1075 complete. The caller is responsible for
1076 initializing (and potentially populating) it
1077 before calling this function.
1078
1079 @param[in,out] ActiveOption The array of active boot options to scan.
1080 Entries marked as Appended will be skipped.
1081 Those of the rest that satisfy the survival
1082 policy will be added to BootOrder with
1083 BootOrderAppend().
1084
1085 @param[in] ActiveCount Number of elements in ActiveOption.
1086
1087
1088 @retval RETURN_SUCCESS BootOrder has been extended with any eligible boot
1089 options.
1090
1091 @return Error codes returned by BootOrderAppend().
1092 **/
1093 STATIC
1094 RETURN_STATUS
1095 BootOrderComplete (
1096 IN OUT BOOT_ORDER *BootOrder,
1097 IN OUT ACTIVE_OPTION *ActiveOption,
1098 IN UINTN ActiveCount
1099 )
1100 {
1101 RETURN_STATUS Status;
1102 UINTN Idx;
1103
1104 Status = RETURN_SUCCESS;
1105 Idx = 0;
1106 while (!RETURN_ERROR (Status) && Idx < ActiveCount) {
1107 if (!ActiveOption[Idx].Appended) {
1108 CONST BDS_COMMON_OPTION *Current;
1109 CONST EFI_DEVICE_PATH_PROTOCOL *FirstNode;
1110
1111 Current = ActiveOption[Idx].BootOption;
1112 FirstNode = Current->DevicePath;
1113 if (FirstNode != NULL) {
1114 CHAR16 *Converted;
1115 STATIC CHAR16 ConvFallBack[] = L"<unable to convert>";
1116 BOOLEAN Keep;
1117
1118 Converted = ConvertDevicePathToText (FirstNode, FALSE, FALSE);
1119 if (Converted == NULL) {
1120 Converted = ConvFallBack;
1121 }
1122
1123 Keep = TRUE;
1124 if (DevicePathType(FirstNode) == MEDIA_DEVICE_PATH &&
1125 DevicePathSubType(FirstNode) == MEDIA_HARDDRIVE_DP) {
1126 //
1127 // drop HD()
1128 //
1129 Keep = FALSE;
1130 } else if (DevicePathType(FirstNode) == ACPI_DEVICE_PATH &&
1131 DevicePathSubType(FirstNode) == ACPI_DP) {
1132 ACPI_HID_DEVICE_PATH *Acpi;
1133
1134 Acpi = (ACPI_HID_DEVICE_PATH *) FirstNode;
1135 if ((Acpi->HID & PNP_EISA_ID_MASK) == PNP_EISA_ID_CONST &&
1136 EISA_ID_TO_NUM (Acpi->HID) == 0x0a03) {
1137 //
1138 // drop PciRoot() if we enabled the user to select PCI-like boot
1139 // options, by providing translation for such OFW device path
1140 // fragments
1141 //
1142 Keep = !FeaturePcdGet (PcdQemuBootOrderPciTranslation);
1143 }
1144 }
1145
1146 if (Keep) {
1147 Status = BootOrderAppend (BootOrder, &ActiveOption[Idx]);
1148 if (!RETURN_ERROR (Status)) {
1149 DEBUG ((DEBUG_VERBOSE, "%a: keeping \"%s\"\n", __FUNCTION__,
1150 Converted));
1151 }
1152 } else {
1153 DEBUG ((DEBUG_VERBOSE, "%a: dropping \"%s\"\n", __FUNCTION__,
1154 Converted));
1155 }
1156
1157 if (Converted != ConvFallBack) {
1158 FreePool (Converted);
1159 }
1160 }
1161 }
1162 ++Idx;
1163 }
1164 return Status;
1165 }
1166
1167
1168 /**
1169 Delete Boot#### variables that stand for such active boot options that have
1170 been dropped (ie. have not been selected by either matching or "survival
1171 policy").
1172
1173 @param[in] ActiveOption The array of active boot options to scan. Each
1174 entry not marked as appended will trigger the
1175 deletion of the matching Boot#### variable.
1176
1177 @param[in] ActiveCount Number of elements in ActiveOption.
1178 **/
1179 STATIC
1180 VOID
1181 PruneBootVariables (
1182 IN CONST ACTIVE_OPTION *ActiveOption,
1183 IN UINTN ActiveCount
1184 )
1185 {
1186 UINTN Idx;
1187
1188 for (Idx = 0; Idx < ActiveCount; ++Idx) {
1189 if (!ActiveOption[Idx].Appended) {
1190 CHAR16 VariableName[9];
1191
1192 UnicodeSPrintAsciiFormat (VariableName, sizeof VariableName, "Boot%04x",
1193 ActiveOption[Idx].BootOption->BootCurrent);
1194
1195 //
1196 // "The space consumed by the deleted variable may not be available until
1197 // the next power cycle", but that's good enough.
1198 //
1199 gRT->SetVariable (VariableName, &gEfiGlobalVariableGuid,
1200 0, // Attributes, 0 means deletion
1201 0, // DataSize, 0 means deletion
1202 NULL // Data
1203 );
1204 }
1205 }
1206 }
1207
1208
1209 /**
1210
1211 Set the boot order based on configuration retrieved from QEMU.
1212
1213 Attempt to retrieve the "bootorder" fw_cfg file from QEMU. Translate the
1214 OpenFirmware device paths therein to UEFI device path fragments. Match the
1215 translated fragments against BootOptionList, and rewrite the BootOrder NvVar
1216 so that it corresponds to the order described in fw_cfg.
1217
1218 @param[in] BootOptionList A boot option list, created with
1219 BdsLibEnumerateAllBootOption ().
1220
1221
1222 @retval RETURN_SUCCESS BootOrder NvVar rewritten.
1223
1224 @retval RETURN_UNSUPPORTED QEMU's fw_cfg is not supported.
1225
1226 @retval RETURN_NOT_FOUND Empty or nonexistent "bootorder" fw_cfg
1227 file, or no match found between the
1228 "bootorder" fw_cfg file and BootOptionList.
1229
1230 @retval RETURN_INVALID_PARAMETER Parse error in the "bootorder" fw_cfg file.
1231
1232 @retval RETURN_OUT_OF_RESOURCES Memory allocation failed.
1233
1234 @return Values returned by gBS->LocateProtocol ()
1235 or gRT->SetVariable ().
1236
1237 **/
1238 RETURN_STATUS
1239 SetBootOrderFromQemu (
1240 IN CONST LIST_ENTRY *BootOptionList
1241 )
1242 {
1243 RETURN_STATUS Status;
1244 FIRMWARE_CONFIG_ITEM FwCfgItem;
1245 UINTN FwCfgSize;
1246 CHAR8 *FwCfg;
1247 CONST CHAR8 *FwCfgPtr;
1248
1249 BOOT_ORDER BootOrder;
1250 ACTIVE_OPTION *ActiveOption;
1251 UINTN ActiveCount;
1252
1253 UINTN TranslatedSize;
1254 CHAR16 Translated[TRANSLATION_OUTPUT_SIZE];
1255
1256 Status = QemuFwCfgFindFile ("bootorder", &FwCfgItem, &FwCfgSize);
1257 if (Status != RETURN_SUCCESS) {
1258 return Status;
1259 }
1260
1261 if (FwCfgSize == 0) {
1262 return RETURN_NOT_FOUND;
1263 }
1264
1265 FwCfg = AllocatePool (FwCfgSize);
1266 if (FwCfg == NULL) {
1267 return RETURN_OUT_OF_RESOURCES;
1268 }
1269
1270 QemuFwCfgSelectItem (FwCfgItem);
1271 QemuFwCfgReadBytes (FwCfgSize, FwCfg);
1272 if (FwCfg[FwCfgSize - 1] != '\0') {
1273 Status = RETURN_INVALID_PARAMETER;
1274 goto ErrorFreeFwCfg;
1275 }
1276
1277 DEBUG ((DEBUG_VERBOSE, "%a: FwCfg:\n", __FUNCTION__));
1278 DEBUG ((DEBUG_VERBOSE, "%a\n", FwCfg));
1279 DEBUG ((DEBUG_VERBOSE, "%a: FwCfg: <end>\n", __FUNCTION__));
1280 FwCfgPtr = FwCfg;
1281
1282 BootOrder.Produced = 0;
1283 BootOrder.Allocated = 1;
1284 BootOrder.Data = AllocatePool (
1285 BootOrder.Allocated * sizeof (*BootOrder.Data)
1286 );
1287 if (BootOrder.Data == NULL) {
1288 Status = RETURN_OUT_OF_RESOURCES;
1289 goto ErrorFreeFwCfg;
1290 }
1291
1292 Status = CollectActiveOptions (BootOptionList, &ActiveOption, &ActiveCount);
1293 if (RETURN_ERROR (Status)) {
1294 goto ErrorFreeBootOrder;
1295 }
1296
1297 //
1298 // translate each OpenFirmware path
1299 //
1300 TranslatedSize = sizeof (Translated) / sizeof (Translated[0]);
1301 Status = TranslateOfwPath (&FwCfgPtr, Translated, &TranslatedSize);
1302 while (Status == RETURN_SUCCESS ||
1303 Status == RETURN_UNSUPPORTED ||
1304 Status == RETURN_BUFFER_TOO_SMALL) {
1305 if (Status == RETURN_SUCCESS) {
1306 UINTN Idx;
1307
1308 //
1309 // match translated OpenFirmware path against all active boot options
1310 //
1311 for (Idx = 0; Idx < ActiveCount; ++Idx) {
1312 if (Match (
1313 Translated,
1314 TranslatedSize, // contains length, not size, in CHAR16's here
1315 ActiveOption[Idx].BootOption->DevicePath
1316 )
1317 ) {
1318 //
1319 // match found, store ID and continue with next OpenFirmware path
1320 //
1321 Status = BootOrderAppend (&BootOrder, &ActiveOption[Idx]);
1322 if (Status != RETURN_SUCCESS) {
1323 goto ErrorFreeActiveOption;
1324 }
1325 break;
1326 }
1327 } // scanned all active boot options
1328 } // translation successful
1329
1330 TranslatedSize = sizeof (Translated) / sizeof (Translated[0]);
1331 Status = TranslateOfwPath (&FwCfgPtr, Translated, &TranslatedSize);
1332 } // scanning of OpenFirmware paths done
1333
1334 if (Status == RETURN_NOT_FOUND && BootOrder.Produced > 0) {
1335 //
1336 // No more OpenFirmware paths, some matches found: rewrite BootOrder NvVar.
1337 // Some of the active boot options that have not been selected over fw_cfg
1338 // should be preserved at the end of the boot order.
1339 //
1340 Status = BootOrderComplete (&BootOrder, ActiveOption, ActiveCount);
1341 if (RETURN_ERROR (Status)) {
1342 goto ErrorFreeActiveOption;
1343 }
1344
1345 //
1346 // See Table 10 in the UEFI Spec 2.3.1 with Errata C for the required
1347 // attributes.
1348 //
1349 Status = gRT->SetVariable (
1350 L"BootOrder",
1351 &gEfiGlobalVariableGuid,
1352 EFI_VARIABLE_NON_VOLATILE |
1353 EFI_VARIABLE_BOOTSERVICE_ACCESS |
1354 EFI_VARIABLE_RUNTIME_ACCESS,
1355 BootOrder.Produced * sizeof (*BootOrder.Data),
1356 BootOrder.Data
1357 );
1358 if (EFI_ERROR (Status)) {
1359 DEBUG ((DEBUG_ERROR, "%a: setting BootOrder: %r\n", __FUNCTION__, Status));
1360 goto ErrorFreeActiveOption;
1361 }
1362
1363 DEBUG ((DEBUG_INFO, "%a: setting BootOrder: success\n", __FUNCTION__));
1364 PruneBootVariables (ActiveOption, ActiveCount);
1365 }
1366
1367 ErrorFreeActiveOption:
1368 FreePool (ActiveOption);
1369
1370 ErrorFreeBootOrder:
1371 FreePool (BootOrder.Data);
1372
1373 ErrorFreeFwCfg:
1374 FreePool (FwCfg);
1375
1376 return Status;
1377 }