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