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