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