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