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