imx8m: config: convert to bootm_size
[platform/kernel/u-boot.git] / lib / efi_loader / efi_runtime.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  *  EFI application runtime services
4  *
5  *  Copyright (c) 2016 Alexander Graf
6  */
7
8 #include <common.h>
9 #include <command.h>
10 #include <cpu_func.h>
11 #include <dm.h>
12 #include <elf.h>
13 #include <efi_loader.h>
14 #include <log.h>
15 #include <malloc.h>
16 #include <rtc.h>
17 #include <u-boot/crc.h>
18
19 /* For manual relocation support */
20 DECLARE_GLOBAL_DATA_PTR;
21
22 /* GUID of the runtime properties table */
23 static const efi_guid_t efi_rt_properties_table_guid =
24                                 EFI_RT_PROPERTIES_TABLE_GUID;
25
26 struct efi_runtime_mmio_list {
27         struct list_head link;
28         void **ptr;
29         u64 paddr;
30         u64 len;
31 };
32
33 /* This list contains all runtime available mmio regions */
34 LIST_HEAD(efi_runtime_mmio);
35
36 static efi_status_t __efi_runtime EFIAPI efi_unimplemented(void);
37
38 /*
39  * TODO(sjg@chromium.org): These defines and structures should come from the ELF
40  * header for each architecture (or a generic header) rather than being repeated
41  * here.
42  */
43 #if defined(__aarch64__)
44 #define R_RELATIVE      R_AARCH64_RELATIVE
45 #define R_MASK          0xffffffffULL
46 #define IS_RELA         1
47 #elif defined(__arm__)
48 #define R_RELATIVE      R_ARM_RELATIVE
49 #define R_MASK          0xffULL
50 #elif defined(__i386__)
51 #define R_RELATIVE      R_386_RELATIVE
52 #define R_MASK          0xffULL
53 #elif defined(__x86_64__)
54 #define R_RELATIVE      R_X86_64_RELATIVE
55 #define R_MASK          0xffffffffULL
56 #define IS_RELA         1
57 #elif defined(__riscv)
58 #define R_RELATIVE      R_RISCV_RELATIVE
59 #define R_MASK          0xffULL
60 #define IS_RELA         1
61
62 struct dyn_sym {
63         ulong foo1;
64         ulong addr;
65         u32 foo2;
66         u32 foo3;
67 };
68 #if (__riscv_xlen == 32)
69 #define R_ABSOLUTE      R_RISCV_32
70 #define SYM_INDEX       8
71 #elif (__riscv_xlen == 64)
72 #define R_ABSOLUTE      R_RISCV_64
73 #define SYM_INDEX       32
74 #else
75 #error unknown riscv target
76 #endif
77 #else
78 #error Need to add relocation awareness
79 #endif
80
81 struct elf_rel {
82         ulong *offset;
83         ulong info;
84 };
85
86 struct elf_rela {
87         ulong *offset;
88         ulong info;
89         long addend;
90 };
91
92 static __efi_runtime_data struct efi_mem_desc *efi_virtmap;
93 static __efi_runtime_data efi_uintn_t efi_descriptor_count;
94 static __efi_runtime_data efi_uintn_t efi_descriptor_size;
95
96 /*
97  * EFI runtime code lives in two stages. In the first stage, U-Boot and an EFI
98  * payload are running concurrently at the same time. In this mode, we can
99  * handle a good number of runtime callbacks
100  */
101
102 /**
103  * efi_init_runtime_supported() - create runtime properties table
104  *
105  * Create a configuration table specifying which services are available at
106  * runtime.
107  *
108  * Return:      status code
109  */
110 efi_status_t efi_init_runtime_supported(void)
111 {
112         efi_status_t ret;
113         struct efi_rt_properties_table *rt_table;
114
115         ret = efi_allocate_pool(EFI_RUNTIME_SERVICES_DATA,
116                                 sizeof(struct efi_rt_properties_table),
117                                 (void **)&rt_table);
118         if (ret != EFI_SUCCESS)
119                 return ret;
120
121         rt_table->version = EFI_RT_PROPERTIES_TABLE_VERSION;
122         rt_table->length = sizeof(struct efi_rt_properties_table);
123         rt_table->runtime_services_supported =
124                                 EFI_RT_SUPPORTED_GET_VARIABLE |
125                                 EFI_RT_SUPPORTED_GET_NEXT_VARIABLE_NAME |
126                                 EFI_RT_SUPPORTED_SET_VIRTUAL_ADDRESS_MAP |
127                                 EFI_RT_SUPPORTED_CONVERT_POINTER;
128
129         /*
130          * This value must be synced with efi_runtime_detach_list
131          * as well as efi_runtime_services.
132          */
133 #ifdef CONFIG_EFI_HAVE_RUNTIME_RESET
134         rt_table->runtime_services_supported |= EFI_RT_SUPPORTED_RESET_SYSTEM;
135 #endif
136
137         ret = efi_install_configuration_table(&efi_rt_properties_table_guid,
138                                               rt_table);
139         return ret;
140 }
141
142 /**
143  * efi_memcpy_runtime() - copy memory area
144  *
145  * At runtime memcpy() is not available.
146  *
147  * Overlapping memory areas can be copied safely if src >= dest.
148  *
149  * @dest:       destination buffer
150  * @src:        source buffer
151  * @n:          number of bytes to copy
152  * Return:      pointer to destination buffer
153  */
154 void __efi_runtime efi_memcpy_runtime(void *dest, const void *src, size_t n)
155 {
156         u8 *d = dest;
157         const u8 *s = src;
158
159         for (; n; --n)
160                 *d++ = *s++;
161 }
162
163 /**
164  * efi_update_table_header_crc32() - Update crc32 in table header
165  *
166  * @table:      EFI table
167  */
168 void __efi_runtime efi_update_table_header_crc32(struct efi_table_hdr *table)
169 {
170         table->crc32 = 0;
171         table->crc32 = crc32(0, (const unsigned char *)table,
172                              table->headersize);
173 }
174
175 /**
176  * efi_reset_system_boottime() - reset system at boot time
177  *
178  * This function implements the ResetSystem() runtime service before
179  * SetVirtualAddressMap() is called.
180  *
181  * See the Unified Extensible Firmware Interface (UEFI) specification for
182  * details.
183  *
184  * @reset_type:         type of reset to perform
185  * @reset_status:       status code for the reset
186  * @data_size:          size of reset_data
187  * @reset_data:         information about the reset
188  */
189 static void EFIAPI efi_reset_system_boottime(
190                         enum efi_reset_type reset_type,
191                         efi_status_t reset_status,
192                         unsigned long data_size, void *reset_data)
193 {
194         struct efi_event *evt;
195
196         EFI_ENTRY("%d %lx %lx %p", reset_type, reset_status, data_size,
197                   reset_data);
198
199         /* Notify reset */
200         list_for_each_entry(evt, &efi_events, link) {
201                 if (evt->group &&
202                     !guidcmp(evt->group,
203                              &efi_guid_event_group_reset_system)) {
204                         efi_signal_event(evt);
205                         break;
206                 }
207         }
208         switch (reset_type) {
209         case EFI_RESET_COLD:
210         case EFI_RESET_WARM:
211         case EFI_RESET_PLATFORM_SPECIFIC:
212                 do_reset(NULL, 0, 0, NULL);
213                 break;
214         case EFI_RESET_SHUTDOWN:
215 #ifdef CONFIG_CMD_POWEROFF
216                 do_poweroff(NULL, 0, 0, NULL);
217 #endif
218                 break;
219         }
220
221         while (1) { }
222 }
223
224 /**
225  * efi_get_time_boottime() - get current time at boot time
226  *
227  * This function implements the GetTime runtime service before
228  * SetVirtualAddressMap() is called.
229  *
230  * See the Unified Extensible Firmware Interface (UEFI) specification
231  * for details.
232  *
233  * @time:               pointer to structure to receive current time
234  * @capabilities:       pointer to structure to receive RTC properties
235  * Returns:             status code
236  */
237 static efi_status_t EFIAPI efi_get_time_boottime(
238                         struct efi_time *time,
239                         struct efi_time_cap *capabilities)
240 {
241 #ifdef CONFIG_EFI_GET_TIME
242         efi_status_t ret = EFI_SUCCESS;
243         struct rtc_time tm;
244         struct udevice *dev;
245
246         EFI_ENTRY("%p %p", time, capabilities);
247
248         if (!time) {
249                 ret = EFI_INVALID_PARAMETER;
250                 goto out;
251         }
252         if (uclass_get_device(UCLASS_RTC, 0, &dev) ||
253             dm_rtc_get(dev, &tm)) {
254                 ret = EFI_UNSUPPORTED;
255                 goto out;
256         }
257         if (dm_rtc_get(dev, &tm)) {
258                 ret = EFI_DEVICE_ERROR;
259                 goto out;
260         }
261
262         memset(time, 0, sizeof(*time));
263         time->year = tm.tm_year;
264         time->month = tm.tm_mon;
265         time->day = tm.tm_mday;
266         time->hour = tm.tm_hour;
267         time->minute = tm.tm_min;
268         time->second = tm.tm_sec;
269         if (tm.tm_isdst)
270                 time->daylight =
271                         EFI_TIME_ADJUST_DAYLIGHT | EFI_TIME_IN_DAYLIGHT;
272         time->timezone = EFI_UNSPECIFIED_TIMEZONE;
273
274         if (capabilities) {
275                 /* Set reasonable dummy values */
276                 capabilities->resolution = 1;           /* 1 Hz */
277                 capabilities->accuracy = 100000000;     /* 100 ppm */
278                 capabilities->sets_to_zero = false;
279         }
280 out:
281         return EFI_EXIT(ret);
282 #else
283         EFI_ENTRY("%p %p", time, capabilities);
284         return EFI_EXIT(EFI_UNSUPPORTED);
285 #endif
286 }
287
288 #ifdef CONFIG_EFI_SET_TIME
289
290 /**
291  * efi_validate_time() - checks if timestamp is valid
292  *
293  * @time:       timestamp to validate
294  * Returns:     0 if timestamp is valid, 1 otherwise
295  */
296 static int efi_validate_time(struct efi_time *time)
297 {
298         return (!time ||
299                 time->year < 1900 || time->year > 9999 ||
300                 !time->month || time->month > 12 || !time->day ||
301                 time->day > rtc_month_days(time->month - 1, time->year) ||
302                 time->hour > 23 || time->minute > 59 || time->second > 59 ||
303                 time->nanosecond > 999999999 ||
304                 time->daylight &
305                 ~(EFI_TIME_IN_DAYLIGHT | EFI_TIME_ADJUST_DAYLIGHT) ||
306                 ((time->timezone < -1440 || time->timezone > 1440) &&
307                 time->timezone != EFI_UNSPECIFIED_TIMEZONE));
308 }
309
310 #endif
311
312 /**
313  * efi_set_time_boottime() - set current time
314  *
315  * This function implements the SetTime() runtime service before
316  * SetVirtualAddressMap() is called.
317  *
318  * See the Unified Extensible Firmware Interface (UEFI) specification
319  * for details.
320  *
321  * @time:               pointer to structure to with current time
322  * Returns:             status code
323  */
324 static efi_status_t EFIAPI efi_set_time_boottime(struct efi_time *time)
325 {
326 #ifdef CONFIG_EFI_SET_TIME
327         efi_status_t ret = EFI_SUCCESS;
328         struct rtc_time tm;
329         struct udevice *dev;
330
331         EFI_ENTRY("%p", time);
332
333         if (efi_validate_time(time)) {
334                 ret = EFI_INVALID_PARAMETER;
335                 goto out;
336         }
337
338         if (uclass_get_device(UCLASS_RTC, 0, &dev)) {
339                 ret = EFI_UNSUPPORTED;
340                 goto out;
341         }
342
343         memset(&tm, 0, sizeof(tm));
344         tm.tm_year = time->year;
345         tm.tm_mon = time->month;
346         tm.tm_mday = time->day;
347         tm.tm_hour = time->hour;
348         tm.tm_min = time->minute;
349         tm.tm_sec = time->second;
350         tm.tm_isdst = time->daylight ==
351                       (EFI_TIME_ADJUST_DAYLIGHT | EFI_TIME_IN_DAYLIGHT);
352         /* Calculate day of week */
353         rtc_calc_weekday(&tm);
354
355         if (dm_rtc_set(dev, &tm))
356                 ret = EFI_DEVICE_ERROR;
357 out:
358         return EFI_EXIT(ret);
359 #else
360         EFI_ENTRY("%p", time);
361         return EFI_EXIT(EFI_UNSUPPORTED);
362 #endif
363 }
364 /**
365  * efi_reset_system() - reset system
366  *
367  * This function implements the ResetSystem() runtime service after
368  * SetVirtualAddressMap() is called. It only executes an endless loop.
369  * Boards may override the helpers below to implement reset functionality.
370  *
371  * See the Unified Extensible Firmware Interface (UEFI) specification for
372  * details.
373  *
374  * @reset_type:         type of reset to perform
375  * @reset_status:       status code for the reset
376  * @data_size:          size of reset_data
377  * @reset_data:         information about the reset
378  */
379 void __weak __efi_runtime EFIAPI efi_reset_system(
380                         enum efi_reset_type reset_type,
381                         efi_status_t reset_status,
382                         unsigned long data_size, void *reset_data)
383 {
384         /* Nothing we can do */
385         while (1) { }
386 }
387
388 /**
389  * efi_reset_system_init() - initialize the reset driver
390  *
391  * Boards may override this function to initialize the reset driver.
392  */
393 efi_status_t __weak efi_reset_system_init(void)
394 {
395         return EFI_SUCCESS;
396 }
397
398 /**
399  * efi_get_time() - get current time
400  *
401  * This function implements the GetTime runtime service after
402  * SetVirtualAddressMap() is called. As the U-Boot driver are not available
403  * anymore only an error code is returned.
404  *
405  * See the Unified Extensible Firmware Interface (UEFI) specification
406  * for details.
407  *
408  * @time:               pointer to structure to receive current time
409  * @capabilities:       pointer to structure to receive RTC properties
410  * Returns:             status code
411  */
412 efi_status_t __weak __efi_runtime EFIAPI efi_get_time(
413                         struct efi_time *time,
414                         struct efi_time_cap *capabilities)
415 {
416         return EFI_UNSUPPORTED;
417 }
418
419 /**
420  * efi_set_time() - set current time
421  *
422  * This function implements the SetTime runtime service after
423  * SetVirtualAddressMap() is called. As the U-Boot driver are not available
424  * anymore only an error code is returned.
425  *
426  * See the Unified Extensible Firmware Interface (UEFI) specification
427  * for details.
428  *
429  * @time:               pointer to structure to with current time
430  * Returns:             status code
431  */
432 efi_status_t __weak __efi_runtime EFIAPI efi_set_time(struct efi_time *time)
433 {
434         return EFI_UNSUPPORTED;
435 }
436
437 /**
438  * efi_is_runtime_service_pointer() - check if pointer points to runtime table
439  *
440  * @p:          pointer to check
441  * Return:      true if the pointer points to a service function pointer in the
442  *              runtime table
443  */
444 static bool efi_is_runtime_service_pointer(void *p)
445 {
446         return (p >= (void *)&efi_runtime_services.get_time &&
447                 p <= (void *)&efi_runtime_services.query_variable_info) ||
448                p == (void *)&efi_events.prev ||
449                p == (void *)&efi_events.next;
450 }
451
452 /**
453  * efi_runtime_detach() - detach unimplemented runtime functions
454  */
455 void efi_runtime_detach(void)
456 {
457         efi_runtime_services.reset_system = efi_reset_system;
458         efi_runtime_services.get_time = efi_get_time;
459         efi_runtime_services.set_time = efi_set_time;
460
461         /* Update CRC32 */
462         efi_update_table_header_crc32(&efi_runtime_services.hdr);
463 }
464
465 /**
466  * efi_set_virtual_address_map_runtime() - change from physical to virtual
467  *                                         mapping
468  *
469  * This function implements the SetVirtualAddressMap() runtime service after
470  * it is first called.
471  *
472  * See the Unified Extensible Firmware Interface (UEFI) specification for
473  * details.
474  *
475  * @memory_map_size:    size of the virtual map
476  * @descriptor_size:    size of an entry in the map
477  * @descriptor_version: version of the map entries
478  * @virtmap:            virtual address mapping information
479  * Return:              status code EFI_UNSUPPORTED
480  */
481 static __efi_runtime efi_status_t EFIAPI efi_set_virtual_address_map_runtime(
482                         efi_uintn_t memory_map_size,
483                         efi_uintn_t descriptor_size,
484                         uint32_t descriptor_version,
485                         struct efi_mem_desc *virtmap)
486 {
487         return EFI_UNSUPPORTED;
488 }
489
490 /**
491  * efi_convert_pointer_runtime() - convert from physical to virtual pointer
492  *
493  * This function implements the ConvertPointer() runtime service after
494  * the first call to SetVirtualAddressMap().
495  *
496  * See the Unified Extensible Firmware Interface (UEFI) specification for
497  * details.
498  *
499  * @debug_disposition:  indicates if pointer may be converted to NULL
500  * @address:            pointer to be converted
501  * Return:              status code EFI_UNSUPPORTED
502  */
503 static __efi_runtime efi_status_t EFIAPI efi_convert_pointer_runtime(
504                         efi_uintn_t debug_disposition, void **address)
505 {
506         return EFI_UNSUPPORTED;
507 }
508
509 /**
510  * efi_convert_pointer() - convert from physical to virtual pointer
511  *
512  * This function implements the ConvertPointer() runtime service until
513  * the first call to SetVirtualAddressMap().
514  *
515  * See the Unified Extensible Firmware Interface (UEFI) specification for
516  * details.
517  *
518  * @debug_disposition:  indicates if pointer may be converted to NULL
519  * @address:            pointer to be converted
520  * Return:              status code
521  */
522 __efi_runtime efi_status_t EFIAPI
523 efi_convert_pointer(efi_uintn_t debug_disposition, void **address)
524 {
525         efi_physical_addr_t addr;
526         efi_uintn_t i;
527         efi_status_t ret = EFI_NOT_FOUND;
528
529         if (!efi_virtmap) {
530                 ret = EFI_UNSUPPORTED;
531                 goto out;
532         }
533
534         if (!address) {
535                 ret = EFI_INVALID_PARAMETER;
536                 goto out;
537         }
538         if (!*address) {
539                 if (debug_disposition & EFI_OPTIONAL_PTR)
540                         return EFI_SUCCESS;
541                 else
542                         return EFI_INVALID_PARAMETER;
543         }
544
545         addr = (uintptr_t)*address;
546         for (i = 0; i < efi_descriptor_count; i++) {
547                 struct efi_mem_desc *map = (void *)efi_virtmap +
548                                            (efi_descriptor_size * i);
549
550                 if (addr >= map->physical_start &&
551                     (addr < map->physical_start
552                             + (map->num_pages << EFI_PAGE_SHIFT))) {
553                         *address = (void *)(uintptr_t)
554                                    (addr + map->virtual_start -
555                                     map->physical_start);
556
557                         ret = EFI_SUCCESS;
558                         break;
559                 }
560         }
561
562 out:
563         return ret;
564 }
565
566 static __efi_runtime void efi_relocate_runtime_table(ulong offset)
567 {
568         ulong patchoff;
569         void **pos;
570
571         /* Relocate the runtime services pointers */
572         patchoff = offset - gd->relocaddr;
573         for (pos = (void **)&efi_runtime_services.get_time;
574              pos <= (void **)&efi_runtime_services.query_variable_info; ++pos) {
575                 if (*pos)
576                         *pos += patchoff;
577         }
578
579         /*
580          * The entry for SetVirtualAddress() must point to a physical address.
581          * After the first execution the service must return EFI_UNSUPPORTED.
582          */
583         efi_runtime_services.set_virtual_address_map =
584                         &efi_set_virtual_address_map_runtime;
585
586         /*
587          * The entry for ConvertPointer() must point to a physical address.
588          * The service is not usable after SetVirtualAddress().
589          */
590         efi_runtime_services.convert_pointer = &efi_convert_pointer_runtime;
591
592         /*
593          * TODO: Update UEFI variable RuntimeServicesSupported removing flags
594          * EFI_RT_SUPPORTED_SET_VIRTUAL_ADDRESS_MAP and
595          * EFI_RT_SUPPORTED_CONVERT_POINTER as required by the UEFI spec 2.8.
596          */
597
598         /* Update CRC32 */
599         efi_update_table_header_crc32(&efi_runtime_services.hdr);
600 }
601
602 /* Relocate EFI runtime to uboot_reloc_base = offset */
603 void efi_runtime_relocate(ulong offset, struct efi_mem_desc *map)
604 {
605 #ifdef IS_RELA
606         struct elf_rela *rel = (void*)&__efi_runtime_rel_start;
607 #else
608         struct elf_rel *rel = (void*)&__efi_runtime_rel_start;
609         static ulong lastoff = CONFIG_SYS_TEXT_BASE;
610 #endif
611
612         debug("%s: Relocating to offset=%lx\n", __func__, offset);
613         for (; (ulong)rel < (ulong)&__efi_runtime_rel_stop; rel++) {
614                 ulong base = CONFIG_SYS_TEXT_BASE;
615                 ulong *p;
616                 ulong newaddr;
617
618                 p = (void*)((ulong)rel->offset - base) + gd->relocaddr;
619
620                 /*
621                  * The runtime services table is updated in
622                  * efi_relocate_runtime_table()
623                  */
624                 if (map && efi_is_runtime_service_pointer(p))
625                         continue;
626
627                 debug("%s: rel->info=%#lx *p=%#lx rel->offset=%p\n", __func__,
628                       rel->info, *p, rel->offset);
629
630                 switch (rel->info & R_MASK) {
631                 case R_RELATIVE:
632 #ifdef IS_RELA
633                 newaddr = rel->addend + offset - CONFIG_SYS_TEXT_BASE;
634 #else
635                 newaddr = *p - lastoff + offset;
636 #endif
637                         break;
638 #ifdef R_ABSOLUTE
639                 case R_ABSOLUTE: {
640                         ulong symidx = rel->info >> SYM_INDEX;
641                         extern struct dyn_sym __dyn_sym_start[];
642                         newaddr = __dyn_sym_start[symidx].addr + offset;
643 #ifdef IS_RELA
644                         newaddr -= CONFIG_SYS_TEXT_BASE;
645 #endif
646                         break;
647                 }
648 #endif
649                 default:
650                         printf("%s: Unknown relocation type %llx\n",
651                                __func__, rel->info & R_MASK);
652                         continue;
653                 }
654
655                 /* Check if the relocation is inside bounds */
656                 if (map && ((newaddr < map->virtual_start) ||
657                     newaddr > (map->virtual_start +
658                               (map->num_pages << EFI_PAGE_SHIFT)))) {
659                         printf("%s: Relocation at %p is out of range (%lx)\n",
660                                __func__, p, newaddr);
661                         continue;
662                 }
663
664                 debug("%s: Setting %p to %lx\n", __func__, p, newaddr);
665                 *p = newaddr;
666                 flush_dcache_range((ulong)p & ~(EFI_CACHELINE_SIZE - 1),
667                         ALIGN((ulong)&p[1], EFI_CACHELINE_SIZE));
668         }
669
670 #ifndef IS_RELA
671         lastoff = offset;
672 #endif
673
674         invalidate_icache_all();
675 }
676
677 /**
678  * efi_set_virtual_address_map() - change from physical to virtual mapping
679  *
680  * This function implements the SetVirtualAddressMap() runtime service.
681  *
682  * See the Unified Extensible Firmware Interface (UEFI) specification for
683  * details.
684  *
685  * @memory_map_size:    size of the virtual map
686  * @descriptor_size:    size of an entry in the map
687  * @descriptor_version: version of the map entries
688  * @virtmap:            virtual address mapping information
689  * Return:              status code
690  */
691 static efi_status_t EFIAPI efi_set_virtual_address_map(
692                         efi_uintn_t memory_map_size,
693                         efi_uintn_t descriptor_size,
694                         uint32_t descriptor_version,
695                         struct efi_mem_desc *virtmap)
696 {
697         efi_uintn_t n = memory_map_size / descriptor_size;
698         efi_uintn_t i;
699         efi_status_t ret = EFI_INVALID_PARAMETER;
700         int rt_code_sections = 0;
701         struct efi_event *event;
702
703         EFI_ENTRY("%zx %zx %x %p", memory_map_size, descriptor_size,
704                   descriptor_version, virtmap);
705
706         if (descriptor_version != EFI_MEMORY_DESCRIPTOR_VERSION ||
707             descriptor_size < sizeof(struct efi_mem_desc))
708                 goto out;
709
710         efi_virtmap = virtmap;
711         efi_descriptor_size = descriptor_size;
712         efi_descriptor_count = n;
713
714         /*
715          * TODO:
716          * Further down we are cheating. While really we should implement
717          * SetVirtualAddressMap() events and ConvertPointer() to allow
718          * dynamically loaded drivers to expose runtime services, we don't
719          * today.
720          *
721          * So let's ensure we see exactly one single runtime section, as
722          * that is the built-in one. If we see more (or less), someone must
723          * have tried adding or removing to that which we don't support yet.
724          * In that case, let's better fail rather than expose broken runtime
725          * services.
726          */
727         for (i = 0; i < n; i++) {
728                 struct efi_mem_desc *map = (void*)virtmap +
729                                            (descriptor_size * i);
730
731                 if (map->type == EFI_RUNTIME_SERVICES_CODE)
732                         rt_code_sections++;
733         }
734
735         if (rt_code_sections != 1) {
736                 /*
737                  * We expose exactly one single runtime code section, so
738                  * something is definitely going wrong.
739                  */
740                 goto out;
741         }
742
743         /* Notify EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE */
744         list_for_each_entry(event, &efi_events, link) {
745                 if (event->notify_function)
746                         EFI_CALL_VOID(event->notify_function(
747                                         event, event->notify_context));
748         }
749
750         /* Rebind mmio pointers */
751         for (i = 0; i < n; i++) {
752                 struct efi_mem_desc *map = (void*)virtmap +
753                                            (descriptor_size * i);
754                 struct list_head *lhandle;
755                 efi_physical_addr_t map_start = map->physical_start;
756                 efi_physical_addr_t map_len = map->num_pages << EFI_PAGE_SHIFT;
757                 efi_physical_addr_t map_end = map_start + map_len;
758                 u64 off = map->virtual_start - map_start;
759
760                 /* Adjust all mmio pointers in this region */
761                 list_for_each(lhandle, &efi_runtime_mmio) {
762                         struct efi_runtime_mmio_list *lmmio;
763
764                         lmmio = list_entry(lhandle,
765                                            struct efi_runtime_mmio_list,
766                                            link);
767                         if ((map_start <= lmmio->paddr) &&
768                             (map_end >= lmmio->paddr)) {
769                                 uintptr_t new_addr = lmmio->paddr + off;
770                                 *lmmio->ptr = (void *)new_addr;
771                         }
772                 }
773                 if ((map_start <= (uintptr_t)systab.tables) &&
774                     (map_end >= (uintptr_t)systab.tables)) {
775                         char *ptr = (char *)systab.tables;
776
777                         ptr += off;
778                         systab.tables = (struct efi_configuration_table *)ptr;
779                 }
780         }
781
782         /* Relocate the runtime. See TODO above */
783         for (i = 0; i < n; i++) {
784                 struct efi_mem_desc *map;
785
786                 map = (void*)virtmap + (descriptor_size * i);
787                 if (map->type == EFI_RUNTIME_SERVICES_CODE) {
788                         ulong new_offset = map->virtual_start -
789                                            map->physical_start + gd->relocaddr;
790
791                         efi_relocate_runtime_table(new_offset);
792                         efi_runtime_relocate(new_offset, map);
793                         ret = EFI_SUCCESS;
794                         goto out;
795                 }
796         }
797
798 out:
799         return EFI_EXIT(ret);
800 }
801
802 /**
803  * efi_add_runtime_mmio() - add memory-mapped IO region
804  *
805  * This function adds a memory-mapped IO region to the memory map to make it
806  * available at runtime.
807  *
808  * @mmio_ptr:           pointer to a pointer to the start of the memory-mapped
809  *                      IO region
810  * @len:                size of the memory-mapped IO region
811  * Returns:             status code
812  */
813 efi_status_t efi_add_runtime_mmio(void *mmio_ptr, u64 len)
814 {
815         struct efi_runtime_mmio_list *newmmio;
816         uint64_t addr = *(uintptr_t *)mmio_ptr;
817         efi_status_t ret;
818
819         ret = efi_add_memory_map(addr, len, EFI_MMAP_IO);
820         if (ret != EFI_SUCCESS)
821                 return EFI_OUT_OF_RESOURCES;
822
823         newmmio = calloc(1, sizeof(*newmmio));
824         if (!newmmio)
825                 return EFI_OUT_OF_RESOURCES;
826         newmmio->ptr = mmio_ptr;
827         newmmio->paddr = *(uintptr_t *)mmio_ptr;
828         newmmio->len = len;
829         list_add_tail(&newmmio->link, &efi_runtime_mmio);
830
831         return EFI_SUCCESS;
832 }
833
834 /*
835  * In the second stage, U-Boot has disappeared. To isolate our runtime code
836  * that at this point still exists from the rest, we put it into a special
837  * section.
838  *
839  *        !!WARNING!!
840  *
841  * This means that we can not rely on any code outside of this file in any
842  * function or variable below this line.
843  *
844  * Please keep everything fully self-contained and annotated with
845  * __efi_runtime and __efi_runtime_data markers.
846  */
847
848 /*
849  * Relocate the EFI runtime stub to a different place. We need to call this
850  * the first time we expose the runtime interface to a user and on set virtual
851  * address map calls.
852  */
853
854 /**
855  * efi_unimplemented() - replacement function, returns EFI_UNSUPPORTED
856  *
857  * This function is used after SetVirtualAddressMap() is called as replacement
858  * for services that are not available anymore due to constraints of the U-Boot
859  * implementation.
860  *
861  * Return:      EFI_UNSUPPORTED
862  */
863 static efi_status_t __efi_runtime EFIAPI efi_unimplemented(void)
864 {
865         return EFI_UNSUPPORTED;
866 }
867
868 /**
869  * efi_update_capsule() - process information from operating system
870  *
871  * This function implements the UpdateCapsule() runtime service.
872  *
873  * See the Unified Extensible Firmware Interface (UEFI) specification for
874  * details.
875  *
876  * @capsule_header_array:       pointer to array of virtual pointers
877  * @capsule_count:              number of pointers in capsule_header_array
878  * @scatter_gather_list:        pointer to arry of physical pointers
879  * Returns:                     status code
880  */
881 efi_status_t __efi_runtime EFIAPI efi_update_capsule(
882                         struct efi_capsule_header **capsule_header_array,
883                         efi_uintn_t capsule_count,
884                         u64 scatter_gather_list)
885 {
886         return EFI_UNSUPPORTED;
887 }
888
889 /**
890  * efi_query_capsule_caps() - check if capsule is supported
891  *
892  * This function implements the QueryCapsuleCapabilities() runtime service.
893  *
894  * See the Unified Extensible Firmware Interface (UEFI) specification for
895  * details.
896  *
897  * @capsule_header_array:       pointer to array of virtual pointers
898  * @capsule_count:              number of pointers in capsule_header_array
899  * @maximum_capsule_size:       maximum capsule size
900  * @reset_type:                 type of reset needed for capsule update
901  * Returns:                     status code
902  */
903 efi_status_t __efi_runtime EFIAPI efi_query_capsule_caps(
904                         struct efi_capsule_header **capsule_header_array,
905                         efi_uintn_t capsule_count,
906                         u64 *maximum_capsule_size,
907                         u32 *reset_type)
908 {
909         return EFI_UNSUPPORTED;
910 }
911
912 struct efi_runtime_services __efi_runtime_data efi_runtime_services = {
913         .hdr = {
914                 .signature = EFI_RUNTIME_SERVICES_SIGNATURE,
915                 .revision = EFI_SPECIFICATION_VERSION,
916                 .headersize = sizeof(struct efi_runtime_services),
917         },
918         .get_time = &efi_get_time_boottime,
919         .set_time = &efi_set_time_boottime,
920         .get_wakeup_time = (void *)&efi_unimplemented,
921         .set_wakeup_time = (void *)&efi_unimplemented,
922         .set_virtual_address_map = &efi_set_virtual_address_map,
923         .convert_pointer = efi_convert_pointer,
924         .get_variable = efi_get_variable,
925         .get_next_variable_name = efi_get_next_variable_name,
926         .set_variable = efi_set_variable,
927         .get_next_high_mono_count = (void *)&efi_unimplemented,
928         .reset_system = &efi_reset_system_boottime,
929         .update_capsule = efi_update_capsule,
930         .query_capsule_caps = efi_query_capsule_caps,
931         .query_variable_info = efi_query_variable_info,
932 };