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