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