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