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