]> git.proxmox.com Git - mirror_edk2.git/blob - ArmPkg/Library/BdsLib/BdsLinuxFdt.c
43daf5dd2a277d471558e290c663d0cc41702698
[mirror_edk2.git] / ArmPkg / Library / BdsLib / BdsLinuxFdt.c
1 /** @file
2 *
3 * Copyright (c) 2011-2013, ARM Limited. All rights reserved.
4 *
5 * This program and the accompanying materials
6 * are licensed and made available under the terms and conditions of the BSD License
7 * which accompanies this distribution. The full text of the license may be found at
8 * http://opensource.org/licenses/bsd-license.php
9 *
10 * THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
12 *
13 **/
14
15 #include <Library/ArmSmcLib.h>
16 #include <Library/PcdLib.h>
17 #include <libfdt.h>
18
19 #include <IndustryStandard/ArmSmc.h>
20
21 #include "BdsInternal.h"
22 #include "BdsLinuxLoader.h"
23
24 #define ALIGN(x, a) (((x) + ((a) - 1)) & ~((a) - 1))
25 #define PALIGN(p, a) ((void *)(ALIGN((unsigned long)(p), (a))))
26 #define GET_CELL(p) (p += 4, *((const UINT32 *)(p-4)))
27
28 STATIC
29 UINTN
30 IsPrintableString (
31 IN CONST VOID* data,
32 IN UINTN len
33 )
34 {
35 CONST CHAR8 *s = data;
36 CONST CHAR8 *ss;
37
38 // Zero length is not
39 if (len == 0) {
40 return 0;
41 }
42
43 // Must terminate with zero
44 if (s[len - 1] != '\0') {
45 return 0;
46 }
47
48 ss = s;
49 while (*s/* && isprint(*s)*/) {
50 s++;
51 }
52
53 // Not zero, or not done yet
54 if (*s != '\0' || (s + 1 - ss) < len) {
55 return 0;
56 }
57
58 return 1;
59 }
60
61 STATIC
62 VOID
63 PrintData (
64 IN CONST CHAR8* data,
65 IN UINTN len
66 )
67 {
68 UINTN i;
69 CONST CHAR8 *p = data;
70
71 // No data, don't print
72 if (len == 0)
73 return;
74
75 if (IsPrintableString (data, len)) {
76 Print(L" = \"%a\"", (const char *)data);
77 } else if ((len % 4) == 0) {
78 Print(L" = <");
79 for (i = 0; i < len; i += 4) {
80 Print(L"0x%08x%a", fdt32_to_cpu(GET_CELL(p)),i < (len - 4) ? " " : "");
81 }
82 Print(L">");
83 } else {
84 Print(L" = [");
85 for (i = 0; i < len; i++)
86 Print(L"%02x%a", *p++, i < len - 1 ? " " : "");
87 Print(L"]");
88 }
89 }
90
91 VOID
92 DebugDumpFdt (
93 IN VOID* FdtBlob
94 )
95 {
96 struct fdt_header *bph;
97 UINT32 off_dt;
98 UINT32 off_str;
99 CONST CHAR8* p_struct;
100 CONST CHAR8* p_strings;
101 CONST CHAR8* p;
102 CONST CHAR8* s;
103 CONST CHAR8* t;
104 UINT32 tag;
105 UINTN sz;
106 UINTN depth;
107 UINTN shift;
108 UINT32 version;
109
110 {
111 // Can 'memreserve' be printed by below code?
112 INTN num = fdt_num_mem_rsv(FdtBlob);
113 INTN i, err;
114 UINT64 addr = 0,size = 0;
115
116 for (i = 0; i < num; i++) {
117 err = fdt_get_mem_rsv(FdtBlob, i, &addr, &size);
118 if (err) {
119 DEBUG((EFI_D_ERROR, "Error (%d) : Cannot get memreserve section (%d)\n", err, i));
120 }
121 else {
122 Print(L"/memreserve/ \t0x%lx \t0x%lx;\n",addr,size);
123 }
124 }
125 }
126
127 depth = 0;
128 shift = 4;
129
130 bph = FdtBlob;
131 off_dt = fdt32_to_cpu(bph->off_dt_struct);
132 off_str = fdt32_to_cpu(bph->off_dt_strings);
133 p_struct = (CONST CHAR8*)FdtBlob + off_dt;
134 p_strings = (CONST CHAR8*)FdtBlob + off_str;
135 version = fdt32_to_cpu(bph->version);
136
137 p = p_struct;
138 while ((tag = fdt32_to_cpu(GET_CELL(p))) != FDT_END) {
139 if (tag == FDT_BEGIN_NODE) {
140 s = p;
141 p = PALIGN(p + AsciiStrLen (s) + 1, 4);
142
143 if (*s == '\0')
144 s = "/";
145
146 Print(L"%*s%a {\n", depth * shift, L" ", s);
147
148 depth++;
149 continue;
150 }
151
152 if (tag == FDT_END_NODE) {
153 depth--;
154
155 Print(L"%*s};\n", depth * shift, L" ");
156 continue;
157 }
158
159 if (tag == FDT_NOP) {
160 Print(L"%*s// [NOP]\n", depth * shift, L" ");
161 continue;
162 }
163
164 if (tag != FDT_PROP) {
165 Print(L"%*s ** Unknown tag 0x%08x\n", depth * shift, L" ", tag);
166 break;
167 }
168 sz = fdt32_to_cpu(GET_CELL(p));
169 s = p_strings + fdt32_to_cpu(GET_CELL(p));
170 if (version < 16 && sz >= 8)
171 p = PALIGN(p, 8);
172 t = p;
173
174 p = PALIGN(p + sz, 4);
175
176 Print(L"%*s%a", depth * shift, L" ", s);
177 PrintData(t, sz);
178 Print(L";\n");
179 }
180 }
181
182 STATIC
183 BOOLEAN
184 IsLinuxReservedRegion (
185 IN EFI_MEMORY_TYPE MemoryType
186 )
187 {
188 switch(MemoryType) {
189 case EfiRuntimeServicesCode:
190 case EfiRuntimeServicesData:
191 case EfiUnusableMemory:
192 case EfiACPIReclaimMemory:
193 case EfiACPIMemoryNVS:
194 return TRUE;
195 default:
196 return FALSE;
197 }
198 }
199
200
201 typedef struct {
202 UINTN Base;
203 UINTN Size;
204 } FdtRegion;
205
206 EFI_STATUS
207 PrepareFdt (
208 IN CONST CHAR8* CommandLineArguments,
209 IN EFI_PHYSICAL_ADDRESS InitrdImage,
210 IN UINTN InitrdImageSize,
211 IN OUT EFI_PHYSICAL_ADDRESS *FdtBlobBase,
212 IN OUT UINTN *FdtBlobSize
213 )
214 {
215 EFI_STATUS Status;
216 EFI_PHYSICAL_ADDRESS NewFdtBlobBase;
217 EFI_PHYSICAL_ADDRESS NewFdtBlobAllocation;
218 UINTN NewFdtBlobSize;
219 UINT32 FdtAlignment;
220 VOID* fdt;
221 INTN err;
222 INTN node;
223 INTN cpu_node;
224 INTN lenp;
225 CONST VOID* BootArg;
226 CONST VOID* Method;
227 EFI_PHYSICAL_ADDRESS InitrdImageStart;
228 EFI_PHYSICAL_ADDRESS InitrdImageEnd;
229 FdtRegion Region;
230 UINTN Index;
231 CHAR8 Name[10];
232 LIST_ENTRY ResourceList;
233 BDS_SYSTEM_MEMORY_RESOURCE *Resource;
234 ARM_PROCESSOR_TABLE *ArmProcessorTable;
235 ARM_CORE_INFO *ArmCoreInfoTable;
236 UINT32 MpId;
237 UINT32 ClusterId;
238 UINT32 CoreId;
239 UINT64 CpuReleaseAddr;
240 UINTN MemoryMapSize;
241 EFI_MEMORY_DESCRIPTOR *MemoryMap;
242 UINTN MapKey;
243 UINTN DescriptorSize;
244 UINT32 DescriptorVersion;
245 UINTN Pages;
246 BOOLEAN PsciSmcSupported;
247 UINTN Rx;
248 UINTN OriginalFdtSize;
249 BOOLEAN CpusNodeExist;
250
251 //
252 // Ensure the Power State Coordination Interface (PSCI) SMCs are there if supported
253 //
254 PsciSmcSupported = FALSE;
255 if (FeaturePcdGet (PcdArmPsciSupport) == TRUE) {
256 // Check the SMC response to the Presence SMC
257 Rx = ARM_SMC_ID_PRESENCE;
258 ArmCallSmc (&Rx);
259 if (Rx == 1) {
260 // Check the SMC UID
261 Rx = ARM_SMC_ID_UID;
262 ArmCallSmc (&Rx);
263 if (Rx == ARM_TRUSTZONE_UID_4LETTERID) {
264 Rx = ARM_SMC_ID_UID + 1;
265 ArmCallSmc (&Rx);
266 if (Rx == ARM_TRUSTZONE_ARM_UID) {
267 PsciSmcSupported = TRUE;
268 }
269 }
270 if (PsciSmcSupported == FALSE) {
271 DEBUG((EFI_D_ERROR,"Warning: The Power State Coordination Interface (PSCI) is not supported"
272 "by your platform Trusted Firmware.\n"));
273 }
274 }
275 }
276
277 //
278 // Sanity checks on the original FDT blob.
279 //
280 err = fdt_check_header ((VOID*)(UINTN)(*FdtBlobBase));
281 if (err != 0) {
282 Print (L"ERROR: Device Tree header not valid (err:%d)\n", err);
283 return EFI_INVALID_PARAMETER;
284 }
285
286 // The original FDT blob might have been loaded partially.
287 // Check that it is not the case.
288 OriginalFdtSize = (UINTN)fdt_totalsize ((VOID*)(UINTN)(*FdtBlobBase));
289 if (OriginalFdtSize > *FdtBlobSize) {
290 Print (L"ERROR: Incomplete FDT. Only %d/%d bytes have been loaded.\n",
291 *FdtBlobSize, OriginalFdtSize);
292 return EFI_INVALID_PARAMETER;
293 }
294
295 //
296 // Allocate memory for the new FDT
297 //
298 NewFdtBlobSize = OriginalFdtSize + FDT_ADDITIONAL_ENTRIES_SIZE;
299
300 // If FDT load address needs to be aligned, allocate more space.
301 FdtAlignment = PcdGet32 (PcdArmLinuxFdtAlignment);
302 if (FdtAlignment != 0) {
303 NewFdtBlobSize += FdtAlignment;
304 }
305
306 // Try below a watermark address
307 Status = EFI_NOT_FOUND;
308 if (PcdGet32 (PcdArmLinuxFdtMaxOffset) != 0) {
309 NewFdtBlobBase = LINUX_FDT_MAX_OFFSET;
310 Status = gBS->AllocatePages (AllocateMaxAddress, EfiBootServicesData, EFI_SIZE_TO_PAGES(NewFdtBlobSize), &NewFdtBlobBase);
311 if (EFI_ERROR(Status)) {
312 DEBUG ((EFI_D_WARN, "Warning: Failed to load FDT below address 0x%lX (%r). Will try again at a random address anywhere.\n", NewFdtBlobBase, Status));
313 }
314 }
315
316 // Try anywhere there is available space
317 if (EFI_ERROR(Status)) {
318 Status = gBS->AllocatePages (AllocateAnyPages, EfiBootServicesData, EFI_SIZE_TO_PAGES(NewFdtBlobSize), &NewFdtBlobBase);
319 if (EFI_ERROR(Status)) {
320 ASSERT_EFI_ERROR(Status);
321 goto FAIL_ALLOCATE_NEW_FDT;
322 } else {
323 DEBUG ((EFI_D_WARN, "WARNING: Loaded FDT at random address 0x%lX.\nWARNING: There is a risk of accidental overwriting by other code/data.\n", NewFdtBlobBase));
324 }
325 }
326
327 NewFdtBlobAllocation = NewFdtBlobBase;
328 if (FdtAlignment != 0) {
329 NewFdtBlobBase = ALIGN (NewFdtBlobBase, FdtAlignment);
330 }
331
332 // Load the Original FDT tree into the new region
333 fdt = (VOID*)(UINTN)NewFdtBlobBase;
334 err = fdt_open_into((VOID*)(UINTN)(*FdtBlobBase), fdt, NewFdtBlobSize);
335 if (err) {
336 DEBUG((EFI_D_ERROR, "fdt_open_into(): %a\n", fdt_strerror(err)));
337 Status = EFI_INVALID_PARAMETER;
338 goto FAIL_NEW_FDT;
339 }
340
341 DEBUG_CODE_BEGIN();
342 //DebugDumpFdt (fdt);
343 DEBUG_CODE_END();
344
345 node = fdt_subnode_offset(fdt, 0, "chosen");
346 if (node < 0) {
347 // The 'chosen' node does not exist, create it
348 node = fdt_add_subnode(fdt, 0, "chosen");
349 if (node < 0) {
350 DEBUG((EFI_D_ERROR,"Error on finding 'chosen' node\n"));
351 Status = EFI_INVALID_PARAMETER;
352 goto FAIL_NEW_FDT;
353 }
354 }
355
356 DEBUG_CODE_BEGIN();
357 BootArg = fdt_getprop(fdt, node, "bootargs", &lenp);
358 if (BootArg != NULL) {
359 DEBUG((EFI_D_ERROR,"BootArg: %a\n",BootArg));
360 }
361 DEBUG_CODE_END();
362
363 //
364 // Set Linux CmdLine
365 //
366 if ((CommandLineArguments != NULL) && (AsciiStrLen (CommandLineArguments) > 0)) {
367 err = fdt_setprop(fdt, node, "bootargs", CommandLineArguments, AsciiStrSize(CommandLineArguments));
368 if (err) {
369 DEBUG((EFI_D_ERROR,"Fail to set new 'bootarg' (err:%d)\n",err));
370 }
371 }
372
373 //
374 // Set Linux Initrd
375 //
376 if (InitrdImageSize != 0) {
377 InitrdImageStart = cpu_to_fdt64 (InitrdImage);
378 err = fdt_setprop(fdt, node, "linux,initrd-start", &InitrdImageStart, sizeof(EFI_PHYSICAL_ADDRESS));
379 if (err) {
380 DEBUG((EFI_D_ERROR,"Fail to set new 'linux,initrd-start' (err:%d)\n",err));
381 }
382 InitrdImageEnd = cpu_to_fdt64 (InitrdImage + InitrdImageSize);
383 err = fdt_setprop(fdt, node, "linux,initrd-end", &InitrdImageEnd, sizeof(EFI_PHYSICAL_ADDRESS));
384 if (err) {
385 DEBUG((EFI_D_ERROR,"Fail to set new 'linux,initrd-start' (err:%d)\n",err));
386 }
387 }
388
389 //
390 // Set Physical memory setup if does not exist
391 //
392 node = fdt_subnode_offset(fdt, 0, "memory");
393 if (node < 0) {
394 // The 'memory' node does not exist, create it
395 node = fdt_add_subnode(fdt, 0, "memory");
396 if (node >= 0) {
397 fdt_setprop_string(fdt, node, "name", "memory");
398 fdt_setprop_string(fdt, node, "device_type", "memory");
399
400 GetSystemMemoryResources (&ResourceList);
401 Resource = (BDS_SYSTEM_MEMORY_RESOURCE*)ResourceList.ForwardLink;
402
403 if (sizeof(UINTN) == sizeof(UINT32)) {
404 Region.Base = cpu_to_fdt32((UINTN)Resource->PhysicalStart);
405 Region.Size = cpu_to_fdt32((UINTN)Resource->ResourceLength);
406 } else {
407 Region.Base = cpu_to_fdt64((UINTN)Resource->PhysicalStart);
408 Region.Size = cpu_to_fdt64((UINTN)Resource->ResourceLength);
409 }
410
411 err = fdt_setprop(fdt, node, "reg", &Region, sizeof(Region));
412 if (err) {
413 DEBUG((EFI_D_ERROR,"Fail to set new 'memory region' (err:%d)\n",err));
414 }
415 }
416 }
417
418 //
419 // Add the memory regions reserved by the UEFI Firmware
420 //
421
422 // Retrieve the UEFI Memory Map
423 MemoryMap = NULL;
424 MemoryMapSize = 0;
425 Status = gBS->GetMemoryMap (&MemoryMapSize, MemoryMap, &MapKey, &DescriptorSize, &DescriptorVersion);
426 if (Status == EFI_BUFFER_TOO_SMALL) {
427 Pages = EFI_SIZE_TO_PAGES (MemoryMapSize) + 1;
428 MemoryMap = AllocatePages (Pages);
429 Status = gBS->GetMemoryMap (&MemoryMapSize, MemoryMap, &MapKey, &DescriptorSize, &DescriptorVersion);
430 }
431
432 // Go through the list and add the reserved region to the Device Tree
433 if (!EFI_ERROR(Status)) {
434 for (Index = 0; Index < (MemoryMapSize / sizeof(EFI_MEMORY_DESCRIPTOR)); Index++) {
435 if (IsLinuxReservedRegion ((EFI_MEMORY_TYPE)MemoryMap[Index].Type)) {
436 DEBUG((DEBUG_VERBOSE, "Reserved region of type %d [0x%X, 0x%X]\n",
437 MemoryMap[Index].Type,
438 (UINTN)MemoryMap[Index].PhysicalStart,
439 (UINTN)(MemoryMap[Index].PhysicalStart + MemoryMap[Index].NumberOfPages * EFI_PAGE_SIZE)));
440 err = fdt_add_mem_rsv(fdt, MemoryMap[Index].PhysicalStart, MemoryMap[Index].NumberOfPages * EFI_PAGE_SIZE);
441 if (err != 0) {
442 Print(L"Warning: Fail to add 'memreserve' (err:%d)\n", err);
443 }
444 }
445 }
446 }
447
448 //
449 // Setup Arm Mpcore Info if it is a multi-core or multi-cluster platforms
450 //
451 for (Index=0; Index < gST->NumberOfTableEntries; Index++) {
452 // Check for correct GUID type
453 if (CompareGuid (&gArmMpCoreInfoGuid, &(gST->ConfigurationTable[Index].VendorGuid))) {
454 MpId = ArmReadMpidr ();
455 ClusterId = GET_CLUSTER_ID(MpId);
456 CoreId = GET_CORE_ID(MpId);
457
458 node = fdt_subnode_offset(fdt, 0, "cpus");
459 if (node < 0) {
460 // Create the /cpus node
461 node = fdt_add_subnode(fdt, 0, "cpus");
462 fdt_setprop_string(fdt, node, "name", "cpus");
463 fdt_setprop_cell(fdt, node, "#address-cells", 1);
464 fdt_setprop_cell(fdt, node, "#size-cells", 0);
465 CpusNodeExist = FALSE;
466 } else {
467 CpusNodeExist = TRUE;
468 }
469
470 // Get pointer to ARM processor table
471 ArmProcessorTable = (ARM_PROCESSOR_TABLE *)gST->ConfigurationTable[Index].VendorTable;
472 ArmCoreInfoTable = ArmProcessorTable->ArmCpus;
473
474 for (Index = 0; Index < ArmProcessorTable->NumberOfEntries; Index++) {
475 AsciiSPrint (Name, 10, "cpu@%d", Index);
476
477 // If the 'cpus' node did not exist then creates the 'cpu' nodes. In case 'cpus' node
478 // is provided in the original FDT then we do not add any 'cpu' node.
479 if (!CpusNodeExist) {
480 cpu_node = fdt_add_subnode(fdt, node, Name);
481 fdt_setprop_string(fdt, cpu_node, "device-type", "cpu");
482 fdt_setprop(fdt, cpu_node, "reg", &Index, sizeof(Index));
483 } else {
484 cpu_node = fdt_subnode_offset(fdt, node, Name);
485 }
486
487 // If Power State Coordination Interface (PSCI) is not supported then it is expected the secondary
488 // cores are spinning waiting for the Operating System to release them
489 if ((PsciSmcSupported == FALSE) && (cpu_node >= 0)) {
490 // We as the bootloader are responsible for either creating or updating
491 // these entries. Do not trust the entries in the DT. We only know about
492 // 'spin-table' type. Do not try to update other types if defined.
493 Method = fdt_getprop(fdt, cpu_node, "enable-method", &lenp);
494 if ( (Method == NULL) || (!AsciiStrCmp((CHAR8 *)Method, "spin-table")) ) {
495 fdt_setprop_string(fdt, cpu_node, "enable-method", "spin-table");
496 CpuReleaseAddr = cpu_to_fdt64(ArmCoreInfoTable[Index].MailboxSetAddress);
497 fdt_setprop(fdt, cpu_node, "cpu-release-addr", &CpuReleaseAddr, sizeof(CpuReleaseAddr));
498
499 // If it is not the primary core than the cpu should be disabled
500 if (((ArmCoreInfoTable[Index].ClusterId != ClusterId) || (ArmCoreInfoTable[Index].CoreId != CoreId))) {
501 fdt_setprop_string(fdt, cpu_node, "status", "disabled");
502 }
503 } else {
504 Print(L"Warning: Unsupported enable-method type for CPU[%d] : %a\n", Index, (CHAR8 *)Method);
505 }
506 }
507 }
508 break;
509 }
510 }
511
512 // If the Power State Coordination Interface is supported then we signal it in the Device Tree
513 if (PsciSmcSupported == TRUE) {
514 // Before to create it we check if the node is not already defined in the Device Tree
515 node = fdt_subnode_offset(fdt, 0, "psci");
516 if (node < 0) {
517 // The 'psci' node does not exist, create it
518 node = fdt_add_subnode(fdt, 0, "psci");
519 if (node < 0) {
520 DEBUG((EFI_D_ERROR,"Error on creating 'psci' node\n"));
521 Status = EFI_INVALID_PARAMETER;
522 goto FAIL_NEW_FDT;
523 } else {
524 fdt_setprop_string(fdt, node, "compatible", "arm,psci");
525 fdt_setprop_string(fdt, node, "method", "smc");
526 fdt_setprop_cell(fdt, node, "cpu_suspend", ARM_SMC_ARM_CPU_SUSPEND);
527 fdt_setprop_cell(fdt, node, "cpu_off", ARM_SMC_ARM_CPU_OFF);
528 fdt_setprop_cell(fdt, node, "cpu_on", ARM_SMC_ARM_CPU_ON);
529 fdt_setprop_cell(fdt, node, "cpu_migrate", ARM_SMC_ARM_MIGRATE);
530 }
531 }
532 }
533
534 DEBUG_CODE_BEGIN();
535 //DebugDumpFdt (fdt);
536 DEBUG_CODE_END();
537
538 // If we succeeded to generate the new Device Tree then free the old Device Tree
539 gBS->FreePages (*FdtBlobBase, EFI_SIZE_TO_PAGES (*FdtBlobSize));
540
541 *FdtBlobBase = NewFdtBlobBase;
542 *FdtBlobSize = (UINTN)fdt_totalsize ((VOID*)(UINTN)(NewFdtBlobBase));
543 return EFI_SUCCESS;
544
545 FAIL_NEW_FDT:
546 gBS->FreePages (NewFdtBlobAllocation, EFI_SIZE_TO_PAGES (NewFdtBlobSize));
547
548 FAIL_ALLOCATE_NEW_FDT:
549 *FdtBlobSize = (UINTN)fdt_totalsize ((VOID*)(UINTN)(*FdtBlobBase));
550 // Return success even if we failed to update the FDT blob. The original one is still valid.
551 return EFI_SUCCESS;
552 }
553
554