board: cssi: Add CPU board CMPCPRO
[platform/kernel/u-boot.git] / lib / efi_loader / efi_boottime.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * EFI application boot time services
4  *
5  * Copyright (c) 2016 Alexander Graf
6  */
7
8 #include <common.h>
9 #include <bootm.h>
10 #include <div64.h>
11 #include <dm/device.h>
12 #include <dm/root.h>
13 #include <efi_loader.h>
14 #include <irq_func.h>
15 #include <log.h>
16 #include <malloc.h>
17 #include <pe.h>
18 #include <time.h>
19 #include <u-boot/crc.h>
20 #include <usb.h>
21 #include <watchdog.h>
22 #include <asm/global_data.h>
23 #include <asm/setjmp.h>
24 #include <linux/libfdt_env.h>
25
26 DECLARE_GLOBAL_DATA_PTR;
27
28 /* Task priority level */
29 static efi_uintn_t efi_tpl = TPL_APPLICATION;
30
31 /* This list contains all the EFI objects our payload has access to */
32 LIST_HEAD(efi_obj_list);
33
34 /* List of all events */
35 __efi_runtime_data LIST_HEAD(efi_events);
36
37 /* List of queued events */
38 LIST_HEAD(efi_event_queue);
39
40 /* Flag to disable timer activity in ExitBootServices() */
41 static bool timers_enabled = true;
42
43 /* Flag used by the selftest to avoid detaching devices in ExitBootServices() */
44 bool efi_st_keep_devices;
45
46 /* List of all events registered by RegisterProtocolNotify() */
47 LIST_HEAD(efi_register_notify_events);
48
49 /* Handle of the currently executing image */
50 static efi_handle_t current_image;
51
52 #if defined(CONFIG_ARM) || defined(CONFIG_RISCV)
53 /*
54  * The "gd" pointer lives in a register on ARM and RISC-V that we declare
55  * fixed when compiling U-Boot. However, the payload does not know about that
56  * restriction so we need to manually swap its and our view of that register on
57  * EFI callback entry/exit.
58  */
59 static volatile gd_t *efi_gd, *app_gd;
60 #endif
61
62 /* 1 if inside U-Boot code, 0 if inside EFI payload code */
63 static int entry_count = 1;
64 static int nesting_level;
65 /* GUID of the device tree table */
66 const efi_guid_t efi_guid_fdt = EFI_FDT_GUID;
67 /* GUID of the EFI_DRIVER_BINDING_PROTOCOL */
68 const efi_guid_t efi_guid_driver_binding_protocol =
69                         EFI_DRIVER_BINDING_PROTOCOL_GUID;
70
71 /* event group ExitBootServices() invoked */
72 const efi_guid_t efi_guid_event_group_exit_boot_services =
73                         EFI_EVENT_GROUP_EXIT_BOOT_SERVICES;
74 /* event group before ExitBootServices() invoked */
75 const efi_guid_t efi_guid_event_group_before_exit_boot_services =
76                         EFI_EVENT_GROUP_BEFORE_EXIT_BOOT_SERVICES;
77 /* event group SetVirtualAddressMap() invoked */
78 const efi_guid_t efi_guid_event_group_virtual_address_change =
79                         EFI_EVENT_GROUP_VIRTUAL_ADDRESS_CHANGE;
80 /* event group memory map changed */
81 const efi_guid_t efi_guid_event_group_memory_map_change =
82                         EFI_EVENT_GROUP_MEMORY_MAP_CHANGE;
83 /* event group boot manager about to boot */
84 const efi_guid_t efi_guid_event_group_ready_to_boot =
85                         EFI_EVENT_GROUP_READY_TO_BOOT;
86 /* event group ResetSystem() invoked (before ExitBootServices) */
87 const efi_guid_t efi_guid_event_group_reset_system =
88                         EFI_EVENT_GROUP_RESET_SYSTEM;
89 /* GUIDs of the Load File and Load File2 protocols */
90 const efi_guid_t efi_guid_load_file_protocol = EFI_LOAD_FILE_PROTOCOL_GUID;
91 const efi_guid_t efi_guid_load_file2_protocol = EFI_LOAD_FILE2_PROTOCOL_GUID;
92 /* GUID of the SMBIOS table */
93 const efi_guid_t smbios_guid = SMBIOS_TABLE_GUID;
94
95 static efi_status_t EFIAPI efi_disconnect_controller(
96                                         efi_handle_t controller_handle,
97                                         efi_handle_t driver_image_handle,
98                                         efi_handle_t child_handle);
99
100 /* Called on every callback entry */
101 int __efi_entry_check(void)
102 {
103         int ret = entry_count++ == 0;
104 #if defined(CONFIG_ARM) || defined(CONFIG_RISCV)
105         assert(efi_gd);
106         app_gd = gd;
107         set_gd(efi_gd);
108 #endif
109         return ret;
110 }
111
112 /* Called on every callback exit */
113 int __efi_exit_check(void)
114 {
115         int ret = --entry_count == 0;
116 #if defined(CONFIG_ARM) || defined(CONFIG_RISCV)
117         set_gd(app_gd);
118 #endif
119         return ret;
120 }
121
122 /**
123  * efi_save_gd() - save global data register
124  *
125  * On the ARM and RISC-V architectures gd is mapped to a fixed register.
126  * As this register may be overwritten by an EFI payload we save it here
127  * and restore it on every callback entered.
128  *
129  * This function is called after relocation from initr_reloc_global_data().
130  */
131 void efi_save_gd(void)
132 {
133 #if defined(CONFIG_ARM) || defined(CONFIG_RISCV)
134         efi_gd = gd;
135 #endif
136 }
137
138 /**
139  * efi_restore_gd() - restore global data register
140  *
141  * On the ARM and RISC-V architectures gd is mapped to a fixed register.
142  * Restore it after returning from the UEFI world to the value saved via
143  * efi_save_gd().
144  */
145 void efi_restore_gd(void)
146 {
147 #if defined(CONFIG_ARM) || defined(CONFIG_RISCV)
148         /* Only restore if we're already in EFI context */
149         if (!efi_gd)
150                 return;
151         set_gd(efi_gd);
152 #endif
153 }
154
155 /**
156  * indent_string() - returns a string for indenting with two spaces per level
157  * @level: indent level
158  *
159  * A maximum of ten indent levels is supported. Higher indent levels will be
160  * truncated.
161  *
162  * Return: A string for indenting with two spaces per level is
163  *         returned.
164  */
165 static const char *indent_string(int level)
166 {
167         const char *indent = "                    ";
168         const int max = strlen(indent);
169
170         level = min(max, level * 2);
171         return &indent[max - level];
172 }
173
174 const char *__efi_nesting(void)
175 {
176         return indent_string(nesting_level);
177 }
178
179 const char *__efi_nesting_inc(void)
180 {
181         return indent_string(nesting_level++);
182 }
183
184 const char *__efi_nesting_dec(void)
185 {
186         return indent_string(--nesting_level);
187 }
188
189 /**
190  * efi_event_is_queued() - check if an event is queued
191  *
192  * @event:      event
193  * Return:      true if event is queued
194  */
195 static bool efi_event_is_queued(struct efi_event *event)
196 {
197         return !!event->queue_link.next;
198 }
199
200 /**
201  * efi_process_event_queue() - process event queue
202  */
203 static void efi_process_event_queue(void)
204 {
205         while (!list_empty(&efi_event_queue)) {
206                 struct efi_event *event;
207                 efi_uintn_t old_tpl;
208
209                 event = list_first_entry(&efi_event_queue, struct efi_event,
210                                          queue_link);
211                 if (efi_tpl >= event->notify_tpl)
212                         return;
213                 list_del(&event->queue_link);
214                 event->queue_link.next = NULL;
215                 event->queue_link.prev = NULL;
216                 /* Events must be executed at the event's TPL */
217                 old_tpl = efi_tpl;
218                 efi_tpl = event->notify_tpl;
219                 EFI_CALL_VOID(event->notify_function(event,
220                                                      event->notify_context));
221                 efi_tpl = old_tpl;
222                 if (event->type == EVT_NOTIFY_SIGNAL)
223                         event->is_signaled = 0;
224         }
225 }
226
227 /**
228  * efi_queue_event() - queue an EFI event
229  * @event:     event to signal
230  *
231  * This function queues the notification function of the event for future
232  * execution.
233  *
234  */
235 static void efi_queue_event(struct efi_event *event)
236 {
237         struct efi_event *item;
238
239         if (!event->notify_function)
240                 return;
241
242         if (!efi_event_is_queued(event)) {
243                 /*
244                  * Events must be notified in order of decreasing task priority
245                  * level. Insert the new event accordingly.
246                  */
247                 list_for_each_entry(item, &efi_event_queue, queue_link) {
248                         if (item->notify_tpl < event->notify_tpl) {
249                                 list_add_tail(&event->queue_link,
250                                               &item->queue_link);
251                                 event = NULL;
252                                 break;
253                         }
254                 }
255                 if (event)
256                         list_add_tail(&event->queue_link, &efi_event_queue);
257                 efi_process_event_queue();
258         }
259 }
260
261 /**
262  * is_valid_tpl() - check if the task priority level is valid
263  *
264  * @tpl:                TPL level to check
265  * Return:              status code
266  */
267 static efi_status_t is_valid_tpl(efi_uintn_t tpl)
268 {
269         switch (tpl) {
270         case TPL_APPLICATION:
271         case TPL_CALLBACK:
272         case TPL_NOTIFY:
273                 return EFI_SUCCESS;
274         default:
275                 return EFI_INVALID_PARAMETER;
276         }
277 }
278
279 /**
280  * efi_signal_event() - signal an EFI event
281  * @event:     event to signal
282  *
283  * This function signals an event. If the event belongs to an event group, all
284  * events of the group are signaled. If they are of type EVT_NOTIFY_SIGNAL,
285  * their notification function is queued.
286  *
287  * For the SignalEvent service see efi_signal_event_ext.
288  */
289 void efi_signal_event(struct efi_event *event)
290 {
291         if (event->is_signaled)
292                 return;
293         if (event->group) {
294                 struct efi_event *evt;
295
296                 /*
297                  * The signaled state has to set before executing any
298                  * notification function
299                  */
300                 list_for_each_entry(evt, &efi_events, link) {
301                         if (!evt->group || guidcmp(evt->group, event->group))
302                                 continue;
303                         if (evt->is_signaled)
304                                 continue;
305                         evt->is_signaled = true;
306                 }
307                 list_for_each_entry(evt, &efi_events, link) {
308                         if (!evt->group || guidcmp(evt->group, event->group))
309                                 continue;
310                         efi_queue_event(evt);
311                 }
312         } else {
313                 event->is_signaled = true;
314                 efi_queue_event(event);
315         }
316 }
317
318 /**
319  * efi_raise_tpl() - raise the task priority level
320  * @new_tpl: new value of the task priority level
321  *
322  * This function implements the RaiseTpl service.
323  *
324  * See the Unified Extensible Firmware Interface (UEFI) specification for
325  * details.
326  *
327  * Return: old value of the task priority level
328  */
329 static unsigned long EFIAPI efi_raise_tpl(efi_uintn_t new_tpl)
330 {
331         efi_uintn_t old_tpl = efi_tpl;
332
333         EFI_ENTRY("0x%zx", new_tpl);
334
335         if (new_tpl < efi_tpl)
336                 EFI_PRINT("WARNING: new_tpl < current_tpl in %s\n", __func__);
337         efi_tpl = new_tpl;
338         if (efi_tpl > TPL_HIGH_LEVEL)
339                 efi_tpl = TPL_HIGH_LEVEL;
340
341         EFI_EXIT(EFI_SUCCESS);
342         return old_tpl;
343 }
344
345 /**
346  * efi_restore_tpl() - lower the task priority level
347  * @old_tpl: value of the task priority level to be restored
348  *
349  * This function implements the RestoreTpl service.
350  *
351  * See the Unified Extensible Firmware Interface (UEFI) specification for
352  * details.
353  */
354 static void EFIAPI efi_restore_tpl(efi_uintn_t old_tpl)
355 {
356         EFI_ENTRY("0x%zx", old_tpl);
357
358         if (old_tpl > efi_tpl)
359                 EFI_PRINT("WARNING: old_tpl > current_tpl in %s\n", __func__);
360         efi_tpl = old_tpl;
361         if (efi_tpl > TPL_HIGH_LEVEL)
362                 efi_tpl = TPL_HIGH_LEVEL;
363
364         /*
365          * Lowering the TPL may have made queued events eligible for execution.
366          */
367         efi_timer_check();
368
369         EFI_EXIT(EFI_SUCCESS);
370 }
371
372 /**
373  * efi_allocate_pages_ext() - allocate memory pages
374  * @type:        type of allocation to be performed
375  * @memory_type: usage type of the allocated memory
376  * @pages:       number of pages to be allocated
377  * @memory:      allocated memory
378  *
379  * This function implements the AllocatePages service.
380  *
381  * See the Unified Extensible Firmware Interface (UEFI) specification for
382  * details.
383  *
384  * Return: status code
385  */
386 static efi_status_t EFIAPI efi_allocate_pages_ext(int type, int memory_type,
387                                                   efi_uintn_t pages,
388                                                   uint64_t *memory)
389 {
390         efi_status_t r;
391
392         EFI_ENTRY("%d, %d, 0x%zx, %p", type, memory_type, pages, memory);
393         r = efi_allocate_pages(type, memory_type, pages, memory);
394         return EFI_EXIT(r);
395 }
396
397 /**
398  * efi_free_pages_ext() - Free memory pages.
399  * @memory: start of the memory area to be freed
400  * @pages:  number of pages to be freed
401  *
402  * This function implements the FreePages service.
403  *
404  * See the Unified Extensible Firmware Interface (UEFI) specification for
405  * details.
406  *
407  * Return: status code
408  */
409 static efi_status_t EFIAPI efi_free_pages_ext(uint64_t memory,
410                                               efi_uintn_t pages)
411 {
412         efi_status_t r;
413
414         EFI_ENTRY("%llx, 0x%zx", memory, pages);
415         r = efi_free_pages(memory, pages);
416         return EFI_EXIT(r);
417 }
418
419 /**
420  * efi_get_memory_map_ext() - get map describing memory usage
421  * @memory_map_size:    on entry the size, in bytes, of the memory map buffer,
422  *                      on exit the size of the copied memory map
423  * @memory_map:         buffer to which the memory map is written
424  * @map_key:            key for the memory map
425  * @descriptor_size:    size of an individual memory descriptor
426  * @descriptor_version: version number of the memory descriptor structure
427  *
428  * This function implements the GetMemoryMap service.
429  *
430  * See the Unified Extensible Firmware Interface (UEFI) specification for
431  * details.
432  *
433  * Return: status code
434  */
435 static efi_status_t EFIAPI efi_get_memory_map_ext(
436                                         efi_uintn_t *memory_map_size,
437                                         struct efi_mem_desc *memory_map,
438                                         efi_uintn_t *map_key,
439                                         efi_uintn_t *descriptor_size,
440                                         uint32_t *descriptor_version)
441 {
442         efi_status_t r;
443
444         EFI_ENTRY("%p, %p, %p, %p, %p", memory_map_size, memory_map,
445                   map_key, descriptor_size, descriptor_version);
446         r = efi_get_memory_map(memory_map_size, memory_map, map_key,
447                                descriptor_size, descriptor_version);
448         return EFI_EXIT(r);
449 }
450
451 /**
452  * efi_allocate_pool_ext() - allocate memory from pool
453  * @pool_type: type of the pool from which memory is to be allocated
454  * @size:      number of bytes to be allocated
455  * @buffer:    allocated memory
456  *
457  * This function implements the AllocatePool service.
458  *
459  * See the Unified Extensible Firmware Interface (UEFI) specification for
460  * details.
461  *
462  * Return: status code
463  */
464 static efi_status_t EFIAPI efi_allocate_pool_ext(int pool_type,
465                                                  efi_uintn_t size,
466                                                  void **buffer)
467 {
468         efi_status_t r;
469
470         EFI_ENTRY("%d, %zu, %p", pool_type, size, buffer);
471         r = efi_allocate_pool(pool_type, size, buffer);
472         return EFI_EXIT(r);
473 }
474
475 /**
476  * efi_free_pool_ext() - free memory from pool
477  * @buffer: start of memory to be freed
478  *
479  * This function implements the FreePool service.
480  *
481  * See the Unified Extensible Firmware Interface (UEFI) specification for
482  * details.
483  *
484  * Return: status code
485  */
486 static efi_status_t EFIAPI efi_free_pool_ext(void *buffer)
487 {
488         efi_status_t r;
489
490         EFI_ENTRY("%p", buffer);
491         r = efi_free_pool(buffer);
492         return EFI_EXIT(r);
493 }
494
495 /**
496  * efi_add_handle() - add a new handle to the object list
497  *
498  * @handle:     handle to be added
499  *
500  * The protocols list is initialized. The handle is added to the list of known
501  * UEFI objects.
502  */
503 void efi_add_handle(efi_handle_t handle)
504 {
505         if (!handle)
506                 return;
507         INIT_LIST_HEAD(&handle->protocols);
508         list_add_tail(&handle->link, &efi_obj_list);
509 }
510
511 /**
512  * efi_create_handle() - create handle
513  * @handle: new handle
514  *
515  * Return: status code
516  */
517 efi_status_t efi_create_handle(efi_handle_t *handle)
518 {
519         struct efi_object *obj;
520
521         obj = calloc(1, sizeof(struct efi_object));
522         if (!obj)
523                 return EFI_OUT_OF_RESOURCES;
524
525         efi_add_handle(obj);
526         *handle = obj;
527
528         return EFI_SUCCESS;
529 }
530
531 /**
532  * efi_search_protocol() - find a protocol on a handle.
533  * @handle:        handle
534  * @protocol_guid: GUID of the protocol
535  * @handler:       reference to the protocol
536  *
537  * Return: status code
538  */
539 efi_status_t efi_search_protocol(const efi_handle_t handle,
540                                  const efi_guid_t *protocol_guid,
541                                  struct efi_handler **handler)
542 {
543         struct efi_object *efiobj;
544         struct list_head *lhandle;
545
546         if (!handle || !protocol_guid)
547                 return EFI_INVALID_PARAMETER;
548         efiobj = efi_search_obj(handle);
549         if (!efiobj)
550                 return EFI_INVALID_PARAMETER;
551         list_for_each(lhandle, &efiobj->protocols) {
552                 struct efi_handler *protocol;
553
554                 protocol = list_entry(lhandle, struct efi_handler, link);
555                 if (!guidcmp(&protocol->guid, protocol_guid)) {
556                         if (handler)
557                                 *handler = protocol;
558                         return EFI_SUCCESS;
559                 }
560         }
561         return EFI_NOT_FOUND;
562 }
563
564 /**
565  * efi_remove_protocol() - delete protocol from a handle
566  * @handle:             handle from which the protocol shall be deleted
567  * @protocol:           GUID of the protocol to be deleted
568  * @protocol_interface: interface of the protocol implementation
569  *
570  * Return: status code
571  */
572 efi_status_t efi_remove_protocol(const efi_handle_t handle,
573                                  const efi_guid_t *protocol,
574                                  void *protocol_interface)
575 {
576         struct efi_handler *handler;
577         efi_status_t ret;
578
579         ret = efi_search_protocol(handle, protocol, &handler);
580         if (ret != EFI_SUCCESS)
581                 return ret;
582         if (handler->protocol_interface != protocol_interface)
583                 return EFI_NOT_FOUND;
584         list_del(&handler->link);
585         free(handler);
586         return EFI_SUCCESS;
587 }
588
589 /**
590  * efi_remove_all_protocols() - delete all protocols from a handle
591  * @handle: handle from which the protocols shall be deleted
592  *
593  * Return: status code
594  */
595 static efi_status_t efi_remove_all_protocols(const efi_handle_t handle)
596 {
597         struct efi_object *efiobj;
598         struct efi_handler *protocol;
599         struct efi_handler *pos;
600
601         efiobj = efi_search_obj(handle);
602         if (!efiobj)
603                 return EFI_INVALID_PARAMETER;
604         list_for_each_entry_safe(protocol, pos, &efiobj->protocols, link) {
605                 efi_status_t ret;
606
607                 ret = efi_remove_protocol(handle, &protocol->guid,
608                                           protocol->protocol_interface);
609                 if (ret != EFI_SUCCESS)
610                         return ret;
611         }
612         return EFI_SUCCESS;
613 }
614
615 /**
616  * efi_delete_handle() - delete handle
617  *
618  * @handle: handle to delete
619  */
620 void efi_delete_handle(efi_handle_t handle)
621 {
622         efi_status_t ret;
623
624         ret = efi_remove_all_protocols(handle);
625         if (ret == EFI_INVALID_PARAMETER) {
626                 log_err("Can't remove invalid handle %p\n", handle);
627                 return;
628         }
629
630         list_del(&handle->link);
631         free(handle);
632 }
633
634 /**
635  * efi_is_event() - check if a pointer is a valid event
636  * @event: pointer to check
637  *
638  * Return: status code
639  */
640 static efi_status_t efi_is_event(const struct efi_event *event)
641 {
642         const struct efi_event *evt;
643
644         if (!event)
645                 return EFI_INVALID_PARAMETER;
646         list_for_each_entry(evt, &efi_events, link) {
647                 if (evt == event)
648                         return EFI_SUCCESS;
649         }
650         return EFI_INVALID_PARAMETER;
651 }
652
653 /**
654  * efi_create_event() - create an event
655  *
656  * @type:            type of the event to create
657  * @notify_tpl:      task priority level of the event
658  * @notify_function: notification function of the event
659  * @notify_context:  pointer passed to the notification function
660  * @group:           event group
661  * @event:           created event
662  *
663  * This function is used inside U-Boot code to create an event.
664  *
665  * For the API function implementing the CreateEvent service see
666  * efi_create_event_ext.
667  *
668  * Return: status code
669  */
670 efi_status_t efi_create_event(uint32_t type, efi_uintn_t notify_tpl,
671                               void (EFIAPI *notify_function) (
672                                         struct efi_event *event,
673                                         void *context),
674                               void *notify_context, efi_guid_t *group,
675                               struct efi_event **event)
676 {
677         struct efi_event *evt;
678         efi_status_t ret;
679         int pool_type;
680
681         if (event == NULL)
682                 return EFI_INVALID_PARAMETER;
683
684         switch (type) {
685         case 0:
686         case EVT_TIMER:
687         case EVT_NOTIFY_SIGNAL:
688         case EVT_TIMER | EVT_NOTIFY_SIGNAL:
689         case EVT_NOTIFY_WAIT:
690         case EVT_TIMER | EVT_NOTIFY_WAIT:
691         case EVT_SIGNAL_EXIT_BOOT_SERVICES:
692                 pool_type = EFI_BOOT_SERVICES_DATA;
693                 break;
694         case EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE:
695                 pool_type = EFI_RUNTIME_SERVICES_DATA;
696                 break;
697         default:
698                 return EFI_INVALID_PARAMETER;
699         }
700
701         /*
702          * The UEFI specification requires event notification levels to be
703          * > TPL_APPLICATION and <= TPL_HIGH_LEVEL.
704          *
705          * Parameter NotifyTpl should not be checked if it is not used.
706          */
707         if ((type & (EVT_NOTIFY_WAIT | EVT_NOTIFY_SIGNAL)) &&
708             (!notify_function || is_valid_tpl(notify_tpl) != EFI_SUCCESS ||
709              notify_tpl == TPL_APPLICATION))
710                 return EFI_INVALID_PARAMETER;
711
712         ret = efi_allocate_pool(pool_type, sizeof(struct efi_event),
713                                 (void **)&evt);
714         if (ret != EFI_SUCCESS)
715                 return ret;
716         memset(evt, 0, sizeof(struct efi_event));
717         evt->type = type;
718         evt->notify_tpl = notify_tpl;
719         evt->notify_function = notify_function;
720         evt->notify_context = notify_context;
721         evt->group = group;
722         /* Disable timers on boot up */
723         evt->trigger_next = -1ULL;
724         list_add_tail(&evt->link, &efi_events);
725         *event = evt;
726         return EFI_SUCCESS;
727 }
728
729 /*
730  * efi_create_event_ex() - create an event in a group
731  *
732  * @type:            type of the event to create
733  * @notify_tpl:      task priority level of the event
734  * @notify_function: notification function of the event
735  * @notify_context:  pointer passed to the notification function
736  * @event:           created event
737  * @event_group:     event group
738  *
739  * This function implements the CreateEventEx service.
740  *
741  * See the Unified Extensible Firmware Interface (UEFI) specification for
742  * details.
743  *
744  * Return: status code
745  */
746 static
747 efi_status_t EFIAPI efi_create_event_ex(uint32_t type, efi_uintn_t notify_tpl,
748                                         void (EFIAPI *notify_function) (
749                                                         struct efi_event *event,
750                                                         void *context),
751                                         void *notify_context,
752                                         efi_guid_t *event_group,
753                                         struct efi_event **event)
754 {
755         efi_status_t ret;
756
757         EFI_ENTRY("%d, 0x%zx, %p, %p, %pUs", type, notify_tpl, notify_function,
758                   notify_context, event_group);
759
760         /*
761          * The allowable input parameters are the same as in CreateEvent()
762          * except for the following two disallowed event types.
763          */
764         switch (type) {
765         case EVT_SIGNAL_EXIT_BOOT_SERVICES:
766         case EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE:
767                 ret = EFI_INVALID_PARAMETER;
768                 goto out;
769         }
770
771         ret = efi_create_event(type, notify_tpl, notify_function,
772                                notify_context, event_group, event);
773 out:
774         return EFI_EXIT(ret);
775 }
776
777 /**
778  * efi_create_event_ext() - create an event
779  * @type:            type of the event to create
780  * @notify_tpl:      task priority level of the event
781  * @notify_function: notification function of the event
782  * @notify_context:  pointer passed to the notification function
783  * @event:           created event
784  *
785  * This function implements the CreateEvent service.
786  *
787  * See the Unified Extensible Firmware Interface (UEFI) specification for
788  * details.
789  *
790  * Return: status code
791  */
792 static efi_status_t EFIAPI efi_create_event_ext(
793                         uint32_t type, efi_uintn_t notify_tpl,
794                         void (EFIAPI *notify_function) (
795                                         struct efi_event *event,
796                                         void *context),
797                         void *notify_context, struct efi_event **event)
798 {
799         EFI_ENTRY("%d, 0x%zx, %p, %p", type, notify_tpl, notify_function,
800                   notify_context);
801         return EFI_EXIT(efi_create_event(type, notify_tpl, notify_function,
802                                          notify_context, NULL, event));
803 }
804
805 /**
806  * efi_timer_check() - check if a timer event has occurred
807  *
808  * Check if a timer event has occurred or a queued notification function should
809  * be called.
810  *
811  * Our timers have to work without interrupts, so we check whenever keyboard
812  * input or disk accesses happen if enough time elapsed for them to fire.
813  */
814 void efi_timer_check(void)
815 {
816         struct efi_event *evt;
817         u64 now = timer_get_us();
818
819         list_for_each_entry(evt, &efi_events, link) {
820                 if (!timers_enabled)
821                         continue;
822                 if (!(evt->type & EVT_TIMER) || now < evt->trigger_next)
823                         continue;
824                 switch (evt->trigger_type) {
825                 case EFI_TIMER_RELATIVE:
826                         evt->trigger_type = EFI_TIMER_STOP;
827                         break;
828                 case EFI_TIMER_PERIODIC:
829                         evt->trigger_next += evt->trigger_time;
830                         break;
831                 default:
832                         continue;
833                 }
834                 evt->is_signaled = false;
835                 efi_signal_event(evt);
836         }
837         efi_process_event_queue();
838         schedule();
839 }
840
841 /**
842  * efi_set_timer() - set the trigger time for a timer event or stop the event
843  * @event:        event for which the timer is set
844  * @type:         type of the timer
845  * @trigger_time: trigger period in multiples of 100 ns
846  *
847  * This is the function for internal usage in U-Boot. For the API function
848  * implementing the SetTimer service see efi_set_timer_ext.
849  *
850  * Return: status code
851  */
852 efi_status_t efi_set_timer(struct efi_event *event, enum efi_timer_delay type,
853                            uint64_t trigger_time)
854 {
855         /* Check that the event is valid */
856         if (efi_is_event(event) != EFI_SUCCESS || !(event->type & EVT_TIMER))
857                 return EFI_INVALID_PARAMETER;
858
859         /*
860          * The parameter defines a multiple of 100 ns.
861          * We use multiples of 1000 ns. So divide by 10.
862          */
863         do_div(trigger_time, 10);
864
865         switch (type) {
866         case EFI_TIMER_STOP:
867                 event->trigger_next = -1ULL;
868                 break;
869         case EFI_TIMER_PERIODIC:
870         case EFI_TIMER_RELATIVE:
871                 event->trigger_next = timer_get_us() + trigger_time;
872                 break;
873         default:
874                 return EFI_INVALID_PARAMETER;
875         }
876         event->trigger_type = type;
877         event->trigger_time = trigger_time;
878         event->is_signaled = false;
879         return EFI_SUCCESS;
880 }
881
882 /**
883  * efi_set_timer_ext() - Set the trigger time for a timer event or stop the
884  *                       event
885  * @event:        event for which the timer is set
886  * @type:         type of the timer
887  * @trigger_time: trigger period in multiples of 100 ns
888  *
889  * This function implements the SetTimer service.
890  *
891  * See the Unified Extensible Firmware Interface (UEFI) specification for
892  * details.
893  *
894  *
895  * Return: status code
896  */
897 static efi_status_t EFIAPI efi_set_timer_ext(struct efi_event *event,
898                                              enum efi_timer_delay type,
899                                              uint64_t trigger_time)
900 {
901         EFI_ENTRY("%p, %d, %llx", event, type, trigger_time);
902         return EFI_EXIT(efi_set_timer(event, type, trigger_time));
903 }
904
905 /**
906  * efi_wait_for_event() - wait for events to be signaled
907  * @num_events: number of events to be waited for
908  * @event:      events to be waited for
909  * @index:      index of the event that was signaled
910  *
911  * This function implements the WaitForEvent service.
912  *
913  * See the Unified Extensible Firmware Interface (UEFI) specification for
914  * details.
915  *
916  * Return: status code
917  */
918 static efi_status_t EFIAPI efi_wait_for_event(efi_uintn_t num_events,
919                                               struct efi_event **event,
920                                               efi_uintn_t *index)
921 {
922         int i;
923
924         EFI_ENTRY("%zu, %p, %p", num_events, event, index);
925
926         /* Check parameters */
927         if (!num_events || !event)
928                 return EFI_EXIT(EFI_INVALID_PARAMETER);
929         /* Check TPL */
930         if (efi_tpl != TPL_APPLICATION)
931                 return EFI_EXIT(EFI_UNSUPPORTED);
932         for (i = 0; i < num_events; ++i) {
933                 if (efi_is_event(event[i]) != EFI_SUCCESS)
934                         return EFI_EXIT(EFI_INVALID_PARAMETER);
935                 if (!event[i]->type || event[i]->type & EVT_NOTIFY_SIGNAL)
936                         return EFI_EXIT(EFI_INVALID_PARAMETER);
937                 if (!event[i]->is_signaled)
938                         efi_queue_event(event[i]);
939         }
940
941         /* Wait for signal */
942         for (;;) {
943                 for (i = 0; i < num_events; ++i) {
944                         if (event[i]->is_signaled)
945                                 goto out;
946                 }
947                 /* Allow events to occur. */
948                 efi_timer_check();
949         }
950
951 out:
952         /*
953          * Reset the signal which is passed to the caller to allow periodic
954          * events to occur.
955          */
956         event[i]->is_signaled = false;
957         if (index)
958                 *index = i;
959
960         return EFI_EXIT(EFI_SUCCESS);
961 }
962
963 /**
964  * efi_signal_event_ext() - signal an EFI event
965  * @event: event to signal
966  *
967  * This function implements the SignalEvent service.
968  *
969  * See the Unified Extensible Firmware Interface (UEFI) specification for
970  * details.
971  *
972  * This functions sets the signaled state of the event and queues the
973  * notification function for execution.
974  *
975  * Return: status code
976  */
977 static efi_status_t EFIAPI efi_signal_event_ext(struct efi_event *event)
978 {
979         EFI_ENTRY("%p", event);
980         if (efi_is_event(event) != EFI_SUCCESS)
981                 return EFI_EXIT(EFI_INVALID_PARAMETER);
982         efi_signal_event(event);
983         return EFI_EXIT(EFI_SUCCESS);
984 }
985
986 /**
987  * efi_close_event() - close an EFI event
988  * @event: event to close
989  *
990  * This function implements the CloseEvent service.
991  *
992  * See the Unified Extensible Firmware Interface (UEFI) specification for
993  * details.
994  *
995  * Return: status code
996  */
997 static efi_status_t EFIAPI efi_close_event(struct efi_event *event)
998 {
999         struct efi_register_notify_event *item, *next;
1000
1001         EFI_ENTRY("%p", event);
1002         if (efi_is_event(event) != EFI_SUCCESS)
1003                 return EFI_EXIT(EFI_INVALID_PARAMETER);
1004
1005         /* Remove protocol notify registrations for the event */
1006         list_for_each_entry_safe(item, next, &efi_register_notify_events,
1007                                  link) {
1008                 if (event == item->event) {
1009                         struct efi_protocol_notification *hitem, *hnext;
1010
1011                         /* Remove signaled handles */
1012                         list_for_each_entry_safe(hitem, hnext, &item->handles,
1013                                                  link) {
1014                                 list_del(&hitem->link);
1015                                 free(hitem);
1016                         }
1017                         list_del(&item->link);
1018                         free(item);
1019                 }
1020         }
1021         /* Remove event from queue */
1022         if (efi_event_is_queued(event))
1023                 list_del(&event->queue_link);
1024
1025         list_del(&event->link);
1026         efi_free_pool(event);
1027         return EFI_EXIT(EFI_SUCCESS);
1028 }
1029
1030 /**
1031  * efi_check_event() - check if an event is signaled
1032  * @event: event to check
1033  *
1034  * This function implements the CheckEvent service.
1035  *
1036  * See the Unified Extensible Firmware Interface (UEFI) specification for
1037  * details.
1038  *
1039  * If an event is not signaled yet, the notification function is queued. The
1040  * signaled state is cleared.
1041  *
1042  * Return: status code
1043  */
1044 static efi_status_t EFIAPI efi_check_event(struct efi_event *event)
1045 {
1046         EFI_ENTRY("%p", event);
1047         efi_timer_check();
1048         if (efi_is_event(event) != EFI_SUCCESS ||
1049             event->type & EVT_NOTIFY_SIGNAL)
1050                 return EFI_EXIT(EFI_INVALID_PARAMETER);
1051         if (!event->is_signaled)
1052                 efi_queue_event(event);
1053         if (event->is_signaled) {
1054                 event->is_signaled = false;
1055                 return EFI_EXIT(EFI_SUCCESS);
1056         }
1057         return EFI_EXIT(EFI_NOT_READY);
1058 }
1059
1060 /**
1061  * efi_search_obj() - find the internal EFI object for a handle
1062  * @handle: handle to find
1063  *
1064  * Return: EFI object
1065  */
1066 struct efi_object *efi_search_obj(const efi_handle_t handle)
1067 {
1068         struct efi_object *efiobj;
1069
1070         if (!handle)
1071                 return NULL;
1072
1073         list_for_each_entry(efiobj, &efi_obj_list, link) {
1074                 if (efiobj == handle)
1075                         return efiobj;
1076         }
1077         return NULL;
1078 }
1079
1080 /**
1081  * efi_open_protocol_info_entry() - create open protocol info entry and add it
1082  *                                  to a protocol
1083  * @handler: handler of a protocol
1084  *
1085  * Return: open protocol info entry
1086  */
1087 static struct efi_open_protocol_info_entry *efi_create_open_info(
1088                         struct efi_handler *handler)
1089 {
1090         struct efi_open_protocol_info_item *item;
1091
1092         item = calloc(1, sizeof(struct efi_open_protocol_info_item));
1093         if (!item)
1094                 return NULL;
1095         /* Append the item to the open protocol info list. */
1096         list_add_tail(&item->link, &handler->open_infos);
1097
1098         return &item->info;
1099 }
1100
1101 /**
1102  * efi_delete_open_info() - remove an open protocol info entry from a protocol
1103  * @item: open protocol info entry to delete
1104  *
1105  * Return: status code
1106  */
1107 static efi_status_t efi_delete_open_info(
1108                         struct efi_open_protocol_info_item *item)
1109 {
1110         list_del(&item->link);
1111         free(item);
1112         return EFI_SUCCESS;
1113 }
1114
1115 /**
1116  * efi_add_protocol() - install new protocol on a handle
1117  * @handle:             handle on which the protocol shall be installed
1118  * @protocol:           GUID of the protocol to be installed
1119  * @protocol_interface: interface of the protocol implementation
1120  *
1121  * Return: status code
1122  */
1123 efi_status_t efi_add_protocol(const efi_handle_t handle,
1124                               const efi_guid_t *protocol,
1125                               void *protocol_interface)
1126 {
1127         struct efi_object *efiobj;
1128         struct efi_handler *handler;
1129         efi_status_t ret;
1130         struct efi_register_notify_event *event;
1131
1132         efiobj = efi_search_obj(handle);
1133         if (!efiobj)
1134                 return EFI_INVALID_PARAMETER;
1135         ret = efi_search_protocol(handle, protocol, NULL);
1136         if (ret != EFI_NOT_FOUND)
1137                 return EFI_INVALID_PARAMETER;
1138         handler = calloc(1, sizeof(struct efi_handler));
1139         if (!handler)
1140                 return EFI_OUT_OF_RESOURCES;
1141         memcpy((void *)&handler->guid, protocol, sizeof(efi_guid_t));
1142         handler->protocol_interface = protocol_interface;
1143         INIT_LIST_HEAD(&handler->open_infos);
1144         list_add_tail(&handler->link, &efiobj->protocols);
1145
1146         /* Notify registered events */
1147         list_for_each_entry(event, &efi_register_notify_events, link) {
1148                 if (!guidcmp(protocol, &event->protocol)) {
1149                         struct efi_protocol_notification *notif;
1150
1151                         notif = calloc(1, sizeof(*notif));
1152                         if (!notif) {
1153                                 list_del(&handler->link);
1154                                 free(handler);
1155                                 return EFI_OUT_OF_RESOURCES;
1156                         }
1157                         notif->handle = handle;
1158                         list_add_tail(&notif->link, &event->handles);
1159                         event->event->is_signaled = false;
1160                         efi_signal_event(event->event);
1161                 }
1162         }
1163
1164         if (!guidcmp(&efi_guid_device_path, protocol))
1165                 EFI_PRINT("installed device path '%pD'\n", protocol_interface);
1166         return EFI_SUCCESS;
1167 }
1168
1169 /**
1170  * efi_install_protocol_interface() - install protocol interface
1171  * @handle:                  handle on which the protocol shall be installed
1172  * @protocol:                GUID of the protocol to be installed
1173  * @protocol_interface_type: type of the interface to be installed,
1174  *                           always EFI_NATIVE_INTERFACE
1175  * @protocol_interface:      interface of the protocol implementation
1176  *
1177  * This function implements the InstallProtocolInterface service.
1178  *
1179  * See the Unified Extensible Firmware Interface (UEFI) specification for
1180  * details.
1181  *
1182  * Return: status code
1183  */
1184 static efi_status_t EFIAPI efi_install_protocol_interface(
1185                         efi_handle_t *handle, const efi_guid_t *protocol,
1186                         int protocol_interface_type, void *protocol_interface)
1187 {
1188         efi_status_t r;
1189
1190         EFI_ENTRY("%p, %pUs, %d, %p", handle, protocol, protocol_interface_type,
1191                   protocol_interface);
1192
1193         if (!handle || !protocol ||
1194             protocol_interface_type != EFI_NATIVE_INTERFACE) {
1195                 r = EFI_INVALID_PARAMETER;
1196                 goto out;
1197         }
1198
1199         /* Create new handle if requested. */
1200         if (!*handle) {
1201                 r = efi_create_handle(handle);
1202                 if (r != EFI_SUCCESS)
1203                         goto out;
1204                 EFI_PRINT("new handle %p\n", *handle);
1205         } else {
1206                 EFI_PRINT("handle %p\n", *handle);
1207         }
1208         /* Add new protocol */
1209         r = efi_add_protocol(*handle, protocol, protocol_interface);
1210 out:
1211         return EFI_EXIT(r);
1212 }
1213
1214 /**
1215  * efi_get_drivers() - get all drivers associated to a controller
1216  * @handle:               handle of the controller
1217  * @protocol:             protocol GUID (optional)
1218  * @number_of_drivers:    number of child controllers
1219  * @driver_handle_buffer: handles of the the drivers
1220  *
1221  * The allocated buffer has to be freed with free().
1222  *
1223  * Return: status code
1224  */
1225 static efi_status_t efi_get_drivers(efi_handle_t handle,
1226                                     const efi_guid_t *protocol,
1227                                     efi_uintn_t *number_of_drivers,
1228                                     efi_handle_t **driver_handle_buffer)
1229 {
1230         struct efi_handler *handler;
1231         struct efi_open_protocol_info_item *item;
1232         efi_uintn_t count = 0, i;
1233         bool duplicate;
1234
1235         /* Count all driver associations */
1236         list_for_each_entry(handler, &handle->protocols, link) {
1237                 if (protocol && guidcmp(&handler->guid, protocol))
1238                         continue;
1239                 list_for_each_entry(item, &handler->open_infos, link) {
1240                         if (item->info.attributes &
1241                             EFI_OPEN_PROTOCOL_BY_DRIVER)
1242                                 ++count;
1243                 }
1244         }
1245         *number_of_drivers = 0;
1246         if (!count) {
1247                 *driver_handle_buffer = NULL;
1248                 return EFI_SUCCESS;
1249         }
1250         /*
1251          * Create buffer. In case of duplicate driver assignments the buffer
1252          * will be too large. But that does not harm.
1253          */
1254         *driver_handle_buffer = calloc(count, sizeof(efi_handle_t));
1255         if (!*driver_handle_buffer)
1256                 return EFI_OUT_OF_RESOURCES;
1257         /* Collect unique driver handles */
1258         list_for_each_entry(handler, &handle->protocols, link) {
1259                 if (protocol && guidcmp(&handler->guid, protocol))
1260                         continue;
1261                 list_for_each_entry(item, &handler->open_infos, link) {
1262                         if (item->info.attributes &
1263                             EFI_OPEN_PROTOCOL_BY_DRIVER) {
1264                                 /* Check this is a new driver */
1265                                 duplicate = false;
1266                                 for (i = 0; i < *number_of_drivers; ++i) {
1267                                         if ((*driver_handle_buffer)[i] ==
1268                                             item->info.agent_handle)
1269                                                 duplicate = true;
1270                                 }
1271                                 /* Copy handle to buffer */
1272                                 if (!duplicate) {
1273                                         i = (*number_of_drivers)++;
1274                                         (*driver_handle_buffer)[i] =
1275                                                 item->info.agent_handle;
1276                                 }
1277                         }
1278                 }
1279         }
1280         return EFI_SUCCESS;
1281 }
1282
1283 /**
1284  * efi_disconnect_all_drivers() - disconnect all drivers from a controller
1285  * @handle:       handle of the controller
1286  * @protocol:     protocol GUID (optional)
1287  * @child_handle: handle of the child to destroy
1288  *
1289  * This function implements the DisconnectController service.
1290  *
1291  * See the Unified Extensible Firmware Interface (UEFI) specification for
1292  * details.
1293  *
1294  * Return: status code
1295  */
1296 static efi_status_t efi_disconnect_all_drivers
1297                                 (efi_handle_t handle,
1298                                  const efi_guid_t *protocol,
1299                                  efi_handle_t child_handle)
1300 {
1301         efi_uintn_t number_of_drivers;
1302         efi_handle_t *driver_handle_buffer;
1303         efi_status_t r, ret;
1304
1305         ret = efi_get_drivers(handle, protocol, &number_of_drivers,
1306                               &driver_handle_buffer);
1307         if (ret != EFI_SUCCESS)
1308                 return ret;
1309         if (!number_of_drivers)
1310                 return EFI_SUCCESS;
1311         ret = EFI_NOT_FOUND;
1312         while (number_of_drivers) {
1313                 r = EFI_CALL(efi_disconnect_controller(
1314                                 handle,
1315                                 driver_handle_buffer[--number_of_drivers],
1316                                 child_handle));
1317                 if (r == EFI_SUCCESS)
1318                         ret = r;
1319         }
1320         free(driver_handle_buffer);
1321         return ret;
1322 }
1323
1324 /**
1325  * efi_uninstall_protocol() - uninstall protocol interface
1326  *
1327  * @handle:             handle from which the protocol shall be removed
1328  * @protocol:           GUID of the protocol to be removed
1329  * @protocol_interface: interface to be removed
1330  *
1331  * This function DOES NOT delete a handle without installed protocol.
1332  *
1333  * Return: status code
1334  */
1335 static efi_status_t efi_uninstall_protocol
1336                         (efi_handle_t handle, const efi_guid_t *protocol,
1337                          void *protocol_interface)
1338 {
1339         struct efi_object *efiobj;
1340         struct efi_handler *handler;
1341         struct efi_open_protocol_info_item *item;
1342         struct efi_open_protocol_info_item *pos;
1343         efi_status_t r;
1344
1345         /* Check handle */
1346         efiobj = efi_search_obj(handle);
1347         if (!efiobj) {
1348                 r = EFI_INVALID_PARAMETER;
1349                 goto out;
1350         }
1351         /* Find the protocol on the handle */
1352         r = efi_search_protocol(handle, protocol, &handler);
1353         if (r != EFI_SUCCESS)
1354                 goto out;
1355         /* Disconnect controllers */
1356         efi_disconnect_all_drivers(efiobj, protocol, NULL);
1357         /* Close protocol */
1358         list_for_each_entry_safe(item, pos, &handler->open_infos, link) {
1359                 if (item->info.attributes ==
1360                         EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL ||
1361                     item->info.attributes == EFI_OPEN_PROTOCOL_GET_PROTOCOL ||
1362                     item->info.attributes == EFI_OPEN_PROTOCOL_TEST_PROTOCOL)
1363                         list_del(&item->link);
1364         }
1365         if (!list_empty(&handler->open_infos)) {
1366                 r =  EFI_ACCESS_DENIED;
1367                 goto out;
1368         }
1369         r = efi_remove_protocol(handle, protocol, protocol_interface);
1370 out:
1371         return r;
1372 }
1373
1374 /**
1375  * efi_uninstall_protocol_interface() - uninstall protocol interface
1376  * @handle:             handle from which the protocol shall be removed
1377  * @protocol:           GUID of the protocol to be removed
1378  * @protocol_interface: interface to be removed
1379  *
1380  * This function implements the UninstallProtocolInterface service.
1381  *
1382  * See the Unified Extensible Firmware Interface (UEFI) specification for
1383  * details.
1384  *
1385  * Return: status code
1386  */
1387 static efi_status_t EFIAPI efi_uninstall_protocol_interface
1388                         (efi_handle_t handle, const efi_guid_t *protocol,
1389                          void *protocol_interface)
1390 {
1391         efi_status_t ret;
1392
1393         EFI_ENTRY("%p, %pUs, %p", handle, protocol, protocol_interface);
1394
1395         ret = efi_uninstall_protocol(handle, protocol, protocol_interface);
1396         if (ret != EFI_SUCCESS)
1397                 goto out;
1398
1399         /* If the last protocol has been removed, delete the handle. */
1400         if (list_empty(&handle->protocols)) {
1401                 list_del(&handle->link);
1402                 free(handle);
1403         }
1404 out:
1405         return EFI_EXIT(ret);
1406 }
1407
1408 /**
1409  * efi_register_protocol_notify() - register an event for notification when a
1410  *                                  protocol is installed.
1411  * @protocol:     GUID of the protocol whose installation shall be notified
1412  * @event:        event to be signaled upon installation of the protocol
1413  * @registration: key for retrieving the registration information
1414  *
1415  * This function implements the RegisterProtocolNotify service.
1416  * See the Unified Extensible Firmware Interface (UEFI) specification
1417  * for details.
1418  *
1419  * Return: status code
1420  */
1421 efi_status_t EFIAPI efi_register_protocol_notify(const efi_guid_t *protocol,
1422                                                  struct efi_event *event,
1423                                                  void **registration)
1424 {
1425         struct efi_register_notify_event *item;
1426         efi_status_t ret = EFI_SUCCESS;
1427
1428         EFI_ENTRY("%pUs, %p, %p", protocol, event, registration);
1429
1430         if (!protocol || !event || !registration) {
1431                 ret = EFI_INVALID_PARAMETER;
1432                 goto out;
1433         }
1434
1435         item = calloc(1, sizeof(struct efi_register_notify_event));
1436         if (!item) {
1437                 ret = EFI_OUT_OF_RESOURCES;
1438                 goto out;
1439         }
1440
1441         item->event = event;
1442         guidcpy(&item->protocol, protocol);
1443         INIT_LIST_HEAD(&item->handles);
1444
1445         list_add_tail(&item->link, &efi_register_notify_events);
1446
1447         *registration = item;
1448 out:
1449         return EFI_EXIT(ret);
1450 }
1451
1452 /**
1453  * efi_search() - determine if an EFI handle implements a protocol
1454  *
1455  * @search_type: selection criterion
1456  * @protocol:    GUID of the protocol
1457  * @handle:      handle
1458  *
1459  * See the documentation of the LocateHandle service in the UEFI specification.
1460  *
1461  * Return: 0 if the handle implements the protocol
1462  */
1463 static int efi_search(enum efi_locate_search_type search_type,
1464                       const efi_guid_t *protocol, efi_handle_t handle)
1465 {
1466         efi_status_t ret;
1467
1468         switch (search_type) {
1469         case ALL_HANDLES:
1470                 return 0;
1471         case BY_PROTOCOL:
1472                 ret = efi_search_protocol(handle, protocol, NULL);
1473                 return (ret != EFI_SUCCESS);
1474         default:
1475                 /* Invalid search type */
1476                 return -1;
1477         }
1478 }
1479
1480 /**
1481  * efi_check_register_notify_event() - check if registration key is valid
1482  *
1483  * Check that a pointer is a valid registration key as returned by
1484  * RegisterProtocolNotify().
1485  *
1486  * @key:        registration key
1487  * Return:      valid registration key or NULL
1488  */
1489 static struct efi_register_notify_event *efi_check_register_notify_event
1490                                                                 (void *key)
1491 {
1492         struct efi_register_notify_event *event;
1493
1494         list_for_each_entry(event, &efi_register_notify_events, link) {
1495                 if (event == (struct efi_register_notify_event *)key)
1496                         return event;
1497         }
1498         return NULL;
1499 }
1500
1501 /**
1502  * efi_locate_handle() - locate handles implementing a protocol
1503  *
1504  * @search_type:        selection criterion
1505  * @protocol:           GUID of the protocol
1506  * @search_key:         registration key
1507  * @buffer_size:        size of the buffer to receive the handles in bytes
1508  * @buffer:             buffer to receive the relevant handles
1509  *
1510  * This function is meant for U-Boot internal calls. For the API implementation
1511  * of the LocateHandle service see efi_locate_handle_ext.
1512  *
1513  * Return: status code
1514  */
1515 static efi_status_t efi_locate_handle(
1516                         enum efi_locate_search_type search_type,
1517                         const efi_guid_t *protocol, void *search_key,
1518                         efi_uintn_t *buffer_size, efi_handle_t *buffer)
1519 {
1520         struct efi_object *efiobj;
1521         efi_uintn_t size = 0;
1522         struct efi_register_notify_event *event;
1523         struct efi_protocol_notification *handle = NULL;
1524
1525         /* Check parameters */
1526         switch (search_type) {
1527         case ALL_HANDLES:
1528                 break;
1529         case BY_REGISTER_NOTIFY:
1530                 if (!search_key)
1531                         return EFI_INVALID_PARAMETER;
1532                 /* Check that the registration key is valid */
1533                 event = efi_check_register_notify_event(search_key);
1534                 if (!event)
1535                         return EFI_INVALID_PARAMETER;
1536                 break;
1537         case BY_PROTOCOL:
1538                 if (!protocol)
1539                         return EFI_INVALID_PARAMETER;
1540                 break;
1541         default:
1542                 return EFI_INVALID_PARAMETER;
1543         }
1544
1545         /* Count how much space we need */
1546         if (search_type == BY_REGISTER_NOTIFY) {
1547                 if (list_empty(&event->handles))
1548                         return EFI_NOT_FOUND;
1549                 handle = list_first_entry(&event->handles,
1550                                           struct efi_protocol_notification,
1551                                           link);
1552                 efiobj = handle->handle;
1553                 size += sizeof(void *);
1554         } else {
1555                 list_for_each_entry(efiobj, &efi_obj_list, link) {
1556                         if (!efi_search(search_type, protocol, efiobj))
1557                                 size += sizeof(void *);
1558                 }
1559                 if (size == 0)
1560                         return EFI_NOT_FOUND;
1561         }
1562
1563         if (!buffer_size)
1564                 return EFI_INVALID_PARAMETER;
1565
1566         if (*buffer_size < size) {
1567                 *buffer_size = size;
1568                 return EFI_BUFFER_TOO_SMALL;
1569         }
1570
1571         *buffer_size = size;
1572
1573         /* The buffer size is sufficient but there is no buffer */
1574         if (!buffer)
1575                 return EFI_INVALID_PARAMETER;
1576
1577         /* Then fill the array */
1578         if (search_type == BY_REGISTER_NOTIFY) {
1579                 *buffer = efiobj;
1580                 list_del(&handle->link);
1581         } else {
1582                 list_for_each_entry(efiobj, &efi_obj_list, link) {
1583                         if (!efi_search(search_type, protocol, efiobj))
1584                                 *buffer++ = efiobj;
1585                 }
1586         }
1587
1588         return EFI_SUCCESS;
1589 }
1590
1591 /**
1592  * efi_locate_handle_ext() - locate handles implementing a protocol.
1593  * @search_type: selection criterion
1594  * @protocol:    GUID of the protocol
1595  * @search_key:  registration key
1596  * @buffer_size: size of the buffer to receive the handles in bytes
1597  * @buffer:      buffer to receive the relevant handles
1598  *
1599  * This function implements the LocateHandle service.
1600  *
1601  * See the Unified Extensible Firmware Interface (UEFI) specification for
1602  * details.
1603  *
1604  * Return: 0 if the handle implements the protocol
1605  */
1606 static efi_status_t EFIAPI efi_locate_handle_ext(
1607                         enum efi_locate_search_type search_type,
1608                         const efi_guid_t *protocol, void *search_key,
1609                         efi_uintn_t *buffer_size, efi_handle_t *buffer)
1610 {
1611         EFI_ENTRY("%d, %pUs, %p, %p, %p", search_type, protocol, search_key,
1612                   buffer_size, buffer);
1613
1614         return EFI_EXIT(efi_locate_handle(search_type, protocol, search_key,
1615                         buffer_size, buffer));
1616 }
1617
1618 /**
1619  * efi_remove_configuration_table() - collapses configuration table entries,
1620  *                                    removing index i
1621  *
1622  * @i: index of the table entry to be removed
1623  */
1624 static void efi_remove_configuration_table(int i)
1625 {
1626         struct efi_configuration_table *this = &systab.tables[i];
1627         struct efi_configuration_table *next = &systab.tables[i + 1];
1628         struct efi_configuration_table *end = &systab.tables[systab.nr_tables];
1629
1630         memmove(this, next, (ulong)end - (ulong)next);
1631         systab.nr_tables--;
1632 }
1633
1634 /**
1635  * efi_install_configuration_table() - adds, updates, or removes a
1636  *                                     configuration table
1637  * @guid:  GUID of the installed table
1638  * @table: table to be installed
1639  *
1640  * This function is used for internal calls. For the API implementation of the
1641  * InstallConfigurationTable service see efi_install_configuration_table_ext.
1642  *
1643  * Return: status code
1644  */
1645 efi_status_t efi_install_configuration_table(const efi_guid_t *guid,
1646                                              void *table)
1647 {
1648         struct efi_event *evt;
1649         int i;
1650
1651         if (!guid)
1652                 return EFI_INVALID_PARAMETER;
1653
1654         /* Check for GUID override */
1655         for (i = 0; i < systab.nr_tables; i++) {
1656                 if (!guidcmp(guid, &systab.tables[i].guid)) {
1657                         if (table)
1658                                 systab.tables[i].table = table;
1659                         else
1660                                 efi_remove_configuration_table(i);
1661                         goto out;
1662                 }
1663         }
1664
1665         if (!table)
1666                 return EFI_NOT_FOUND;
1667
1668         /* No override, check for overflow */
1669         if (i >= EFI_MAX_CONFIGURATION_TABLES)
1670                 return EFI_OUT_OF_RESOURCES;
1671
1672         /* Add a new entry */
1673         guidcpy(&systab.tables[i].guid, guid);
1674         systab.tables[i].table = table;
1675         systab.nr_tables = i + 1;
1676
1677 out:
1678         /* systab.nr_tables may have changed. So we need to update the CRC32 */
1679         efi_update_table_header_crc32(&systab.hdr);
1680
1681         /* Notify that the configuration table was changed */
1682         list_for_each_entry(evt, &efi_events, link) {
1683                 if (evt->group && !guidcmp(evt->group, guid)) {
1684                         efi_signal_event(evt);
1685                         break;
1686                 }
1687         }
1688
1689         return EFI_SUCCESS;
1690 }
1691
1692 /**
1693  * efi_install_configuration_table_ex() - Adds, updates, or removes a
1694  *                                        configuration table.
1695  * @guid:  GUID of the installed table
1696  * @table: table to be installed
1697  *
1698  * This function implements the InstallConfigurationTable service.
1699  *
1700  * See the Unified Extensible Firmware Interface (UEFI) specification for
1701  * details.
1702  *
1703  * Return: status code
1704  */
1705 static efi_status_t
1706 EFIAPI efi_install_configuration_table_ext(const efi_guid_t *guid,
1707                                            void *table)
1708 {
1709         EFI_ENTRY("%pUs, %p", guid, table);
1710         return EFI_EXIT(efi_install_configuration_table(guid, table));
1711 }
1712
1713 /**
1714  * efi_setup_loaded_image() - initialize a loaded image
1715  *
1716  * Initialize a loaded_image_info and loaded_image_info object with correct
1717  * protocols, boot-device, etc.
1718  *
1719  * In case of an error \*handle_ptr and \*info_ptr are set to NULL and an error
1720  * code is returned.
1721  *
1722  * @device_path:        device path of the loaded image
1723  * @file_path:          file path of the loaded image
1724  * @handle_ptr:         handle of the loaded image
1725  * @info_ptr:           loaded image protocol
1726  * Return:              status code
1727  */
1728 efi_status_t efi_setup_loaded_image(struct efi_device_path *device_path,
1729                                     struct efi_device_path *file_path,
1730                                     struct efi_loaded_image_obj **handle_ptr,
1731                                     struct efi_loaded_image **info_ptr)
1732 {
1733         efi_status_t ret;
1734         struct efi_loaded_image *info = NULL;
1735         struct efi_loaded_image_obj *obj = NULL;
1736         struct efi_device_path *dp;
1737
1738         /* In case of EFI_OUT_OF_RESOURCES avoid illegal free by caller. */
1739         *handle_ptr = NULL;
1740         *info_ptr = NULL;
1741
1742         info = calloc(1, sizeof(*info));
1743         if (!info)
1744                 return EFI_OUT_OF_RESOURCES;
1745         obj = calloc(1, sizeof(*obj));
1746         if (!obj) {
1747                 free(info);
1748                 return EFI_OUT_OF_RESOURCES;
1749         }
1750         obj->header.type = EFI_OBJECT_TYPE_LOADED_IMAGE;
1751
1752         /* Add internal object to object list */
1753         efi_add_handle(&obj->header);
1754
1755         info->revision =  EFI_LOADED_IMAGE_PROTOCOL_REVISION;
1756         info->file_path = file_path;
1757         info->system_table = &systab;
1758
1759         if (device_path) {
1760                 info->device_handle = efi_dp_find_obj(device_path, NULL, NULL);
1761
1762                 dp = efi_dp_append(device_path, file_path);
1763                 if (!dp) {
1764                         ret = EFI_OUT_OF_RESOURCES;
1765                         goto failure;
1766                 }
1767         } else {
1768                 dp = NULL;
1769         }
1770         ret = efi_add_protocol(&obj->header,
1771                                &efi_guid_loaded_image_device_path, dp);
1772         if (ret != EFI_SUCCESS)
1773                 goto failure;
1774
1775         /*
1776          * When asking for the loaded_image interface, just
1777          * return handle which points to loaded_image_info
1778          */
1779         ret = efi_add_protocol(&obj->header,
1780                                &efi_guid_loaded_image, info);
1781         if (ret != EFI_SUCCESS)
1782                 goto failure;
1783
1784         *info_ptr = info;
1785         *handle_ptr = obj;
1786
1787         return ret;
1788 failure:
1789         printf("ERROR: Failure to install protocols for loaded image\n");
1790         efi_delete_handle(&obj->header);
1791         free(info);
1792         return ret;
1793 }
1794
1795 /**
1796  * efi_locate_device_path() - Get the device path and handle of an device
1797  *                            implementing a protocol
1798  * @protocol:    GUID of the protocol
1799  * @device_path: device path
1800  * @device:      handle of the device
1801  *
1802  * This function implements the LocateDevicePath service.
1803  *
1804  * See the Unified Extensible Firmware Interface (UEFI) specification for
1805  * details.
1806  *
1807  * Return: status code
1808  */
1809 efi_status_t EFIAPI efi_locate_device_path(const efi_guid_t *protocol,
1810                                            struct efi_device_path **device_path,
1811                                            efi_handle_t *device)
1812 {
1813         struct efi_device_path *dp;
1814         size_t i;
1815         struct efi_handler *handler;
1816         efi_handle_t *handles;
1817         size_t len, len_dp;
1818         size_t len_best = 0;
1819         efi_uintn_t no_handles;
1820         u8 *remainder;
1821         efi_status_t ret;
1822
1823         EFI_ENTRY("%pUs, %p, %p", protocol, device_path, device);
1824
1825         if (!protocol || !device_path || !*device_path) {
1826                 ret = EFI_INVALID_PARAMETER;
1827                 goto out;
1828         }
1829
1830         /* Find end of device path */
1831         len = efi_dp_instance_size(*device_path);
1832
1833         /* Get all handles implementing the protocol */
1834         ret = EFI_CALL(efi_locate_handle_buffer(BY_PROTOCOL, protocol, NULL,
1835                                                 &no_handles, &handles));
1836         if (ret != EFI_SUCCESS)
1837                 goto out;
1838
1839         for (i = 0; i < no_handles; ++i) {
1840                 /* Find the device path protocol */
1841                 ret = efi_search_protocol(handles[i], &efi_guid_device_path,
1842                                           &handler);
1843                 if (ret != EFI_SUCCESS)
1844                         continue;
1845                 dp = (struct efi_device_path *)handler->protocol_interface;
1846                 len_dp = efi_dp_instance_size(dp);
1847                 /*
1848                  * This handle can only be a better fit
1849                  * if its device path length is longer than the best fit and
1850                  * if its device path length is shorter of equal the searched
1851                  * device path.
1852                  */
1853                 if (len_dp <= len_best || len_dp > len)
1854                         continue;
1855                 /* Check if dp is a subpath of device_path */
1856                 if (memcmp(*device_path, dp, len_dp))
1857                         continue;
1858                 if (!device) {
1859                         ret = EFI_INVALID_PARAMETER;
1860                         goto out;
1861                 }
1862                 *device = handles[i];
1863                 len_best = len_dp;
1864         }
1865         if (len_best) {
1866                 remainder = (u8 *)*device_path + len_best;
1867                 *device_path = (struct efi_device_path *)remainder;
1868                 ret = EFI_SUCCESS;
1869         } else {
1870                 ret = EFI_NOT_FOUND;
1871         }
1872 out:
1873         return EFI_EXIT(ret);
1874 }
1875
1876 /**
1877  * efi_load_image_from_file() - load an image from file system
1878  *
1879  * Read a file into a buffer allocated as EFI_BOOT_SERVICES_DATA. It is the
1880  * callers obligation to update the memory type as needed.
1881  *
1882  * @file_path:          the path of the image to load
1883  * @buffer:             buffer containing the loaded image
1884  * @size:               size of the loaded image
1885  * Return:              status code
1886  */
1887 static
1888 efi_status_t efi_load_image_from_file(struct efi_device_path *file_path,
1889                                       void **buffer, efi_uintn_t *size)
1890 {
1891         struct efi_file_handle *f;
1892         efi_status_t ret;
1893         u64 addr;
1894         efi_uintn_t bs;
1895
1896         /* Open file */
1897         f = efi_file_from_path(file_path);
1898         if (!f)
1899                 return EFI_NOT_FOUND;
1900
1901         ret = efi_file_size(f, &bs);
1902         if (ret != EFI_SUCCESS)
1903                 goto error;
1904
1905         /*
1906          * When reading the file we do not yet know if it contains an
1907          * application, a boottime driver, or a runtime driver. So here we
1908          * allocate a buffer as EFI_BOOT_SERVICES_DATA. The caller has to
1909          * update the reservation according to the image type.
1910          */
1911         ret = efi_allocate_pages(EFI_ALLOCATE_ANY_PAGES,
1912                                  EFI_BOOT_SERVICES_DATA,
1913                                  efi_size_in_pages(bs), &addr);
1914         if (ret != EFI_SUCCESS) {
1915                 ret = EFI_OUT_OF_RESOURCES;
1916                 goto error;
1917         }
1918
1919         /* Read file */
1920         EFI_CALL(ret = f->read(f, &bs, (void *)(uintptr_t)addr));
1921         if (ret != EFI_SUCCESS)
1922                 efi_free_pages(addr, efi_size_in_pages(bs));
1923         *buffer = (void *)(uintptr_t)addr;
1924         *size = bs;
1925 error:
1926         EFI_CALL(f->close(f));
1927         return ret;
1928 }
1929
1930 /**
1931  * efi_load_image_from_path() - load an image using a file path
1932  *
1933  * Read a file into a buffer allocated as EFI_BOOT_SERVICES_DATA. It is the
1934  * callers obligation to update the memory type as needed.
1935  *
1936  * @boot_policy:        true for request originating from the boot manager
1937  * @file_path:          the path of the image to load
1938  * @buffer:             buffer containing the loaded image
1939  * @size:               size of the loaded image
1940  * Return:              status code
1941  */
1942 static
1943 efi_status_t efi_load_image_from_path(bool boot_policy,
1944                                       struct efi_device_path *file_path,
1945                                       void **buffer, efi_uintn_t *size)
1946 {
1947         efi_handle_t device;
1948         efi_status_t ret;
1949         struct efi_device_path *dp, *rem;
1950         struct efi_load_file_protocol *load_file_protocol = NULL;
1951         efi_uintn_t buffer_size;
1952         uint64_t addr, pages;
1953         const efi_guid_t *guid;
1954         struct efi_handler *handler;
1955
1956         /* In case of failure nothing is returned */
1957         *buffer = NULL;
1958         *size = 0;
1959
1960         dp = file_path;
1961         device = efi_dp_find_obj(dp, NULL, &rem);
1962         ret = efi_search_protocol(device, &efi_simple_file_system_protocol_guid,
1963                                   NULL);
1964         if (ret == EFI_SUCCESS)
1965                 return efi_load_image_from_file(file_path, buffer, size);
1966
1967         ret = efi_search_protocol(device, &efi_guid_load_file_protocol, NULL);
1968         if (ret == EFI_SUCCESS) {
1969                 guid = &efi_guid_load_file_protocol;
1970         } else if (!boot_policy) {
1971                 guid = &efi_guid_load_file2_protocol;
1972                 ret = efi_search_protocol(device, guid, NULL);
1973         }
1974         if (ret != EFI_SUCCESS)
1975                 return EFI_NOT_FOUND;
1976         ret = efi_search_protocol(device, guid, &handler);
1977         if (ret != EFI_SUCCESS)
1978                 return EFI_NOT_FOUND;
1979         buffer_size = 0;
1980         load_file_protocol = handler->protocol_interface;
1981         ret = EFI_CALL(load_file_protocol->load_file(
1982                                         load_file_protocol, rem, boot_policy,
1983                                         &buffer_size, NULL));
1984         if (ret != EFI_BUFFER_TOO_SMALL)
1985                 goto out;
1986         pages = efi_size_in_pages(buffer_size);
1987         ret = efi_allocate_pages(EFI_ALLOCATE_ANY_PAGES, EFI_BOOT_SERVICES_DATA,
1988                                  pages, &addr);
1989         if (ret != EFI_SUCCESS) {
1990                 ret = EFI_OUT_OF_RESOURCES;
1991                 goto out;
1992         }
1993         ret = EFI_CALL(load_file_protocol->load_file(
1994                                         load_file_protocol, rem, boot_policy,
1995                                         &buffer_size, (void *)(uintptr_t)addr));
1996         if (ret != EFI_SUCCESS)
1997                 efi_free_pages(addr, pages);
1998 out:
1999         efi_close_protocol(device, guid, efi_root, NULL);
2000         if (ret == EFI_SUCCESS) {
2001                 *buffer = (void *)(uintptr_t)addr;
2002                 *size = buffer_size;
2003         }
2004
2005         return ret;
2006 }
2007
2008 /**
2009  * efi_load_image() - load an EFI image into memory
2010  * @boot_policy:   true for request originating from the boot manager
2011  * @parent_image:  the caller's image handle
2012  * @file_path:     the path of the image to load
2013  * @source_buffer: memory location from which the image is installed
2014  * @source_size:   size of the memory area from which the image is installed
2015  * @image_handle:  handle for the newly installed image
2016  *
2017  * This function implements the LoadImage service.
2018  *
2019  * See the Unified Extensible Firmware Interface (UEFI) specification
2020  * for details.
2021  *
2022  * Return: status code
2023  */
2024 efi_status_t EFIAPI efi_load_image(bool boot_policy,
2025                                    efi_handle_t parent_image,
2026                                    struct efi_device_path *file_path,
2027                                    void *source_buffer,
2028                                    efi_uintn_t source_size,
2029                                    efi_handle_t *image_handle)
2030 {
2031         struct efi_device_path *dp, *fp;
2032         struct efi_loaded_image *info = NULL;
2033         struct efi_loaded_image_obj **image_obj =
2034                 (struct efi_loaded_image_obj **)image_handle;
2035         efi_status_t ret;
2036         void *dest_buffer;
2037
2038         EFI_ENTRY("%d, %p, %pD, %p, %zu, %p", boot_policy, parent_image,
2039                   file_path, source_buffer, source_size, image_handle);
2040
2041         if (!image_handle || (!source_buffer && !file_path) ||
2042             !efi_search_obj(parent_image) ||
2043             /* The parent image handle must refer to a loaded image */
2044             !parent_image->type) {
2045                 ret = EFI_INVALID_PARAMETER;
2046                 goto error;
2047         }
2048
2049         if (!source_buffer) {
2050                 ret = efi_load_image_from_path(boot_policy, file_path,
2051                                                &dest_buffer, &source_size);
2052                 if (ret != EFI_SUCCESS)
2053                         goto error;
2054         } else {
2055                 dest_buffer = source_buffer;
2056         }
2057         /* split file_path which contains both the device and file parts */
2058         efi_dp_split_file_path(file_path, &dp, &fp);
2059         ret = efi_setup_loaded_image(dp, fp, image_obj, &info);
2060         if (ret == EFI_SUCCESS)
2061                 ret = efi_load_pe(*image_obj, dest_buffer, source_size, info);
2062         if (!source_buffer)
2063                 /* Release buffer to which file was loaded */
2064                 efi_free_pages((uintptr_t)dest_buffer,
2065                                efi_size_in_pages(source_size));
2066         if (ret == EFI_SUCCESS || ret == EFI_SECURITY_VIOLATION) {
2067                 info->system_table = &systab;
2068                 info->parent_handle = parent_image;
2069         } else {
2070                 /* The image is invalid. Release all associated resources. */
2071                 efi_delete_handle(*image_handle);
2072                 *image_handle = NULL;
2073                 free(info);
2074         }
2075 error:
2076         return EFI_EXIT(ret);
2077 }
2078
2079 /**
2080  * efi_exit_caches() - fix up caches for EFI payloads if necessary
2081  */
2082 static void efi_exit_caches(void)
2083 {
2084 #if defined(CONFIG_EFI_GRUB_ARM32_WORKAROUND)
2085         /*
2086          * Boooting Linux via GRUB prior to version 2.04 fails on 32bit ARM if
2087          * caches are enabled.
2088          *
2089          * TODO:
2090          * According to the UEFI spec caches that can be managed via CP15
2091          * operations should be enabled. Caches requiring platform information
2092          * to manage should be disabled. This should not happen in
2093          * ExitBootServices() but before invoking any UEFI binary is invoked.
2094          *
2095          * We want to keep the current workaround while GRUB prior to version
2096          * 2.04 is still in use.
2097          */
2098         cleanup_before_linux();
2099 #endif
2100 }
2101
2102 /**
2103  * efi_exit_boot_services() - stop all boot services
2104  * @image_handle: handle of the loaded image
2105  * @map_key:      key of the memory map
2106  *
2107  * This function implements the ExitBootServices service.
2108  *
2109  * See the Unified Extensible Firmware Interface (UEFI) specification
2110  * for details.
2111  *
2112  * All timer events are disabled. For exit boot services events the
2113  * notification function is called. The boot services are disabled in the
2114  * system table.
2115  *
2116  * Return: status code
2117  */
2118 static efi_status_t EFIAPI efi_exit_boot_services(efi_handle_t image_handle,
2119                                                   efi_uintn_t map_key)
2120 {
2121         struct efi_event *evt, *next_event;
2122         efi_status_t ret = EFI_SUCCESS;
2123
2124         EFI_ENTRY("%p, %zx", image_handle, map_key);
2125
2126         /* Check that the caller has read the current memory map */
2127         if (map_key != efi_memory_map_key) {
2128                 ret = EFI_INVALID_PARAMETER;
2129                 goto out;
2130         }
2131
2132         /* Check if ExitBootServices has already been called */
2133         if (!systab.boottime)
2134                 goto out;
2135
2136         /* Notify EFI_EVENT_GROUP_BEFORE_EXIT_BOOT_SERVICES event group. */
2137         list_for_each_entry(evt, &efi_events, link) {
2138                 if (evt->group &&
2139                     !guidcmp(evt->group,
2140                              &efi_guid_event_group_before_exit_boot_services)) {
2141                         efi_signal_event(evt);
2142                         break;
2143                 }
2144         }
2145
2146         /* Stop all timer related activities */
2147         timers_enabled = false;
2148
2149         /* Add related events to the event group */
2150         list_for_each_entry(evt, &efi_events, link) {
2151                 if (evt->type == EVT_SIGNAL_EXIT_BOOT_SERVICES)
2152                         evt->group = &efi_guid_event_group_exit_boot_services;
2153         }
2154         /* Notify that ExitBootServices is invoked. */
2155         list_for_each_entry(evt, &efi_events, link) {
2156                 if (evt->group &&
2157                     !guidcmp(evt->group,
2158                              &efi_guid_event_group_exit_boot_services)) {
2159                         efi_signal_event(evt);
2160                         break;
2161                 }
2162         }
2163
2164         /* Make sure that notification functions are not called anymore */
2165         efi_tpl = TPL_HIGH_LEVEL;
2166
2167         /* Notify variable services */
2168         efi_variables_boot_exit_notify();
2169
2170         /* Remove all events except EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE */
2171         list_for_each_entry_safe(evt, next_event, &efi_events, link) {
2172                 if (evt->type != EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE)
2173                         list_del(&evt->link);
2174         }
2175
2176         if (!efi_st_keep_devices) {
2177                 bootm_disable_interrupts();
2178                 if (IS_ENABLED(CONFIG_USB_DEVICE))
2179                         udc_disconnect();
2180                 board_quiesce_devices();
2181                 dm_remove_devices_flags(DM_REMOVE_ACTIVE_ALL);
2182         }
2183
2184         /* Patch out unsupported runtime function */
2185         efi_runtime_detach();
2186
2187         /* Fix up caches for EFI payloads if necessary */
2188         efi_exit_caches();
2189
2190         /* Disable boot time services */
2191         systab.con_in_handle = NULL;
2192         systab.con_in = NULL;
2193         systab.con_out_handle = NULL;
2194         systab.con_out = NULL;
2195         systab.stderr_handle = NULL;
2196         systab.std_err = NULL;
2197         systab.boottime = NULL;
2198
2199         /* Recalculate CRC32 */
2200         efi_update_table_header_crc32(&systab.hdr);
2201
2202         /* Give the payload some time to boot */
2203         efi_set_watchdog(0);
2204         schedule();
2205 out:
2206         if (IS_ENABLED(CONFIG_EFI_TCG2_PROTOCOL)) {
2207                 if (ret != EFI_SUCCESS)
2208                         efi_tcg2_notify_exit_boot_services_failed();
2209         }
2210
2211         return EFI_EXIT(ret);
2212 }
2213
2214 /**
2215  * efi_get_next_monotonic_count() - get next value of the counter
2216  * @count: returned value of the counter
2217  *
2218  * This function implements the NextMonotonicCount service.
2219  *
2220  * See the Unified Extensible Firmware Interface (UEFI) specification for
2221  * details.
2222  *
2223  * Return: status code
2224  */
2225 static efi_status_t EFIAPI efi_get_next_monotonic_count(uint64_t *count)
2226 {
2227         static uint64_t mono;
2228         efi_status_t ret;
2229
2230         EFI_ENTRY("%p", count);
2231         if (!count) {
2232                 ret = EFI_INVALID_PARAMETER;
2233                 goto out;
2234         }
2235         *count = mono++;
2236         ret = EFI_SUCCESS;
2237 out:
2238         return EFI_EXIT(ret);
2239 }
2240
2241 /**
2242  * efi_stall() - sleep
2243  * @microseconds: period to sleep in microseconds
2244  *
2245  * This function implements the Stall service.
2246  *
2247  * See the Unified Extensible Firmware Interface (UEFI) specification for
2248  * details.
2249  *
2250  * Return:  status code
2251  */
2252 static efi_status_t EFIAPI efi_stall(unsigned long microseconds)
2253 {
2254         u64 end_tick;
2255
2256         EFI_ENTRY("%ld", microseconds);
2257
2258         end_tick = get_ticks() + usec_to_tick(microseconds);
2259         while (get_ticks() < end_tick)
2260                 efi_timer_check();
2261
2262         return EFI_EXIT(EFI_SUCCESS);
2263 }
2264
2265 /**
2266  * efi_set_watchdog_timer() - reset the watchdog timer
2267  * @timeout:       seconds before reset by watchdog
2268  * @watchdog_code: code to be logged when resetting
2269  * @data_size:     size of buffer in bytes
2270  * @watchdog_data: buffer with data describing the reset reason
2271  *
2272  * This function implements the SetWatchdogTimer service.
2273  *
2274  * See the Unified Extensible Firmware Interface (UEFI) specification for
2275  * details.
2276  *
2277  * Return: status code
2278  */
2279 static efi_status_t EFIAPI efi_set_watchdog_timer(unsigned long timeout,
2280                                                   uint64_t watchdog_code,
2281                                                   unsigned long data_size,
2282                                                   uint16_t *watchdog_data)
2283 {
2284         EFI_ENTRY("%ld, 0x%llx, %ld, %p", timeout, watchdog_code,
2285                   data_size, watchdog_data);
2286         return EFI_EXIT(efi_set_watchdog(timeout));
2287 }
2288
2289 /**
2290  * efi_close_protocol() - close a protocol
2291  * @handle:            handle on which the protocol shall be closed
2292  * @protocol:          GUID of the protocol to close
2293  * @agent_handle:      handle of the driver
2294  * @controller_handle: handle of the controller
2295  *
2296  * This is the function implementing the CloseProtocol service is for internal
2297  * usage in U-Boot. For API usage wrapper efi_close_protocol_ext() is provided.
2298  *
2299  * See the Unified Extensible Firmware Interface (UEFI) specification for
2300  * details.
2301  *
2302  * Return: status code
2303  */
2304 efi_status_t efi_close_protocol(efi_handle_t handle, const efi_guid_t *protocol,
2305                                 efi_handle_t agent_handle,
2306                                 efi_handle_t controller_handle)
2307 {
2308         struct efi_handler *handler;
2309         struct efi_open_protocol_info_item *item;
2310         struct efi_open_protocol_info_item *pos;
2311         efi_status_t ret;
2312
2313         if (!efi_search_obj(agent_handle) ||
2314             (controller_handle && !efi_search_obj(controller_handle)))
2315                 return EFI_INVALID_PARAMETER;
2316         ret = efi_search_protocol(handle, protocol, &handler);
2317         if (ret != EFI_SUCCESS)
2318                 return ret;
2319
2320         ret = EFI_NOT_FOUND;
2321         list_for_each_entry_safe(item, pos, &handler->open_infos, link) {
2322                 if (item->info.agent_handle == agent_handle &&
2323                     item->info.controller_handle == controller_handle) {
2324                         efi_delete_open_info(item);
2325                         ret = EFI_SUCCESS;
2326                 }
2327         }
2328
2329         return ret;
2330 }
2331
2332 /**
2333  * efi_close_protocol_ext() - close a protocol
2334  * @handle:            handle on which the protocol shall be closed
2335  * @protocol:          GUID of the protocol to close
2336  * @agent_handle:      handle of the driver
2337  * @controller_handle: handle of the controller
2338  *
2339  * This function implements the CloseProtocol service.
2340  *
2341  * See the Unified Extensible Firmware Interface (UEFI) specification for
2342  * details.
2343  *
2344  * Return: status code
2345  */
2346 static efi_status_t EFIAPI
2347 efi_close_protocol_ext(efi_handle_t handle, const efi_guid_t *protocol,
2348                        efi_handle_t agent_handle,
2349                        efi_handle_t controller_handle)
2350 {
2351         efi_status_t ret;
2352
2353         EFI_ENTRY("%p, %pUs, %p, %p", handle, protocol, agent_handle,
2354                   controller_handle);
2355
2356         ret = efi_close_protocol(handle, protocol,
2357                                  agent_handle, controller_handle);
2358
2359         return EFI_EXIT(ret);
2360 }
2361
2362 /**
2363  * efi_open_protocol_information() - provide information about then open status
2364  *                                   of a protocol on a handle
2365  * @handle:       handle for which the information shall be retrieved
2366  * @protocol:     GUID of the protocol
2367  * @entry_buffer: buffer to receive the open protocol information
2368  * @entry_count:  number of entries available in the buffer
2369  *
2370  * This function implements the OpenProtocolInformation service.
2371  *
2372  * See the Unified Extensible Firmware Interface (UEFI) specification for
2373  * details.
2374  *
2375  * Return: status code
2376  */
2377 static efi_status_t EFIAPI efi_open_protocol_information(
2378                         efi_handle_t handle, const efi_guid_t *protocol,
2379                         struct efi_open_protocol_info_entry **entry_buffer,
2380                         efi_uintn_t *entry_count)
2381 {
2382         unsigned long buffer_size;
2383         unsigned long count;
2384         struct efi_handler *handler;
2385         struct efi_open_protocol_info_item *item;
2386         efi_status_t r;
2387
2388         EFI_ENTRY("%p, %pUs, %p, %p", handle, protocol, entry_buffer,
2389                   entry_count);
2390
2391         /* Check parameters */
2392         if (!entry_buffer) {
2393                 r = EFI_INVALID_PARAMETER;
2394                 goto out;
2395         }
2396         r = efi_search_protocol(handle, protocol, &handler);
2397         if (r != EFI_SUCCESS)
2398                 goto out;
2399
2400         /* Count entries */
2401         count = 0;
2402         list_for_each_entry(item, &handler->open_infos, link) {
2403                 if (item->info.open_count)
2404                         ++count;
2405         }
2406         *entry_count = count;
2407         *entry_buffer = NULL;
2408         if (!count) {
2409                 r = EFI_SUCCESS;
2410                 goto out;
2411         }
2412
2413         /* Copy entries */
2414         buffer_size = count * sizeof(struct efi_open_protocol_info_entry);
2415         r = efi_allocate_pool(EFI_BOOT_SERVICES_DATA, buffer_size,
2416                               (void **)entry_buffer);
2417         if (r != EFI_SUCCESS)
2418                 goto out;
2419         list_for_each_entry_reverse(item, &handler->open_infos, link) {
2420                 if (item->info.open_count)
2421                         (*entry_buffer)[--count] = item->info;
2422         }
2423 out:
2424         return EFI_EXIT(r);
2425 }
2426
2427 /**
2428  * efi_protocols_per_handle() - get protocols installed on a handle
2429  * @handle:                handle for which the information is retrieved
2430  * @protocol_buffer:       buffer with protocol GUIDs
2431  * @protocol_buffer_count: number of entries in the buffer
2432  *
2433  * This function implements the ProtocolsPerHandleService.
2434  *
2435  * See the Unified Extensible Firmware Interface (UEFI) specification for
2436  * details.
2437  *
2438  * Return: status code
2439  */
2440 static efi_status_t EFIAPI efi_protocols_per_handle(
2441                         efi_handle_t handle, efi_guid_t ***protocol_buffer,
2442                         efi_uintn_t *protocol_buffer_count)
2443 {
2444         unsigned long buffer_size;
2445         struct efi_object *efiobj;
2446         struct list_head *protocol_handle;
2447         efi_status_t r;
2448
2449         EFI_ENTRY("%p, %p, %p", handle, protocol_buffer,
2450                   protocol_buffer_count);
2451
2452         if (!handle || !protocol_buffer || !protocol_buffer_count)
2453                 return EFI_EXIT(EFI_INVALID_PARAMETER);
2454
2455         *protocol_buffer = NULL;
2456         *protocol_buffer_count = 0;
2457
2458         efiobj = efi_search_obj(handle);
2459         if (!efiobj)
2460                 return EFI_EXIT(EFI_INVALID_PARAMETER);
2461
2462         /* Count protocols */
2463         list_for_each(protocol_handle, &efiobj->protocols) {
2464                 ++*protocol_buffer_count;
2465         }
2466
2467         /* Copy GUIDs */
2468         if (*protocol_buffer_count) {
2469                 size_t j = 0;
2470
2471                 buffer_size = sizeof(efi_guid_t *) * *protocol_buffer_count;
2472                 r = efi_allocate_pool(EFI_BOOT_SERVICES_DATA, buffer_size,
2473                                       (void **)protocol_buffer);
2474                 if (r != EFI_SUCCESS)
2475                         return EFI_EXIT(r);
2476                 list_for_each(protocol_handle, &efiobj->protocols) {
2477                         struct efi_handler *protocol;
2478
2479                         protocol = list_entry(protocol_handle,
2480                                               struct efi_handler, link);
2481                         (*protocol_buffer)[j] = (void *)&protocol->guid;
2482                         ++j;
2483                 }
2484         }
2485
2486         return EFI_EXIT(EFI_SUCCESS);
2487 }
2488
2489 efi_status_t efi_locate_handle_buffer_int(enum efi_locate_search_type search_type,
2490                                           const efi_guid_t *protocol, void *search_key,
2491                                           efi_uintn_t *no_handles, efi_handle_t **buffer)
2492 {
2493         efi_status_t r;
2494         efi_uintn_t buffer_size = 0;
2495
2496         if (!no_handles || !buffer) {
2497                 r = EFI_INVALID_PARAMETER;
2498                 goto out;
2499         }
2500         *no_handles = 0;
2501         *buffer = NULL;
2502         r = efi_locate_handle(search_type, protocol, search_key, &buffer_size,
2503                               *buffer);
2504         if (r != EFI_BUFFER_TOO_SMALL)
2505                 goto out;
2506         r = efi_allocate_pool(EFI_BOOT_SERVICES_DATA, buffer_size,
2507                               (void **)buffer);
2508         if (r != EFI_SUCCESS)
2509                 goto out;
2510         r = efi_locate_handle(search_type, protocol, search_key, &buffer_size,
2511                               *buffer);
2512         if (r == EFI_SUCCESS)
2513                 *no_handles = buffer_size / sizeof(efi_handle_t);
2514 out:
2515         return r;
2516 }
2517
2518 /**
2519  * efi_locate_handle_buffer() - locate handles implementing a protocol
2520  * @search_type: selection criterion
2521  * @protocol:    GUID of the protocol
2522  * @search_key:  registration key
2523  * @no_handles:  number of returned handles
2524  * @buffer:      buffer with the returned handles
2525  *
2526  * This function implements the LocateHandleBuffer service.
2527  *
2528  * See the Unified Extensible Firmware Interface (UEFI) specification for
2529  * details.
2530  *
2531  * Return: status code
2532  */
2533 efi_status_t EFIAPI efi_locate_handle_buffer(
2534                         enum efi_locate_search_type search_type,
2535                         const efi_guid_t *protocol, void *search_key,
2536                         efi_uintn_t *no_handles, efi_handle_t **buffer)
2537 {
2538         efi_status_t r;
2539
2540         EFI_ENTRY("%d, %pUs, %p, %p, %p", search_type, protocol, search_key,
2541                   no_handles, buffer);
2542
2543         r = efi_locate_handle_buffer_int(search_type, protocol, search_key,
2544                                          no_handles, buffer);
2545
2546         return EFI_EXIT(r);
2547 }
2548
2549 /**
2550  * efi_locate_protocol() - find an interface implementing a protocol
2551  * @protocol:           GUID of the protocol
2552  * @registration:       registration key passed to the notification function
2553  * @protocol_interface: interface implementing the protocol
2554  *
2555  * This function implements the LocateProtocol service.
2556  *
2557  * See the Unified Extensible Firmware Interface (UEFI) specification for
2558  * details.
2559  *
2560  * Return: status code
2561  */
2562 static efi_status_t EFIAPI efi_locate_protocol(const efi_guid_t *protocol,
2563                                                void *registration,
2564                                                void **protocol_interface)
2565 {
2566         struct efi_handler *handler;
2567         efi_status_t ret;
2568         struct efi_object *efiobj;
2569
2570         EFI_ENTRY("%pUs, %p, %p", protocol, registration, protocol_interface);
2571
2572         /*
2573          * The UEFI spec explicitly requires a protocol even if a registration
2574          * key is provided. This differs from the logic in LocateHandle().
2575          */
2576         if (!protocol || !protocol_interface)
2577                 return EFI_EXIT(EFI_INVALID_PARAMETER);
2578
2579         if (registration) {
2580                 struct efi_register_notify_event *event;
2581                 struct efi_protocol_notification *handle;
2582
2583                 event = efi_check_register_notify_event(registration);
2584                 if (!event)
2585                         return EFI_EXIT(EFI_INVALID_PARAMETER);
2586                 /*
2587                  * The UEFI spec requires to return EFI_NOT_FOUND if no
2588                  * protocol instance matches protocol and registration.
2589                  * So let's do the same for a mismatch between protocol and
2590                  * registration.
2591                  */
2592                 if (guidcmp(&event->protocol, protocol))
2593                         goto not_found;
2594                 if (list_empty(&event->handles))
2595                         goto not_found;
2596                 handle = list_first_entry(&event->handles,
2597                                           struct efi_protocol_notification,
2598                                           link);
2599                 efiobj = handle->handle;
2600                 list_del(&handle->link);
2601                 free(handle);
2602                 ret = efi_search_protocol(efiobj, protocol, &handler);
2603                 if (ret == EFI_SUCCESS)
2604                         goto found;
2605         } else {
2606                 list_for_each_entry(efiobj, &efi_obj_list, link) {
2607                         ret = efi_search_protocol(efiobj, protocol, &handler);
2608                         if (ret == EFI_SUCCESS)
2609                                 goto found;
2610                 }
2611         }
2612 not_found:
2613         *protocol_interface = NULL;
2614         return EFI_EXIT(EFI_NOT_FOUND);
2615 found:
2616         *protocol_interface = handler->protocol_interface;
2617         return EFI_EXIT(EFI_SUCCESS);
2618 }
2619
2620 /**
2621  * efi_install_multiple_protocol_interfaces_int() - Install multiple protocol
2622  *                                              interfaces
2623  * @handle: handle on which the protocol interfaces shall be installed
2624  * @argptr: va_list of args
2625  *
2626  * Core functionality of efi_install_multiple_protocol_interfaces
2627  * Must not be called directly
2628  *
2629  * Return: status code
2630  */
2631 static efi_status_t EFIAPI
2632 efi_install_multiple_protocol_interfaces_int(efi_handle_t *handle,
2633                                              efi_va_list argptr)
2634 {
2635         const efi_guid_t *protocol;
2636         void *protocol_interface;
2637         efi_handle_t old_handle;
2638         efi_status_t ret = EFI_SUCCESS;
2639         int i = 0;
2640         efi_va_list argptr_copy;
2641
2642         if (!handle)
2643                 return EFI_INVALID_PARAMETER;
2644
2645         efi_va_copy(argptr_copy, argptr);
2646         for (;;) {
2647                 protocol = efi_va_arg(argptr, efi_guid_t*);
2648                 if (!protocol)
2649                         break;
2650                 protocol_interface = efi_va_arg(argptr, void*);
2651                 /* Check that a device path has not been installed before */
2652                 if (!guidcmp(protocol, &efi_guid_device_path)) {
2653                         struct efi_device_path *dp = protocol_interface;
2654
2655                         ret = EFI_CALL(efi_locate_device_path(protocol, &dp,
2656                                                               &old_handle));
2657                         if (ret == EFI_SUCCESS &&
2658                             dp->type == DEVICE_PATH_TYPE_END) {
2659                                 EFI_PRINT("Path %pD already installed\n",
2660                                           protocol_interface);
2661                                 ret = EFI_ALREADY_STARTED;
2662                                 break;
2663                         }
2664                 }
2665                 ret = EFI_CALL(efi_install_protocol_interface(handle, protocol,
2666                                                               EFI_NATIVE_INTERFACE,
2667                                                               protocol_interface));
2668                 if (ret != EFI_SUCCESS)
2669                         break;
2670                 i++;
2671         }
2672         if (ret == EFI_SUCCESS)
2673                 goto out;
2674
2675         /* If an error occurred undo all changes. */
2676         for (; i; --i) {
2677                 protocol = efi_va_arg(argptr_copy, efi_guid_t*);
2678                 protocol_interface = efi_va_arg(argptr_copy, void*);
2679                 EFI_CALL(efi_uninstall_protocol_interface(*handle, protocol,
2680                                                           protocol_interface));
2681         }
2682
2683 out:
2684         efi_va_end(argptr_copy);
2685         return ret;
2686
2687 }
2688
2689 /**
2690  * efi_install_multiple_protocol_interfaces() - Install multiple protocol
2691  *                                              interfaces
2692  * @handle: handle on which the protocol interfaces shall be installed
2693  * @...:    NULL terminated argument list with pairs of protocol GUIDS and
2694  *          interfaces
2695  *
2696  *
2697  * This is the function for internal usage in U-Boot. For the API function
2698  * implementing the InstallMultipleProtocol service see
2699  * efi_install_multiple_protocol_interfaces_ext()
2700  *
2701  * Return: status code
2702  */
2703 efi_status_t EFIAPI
2704 efi_install_multiple_protocol_interfaces(efi_handle_t *handle, ...)
2705 {
2706         efi_status_t ret;
2707         efi_va_list argptr;
2708
2709         efi_va_start(argptr, handle);
2710         ret = efi_install_multiple_protocol_interfaces_int(handle, argptr);
2711         efi_va_end(argptr);
2712         return ret;
2713 }
2714
2715 /**
2716  * efi_install_multiple_protocol_interfaces_ext() - Install multiple protocol
2717  *                                                  interfaces
2718  * @handle: handle on which the protocol interfaces shall be installed
2719  * @...:    NULL terminated argument list with pairs of protocol GUIDS and
2720  *          interfaces
2721  *
2722  * This function implements the MultipleProtocolInterfaces service.
2723  *
2724  * See the Unified Extensible Firmware Interface (UEFI) specification for
2725  * details.
2726  *
2727  * Return: status code
2728  */
2729 static efi_status_t EFIAPI
2730 efi_install_multiple_protocol_interfaces_ext(efi_handle_t *handle, ...)
2731 {
2732         EFI_ENTRY("%p", handle);
2733         efi_status_t ret;
2734         efi_va_list argptr;
2735
2736         efi_va_start(argptr, handle);
2737         ret = efi_install_multiple_protocol_interfaces_int(handle, argptr);
2738         efi_va_end(argptr);
2739         return EFI_EXIT(ret);
2740 }
2741
2742 /**
2743  * efi_uninstall_multiple_protocol_interfaces_int() - wrapper for uninstall
2744  *                                                  multiple protocol
2745  *                                                  interfaces
2746  * @handle: handle from which the protocol interfaces shall be removed
2747  * @argptr: va_list of args
2748  *
2749  * Core functionality of efi_uninstall_multiple_protocol_interfaces
2750  * Must not be called directly
2751  *
2752  * Return: status code
2753  */
2754 static efi_status_t EFIAPI
2755 efi_uninstall_multiple_protocol_interfaces_int(efi_handle_t handle,
2756                                                efi_va_list argptr)
2757 {
2758         const efi_guid_t *protocol;
2759         void *protocol_interface;
2760         efi_status_t ret = EFI_SUCCESS;
2761         size_t i = 0;
2762         efi_va_list argptr_copy;
2763
2764         if (!handle)
2765                 return EFI_INVALID_PARAMETER;
2766
2767         efi_va_copy(argptr_copy, argptr);
2768         for (;;) {
2769                 protocol = efi_va_arg(argptr, efi_guid_t*);
2770                 if (!protocol)
2771                         break;
2772                 protocol_interface = efi_va_arg(argptr, void*);
2773                 ret = efi_uninstall_protocol(handle, protocol,
2774                                              protocol_interface);
2775                 if (ret != EFI_SUCCESS)
2776                         break;
2777                 i++;
2778         }
2779         if (ret == EFI_SUCCESS) {
2780                 /* If the last protocol has been removed, delete the handle. */
2781                 if (list_empty(&handle->protocols)) {
2782                         list_del(&handle->link);
2783                         free(handle);
2784                 }
2785                 goto out;
2786         }
2787
2788         /* If an error occurred undo all changes. */
2789         for (; i; --i) {
2790                 protocol = efi_va_arg(argptr_copy, efi_guid_t*);
2791                 protocol_interface = efi_va_arg(argptr_copy, void*);
2792                 EFI_CALL(efi_install_protocol_interface(&handle, protocol,
2793                                                         EFI_NATIVE_INTERFACE,
2794                                                         protocol_interface));
2795         }
2796         /*
2797          * If any errors are generated while the protocol interfaces are being
2798          * uninstalled, then the protocols uninstalled prior to the error will
2799          * be reinstalled using InstallProtocolInterface() and the status code
2800          * EFI_INVALID_PARAMETER is returned.
2801          */
2802         ret = EFI_INVALID_PARAMETER;
2803
2804 out:
2805         efi_va_end(argptr_copy);
2806         return ret;
2807 }
2808
2809 /**
2810  * efi_uninstall_multiple_protocol_interfaces() - uninstall multiple protocol
2811  *                                                interfaces
2812  * @handle: handle from which the protocol interfaces shall be removed
2813  * @...:    NULL terminated argument list with pairs of protocol GUIDS and
2814  *          interfaces
2815  *
2816  * This function implements the UninstallMultipleProtocolInterfaces service.
2817  *
2818  * This is the function for internal usage in U-Boot. For the API function
2819  * implementing the UninstallMultipleProtocolInterfaces service see
2820  * efi_uninstall_multiple_protocol_interfaces_ext()
2821  *
2822  * Return: status code
2823  */
2824 efi_status_t EFIAPI
2825 efi_uninstall_multiple_protocol_interfaces(efi_handle_t handle, ...)
2826 {
2827         efi_status_t ret;
2828         efi_va_list argptr;
2829
2830         efi_va_start(argptr, handle);
2831         ret = efi_uninstall_multiple_protocol_interfaces_int(handle, argptr);
2832         efi_va_end(argptr);
2833         return ret;
2834 }
2835
2836 /**
2837  * efi_uninstall_multiple_protocol_interfaces_ext() - uninstall multiple protocol
2838  *                                                    interfaces
2839  * @handle: handle from which the protocol interfaces shall be removed
2840  * @...:    NULL terminated argument list with pairs of protocol GUIDS and
2841  *          interfaces
2842  *
2843  * This function implements the UninstallMultipleProtocolInterfaces service.
2844  *
2845  * See the Unified Extensible Firmware Interface (UEFI) specification for
2846  * details.
2847  *
2848  * Return: status code
2849  */
2850 static efi_status_t EFIAPI
2851 efi_uninstall_multiple_protocol_interfaces_ext(efi_handle_t handle, ...)
2852 {
2853         EFI_ENTRY("%p", handle);
2854         efi_status_t ret;
2855         efi_va_list argptr;
2856
2857         efi_va_start(argptr, handle);
2858         ret = efi_uninstall_multiple_protocol_interfaces_int(handle, argptr);
2859         efi_va_end(argptr);
2860         return EFI_EXIT(ret);
2861 }
2862
2863 /**
2864  * efi_calculate_crc32() - calculate cyclic redundancy code
2865  * @data:      buffer with data
2866  * @data_size: size of buffer in bytes
2867  * @crc32_p:   cyclic redundancy code
2868  *
2869  * This function implements the CalculateCrc32 service.
2870  *
2871  * See the Unified Extensible Firmware Interface (UEFI) specification for
2872  * details.
2873  *
2874  * Return: status code
2875  */
2876 static efi_status_t EFIAPI efi_calculate_crc32(const void *data,
2877                                                efi_uintn_t data_size,
2878                                                u32 *crc32_p)
2879 {
2880         efi_status_t ret = EFI_SUCCESS;
2881
2882         EFI_ENTRY("%p, %zu", data, data_size);
2883         if (!data || !data_size || !crc32_p) {
2884                 ret = EFI_INVALID_PARAMETER;
2885                 goto out;
2886         }
2887         *crc32_p = crc32(0, data, data_size);
2888 out:
2889         return EFI_EXIT(ret);
2890 }
2891
2892 /**
2893  * efi_copy_mem() - copy memory
2894  * @destination: destination of the copy operation
2895  * @source:      source of the copy operation
2896  * @length:      number of bytes to copy
2897  *
2898  * This function implements the CopyMem service.
2899  *
2900  * See the Unified Extensible Firmware Interface (UEFI) specification for
2901  * details.
2902  */
2903 static void EFIAPI efi_copy_mem(void *destination, const void *source,
2904                                 size_t length)
2905 {
2906         EFI_ENTRY("%p, %p, %ld", destination, source, (unsigned long)length);
2907         memmove(destination, source, length);
2908         EFI_EXIT(EFI_SUCCESS);
2909 }
2910
2911 /**
2912  * efi_set_mem() - Fill memory with a byte value.
2913  * @buffer: buffer to fill
2914  * @size:   size of buffer in bytes
2915  * @value:  byte to copy to the buffer
2916  *
2917  * This function implements the SetMem service.
2918  *
2919  * See the Unified Extensible Firmware Interface (UEFI) specification for
2920  * details.
2921  */
2922 static void EFIAPI efi_set_mem(void *buffer, size_t size, uint8_t value)
2923 {
2924         EFI_ENTRY("%p, %ld, 0x%x", buffer, (unsigned long)size, value);
2925         memset(buffer, value, size);
2926         EFI_EXIT(EFI_SUCCESS);
2927 }
2928
2929 /**
2930  * efi_protocol_open() - open protocol interface on a handle
2931  * @handler:            handler of a protocol
2932  * @protocol_interface: interface implementing the protocol
2933  * @agent_handle:       handle of the driver
2934  * @controller_handle:  handle of the controller
2935  * @attributes:         attributes indicating how to open the protocol
2936  *
2937  * Return: status code
2938  */
2939 efi_status_t efi_protocol_open(
2940                         struct efi_handler *handler,
2941                         void **protocol_interface, void *agent_handle,
2942                         void *controller_handle, uint32_t attributes)
2943 {
2944         struct efi_open_protocol_info_item *item;
2945         struct efi_open_protocol_info_entry *match = NULL;
2946         bool opened_by_driver = false;
2947         bool opened_exclusive = false;
2948
2949         /* If there is no agent, only return the interface */
2950         if (!agent_handle)
2951                 goto out;
2952
2953         /* For TEST_PROTOCOL ignore interface attribute */
2954         if (attributes != EFI_OPEN_PROTOCOL_TEST_PROTOCOL)
2955                 *protocol_interface = NULL;
2956
2957         /*
2958          * Check if the protocol is already opened by a driver with the same
2959          * attributes or opened exclusively
2960          */
2961         list_for_each_entry(item, &handler->open_infos, link) {
2962                 if (item->info.agent_handle == agent_handle) {
2963                         if ((attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) &&
2964                             (item->info.attributes == attributes))
2965                                 return EFI_ALREADY_STARTED;
2966                 } else {
2967                         if (item->info.attributes &
2968                             EFI_OPEN_PROTOCOL_BY_DRIVER)
2969                                 opened_by_driver = true;
2970                 }
2971                 if (item->info.attributes & EFI_OPEN_PROTOCOL_EXCLUSIVE)
2972                         opened_exclusive = true;
2973         }
2974
2975         /* Only one controller can open the protocol exclusively */
2976         if (attributes & EFI_OPEN_PROTOCOL_EXCLUSIVE) {
2977                 if (opened_exclusive)
2978                         return EFI_ACCESS_DENIED;
2979         } else if (attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) {
2980                 if (opened_exclusive || opened_by_driver)
2981                         return EFI_ACCESS_DENIED;
2982         }
2983
2984         /* Prepare exclusive opening */
2985         if (attributes & EFI_OPEN_PROTOCOL_EXCLUSIVE) {
2986                 /* Try to disconnect controllers */
2987 disconnect_next:
2988                 opened_by_driver = false;
2989                 list_for_each_entry(item, &handler->open_infos, link) {
2990                         efi_status_t ret;
2991
2992                         if (item->info.attributes ==
2993                                         EFI_OPEN_PROTOCOL_BY_DRIVER) {
2994                                 ret = EFI_CALL(efi_disconnect_controller(
2995                                                 item->info.controller_handle,
2996                                                 item->info.agent_handle,
2997                                                 NULL));
2998                                 if (ret == EFI_SUCCESS)
2999                                         /*
3000                                          * Child controllers may have been
3001                                          * removed from the open_infos list. So
3002                                          * let's restart the loop.
3003                                          */
3004                                         goto disconnect_next;
3005                                 else
3006                                         opened_by_driver = true;
3007                         }
3008                 }
3009                 /* Only one driver can be connected */
3010                 if (opened_by_driver)
3011                         return EFI_ACCESS_DENIED;
3012         }
3013
3014         /* Find existing entry */
3015         list_for_each_entry(item, &handler->open_infos, link) {
3016                 if (item->info.agent_handle == agent_handle &&
3017                     item->info.controller_handle == controller_handle &&
3018                     item->info.attributes == attributes)
3019                         match = &item->info;
3020         }
3021         /* None found, create one */
3022         if (!match) {
3023                 match = efi_create_open_info(handler);
3024                 if (!match)
3025                         return EFI_OUT_OF_RESOURCES;
3026         }
3027
3028         match->agent_handle = agent_handle;
3029         match->controller_handle = controller_handle;
3030         match->attributes = attributes;
3031         match->open_count++;
3032
3033 out:
3034         /* For TEST_PROTOCOL ignore interface attribute. */
3035         if (attributes != EFI_OPEN_PROTOCOL_TEST_PROTOCOL)
3036                 *protocol_interface = handler->protocol_interface;
3037
3038         return EFI_SUCCESS;
3039 }
3040
3041 /**
3042  * efi_open_protocol() - open protocol interface on a handle
3043  * @handle:             handle on which the protocol shall be opened
3044  * @protocol:           GUID of the protocol
3045  * @protocol_interface: interface implementing the protocol
3046  * @agent_handle:       handle of the driver
3047  * @controller_handle:  handle of the controller
3048  * @attributes:         attributes indicating how to open the protocol
3049  *
3050  * This function implements the OpenProtocol interface.
3051  *
3052  * See the Unified Extensible Firmware Interface (UEFI) specification for
3053  * details.
3054  *
3055  * Return: status code
3056  */
3057 static efi_status_t EFIAPI efi_open_protocol
3058                         (efi_handle_t handle, const efi_guid_t *protocol,
3059                          void **protocol_interface, efi_handle_t agent_handle,
3060                          efi_handle_t controller_handle, uint32_t attributes)
3061 {
3062         struct efi_handler *handler;
3063         efi_status_t r = EFI_INVALID_PARAMETER;
3064
3065         EFI_ENTRY("%p, %pUs, %p, %p, %p, 0x%x", handle, protocol,
3066                   protocol_interface, agent_handle, controller_handle,
3067                   attributes);
3068
3069         if (!handle || !protocol ||
3070             (!protocol_interface && attributes !=
3071              EFI_OPEN_PROTOCOL_TEST_PROTOCOL)) {
3072                 goto out;
3073         }
3074
3075         switch (attributes) {
3076         case EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL:
3077         case EFI_OPEN_PROTOCOL_GET_PROTOCOL:
3078         case EFI_OPEN_PROTOCOL_TEST_PROTOCOL:
3079                 break;
3080         case EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER:
3081                 if (controller_handle == handle)
3082                         goto out;
3083                 /* fall-through */
3084         case EFI_OPEN_PROTOCOL_BY_DRIVER:
3085         case EFI_OPEN_PROTOCOL_BY_DRIVER | EFI_OPEN_PROTOCOL_EXCLUSIVE:
3086                 /* Check that the controller handle is valid */
3087                 if (!efi_search_obj(controller_handle))
3088                         goto out;
3089                 /* fall-through */
3090         case EFI_OPEN_PROTOCOL_EXCLUSIVE:
3091                 /* Check that the agent handle is valid */
3092                 if (!efi_search_obj(agent_handle))
3093                         goto out;
3094                 break;
3095         default:
3096                 goto out;
3097         }
3098
3099         r = efi_search_protocol(handle, protocol, &handler);
3100         switch (r) {
3101         case EFI_SUCCESS:
3102                 break;
3103         case EFI_NOT_FOUND:
3104                 r = EFI_UNSUPPORTED;
3105                 goto out;
3106         default:
3107                 goto out;
3108         }
3109
3110         r = efi_protocol_open(handler, protocol_interface, agent_handle,
3111                               controller_handle, attributes);
3112 out:
3113         return EFI_EXIT(r);
3114 }
3115
3116 /**
3117  * efi_start_image() - call the entry point of an image
3118  * @image_handle:   handle of the image
3119  * @exit_data_size: size of the buffer
3120  * @exit_data:      buffer to receive the exit data of the called image
3121  *
3122  * This function implements the StartImage service.
3123  *
3124  * See the Unified Extensible Firmware Interface (UEFI) specification for
3125  * details.
3126  *
3127  * Return: status code
3128  */
3129 efi_status_t EFIAPI efi_start_image(efi_handle_t image_handle,
3130                                     efi_uintn_t *exit_data_size,
3131                                     u16 **exit_data)
3132 {
3133         struct efi_loaded_image_obj *image_obj =
3134                 (struct efi_loaded_image_obj *)image_handle;
3135         efi_status_t ret;
3136         void *info;
3137         efi_handle_t parent_image = current_image;
3138         efi_status_t exit_status;
3139         struct jmp_buf_data exit_jmp;
3140
3141         EFI_ENTRY("%p, %p, %p", image_handle, exit_data_size, exit_data);
3142
3143         if (!efi_search_obj(image_handle))
3144                 return EFI_EXIT(EFI_INVALID_PARAMETER);
3145
3146         /* Check parameters */
3147         if (image_obj->header.type != EFI_OBJECT_TYPE_LOADED_IMAGE)
3148                 return EFI_EXIT(EFI_INVALID_PARAMETER);
3149
3150         if (image_obj->auth_status != EFI_IMAGE_AUTH_PASSED)
3151                 return EFI_EXIT(EFI_SECURITY_VIOLATION);
3152
3153         ret = EFI_CALL(efi_open_protocol(image_handle, &efi_guid_loaded_image,
3154                                          &info, NULL, NULL,
3155                                          EFI_OPEN_PROTOCOL_GET_PROTOCOL));
3156         if (ret != EFI_SUCCESS)
3157                 return EFI_EXIT(EFI_INVALID_PARAMETER);
3158
3159         image_obj->exit_data_size = exit_data_size;
3160         image_obj->exit_data = exit_data;
3161         image_obj->exit_status = &exit_status;
3162         image_obj->exit_jmp = &exit_jmp;
3163
3164         if (IS_ENABLED(CONFIG_EFI_TCG2_PROTOCOL)) {
3165                 if (image_obj->image_type == IMAGE_SUBSYSTEM_EFI_APPLICATION) {
3166                         ret = efi_tcg2_measure_efi_app_invocation(image_obj);
3167                         if (ret == EFI_SECURITY_VIOLATION) {
3168                                 /*
3169                                  * TCG2 Protocol is installed but no TPM device found,
3170                                  * this is not expected.
3171                                  */
3172                                 return EFI_EXIT(EFI_SECURITY_VIOLATION);
3173                         }
3174                 }
3175         }
3176
3177         /* call the image! */
3178         if (setjmp(&exit_jmp)) {
3179                 /*
3180                  * We called the entry point of the child image with EFI_CALL
3181                  * in the lines below. The child image called the Exit() boot
3182                  * service efi_exit() which executed the long jump that brought
3183                  * us to the current line. This implies that the second half
3184                  * of the EFI_CALL macro has not been executed.
3185                  */
3186 #if defined(CONFIG_ARM) || defined(CONFIG_RISCV)
3187                 /*
3188                  * efi_exit() called efi_restore_gd(). We have to undo this
3189                  * otherwise __efi_entry_check() will put the wrong value into
3190                  * app_gd.
3191                  */
3192                 set_gd(app_gd);
3193 #endif
3194                 /*
3195                  * To get ready to call EFI_EXIT below we have to execute the
3196                  * missed out steps of EFI_CALL.
3197                  */
3198                 assert(__efi_entry_check());
3199                 EFI_PRINT("%lu returned by started image\n",
3200                           (unsigned long)((uintptr_t)exit_status &
3201                           ~EFI_ERROR_MASK));
3202                 current_image = parent_image;
3203                 return EFI_EXIT(exit_status);
3204         }
3205
3206         current_image = image_handle;
3207         image_obj->header.type = EFI_OBJECT_TYPE_STARTED_IMAGE;
3208         EFI_PRINT("Jumping into 0x%p\n", image_obj->entry);
3209         ret = EFI_CALL(image_obj->entry(image_handle, &systab));
3210
3211         /*
3212          * Control is returned from a started UEFI image either by calling
3213          * Exit() (where exit data can be provided) or by simply returning from
3214          * the entry point. In the latter case call Exit() on behalf of the
3215          * image.
3216          */
3217         return EFI_CALL(systab.boottime->exit(image_handle, ret, 0, NULL));
3218 }
3219
3220 /**
3221  * efi_delete_image() - delete loaded image from memory)
3222  *
3223  * @image_obj:                  handle of the loaded image
3224  * @loaded_image_protocol:      loaded image protocol
3225  */
3226 static efi_status_t efi_delete_image
3227                         (struct efi_loaded_image_obj *image_obj,
3228                          struct efi_loaded_image *loaded_image_protocol)
3229 {
3230         struct efi_object *efiobj;
3231         efi_status_t r, ret = EFI_SUCCESS;
3232
3233 close_next:
3234         list_for_each_entry(efiobj, &efi_obj_list, link) {
3235                 struct efi_handler *protocol;
3236
3237                 list_for_each_entry(protocol, &efiobj->protocols, link) {
3238                         struct efi_open_protocol_info_item *info;
3239
3240                         list_for_each_entry(info, &protocol->open_infos, link) {
3241                                 if (info->info.agent_handle !=
3242                                     (efi_handle_t)image_obj)
3243                                         continue;
3244                                 r = efi_close_protocol(
3245                                                 efiobj, &protocol->guid,
3246                                                 info->info.agent_handle,
3247                                                 info->info.controller_handle);
3248                                 if (r !=  EFI_SUCCESS)
3249                                         ret = r;
3250                                 /*
3251                                  * Closing protocols may results in further
3252                                  * items being deleted. To play it safe loop
3253                                  * over all elements again.
3254                                  */
3255                                 goto close_next;
3256                         }
3257                 }
3258         }
3259
3260         efi_free_pages((uintptr_t)loaded_image_protocol->image_base,
3261                        efi_size_in_pages(loaded_image_protocol->image_size));
3262         efi_delete_handle(&image_obj->header);
3263
3264         return ret;
3265 }
3266
3267 /**
3268  * efi_unload_image() - unload an EFI image
3269  * @image_handle: handle of the image to be unloaded
3270  *
3271  * This function implements the UnloadImage service.
3272  *
3273  * See the Unified Extensible Firmware Interface (UEFI) specification for
3274  * details.
3275  *
3276  * Return: status code
3277  */
3278 efi_status_t EFIAPI efi_unload_image(efi_handle_t image_handle)
3279 {
3280         efi_status_t ret = EFI_SUCCESS;
3281         struct efi_object *efiobj;
3282         struct efi_loaded_image *loaded_image_protocol;
3283
3284         EFI_ENTRY("%p", image_handle);
3285
3286         efiobj = efi_search_obj(image_handle);
3287         if (!efiobj) {
3288                 ret = EFI_INVALID_PARAMETER;
3289                 goto out;
3290         }
3291         /* Find the loaded image protocol */
3292         ret = EFI_CALL(efi_open_protocol(image_handle, &efi_guid_loaded_image,
3293                                          (void **)&loaded_image_protocol,
3294                                          NULL, NULL,
3295                                          EFI_OPEN_PROTOCOL_GET_PROTOCOL));
3296         if (ret != EFI_SUCCESS) {
3297                 ret = EFI_INVALID_PARAMETER;
3298                 goto out;
3299         }
3300         switch (efiobj->type) {
3301         case EFI_OBJECT_TYPE_STARTED_IMAGE:
3302                 /* Call the unload function */
3303                 if (!loaded_image_protocol->unload) {
3304                         ret = EFI_UNSUPPORTED;
3305                         goto out;
3306                 }
3307                 ret = EFI_CALL(loaded_image_protocol->unload(image_handle));
3308                 if (ret != EFI_SUCCESS)
3309                         goto out;
3310                 break;
3311         case EFI_OBJECT_TYPE_LOADED_IMAGE:
3312                 break;
3313         default:
3314                 ret = EFI_INVALID_PARAMETER;
3315                 goto out;
3316         }
3317         efi_delete_image((struct efi_loaded_image_obj *)efiobj,
3318                          loaded_image_protocol);
3319 out:
3320         return EFI_EXIT(ret);
3321 }
3322
3323 /**
3324  * efi_update_exit_data() - fill exit data parameters of StartImage()
3325  *
3326  * @image_obj:          image handle
3327  * @exit_data_size:     size of the exit data buffer
3328  * @exit_data:          buffer with data returned by UEFI payload
3329  * Return:              status code
3330  */
3331 static efi_status_t efi_update_exit_data(struct efi_loaded_image_obj *image_obj,
3332                                          efi_uintn_t exit_data_size,
3333                                          u16 *exit_data)
3334 {
3335         efi_status_t ret;
3336
3337         /*
3338          * If exit_data is not provided to StartImage(), exit_data_size must be
3339          * ignored.
3340          */
3341         if (!image_obj->exit_data)
3342                 return EFI_SUCCESS;
3343         if (image_obj->exit_data_size)
3344                 *image_obj->exit_data_size = exit_data_size;
3345         if (exit_data_size && exit_data) {
3346                 ret = efi_allocate_pool(EFI_BOOT_SERVICES_DATA,
3347                                         exit_data_size,
3348                                         (void **)image_obj->exit_data);
3349                 if (ret != EFI_SUCCESS)
3350                         return ret;
3351                 memcpy(*image_obj->exit_data, exit_data, exit_data_size);
3352         } else {
3353                 image_obj->exit_data = NULL;
3354         }
3355         return EFI_SUCCESS;
3356 }
3357
3358 /**
3359  * efi_exit() - leave an EFI application or driver
3360  * @image_handle:   handle of the application or driver that is exiting
3361  * @exit_status:    status code
3362  * @exit_data_size: size of the buffer in bytes
3363  * @exit_data:      buffer with data describing an error
3364  *
3365  * This function implements the Exit service.
3366  *
3367  * See the Unified Extensible Firmware Interface (UEFI) specification for
3368  * details.
3369  *
3370  * Return: status code
3371  */
3372 static efi_status_t EFIAPI efi_exit(efi_handle_t image_handle,
3373                                     efi_status_t exit_status,
3374                                     efi_uintn_t exit_data_size,
3375                                     u16 *exit_data)
3376 {
3377         /*
3378          * TODO: We should call the unload procedure of the loaded
3379          *       image protocol.
3380          */
3381         efi_status_t ret;
3382         struct efi_loaded_image *loaded_image_protocol;
3383         struct efi_loaded_image_obj *image_obj =
3384                 (struct efi_loaded_image_obj *)image_handle;
3385         struct jmp_buf_data *exit_jmp;
3386
3387         EFI_ENTRY("%p, %ld, %zu, %p", image_handle, exit_status,
3388                   exit_data_size, exit_data);
3389
3390         /* Check parameters */
3391         ret = EFI_CALL(efi_open_protocol(image_handle, &efi_guid_loaded_image,
3392                                          (void **)&loaded_image_protocol,
3393                                          NULL, NULL,
3394                                          EFI_OPEN_PROTOCOL_GET_PROTOCOL));
3395         if (ret != EFI_SUCCESS) {
3396                 ret = EFI_INVALID_PARAMETER;
3397                 goto out;
3398         }
3399
3400         /* Unloading of unstarted images */
3401         switch (image_obj->header.type) {
3402         case EFI_OBJECT_TYPE_STARTED_IMAGE:
3403                 break;
3404         case EFI_OBJECT_TYPE_LOADED_IMAGE:
3405                 efi_delete_image(image_obj, loaded_image_protocol);
3406                 ret = EFI_SUCCESS;
3407                 goto out;
3408         default:
3409                 /* Handle does not refer to loaded image */
3410                 ret = EFI_INVALID_PARAMETER;
3411                 goto out;
3412         }
3413         /* A started image can only be unloaded it is the last one started. */
3414         if (image_handle != current_image) {
3415                 ret = EFI_INVALID_PARAMETER;
3416                 goto out;
3417         }
3418
3419         /* Exit data is only foreseen in case of failure. */
3420         if (exit_status != EFI_SUCCESS) {
3421                 ret = efi_update_exit_data(image_obj, exit_data_size,
3422                                            exit_data);
3423                 /* Exiting has priority. Don't return error to caller. */
3424                 if (ret != EFI_SUCCESS)
3425                         EFI_PRINT("%s: out of memory\n", __func__);
3426         }
3427         /* efi_delete_image() frees image_obj. Copy before the call. */
3428         exit_jmp = image_obj->exit_jmp;
3429         *image_obj->exit_status = exit_status;
3430         if (image_obj->image_type == IMAGE_SUBSYSTEM_EFI_APPLICATION ||
3431             exit_status != EFI_SUCCESS)
3432                 efi_delete_image(image_obj, loaded_image_protocol);
3433
3434         if (IS_ENABLED(CONFIG_EFI_TCG2_PROTOCOL)) {
3435                 if (image_obj->image_type == IMAGE_SUBSYSTEM_EFI_APPLICATION) {
3436                         ret = efi_tcg2_measure_efi_app_exit();
3437                         if (ret != EFI_SUCCESS) {
3438                                 log_warning("tcg2 measurement fails(0x%lx)\n",
3439                                             ret);
3440                         }
3441                 }
3442         }
3443
3444         /* Make sure entry/exit counts for EFI world cross-overs match */
3445         EFI_EXIT(exit_status);
3446
3447         /*
3448          * But longjmp out with the U-Boot gd, not the application's, as
3449          * the other end is a setjmp call inside EFI context.
3450          */
3451         efi_restore_gd();
3452
3453         longjmp(exit_jmp, 1);
3454
3455         panic("EFI application exited");
3456 out:
3457         return EFI_EXIT(ret);
3458 }
3459
3460 /**
3461  * efi_handle_protocol() - get interface of a protocol on a handle
3462  * @handle:             handle on which the protocol shall be opened
3463  * @protocol:           GUID of the protocol
3464  * @protocol_interface: interface implementing the protocol
3465  *
3466  * This function implements the HandleProtocol service.
3467  *
3468  * See the Unified Extensible Firmware Interface (UEFI) specification for
3469  * details.
3470  *
3471  * Return: status code
3472  */
3473 efi_status_t EFIAPI efi_handle_protocol(efi_handle_t handle,
3474                                         const efi_guid_t *protocol,
3475                                         void **protocol_interface)
3476 {
3477         return efi_open_protocol(handle, protocol, protocol_interface, efi_root,
3478                                  NULL, EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL);
3479 }
3480
3481 /**
3482  * efi_bind_controller() - bind a single driver to a controller
3483  * @controller_handle:   controller handle
3484  * @driver_image_handle: driver handle
3485  * @remain_device_path:  remaining path
3486  *
3487  * Return: status code
3488  */
3489 static efi_status_t efi_bind_controller(
3490                         efi_handle_t controller_handle,
3491                         efi_handle_t driver_image_handle,
3492                         struct efi_device_path *remain_device_path)
3493 {
3494         struct efi_driver_binding_protocol *binding_protocol;
3495         efi_status_t r;
3496
3497         r = EFI_CALL(efi_open_protocol(driver_image_handle,
3498                                        &efi_guid_driver_binding_protocol,
3499                                        (void **)&binding_protocol,
3500                                        driver_image_handle, NULL,
3501                                        EFI_OPEN_PROTOCOL_GET_PROTOCOL));
3502         if (r != EFI_SUCCESS)
3503                 return r;
3504         r = EFI_CALL(binding_protocol->supported(binding_protocol,
3505                                                  controller_handle,
3506                                                  remain_device_path));
3507         if (r == EFI_SUCCESS)
3508                 r = EFI_CALL(binding_protocol->start(binding_protocol,
3509                                                      controller_handle,
3510                                                      remain_device_path));
3511         efi_close_protocol(driver_image_handle,
3512                            &efi_guid_driver_binding_protocol,
3513                            driver_image_handle, NULL);
3514         return r;
3515 }
3516
3517 /**
3518  * efi_connect_single_controller() - connect a single driver to a controller
3519  * @controller_handle:   controller
3520  * @driver_image_handle: driver
3521  * @remain_device_path:  remaining path
3522  *
3523  * Return: status code
3524  */
3525 static efi_status_t efi_connect_single_controller(
3526                         efi_handle_t controller_handle,
3527                         efi_handle_t *driver_image_handle,
3528                         struct efi_device_path *remain_device_path)
3529 {
3530         efi_handle_t *buffer;
3531         size_t count;
3532         size_t i;
3533         efi_status_t r;
3534         size_t connected = 0;
3535
3536         /* Get buffer with all handles with driver binding protocol */
3537         r = EFI_CALL(efi_locate_handle_buffer(BY_PROTOCOL,
3538                                               &efi_guid_driver_binding_protocol,
3539                                               NULL, &count, &buffer));
3540         if (r != EFI_SUCCESS)
3541                 return r;
3542
3543         /* Context Override */
3544         if (driver_image_handle) {
3545                 for (; *driver_image_handle; ++driver_image_handle) {
3546                         for (i = 0; i < count; ++i) {
3547                                 if (buffer[i] == *driver_image_handle) {
3548                                         buffer[i] = NULL;
3549                                         r = efi_bind_controller(
3550                                                         controller_handle,
3551                                                         *driver_image_handle,
3552                                                         remain_device_path);
3553                                         /*
3554                                          * For drivers that do not support the
3555                                          * controller or are already connected
3556                                          * we receive an error code here.
3557                                          */
3558                                         if (r == EFI_SUCCESS)
3559                                                 ++connected;
3560                                 }
3561                         }
3562                 }
3563         }
3564
3565         /*
3566          * TODO: Some overrides are not yet implemented:
3567          * - Platform Driver Override
3568          * - Driver Family Override Search
3569          * - Bus Specific Driver Override
3570          */
3571
3572         /* Driver Binding Search */
3573         for (i = 0; i < count; ++i) {
3574                 if (buffer[i]) {
3575                         r = efi_bind_controller(controller_handle,
3576                                                 buffer[i],
3577                                                 remain_device_path);
3578                         if (r == EFI_SUCCESS)
3579                                 ++connected;
3580                 }
3581         }
3582
3583         efi_free_pool(buffer);
3584         if (!connected)
3585                 return EFI_NOT_FOUND;
3586         return EFI_SUCCESS;
3587 }
3588
3589 /**
3590  * efi_connect_controller() - connect a controller to a driver
3591  * @controller_handle:   handle of the controller
3592  * @driver_image_handle: handle of the driver
3593  * @remain_device_path:  device path of a child controller
3594  * @recursive:           true to connect all child controllers
3595  *
3596  * This function implements the ConnectController service.
3597  *
3598  * See the Unified Extensible Firmware Interface (UEFI) specification for
3599  * details.
3600  *
3601  * First all driver binding protocol handles are tried for binding drivers.
3602  * Afterwards all handles that have opened a protocol of the controller
3603  * with EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER are connected to drivers.
3604  *
3605  * Return: status code
3606  */
3607 static efi_status_t EFIAPI efi_connect_controller(
3608                         efi_handle_t controller_handle,
3609                         efi_handle_t *driver_image_handle,
3610                         struct efi_device_path *remain_device_path,
3611                         bool recursive)
3612 {
3613         efi_status_t r;
3614         efi_status_t ret = EFI_NOT_FOUND;
3615         struct efi_object *efiobj;
3616
3617         EFI_ENTRY("%p, %p, %pD, %d", controller_handle, driver_image_handle,
3618                   remain_device_path, recursive);
3619
3620         efiobj = efi_search_obj(controller_handle);
3621         if (!efiobj) {
3622                 ret = EFI_INVALID_PARAMETER;
3623                 goto out;
3624         }
3625
3626         r = efi_connect_single_controller(controller_handle,
3627                                           driver_image_handle,
3628                                           remain_device_path);
3629         if (r == EFI_SUCCESS)
3630                 ret = EFI_SUCCESS;
3631         if (recursive) {
3632                 struct efi_handler *handler;
3633                 struct efi_open_protocol_info_item *item;
3634
3635                 list_for_each_entry(handler, &efiobj->protocols, link) {
3636                         list_for_each_entry(item, &handler->open_infos, link) {
3637                                 if (item->info.attributes &
3638                                     EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER) {
3639                                         r = EFI_CALL(efi_connect_controller(
3640                                                 item->info.controller_handle,
3641                                                 driver_image_handle,
3642                                                 remain_device_path,
3643                                                 recursive));
3644                                         if (r == EFI_SUCCESS)
3645                                                 ret = EFI_SUCCESS;
3646                                 }
3647                         }
3648                 }
3649         }
3650         /* Check for child controller specified by end node */
3651         if (ret != EFI_SUCCESS && remain_device_path &&
3652             remain_device_path->type == DEVICE_PATH_TYPE_END)
3653                 ret = EFI_SUCCESS;
3654 out:
3655         return EFI_EXIT(ret);
3656 }
3657
3658 /**
3659  * efi_reinstall_protocol_interface() - reinstall protocol interface
3660  * @handle:        handle on which the protocol shall be reinstalled
3661  * @protocol:      GUID of the protocol to be installed
3662  * @old_interface: interface to be removed
3663  * @new_interface: interface to be installed
3664  *
3665  * This function implements the ReinstallProtocolInterface service.
3666  *
3667  * See the Unified Extensible Firmware Interface (UEFI) specification for
3668  * details.
3669  *
3670  * The old interface is uninstalled. The new interface is installed.
3671  * Drivers are connected.
3672  *
3673  * Return: status code
3674  */
3675 static efi_status_t EFIAPI efi_reinstall_protocol_interface(
3676                         efi_handle_t handle, const efi_guid_t *protocol,
3677                         void *old_interface, void *new_interface)
3678 {
3679         efi_status_t ret;
3680
3681         EFI_ENTRY("%p, %pUs, %p, %p", handle, protocol, old_interface,
3682                   new_interface);
3683
3684         /* Uninstall protocol but do not delete handle */
3685         ret = efi_uninstall_protocol(handle, protocol, old_interface);
3686         if (ret != EFI_SUCCESS)
3687                 goto out;
3688
3689         /* Install the new protocol */
3690         ret = efi_add_protocol(handle, protocol, new_interface);
3691         /*
3692          * The UEFI spec does not specify what should happen to the handle
3693          * if in case of an error no protocol interface remains on the handle.
3694          * So let's do nothing here.
3695          */
3696         if (ret != EFI_SUCCESS)
3697                 goto out;
3698         /*
3699          * The returned status code has to be ignored.
3700          * Do not create an error if no suitable driver for the handle exists.
3701          */
3702         EFI_CALL(efi_connect_controller(handle, NULL, NULL, true));
3703 out:
3704         return EFI_EXIT(ret);
3705 }
3706
3707 /**
3708  * efi_get_child_controllers() - get all child controllers associated to a driver
3709  * @efiobj:              handle of the controller
3710  * @driver_handle:       handle of the driver
3711  * @number_of_children:  number of child controllers
3712  * @child_handle_buffer: handles of the the child controllers
3713  *
3714  * The allocated buffer has to be freed with free().
3715  *
3716  * Return: status code
3717  */
3718 static efi_status_t efi_get_child_controllers(
3719                                 struct efi_object *efiobj,
3720                                 efi_handle_t driver_handle,
3721                                 efi_uintn_t *number_of_children,
3722                                 efi_handle_t **child_handle_buffer)
3723 {
3724         struct efi_handler *handler;
3725         struct efi_open_protocol_info_item *item;
3726         efi_uintn_t count = 0, i;
3727         bool duplicate;
3728
3729         /* Count all child controller associations */
3730         list_for_each_entry(handler, &efiobj->protocols, link) {
3731                 list_for_each_entry(item, &handler->open_infos, link) {
3732                         if (item->info.agent_handle == driver_handle &&
3733                             item->info.attributes &
3734                             EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER)
3735                                 ++count;
3736                 }
3737         }
3738         /*
3739          * Create buffer. In case of duplicate child controller assignments
3740          * the buffer will be too large. But that does not harm.
3741          */
3742         *number_of_children = 0;
3743         if (!count)
3744                 return EFI_SUCCESS;
3745         *child_handle_buffer = calloc(count, sizeof(efi_handle_t));
3746         if (!*child_handle_buffer)
3747                 return EFI_OUT_OF_RESOURCES;
3748         /* Copy unique child handles */
3749         list_for_each_entry(handler, &efiobj->protocols, link) {
3750                 list_for_each_entry(item, &handler->open_infos, link) {
3751                         if (item->info.agent_handle == driver_handle &&
3752                             item->info.attributes &
3753                             EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER) {
3754                                 /* Check this is a new child controller */
3755                                 duplicate = false;
3756                                 for (i = 0; i < *number_of_children; ++i) {
3757                                         if ((*child_handle_buffer)[i] ==
3758                                             item->info.controller_handle)
3759                                                 duplicate = true;
3760                                 }
3761                                 /* Copy handle to buffer */
3762                                 if (!duplicate) {
3763                                         i = (*number_of_children)++;
3764                                         (*child_handle_buffer)[i] =
3765                                                 item->info.controller_handle;
3766                                 }
3767                         }
3768                 }
3769         }
3770         return EFI_SUCCESS;
3771 }
3772
3773 /**
3774  * efi_disconnect_controller() - disconnect a controller from a driver
3775  * @controller_handle:   handle of the controller
3776  * @driver_image_handle: handle of the driver
3777  * @child_handle:        handle of the child to destroy
3778  *
3779  * This function implements the DisconnectController service.
3780  *
3781  * See the Unified Extensible Firmware Interface (UEFI) specification for
3782  * details.
3783  *
3784  * Return: status code
3785  */
3786 static efi_status_t EFIAPI efi_disconnect_controller(
3787                                 efi_handle_t controller_handle,
3788                                 efi_handle_t driver_image_handle,
3789                                 efi_handle_t child_handle)
3790 {
3791         struct efi_driver_binding_protocol *binding_protocol;
3792         efi_handle_t *child_handle_buffer = NULL;
3793         size_t number_of_children = 0;
3794         efi_status_t r;
3795         struct efi_object *efiobj;
3796         bool sole_child;
3797
3798         EFI_ENTRY("%p, %p, %p", controller_handle, driver_image_handle,
3799                   child_handle);
3800
3801         efiobj = efi_search_obj(controller_handle);
3802         if (!efiobj) {
3803                 r = EFI_INVALID_PARAMETER;
3804                 goto out;
3805         }
3806
3807         if (child_handle && !efi_search_obj(child_handle)) {
3808                 r = EFI_INVALID_PARAMETER;
3809                 goto out;
3810         }
3811
3812         /* If no driver handle is supplied, disconnect all drivers */
3813         if (!driver_image_handle) {
3814                 r = efi_disconnect_all_drivers(efiobj, NULL, child_handle);
3815                 goto out;
3816         }
3817
3818         /* Create list of child handles */
3819         r = efi_get_child_controllers(efiobj,
3820                                       driver_image_handle,
3821                                       &number_of_children,
3822                                       &child_handle_buffer);
3823         if (r != EFI_SUCCESS)
3824                 return r;
3825         sole_child = (number_of_children == 1);
3826
3827         if (child_handle) {
3828                 number_of_children = 1;
3829                 free(child_handle_buffer);
3830                 child_handle_buffer = &child_handle;
3831         }
3832
3833         /* Get the driver binding protocol */
3834         r = EFI_CALL(efi_open_protocol(driver_image_handle,
3835                                        &efi_guid_driver_binding_protocol,
3836                                        (void **)&binding_protocol,
3837                                        driver_image_handle, NULL,
3838                                        EFI_OPEN_PROTOCOL_GET_PROTOCOL));
3839         if (r != EFI_SUCCESS) {
3840                 r = EFI_INVALID_PARAMETER;
3841                 goto out;
3842         }
3843         /* Remove the children */
3844         if (number_of_children) {
3845                 r = EFI_CALL(binding_protocol->stop(binding_protocol,
3846                                                     controller_handle,
3847                                                     number_of_children,
3848                                                     child_handle_buffer));
3849                 if (r != EFI_SUCCESS) {
3850                         r = EFI_DEVICE_ERROR;
3851                         goto out;
3852                 }
3853         }
3854         /* Remove the driver */
3855         if (!child_handle || sole_child) {
3856                 r = EFI_CALL(binding_protocol->stop(binding_protocol,
3857                                                     controller_handle,
3858                                                     0, NULL));
3859                 if (r != EFI_SUCCESS) {
3860                         r = EFI_DEVICE_ERROR;
3861                         goto out;
3862                 }
3863         }
3864         efi_close_protocol(driver_image_handle,
3865                            &efi_guid_driver_binding_protocol,
3866                            driver_image_handle, NULL);
3867         r = EFI_SUCCESS;
3868 out:
3869         if (!child_handle)
3870                 free(child_handle_buffer);
3871         return EFI_EXIT(r);
3872 }
3873
3874 static struct efi_boot_services efi_boot_services = {
3875         .hdr = {
3876                 .signature = EFI_BOOT_SERVICES_SIGNATURE,
3877                 .revision = EFI_SPECIFICATION_VERSION,
3878                 .headersize = sizeof(struct efi_boot_services),
3879         },
3880         .raise_tpl = efi_raise_tpl,
3881         .restore_tpl = efi_restore_tpl,
3882         .allocate_pages = efi_allocate_pages_ext,
3883         .free_pages = efi_free_pages_ext,
3884         .get_memory_map = efi_get_memory_map_ext,
3885         .allocate_pool = efi_allocate_pool_ext,
3886         .free_pool = efi_free_pool_ext,
3887         .create_event = efi_create_event_ext,
3888         .set_timer = efi_set_timer_ext,
3889         .wait_for_event = efi_wait_for_event,
3890         .signal_event = efi_signal_event_ext,
3891         .close_event = efi_close_event,
3892         .check_event = efi_check_event,
3893         .install_protocol_interface = efi_install_protocol_interface,
3894         .reinstall_protocol_interface = efi_reinstall_protocol_interface,
3895         .uninstall_protocol_interface = efi_uninstall_protocol_interface,
3896         .handle_protocol = efi_handle_protocol,
3897         .reserved = NULL,
3898         .register_protocol_notify = efi_register_protocol_notify,
3899         .locate_handle = efi_locate_handle_ext,
3900         .locate_device_path = efi_locate_device_path,
3901         .install_configuration_table = efi_install_configuration_table_ext,
3902         .load_image = efi_load_image,
3903         .start_image = efi_start_image,
3904         .exit = efi_exit,
3905         .unload_image = efi_unload_image,
3906         .exit_boot_services = efi_exit_boot_services,
3907         .get_next_monotonic_count = efi_get_next_monotonic_count,
3908         .stall = efi_stall,
3909         .set_watchdog_timer = efi_set_watchdog_timer,
3910         .connect_controller = efi_connect_controller,
3911         .disconnect_controller = efi_disconnect_controller,
3912         .open_protocol = efi_open_protocol,
3913         .close_protocol = efi_close_protocol_ext,
3914         .open_protocol_information = efi_open_protocol_information,
3915         .protocols_per_handle = efi_protocols_per_handle,
3916         .locate_handle_buffer = efi_locate_handle_buffer,
3917         .locate_protocol = efi_locate_protocol,
3918         .install_multiple_protocol_interfaces =
3919                         efi_install_multiple_protocol_interfaces_ext,
3920         .uninstall_multiple_protocol_interfaces =
3921                         efi_uninstall_multiple_protocol_interfaces_ext,
3922         .calculate_crc32 = efi_calculate_crc32,
3923         .copy_mem = efi_copy_mem,
3924         .set_mem = efi_set_mem,
3925         .create_event_ex = efi_create_event_ex,
3926 };
3927
3928 static u16 __efi_runtime_data firmware_vendor[] = u"Das U-Boot";
3929
3930 struct efi_system_table __efi_runtime_data systab = {
3931         .hdr = {
3932                 .signature = EFI_SYSTEM_TABLE_SIGNATURE,
3933                 .revision = EFI_SPECIFICATION_VERSION,
3934                 .headersize = sizeof(struct efi_system_table),
3935         },
3936         .fw_vendor = firmware_vendor,
3937         .fw_revision = FW_VERSION << 16 | FW_PATCHLEVEL << 8,
3938         .runtime = &efi_runtime_services,
3939         .nr_tables = 0,
3940         .tables = NULL,
3941 };
3942
3943 /**
3944  * efi_initialize_system_table() - Initialize system table
3945  *
3946  * Return:      status code
3947  */
3948 efi_status_t efi_initialize_system_table(void)
3949 {
3950         efi_status_t ret;
3951
3952         /* Allocate configuration table array */
3953         ret = efi_allocate_pool(EFI_RUNTIME_SERVICES_DATA,
3954                                 EFI_MAX_CONFIGURATION_TABLES *
3955                                 sizeof(struct efi_configuration_table),
3956                                 (void **)&systab.tables);
3957
3958         /*
3959          * These entries will be set to NULL in ExitBootServices(). To avoid
3960          * relocation in SetVirtualAddressMap(), set them dynamically.
3961          */
3962         systab.con_in_handle = efi_root;
3963         systab.con_in = &efi_con_in;
3964         systab.con_out_handle = efi_root;
3965         systab.con_out = &efi_con_out;
3966         systab.stderr_handle = efi_root;
3967         systab.std_err = &efi_con_out;
3968         systab.boottime = &efi_boot_services;
3969
3970         /* Set CRC32 field in table headers */
3971         efi_update_table_header_crc32(&systab.hdr);
3972         efi_update_table_header_crc32(&efi_runtime_services.hdr);
3973         efi_update_table_header_crc32(&efi_boot_services.hdr);
3974
3975         return ret;
3976 }