]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Library/UefiBootManagerLib/BmMisc.c
MdeModulePkg: Replace BSD License with BSD+Patent License
[mirror_edk2.git] / MdeModulePkg / Library / UefiBootManagerLib / BmMisc.c
1 /** @file
2 Misc library functions.
3
4 Copyright (c) 2011 - 2018, Intel Corporation. All rights reserved.<BR>
5 (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
6 SPDX-License-Identifier: BSD-2-Clause-Patent
7
8 **/
9
10 #include "InternalBm.h"
11
12 /**
13 Delete the instance in Multi which matches partly with Single instance
14
15 @param Multi A pointer to a multi-instance device path data
16 structure.
17 @param Single A pointer to a single-instance device path data
18 structure.
19
20 @return This function will remove the device path instances in Multi which partly
21 match with the Single, and return the result device path. If there is no
22 remaining device path as a result, this function will return NULL.
23
24 **/
25 EFI_DEVICE_PATH_PROTOCOL *
26 BmDelPartMatchInstance (
27 IN EFI_DEVICE_PATH_PROTOCOL *Multi,
28 IN EFI_DEVICE_PATH_PROTOCOL *Single
29 )
30 {
31 EFI_DEVICE_PATH_PROTOCOL *Instance;
32 EFI_DEVICE_PATH_PROTOCOL *NewDevicePath;
33 EFI_DEVICE_PATH_PROTOCOL *TempNewDevicePath;
34 UINTN InstanceSize;
35 UINTN SingleDpSize;
36
37 NewDevicePath = NULL;
38 TempNewDevicePath = NULL;
39
40 if (Multi == NULL || Single == NULL) {
41 return Multi;
42 }
43
44 Instance = GetNextDevicePathInstance (&Multi, &InstanceSize);
45 SingleDpSize = GetDevicePathSize (Single) - END_DEVICE_PATH_LENGTH;
46 InstanceSize -= END_DEVICE_PATH_LENGTH;
47
48 while (Instance != NULL) {
49
50 if (CompareMem (Instance, Single, MIN (SingleDpSize, InstanceSize)) != 0) {
51 //
52 // Append the device path instance which does not match with Single
53 //
54 TempNewDevicePath = NewDevicePath;
55 NewDevicePath = AppendDevicePathInstance (NewDevicePath, Instance);
56 if (TempNewDevicePath != NULL) {
57 FreePool(TempNewDevicePath);
58 }
59 }
60 FreePool(Instance);
61 Instance = GetNextDevicePathInstance (&Multi, &InstanceSize);
62 InstanceSize -= END_DEVICE_PATH_LENGTH;
63 }
64
65 return NewDevicePath;
66 }
67
68 /**
69 Function compares a device path data structure to that of all the nodes of a
70 second device path instance.
71
72 @param Multi A pointer to a multi-instance device path data
73 structure.
74 @param Single A pointer to a single-instance device path data
75 structure.
76
77 @retval TRUE If the Single device path is contained within Multi device path.
78 @retval FALSE The Single device path is not match within Multi device path.
79
80 **/
81 BOOLEAN
82 BmMatchDevicePaths (
83 IN EFI_DEVICE_PATH_PROTOCOL *Multi,
84 IN EFI_DEVICE_PATH_PROTOCOL *Single
85 )
86 {
87 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
88 EFI_DEVICE_PATH_PROTOCOL *DevicePathInst;
89 UINTN Size;
90
91 if (Multi == NULL || Single == NULL) {
92 return FALSE;
93 }
94
95 DevicePath = Multi;
96 DevicePathInst = GetNextDevicePathInstance (&DevicePath, &Size);
97
98 //
99 // Search for the match of 'Single' in 'Multi'
100 //
101 while (DevicePathInst != NULL) {
102 //
103 // If the single device path is found in multiple device paths,
104 // return success
105 //
106 if (CompareMem (Single, DevicePathInst, Size) == 0) {
107 FreePool (DevicePathInst);
108 return TRUE;
109 }
110
111 FreePool (DevicePathInst);
112 DevicePathInst = GetNextDevicePathInstance (&DevicePath, &Size);
113 }
114
115 return FALSE;
116 }
117
118 /**
119 This routine adjust the memory information for different memory type and
120 save them into the variables for next boot. It resets the system when
121 memory information is updated and the current boot option belongs to
122 boot category instead of application category. It doesn't count the
123 reserved memory occupied by RAM Disk.
124
125 @param Boot TRUE if current boot option belongs to boot
126 category instead of application category.
127 **/
128 VOID
129 BmSetMemoryTypeInformationVariable (
130 IN BOOLEAN Boot
131 )
132 {
133 EFI_STATUS Status;
134 EFI_MEMORY_TYPE_INFORMATION *PreviousMemoryTypeInformation;
135 EFI_MEMORY_TYPE_INFORMATION *CurrentMemoryTypeInformation;
136 UINTN VariableSize;
137 UINTN Index;
138 UINTN Index1;
139 UINT32 Previous;
140 UINT32 Current;
141 UINT32 Next;
142 EFI_HOB_GUID_TYPE *GuidHob;
143 BOOLEAN MemoryTypeInformationModified;
144 BOOLEAN MemoryTypeInformationVariableExists;
145 EFI_BOOT_MODE BootMode;
146
147 MemoryTypeInformationModified = FALSE;
148 MemoryTypeInformationVariableExists = FALSE;
149
150
151 BootMode = GetBootModeHob ();
152 //
153 // In BOOT_IN_RECOVERY_MODE, Variable region is not reliable.
154 //
155 if (BootMode == BOOT_IN_RECOVERY_MODE) {
156 return;
157 }
158
159 //
160 // Only check the the Memory Type Information variable in the boot mode
161 // other than BOOT_WITH_DEFAULT_SETTINGS because the Memory Type
162 // Information is not valid in this boot mode.
163 //
164 if (BootMode != BOOT_WITH_DEFAULT_SETTINGS) {
165 VariableSize = 0;
166 Status = gRT->GetVariable (
167 EFI_MEMORY_TYPE_INFORMATION_VARIABLE_NAME,
168 &gEfiMemoryTypeInformationGuid,
169 NULL,
170 &VariableSize,
171 NULL
172 );
173 if (Status == EFI_BUFFER_TOO_SMALL) {
174 MemoryTypeInformationVariableExists = TRUE;
175 }
176 }
177
178 //
179 // Retrieve the current memory usage statistics. If they are not found, then
180 // no adjustments can be made to the Memory Type Information variable.
181 //
182 Status = EfiGetSystemConfigurationTable (
183 &gEfiMemoryTypeInformationGuid,
184 (VOID **) &CurrentMemoryTypeInformation
185 );
186 if (EFI_ERROR (Status) || CurrentMemoryTypeInformation == NULL) {
187 return;
188 }
189
190 //
191 // Get the Memory Type Information settings from Hob if they exist,
192 // PEI is responsible for getting them from variable and build a Hob to save them.
193 // If the previous Memory Type Information is not available, then set defaults
194 //
195 GuidHob = GetFirstGuidHob (&gEfiMemoryTypeInformationGuid);
196 if (GuidHob == NULL) {
197 //
198 // If Platform has not built Memory Type Info into the Hob, just return.
199 //
200 return;
201 }
202 VariableSize = GET_GUID_HOB_DATA_SIZE (GuidHob);
203 PreviousMemoryTypeInformation = AllocateCopyPool (VariableSize, GET_GUID_HOB_DATA (GuidHob));
204 if (PreviousMemoryTypeInformation == NULL) {
205 return;
206 }
207
208 //
209 // Use a heuristic to adjust the Memory Type Information for the next boot
210 //
211 DEBUG ((EFI_D_INFO, "Memory Previous Current Next \n"));
212 DEBUG ((EFI_D_INFO, " Type Pages Pages Pages \n"));
213 DEBUG ((EFI_D_INFO, "====== ======== ======== ========\n"));
214
215 for (Index = 0; PreviousMemoryTypeInformation[Index].Type != EfiMaxMemoryType; Index++) {
216
217 for (Index1 = 0; CurrentMemoryTypeInformation[Index1].Type != EfiMaxMemoryType; Index1++) {
218 if (PreviousMemoryTypeInformation[Index].Type == CurrentMemoryTypeInformation[Index1].Type) {
219 break;
220 }
221 }
222 if (CurrentMemoryTypeInformation[Index1].Type == EfiMaxMemoryType) {
223 continue;
224 }
225
226 //
227 // Previous is the number of pages pre-allocated
228 // Current is the number of pages actually needed
229 //
230 Previous = PreviousMemoryTypeInformation[Index].NumberOfPages;
231 Current = CurrentMemoryTypeInformation[Index1].NumberOfPages;
232 Next = Previous;
233
234 //
235 // Inconsistent Memory Reserved across bootings may lead to S4 fail
236 // Write next varible to 125% * current when the pre-allocated memory is:
237 // 1. More than 150% of needed memory and boot mode is BOOT_WITH_DEFAULT_SETTING
238 // 2. Less than the needed memory
239 //
240 if ((Current + (Current >> 1)) < Previous) {
241 if (BootMode == BOOT_WITH_DEFAULT_SETTINGS) {
242 Next = Current + (Current >> 2);
243 }
244 } else if (Current > Previous) {
245 Next = Current + (Current >> 2);
246 }
247 if (Next > 0 && Next < 4) {
248 Next = 4;
249 }
250
251 if (Next != Previous) {
252 PreviousMemoryTypeInformation[Index].NumberOfPages = Next;
253 MemoryTypeInformationModified = TRUE;
254 }
255
256 DEBUG ((EFI_D_INFO, " %02x %08x %08x %08x\n", PreviousMemoryTypeInformation[Index].Type, Previous, Current, Next));
257 }
258
259 //
260 // If any changes were made to the Memory Type Information settings, then set the new variable value;
261 // Or create the variable in first boot.
262 //
263 if (MemoryTypeInformationModified || !MemoryTypeInformationVariableExists) {
264 Status = BmSetVariableAndReportStatusCodeOnError (
265 EFI_MEMORY_TYPE_INFORMATION_VARIABLE_NAME,
266 &gEfiMemoryTypeInformationGuid,
267 EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,
268 VariableSize,
269 PreviousMemoryTypeInformation
270 );
271
272 if (!EFI_ERROR (Status)) {
273 //
274 // If the Memory Type Information settings have been modified and the boot option belongs to boot category,
275 // then reset the platform so the new Memory Type Information setting will be used to guarantee that an S4
276 // entry/resume cycle will not fail.
277 //
278 if (MemoryTypeInformationModified) {
279 DEBUG ((EFI_D_INFO, "Memory Type Information settings change.\n"));
280 if (Boot && PcdGetBool (PcdResetOnMemoryTypeInformationChange)) {
281 DEBUG ((EFI_D_INFO, "...Warm Reset!!!\n"));
282 gRT->ResetSystem (EfiResetWarm, EFI_SUCCESS, 0, NULL);
283 }
284 }
285 } else {
286 DEBUG ((EFI_D_ERROR, "Memory Type Information settings cannot be saved. OS S4 may fail!\n"));
287 }
288 }
289 FreePool (PreviousMemoryTypeInformation);
290 }
291
292 /**
293 Set the variable and report the error through status code upon failure.
294
295 @param VariableName A Null-terminated string that is the name of the vendor's variable.
296 Each VariableName is unique for each VendorGuid. VariableName must
297 contain 1 or more characters. If VariableName is an empty string,
298 then EFI_INVALID_PARAMETER is returned.
299 @param VendorGuid A unique identifier for the vendor.
300 @param Attributes Attributes bitmask to set for the variable.
301 @param DataSize The size in bytes of the Data buffer. Unless the EFI_VARIABLE_APPEND_WRITE,
302 or EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS attribute is set, a size of zero
303 causes the variable to be deleted. When the EFI_VARIABLE_APPEND_WRITE attribute is
304 set, then a SetVariable() call with a DataSize of zero will not cause any change to
305 the variable value (the timestamp associated with the variable may be updated however
306 even if no new data value is provided,see the description of the
307 EFI_VARIABLE_AUTHENTICATION_2 descriptor below. In this case the DataSize will not
308 be zero since the EFI_VARIABLE_AUTHENTICATION_2 descriptor will be populated).
309 @param Data The contents for the variable.
310
311 @retval EFI_SUCCESS The firmware has successfully stored the variable and its data as
312 defined by the Attributes.
313 @retval EFI_INVALID_PARAMETER An invalid combination of attribute bits, name, and GUID was supplied, or the
314 DataSize exceeds the maximum allowed.
315 @retval EFI_INVALID_PARAMETER VariableName is an empty string.
316 @retval EFI_OUT_OF_RESOURCES Not enough storage is available to hold the variable and its data.
317 @retval EFI_DEVICE_ERROR The variable could not be retrieved due to a hardware error.
318 @retval EFI_WRITE_PROTECTED The variable in question is read-only.
319 @retval EFI_WRITE_PROTECTED The variable in question cannot be deleted.
320 @retval EFI_SECURITY_VIOLATION The variable could not be written due to EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACESS
321 being set, but the AuthInfo does NOT pass the validation check carried out by the firmware.
322
323 @retval EFI_NOT_FOUND The variable trying to be updated or deleted was not found.
324 **/
325 EFI_STATUS
326 BmSetVariableAndReportStatusCodeOnError (
327 IN CHAR16 *VariableName,
328 IN EFI_GUID *VendorGuid,
329 IN UINT32 Attributes,
330 IN UINTN DataSize,
331 IN VOID *Data
332 )
333 {
334 EFI_STATUS Status;
335 EDKII_SET_VARIABLE_STATUS *SetVariableStatus;
336 UINTN NameSize;
337
338 Status = gRT->SetVariable (
339 VariableName,
340 VendorGuid,
341 Attributes,
342 DataSize,
343 Data
344 );
345 if (EFI_ERROR (Status)) {
346 NameSize = StrSize (VariableName);
347 SetVariableStatus = AllocatePool (sizeof (EDKII_SET_VARIABLE_STATUS) + NameSize + DataSize);
348 if (SetVariableStatus != NULL) {
349 CopyGuid (&SetVariableStatus->Guid, VendorGuid);
350 SetVariableStatus->NameSize = NameSize;
351 SetVariableStatus->DataSize = DataSize;
352 SetVariableStatus->SetStatus = Status;
353 SetVariableStatus->Attributes = Attributes;
354 CopyMem (SetVariableStatus + 1, VariableName, NameSize);
355 CopyMem (((UINT8 *) (SetVariableStatus + 1)) + NameSize, Data, DataSize);
356
357 REPORT_STATUS_CODE_EX (
358 EFI_ERROR_CODE,
359 PcdGet32 (PcdErrorCodeSetVariable),
360 0,
361 NULL,
362 &gEdkiiStatusCodeDataTypeVariableGuid,
363 SetVariableStatus,
364 sizeof (EDKII_SET_VARIABLE_STATUS) + NameSize + DataSize
365 );
366
367 FreePool (SetVariableStatus);
368 }
369 }
370
371 return Status;
372 }
373
374
375 /**
376 Print the device path info.
377
378 @param DevicePath The device path need to print.
379 **/
380 VOID
381 BmPrintDp (
382 EFI_DEVICE_PATH_PROTOCOL *DevicePath
383 )
384 {
385 CHAR16 *Str;
386
387 Str = ConvertDevicePathToText (DevicePath, FALSE, FALSE);
388 DEBUG ((EFI_D_INFO, "%s", Str));
389 if (Str != NULL) {
390 FreePool (Str);
391 }
392 }
393
394 /**
395 Convert a single character to number.
396 It assumes the input Char is in the scope of L'0' ~ L'9' and L'A' ~ L'F'
397
398 @param Char The input char which need to convert to int.
399
400 @return The converted 8-bit number or (UINTN) -1 if conversion failed.
401 **/
402 UINTN
403 BmCharToUint (
404 IN CHAR16 Char
405 )
406 {
407 if ((Char >= L'0') && (Char <= L'9')) {
408 return (Char - L'0');
409 }
410
411 if ((Char >= L'A') && (Char <= L'F')) {
412 return (Char - L'A' + 0xA);
413 }
414
415 return (UINTN) -1;
416 }
417
418 /**
419 Dispatch the deferred images that are returned from all DeferredImageLoad instances.
420
421 @retval EFI_SUCCESS At least one deferred image is loaded successfully and started.
422 @retval EFI_NOT_FOUND There is no deferred image.
423 @retval EFI_ACCESS_DENIED There are deferred images but all of them are failed to load.
424 **/
425 EFI_STATUS
426 EFIAPI
427 EfiBootManagerDispatchDeferredImages (
428 VOID
429 )
430 {
431 EFI_STATUS Status;
432 EFI_DEFERRED_IMAGE_LOAD_PROTOCOL *DeferredImage;
433 UINTN HandleCount;
434 EFI_HANDLE *Handles;
435 UINTN Index;
436 UINTN ImageIndex;
437 EFI_DEVICE_PATH_PROTOCOL *ImageDevicePath;
438 VOID *Image;
439 UINTN ImageSize;
440 BOOLEAN BootOption;
441 EFI_HANDLE ImageHandle;
442 UINTN ExitDataSize;
443 CHAR16 *ExitData;
444 UINTN ImageCount;
445 UINTN LoadCount;
446
447 //
448 // Find all the deferred image load protocols.
449 //
450 HandleCount = 0;
451 Handles = NULL;
452 Status = gBS->LocateHandleBuffer (
453 ByProtocol,
454 &gEfiDeferredImageLoadProtocolGuid,
455 NULL,
456 &HandleCount,
457 &Handles
458 );
459 if (EFI_ERROR (Status)) {
460 return EFI_NOT_FOUND;
461 }
462
463 ImageCount = 0;
464 LoadCount = 0;
465 for (Index = 0; Index < HandleCount; Index++) {
466 Status = gBS->HandleProtocol (Handles[Index], &gEfiDeferredImageLoadProtocolGuid, (VOID **) &DeferredImage);
467 if (EFI_ERROR (Status)) {
468 continue;
469 }
470
471 for (ImageIndex = 0; ;ImageIndex++) {
472 //
473 // Load all the deferred images in this protocol instance.
474 //
475 Status = DeferredImage->GetImageInfo (
476 DeferredImage,
477 ImageIndex,
478 &ImageDevicePath,
479 (VOID **) &Image,
480 &ImageSize,
481 &BootOption
482 );
483 if (EFI_ERROR (Status)) {
484 break;
485 }
486 ImageCount++;
487 //
488 // Load and start the image.
489 //
490 Status = gBS->LoadImage (
491 BootOption,
492 gImageHandle,
493 ImageDevicePath,
494 NULL,
495 0,
496 &ImageHandle
497 );
498 if (!EFI_ERROR (Status)) {
499 LoadCount++;
500 //
501 // Before calling the image, enable the Watchdog Timer for
502 // a 5 Minute period
503 //
504 gBS->SetWatchdogTimer (5 * 60, 0x0000, 0x00, NULL);
505 Status = gBS->StartImage (ImageHandle, &ExitDataSize, &ExitData);
506 if (ExitData != NULL) {
507 FreePool (ExitData);
508 }
509
510 //
511 // Clear the Watchdog Timer after the image returns.
512 //
513 gBS->SetWatchdogTimer (0x0000, 0x0000, 0x0000, NULL);
514 }
515 }
516 }
517 if (Handles != NULL) {
518 FreePool (Handles);
519 }
520
521 if (ImageCount == 0) {
522 return EFI_NOT_FOUND;
523 } else {
524 if (LoadCount == 0) {
525 return EFI_ACCESS_DENIED;
526 } else {
527 return EFI_SUCCESS;
528 }
529 }
530 }