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