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