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