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