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