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