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