]> git.proxmox.com Git - mirror_edk2.git/blob - OvmfPkg/Library/PlatformBdsLib/QemuBootOrder.c
OvmfPkg: QemuBootOrder: collect active UEFI boot options in advance
[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 } ACTIVE_OPTION;
248
249
250 /**
251
252 Append BootOptionId to BootOrder, reallocating the latter if needed.
253
254 @param[in out] BootOrder The structure pointing to the array and holding
255 allocation and usage counters.
256
257 @param[in] BootOptionId The value to append to the array.
258
259
260 @retval RETURN_SUCCESS BootOptionId appended.
261
262 @retval RETURN_OUT_OF_RESOURCES Memory reallocation failed.
263
264 **/
265 STATIC
266 RETURN_STATUS
267 BootOrderAppend (
268 IN OUT BOOT_ORDER *BootOrder,
269 IN UINT16 BootOptionId
270 )
271 {
272 if (BootOrder->Produced == BootOrder->Allocated) {
273 UINTN AllocatedNew;
274 UINT16 *DataNew;
275
276 ASSERT (BootOrder->Allocated > 0);
277 AllocatedNew = BootOrder->Allocated * 2;
278 DataNew = ReallocatePool (
279 BootOrder->Allocated * sizeof (*BootOrder->Data),
280 AllocatedNew * sizeof (*DataNew),
281 BootOrder->Data
282 );
283 if (DataNew == NULL) {
284 return RETURN_OUT_OF_RESOURCES;
285 }
286 BootOrder->Allocated = AllocatedNew;
287 BootOrder->Data = DataNew;
288 }
289
290 BootOrder->Data[BootOrder->Produced++] = BootOptionId;
291 return RETURN_SUCCESS;
292 }
293
294
295 /**
296
297 Create an array of ACTIVE_OPTION elements for a boot option list.
298
299 @param[in] BootOptionList A boot option list, created with
300 BdsLibEnumerateAllBootOption().
301
302 @param[out] ActiveOption Pointer to the first element in the new array.
303 The caller is responsible for freeing the array
304 with FreePool() after use.
305
306 @param[out] Count Number of elements in the new array.
307
308
309 @retval RETURN_SUCCESS The ActiveOption array has been created.
310
311 @retval RETURN_NOT_FOUND No active entry has been found in
312 BootOptionList.
313
314 @retval RETURN_OUT_OF_RESOURCES Memory allocation failed.
315
316 **/
317 STATIC
318 RETURN_STATUS
319 CollectActiveOptions (
320 IN CONST LIST_ENTRY *BootOptionList,
321 OUT ACTIVE_OPTION **ActiveOption,
322 OUT UINTN *Count
323 )
324 {
325 UINTN ScanMode;
326
327 *ActiveOption = NULL;
328
329 //
330 // Scan the list twice:
331 // - count active entries,
332 // - store links to active entries.
333 //
334 for (ScanMode = 0; ScanMode < 2; ++ScanMode) {
335 CONST LIST_ENTRY *Link;
336
337 Link = BootOptionList->ForwardLink;
338 *Count = 0;
339 while (Link != BootOptionList) {
340 CONST BDS_COMMON_OPTION *Current;
341
342 Current = CR (Link, BDS_COMMON_OPTION, Link, BDS_LOAD_OPTION_SIGNATURE);
343 if (IS_LOAD_OPTION_TYPE (Current->Attribute, LOAD_OPTION_ACTIVE)) {
344 if (ScanMode == 1) {
345 (*ActiveOption)[*Count].BootOption = Current;
346 }
347 ++*Count;
348 }
349 Link = Link->ForwardLink;
350 }
351
352 if (ScanMode == 0) {
353 if (*Count == 0) {
354 return RETURN_NOT_FOUND;
355 }
356 *ActiveOption = AllocatePool (*Count * sizeof **ActiveOption);
357 if (*ActiveOption == NULL) {
358 return RETURN_OUT_OF_RESOURCES;
359 }
360 }
361 }
362 return RETURN_SUCCESS;
363 }
364
365
366 /**
367 OpenFirmware device path node
368 **/
369 typedef struct {
370 SUBSTRING DriverName;
371 SUBSTRING UnitAddress;
372 SUBSTRING DeviceArguments;
373 } OFW_NODE;
374
375
376 /**
377
378 Parse an OpenFirmware device path node into the caller-allocated OFW_NODE
379 structure, and advance in the input string.
380
381 The node format is mostly parsed after IEEE 1275-1994, 3.2.1.1 "Node names"
382 (a leading slash is expected and not returned):
383
384 /driver-name@unit-address[:device-arguments][<LF>]
385
386 A single trailing <LF> character is consumed but not returned. A trailing
387 <LF> or NUL character terminates the device path.
388
389 The function relies on ASCII encoding.
390
391 @param[in out] Ptr Address of the pointer pointing to the start of the
392 node string. After successful parsing *Ptr is set to
393 the byte immediately following the consumed
394 characters. On error it points to the byte that
395 caused the error. The input string is never modified.
396
397 @param[out] OfwNode The members of this structure point into the input
398 string, designating components of the node.
399 Separators are never included. If "device-arguments"
400 is missing, then DeviceArguments.Ptr is set to NULL.
401 All components that are present have nonzero length.
402
403 If the call doesn't succeed, the contents of this
404 structure is indeterminate.
405
406 @param[out] IsFinal In case of successul parsing, this parameter signals
407 whether the node just parsed is the final node in the
408 device path. The call after a final node will attempt
409 to start parsing the next path. If the call doesn't
410 succeed, then this parameter is not changed.
411
412
413 @retval RETURN_SUCCESS Parsing successful.
414
415 @retval RETURN_NOT_FOUND Parsing terminated. *Ptr was (and is)
416 pointing to an empty string.
417
418 @retval RETURN_INVALID_PARAMETER Parse error.
419
420 **/
421 STATIC
422 RETURN_STATUS
423 ParseOfwNode (
424 IN OUT CONST CHAR8 **Ptr,
425 OUT OFW_NODE *OfwNode,
426 OUT BOOLEAN *IsFinal
427 )
428 {
429 //
430 // A leading slash is expected. End of string is tolerated.
431 //
432 switch (**Ptr) {
433 case '\0':
434 return RETURN_NOT_FOUND;
435
436 case '/':
437 ++*Ptr;
438 break;
439
440 default:
441 return RETURN_INVALID_PARAMETER;
442 }
443
444 //
445 // driver-name
446 //
447 OfwNode->DriverName.Ptr = *Ptr;
448 OfwNode->DriverName.Len = 0;
449 while (OfwNode->DriverName.Len < 32 &&
450 (IsAlnum (**Ptr) || IsDriverNamePunct (**Ptr))
451 ) {
452 ++*Ptr;
453 ++OfwNode->DriverName.Len;
454 }
455
456 if (OfwNode->DriverName.Len == 0 || OfwNode->DriverName.Len == 32) {
457 return RETURN_INVALID_PARAMETER;
458 }
459
460
461 //
462 // unit-address
463 //
464 if (**Ptr != '@') {
465 return RETURN_INVALID_PARAMETER;
466 }
467 ++*Ptr;
468
469 OfwNode->UnitAddress.Ptr = *Ptr;
470 OfwNode->UnitAddress.Len = 0;
471 while (IsPrintNotDelim (**Ptr)) {
472 ++*Ptr;
473 ++OfwNode->UnitAddress.Len;
474 }
475
476 if (OfwNode->UnitAddress.Len == 0) {
477 return RETURN_INVALID_PARAMETER;
478 }
479
480
481 //
482 // device-arguments, may be omitted
483 //
484 OfwNode->DeviceArguments.Len = 0;
485 if (**Ptr == ':') {
486 ++*Ptr;
487 OfwNode->DeviceArguments.Ptr = *Ptr;
488
489 while (IsPrintNotDelim (**Ptr)) {
490 ++*Ptr;
491 ++OfwNode->DeviceArguments.Len;
492 }
493
494 if (OfwNode->DeviceArguments.Len == 0) {
495 return RETURN_INVALID_PARAMETER;
496 }
497 }
498 else {
499 OfwNode->DeviceArguments.Ptr = NULL;
500 }
501
502 switch (**Ptr) {
503 case '\n':
504 ++*Ptr;
505 //
506 // fall through
507 //
508
509 case '\0':
510 *IsFinal = TRUE;
511 break;
512
513 case '/':
514 *IsFinal = FALSE;
515 break;
516
517 default:
518 return RETURN_INVALID_PARAMETER;
519 }
520
521 DEBUG ((
522 DEBUG_VERBOSE,
523 "%a: DriverName=\"%.*a\" UnitAddress=\"%.*a\" DeviceArguments=\"%.*a\"\n",
524 __FUNCTION__,
525 OfwNode->DriverName.Len, OfwNode->DriverName.Ptr,
526 OfwNode->UnitAddress.Len, OfwNode->UnitAddress.Ptr,
527 OfwNode->DeviceArguments.Len,
528 OfwNode->DeviceArguments.Ptr == NULL ? "" : OfwNode->DeviceArguments.Ptr
529 ));
530 return RETURN_SUCCESS;
531 }
532
533
534 /**
535
536 Translate an array of OpenFirmware device nodes to a UEFI device path
537 fragment.
538
539 @param[in] OfwNode Array of OpenFirmware device nodes to
540 translate, constituting the beginning of an
541 OpenFirmware device path.
542
543 @param[in] NumNodes Number of elements in OfwNode.
544
545 @param[out] Translated Destination array receiving the UEFI path
546 fragment, allocated by the caller. If the
547 return value differs from RETURN_SUCCESS, its
548 contents is indeterminate.
549
550 @param[in out] TranslatedSize On input, the number of CHAR16's in
551 Translated. On RETURN_SUCCESS this parameter
552 is assigned the number of non-NUL CHAR16's
553 written to Translated. In case of other return
554 values, TranslatedSize is indeterminate.
555
556
557 @retval RETURN_SUCCESS Translation successful.
558
559 @retval RETURN_BUFFER_TOO_SMALL The translation does not fit into the number
560 of bytes provided.
561
562 @retval RETURN_UNSUPPORTED The array of OpenFirmware device nodes can't
563 be translated in the current implementation.
564
565 **/
566 STATIC
567 RETURN_STATUS
568 TranslateOfwNodes (
569 IN CONST OFW_NODE *OfwNode,
570 IN UINTN NumNodes,
571 OUT CHAR16 *Translated,
572 IN OUT UINTN *TranslatedSize
573 )
574 {
575 UINT32 PciDevFun[2];
576 UINTN NumEntries;
577 UINTN Written;
578
579 //
580 // Get PCI device and optional PCI function. Assume a single PCI root.
581 //
582 if (NumNodes < REQUIRED_OFW_NODES ||
583 !SubstringEq (OfwNode[0].DriverName, "pci")
584 ) {
585 return RETURN_UNSUPPORTED;
586 }
587 PciDevFun[1] = 0;
588 NumEntries = sizeof (PciDevFun) / sizeof (PciDevFun[0]);
589 if (ParseUnitAddressHexList (
590 OfwNode[1].UnitAddress,
591 PciDevFun,
592 &NumEntries
593 ) != RETURN_SUCCESS
594 ) {
595 return RETURN_UNSUPPORTED;
596 }
597
598 if (NumNodes >= 4 &&
599 SubstringEq (OfwNode[1].DriverName, "ide") &&
600 SubstringEq (OfwNode[2].DriverName, "drive") &&
601 SubstringEq (OfwNode[3].DriverName, "disk")
602 ) {
603 //
604 // OpenFirmware device path (IDE disk, IDE CD-ROM):
605 //
606 // /pci@i0cf8/ide@1,1/drive@0/disk@0
607 // ^ ^ ^ ^ ^
608 // | | | | master or slave
609 // | | | primary or secondary
610 // | PCI slot & function holding IDE controller
611 // PCI root at system bus port, PIO
612 //
613 // UEFI device path:
614 //
615 // PciRoot(0x0)/Pci(0x1,0x1)/Ata(Primary,Master,0x0)
616 // ^
617 // fixed LUN
618 //
619 UINT32 Secondary;
620 UINT32 Slave;
621
622 NumEntries = 1;
623 if (ParseUnitAddressHexList (
624 OfwNode[2].UnitAddress,
625 &Secondary,
626 &NumEntries
627 ) != RETURN_SUCCESS ||
628 Secondary > 1 ||
629 ParseUnitAddressHexList (
630 OfwNode[3].UnitAddress,
631 &Slave,
632 &NumEntries // reuse after previous single-element call
633 ) != RETURN_SUCCESS ||
634 Slave > 1
635 ) {
636 return RETURN_UNSUPPORTED;
637 }
638
639 Written = UnicodeSPrintAsciiFormat (
640 Translated,
641 *TranslatedSize * sizeof (*Translated), // BufferSize in bytes
642 "PciRoot(0x0)/Pci(0x%x,0x%x)/Ata(%a,%a,0x0)",
643 PciDevFun[0],
644 PciDevFun[1],
645 Secondary ? "Secondary" : "Primary",
646 Slave ? "Slave" : "Master"
647 );
648 } else if (NumNodes >= 4 &&
649 SubstringEq (OfwNode[1].DriverName, "isa") &&
650 SubstringEq (OfwNode[2].DriverName, "fdc") &&
651 SubstringEq (OfwNode[3].DriverName, "floppy")
652 ) {
653 //
654 // OpenFirmware device path (floppy disk):
655 //
656 // /pci@i0cf8/isa@1/fdc@03f0/floppy@0
657 // ^ ^ ^ ^
658 // | | | A: or B:
659 // | | ISA controller io-port (hex)
660 // | PCI slot holding ISA controller
661 // PCI root at system bus port, PIO
662 //
663 // UEFI device path:
664 //
665 // PciRoot(0x0)/Pci(0x1,0x0)/Floppy(0x0)
666 // ^
667 // ACPI UID
668 //
669 UINT32 AcpiUid;
670
671 NumEntries = 1;
672 if (ParseUnitAddressHexList (
673 OfwNode[3].UnitAddress,
674 &AcpiUid,
675 &NumEntries
676 ) != RETURN_SUCCESS ||
677 AcpiUid > 1
678 ) {
679 return RETURN_UNSUPPORTED;
680 }
681
682 Written = UnicodeSPrintAsciiFormat (
683 Translated,
684 *TranslatedSize * sizeof (*Translated), // BufferSize in bytes
685 "PciRoot(0x0)/Pci(0x%x,0x%x)/Floppy(0x%x)",
686 PciDevFun[0],
687 PciDevFun[1],
688 AcpiUid
689 );
690 } else if (NumNodes >= 3 &&
691 SubstringEq (OfwNode[1].DriverName, "scsi") &&
692 SubstringEq (OfwNode[2].DriverName, "disk")
693 ) {
694 //
695 // OpenFirmware device path (virtio-blk disk):
696 //
697 // /pci@i0cf8/scsi@6[,3]/disk@0,0
698 // ^ ^ ^ ^ ^
699 // | | | fixed
700 // | | PCI function corresponding to disk (optional)
701 // | PCI slot holding disk
702 // PCI root at system bus port, PIO
703 //
704 // UEFI device path prefix:
705 //
706 // PciRoot(0x0)/Pci(0x6,0x0)/HD( -- if PCI function is 0 or absent
707 // PciRoot(0x0)/Pci(0x6,0x3)/HD( -- if PCI function is present and nonzero
708 //
709 Written = UnicodeSPrintAsciiFormat (
710 Translated,
711 *TranslatedSize * sizeof (*Translated), // BufferSize in bytes
712 "PciRoot(0x0)/Pci(0x%x,0x%x)/HD(",
713 PciDevFun[0],
714 PciDevFun[1]
715 );
716 } else if (NumNodes >= 4 &&
717 SubstringEq (OfwNode[1].DriverName, "scsi") &&
718 SubstringEq (OfwNode[2].DriverName, "channel") &&
719 SubstringEq (OfwNode[3].DriverName, "disk")
720 ) {
721 //
722 // OpenFirmware device path (virtio-scsi disk):
723 //
724 // /pci@i0cf8/scsi@7[,3]/channel@0/disk@2,3
725 // ^ ^ ^ ^ ^
726 // | | | | LUN
727 // | | | target
728 // | | channel (unused, fixed 0)
729 // | PCI slot[, function] holding SCSI controller
730 // PCI root at system bus port, PIO
731 //
732 // UEFI device path prefix:
733 //
734 // PciRoot(0x0)/Pci(0x7,0x0)/Scsi(0x2,0x3)
735 // -- if PCI function is 0 or absent
736 // PciRoot(0x0)/Pci(0x7,0x3)/Scsi(0x2,0x3)
737 // -- if PCI function is present and nonzero
738 //
739 UINT32 TargetLun[2];
740
741 TargetLun[1] = 0;
742 NumEntries = sizeof (TargetLun) / sizeof (TargetLun[0]);
743 if (ParseUnitAddressHexList (
744 OfwNode[3].UnitAddress,
745 TargetLun,
746 &NumEntries
747 ) != RETURN_SUCCESS
748 ) {
749 return RETURN_UNSUPPORTED;
750 }
751
752 Written = UnicodeSPrintAsciiFormat (
753 Translated,
754 *TranslatedSize * sizeof (*Translated), // BufferSize in bytes
755 "PciRoot(0x0)/Pci(0x%x,0x%x)/Scsi(0x%x,0x%x)",
756 PciDevFun[0],
757 PciDevFun[1],
758 TargetLun[0],
759 TargetLun[1]
760 );
761 } else if (NumNodes >= 3 &&
762 SubstringEq (OfwNode[1].DriverName, "ethernet") &&
763 SubstringEq (OfwNode[2].DriverName, "ethernet-phy")
764 ) {
765 //
766 // OpenFirmware device path (Ethernet NIC):
767 //
768 // /pci@i0cf8/ethernet@3[,2]/ethernet-phy@0
769 // ^ ^ ^
770 // | | fixed
771 // | PCI slot[, function] holding Ethernet card
772 // PCI root at system bus port, PIO
773 //
774 // UEFI device path prefix (dependent on presence of nonzero PCI function):
775 //
776 // PciRoot(0x0)/Pci(0x3,0x0)/MAC(525400E15EEF,0x1)
777 // PciRoot(0x0)/Pci(0x3,0x2)/MAC(525400E15EEF,0x1)
778 // ^ ^
779 // MAC address IfType (1 == Ethernet)
780 //
781 // (Some UEFI NIC drivers don't set 0x1 for IfType.)
782 //
783 Written = UnicodeSPrintAsciiFormat (
784 Translated,
785 *TranslatedSize * sizeof (*Translated), // BufferSize in bytes
786 "PciRoot(0x0)/Pci(0x%x,0x%x)/MAC",
787 PciDevFun[0],
788 PciDevFun[1]
789 );
790 } else {
791 return RETURN_UNSUPPORTED;
792 }
793
794 //
795 // There's no way to differentiate between "completely used up without
796 // truncation" and "truncated", so treat the former as the latter, and return
797 // success only for "some room left unused".
798 //
799 if (Written + 1 < *TranslatedSize) {
800 *TranslatedSize = Written;
801 return RETURN_SUCCESS;
802 }
803
804 return RETURN_BUFFER_TOO_SMALL;
805 }
806
807
808 /**
809
810 Translate an OpenFirmware device path fragment to a UEFI device path
811 fragment, and advance in the input string.
812
813 @param[in out] Ptr Address of the pointer pointing to the start
814 of the path string. After successful
815 translation (RETURN_SUCCESS) or at least
816 successful parsing (RETURN_UNSUPPORTED,
817 RETURN_BUFFER_TOO_SMALL), *Ptr is set to the
818 byte immediately following the consumed
819 characters. In other error cases, it points to
820 the byte that caused the error.
821
822 @param[out] Translated Destination array receiving the UEFI path
823 fragment, allocated by the caller. If the
824 return value differs from RETURN_SUCCESS, its
825 contents is indeterminate.
826
827 @param[in out] TranslatedSize On input, the number of CHAR16's in
828 Translated. On RETURN_SUCCESS this parameter
829 is assigned the number of non-NUL CHAR16's
830 written to Translated. In case of other return
831 values, TranslatedSize is indeterminate.
832
833
834 @retval RETURN_SUCCESS Translation successful.
835
836 @retval RETURN_BUFFER_TOO_SMALL The OpenFirmware device path was parsed
837 successfully, but its translation did not
838 fit into the number of bytes provided.
839 Further calls to this function are
840 possible.
841
842 @retval RETURN_UNSUPPORTED The OpenFirmware device path was parsed
843 successfully, but it can't be translated in
844 the current implementation. Further calls
845 to this function are possible.
846
847 @retval RETURN_NOT_FOUND Translation terminated, *Ptr was (and is)
848 pointing to an empty string.
849
850 @retval RETURN_INVALID_PARAMETER Parse error. This is a permanent error.
851
852 **/
853 STATIC
854 RETURN_STATUS
855 TranslateOfwPath (
856 IN OUT CONST CHAR8 **Ptr,
857 OUT CHAR16 *Translated,
858 IN OUT UINTN *TranslatedSize
859 )
860 {
861 UINTN NumNodes;
862 RETURN_STATUS Status;
863 OFW_NODE Node[EXAMINED_OFW_NODES];
864 BOOLEAN IsFinal;
865 OFW_NODE Skip;
866
867 NumNodes = 0;
868 Status = ParseOfwNode (Ptr, &Node[NumNodes], &IsFinal);
869
870 if (Status == RETURN_NOT_FOUND) {
871 DEBUG ((DEBUG_VERBOSE, "%a: no more nodes\n", __FUNCTION__));
872 return RETURN_NOT_FOUND;
873 }
874
875 while (Status == RETURN_SUCCESS && !IsFinal) {
876 ++NumNodes;
877 Status = ParseOfwNode (
878 Ptr,
879 (NumNodes < EXAMINED_OFW_NODES) ? &Node[NumNodes] : &Skip,
880 &IsFinal
881 );
882 }
883
884 switch (Status) {
885 case RETURN_SUCCESS:
886 ++NumNodes;
887 break;
888
889 case RETURN_INVALID_PARAMETER:
890 DEBUG ((DEBUG_VERBOSE, "%a: parse error\n", __FUNCTION__));
891 return RETURN_INVALID_PARAMETER;
892
893 default:
894 ASSERT (0);
895 }
896
897 Status = TranslateOfwNodes (
898 Node,
899 NumNodes < EXAMINED_OFW_NODES ? NumNodes : EXAMINED_OFW_NODES,
900 Translated,
901 TranslatedSize);
902 switch (Status) {
903 case RETURN_SUCCESS:
904 DEBUG ((DEBUG_VERBOSE, "%a: success: \"%s\"\n", __FUNCTION__, Translated));
905 break;
906
907 case RETURN_BUFFER_TOO_SMALL:
908 DEBUG ((DEBUG_VERBOSE, "%a: buffer too small\n", __FUNCTION__));
909 break;
910
911 case RETURN_UNSUPPORTED:
912 DEBUG ((DEBUG_VERBOSE, "%a: unsupported\n", __FUNCTION__));
913 break;
914
915 default:
916 ASSERT (0);
917 }
918 return Status;
919 }
920
921
922 /**
923
924 Convert the UEFI DevicePath to full text representation with DevPathToText,
925 then match the UEFI device path fragment in Translated against it.
926
927 @param[in] Translated UEFI device path fragment, translated from
928 OpenFirmware format, to search for.
929
930 @param[in] TranslatedLength The length of Translated in CHAR16's.
931
932 @param[in] DevicePath Boot option device path whose textual rendering
933 to search in.
934
935 @param[in] DevPathToText Binary-to-text conversion protocol for DevicePath.
936
937
938 @retval TRUE If Translated was found at the beginning of DevicePath after
939 converting the latter to text.
940
941 @retval FALSE If DevicePath was NULL, or it could not be converted, or there
942 was no match.
943
944 **/
945 STATIC
946 BOOLEAN
947 Match (
948 IN CONST CHAR16 *Translated,
949 IN UINTN TranslatedLength,
950 IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePath
951 )
952 {
953 CHAR16 *Converted;
954 BOOLEAN Result;
955
956 Converted = ConvertDevicePathToText (
957 DevicePath,
958 FALSE, // DisplayOnly
959 FALSE // AllowShortcuts
960 );
961 if (Converted == NULL) {
962 return FALSE;
963 }
964
965 //
966 // Attempt to expand any relative UEFI device path starting with HD() to an
967 // absolute device path first. The logic imitates BdsLibBootViaBootOption().
968 // We don't have to free the absolute device path,
969 // BdsExpandPartitionPartialDevicePathToFull() has internal caching.
970 //
971 Result = FALSE;
972 if (DevicePathType (DevicePath) == MEDIA_DEVICE_PATH &&
973 DevicePathSubType (DevicePath) == MEDIA_HARDDRIVE_DP) {
974 EFI_DEVICE_PATH_PROTOCOL *AbsDevicePath;
975 CHAR16 *AbsConverted;
976
977 AbsDevicePath = BdsExpandPartitionPartialDevicePathToFull (
978 (HARDDRIVE_DEVICE_PATH *) DevicePath);
979 if (AbsDevicePath == NULL) {
980 goto Exit;
981 }
982 AbsConverted = ConvertDevicePathToText (AbsDevicePath, FALSE, FALSE);
983 if (AbsConverted == NULL) {
984 goto Exit;
985 }
986 DEBUG ((DEBUG_VERBOSE,
987 "%a: expanded relative device path \"%s\" for prefix matching\n",
988 __FUNCTION__, Converted));
989 FreePool (Converted);
990 Converted = AbsConverted;
991 }
992
993 //
994 // Is Translated a prefix of Converted?
995 //
996 Result = (BOOLEAN)(StrnCmp (Converted, Translated, TranslatedLength) == 0);
997 DEBUG ((
998 DEBUG_VERBOSE,
999 "%a: against \"%s\": %a\n",
1000 __FUNCTION__,
1001 Converted,
1002 Result ? "match" : "no match"
1003 ));
1004 Exit:
1005 FreePool (Converted);
1006 return Result;
1007 }
1008
1009
1010 /**
1011
1012 Set the boot order based on configuration retrieved from QEMU.
1013
1014 Attempt to retrieve the "bootorder" fw_cfg file from QEMU. Translate the
1015 OpenFirmware device paths therein to UEFI device path fragments. Match the
1016 translated fragments against BootOptionList, and rewrite the BootOrder NvVar
1017 so that it corresponds to the order described in fw_cfg.
1018
1019 @param[in] BootOptionList A boot option list, created with
1020 BdsLibEnumerateAllBootOption ().
1021
1022
1023 @retval RETURN_SUCCESS BootOrder NvVar rewritten.
1024
1025 @retval RETURN_UNSUPPORTED QEMU's fw_cfg is not supported.
1026
1027 @retval RETURN_NOT_FOUND Empty or nonexistent "bootorder" fw_cfg
1028 file, or no match found between the
1029 "bootorder" fw_cfg file and BootOptionList.
1030
1031 @retval RETURN_INVALID_PARAMETER Parse error in the "bootorder" fw_cfg file.
1032
1033 @retval RETURN_OUT_OF_RESOURCES Memory allocation failed.
1034
1035 @return Values returned by gBS->LocateProtocol ()
1036 or gRT->SetVariable ().
1037
1038 **/
1039 RETURN_STATUS
1040 SetBootOrderFromQemu (
1041 IN CONST LIST_ENTRY *BootOptionList
1042 )
1043 {
1044 RETURN_STATUS Status;
1045 FIRMWARE_CONFIG_ITEM FwCfgItem;
1046 UINTN FwCfgSize;
1047 CHAR8 *FwCfg;
1048 CONST CHAR8 *FwCfgPtr;
1049
1050 BOOT_ORDER BootOrder;
1051 ACTIVE_OPTION *ActiveOption;
1052 UINTN ActiveCount;
1053
1054 UINTN TranslatedSize;
1055 CHAR16 Translated[TRANSLATION_OUTPUT_SIZE];
1056
1057 Status = QemuFwCfgFindFile ("bootorder", &FwCfgItem, &FwCfgSize);
1058 if (Status != RETURN_SUCCESS) {
1059 return Status;
1060 }
1061
1062 if (FwCfgSize == 0) {
1063 return RETURN_NOT_FOUND;
1064 }
1065
1066 FwCfg = AllocatePool (FwCfgSize);
1067 if (FwCfg == NULL) {
1068 return RETURN_OUT_OF_RESOURCES;
1069 }
1070
1071 QemuFwCfgSelectItem (FwCfgItem);
1072 QemuFwCfgReadBytes (FwCfgSize, FwCfg);
1073 if (FwCfg[FwCfgSize - 1] != '\0') {
1074 Status = RETURN_INVALID_PARAMETER;
1075 goto ErrorFreeFwCfg;
1076 }
1077
1078 DEBUG ((DEBUG_VERBOSE, "%a: FwCfg:\n", __FUNCTION__));
1079 DEBUG ((DEBUG_VERBOSE, "%a\n", FwCfg));
1080 DEBUG ((DEBUG_VERBOSE, "%a: FwCfg: <end>\n", __FUNCTION__));
1081 FwCfgPtr = FwCfg;
1082
1083 BootOrder.Produced = 0;
1084 BootOrder.Allocated = 1;
1085 BootOrder.Data = AllocatePool (
1086 BootOrder.Allocated * sizeof (*BootOrder.Data)
1087 );
1088 if (BootOrder.Data == NULL) {
1089 Status = RETURN_OUT_OF_RESOURCES;
1090 goto ErrorFreeFwCfg;
1091 }
1092
1093 Status = CollectActiveOptions (BootOptionList, &ActiveOption, &ActiveCount);
1094 if (RETURN_ERROR (Status)) {
1095 goto ErrorFreeBootOrder;
1096 }
1097
1098 //
1099 // translate each OpenFirmware path
1100 //
1101 TranslatedSize = sizeof (Translated) / sizeof (Translated[0]);
1102 Status = TranslateOfwPath (&FwCfgPtr, Translated, &TranslatedSize);
1103 while (Status == RETURN_SUCCESS ||
1104 Status == RETURN_UNSUPPORTED ||
1105 Status == RETURN_BUFFER_TOO_SMALL) {
1106 if (Status == RETURN_SUCCESS) {
1107 UINTN Idx;
1108
1109 //
1110 // match translated OpenFirmware path against all active boot options
1111 //
1112 for (Idx = 0; Idx < ActiveCount; ++Idx) {
1113 if (Match (
1114 Translated,
1115 TranslatedSize, // contains length, not size, in CHAR16's here
1116 ActiveOption[Idx].BootOption->DevicePath
1117 )
1118 ) {
1119 //
1120 // match found, store ID and continue with next OpenFirmware path
1121 //
1122 Status = BootOrderAppend (&BootOrder,
1123 ActiveOption[Idx].BootOption->BootCurrent);
1124 if (Status != RETURN_SUCCESS) {
1125 goto ErrorFreeActiveOption;
1126 }
1127 break;
1128 }
1129 } // scanned all active boot options
1130 } // translation successful
1131
1132 TranslatedSize = sizeof (Translated) / sizeof (Translated[0]);
1133 Status = TranslateOfwPath (&FwCfgPtr, Translated, &TranslatedSize);
1134 } // scanning of OpenFirmware paths done
1135
1136 if (Status == RETURN_NOT_FOUND && BootOrder.Produced > 0) {
1137 //
1138 // No more OpenFirmware paths, some matches found: rewrite BootOrder NvVar.
1139 // See Table 10 in the UEFI Spec 2.3.1 with Errata C for the required
1140 // attributes.
1141 //
1142 Status = gRT->SetVariable (
1143 L"BootOrder",
1144 &gEfiGlobalVariableGuid,
1145 EFI_VARIABLE_NON_VOLATILE |
1146 EFI_VARIABLE_BOOTSERVICE_ACCESS |
1147 EFI_VARIABLE_RUNTIME_ACCESS,
1148 BootOrder.Produced * sizeof (*BootOrder.Data),
1149 BootOrder.Data
1150 );
1151 DEBUG ((
1152 DEBUG_INFO,
1153 "%a: setting BootOrder: %a\n",
1154 __FUNCTION__,
1155 Status == EFI_SUCCESS ? "success" : "error"
1156 ));
1157 }
1158
1159 ErrorFreeActiveOption:
1160 FreePool (ActiveOption);
1161
1162 ErrorFreeBootOrder:
1163 FreePool (BootOrder.Data);
1164
1165 ErrorFreeFwCfg:
1166 FreePool (FwCfg);
1167
1168 return Status;
1169 }