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