]> git.proxmox.com Git - mirror_edk2.git/blob - OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.c
OvmfPkg: extract QemuBootOrderLib
[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_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 UINT32 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 UINT32 *Result,
172 IN OUT UINTN *NumResults
173 )
174 {
175 UINTN Entry; // number of entry currently being parsed
176 UINT32 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 > 0xFFFFFFF) {
197 return RETURN_INVALID_PARAMETER;
198 }
199 EntryVal = (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 an 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 TranslateOfwNodes (
575 IN CONST OFW_NODE *OfwNode,
576 IN UINTN NumNodes,
577 OUT CHAR16 *Translated,
578 IN OUT UINTN *TranslatedSize
579 )
580 {
581 UINT32 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_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 UINT32 Secondary;
626 UINT32 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%x,0x%x)/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 UINT32 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%x,0x%x)/Floppy(0x%x)",
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%x,0x%x)/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 UINT32 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%x,0x%x)/Scsi(0x%x,0x%x)",
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%x,0x%x)",
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 OpenFirmware device path fragment to a UEFI device path
807 fragment, and advance in the input string.
808
809 @param[in out] Ptr Address of the pointer pointing to the start
810 of the path string. After successful
811 translation (RETURN_SUCCESS) or at least
812 successful parsing (RETURN_UNSUPPORTED,
813 RETURN_BUFFER_TOO_SMALL), *Ptr is set to the
814 byte immediately following the consumed
815 characters. In other error cases, it points to
816 the byte that caused the error.
817
818 @param[out] Translated Destination array receiving the UEFI path
819 fragment, allocated by the caller. If the
820 return value differs from RETURN_SUCCESS, its
821 contents is indeterminate.
822
823 @param[in out] TranslatedSize On input, the number of CHAR16's in
824 Translated. On RETURN_SUCCESS this parameter
825 is assigned the number of non-NUL CHAR16's
826 written to Translated. In case of other return
827 values, TranslatedSize is indeterminate.
828
829
830 @retval RETURN_SUCCESS Translation successful.
831
832 @retval RETURN_BUFFER_TOO_SMALL The OpenFirmware device path was parsed
833 successfully, but its translation did not
834 fit into the number of bytes provided.
835 Further calls to this function are
836 possible.
837
838 @retval RETURN_UNSUPPORTED The OpenFirmware device path was parsed
839 successfully, but it can't be translated in
840 the current implementation. Further calls
841 to this function are possible.
842
843 @retval RETURN_NOT_FOUND Translation terminated. On input, *Ptr was
844 pointing to the empty string or "HALT". On
845 output, *Ptr points to the empty string
846 (ie. "HALT" is consumed transparently when
847 present).
848
849 @retval RETURN_INVALID_PARAMETER Parse error. This is a permanent error.
850
851 **/
852 STATIC
853 RETURN_STATUS
854 TranslateOfwPath (
855 IN OUT CONST CHAR8 **Ptr,
856 OUT CHAR16 *Translated,
857 IN OUT UINTN *TranslatedSize
858 )
859 {
860 UINTN NumNodes;
861 RETURN_STATUS Status;
862 OFW_NODE Node[EXAMINED_OFW_NODES];
863 BOOLEAN IsFinal;
864 OFW_NODE Skip;
865
866 IsFinal = FALSE;
867 NumNodes = 0;
868 if (AsciiStrCmp (*Ptr, "HALT") == 0) {
869 *Ptr += 4;
870 Status = RETURN_NOT_FOUND;
871 } else {
872 Status = ParseOfwNode (Ptr, &Node[NumNodes], &IsFinal);
873 }
874
875 if (Status == RETURN_NOT_FOUND) {
876 DEBUG ((DEBUG_VERBOSE, "%a: no more nodes\n", __FUNCTION__));
877 return RETURN_NOT_FOUND;
878 }
879
880 while (Status == RETURN_SUCCESS && !IsFinal) {
881 ++NumNodes;
882 Status = ParseOfwNode (
883 Ptr,
884 (NumNodes < EXAMINED_OFW_NODES) ? &Node[NumNodes] : &Skip,
885 &IsFinal
886 );
887 }
888
889 switch (Status) {
890 case RETURN_SUCCESS:
891 ++NumNodes;
892 break;
893
894 case RETURN_INVALID_PARAMETER:
895 DEBUG ((DEBUG_VERBOSE, "%a: parse error\n", __FUNCTION__));
896 return RETURN_INVALID_PARAMETER;
897
898 default:
899 ASSERT (0);
900 }
901
902 Status = TranslateOfwNodes (
903 Node,
904 NumNodes < EXAMINED_OFW_NODES ? NumNodes : EXAMINED_OFW_NODES,
905 Translated,
906 TranslatedSize);
907 switch (Status) {
908 case RETURN_SUCCESS:
909 DEBUG ((DEBUG_VERBOSE, "%a: success: \"%s\"\n", __FUNCTION__, Translated));
910 break;
911
912 case RETURN_BUFFER_TOO_SMALL:
913 DEBUG ((DEBUG_VERBOSE, "%a: buffer too small\n", __FUNCTION__));
914 break;
915
916 case RETURN_UNSUPPORTED:
917 DEBUG ((DEBUG_VERBOSE, "%a: unsupported\n", __FUNCTION__));
918 break;
919
920 default:
921 ASSERT (0);
922 }
923 return Status;
924 }
925
926
927 /**
928
929 Convert the UEFI DevicePath to full text representation with DevPathToText,
930 then match the UEFI device path fragment in Translated against it.
931
932 @param[in] Translated UEFI device path fragment, translated from
933 OpenFirmware format, to search for.
934
935 @param[in] TranslatedLength The length of Translated in CHAR16's.
936
937 @param[in] DevicePath Boot option device path whose textual rendering
938 to search in.
939
940 @param[in] DevPathToText Binary-to-text conversion protocol for DevicePath.
941
942
943 @retval TRUE If Translated was found at the beginning of DevicePath after
944 converting the latter to text.
945
946 @retval FALSE If DevicePath was NULL, or it could not be converted, or there
947 was no match.
948
949 **/
950 STATIC
951 BOOLEAN
952 Match (
953 IN CONST CHAR16 *Translated,
954 IN UINTN TranslatedLength,
955 IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePath
956 )
957 {
958 CHAR16 *Converted;
959 BOOLEAN Result;
960
961 Converted = ConvertDevicePathToText (
962 DevicePath,
963 FALSE, // DisplayOnly
964 FALSE // AllowShortcuts
965 );
966 if (Converted == NULL) {
967 return FALSE;
968 }
969
970 //
971 // Attempt to expand any relative UEFI device path starting with HD() to an
972 // absolute device path first. The logic imitates BdsLibBootViaBootOption().
973 // We don't have to free the absolute device path,
974 // BdsExpandPartitionPartialDevicePathToFull() has internal caching.
975 //
976 Result = FALSE;
977 if (DevicePathType (DevicePath) == MEDIA_DEVICE_PATH &&
978 DevicePathSubType (DevicePath) == MEDIA_HARDDRIVE_DP) {
979 EFI_DEVICE_PATH_PROTOCOL *AbsDevicePath;
980 CHAR16 *AbsConverted;
981
982 AbsDevicePath = BdsExpandPartitionPartialDevicePathToFull (
983 (HARDDRIVE_DEVICE_PATH *) DevicePath);
984 if (AbsDevicePath == NULL) {
985 goto Exit;
986 }
987 AbsConverted = ConvertDevicePathToText (AbsDevicePath, FALSE, FALSE);
988 if (AbsConverted == NULL) {
989 goto Exit;
990 }
991 DEBUG ((DEBUG_VERBOSE,
992 "%a: expanded relative device path \"%s\" for prefix matching\n",
993 __FUNCTION__, Converted));
994 FreePool (Converted);
995 Converted = AbsConverted;
996 }
997
998 //
999 // Is Translated a prefix of Converted?
1000 //
1001 Result = (BOOLEAN)(StrnCmp (Converted, Translated, TranslatedLength) == 0);
1002 DEBUG ((
1003 DEBUG_VERBOSE,
1004 "%a: against \"%s\": %a\n",
1005 __FUNCTION__,
1006 Converted,
1007 Result ? "match" : "no match"
1008 ));
1009 Exit:
1010 FreePool (Converted);
1011 return Result;
1012 }
1013
1014
1015 /**
1016 Append some of the unselected active boot options to the boot order.
1017
1018 This function should accommodate any further policy changes in "boot option
1019 survival". Currently we're adding back everything that starts with neither
1020 PciRoot() nor HD().
1021
1022 @param[in,out] BootOrder The structure holding the boot order to
1023 complete. The caller is responsible for
1024 initializing (and potentially populating) it
1025 before calling this function.
1026
1027 @param[in,out] ActiveOption The array of active boot options to scan.
1028 Entries marked as Appended will be skipped.
1029 Those of the rest that satisfy the survival
1030 policy will be added to BootOrder with
1031 BootOrderAppend().
1032
1033 @param[in] ActiveCount Number of elements in ActiveOption.
1034
1035
1036 @retval RETURN_SUCCESS BootOrder has been extended with any eligible boot
1037 options.
1038
1039 @return Error codes returned by BootOrderAppend().
1040 **/
1041 STATIC
1042 RETURN_STATUS
1043 BootOrderComplete (
1044 IN OUT BOOT_ORDER *BootOrder,
1045 IN OUT ACTIVE_OPTION *ActiveOption,
1046 IN UINTN ActiveCount
1047 )
1048 {
1049 RETURN_STATUS Status;
1050 UINTN Idx;
1051
1052 Status = RETURN_SUCCESS;
1053 Idx = 0;
1054 while (!RETURN_ERROR (Status) && Idx < ActiveCount) {
1055 if (!ActiveOption[Idx].Appended) {
1056 CONST BDS_COMMON_OPTION *Current;
1057 CONST EFI_DEVICE_PATH_PROTOCOL *FirstNode;
1058
1059 Current = ActiveOption[Idx].BootOption;
1060 FirstNode = Current->DevicePath;
1061 if (FirstNode != NULL) {
1062 CHAR16 *Converted;
1063 STATIC CHAR16 ConvFallBack[] = L"<unable to convert>";
1064 BOOLEAN Keep;
1065
1066 Converted = ConvertDevicePathToText (FirstNode, FALSE, FALSE);
1067 if (Converted == NULL) {
1068 Converted = ConvFallBack;
1069 }
1070
1071 Keep = TRUE;
1072 if (DevicePathType(FirstNode) == MEDIA_DEVICE_PATH &&
1073 DevicePathSubType(FirstNode) == MEDIA_HARDDRIVE_DP) {
1074 //
1075 // drop HD()
1076 //
1077 Keep = FALSE;
1078 } else if (DevicePathType(FirstNode) == ACPI_DEVICE_PATH &&
1079 DevicePathSubType(FirstNode) == ACPI_DP) {
1080 ACPI_HID_DEVICE_PATH *Acpi;
1081
1082 Acpi = (ACPI_HID_DEVICE_PATH *) FirstNode;
1083 if ((Acpi->HID & PNP_EISA_ID_MASK) == PNP_EISA_ID_CONST &&
1084 EISA_ID_TO_NUM (Acpi->HID) == 0x0a03) {
1085 //
1086 // drop PciRoot()
1087 //
1088 Keep = FALSE;
1089 }
1090 }
1091
1092 if (Keep) {
1093 Status = BootOrderAppend (BootOrder, &ActiveOption[Idx]);
1094 if (!RETURN_ERROR (Status)) {
1095 DEBUG ((DEBUG_VERBOSE, "%a: keeping \"%s\"\n", __FUNCTION__,
1096 Converted));
1097 }
1098 } else {
1099 DEBUG ((DEBUG_VERBOSE, "%a: dropping \"%s\"\n", __FUNCTION__,
1100 Converted));
1101 }
1102
1103 if (Converted != ConvFallBack) {
1104 FreePool (Converted);
1105 }
1106 }
1107 }
1108 ++Idx;
1109 }
1110 return Status;
1111 }
1112
1113
1114 /**
1115 Delete Boot#### variables that stand for such active boot options that have
1116 been dropped (ie. have not been selected by either matching or "survival
1117 policy").
1118
1119 @param[in] ActiveOption The array of active boot options to scan. Each
1120 entry not marked as appended will trigger the
1121 deletion of the matching Boot#### variable.
1122
1123 @param[in] ActiveCount Number of elements in ActiveOption.
1124 **/
1125 STATIC
1126 VOID
1127 PruneBootVariables (
1128 IN CONST ACTIVE_OPTION *ActiveOption,
1129 IN UINTN ActiveCount
1130 )
1131 {
1132 UINTN Idx;
1133
1134 for (Idx = 0; Idx < ActiveCount; ++Idx) {
1135 if (!ActiveOption[Idx].Appended) {
1136 CHAR16 VariableName[9];
1137
1138 UnicodeSPrintAsciiFormat (VariableName, sizeof VariableName, "Boot%04x",
1139 ActiveOption[Idx].BootOption->BootCurrent);
1140
1141 //
1142 // "The space consumed by the deleted variable may not be available until
1143 // the next power cycle", but that's good enough.
1144 //
1145 gRT->SetVariable (VariableName, &gEfiGlobalVariableGuid,
1146 0, // Attributes, 0 means deletion
1147 0, // DataSize, 0 means deletion
1148 NULL // Data
1149 );
1150 }
1151 }
1152 }
1153
1154
1155 /**
1156
1157 Set the boot order based on configuration retrieved from QEMU.
1158
1159 Attempt to retrieve the "bootorder" fw_cfg file from QEMU. Translate the
1160 OpenFirmware device paths therein to UEFI device path fragments. Match the
1161 translated fragments against BootOptionList, and rewrite the BootOrder NvVar
1162 so that it corresponds to the order described in fw_cfg.
1163
1164 @param[in] BootOptionList A boot option list, created with
1165 BdsLibEnumerateAllBootOption ().
1166
1167
1168 @retval RETURN_SUCCESS BootOrder NvVar rewritten.
1169
1170 @retval RETURN_UNSUPPORTED QEMU's fw_cfg is not supported.
1171
1172 @retval RETURN_NOT_FOUND Empty or nonexistent "bootorder" fw_cfg
1173 file, or no match found between the
1174 "bootorder" fw_cfg file and BootOptionList.
1175
1176 @retval RETURN_INVALID_PARAMETER Parse error in the "bootorder" fw_cfg file.
1177
1178 @retval RETURN_OUT_OF_RESOURCES Memory allocation failed.
1179
1180 @return Values returned by gBS->LocateProtocol ()
1181 or gRT->SetVariable ().
1182
1183 **/
1184 RETURN_STATUS
1185 SetBootOrderFromQemu (
1186 IN CONST LIST_ENTRY *BootOptionList
1187 )
1188 {
1189 RETURN_STATUS Status;
1190 FIRMWARE_CONFIG_ITEM FwCfgItem;
1191 UINTN FwCfgSize;
1192 CHAR8 *FwCfg;
1193 CONST CHAR8 *FwCfgPtr;
1194
1195 BOOT_ORDER BootOrder;
1196 ACTIVE_OPTION *ActiveOption;
1197 UINTN ActiveCount;
1198
1199 UINTN TranslatedSize;
1200 CHAR16 Translated[TRANSLATION_OUTPUT_SIZE];
1201
1202 Status = QemuFwCfgFindFile ("bootorder", &FwCfgItem, &FwCfgSize);
1203 if (Status != RETURN_SUCCESS) {
1204 return Status;
1205 }
1206
1207 if (FwCfgSize == 0) {
1208 return RETURN_NOT_FOUND;
1209 }
1210
1211 FwCfg = AllocatePool (FwCfgSize);
1212 if (FwCfg == NULL) {
1213 return RETURN_OUT_OF_RESOURCES;
1214 }
1215
1216 QemuFwCfgSelectItem (FwCfgItem);
1217 QemuFwCfgReadBytes (FwCfgSize, FwCfg);
1218 if (FwCfg[FwCfgSize - 1] != '\0') {
1219 Status = RETURN_INVALID_PARAMETER;
1220 goto ErrorFreeFwCfg;
1221 }
1222
1223 DEBUG ((DEBUG_VERBOSE, "%a: FwCfg:\n", __FUNCTION__));
1224 DEBUG ((DEBUG_VERBOSE, "%a\n", FwCfg));
1225 DEBUG ((DEBUG_VERBOSE, "%a: FwCfg: <end>\n", __FUNCTION__));
1226 FwCfgPtr = FwCfg;
1227
1228 BootOrder.Produced = 0;
1229 BootOrder.Allocated = 1;
1230 BootOrder.Data = AllocatePool (
1231 BootOrder.Allocated * sizeof (*BootOrder.Data)
1232 );
1233 if (BootOrder.Data == NULL) {
1234 Status = RETURN_OUT_OF_RESOURCES;
1235 goto ErrorFreeFwCfg;
1236 }
1237
1238 Status = CollectActiveOptions (BootOptionList, &ActiveOption, &ActiveCount);
1239 if (RETURN_ERROR (Status)) {
1240 goto ErrorFreeBootOrder;
1241 }
1242
1243 //
1244 // translate each OpenFirmware path
1245 //
1246 TranslatedSize = sizeof (Translated) / sizeof (Translated[0]);
1247 Status = TranslateOfwPath (&FwCfgPtr, Translated, &TranslatedSize);
1248 while (Status == RETURN_SUCCESS ||
1249 Status == RETURN_UNSUPPORTED ||
1250 Status == RETURN_BUFFER_TOO_SMALL) {
1251 if (Status == RETURN_SUCCESS) {
1252 UINTN Idx;
1253
1254 //
1255 // match translated OpenFirmware path against all active boot options
1256 //
1257 for (Idx = 0; Idx < ActiveCount; ++Idx) {
1258 if (Match (
1259 Translated,
1260 TranslatedSize, // contains length, not size, in CHAR16's here
1261 ActiveOption[Idx].BootOption->DevicePath
1262 )
1263 ) {
1264 //
1265 // match found, store ID and continue with next OpenFirmware path
1266 //
1267 Status = BootOrderAppend (&BootOrder, &ActiveOption[Idx]);
1268 if (Status != RETURN_SUCCESS) {
1269 goto ErrorFreeActiveOption;
1270 }
1271 break;
1272 }
1273 } // scanned all active boot options
1274 } // translation successful
1275
1276 TranslatedSize = sizeof (Translated) / sizeof (Translated[0]);
1277 Status = TranslateOfwPath (&FwCfgPtr, Translated, &TranslatedSize);
1278 } // scanning of OpenFirmware paths done
1279
1280 if (Status == RETURN_NOT_FOUND && BootOrder.Produced > 0) {
1281 //
1282 // No more OpenFirmware paths, some matches found: rewrite BootOrder NvVar.
1283 // Some of the active boot options that have not been selected over fw_cfg
1284 // should be preserved at the end of the boot order.
1285 //
1286 Status = BootOrderComplete (&BootOrder, ActiveOption, ActiveCount);
1287 if (RETURN_ERROR (Status)) {
1288 goto ErrorFreeActiveOption;
1289 }
1290
1291 //
1292 // See Table 10 in the UEFI Spec 2.3.1 with Errata C for the required
1293 // attributes.
1294 //
1295 Status = gRT->SetVariable (
1296 L"BootOrder",
1297 &gEfiGlobalVariableGuid,
1298 EFI_VARIABLE_NON_VOLATILE |
1299 EFI_VARIABLE_BOOTSERVICE_ACCESS |
1300 EFI_VARIABLE_RUNTIME_ACCESS,
1301 BootOrder.Produced * sizeof (*BootOrder.Data),
1302 BootOrder.Data
1303 );
1304 if (EFI_ERROR (Status)) {
1305 DEBUG ((DEBUG_ERROR, "%a: setting BootOrder: %r\n", __FUNCTION__, Status));
1306 goto ErrorFreeActiveOption;
1307 }
1308
1309 DEBUG ((DEBUG_INFO, "%a: setting BootOrder: success\n", __FUNCTION__));
1310 PruneBootVariables (ActiveOption, ActiveCount);
1311 }
1312
1313 ErrorFreeActiveOption:
1314 FreePool (ActiveOption);
1315
1316 ErrorFreeBootOrder:
1317 FreePool (BootOrder.Data);
1318
1319 ErrorFreeFwCfg:
1320 FreePool (FwCfg);
1321
1322 return Status;
1323 }