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