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