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