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