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