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