]> git.sur5r.net Git - u-boot/blob - lib/efi_loader/efi_boottime.c
efi_loader: implement event groups
[u-boot] / lib / efi_loader / efi_boottime.c
1 /*
2  *  EFI application boot time services
3  *
4  *  Copyright (c) 2016 Alexander Graf
5  *
6  *  SPDX-License-Identifier:     GPL-2.0+
7  */
8
9 #include <common.h>
10 #include <div64.h>
11 #include <efi_loader.h>
12 #include <environment.h>
13 #include <malloc.h>
14 #include <asm/global_data.h>
15 #include <linux/libfdt_env.h>
16 #include <u-boot/crc.h>
17 #include <bootm.h>
18 #include <inttypes.h>
19 #include <watchdog.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 LIST_HEAD(efi_events);
31
32 /*
33  * If we're running on nasty systems (32bit ARM booting into non-EFI Linux)
34  * we need to do trickery with caches. Since we don't want to break the EFI
35  * aware boot path, only apply hacks when loading exiting directly (breaking
36  * direct Linux EFI booting along the way - oh well).
37  */
38 static bool efi_is_direct_boot = true;
39
40 /*
41  * EFI can pass arbitrary additional "tables" containing vendor specific
42  * information to the payload. One such table is the FDT table which contains
43  * a pointer to a flattened device tree blob.
44  *
45  * In most cases we want to pass an FDT to the payload, so reserve one slot of
46  * config table space for it. The pointer gets populated by do_bootefi_exec().
47  */
48 static struct efi_configuration_table __efi_runtime_data efi_conf_table[2];
49
50 #ifdef CONFIG_ARM
51 /*
52  * The "gd" pointer lives in a register on ARM and AArch64 that we declare
53  * fixed when compiling U-Boot. However, the payload does not know about that
54  * restriction so we need to manually swap its and our view of that register on
55  * EFI callback entry/exit.
56  */
57 static volatile void *efi_gd, *app_gd;
58 #endif
59
60 static int entry_count;
61 static int nesting_level;
62 /* GUID of the device tree table */
63 const efi_guid_t efi_guid_fdt = EFI_FDT_GUID;
64 /* GUID of the EFI_DRIVER_BINDING_PROTOCOL */
65 const efi_guid_t efi_guid_driver_binding_protocol =
66                         EFI_DRIVER_BINDING_PROTOCOL_GUID;
67
68 /* event group ExitBootServices() invoked */
69 const efi_guid_t efi_guid_event_group_exit_boot_services =
70                         EFI_EVENT_GROUP_EXIT_BOOT_SERVICES;
71 /* event group SetVirtualAddressMap() invoked */
72 const efi_guid_t efi_guid_event_group_virtual_address_change =
73                         EFI_EVENT_GROUP_VIRTUAL_ADDRESS_CHANGE;
74 /* event group memory map changed */
75 const efi_guid_t efi_guid_event_group_memory_map_change =
76                         EFI_EVENT_GROUP_MEMORY_MAP_CHANGE;
77 /* event group boot manager about to boot */
78 const efi_guid_t efi_guid_event_group_ready_to_boot =
79                         EFI_EVENT_GROUP_READY_TO_BOOT;
80 /* event group ResetSystem() invoked (before ExitBootServices) */
81 const efi_guid_t efi_guid_event_group_reset_system =
82                         EFI_EVENT_GROUP_RESET_SYSTEM;
83
84 static efi_status_t EFIAPI efi_disconnect_controller(
85                                         efi_handle_t controller_handle,
86                                         efi_handle_t driver_image_handle,
87                                         efi_handle_t child_handle);
88
89 /* Called on every callback entry */
90 int __efi_entry_check(void)
91 {
92         int ret = entry_count++ == 0;
93 #ifdef CONFIG_ARM
94         assert(efi_gd);
95         app_gd = gd;
96         gd = efi_gd;
97 #endif
98         return ret;
99 }
100
101 /* Called on every callback exit */
102 int __efi_exit_check(void)
103 {
104         int ret = --entry_count == 0;
105 #ifdef CONFIG_ARM
106         gd = app_gd;
107 #endif
108         return ret;
109 }
110
111 /* Called from do_bootefi_exec() */
112 void efi_save_gd(void)
113 {
114 #ifdef CONFIG_ARM
115         efi_gd = gd;
116 #endif
117 }
118
119 /*
120  * Special case handler for error/abort that just forces things back
121  * to u-boot world so we can dump out an abort msg, without any care
122  * about returning back to UEFI world.
123  */
124 void efi_restore_gd(void)
125 {
126 #ifdef CONFIG_ARM
127         /* Only restore if we're already in EFI context */
128         if (!efi_gd)
129                 return;
130         gd = efi_gd;
131 #endif
132 }
133
134 /*
135  * Return a string for indenting with two spaces per level. A maximum of ten
136  * indent levels is supported. Higher indent levels will be truncated.
137  *
138  * @level       indent level
139  * @return      indent string
140  */
141 static const char *indent_string(int level)
142 {
143         const char *indent = "                    ";
144         const int max = strlen(indent);
145
146         level = min(max, level * 2);
147         return &indent[max - level];
148 }
149
150 const char *__efi_nesting(void)
151 {
152         return indent_string(nesting_level);
153 }
154
155 const char *__efi_nesting_inc(void)
156 {
157         return indent_string(nesting_level++);
158 }
159
160 const char *__efi_nesting_dec(void)
161 {
162         return indent_string(--nesting_level);
163 }
164
165 /*
166  * Queue an EFI event.
167  *
168  * This function queues the notification function of the event for future
169  * execution.
170  *
171  * The notification function is called if the task priority level of the
172  * event is higher than the current task priority level.
173  *
174  * For the SignalEvent service see efi_signal_event_ext.
175  *
176  * @event       event to signal
177  * @check_tpl   check the TPL level
178  */
179 static void efi_queue_event(struct efi_event *event, bool check_tpl)
180 {
181         if (event->notify_function) {
182                 event->is_queued = true;
183                 /* Check TPL */
184                 if (check_tpl && efi_tpl >= event->notify_tpl)
185                         return;
186                 EFI_CALL_VOID(event->notify_function(event,
187                                                      event->notify_context));
188         }
189         event->is_queued = false;
190 }
191
192 /*
193  * Signal an EFI event.
194  *
195  * This function signals an event. If the event belongs to an event group
196  * all events of the group are signaled. If they are of type EVT_NOTIFY_SIGNAL
197  * their notification function is queued.
198  *
199  * For the SignalEvent service see efi_signal_event_ext.
200  *
201  * @event       event to signal
202  * @check_tpl   check the TPL level
203  */
204 void efi_signal_event(struct efi_event *event, bool check_tpl)
205 {
206         if (event->group) {
207                 struct efi_event *evt;
208
209                 /*
210                  * The signaled state has to set before executing any
211                  * notification function
212                  */
213                 list_for_each_entry(evt, &efi_events, link) {
214                         if (!evt->group || guidcmp(evt->group, event->group))
215                                 continue;
216                         if (evt->is_signaled)
217                                 continue;
218                         evt->is_signaled = true;
219                         if (evt->type & EVT_NOTIFY_SIGNAL &&
220                             evt->notify_function)
221                                 evt->is_queued = true;
222                 }
223                 list_for_each_entry(evt, &efi_events, link) {
224                         if (!evt->group || guidcmp(evt->group, event->group))
225                                 continue;
226                         if (evt->is_queued)
227                                 efi_queue_event(evt, check_tpl);
228                 }
229         } else if (!event->is_signaled) {
230                 event->is_signaled = true;
231                 if (event->type & EVT_NOTIFY_SIGNAL)
232                         efi_queue_event(event, check_tpl);
233         }
234 }
235
236 /*
237  * Raise the task priority level.
238  *
239  * This function implements the RaiseTpl service.
240  * See the Unified Extensible Firmware Interface (UEFI) specification
241  * for details.
242  *
243  * @new_tpl     new value of the task priority level
244  * @return      old value of the task priority level
245  */
246 static unsigned long EFIAPI efi_raise_tpl(efi_uintn_t new_tpl)
247 {
248         efi_uintn_t old_tpl = efi_tpl;
249
250         EFI_ENTRY("0x%zx", new_tpl);
251
252         if (new_tpl < efi_tpl)
253                 debug("WARNING: new_tpl < current_tpl in %s\n", __func__);
254         efi_tpl = new_tpl;
255         if (efi_tpl > TPL_HIGH_LEVEL)
256                 efi_tpl = TPL_HIGH_LEVEL;
257
258         EFI_EXIT(EFI_SUCCESS);
259         return old_tpl;
260 }
261
262 /*
263  * Lower the task priority level.
264  *
265  * This function implements the RestoreTpl service.
266  * See the Unified Extensible Firmware Interface (UEFI) specification
267  * for details.
268  *
269  * @old_tpl     value of the task priority level to be restored
270  */
271 static void EFIAPI efi_restore_tpl(efi_uintn_t old_tpl)
272 {
273         EFI_ENTRY("0x%zx", old_tpl);
274
275         if (old_tpl > efi_tpl)
276                 debug("WARNING: old_tpl > current_tpl in %s\n", __func__);
277         efi_tpl = old_tpl;
278         if (efi_tpl > TPL_HIGH_LEVEL)
279                 efi_tpl = TPL_HIGH_LEVEL;
280
281         EFI_EXIT(EFI_SUCCESS);
282 }
283
284 /*
285  * Allocate memory pages.
286  *
287  * This function implements the AllocatePages service.
288  * See the Unified Extensible Firmware Interface (UEFI) specification
289  * for details.
290  *
291  * @type                type of allocation to be performed
292  * @memory_type         usage type of the allocated memory
293  * @pages               number of pages to be allocated
294  * @memory              allocated memory
295  * @return              status code
296  */
297 static efi_status_t EFIAPI efi_allocate_pages_ext(int type, int memory_type,
298                                                   efi_uintn_t pages,
299                                                   uint64_t *memory)
300 {
301         efi_status_t r;
302
303         EFI_ENTRY("%d, %d, 0x%zx, %p", type, memory_type, pages, memory);
304         r = efi_allocate_pages(type, memory_type, pages, memory);
305         return EFI_EXIT(r);
306 }
307
308 /*
309  * Free memory pages.
310  *
311  * This function implements the FreePages service.
312  * See the Unified Extensible Firmware Interface (UEFI) specification
313  * for details.
314  *
315  * @memory      start of the memory area to be freed
316  * @pages       number of pages to be freed
317  * @return      status code
318  */
319 static efi_status_t EFIAPI efi_free_pages_ext(uint64_t memory,
320                                               efi_uintn_t pages)
321 {
322         efi_status_t r;
323
324         EFI_ENTRY("%" PRIx64 ", 0x%zx", memory, pages);
325         r = efi_free_pages(memory, pages);
326         return EFI_EXIT(r);
327 }
328
329 /*
330  * Get map describing memory usage.
331  *
332  * This function implements the GetMemoryMap service.
333  * See the Unified Extensible Firmware Interface (UEFI) specification
334  * for details.
335  *
336  * @memory_map_size     on entry the size, in bytes, of the memory map buffer,
337  *                      on exit the size of the copied memory map
338  * @memory_map          buffer to which the memory map is written
339  * @map_key             key for the memory map
340  * @descriptor_size     size of an individual memory descriptor
341  * @descriptor_version  version number of the memory descriptor structure
342  * @return              status code
343  */
344 static efi_status_t EFIAPI efi_get_memory_map_ext(
345                                         efi_uintn_t *memory_map_size,
346                                         struct efi_mem_desc *memory_map,
347                                         efi_uintn_t *map_key,
348                                         efi_uintn_t *descriptor_size,
349                                         uint32_t *descriptor_version)
350 {
351         efi_status_t r;
352
353         EFI_ENTRY("%p, %p, %p, %p, %p", memory_map_size, memory_map,
354                   map_key, descriptor_size, descriptor_version);
355         r = efi_get_memory_map(memory_map_size, memory_map, map_key,
356                                descriptor_size, descriptor_version);
357         return EFI_EXIT(r);
358 }
359
360 /*
361  * Allocate memory from pool.
362  *
363  * This function implements the AllocatePool service.
364  * See the Unified Extensible Firmware Interface (UEFI) specification
365  * for details.
366  *
367  * @pool_type   type of the pool from which memory is to be allocated
368  * @size        number of bytes to be allocated
369  * @buffer      allocated memory
370  * @return      status code
371  */
372 static efi_status_t EFIAPI efi_allocate_pool_ext(int pool_type,
373                                                  efi_uintn_t size,
374                                                  void **buffer)
375 {
376         efi_status_t r;
377
378         EFI_ENTRY("%d, %zd, %p", pool_type, size, buffer);
379         r = efi_allocate_pool(pool_type, size, buffer);
380         return EFI_EXIT(r);
381 }
382
383 /*
384  * Free memory from pool.
385  *
386  * This function implements the FreePool service.
387  * See the Unified Extensible Firmware Interface (UEFI) specification
388  * for details.
389  *
390  * @buffer      start of memory to be freed
391  * @return      status code
392  */
393 static efi_status_t EFIAPI efi_free_pool_ext(void *buffer)
394 {
395         efi_status_t r;
396
397         EFI_ENTRY("%p", buffer);
398         r = efi_free_pool(buffer);
399         return EFI_EXIT(r);
400 }
401
402 /*
403  * Add a new object to the object list.
404  *
405  * The protocols list is initialized.
406  * The object handle is set.
407  *
408  * @obj object to be added
409  */
410 void efi_add_handle(struct efi_object *obj)
411 {
412         if (!obj)
413                 return;
414         INIT_LIST_HEAD(&obj->protocols);
415         obj->handle = obj;
416         list_add_tail(&obj->link, &efi_obj_list);
417 }
418
419 /*
420  * Create handle.
421  *
422  * @handle      new handle
423  * @return      status code
424  */
425 efi_status_t efi_create_handle(efi_handle_t *handle)
426 {
427         struct efi_object *obj;
428         efi_status_t r;
429
430         r = efi_allocate_pool(EFI_ALLOCATE_ANY_PAGES,
431                               sizeof(struct efi_object),
432                               (void **)&obj);
433         if (r != EFI_SUCCESS)
434                 return r;
435         efi_add_handle(obj);
436         *handle = obj->handle;
437         return r;
438 }
439
440 /*
441  * Find a protocol on a handle.
442  *
443  * @handle              handle
444  * @protocol_guid       GUID of the protocol
445  * @handler             reference to the protocol
446  * @return              status code
447  */
448 efi_status_t efi_search_protocol(const efi_handle_t handle,
449                                  const efi_guid_t *protocol_guid,
450                                  struct efi_handler **handler)
451 {
452         struct efi_object *efiobj;
453         struct list_head *lhandle;
454
455         if (!handle || !protocol_guid)
456                 return EFI_INVALID_PARAMETER;
457         efiobj = efi_search_obj(handle);
458         if (!efiobj)
459                 return EFI_INVALID_PARAMETER;
460         list_for_each(lhandle, &efiobj->protocols) {
461                 struct efi_handler *protocol;
462
463                 protocol = list_entry(lhandle, struct efi_handler, link);
464                 if (!guidcmp(protocol->guid, protocol_guid)) {
465                         if (handler)
466                                 *handler = protocol;
467                         return EFI_SUCCESS;
468                 }
469         }
470         return EFI_NOT_FOUND;
471 }
472
473 /*
474  * Delete protocol from a handle.
475  *
476  * @handle                      handle from which the protocol shall be deleted
477  * @protocol                    GUID of the protocol to be deleted
478  * @protocol_interface          interface of the protocol implementation
479  * @return                      status code
480  */
481 efi_status_t efi_remove_protocol(const efi_handle_t handle,
482                                  const efi_guid_t *protocol,
483                                  void *protocol_interface)
484 {
485         struct efi_handler *handler;
486         efi_status_t ret;
487
488         ret = efi_search_protocol(handle, protocol, &handler);
489         if (ret != EFI_SUCCESS)
490                 return ret;
491         if (guidcmp(handler->guid, protocol))
492                 return EFI_INVALID_PARAMETER;
493         list_del(&handler->link);
494         free(handler);
495         return EFI_SUCCESS;
496 }
497
498 /*
499  * Delete all protocols from a handle.
500  *
501  * @handle      handle from which the protocols shall be deleted
502  * @return      status code
503  */
504 efi_status_t efi_remove_all_protocols(const efi_handle_t handle)
505 {
506         struct efi_object *efiobj;
507         struct efi_handler *protocol;
508         struct efi_handler *pos;
509
510         efiobj = efi_search_obj(handle);
511         if (!efiobj)
512                 return EFI_INVALID_PARAMETER;
513         list_for_each_entry_safe(protocol, pos, &efiobj->protocols, link) {
514                 efi_status_t ret;
515
516                 ret = efi_remove_protocol(handle, protocol->guid,
517                                           protocol->protocol_interface);
518                 if (ret != EFI_SUCCESS)
519                         return ret;
520         }
521         return EFI_SUCCESS;
522 }
523
524 /*
525  * Delete handle.
526  *
527  * @handle      handle to delete
528  */
529 void efi_delete_handle(struct efi_object *obj)
530 {
531         if (!obj)
532                 return;
533         efi_remove_all_protocols(obj->handle);
534         list_del(&obj->link);
535         free(obj);
536 }
537
538 /*
539  * Check if a pointer is a valid event.
540  *
541  * @event               pointer to check
542  * @return              status code
543  */
544 static efi_status_t efi_is_event(const struct efi_event *event)
545 {
546         const struct efi_event *evt;
547
548         if (!event)
549                 return EFI_INVALID_PARAMETER;
550         list_for_each_entry(evt, &efi_events, link) {
551                 if (evt == event)
552                         return EFI_SUCCESS;
553         }
554         return EFI_INVALID_PARAMETER;
555 }
556
557 /*
558  * Create an event.
559  *
560  * This function is used inside U-Boot code to create an event.
561  *
562  * For the API function implementing the CreateEvent service see
563  * efi_create_event_ext.
564  *
565  * @type                type of the event to create
566  * @notify_tpl          task priority level of the event
567  * @notify_function     notification function of the event
568  * @notify_context      pointer passed to the notification function
569  * @event               created event
570  * @return              status code
571  */
572 efi_status_t efi_create_event(uint32_t type, efi_uintn_t notify_tpl,
573                               void (EFIAPI *notify_function) (
574                                         struct efi_event *event,
575                                         void *context),
576                               void *notify_context, efi_guid_t *group,
577                               struct efi_event **event)
578 {
579         struct efi_event *evt;
580
581         if (event == NULL)
582                 return EFI_INVALID_PARAMETER;
583
584         if ((type & EVT_NOTIFY_SIGNAL) && (type & EVT_NOTIFY_WAIT))
585                 return EFI_INVALID_PARAMETER;
586
587         if ((type & (EVT_NOTIFY_SIGNAL | EVT_NOTIFY_WAIT)) &&
588             notify_function == NULL)
589                 return EFI_INVALID_PARAMETER;
590
591         evt = calloc(1, sizeof(struct efi_event));
592         if (!evt)
593                 return EFI_OUT_OF_RESOURCES;
594         evt->type = type;
595         evt->notify_tpl = notify_tpl;
596         evt->notify_function = notify_function;
597         evt->notify_context = notify_context;
598         evt->group = group;
599         /* Disable timers on bootup */
600         evt->trigger_next = -1ULL;
601         evt->is_queued = false;
602         evt->is_signaled = false;
603         list_add_tail(&evt->link, &efi_events);
604         *event = evt;
605         return EFI_SUCCESS;
606 }
607
608 /*
609  * Create an event in a group.
610  *
611  * This function implements the CreateEventEx service.
612  * See the Unified Extensible Firmware Interface (UEFI) specification
613  * for details.
614  * TODO: Support event groups
615  *
616  * @type                type of the event to create
617  * @notify_tpl          task priority level of the event
618  * @notify_function     notification function of the event
619  * @notify_context      pointer passed to the notification function
620  * @event               created event
621  * @event_group         event group
622  * @return              status code
623  */
624 efi_status_t EFIAPI efi_create_event_ex(uint32_t type, efi_uintn_t notify_tpl,
625                                         void (EFIAPI *notify_function) (
626                                                         struct efi_event *event,
627                                                         void *context),
628                                         void *notify_context,
629                                         efi_guid_t *event_group,
630                                         struct efi_event **event)
631 {
632         EFI_ENTRY("%d, 0x%zx, %p, %p, %pUl", type, notify_tpl, notify_function,
633                   notify_context, event_group);
634         return EFI_EXIT(efi_create_event(type, notify_tpl, notify_function,
635                                          notify_context, event_group, event));
636 }
637
638 /*
639  * Create an event.
640  *
641  * This function implements the CreateEvent service.
642  * See the Unified Extensible Firmware Interface (UEFI) specification
643  * for details.
644  *
645  * @type                type of the event to create
646  * @notify_tpl          task priority level of the event
647  * @notify_function     notification function of the event
648  * @notify_context      pointer passed to the notification function
649  * @event               created event
650  * @return              status code
651  */
652 static efi_status_t EFIAPI efi_create_event_ext(
653                         uint32_t type, efi_uintn_t notify_tpl,
654                         void (EFIAPI *notify_function) (
655                                         struct efi_event *event,
656                                         void *context),
657                         void *notify_context, struct efi_event **event)
658 {
659         EFI_ENTRY("%d, 0x%zx, %p, %p", type, notify_tpl, notify_function,
660                   notify_context);
661         return EFI_EXIT(efi_create_event(type, notify_tpl, notify_function,
662                                          notify_context, NULL, event));
663 }
664
665 /*
666  * Check if a timer event has occurred or a queued notification function should
667  * be called.
668  *
669  * Our timers have to work without interrupts, so we check whenever keyboard
670  * input or disk accesses happen if enough time elapsed for them to fire.
671  */
672 void efi_timer_check(void)
673 {
674         struct efi_event *evt;
675         u64 now = timer_get_us();
676
677         list_for_each_entry(evt, &efi_events, link) {
678                 if (evt->is_queued)
679                         efi_queue_event(evt, true);
680                 if (!(evt->type & EVT_TIMER) || now < evt->trigger_next)
681                         continue;
682                 switch (evt->trigger_type) {
683                 case EFI_TIMER_RELATIVE:
684                         evt->trigger_type = EFI_TIMER_STOP;
685                         break;
686                 case EFI_TIMER_PERIODIC:
687                         evt->trigger_next += evt->trigger_time;
688                         break;
689                 default:
690                         continue;
691                 }
692                 evt->is_signaled = false;
693                 efi_signal_event(evt, true);
694         }
695         WATCHDOG_RESET();
696 }
697
698 /*
699  * Set the trigger time for a timer event or stop the event.
700  *
701  * This is the function for internal usage in U-Boot. For the API function
702  * implementing the SetTimer service see efi_set_timer_ext.
703  *
704  * @event               event for which the timer is set
705  * @type                type of the timer
706  * @trigger_time        trigger period in multiples of 100ns
707  * @return              status code
708  */
709 efi_status_t efi_set_timer(struct efi_event *event, enum efi_timer_delay type,
710                            uint64_t trigger_time)
711 {
712         /* Check that the event is valid */
713         if (efi_is_event(event) != EFI_SUCCESS || !(event->type & EVT_TIMER))
714                 return EFI_INVALID_PARAMETER;
715
716         /*
717          * The parameter defines a multiple of 100ns.
718          * We use multiples of 1000ns. So divide by 10.
719          */
720         do_div(trigger_time, 10);
721
722         switch (type) {
723         case EFI_TIMER_STOP:
724                 event->trigger_next = -1ULL;
725                 break;
726         case EFI_TIMER_PERIODIC:
727         case EFI_TIMER_RELATIVE:
728                 event->trigger_next = timer_get_us() + trigger_time;
729                 break;
730         default:
731                 return EFI_INVALID_PARAMETER;
732         }
733         event->trigger_type = type;
734         event->trigger_time = trigger_time;
735         event->is_signaled = false;
736         return EFI_SUCCESS;
737 }
738
739 /*
740  * Set the trigger time for a timer event or stop the event.
741  *
742  * This function implements the SetTimer service.
743  * See the Unified Extensible Firmware Interface (UEFI) specification
744  * for details.
745  *
746  * @event               event for which the timer is set
747  * @type                type of the timer
748  * @trigger_time        trigger period in multiples of 100ns
749  * @return              status code
750  */
751 static efi_status_t EFIAPI efi_set_timer_ext(struct efi_event *event,
752                                              enum efi_timer_delay type,
753                                              uint64_t trigger_time)
754 {
755         EFI_ENTRY("%p, %d, %" PRIx64, event, type, trigger_time);
756         return EFI_EXIT(efi_set_timer(event, type, trigger_time));
757 }
758
759 /*
760  * Wait for events to be signaled.
761  *
762  * This function implements the WaitForEvent service.
763  * See the Unified Extensible Firmware Interface (UEFI) specification
764  * for details.
765  *
766  * @num_events  number of events to be waited for
767  * @events      events to be waited for
768  * @index       index of the event that was signaled
769  * @return      status code
770  */
771 static efi_status_t EFIAPI efi_wait_for_event(efi_uintn_t num_events,
772                                               struct efi_event **event,
773                                               efi_uintn_t *index)
774 {
775         int i;
776
777         EFI_ENTRY("%zd, %p, %p", num_events, event, index);
778
779         /* Check parameters */
780         if (!num_events || !event)
781                 return EFI_EXIT(EFI_INVALID_PARAMETER);
782         /* Check TPL */
783         if (efi_tpl != TPL_APPLICATION)
784                 return EFI_EXIT(EFI_UNSUPPORTED);
785         for (i = 0; i < num_events; ++i) {
786                 if (efi_is_event(event[i]) != EFI_SUCCESS)
787                         return EFI_EXIT(EFI_INVALID_PARAMETER);
788                 if (!event[i]->type || event[i]->type & EVT_NOTIFY_SIGNAL)
789                         return EFI_EXIT(EFI_INVALID_PARAMETER);
790                 if (!event[i]->is_signaled)
791                         efi_queue_event(event[i], true);
792         }
793
794         /* Wait for signal */
795         for (;;) {
796                 for (i = 0; i < num_events; ++i) {
797                         if (event[i]->is_signaled)
798                                 goto out;
799                 }
800                 /* Allow events to occur. */
801                 efi_timer_check();
802         }
803
804 out:
805         /*
806          * Reset the signal which is passed to the caller to allow periodic
807          * events to occur.
808          */
809         event[i]->is_signaled = false;
810         if (index)
811                 *index = i;
812
813         return EFI_EXIT(EFI_SUCCESS);
814 }
815
816 /*
817  * Signal an EFI event.
818  *
819  * This function implements the SignalEvent service.
820  * See the Unified Extensible Firmware Interface (UEFI) specification
821  * for details.
822  *
823  * This functions sets the signaled state of the event and queues the
824  * notification function for execution.
825  *
826  * @event       event to signal
827  * @return      status code
828  */
829 static efi_status_t EFIAPI efi_signal_event_ext(struct efi_event *event)
830 {
831         EFI_ENTRY("%p", event);
832         if (efi_is_event(event) != EFI_SUCCESS)
833                 return EFI_EXIT(EFI_INVALID_PARAMETER);
834         efi_signal_event(event, true);
835         return EFI_EXIT(EFI_SUCCESS);
836 }
837
838 /*
839  * Close an EFI event.
840  *
841  * This function implements the CloseEvent service.
842  * See the Unified Extensible Firmware Interface (UEFI) specification
843  * for details.
844  *
845  * @event       event to close
846  * @return      status code
847  */
848 static efi_status_t EFIAPI efi_close_event(struct efi_event *event)
849 {
850         EFI_ENTRY("%p", event);
851         if (efi_is_event(event) != EFI_SUCCESS)
852                 return EFI_EXIT(EFI_INVALID_PARAMETER);
853         list_del(&event->link);
854         free(event);
855         return EFI_EXIT(EFI_SUCCESS);
856 }
857
858 /*
859  * Check if an event is signaled.
860  *
861  * This function implements the CheckEvent service.
862  * See the Unified Extensible Firmware Interface (UEFI) specification
863  * for details.
864  *
865  * If an event is not signaled yet, the notification function is queued.
866  * The signaled state is cleared.
867  *
868  * @event       event to check
869  * @return      status code
870  */
871 static efi_status_t EFIAPI efi_check_event(struct efi_event *event)
872 {
873         EFI_ENTRY("%p", event);
874         efi_timer_check();
875         if (efi_is_event(event) != EFI_SUCCESS ||
876             event->type & EVT_NOTIFY_SIGNAL)
877                 return EFI_EXIT(EFI_INVALID_PARAMETER);
878         if (!event->is_signaled)
879                 efi_queue_event(event, true);
880         if (event->is_signaled) {
881                 event->is_signaled = false;
882                 return EFI_EXIT(EFI_SUCCESS);
883         }
884         return EFI_EXIT(EFI_NOT_READY);
885 }
886
887 /*
888  * Find the internal EFI object for a handle.
889  *
890  * @handle      handle to find
891  * @return      EFI object
892  */
893 struct efi_object *efi_search_obj(const efi_handle_t handle)
894 {
895         struct efi_object *efiobj;
896
897         list_for_each_entry(efiobj, &efi_obj_list, link) {
898                 if (efiobj->handle == handle)
899                         return efiobj;
900         }
901
902         return NULL;
903 }
904
905 /*
906  * Create open protocol info entry and add it to a protocol.
907  *
908  * @handler     handler of a protocol
909  * @return      open protocol info entry
910  */
911 static struct efi_open_protocol_info_entry *efi_create_open_info(
912                         struct efi_handler *handler)
913 {
914         struct efi_open_protocol_info_item *item;
915
916         item = calloc(1, sizeof(struct efi_open_protocol_info_item));
917         if (!item)
918                 return NULL;
919         /* Append the item to the open protocol info list. */
920         list_add_tail(&item->link, &handler->open_infos);
921
922         return &item->info;
923 }
924
925 /*
926  * Remove an open protocol info entry from a protocol.
927  *
928  * @handler     handler of a protocol
929  * @return      status code
930  */
931 static efi_status_t efi_delete_open_info(
932                         struct efi_open_protocol_info_item *item)
933 {
934         list_del(&item->link);
935         free(item);
936         return EFI_SUCCESS;
937 }
938
939 /*
940  * Install new protocol on a handle.
941  *
942  * @handle                      handle on which the protocol shall be installed
943  * @protocol                    GUID of the protocol to be installed
944  * @protocol_interface          interface of the protocol implementation
945  * @return                      status code
946  */
947 efi_status_t efi_add_protocol(const efi_handle_t handle,
948                               const efi_guid_t *protocol,
949                               void *protocol_interface)
950 {
951         struct efi_object *efiobj;
952         struct efi_handler *handler;
953         efi_status_t ret;
954
955         efiobj = efi_search_obj(handle);
956         if (!efiobj)
957                 return EFI_INVALID_PARAMETER;
958         ret = efi_search_protocol(handle, protocol, NULL);
959         if (ret != EFI_NOT_FOUND)
960                 return EFI_INVALID_PARAMETER;
961         handler = calloc(1, sizeof(struct efi_handler));
962         if (!handler)
963                 return EFI_OUT_OF_RESOURCES;
964         handler->guid = protocol;
965         handler->protocol_interface = protocol_interface;
966         INIT_LIST_HEAD(&handler->open_infos);
967         list_add_tail(&handler->link, &efiobj->protocols);
968         if (!guidcmp(&efi_guid_device_path, protocol))
969                 EFI_PRINT("installed device path '%pD'\n", protocol_interface);
970         return EFI_SUCCESS;
971 }
972
973 /*
974  * Install protocol interface.
975  *
976  * This function implements the InstallProtocolInterface service.
977  * See the Unified Extensible Firmware Interface (UEFI) specification
978  * for details.
979  *
980  * @handle                      handle on which the protocol shall be installed
981  * @protocol                    GUID of the protocol to be installed
982  * @protocol_interface_type     type of the interface to be installed,
983  *                              always EFI_NATIVE_INTERFACE
984  * @protocol_interface          interface of the protocol implementation
985  * @return                      status code
986  */
987 static efi_status_t EFIAPI efi_install_protocol_interface(
988                         void **handle, const efi_guid_t *protocol,
989                         int protocol_interface_type, void *protocol_interface)
990 {
991         efi_status_t r;
992
993         EFI_ENTRY("%p, %pUl, %d, %p", handle, protocol, protocol_interface_type,
994                   protocol_interface);
995
996         if (!handle || !protocol ||
997             protocol_interface_type != EFI_NATIVE_INTERFACE) {
998                 r = EFI_INVALID_PARAMETER;
999                 goto out;
1000         }
1001
1002         /* Create new handle if requested. */
1003         if (!*handle) {
1004                 r = efi_create_handle(handle);
1005                 if (r != EFI_SUCCESS)
1006                         goto out;
1007                 debug("%sEFI: new handle %p\n", indent_string(nesting_level),
1008                       *handle);
1009         } else {
1010                 debug("%sEFI: handle %p\n", indent_string(nesting_level),
1011                       *handle);
1012         }
1013         /* Add new protocol */
1014         r = efi_add_protocol(*handle, protocol, protocol_interface);
1015 out:
1016         return EFI_EXIT(r);
1017 }
1018
1019 /*
1020  * Reinstall protocol interface.
1021  *
1022  * This function implements the ReinstallProtocolInterface service.
1023  * See the Unified Extensible Firmware Interface (UEFI) specification
1024  * for details.
1025  *
1026  * @handle                      handle on which the protocol shall be
1027  *                              reinstalled
1028  * @protocol                    GUID of the protocol to be installed
1029  * @old_interface               interface to be removed
1030  * @new_interface               interface to be installed
1031  * @return                      status code
1032  */
1033 static efi_status_t EFIAPI efi_reinstall_protocol_interface(
1034                         efi_handle_t handle, const efi_guid_t *protocol,
1035                         void *old_interface, void *new_interface)
1036 {
1037         EFI_ENTRY("%p, %pUl, %p, %p", handle, protocol, old_interface,
1038                   new_interface);
1039         return EFI_EXIT(EFI_ACCESS_DENIED);
1040 }
1041
1042 /*
1043  * Get all drivers associated to a controller.
1044  * The allocated buffer has to be freed with free().
1045  *
1046  * @efiobj                      handle of the controller
1047  * @protocol                    protocol guid (optional)
1048  * @number_of_drivers           number of child controllers
1049  * @driver_handle_buffer        handles of the the drivers
1050  * @return                      status code
1051  */
1052 static efi_status_t efi_get_drivers(struct efi_object *efiobj,
1053                                     const efi_guid_t *protocol,
1054                                     efi_uintn_t *number_of_drivers,
1055                                     efi_handle_t **driver_handle_buffer)
1056 {
1057         struct efi_handler *handler;
1058         struct efi_open_protocol_info_item *item;
1059         efi_uintn_t count = 0, i;
1060         bool duplicate;
1061
1062         /* Count all driver associations */
1063         list_for_each_entry(handler, &efiobj->protocols, link) {
1064                 if (protocol && guidcmp(handler->guid, protocol))
1065                         continue;
1066                 list_for_each_entry(item, &handler->open_infos, link) {
1067                         if (item->info.attributes &
1068                             EFI_OPEN_PROTOCOL_BY_DRIVER)
1069                                 ++count;
1070                 }
1071         }
1072         /*
1073          * Create buffer. In case of duplicate driver assignments the buffer
1074          * will be too large. But that does not harm.
1075          */
1076         *number_of_drivers = 0;
1077         *driver_handle_buffer = calloc(count, sizeof(efi_handle_t));
1078         if (!*driver_handle_buffer)
1079                 return EFI_OUT_OF_RESOURCES;
1080         /* Collect unique driver handles */
1081         list_for_each_entry(handler, &efiobj->protocols, link) {
1082                 if (protocol && guidcmp(handler->guid, protocol))
1083                         continue;
1084                 list_for_each_entry(item, &handler->open_infos, link) {
1085                         if (item->info.attributes &
1086                             EFI_OPEN_PROTOCOL_BY_DRIVER) {
1087                                 /* Check this is a new driver */
1088                                 duplicate = false;
1089                                 for (i = 0; i < *number_of_drivers; ++i) {
1090                                         if ((*driver_handle_buffer)[i] ==
1091                                             item->info.agent_handle)
1092                                                 duplicate = true;
1093                                 }
1094                                 /* Copy handle to buffer */
1095                                 if (!duplicate) {
1096                                         i = (*number_of_drivers)++;
1097                                         (*driver_handle_buffer)[i] =
1098                                                 item->info.agent_handle;
1099                                 }
1100                         }
1101                 }
1102         }
1103         return EFI_SUCCESS;
1104 }
1105
1106 /*
1107  * Disconnect all drivers from a controller.
1108  *
1109  * This function implements the DisconnectController service.
1110  * See the Unified Extensible Firmware Interface (UEFI) specification
1111  * for details.
1112  *
1113  * @efiobj              handle of the controller
1114  * @protocol            protocol guid (optional)
1115  * @child_handle        handle of the child to destroy
1116  * @return              status code
1117  */
1118 static efi_status_t efi_disconnect_all_drivers(
1119                                 struct efi_object *efiobj,
1120                                 const efi_guid_t *protocol,
1121                                 efi_handle_t child_handle)
1122 {
1123         efi_uintn_t number_of_drivers;
1124         efi_handle_t *driver_handle_buffer;
1125         efi_status_t r, ret;
1126
1127         ret = efi_get_drivers(efiobj, protocol, &number_of_drivers,
1128                               &driver_handle_buffer);
1129         if (ret != EFI_SUCCESS)
1130                 return ret;
1131
1132         ret = EFI_NOT_FOUND;
1133         while (number_of_drivers) {
1134                 r = EFI_CALL(efi_disconnect_controller(
1135                                 efiobj->handle,
1136                                 driver_handle_buffer[--number_of_drivers],
1137                                 child_handle));
1138                 if (r == EFI_SUCCESS)
1139                         ret = r;
1140         }
1141         free(driver_handle_buffer);
1142         return ret;
1143 }
1144
1145 /*
1146  * Uninstall protocol interface.
1147  *
1148  * This function implements the UninstallProtocolInterface service.
1149  * See the Unified Extensible Firmware Interface (UEFI) specification
1150  * for details.
1151  *
1152  * @handle                      handle from which the protocol shall be removed
1153  * @protocol                    GUID of the protocol to be removed
1154  * @protocol_interface          interface to be removed
1155  * @return                      status code
1156  */
1157 static efi_status_t EFIAPI efi_uninstall_protocol_interface(
1158                                 efi_handle_t handle, const efi_guid_t *protocol,
1159                                 void *protocol_interface)
1160 {
1161         struct efi_object *efiobj;
1162         struct efi_handler *handler;
1163         struct efi_open_protocol_info_item *item;
1164         struct efi_open_protocol_info_item *pos;
1165         efi_status_t r;
1166
1167         EFI_ENTRY("%p, %pUl, %p", handle, protocol, protocol_interface);
1168
1169         /* Check handle */
1170         efiobj = efi_search_obj(handle);
1171         if (!efiobj) {
1172                 r = EFI_INVALID_PARAMETER;
1173                 goto out;
1174         }
1175         /* Find the protocol on the handle */
1176         r = efi_search_protocol(handle, protocol, &handler);
1177         if (r != EFI_SUCCESS)
1178                 goto out;
1179         /* Disconnect controllers */
1180         efi_disconnect_all_drivers(efiobj, protocol, NULL);
1181         if (!list_empty(&handler->open_infos)) {
1182                 r =  EFI_ACCESS_DENIED;
1183                 goto out;
1184         }
1185         /* Close protocol */
1186         list_for_each_entry_safe(item, pos, &handler->open_infos, link) {
1187                 if (item->info.attributes ==
1188                         EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL ||
1189                     item->info.attributes == EFI_OPEN_PROTOCOL_GET_PROTOCOL ||
1190                     item->info.attributes == EFI_OPEN_PROTOCOL_TEST_PROTOCOL)
1191                         list_del(&item->link);
1192         }
1193         if (!list_empty(&handler->open_infos)) {
1194                 r =  EFI_ACCESS_DENIED;
1195                 goto out;
1196         }
1197         r = efi_remove_protocol(handle, protocol, protocol_interface);
1198 out:
1199         return EFI_EXIT(r);
1200 }
1201
1202 /*
1203  * Register an event for notification when a protocol is installed.
1204  *
1205  * This function implements the RegisterProtocolNotify service.
1206  * See the Unified Extensible Firmware Interface (UEFI) specification
1207  * for details.
1208  *
1209  * @protocol            GUID of the protocol whose installation shall be
1210  *                      notified
1211  * @event               event to be signaled upon installation of the protocol
1212  * @registration        key for retrieving the registration information
1213  * @return              status code
1214  */
1215 static efi_status_t EFIAPI efi_register_protocol_notify(
1216                                                 const efi_guid_t *protocol,
1217                                                 struct efi_event *event,
1218                                                 void **registration)
1219 {
1220         EFI_ENTRY("%pUl, %p, %p", protocol, event, registration);
1221         return EFI_EXIT(EFI_OUT_OF_RESOURCES);
1222 }
1223
1224 /*
1225  * Determine if an EFI handle implements a protocol.
1226  *
1227  * See the documentation of the LocateHandle service in the UEFI specification.
1228  *
1229  * @search_type         selection criterion
1230  * @protocol            GUID of the protocol
1231  * @search_key          registration key
1232  * @efiobj              handle
1233  * @return              0 if the handle implements the protocol
1234  */
1235 static int efi_search(enum efi_locate_search_type search_type,
1236                       const efi_guid_t *protocol, void *search_key,
1237                       struct efi_object *efiobj)
1238 {
1239         efi_status_t ret;
1240
1241         switch (search_type) {
1242         case ALL_HANDLES:
1243                 return 0;
1244         case BY_REGISTER_NOTIFY:
1245                 /* TODO: RegisterProtocolNotify is not implemented yet */
1246                 return -1;
1247         case BY_PROTOCOL:
1248                 ret = efi_search_protocol(efiobj->handle, protocol, NULL);
1249                 return (ret != EFI_SUCCESS);
1250         default:
1251                 /* Invalid search type */
1252                 return -1;
1253         }
1254 }
1255
1256 /*
1257  * Locate handles implementing a protocol.
1258  *
1259  * This function is meant for U-Boot internal calls. For the API implementation
1260  * of the LocateHandle service see efi_locate_handle_ext.
1261  *
1262  * @search_type         selection criterion
1263  * @protocol            GUID of the protocol
1264  * @search_key          registration key
1265  * @buffer_size         size of the buffer to receive the handles in bytes
1266  * @buffer              buffer to receive the relevant handles
1267  * @return              status code
1268  */
1269 static efi_status_t efi_locate_handle(
1270                         enum efi_locate_search_type search_type,
1271                         const efi_guid_t *protocol, void *search_key,
1272                         efi_uintn_t *buffer_size, efi_handle_t *buffer)
1273 {
1274         struct efi_object *efiobj;
1275         efi_uintn_t size = 0;
1276
1277         /* Check parameters */
1278         switch (search_type) {
1279         case ALL_HANDLES:
1280                 break;
1281         case BY_REGISTER_NOTIFY:
1282                 if (!search_key)
1283                         return EFI_INVALID_PARAMETER;
1284                 /* RegisterProtocolNotify is not implemented yet */
1285                 return EFI_UNSUPPORTED;
1286         case BY_PROTOCOL:
1287                 if (!protocol)
1288                         return EFI_INVALID_PARAMETER;
1289                 break;
1290         default:
1291                 return EFI_INVALID_PARAMETER;
1292         }
1293
1294         /*
1295          * efi_locate_handle_buffer uses this function for
1296          * the calculation of the necessary buffer size.
1297          * So do not require a buffer for buffersize == 0.
1298          */
1299         if (!buffer_size || (*buffer_size && !buffer))
1300                 return EFI_INVALID_PARAMETER;
1301
1302         /* Count how much space we need */
1303         list_for_each_entry(efiobj, &efi_obj_list, link) {
1304                 if (!efi_search(search_type, protocol, search_key, efiobj))
1305                         size += sizeof(void *);
1306         }
1307
1308         if (*buffer_size < size) {
1309                 *buffer_size = size;
1310                 return EFI_BUFFER_TOO_SMALL;
1311         }
1312
1313         *buffer_size = size;
1314         if (size == 0)
1315                 return EFI_NOT_FOUND;
1316
1317         /* Then fill the array */
1318         list_for_each_entry(efiobj, &efi_obj_list, link) {
1319                 if (!efi_search(search_type, protocol, search_key, efiobj))
1320                         *buffer++ = efiobj->handle;
1321         }
1322
1323         return EFI_SUCCESS;
1324 }
1325
1326 /*
1327  * Locate handles implementing a protocol.
1328  *
1329  * This function implements the LocateHandle service.
1330  * See the Unified Extensible Firmware Interface (UEFI) specification
1331  * for details.
1332  *
1333  * @search_type         selection criterion
1334  * @protocol            GUID of the protocol
1335  * @search_key          registration key
1336  * @buffer_size         size of the buffer to receive the handles in bytes
1337  * @buffer              buffer to receive the relevant handles
1338  * @return              0 if the handle implements the protocol
1339  */
1340 static efi_status_t EFIAPI efi_locate_handle_ext(
1341                         enum efi_locate_search_type search_type,
1342                         const efi_guid_t *protocol, void *search_key,
1343                         efi_uintn_t *buffer_size, efi_handle_t *buffer)
1344 {
1345         EFI_ENTRY("%d, %pUl, %p, %p, %p", search_type, protocol, search_key,
1346                   buffer_size, buffer);
1347
1348         return EFI_EXIT(efi_locate_handle(search_type, protocol, search_key,
1349                         buffer_size, buffer));
1350 }
1351
1352 /* Collapses configuration table entries, removing index i */
1353 static void efi_remove_configuration_table(int i)
1354 {
1355         struct efi_configuration_table *this = &efi_conf_table[i];
1356         struct efi_configuration_table *next = &efi_conf_table[i + 1];
1357         struct efi_configuration_table *end = &efi_conf_table[systab.nr_tables];
1358
1359         memmove(this, next, (ulong)end - (ulong)next);
1360         systab.nr_tables--;
1361 }
1362
1363 /*
1364  * Adds, updates, or removes a configuration table.
1365  *
1366  * This function is used for internal calls. For the API implementation of the
1367  * InstallConfigurationTable service see efi_install_configuration_table_ext.
1368  *
1369  * @guid                GUID of the installed table
1370  * @table               table to be installed
1371  * @return              status code
1372  */
1373 efi_status_t efi_install_configuration_table(const efi_guid_t *guid,
1374                                              void *table)
1375 {
1376         struct efi_event *evt;
1377         int i;
1378
1379         if (!guid)
1380                 return EFI_INVALID_PARAMETER;
1381
1382         /* Check for guid override */
1383         for (i = 0; i < systab.nr_tables; i++) {
1384                 if (!guidcmp(guid, &efi_conf_table[i].guid)) {
1385                         if (table)
1386                                 efi_conf_table[i].table = table;
1387                         else
1388                                 efi_remove_configuration_table(i);
1389                         goto out;
1390                 }
1391         }
1392
1393         if (!table)
1394                 return EFI_NOT_FOUND;
1395
1396         /* No override, check for overflow */
1397         if (i >= ARRAY_SIZE(efi_conf_table))
1398                 return EFI_OUT_OF_RESOURCES;
1399
1400         /* Add a new entry */
1401         memcpy(&efi_conf_table[i].guid, guid, sizeof(*guid));
1402         efi_conf_table[i].table = table;
1403         systab.nr_tables = i + 1;
1404
1405 out:
1406         /* Notify that the configuration table was changed */
1407         list_for_each_entry(evt, &efi_events, link) {
1408                 if (evt->group && !guidcmp(evt->group, guid)) {
1409                         efi_signal_event(evt, false);
1410                         break;
1411                 }
1412         }
1413
1414         return EFI_SUCCESS;
1415 }
1416
1417 /*
1418  * Adds, updates, or removes a configuration table.
1419  *
1420  * This function implements the InstallConfigurationTable service.
1421  * See the Unified Extensible Firmware Interface (UEFI) specification
1422  * for details.
1423  *
1424  * @guid                GUID of the installed table
1425  * @table               table to be installed
1426  * @return              status code
1427  */
1428 static efi_status_t EFIAPI efi_install_configuration_table_ext(efi_guid_t *guid,
1429                                                                void *table)
1430 {
1431         EFI_ENTRY("%pUl, %p", guid, table);
1432         return EFI_EXIT(efi_install_configuration_table(guid, table));
1433 }
1434
1435 /*
1436  * Initialize a loaded_image_info + loaded_image_info object with correct
1437  * protocols, boot-device, etc.
1438  *
1439  * @info                loaded image info to be passed to the entry point of the
1440  *                      image
1441  * @obj                 internal object associated with the loaded image
1442  * @device_path         device path of the loaded image
1443  * @file_path           file path of the loaded image
1444  * @return              status code
1445  */
1446 efi_status_t efi_setup_loaded_image(
1447                         struct efi_loaded_image *info, struct efi_object *obj,
1448                         struct efi_device_path *device_path,
1449                         struct efi_device_path *file_path)
1450 {
1451         efi_status_t ret;
1452
1453         /* Add internal object to object list */
1454         efi_add_handle(obj);
1455         /* efi_exit() assumes that the handle points to the info */
1456         obj->handle = info;
1457
1458         info->file_path = file_path;
1459
1460         if (device_path) {
1461                 info->device_handle = efi_dp_find_obj(device_path, NULL);
1462                 /*
1463                  * When asking for the device path interface, return
1464                  * bootefi_device_path
1465                  */
1466                 ret = efi_add_protocol(obj->handle, &efi_guid_device_path,
1467                                        device_path);
1468                 if (ret != EFI_SUCCESS)
1469                         goto failure;
1470         }
1471
1472         /*
1473          * When asking for the loaded_image interface, just
1474          * return handle which points to loaded_image_info
1475          */
1476         ret = efi_add_protocol(obj->handle, &efi_guid_loaded_image, info);
1477         if (ret != EFI_SUCCESS)
1478                 goto failure;
1479
1480         ret = efi_add_protocol(obj->handle,
1481                                &efi_guid_device_path_to_text_protocol,
1482                                (void *)&efi_device_path_to_text);
1483         if (ret != EFI_SUCCESS)
1484                 goto failure;
1485
1486         ret = efi_add_protocol(obj->handle,
1487                                &efi_guid_device_path_utilities_protocol,
1488                                (void *)&efi_device_path_utilities);
1489         if (ret != EFI_SUCCESS)
1490                 goto failure;
1491
1492         return ret;
1493 failure:
1494         printf("ERROR: Failure to install protocols for loaded image\n");
1495         return ret;
1496 }
1497
1498 /*
1499  * Load an image using a file path.
1500  *
1501  * @file_path           the path of the image to load
1502  * @buffer              buffer containing the loaded image
1503  * @return              status code
1504  */
1505 efi_status_t efi_load_image_from_path(struct efi_device_path *file_path,
1506                                       void **buffer)
1507 {
1508         struct efi_file_info *info = NULL;
1509         struct efi_file_handle *f;
1510         static efi_status_t ret;
1511         uint64_t bs;
1512
1513         f = efi_file_from_path(file_path);
1514         if (!f)
1515                 return EFI_DEVICE_ERROR;
1516
1517         bs = 0;
1518         EFI_CALL(ret = f->getinfo(f, (efi_guid_t *)&efi_file_info_guid,
1519                                   &bs, info));
1520         if (ret == EFI_BUFFER_TOO_SMALL) {
1521                 info = malloc(bs);
1522                 EFI_CALL(ret = f->getinfo(f, (efi_guid_t *)&efi_file_info_guid,
1523                                           &bs, info));
1524         }
1525         if (ret != EFI_SUCCESS)
1526                 goto error;
1527
1528         ret = efi_allocate_pool(EFI_LOADER_DATA, info->file_size, buffer);
1529         if (ret)
1530                 goto error;
1531
1532         EFI_CALL(ret = f->read(f, &info->file_size, *buffer));
1533
1534 error:
1535         free(info);
1536         EFI_CALL(f->close(f));
1537
1538         if (ret != EFI_SUCCESS) {
1539                 efi_free_pool(*buffer);
1540                 *buffer = NULL;
1541         }
1542
1543         return ret;
1544 }
1545
1546 /*
1547  * Load an EFI image into memory.
1548  *
1549  * This function implements the LoadImage service.
1550  * See the Unified Extensible Firmware Interface (UEFI) specification
1551  * for details.
1552  *
1553  * @boot_policy         true for request originating from the boot manager
1554  * @parent_image        the caller's image handle
1555  * @file_path           the path of the image to load
1556  * @source_buffer       memory location from which the image is installed
1557  * @source_size         size of the memory area from which the image is
1558  *                      installed
1559  * @image_handle        handle for the newly installed image
1560  * @return              status code
1561  */
1562 static efi_status_t EFIAPI efi_load_image(bool boot_policy,
1563                                           efi_handle_t parent_image,
1564                                           struct efi_device_path *file_path,
1565                                           void *source_buffer,
1566                                           unsigned long source_size,
1567                                           efi_handle_t *image_handle)
1568 {
1569         struct efi_loaded_image *info;
1570         struct efi_object *obj;
1571         efi_status_t ret;
1572
1573         EFI_ENTRY("%d, %p, %pD, %p, %ld, %p", boot_policy, parent_image,
1574                   file_path, source_buffer, source_size, image_handle);
1575
1576         if (!image_handle || !parent_image) {
1577                 ret = EFI_INVALID_PARAMETER;
1578                 goto error;
1579         }
1580
1581         if (!source_buffer && !file_path) {
1582                 ret = EFI_NOT_FOUND;
1583                 goto error;
1584         }
1585
1586         info = calloc(1, sizeof(*info));
1587         if (!info) {
1588                 ret = EFI_OUT_OF_RESOURCES;
1589                 goto error;
1590         }
1591         obj = calloc(1, sizeof(*obj));
1592         if (!obj) {
1593                 free(info);
1594                 ret = EFI_OUT_OF_RESOURCES;
1595                 goto error;
1596         }
1597
1598         if (!source_buffer) {
1599                 struct efi_device_path *dp, *fp;
1600
1601                 ret = efi_load_image_from_path(file_path, &source_buffer);
1602                 if (ret != EFI_SUCCESS)
1603                         goto failure;
1604                 /*
1605                  * split file_path which contains both the device and
1606                  * file parts:
1607                  */
1608                 efi_dp_split_file_path(file_path, &dp, &fp);
1609                 ret = efi_setup_loaded_image(info, obj, dp, fp);
1610                 if (ret != EFI_SUCCESS)
1611                         goto failure;
1612         } else {
1613                 /* In this case, file_path is the "device" path, ie.
1614                  * something like a HARDWARE_DEVICE:MEMORY_MAPPED
1615                  */
1616                 ret = efi_setup_loaded_image(info, obj, file_path, NULL);
1617                 if (ret != EFI_SUCCESS)
1618                         goto failure;
1619         }
1620         info->reserved = efi_load_pe(source_buffer, info);
1621         if (!info->reserved) {
1622                 ret = EFI_UNSUPPORTED;
1623                 goto failure;
1624         }
1625         info->system_table = &systab;
1626         info->parent_handle = parent_image;
1627         *image_handle = obj->handle;
1628         return EFI_EXIT(EFI_SUCCESS);
1629 failure:
1630         free(info);
1631         efi_delete_handle(obj);
1632 error:
1633         return EFI_EXIT(ret);
1634 }
1635
1636 /*
1637  * Call the entry point of an image.
1638  *
1639  * This function implements the StartImage service.
1640  * See the Unified Extensible Firmware Interface (UEFI) specification
1641  * for details.
1642  *
1643  * @image_handle        handle of the image
1644  * @exit_data_size      size of the buffer
1645  * @exit_data           buffer to receive the exit data of the called image
1646  * @return              status code
1647  */
1648 static efi_status_t EFIAPI efi_start_image(efi_handle_t image_handle,
1649                                            unsigned long *exit_data_size,
1650                                            s16 **exit_data)
1651 {
1652         EFIAPI efi_status_t (*entry)(efi_handle_t image_handle,
1653                                      struct efi_system_table *st);
1654         struct efi_loaded_image *info = image_handle;
1655         efi_status_t ret;
1656
1657         EFI_ENTRY("%p, %p, %p", image_handle, exit_data_size, exit_data);
1658         entry = info->reserved;
1659
1660         efi_is_direct_boot = false;
1661
1662         /* call the image! */
1663         if (setjmp(&info->exit_jmp)) {
1664                 /*
1665                  * We called the entry point of the child image with EFI_CALL
1666                  * in the lines below. The child image called the Exit() boot
1667                  * service efi_exit() which executed the long jump that brought
1668                  * us to the current line. This implies that the second half
1669                  * of the EFI_CALL macro has not been executed.
1670                  */
1671 #ifdef CONFIG_ARM
1672                 /*
1673                  * efi_exit() called efi_restore_gd(). We have to undo this
1674                  * otherwise __efi_entry_check() will put the wrong value into
1675                  * app_gd.
1676                  */
1677                 gd = app_gd;
1678 #endif
1679                 /*
1680                  * To get ready to call EFI_EXIT below we have to execute the
1681                  * missed out steps of EFI_CALL.
1682                  */
1683                 assert(__efi_entry_check());
1684                 debug("%sEFI: %lu returned by started image\n",
1685                       __efi_nesting_dec(),
1686                       (unsigned long)((uintptr_t)info->exit_status &
1687                                       ~EFI_ERROR_MASK));
1688                 return EFI_EXIT(info->exit_status);
1689         }
1690
1691         ret = EFI_CALL(entry(image_handle, &systab));
1692
1693         /*
1694          * Usually UEFI applications call Exit() instead of returning.
1695          * But because the world doesn not consist of ponies and unicorns,
1696          * we're happy to emulate that behavior on behalf of a payload
1697          * that forgot.
1698          */
1699         return EFI_CALL(systab.boottime->exit(image_handle, ret, 0, NULL));
1700 }
1701
1702 /*
1703  * Leave an EFI application or driver.
1704  *
1705  * This function implements the Exit service.
1706  * See the Unified Extensible Firmware Interface (UEFI) specification
1707  * for details.
1708  *
1709  * @image_handle        handle of the application or driver that is exiting
1710  * @exit_status         status code
1711  * @exit_data_size      size of the buffer in bytes
1712  * @exit_data           buffer with data describing an error
1713  * @return              status code
1714  */
1715 static efi_status_t EFIAPI efi_exit(efi_handle_t image_handle,
1716                                     efi_status_t exit_status,
1717                                     unsigned long exit_data_size,
1718                                     int16_t *exit_data)
1719 {
1720         /*
1721          * We require that the handle points to the original loaded
1722          * image protocol interface.
1723          *
1724          * For getting the longjmp address this is safer than locating
1725          * the protocol because the protocol may have been reinstalled
1726          * pointing to another memory location.
1727          *
1728          * TODO: We should call the unload procedure of the loaded
1729          *       image protocol.
1730          */
1731         struct efi_loaded_image *loaded_image_info = (void *)image_handle;
1732
1733         EFI_ENTRY("%p, %ld, %ld, %p", image_handle, exit_status,
1734                   exit_data_size, exit_data);
1735
1736         /* Make sure entry/exit counts for EFI world cross-overs match */
1737         EFI_EXIT(exit_status);
1738
1739         /*
1740          * But longjmp out with the U-Boot gd, not the application's, as
1741          * the other end is a setjmp call inside EFI context.
1742          */
1743         efi_restore_gd();
1744
1745         loaded_image_info->exit_status = exit_status;
1746         longjmp(&loaded_image_info->exit_jmp, 1);
1747
1748         panic("EFI application exited");
1749 }
1750
1751 /*
1752  * Unload an EFI image.
1753  *
1754  * This function implements the UnloadImage service.
1755  * See the Unified Extensible Firmware Interface (UEFI) specification
1756  * for details.
1757  *
1758  * @image_handle        handle of the image to be unloaded
1759  * @return              status code
1760  */
1761 static efi_status_t EFIAPI efi_unload_image(efi_handle_t image_handle)
1762 {
1763         struct efi_object *efiobj;
1764
1765         EFI_ENTRY("%p", image_handle);
1766         efiobj = efi_search_obj(image_handle);
1767         if (efiobj)
1768                 list_del(&efiobj->link);
1769
1770         return EFI_EXIT(EFI_SUCCESS);
1771 }
1772
1773 /*
1774  * Fix up caches for EFI payloads if necessary.
1775  */
1776 static void efi_exit_caches(void)
1777 {
1778 #if defined(CONFIG_ARM) && !defined(CONFIG_ARM64)
1779         /*
1780          * Grub on 32bit ARM needs to have caches disabled before jumping into
1781          * a zImage, but does not know of all cache layers. Give it a hand.
1782          */
1783         if (efi_is_direct_boot)
1784                 cleanup_before_linux();
1785 #endif
1786 }
1787
1788 /*
1789  * Stop all boot services.
1790  *
1791  * This function implements the ExitBootServices service.
1792  * See the Unified Extensible Firmware Interface (UEFI) specification
1793  * for details.
1794  *
1795  * All timer events are disabled.
1796  * For exit boot services events the notification function is called.
1797  * The boot services are disabled in the system table.
1798  *
1799  * @image_handle        handle of the loaded image
1800  * @map_key             key of the memory map
1801  * @return              status code
1802  */
1803 static efi_status_t EFIAPI efi_exit_boot_services(efi_handle_t image_handle,
1804                                                   unsigned long map_key)
1805 {
1806         struct efi_event *evt;
1807
1808         EFI_ENTRY("%p, %ld", image_handle, map_key);
1809
1810         /* Make sure that notification functions are not called anymore */
1811         efi_tpl = TPL_HIGH_LEVEL;
1812
1813         /* Check if ExitBootServices has already been called */
1814         if (!systab.boottime)
1815                 return EFI_EXIT(EFI_SUCCESS);
1816
1817         /* Add related events to the event group */
1818         list_for_each_entry(evt, &efi_events, link) {
1819                 if (evt->type == EVT_SIGNAL_EXIT_BOOT_SERVICES)
1820                         evt->group = &efi_guid_event_group_exit_boot_services;
1821         }
1822         /* Notify that ExitBootServices is invoked. */
1823         list_for_each_entry(evt, &efi_events, link) {
1824                 if (evt->group &&
1825                     !guidcmp(evt->group,
1826                              &efi_guid_event_group_exit_boot_services)) {
1827                         efi_signal_event(evt, false);
1828                         break;
1829                 }
1830         }
1831
1832         /* TODO Should persist EFI variables here */
1833
1834         board_quiesce_devices();
1835
1836         /* Fix up caches for EFI payloads if necessary */
1837         efi_exit_caches();
1838
1839         /* This stops all lingering devices */
1840         bootm_disable_interrupts();
1841
1842         /* Disable boottime services */
1843         systab.con_in_handle = NULL;
1844         systab.con_in = NULL;
1845         systab.con_out_handle = NULL;
1846         systab.con_out = NULL;
1847         systab.stderr_handle = NULL;
1848         systab.std_err = NULL;
1849         systab.boottime = NULL;
1850
1851         /* Recalculate CRC32 */
1852         systab.hdr.crc32 = 0;
1853         systab.hdr.crc32 = crc32(0, (const unsigned char *)&systab,
1854                                  sizeof(struct efi_system_table));
1855
1856         /* Give the payload some time to boot */
1857         efi_set_watchdog(0);
1858         WATCHDOG_RESET();
1859
1860         return EFI_EXIT(EFI_SUCCESS);
1861 }
1862
1863 /*
1864  * Get next value of the counter.
1865  *
1866  * This function implements the NextMonotonicCount service.
1867  * See the Unified Extensible Firmware Interface (UEFI) specification
1868  * for details.
1869  *
1870  * @count       returned value of the counter
1871  * @return      status code
1872  */
1873 static efi_status_t EFIAPI efi_get_next_monotonic_count(uint64_t *count)
1874 {
1875         static uint64_t mono;
1876
1877         EFI_ENTRY("%p", count);
1878         *count = mono++;
1879         return EFI_EXIT(EFI_SUCCESS);
1880 }
1881
1882 /*
1883  * Sleep.
1884  *
1885  * This function implements the Stall sercive.
1886  * See the Unified Extensible Firmware Interface (UEFI) specification
1887  * for details.
1888  *
1889  * @microseconds        period to sleep in microseconds
1890  * @return              status code
1891  */
1892 static efi_status_t EFIAPI efi_stall(unsigned long microseconds)
1893 {
1894         EFI_ENTRY("%ld", microseconds);
1895         udelay(microseconds);
1896         return EFI_EXIT(EFI_SUCCESS);
1897 }
1898
1899 /*
1900  * Reset the watchdog timer.
1901  *
1902  * This function implements the SetWatchdogTimer service.
1903  * See the Unified Extensible Firmware Interface (UEFI) specification
1904  * for details.
1905  *
1906  * @timeout             seconds before reset by watchdog
1907  * @watchdog_code       code to be logged when resetting
1908  * @data_size           size of buffer in bytes
1909  * @watchdog_data       buffer with data describing the reset reason
1910  * @return              status code
1911  */
1912 static efi_status_t EFIAPI efi_set_watchdog_timer(unsigned long timeout,
1913                                                   uint64_t watchdog_code,
1914                                                   unsigned long data_size,
1915                                                   uint16_t *watchdog_data)
1916 {
1917         EFI_ENTRY("%ld, 0x%" PRIx64 ", %ld, %p", timeout, watchdog_code,
1918                   data_size, watchdog_data);
1919         return EFI_EXIT(efi_set_watchdog(timeout));
1920 }
1921
1922 /*
1923  * Close a protocol.
1924  *
1925  * This function implements the CloseProtocol service.
1926  * See the Unified Extensible Firmware Interface (UEFI) specification
1927  * for details.
1928  *
1929  * @handle              handle on which the protocol shall be closed
1930  * @protocol            GUID of the protocol to close
1931  * @agent_handle        handle of the driver
1932  * @controller_handle   handle of the controller
1933  * @return              status code
1934  */
1935 static efi_status_t EFIAPI efi_close_protocol(efi_handle_t handle,
1936                                               const efi_guid_t *protocol,
1937                                               efi_handle_t agent_handle,
1938                                               efi_handle_t controller_handle)
1939 {
1940         struct efi_handler *handler;
1941         struct efi_open_protocol_info_item *item;
1942         struct efi_open_protocol_info_item *pos;
1943         efi_status_t r;
1944
1945         EFI_ENTRY("%p, %pUl, %p, %p", handle, protocol, agent_handle,
1946                   controller_handle);
1947
1948         if (!agent_handle) {
1949                 r = EFI_INVALID_PARAMETER;
1950                 goto out;
1951         }
1952         r = efi_search_protocol(handle, protocol, &handler);
1953         if (r != EFI_SUCCESS)
1954                 goto out;
1955
1956         r = EFI_NOT_FOUND;
1957         list_for_each_entry_safe(item, pos, &handler->open_infos, link) {
1958                 if (item->info.agent_handle == agent_handle &&
1959                     item->info.controller_handle == controller_handle) {
1960                         efi_delete_open_info(item);
1961                         r = EFI_SUCCESS;
1962                         break;
1963                 }
1964         }
1965 out:
1966         return EFI_EXIT(r);
1967 }
1968
1969 /*
1970  * Provide information about then open status of a protocol on a handle
1971  *
1972  * This function implements the OpenProtocolInformation service.
1973  * See the Unified Extensible Firmware Interface (UEFI) specification
1974  * for details.
1975  *
1976  * @handle              handle for which the information shall be retrieved
1977  * @protocol            GUID of the protocol
1978  * @entry_buffer        buffer to receive the open protocol information
1979  * @entry_count         number of entries available in the buffer
1980  * @return              status code
1981  */
1982 static efi_status_t EFIAPI efi_open_protocol_information(
1983                         efi_handle_t handle, const efi_guid_t *protocol,
1984                         struct efi_open_protocol_info_entry **entry_buffer,
1985                         efi_uintn_t *entry_count)
1986 {
1987         unsigned long buffer_size;
1988         unsigned long count;
1989         struct efi_handler *handler;
1990         struct efi_open_protocol_info_item *item;
1991         efi_status_t r;
1992
1993         EFI_ENTRY("%p, %pUl, %p, %p", handle, protocol, entry_buffer,
1994                   entry_count);
1995
1996         /* Check parameters */
1997         if (!entry_buffer) {
1998                 r = EFI_INVALID_PARAMETER;
1999                 goto out;
2000         }
2001         r = efi_search_protocol(handle, protocol, &handler);
2002         if (r != EFI_SUCCESS)
2003                 goto out;
2004
2005         /* Count entries */
2006         count = 0;
2007         list_for_each_entry(item, &handler->open_infos, link) {
2008                 if (item->info.open_count)
2009                         ++count;
2010         }
2011         *entry_count = count;
2012         *entry_buffer = NULL;
2013         if (!count) {
2014                 r = EFI_SUCCESS;
2015                 goto out;
2016         }
2017
2018         /* Copy entries */
2019         buffer_size = count * sizeof(struct efi_open_protocol_info_entry);
2020         r = efi_allocate_pool(EFI_ALLOCATE_ANY_PAGES, buffer_size,
2021                               (void **)entry_buffer);
2022         if (r != EFI_SUCCESS)
2023                 goto out;
2024         list_for_each_entry_reverse(item, &handler->open_infos, link) {
2025                 if (item->info.open_count)
2026                         (*entry_buffer)[--count] = item->info;
2027         }
2028 out:
2029         return EFI_EXIT(r);
2030 }
2031
2032 /*
2033  * Get protocols installed on a handle.
2034  *
2035  * This function implements the ProtocolsPerHandleService.
2036  * See the Unified Extensible Firmware Interface (UEFI) specification
2037  * for details.
2038  *
2039  * @handle                      handle for which the information is retrieved
2040  * @protocol_buffer             buffer with protocol GUIDs
2041  * @protocol_buffer_count       number of entries in the buffer
2042  * @return                      status code
2043  */
2044 static efi_status_t EFIAPI efi_protocols_per_handle(
2045                         efi_handle_t handle, efi_guid_t ***protocol_buffer,
2046                         efi_uintn_t *protocol_buffer_count)
2047 {
2048         unsigned long buffer_size;
2049         struct efi_object *efiobj;
2050         struct list_head *protocol_handle;
2051         efi_status_t r;
2052
2053         EFI_ENTRY("%p, %p, %p", handle, protocol_buffer,
2054                   protocol_buffer_count);
2055
2056         if (!handle || !protocol_buffer || !protocol_buffer_count)
2057                 return EFI_EXIT(EFI_INVALID_PARAMETER);
2058
2059         *protocol_buffer = NULL;
2060         *protocol_buffer_count = 0;
2061
2062         efiobj = efi_search_obj(handle);
2063         if (!efiobj)
2064                 return EFI_EXIT(EFI_INVALID_PARAMETER);
2065
2066         /* Count protocols */
2067         list_for_each(protocol_handle, &efiobj->protocols) {
2068                 ++*protocol_buffer_count;
2069         }
2070
2071         /* Copy guids */
2072         if (*protocol_buffer_count) {
2073                 size_t j = 0;
2074
2075                 buffer_size = sizeof(efi_guid_t *) * *protocol_buffer_count;
2076                 r = efi_allocate_pool(EFI_ALLOCATE_ANY_PAGES, buffer_size,
2077                                       (void **)protocol_buffer);
2078                 if (r != EFI_SUCCESS)
2079                         return EFI_EXIT(r);
2080                 list_for_each(protocol_handle, &efiobj->protocols) {
2081                         struct efi_handler *protocol;
2082
2083                         protocol = list_entry(protocol_handle,
2084                                               struct efi_handler, link);
2085                         (*protocol_buffer)[j] = (void *)protocol->guid;
2086                         ++j;
2087                 }
2088         }
2089
2090         return EFI_EXIT(EFI_SUCCESS);
2091 }
2092
2093 /*
2094  * Locate handles implementing a protocol.
2095  *
2096  * This function implements the LocateHandleBuffer service.
2097  * See the Unified Extensible Firmware Interface (UEFI) specification
2098  * for details.
2099  *
2100  * @search_type         selection criterion
2101  * @protocol            GUID of the protocol
2102  * @search_key          registration key
2103  * @no_handles          number of returned handles
2104  * @buffer              buffer with the returned handles
2105  * @return              status code
2106  */
2107 static efi_status_t EFIAPI efi_locate_handle_buffer(
2108                         enum efi_locate_search_type search_type,
2109                         const efi_guid_t *protocol, void *search_key,
2110                         efi_uintn_t *no_handles, efi_handle_t **buffer)
2111 {
2112         efi_status_t r;
2113         efi_uintn_t buffer_size = 0;
2114
2115         EFI_ENTRY("%d, %pUl, %p, %p, %p", search_type, protocol, search_key,
2116                   no_handles, buffer);
2117
2118         if (!no_handles || !buffer) {
2119                 r = EFI_INVALID_PARAMETER;
2120                 goto out;
2121         }
2122         *no_handles = 0;
2123         *buffer = NULL;
2124         r = efi_locate_handle(search_type, protocol, search_key, &buffer_size,
2125                               *buffer);
2126         if (r != EFI_BUFFER_TOO_SMALL)
2127                 goto out;
2128         r = efi_allocate_pool(EFI_ALLOCATE_ANY_PAGES, buffer_size,
2129                               (void **)buffer);
2130         if (r != EFI_SUCCESS)
2131                 goto out;
2132         r = efi_locate_handle(search_type, protocol, search_key, &buffer_size,
2133                               *buffer);
2134         if (r == EFI_SUCCESS)
2135                 *no_handles = buffer_size / sizeof(efi_handle_t);
2136 out:
2137         return EFI_EXIT(r);
2138 }
2139
2140 /*
2141  * Find an interface implementing a protocol.
2142  *
2143  * This function implements the LocateProtocol service.
2144  * See the Unified Extensible Firmware Interface (UEFI) specification
2145  * for details.
2146  *
2147  * @protocol            GUID of the protocol
2148  * @registration        registration key passed to the notification function
2149  * @protocol_interface  interface implementing the protocol
2150  * @return              status code
2151  */
2152 static efi_status_t EFIAPI efi_locate_protocol(const efi_guid_t *protocol,
2153                                                void *registration,
2154                                                void **protocol_interface)
2155 {
2156         struct list_head *lhandle;
2157         efi_status_t ret;
2158
2159         EFI_ENTRY("%pUl, %p, %p", protocol, registration, protocol_interface);
2160
2161         if (!protocol || !protocol_interface)
2162                 return EFI_EXIT(EFI_INVALID_PARAMETER);
2163
2164         list_for_each(lhandle, &efi_obj_list) {
2165                 struct efi_object *efiobj;
2166                 struct efi_handler *handler;
2167
2168                 efiobj = list_entry(lhandle, struct efi_object, link);
2169
2170                 ret = efi_search_protocol(efiobj->handle, protocol, &handler);
2171                 if (ret == EFI_SUCCESS) {
2172                         *protocol_interface = handler->protocol_interface;
2173                         return EFI_EXIT(EFI_SUCCESS);
2174                 }
2175         }
2176         *protocol_interface = NULL;
2177
2178         return EFI_EXIT(EFI_NOT_FOUND);
2179 }
2180
2181 /*
2182  * Get the device path and handle of an device implementing a protocol.
2183  *
2184  * This function implements the LocateDevicePath service.
2185  * See the Unified Extensible Firmware Interface (UEFI) specification
2186  * for details.
2187  *
2188  * @protocol            GUID of the protocol
2189  * @device_path         device path
2190  * @device              handle of the device
2191  * @return              status code
2192  */
2193 static efi_status_t EFIAPI efi_locate_device_path(
2194                         const efi_guid_t *protocol,
2195                         struct efi_device_path **device_path,
2196                         efi_handle_t *device)
2197 {
2198         struct efi_device_path *dp;
2199         size_t i;
2200         struct efi_handler *handler;
2201         efi_handle_t *handles;
2202         size_t len, len_dp;
2203         size_t len_best = 0;
2204         efi_uintn_t no_handles;
2205         u8 *remainder;
2206         efi_status_t ret;
2207
2208         EFI_ENTRY("%pUl, %p, %p", protocol, device_path, device);
2209
2210         if (!protocol || !device_path || !*device_path || !device) {
2211                 ret = EFI_INVALID_PARAMETER;
2212                 goto out;
2213         }
2214
2215         /* Find end of device path */
2216         len = efi_dp_size(*device_path);
2217
2218         /* Get all handles implementing the protocol */
2219         ret = EFI_CALL(efi_locate_handle_buffer(BY_PROTOCOL, protocol, NULL,
2220                                                 &no_handles, &handles));
2221         if (ret != EFI_SUCCESS)
2222                 goto out;
2223
2224         for (i = 0; i < no_handles; ++i) {
2225                 /* Find the device path protocol */
2226                 ret = efi_search_protocol(handles[i], &efi_guid_device_path,
2227                                           &handler);
2228                 if (ret != EFI_SUCCESS)
2229                         continue;
2230                 dp = (struct efi_device_path *)handler->protocol_interface;
2231                 len_dp = efi_dp_size(dp);
2232                 /*
2233                  * This handle can only be a better fit
2234                  * if its device path length is longer than the best fit and
2235                  * if its device path length is shorter of equal the searched
2236                  * device path.
2237                  */
2238                 if (len_dp <= len_best || len_dp > len)
2239                         continue;
2240                 /* Check if dp is a subpath of device_path */
2241                 if (memcmp(*device_path, dp, len_dp))
2242                         continue;
2243                 *device = handles[i];
2244                 len_best = len_dp;
2245         }
2246         if (len_best) {
2247                 remainder = (u8 *)*device_path + len_best;
2248                 *device_path = (struct efi_device_path *)remainder;
2249                 ret = EFI_SUCCESS;
2250         } else {
2251                 ret = EFI_NOT_FOUND;
2252         }
2253 out:
2254         return EFI_EXIT(ret);
2255 }
2256
2257 /*
2258  * Install multiple protocol interfaces.
2259  *
2260  * This function implements the MultipleProtocolInterfaces service.
2261  * See the Unified Extensible Firmware Interface (UEFI) specification
2262  * for details.
2263  *
2264  * @handle      handle on which the protocol interfaces shall be installed
2265  * @...         NULL terminated argument list with pairs of protocol GUIDS and
2266  *              interfaces
2267  * @return      status code
2268  */
2269 static efi_status_t EFIAPI efi_install_multiple_protocol_interfaces(
2270                         void **handle, ...)
2271 {
2272         EFI_ENTRY("%p", handle);
2273
2274         va_list argptr;
2275         const efi_guid_t *protocol;
2276         void *protocol_interface;
2277         efi_status_t r = EFI_SUCCESS;
2278         int i = 0;
2279
2280         if (!handle)
2281                 return EFI_EXIT(EFI_INVALID_PARAMETER);
2282
2283         va_start(argptr, handle);
2284         for (;;) {
2285                 protocol = va_arg(argptr, efi_guid_t*);
2286                 if (!protocol)
2287                         break;
2288                 protocol_interface = va_arg(argptr, void*);
2289                 r = EFI_CALL(efi_install_protocol_interface(
2290                                                 handle, protocol,
2291                                                 EFI_NATIVE_INTERFACE,
2292                                                 protocol_interface));
2293                 if (r != EFI_SUCCESS)
2294                         break;
2295                 i++;
2296         }
2297         va_end(argptr);
2298         if (r == EFI_SUCCESS)
2299                 return EFI_EXIT(r);
2300
2301         /* If an error occurred undo all changes. */
2302         va_start(argptr, handle);
2303         for (; i; --i) {
2304                 protocol = va_arg(argptr, efi_guid_t*);
2305                 protocol_interface = va_arg(argptr, void*);
2306                 EFI_CALL(efi_uninstall_protocol_interface(handle, protocol,
2307                                                           protocol_interface));
2308         }
2309         va_end(argptr);
2310
2311         return EFI_EXIT(r);
2312 }
2313
2314 /*
2315  * Uninstall multiple protocol interfaces.
2316  *
2317  * This function implements the UninstallMultipleProtocolInterfaces service.
2318  * See the Unified Extensible Firmware Interface (UEFI) specification
2319  * for details.
2320  *
2321  * @handle      handle from which the protocol interfaces shall be removed
2322  * @...         NULL terminated argument list with pairs of protocol GUIDS and
2323  *              interfaces
2324  * @return      status code
2325  */
2326 static efi_status_t EFIAPI efi_uninstall_multiple_protocol_interfaces(
2327                         void *handle, ...)
2328 {
2329         EFI_ENTRY("%p", handle);
2330
2331         va_list argptr;
2332         const efi_guid_t *protocol;
2333         void *protocol_interface;
2334         efi_status_t r = EFI_SUCCESS;
2335         size_t i = 0;
2336
2337         if (!handle)
2338                 return EFI_EXIT(EFI_INVALID_PARAMETER);
2339
2340         va_start(argptr, handle);
2341         for (;;) {
2342                 protocol = va_arg(argptr, efi_guid_t*);
2343                 if (!protocol)
2344                         break;
2345                 protocol_interface = va_arg(argptr, void*);
2346                 r = EFI_CALL(efi_uninstall_protocol_interface(
2347                                                 handle, protocol,
2348                                                 protocol_interface));
2349                 if (r != EFI_SUCCESS)
2350                         break;
2351                 i++;
2352         }
2353         va_end(argptr);
2354         if (r == EFI_SUCCESS)
2355                 return EFI_EXIT(r);
2356
2357         /* If an error occurred undo all changes. */
2358         va_start(argptr, handle);
2359         for (; i; --i) {
2360                 protocol = va_arg(argptr, efi_guid_t*);
2361                 protocol_interface = va_arg(argptr, void*);
2362                 EFI_CALL(efi_install_protocol_interface(&handle, protocol,
2363                                                         EFI_NATIVE_INTERFACE,
2364                                                         protocol_interface));
2365         }
2366         va_end(argptr);
2367
2368         return EFI_EXIT(r);
2369 }
2370
2371 /*
2372  * Calculate cyclic redundancy code.
2373  *
2374  * This function implements the CalculateCrc32 service.
2375  * See the Unified Extensible Firmware Interface (UEFI) specification
2376  * for details.
2377  *
2378  * @data        buffer with data
2379  * @data_size   size of buffer in bytes
2380  * @crc32_p     cyclic redundancy code
2381  * @return      status code
2382  */
2383 static efi_status_t EFIAPI efi_calculate_crc32(void *data,
2384                                                unsigned long data_size,
2385                                                uint32_t *crc32_p)
2386 {
2387         EFI_ENTRY("%p, %ld", data, data_size);
2388         *crc32_p = crc32(0, data, data_size);
2389         return EFI_EXIT(EFI_SUCCESS);
2390 }
2391
2392 /*
2393  * Copy memory.
2394  *
2395  * This function implements the CopyMem service.
2396  * See the Unified Extensible Firmware Interface (UEFI) specification
2397  * for details.
2398  *
2399  * @destination         destination of the copy operation
2400  * @source              source of the copy operation
2401  * @length              number of bytes to copy
2402  */
2403 static void EFIAPI efi_copy_mem(void *destination, const void *source,
2404                                 size_t length)
2405 {
2406         EFI_ENTRY("%p, %p, %ld", destination, source, (unsigned long)length);
2407         memcpy(destination, source, length);
2408         EFI_EXIT(EFI_SUCCESS);
2409 }
2410
2411 /*
2412  * Fill memory with a byte value.
2413  *
2414  * This function implements the SetMem service.
2415  * See the Unified Extensible Firmware Interface (UEFI) specification
2416  * for details.
2417  *
2418  * @buffer              buffer to fill
2419  * @size                size of buffer in bytes
2420  * @value               byte to copy to the buffer
2421  */
2422 static void EFIAPI efi_set_mem(void *buffer, size_t size, uint8_t value)
2423 {
2424         EFI_ENTRY("%p, %ld, 0x%x", buffer, (unsigned long)size, value);
2425         memset(buffer, value, size);
2426         EFI_EXIT(EFI_SUCCESS);
2427 }
2428
2429 /*
2430  * Open protocol interface on a handle.
2431  *
2432  * @handler             handler of a protocol
2433  * @protocol_interface  interface implementing the protocol
2434  * @agent_handle        handle of the driver
2435  * @controller_handle   handle of the controller
2436  * @attributes          attributes indicating how to open the protocol
2437  * @return              status code
2438  */
2439 static efi_status_t efi_protocol_open(
2440                         struct efi_handler *handler,
2441                         void **protocol_interface, void *agent_handle,
2442                         void *controller_handle, uint32_t attributes)
2443 {
2444         struct efi_open_protocol_info_item *item;
2445         struct efi_open_protocol_info_entry *match = NULL;
2446         bool opened_by_driver = false;
2447         bool opened_exclusive = false;
2448
2449         /* If there is no agent, only return the interface */
2450         if (!agent_handle)
2451                 goto out;
2452
2453         /* For TEST_PROTOCOL ignore interface attribute */
2454         if (attributes != EFI_OPEN_PROTOCOL_TEST_PROTOCOL)
2455                 *protocol_interface = NULL;
2456
2457         /*
2458          * Check if the protocol is already opened by a driver with the same
2459          * attributes or opened exclusively
2460          */
2461         list_for_each_entry(item, &handler->open_infos, link) {
2462                 if (item->info.agent_handle == agent_handle) {
2463                         if ((attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) &&
2464                             (item->info.attributes == attributes))
2465                                 return EFI_ALREADY_STARTED;
2466                 }
2467                 if (item->info.attributes & EFI_OPEN_PROTOCOL_EXCLUSIVE)
2468                         opened_exclusive = true;
2469         }
2470
2471         /* Only one controller can open the protocol exclusively */
2472         if (opened_exclusive && attributes &
2473             (EFI_OPEN_PROTOCOL_EXCLUSIVE | EFI_OPEN_PROTOCOL_BY_DRIVER))
2474                 return EFI_ACCESS_DENIED;
2475
2476         /* Prepare exclusive opening */
2477         if (attributes & EFI_OPEN_PROTOCOL_EXCLUSIVE) {
2478                 /* Try to disconnect controllers */
2479                 list_for_each_entry(item, &handler->open_infos, link) {
2480                         if (item->info.attributes ==
2481                                         EFI_OPEN_PROTOCOL_BY_DRIVER)
2482                                 EFI_CALL(efi_disconnect_controller(
2483                                                 item->info.controller_handle,
2484                                                 item->info.agent_handle,
2485                                                 NULL));
2486                 }
2487                 opened_by_driver = false;
2488                 /* Check if all controllers are disconnected */
2489                 list_for_each_entry(item, &handler->open_infos, link) {
2490                         if (item->info.attributes & EFI_OPEN_PROTOCOL_BY_DRIVER)
2491                                 opened_by_driver = true;
2492                 }
2493                 /* Only one controller can be conncected */
2494                 if (opened_by_driver)
2495                         return EFI_ACCESS_DENIED;
2496         }
2497
2498         /* Find existing entry */
2499         list_for_each_entry(item, &handler->open_infos, link) {
2500                 if (item->info.agent_handle == agent_handle &&
2501                     item->info.controller_handle == controller_handle)
2502                         match = &item->info;
2503         }
2504         /* None found, create one */
2505         if (!match) {
2506                 match = efi_create_open_info(handler);
2507                 if (!match)
2508                         return EFI_OUT_OF_RESOURCES;
2509         }
2510
2511         match->agent_handle = agent_handle;
2512         match->controller_handle = controller_handle;
2513         match->attributes = attributes;
2514         match->open_count++;
2515
2516 out:
2517         /* For TEST_PROTOCOL ignore interface attribute. */
2518         if (attributes != EFI_OPEN_PROTOCOL_TEST_PROTOCOL)
2519                 *protocol_interface = handler->protocol_interface;
2520
2521         return EFI_SUCCESS;
2522 }
2523
2524 /*
2525  * Open protocol interface on a handle.
2526  *
2527  * This function implements the OpenProtocol interface.
2528  * See the Unified Extensible Firmware Interface (UEFI) specification
2529  * for details.
2530  *
2531  * @handle              handle on which the protocol shall be opened
2532  * @protocol            GUID of the protocol
2533  * @protocol_interface  interface implementing the protocol
2534  * @agent_handle        handle of the driver
2535  * @controller_handle   handle of the controller
2536  * @attributes          attributes indicating how to open the protocol
2537  * @return              status code
2538  */
2539 static efi_status_t EFIAPI efi_open_protocol(
2540                         void *handle, const efi_guid_t *protocol,
2541                         void **protocol_interface, void *agent_handle,
2542                         void *controller_handle, uint32_t attributes)
2543 {
2544         struct efi_handler *handler;
2545         efi_status_t r = EFI_INVALID_PARAMETER;
2546
2547         EFI_ENTRY("%p, %pUl, %p, %p, %p, 0x%x", handle, protocol,
2548                   protocol_interface, agent_handle, controller_handle,
2549                   attributes);
2550
2551         if (!handle || !protocol ||
2552             (!protocol_interface && attributes !=
2553              EFI_OPEN_PROTOCOL_TEST_PROTOCOL)) {
2554                 goto out;
2555         }
2556
2557         switch (attributes) {
2558         case EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL:
2559         case EFI_OPEN_PROTOCOL_GET_PROTOCOL:
2560         case EFI_OPEN_PROTOCOL_TEST_PROTOCOL:
2561                 break;
2562         case EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER:
2563                 if (controller_handle == handle)
2564                         goto out;
2565                 /* fall-through */
2566         case EFI_OPEN_PROTOCOL_BY_DRIVER:
2567         case EFI_OPEN_PROTOCOL_BY_DRIVER | EFI_OPEN_PROTOCOL_EXCLUSIVE:
2568                 /* Check that the controller handle is valid */
2569                 if (!efi_search_obj(controller_handle))
2570                         goto out;
2571                 /* fall-through */
2572         case EFI_OPEN_PROTOCOL_EXCLUSIVE:
2573                 /* Check that the agent handle is valid */
2574                 if (!efi_search_obj(agent_handle))
2575                         goto out;
2576                 break;
2577         default:
2578                 goto out;
2579         }
2580
2581         r = efi_search_protocol(handle, protocol, &handler);
2582         if (r != EFI_SUCCESS)
2583                 goto out;
2584
2585         r = efi_protocol_open(handler, protocol_interface, agent_handle,
2586                               controller_handle, attributes);
2587 out:
2588         return EFI_EXIT(r);
2589 }
2590
2591 /*
2592  * Get interface of a protocol on a handle.
2593  *
2594  * This function implements the HandleProtocol service.
2595  * See the Unified Extensible Firmware Interface (UEFI) specification
2596  * for details.
2597  *
2598  * @handle              handle on which the protocol shall be opened
2599  * @protocol            GUID of the protocol
2600  * @protocol_interface  interface implementing the protocol
2601  * @return              status code
2602  */
2603 static efi_status_t EFIAPI efi_handle_protocol(efi_handle_t handle,
2604                                                const efi_guid_t *protocol,
2605                                                void **protocol_interface)
2606 {
2607         return efi_open_protocol(handle, protocol, protocol_interface, NULL,
2608                                  NULL, EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL);
2609 }
2610
2611 static efi_status_t efi_bind_controller(
2612                         efi_handle_t controller_handle,
2613                         efi_handle_t driver_image_handle,
2614                         struct efi_device_path *remain_device_path)
2615 {
2616         struct efi_driver_binding_protocol *binding_protocol;
2617         efi_status_t r;
2618
2619         r = EFI_CALL(efi_open_protocol(driver_image_handle,
2620                                        &efi_guid_driver_binding_protocol,
2621                                        (void **)&binding_protocol,
2622                                        driver_image_handle, NULL,
2623                                        EFI_OPEN_PROTOCOL_GET_PROTOCOL));
2624         if (r != EFI_SUCCESS)
2625                 return r;
2626         r = EFI_CALL(binding_protocol->supported(binding_protocol,
2627                                                  controller_handle,
2628                                                  remain_device_path));
2629         if (r == EFI_SUCCESS)
2630                 r = EFI_CALL(binding_protocol->start(binding_protocol,
2631                                                      controller_handle,
2632                                                      remain_device_path));
2633         EFI_CALL(efi_close_protocol(driver_image_handle,
2634                                     &efi_guid_driver_binding_protocol,
2635                                     driver_image_handle, NULL));
2636         return r;
2637 }
2638
2639 static efi_status_t efi_connect_single_controller(
2640                         efi_handle_t controller_handle,
2641                         efi_handle_t *driver_image_handle,
2642                         struct efi_device_path *remain_device_path)
2643 {
2644         efi_handle_t *buffer;
2645         size_t count;
2646         size_t i;
2647         efi_status_t r;
2648         size_t connected = 0;
2649
2650         /* Get buffer with all handles with driver binding protocol */
2651         r = EFI_CALL(efi_locate_handle_buffer(BY_PROTOCOL,
2652                                               &efi_guid_driver_binding_protocol,
2653                                               NULL, &count, &buffer));
2654         if (r != EFI_SUCCESS)
2655                 return r;
2656
2657         /*  Context Override */
2658         if (driver_image_handle) {
2659                 for (; *driver_image_handle; ++driver_image_handle) {
2660                         for (i = 0; i < count; ++i) {
2661                                 if (buffer[i] == *driver_image_handle) {
2662                                         buffer[i] = NULL;
2663                                         r = efi_bind_controller(
2664                                                         controller_handle,
2665                                                         *driver_image_handle,
2666                                                         remain_device_path);
2667                                         /*
2668                                          * For drivers that do not support the
2669                                          * controller or are already connected
2670                                          * we receive an error code here.
2671                                          */
2672                                         if (r == EFI_SUCCESS)
2673                                                 ++connected;
2674                                 }
2675                         }
2676                 }
2677         }
2678
2679         /*
2680          * TODO: Some overrides are not yet implemented:
2681          * - Platform Driver Override
2682          * - Driver Family Override Search
2683          * - Bus Specific Driver Override
2684          */
2685
2686         /* Driver Binding Search */
2687         for (i = 0; i < count; ++i) {
2688                 if (buffer[i]) {
2689                         r = efi_bind_controller(controller_handle,
2690                                                 buffer[i],
2691                                                 remain_device_path);
2692                         if (r == EFI_SUCCESS)
2693                                 ++connected;
2694                 }
2695         }
2696
2697         efi_free_pool(buffer);
2698         if (!connected)
2699                 return EFI_NOT_FOUND;
2700         return EFI_SUCCESS;
2701 }
2702
2703 /*
2704  * Connect a controller to a driver.
2705  *
2706  * This function implements the ConnectController service.
2707  * See the Unified Extensible Firmware Interface (UEFI) specification
2708  * for details.
2709  *
2710  * First all driver binding protocol handles are tried for binding drivers.
2711  * Afterwards all handles that have openened a protocol of the controller
2712  * with EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER are connected to drivers.
2713  *
2714  * @controller_handle   handle of the controller
2715  * @driver_image_handle handle of the driver
2716  * @remain_device_path  device path of a child controller
2717  * @recursive           true to connect all child controllers
2718  * @return              status code
2719  */
2720 static efi_status_t EFIAPI efi_connect_controller(
2721                         efi_handle_t controller_handle,
2722                         efi_handle_t *driver_image_handle,
2723                         struct efi_device_path *remain_device_path,
2724                         bool recursive)
2725 {
2726         efi_status_t r;
2727         efi_status_t ret = EFI_NOT_FOUND;
2728         struct efi_object *efiobj;
2729
2730         EFI_ENTRY("%p, %p, %p, %d", controller_handle, driver_image_handle,
2731                   remain_device_path, recursive);
2732
2733         efiobj = efi_search_obj(controller_handle);
2734         if (!efiobj) {
2735                 ret = EFI_INVALID_PARAMETER;
2736                 goto out;
2737         }
2738
2739         r = efi_connect_single_controller(controller_handle,
2740                                           driver_image_handle,
2741                                           remain_device_path);
2742         if (r == EFI_SUCCESS)
2743                 ret = EFI_SUCCESS;
2744         if (recursive) {
2745                 struct efi_handler *handler;
2746                 struct efi_open_protocol_info_item *item;
2747
2748                 list_for_each_entry(handler, &efiobj->protocols, link) {
2749                         list_for_each_entry(item, &handler->open_infos, link) {
2750                                 if (item->info.attributes &
2751                                     EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER) {
2752                                         r = EFI_CALL(efi_connect_controller(
2753                                                 item->info.controller_handle,
2754                                                 driver_image_handle,
2755                                                 remain_device_path,
2756                                                 recursive));
2757                                         if (r == EFI_SUCCESS)
2758                                                 ret = EFI_SUCCESS;
2759                                 }
2760                         }
2761                 }
2762         }
2763         /*  Check for child controller specified by end node */
2764         if (ret != EFI_SUCCESS && remain_device_path &&
2765             remain_device_path->type == DEVICE_PATH_TYPE_END)
2766                 ret = EFI_SUCCESS;
2767 out:
2768         return EFI_EXIT(ret);
2769 }
2770
2771 /*
2772  * Get all child controllers associated to a driver.
2773  * The allocated buffer has to be freed with free().
2774  *
2775  * @efiobj                      handle of the controller
2776  * @driver_handle               handle of the driver
2777  * @number_of_children          number of child controllers
2778  * @child_handle_buffer         handles of the the child controllers
2779  */
2780 static efi_status_t efi_get_child_controllers(
2781                                 struct efi_object *efiobj,
2782                                 efi_handle_t driver_handle,
2783                                 efi_uintn_t *number_of_children,
2784                                 efi_handle_t **child_handle_buffer)
2785 {
2786         struct efi_handler *handler;
2787         struct efi_open_protocol_info_item *item;
2788         efi_uintn_t count = 0, i;
2789         bool duplicate;
2790
2791         /* Count all child controller associations */
2792         list_for_each_entry(handler, &efiobj->protocols, link) {
2793                 list_for_each_entry(item, &handler->open_infos, link) {
2794                         if (item->info.agent_handle == driver_handle &&
2795                             item->info.attributes &
2796                             EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER)
2797                                 ++count;
2798                 }
2799         }
2800         /*
2801          * Create buffer. In case of duplicate child controller assignments
2802          * the buffer will be too large. But that does not harm.
2803          */
2804         *number_of_children = 0;
2805         *child_handle_buffer = calloc(count, sizeof(efi_handle_t));
2806         if (!*child_handle_buffer)
2807                 return EFI_OUT_OF_RESOURCES;
2808         /* Copy unique child handles */
2809         list_for_each_entry(handler, &efiobj->protocols, link) {
2810                 list_for_each_entry(item, &handler->open_infos, link) {
2811                         if (item->info.agent_handle == driver_handle &&
2812                             item->info.attributes &
2813                             EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER) {
2814                                 /* Check this is a new child controller */
2815                                 duplicate = false;
2816                                 for (i = 0; i < *number_of_children; ++i) {
2817                                         if ((*child_handle_buffer)[i] ==
2818                                             item->info.controller_handle)
2819                                                 duplicate = true;
2820                                 }
2821                                 /* Copy handle to buffer */
2822                                 if (!duplicate) {
2823                                         i = (*number_of_children)++;
2824                                         (*child_handle_buffer)[i] =
2825                                                 item->info.controller_handle;
2826                                 }
2827                         }
2828                 }
2829         }
2830         return EFI_SUCCESS;
2831 }
2832
2833 /*
2834  * Disconnect a controller from a driver.
2835  *
2836  * This function implements the DisconnectController service.
2837  * See the Unified Extensible Firmware Interface (UEFI) specification
2838  * for details.
2839  *
2840  * @controller_handle   handle of the controller
2841  * @driver_image_handle handle of the driver
2842  * @child_handle        handle of the child to destroy
2843  * @return              status code
2844  */
2845 static efi_status_t EFIAPI efi_disconnect_controller(
2846                                 efi_handle_t controller_handle,
2847                                 efi_handle_t driver_image_handle,
2848                                 efi_handle_t child_handle)
2849 {
2850         struct efi_driver_binding_protocol *binding_protocol;
2851         efi_handle_t *child_handle_buffer = NULL;
2852         size_t number_of_children = 0;
2853         efi_status_t r;
2854         size_t stop_count = 0;
2855         struct efi_object *efiobj;
2856
2857         EFI_ENTRY("%p, %p, %p", controller_handle, driver_image_handle,
2858                   child_handle);
2859
2860         efiobj = efi_search_obj(controller_handle);
2861         if (!efiobj) {
2862                 r = EFI_INVALID_PARAMETER;
2863                 goto out;
2864         }
2865
2866         if (child_handle && !efi_search_obj(child_handle)) {
2867                 r = EFI_INVALID_PARAMETER;
2868                 goto out;
2869         }
2870
2871         /* If no driver handle is supplied, disconnect all drivers */
2872         if (!driver_image_handle) {
2873                 r = efi_disconnect_all_drivers(efiobj, NULL, child_handle);
2874                 goto out;
2875         }
2876
2877         /* Create list of child handles */
2878         if (child_handle) {
2879                 number_of_children = 1;
2880                 child_handle_buffer = &child_handle;
2881         } else {
2882                 efi_get_child_controllers(efiobj,
2883                                           driver_image_handle,
2884                                           &number_of_children,
2885                                           &child_handle_buffer);
2886         }
2887
2888         /* Get the driver binding protocol */
2889         r = EFI_CALL(efi_open_protocol(driver_image_handle,
2890                                        &efi_guid_driver_binding_protocol,
2891                                        (void **)&binding_protocol,
2892                                        driver_image_handle, NULL,
2893                                        EFI_OPEN_PROTOCOL_GET_PROTOCOL));
2894         if (r != EFI_SUCCESS)
2895                 goto out;
2896         /* Remove the children */
2897         if (number_of_children) {
2898                 r = EFI_CALL(binding_protocol->stop(binding_protocol,
2899                                                     controller_handle,
2900                                                     number_of_children,
2901                                                     child_handle_buffer));
2902                 if (r == EFI_SUCCESS)
2903                         ++stop_count;
2904         }
2905         /* Remove the driver */
2906         if (!child_handle)
2907                 r = EFI_CALL(binding_protocol->stop(binding_protocol,
2908                                                     controller_handle,
2909                                                     0, NULL));
2910         if (r == EFI_SUCCESS)
2911                 ++stop_count;
2912         EFI_CALL(efi_close_protocol(driver_image_handle,
2913                                     &efi_guid_driver_binding_protocol,
2914                                     driver_image_handle, NULL));
2915
2916         if (stop_count)
2917                 r = EFI_SUCCESS;
2918         else
2919                 r = EFI_NOT_FOUND;
2920 out:
2921         if (!child_handle)
2922                 free(child_handle_buffer);
2923         return EFI_EXIT(r);
2924 }
2925
2926 static const struct efi_boot_services efi_boot_services = {
2927         .hdr = {
2928                 .headersize = sizeof(struct efi_table_hdr),
2929         },
2930         .raise_tpl = efi_raise_tpl,
2931         .restore_tpl = efi_restore_tpl,
2932         .allocate_pages = efi_allocate_pages_ext,
2933         .free_pages = efi_free_pages_ext,
2934         .get_memory_map = efi_get_memory_map_ext,
2935         .allocate_pool = efi_allocate_pool_ext,
2936         .free_pool = efi_free_pool_ext,
2937         .create_event = efi_create_event_ext,
2938         .set_timer = efi_set_timer_ext,
2939         .wait_for_event = efi_wait_for_event,
2940         .signal_event = efi_signal_event_ext,
2941         .close_event = efi_close_event,
2942         .check_event = efi_check_event,
2943         .install_protocol_interface = efi_install_protocol_interface,
2944         .reinstall_protocol_interface = efi_reinstall_protocol_interface,
2945         .uninstall_protocol_interface = efi_uninstall_protocol_interface,
2946         .handle_protocol = efi_handle_protocol,
2947         .reserved = NULL,
2948         .register_protocol_notify = efi_register_protocol_notify,
2949         .locate_handle = efi_locate_handle_ext,
2950         .locate_device_path = efi_locate_device_path,
2951         .install_configuration_table = efi_install_configuration_table_ext,
2952         .load_image = efi_load_image,
2953         .start_image = efi_start_image,
2954         .exit = efi_exit,
2955         .unload_image = efi_unload_image,
2956         .exit_boot_services = efi_exit_boot_services,
2957         .get_next_monotonic_count = efi_get_next_monotonic_count,
2958         .stall = efi_stall,
2959         .set_watchdog_timer = efi_set_watchdog_timer,
2960         .connect_controller = efi_connect_controller,
2961         .disconnect_controller = efi_disconnect_controller,
2962         .open_protocol = efi_open_protocol,
2963         .close_protocol = efi_close_protocol,
2964         .open_protocol_information = efi_open_protocol_information,
2965         .protocols_per_handle = efi_protocols_per_handle,
2966         .locate_handle_buffer = efi_locate_handle_buffer,
2967         .locate_protocol = efi_locate_protocol,
2968         .install_multiple_protocol_interfaces =
2969                         efi_install_multiple_protocol_interfaces,
2970         .uninstall_multiple_protocol_interfaces =
2971                         efi_uninstall_multiple_protocol_interfaces,
2972         .calculate_crc32 = efi_calculate_crc32,
2973         .copy_mem = efi_copy_mem,
2974         .set_mem = efi_set_mem,
2975         .create_event_ex = efi_create_event_ex,
2976 };
2977
2978 static uint16_t __efi_runtime_data firmware_vendor[] = L"Das U-Boot";
2979
2980 struct efi_system_table __efi_runtime_data systab = {
2981         .hdr = {
2982                 .signature = EFI_SYSTEM_TABLE_SIGNATURE,
2983                 .revision = 2 << 16 | 70, /* 2.7 */
2984                 .headersize = sizeof(struct efi_table_hdr),
2985         },
2986         .fw_vendor = (long)firmware_vendor,
2987         .con_in = (void *)&efi_con_in,
2988         .con_out = (void *)&efi_con_out,
2989         .std_err = (void *)&efi_con_out,
2990         .runtime = (void *)&efi_runtime_services,
2991         .boottime = (void *)&efi_boot_services,
2992         .nr_tables = 0,
2993         .tables = (void *)efi_conf_table,
2994 };