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