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 /* 1 if inside U-Boot code, 0 if inside EFI payload code */
48 static int entry_count = 1;
49 static int nesting_level;
50 /* GUID of the device tree table */
51 const efi_guid_t efi_guid_fdt = EFI_FDT_GUID;
52 /* GUID of the EFI_DRIVER_BINDING_PROTOCOL */
53 const efi_guid_t efi_guid_driver_binding_protocol =
54 			EFI_DRIVER_BINDING_PROTOCOL_GUID;
55 
56 /* event group ExitBootServices() invoked */
57 const efi_guid_t efi_guid_event_group_exit_boot_services =
58 			EFI_EVENT_GROUP_EXIT_BOOT_SERVICES;
59 /* event group SetVirtualAddressMap() invoked */
60 const efi_guid_t efi_guid_event_group_virtual_address_change =
61 			EFI_EVENT_GROUP_VIRTUAL_ADDRESS_CHANGE;
62 /* event group memory map changed */
63 const efi_guid_t efi_guid_event_group_memory_map_change =
64 			EFI_EVENT_GROUP_MEMORY_MAP_CHANGE;
65 /* event group boot manager about to boot */
66 const efi_guid_t efi_guid_event_group_ready_to_boot =
67 			EFI_EVENT_GROUP_READY_TO_BOOT;
68 /* event group ResetSystem() invoked (before ExitBootServices) */
69 const efi_guid_t efi_guid_event_group_reset_system =
70 			EFI_EVENT_GROUP_RESET_SYSTEM;
71 
72 static efi_status_t EFIAPI efi_disconnect_controller(
73 					efi_handle_t controller_handle,
74 					efi_handle_t driver_image_handle,
75 					efi_handle_t child_handle);
76 
77 /* Called on every callback entry */
78 int __efi_entry_check(void)
79 {
80 	int ret = entry_count++ == 0;
81 #ifdef CONFIG_ARM
82 	assert(efi_gd);
83 	app_gd = gd;
84 	gd = efi_gd;
85 #endif
86 	return ret;
87 }
88 
89 /* Called on every callback exit */
90 int __efi_exit_check(void)
91 {
92 	int ret = --entry_count == 0;
93 #ifdef CONFIG_ARM
94 	gd = app_gd;
95 #endif
96 	return ret;
97 }
98 
99 /* Called from do_bootefi_exec() */
100 void efi_save_gd(void)
101 {
102 #ifdef CONFIG_ARM
103 	efi_gd = gd;
104 #endif
105 }
106 
107 /*
108  * Special case handler for error/abort that just forces things back to u-boot
109  * world so we can dump out an abort message, without any care about returning
110  * back to UEFI world.
111  */
112 void efi_restore_gd(void)
113 {
114 #ifdef CONFIG_ARM
115 	/* Only restore if we're already in EFI context */
116 	if (!efi_gd)
117 		return;
118 	gd = efi_gd;
119 #endif
120 }
121 
122 /**
123  * indent_string() - returns a string for indenting with two spaces per level
124  * @level: indent level
125  *
126  * A maximum of ten indent levels is supported. Higher indent levels will be
127  * truncated.
128  *
129  * Return: A string for indenting with two spaces per level is
130  *         returned.
131  */
132 static const char *indent_string(int level)
133 {
134 	const char *indent = "                    ";
135 	const int max = strlen(indent);
136 
137 	level = min(max, level * 2);
138 	return &indent[max - level];
139 }
140 
141 const char *__efi_nesting(void)
142 {
143 	return indent_string(nesting_level);
144 }
145 
146 const char *__efi_nesting_inc(void)
147 {
148 	return indent_string(nesting_level++);
149 }
150 
151 const char *__efi_nesting_dec(void)
152 {
153 	return indent_string(--nesting_level);
154 }
155 
156 /**
157  * efi_queue_event() - queue an EFI event
158  * @event:     event to signal
159  * @check_tpl: check the TPL level
160  *
161  * This function queues the notification function of the event for future
162  * execution.
163  *
164  * The notification function is called if the task priority level of the event
165  * is higher than the current task priority level.
166  *
167  * For the SignalEvent service see efi_signal_event_ext.
168  *
169  */
170 static void efi_queue_event(struct efi_event *event, bool check_tpl)
171 {
172 	if (event->notify_function) {
173 		event->is_queued = true;
174 		/* Check TPL */
175 		if (check_tpl && efi_tpl >= event->notify_tpl)
176 			return;
177 		EFI_CALL_VOID(event->notify_function(event,
178 						     event->notify_context));
179 	}
180 	event->is_queued = false;
181 }
182 
183 /**
184  * is_valid_tpl() - check if the task priority level is valid
185  *
186  * @tpl:		TPL level to check
187  * Return:		status code
188  */
189 efi_status_t is_valid_tpl(efi_uintn_t tpl)
190 {
191 	switch (tpl) {
192 	case TPL_APPLICATION:
193 	case TPL_CALLBACK:
194 	case TPL_NOTIFY:
195 	case TPL_HIGH_LEVEL:
196 		return EFI_SUCCESS;
197 	default:
198 		return EFI_INVALID_PARAMETER;
199 	}
200 }
201 
202 /**
203  * efi_signal_event() - signal an EFI event
204  * @event:     event to signal
205  * @check_tpl: check the TPL level
206  *
207  * This function signals an event. If the event belongs to an event group all
208  * events of the group are signaled. If they are of type EVT_NOTIFY_SIGNAL
209  * their notification function is queued.
210  *
211  * For the SignalEvent service see efi_signal_event_ext.
212  */
213 void efi_signal_event(struct efi_event *event, bool check_tpl)
214 {
215 	if (event->group) {
216 		struct efi_event *evt;
217 
218 		/*
219 		 * The signaled state has to set before executing any
220 		 * notification function
221 		 */
222 		list_for_each_entry(evt, &efi_events, link) {
223 			if (!evt->group || guidcmp(evt->group, event->group))
224 				continue;
225 			if (evt->is_signaled)
226 				continue;
227 			evt->is_signaled = true;
228 			if (evt->type & EVT_NOTIFY_SIGNAL &&
229 			    evt->notify_function)
230 				evt->is_queued = true;
231 		}
232 		list_for_each_entry(evt, &efi_events, link) {
233 			if (!evt->group || guidcmp(evt->group, event->group))
234 				continue;
235 			if (evt->is_queued)
236 				efi_queue_event(evt, check_tpl);
237 		}
238 	} else if (!event->is_signaled) {
239 		event->is_signaled = true;
240 		if (event->type & EVT_NOTIFY_SIGNAL)
241 			efi_queue_event(event, check_tpl);
242 	}
243 }
244 
245 /**
246  * efi_raise_tpl() - raise the task priority level
247  * @new_tpl: new value of the task priority level
248  *
249  * This function implements the RaiseTpl service.
250  *
251  * See the Unified Extensible Firmware Interface (UEFI) specification for
252  * details.
253  *
254  * Return: old value of the task priority level
255  */
256 static unsigned long EFIAPI efi_raise_tpl(efi_uintn_t new_tpl)
257 {
258 	efi_uintn_t old_tpl = efi_tpl;
259 
260 	EFI_ENTRY("0x%zx", new_tpl);
261 
262 	if (new_tpl < efi_tpl)
263 		debug("WARNING: new_tpl < current_tpl in %s\n", __func__);
264 	efi_tpl = new_tpl;
265 	if (efi_tpl > TPL_HIGH_LEVEL)
266 		efi_tpl = TPL_HIGH_LEVEL;
267 
268 	EFI_EXIT(EFI_SUCCESS);
269 	return old_tpl;
270 }
271 
272 /**
273  * efi_restore_tpl() - lower the task priority level
274  * @old_tpl: value of the task priority level to be restored
275  *
276  * This function implements the RestoreTpl service.
277  *
278  * See the Unified Extensible Firmware Interface (UEFI) specification for
279  * details.
280  */
281 static void EFIAPI efi_restore_tpl(efi_uintn_t old_tpl)
282 {
283 	EFI_ENTRY("0x%zx", old_tpl);
284 
285 	if (old_tpl > efi_tpl)
286 		debug("WARNING: old_tpl > current_tpl in %s\n", __func__);
287 	efi_tpl = old_tpl;
288 	if (efi_tpl > TPL_HIGH_LEVEL)
289 		efi_tpl = TPL_HIGH_LEVEL;
290 
291 	/*
292 	 * Lowering the TPL may have made queued events eligible for execution.
293 	 */
294 	efi_timer_check();
295 
296 	EFI_EXIT(EFI_SUCCESS);
297 }
298 
299 /**
300  * efi_allocate_pages_ext() - allocate memory pages
301  * @type:        type of allocation to be performed
302  * @memory_type: usage type of the allocated memory
303  * @pages:       number of pages to be allocated
304  * @memory:      allocated memory
305  *
306  * This function implements the AllocatePages service.
307  *
308  * See the Unified Extensible Firmware Interface (UEFI) specification for
309  * details.
310  *
311  * Return: status code
312  */
313 static efi_status_t EFIAPI efi_allocate_pages_ext(int type, int memory_type,
314 						  efi_uintn_t pages,
315 						  uint64_t *memory)
316 {
317 	efi_status_t r;
318 
319 	EFI_ENTRY("%d, %d, 0x%zx, %p", type, memory_type, pages, memory);
320 	r = efi_allocate_pages(type, memory_type, pages, memory);
321 	return EFI_EXIT(r);
322 }
323 
324 /**
325  * efi_free_pages_ext() - Free memory pages.
326  * @memory: start of the memory area to be freed
327  * @pages:  number of pages to be freed
328  *
329  * This function implements the FreePages service.
330  *
331  * See the Unified Extensible Firmware Interface (UEFI) specification for
332  * details.
333  *
334  * Return: status code
335  */
336 static efi_status_t EFIAPI efi_free_pages_ext(uint64_t memory,
337 					      efi_uintn_t pages)
338 {
339 	efi_status_t r;
340 
341 	EFI_ENTRY("%llx, 0x%zx", memory, pages);
342 	r = efi_free_pages(memory, pages);
343 	return EFI_EXIT(r);
344 }
345 
346 /**
347  * efi_get_memory_map_ext() - get map describing memory usage
348  * @memory_map_size:    on entry the size, in bytes, of the memory map buffer,
349  *                      on exit the size of the copied memory map
350  * @memory_map:         buffer to which the memory map is written
351  * @map_key:            key for the memory map
352  * @descriptor_size:    size of an individual memory descriptor
353  * @descriptor_version: version number of the memory descriptor structure
354  *
355  * This function implements the GetMemoryMap service.
356  *
357  * See the Unified Extensible Firmware Interface (UEFI) specification for
358  * details.
359  *
360  * Return: status code
361  */
362 static efi_status_t EFIAPI efi_get_memory_map_ext(
363 					efi_uintn_t *memory_map_size,
364 					struct efi_mem_desc *memory_map,
365 					efi_uintn_t *map_key,
366 					efi_uintn_t *descriptor_size,
367 					uint32_t *descriptor_version)
368 {
369 	efi_status_t r;
370 
371 	EFI_ENTRY("%p, %p, %p, %p, %p", memory_map_size, memory_map,
372 		  map_key, descriptor_size, descriptor_version);
373 	r = efi_get_memory_map(memory_map_size, memory_map, map_key,
374 			       descriptor_size, descriptor_version);
375 	return EFI_EXIT(r);
376 }
377 
378 /**
379  * efi_allocate_pool_ext() - allocate memory from pool
380  * @pool_type: type of the pool from which memory is to be allocated
381  * @size:      number of bytes to be allocated
382  * @buffer:    allocated memory
383  *
384  * This function implements the AllocatePool service.
385  *
386  * See the Unified Extensible Firmware Interface (UEFI) specification for
387  * details.
388  *
389  * Return: status code
390  */
391 static efi_status_t EFIAPI efi_allocate_pool_ext(int pool_type,
392 						 efi_uintn_t size,
393 						 void **buffer)
394 {
395 	efi_status_t r;
396 
397 	EFI_ENTRY("%d, %zd, %p", pool_type, size, buffer);
398 	r = efi_allocate_pool(pool_type, size, buffer);
399 	return EFI_EXIT(r);
400 }
401 
402 /**
403  * efi_free_pool_ext() - free memory from pool
404  * @buffer: start of memory to be freed
405  *
406  * This function implements the FreePool service.
407  *
408  * See the Unified Extensible Firmware Interface (UEFI) specification for
409  * details.
410  *
411  * Return: status code
412  */
413 static efi_status_t EFIAPI efi_free_pool_ext(void *buffer)
414 {
415 	efi_status_t r;
416 
417 	EFI_ENTRY("%p", buffer);
418 	r = efi_free_pool(buffer);
419 	return EFI_EXIT(r);
420 }
421 
422 /**
423  * efi_add_handle() - add a new object to the object list
424  * @obj: object to be added
425  *
426  * The protocols list is initialized. The object handle is set.
427  */
428 void efi_add_handle(efi_handle_t handle)
429 {
430 	if (!handle)
431 		return;
432 	INIT_LIST_HEAD(&handle->protocols);
433 	list_add_tail(&handle->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;
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(efi_handle_t handle)
548 {
549 	if (!handle)
550 		return;
551 	efi_remove_all_protocols(handle);
552 	list_del(&handle->link);
553 	free(handle);
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 boot up */
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 100 ns
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 100 ns.
751 	 * We use multiples of 1000 ns. 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 100 ns
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)
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 			efi_handle_t *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  * @handle:               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(efi_handle_t handle,
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, &handle->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, &handle->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  * @handle:       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 				(efi_handle_t handle,
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(handle, 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 				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() - uninstall protocol interface
1168  *
1169  * @handle:             handle from which the protocol shall be removed
1170  * @protocol:           GUID of the protocol to be removed
1171  * @protocol_interface: interface to be removed
1172  *
1173  * This function DOES NOT delete a handle without installed protocol.
1174  *
1175  * Return: status code
1176  */
1177 static efi_status_t efi_uninstall_protocol
1178 			(efi_handle_t handle, const efi_guid_t *protocol,
1179 			 void *protocol_interface)
1180 {
1181 	struct efi_object *efiobj;
1182 	struct efi_handler *handler;
1183 	struct efi_open_protocol_info_item *item;
1184 	struct efi_open_protocol_info_item *pos;
1185 	efi_status_t r;
1186 
1187 	/* Check handle */
1188 	efiobj = efi_search_obj(handle);
1189 	if (!efiobj) {
1190 		r = EFI_INVALID_PARAMETER;
1191 		goto out;
1192 	}
1193 	/* Find the protocol on the handle */
1194 	r = efi_search_protocol(handle, protocol, &handler);
1195 	if (r != EFI_SUCCESS)
1196 		goto out;
1197 	/* Disconnect controllers */
1198 	efi_disconnect_all_drivers(efiobj, protocol, NULL);
1199 	if (!list_empty(&handler->open_infos)) {
1200 		r =  EFI_ACCESS_DENIED;
1201 		goto out;
1202 	}
1203 	/* Close protocol */
1204 	list_for_each_entry_safe(item, pos, &handler->open_infos, link) {
1205 		if (item->info.attributes ==
1206 			EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL ||
1207 		    item->info.attributes == EFI_OPEN_PROTOCOL_GET_PROTOCOL ||
1208 		    item->info.attributes == EFI_OPEN_PROTOCOL_TEST_PROTOCOL)
1209 			list_del(&item->link);
1210 	}
1211 	if (!list_empty(&handler->open_infos)) {
1212 		r =  EFI_ACCESS_DENIED;
1213 		goto out;
1214 	}
1215 	r = efi_remove_protocol(handle, protocol, protocol_interface);
1216 out:
1217 	return r;
1218 }
1219 
1220 /**
1221  * efi_uninstall_protocol_interface() - uninstall protocol interface
1222  * @handle:             handle from which the protocol shall be removed
1223  * @protocol:           GUID of the protocol to be removed
1224  * @protocol_interface: interface to be removed
1225  *
1226  * This function implements the UninstallProtocolInterface service.
1227  *
1228  * See the Unified Extensible Firmware Interface (UEFI) specification for
1229  * details.
1230  *
1231  * Return: status code
1232  */
1233 static efi_status_t EFIAPI efi_uninstall_protocol_interface
1234 			(efi_handle_t handle, const efi_guid_t *protocol,
1235 			 void *protocol_interface)
1236 {
1237 	efi_status_t ret;
1238 
1239 	EFI_ENTRY("%p, %pUl, %p", handle, protocol, protocol_interface);
1240 
1241 	ret = efi_uninstall_protocol(handle, protocol, protocol_interface);
1242 	if (ret != EFI_SUCCESS)
1243 		goto out;
1244 
1245 	/* If the last protocol has been removed, delete the handle. */
1246 	if (list_empty(&handle->protocols)) {
1247 		list_del(&handle->link);
1248 		free(handle);
1249 	}
1250 out:
1251 	return EFI_EXIT(ret);
1252 }
1253 
1254 /**
1255  * efi_register_protocol_notify() - register an event for notification when a
1256  *                                  protocol is installed.
1257  * @protocol:     GUID of the protocol whose installation shall be notified
1258  * @event:        event to be signaled upon installation of the protocol
1259  * @registration: key for retrieving the registration information
1260  *
1261  * This function implements the RegisterProtocolNotify service.
1262  * See the Unified Extensible Firmware Interface (UEFI) specification
1263  * for details.
1264  *
1265  * Return: status code
1266  */
1267 static efi_status_t EFIAPI efi_register_protocol_notify(
1268 						const efi_guid_t *protocol,
1269 						struct efi_event *event,
1270 						void **registration)
1271 {
1272 	EFI_ENTRY("%pUl, %p, %p", protocol, event, registration);
1273 	return EFI_EXIT(EFI_OUT_OF_RESOURCES);
1274 }
1275 
1276 /**
1277  * efi_search() - determine if an EFI handle implements a protocol
1278  * @search_type: selection criterion
1279  * @protocol:    GUID of the protocol
1280  * @search_key:  registration key
1281  * @handle:      handle
1282  *
1283  * See the documentation of the LocateHandle service in the UEFI specification.
1284  *
1285  * Return: 0 if the handle implements the protocol
1286  */
1287 static int efi_search(enum efi_locate_search_type search_type,
1288 		      const efi_guid_t *protocol, void *search_key,
1289 		      efi_handle_t handle)
1290 {
1291 	efi_status_t ret;
1292 
1293 	switch (search_type) {
1294 	case ALL_HANDLES:
1295 		return 0;
1296 	case BY_REGISTER_NOTIFY:
1297 		/* TODO: RegisterProtocolNotify is not implemented yet */
1298 		return -1;
1299 	case BY_PROTOCOL:
1300 		ret = efi_search_protocol(handle, protocol, NULL);
1301 		return (ret != EFI_SUCCESS);
1302 	default:
1303 		/* Invalid search type */
1304 		return -1;
1305 	}
1306 }
1307 
1308 /**
1309  * efi_locate_handle() - locate handles implementing a protocol
1310  * @search_type: selection criterion
1311  * @protocol:    GUID of the protocol
1312  * @search_key: registration key
1313  * @buffer_size: size of the buffer to receive the handles in bytes
1314  * @buffer:      buffer to receive the relevant handles
1315  *
1316  * This function is meant for U-Boot internal calls. For the API implementation
1317  * of the LocateHandle service see efi_locate_handle_ext.
1318  *
1319  * Return: status code
1320  */
1321 static efi_status_t efi_locate_handle(
1322 			enum efi_locate_search_type search_type,
1323 			const efi_guid_t *protocol, void *search_key,
1324 			efi_uintn_t *buffer_size, efi_handle_t *buffer)
1325 {
1326 	struct efi_object *efiobj;
1327 	efi_uintn_t size = 0;
1328 
1329 	/* Check parameters */
1330 	switch (search_type) {
1331 	case ALL_HANDLES:
1332 		break;
1333 	case BY_REGISTER_NOTIFY:
1334 		if (!search_key)
1335 			return EFI_INVALID_PARAMETER;
1336 		/* RegisterProtocolNotify is not implemented yet */
1337 		return EFI_UNSUPPORTED;
1338 	case BY_PROTOCOL:
1339 		if (!protocol)
1340 			return EFI_INVALID_PARAMETER;
1341 		break;
1342 	default:
1343 		return EFI_INVALID_PARAMETER;
1344 	}
1345 
1346 	/*
1347 	 * efi_locate_handle_buffer uses this function for
1348 	 * the calculation of the necessary buffer size.
1349 	 * So do not require a buffer for buffersize == 0.
1350 	 */
1351 	if (!buffer_size || (*buffer_size && !buffer))
1352 		return EFI_INVALID_PARAMETER;
1353 
1354 	/* Count how much space we need */
1355 	list_for_each_entry(efiobj, &efi_obj_list, link) {
1356 		if (!efi_search(search_type, protocol, search_key, efiobj))
1357 			size += sizeof(void *);
1358 	}
1359 
1360 	if (*buffer_size < size) {
1361 		*buffer_size = size;
1362 		return EFI_BUFFER_TOO_SMALL;
1363 	}
1364 
1365 	*buffer_size = size;
1366 	if (size == 0)
1367 		return EFI_NOT_FOUND;
1368 
1369 	/* Then fill the array */
1370 	list_for_each_entry(efiobj, &efi_obj_list, link) {
1371 		if (!efi_search(search_type, protocol, search_key, efiobj))
1372 			*buffer++ = efiobj;
1373 	}
1374 
1375 	return EFI_SUCCESS;
1376 }
1377 
1378 /**
1379  * efi_locate_handle_ext() - locate handles implementing a protocol.
1380  * @search_type: selection criterion
1381  * @protocol:    GUID of the protocol
1382  * @search_key:  registration key
1383  * @buffer_size: size of the buffer to receive the handles in bytes
1384  * @buffer:      buffer to receive the relevant handles
1385  *
1386  * This function implements the LocateHandle service.
1387  *
1388  * See the Unified Extensible Firmware Interface (UEFI) specification for
1389  * details.
1390  *
1391  * Return: 0 if the handle implements the protocol
1392  */
1393 static efi_status_t EFIAPI efi_locate_handle_ext(
1394 			enum efi_locate_search_type search_type,
1395 			const efi_guid_t *protocol, void *search_key,
1396 			efi_uintn_t *buffer_size, efi_handle_t *buffer)
1397 {
1398 	EFI_ENTRY("%d, %pUl, %p, %p, %p", search_type, protocol, search_key,
1399 		  buffer_size, buffer);
1400 
1401 	return EFI_EXIT(efi_locate_handle(search_type, protocol, search_key,
1402 			buffer_size, buffer));
1403 }
1404 
1405 /**
1406  * efi_remove_configuration_table() - collapses configuration table entries,
1407  *                                    removing index i
1408  *
1409  * @i: index of the table entry to be removed
1410  */
1411 static void efi_remove_configuration_table(int i)
1412 {
1413 	struct efi_configuration_table *this = &systab.tables[i];
1414 	struct efi_configuration_table *next = &systab.tables[i + 1];
1415 	struct efi_configuration_table *end = &systab.tables[systab.nr_tables];
1416 
1417 	memmove(this, next, (ulong)end - (ulong)next);
1418 	systab.nr_tables--;
1419 }
1420 
1421 /**
1422  * efi_install_configuration_table() - adds, updates, or removes a
1423  *                                     configuration table
1424  * @guid:  GUID of the installed table
1425  * @table: table to be installed
1426  *
1427  * This function is used for internal calls. For the API implementation of the
1428  * InstallConfigurationTable service see efi_install_configuration_table_ext.
1429  *
1430  * Return: status code
1431  */
1432 efi_status_t efi_install_configuration_table(const efi_guid_t *guid,
1433 					     void *table)
1434 {
1435 	struct efi_event *evt;
1436 	int i;
1437 
1438 	if (!guid)
1439 		return EFI_INVALID_PARAMETER;
1440 
1441 	/* Check for GUID override */
1442 	for (i = 0; i < systab.nr_tables; i++) {
1443 		if (!guidcmp(guid, &systab.tables[i].guid)) {
1444 			if (table)
1445 				systab.tables[i].table = table;
1446 			else
1447 				efi_remove_configuration_table(i);
1448 			goto out;
1449 		}
1450 	}
1451 
1452 	if (!table)
1453 		return EFI_NOT_FOUND;
1454 
1455 	/* No override, check for overflow */
1456 	if (i >= EFI_MAX_CONFIGURATION_TABLES)
1457 		return EFI_OUT_OF_RESOURCES;
1458 
1459 	/* Add a new entry */
1460 	memcpy(&systab.tables[i].guid, guid, sizeof(*guid));
1461 	systab.tables[i].table = table;
1462 	systab.nr_tables = i + 1;
1463 
1464 out:
1465 	/* systab.nr_tables may have changed. So we need to update the CRC32 */
1466 	efi_update_table_header_crc32(&systab.hdr);
1467 
1468 	/* Notify that the configuration table was changed */
1469 	list_for_each_entry(evt, &efi_events, link) {
1470 		if (evt->group && !guidcmp(evt->group, guid)) {
1471 			efi_signal_event(evt, false);
1472 			break;
1473 		}
1474 	}
1475 
1476 	return EFI_SUCCESS;
1477 }
1478 
1479 /**
1480  * efi_install_configuration_table_ex() - Adds, updates, or removes a
1481  *                                        configuration table.
1482  * @guid:  GUID of the installed table
1483  * @table: table to be installed
1484  *
1485  * This function implements the InstallConfigurationTable service.
1486  *
1487  * See the Unified Extensible Firmware Interface (UEFI) specification for
1488  * details.
1489  *
1490  * Return: status code
1491  */
1492 static efi_status_t EFIAPI efi_install_configuration_table_ext(efi_guid_t *guid,
1493 							       void *table)
1494 {
1495 	EFI_ENTRY("%pUl, %p", guid, table);
1496 	return EFI_EXIT(efi_install_configuration_table(guid, table));
1497 }
1498 
1499 /**
1500  * efi_setup_loaded_image() - initialize a loaded image
1501  *
1502  * Initialize a loaded_image_info and loaded_image_info object with correct
1503  * protocols, boot-device, etc.
1504  *
1505  * In case of an error *handle_ptr and *info_ptr are set to NULL and an error
1506  * code is returned.
1507  *
1508  * @device_path:	device path of the loaded image
1509  * @file_path:		file path of the loaded image
1510  * @handle_ptr:		handle of the loaded image
1511  * @info_ptr:		loaded image protocol
1512  * Return:		status code
1513  */
1514 efi_status_t efi_setup_loaded_image(struct efi_device_path *device_path,
1515 				    struct efi_device_path *file_path,
1516 				    struct efi_loaded_image_obj **handle_ptr,
1517 				    struct efi_loaded_image **info_ptr)
1518 {
1519 	efi_status_t ret;
1520 	struct efi_loaded_image *info = NULL;
1521 	struct efi_loaded_image_obj *obj = NULL;
1522 
1523 	/* In case of EFI_OUT_OF_RESOURCES avoid illegal free by caller. */
1524 	*handle_ptr = NULL;
1525 	*info_ptr = NULL;
1526 
1527 	info = calloc(1, sizeof(*info));
1528 	if (!info)
1529 		return EFI_OUT_OF_RESOURCES;
1530 	obj = calloc(1, sizeof(*obj));
1531 	if (!obj) {
1532 		free(info);
1533 		return EFI_OUT_OF_RESOURCES;
1534 	}
1535 
1536 	/* Add internal object to object list */
1537 	efi_add_handle(&obj->header);
1538 
1539 	info->revision =  EFI_LOADED_IMAGE_PROTOCOL_REVISION;
1540 	info->file_path = file_path;
1541 	info->system_table = &systab;
1542 
1543 	if (device_path) {
1544 		info->device_handle = efi_dp_find_obj(device_path, NULL);
1545 		/*
1546 		 * When asking for the device path interface, return
1547 		 * bootefi_device_path
1548 		 */
1549 		ret = efi_add_protocol(&obj->header,
1550 				       &efi_guid_device_path, device_path);
1551 		if (ret != EFI_SUCCESS)
1552 			goto failure;
1553 	}
1554 
1555 	/*
1556 	 * When asking for the loaded_image interface, just
1557 	 * return handle which points to loaded_image_info
1558 	 */
1559 	ret = efi_add_protocol(&obj->header,
1560 			       &efi_guid_loaded_image, info);
1561 	if (ret != EFI_SUCCESS)
1562 		goto failure;
1563 
1564 #if CONFIG_IS_ENABLED(EFI_LOADER_HII)
1565 	ret = efi_add_protocol(&obj->header,
1566 			       &efi_guid_hii_string_protocol,
1567 			       (void *)&efi_hii_string);
1568 	if (ret != EFI_SUCCESS)
1569 		goto failure;
1570 
1571 	ret = efi_add_protocol(&obj->header,
1572 			       &efi_guid_hii_database_protocol,
1573 			       (void *)&efi_hii_database);
1574 	if (ret != EFI_SUCCESS)
1575 		goto failure;
1576 
1577 	ret = efi_add_protocol(&obj->header,
1578 			       &efi_guid_hii_config_routing_protocol,
1579 			       (void *)&efi_hii_config_routing);
1580 	if (ret != EFI_SUCCESS)
1581 		goto failure;
1582 #endif
1583 
1584 	if (info_ptr)
1585 		*info_ptr = info;
1586 	if (handle_ptr)
1587 		*handle_ptr = obj;
1588 
1589 	return ret;
1590 failure:
1591 	printf("ERROR: Failure to install protocols for loaded image\n");
1592 	efi_delete_handle(&obj->header);
1593 	free(info);
1594 	return ret;
1595 }
1596 
1597 /**
1598  * efi_load_image_from_path() - load an image using a file path
1599  *
1600  * Read a file into a buffer allocated as EFI_BOOT_SERVICES_DATA. It is the
1601  * callers obligation to update the memory type as needed.
1602  *
1603  * @file_path:	the path of the image to load
1604  * @buffer:	buffer containing the loaded image
1605  * @size:	size of the loaded image
1606  * Return:	status code
1607  */
1608 efi_status_t efi_load_image_from_path(struct efi_device_path *file_path,
1609 				      void **buffer, efi_uintn_t *size)
1610 {
1611 	struct efi_file_info *info = NULL;
1612 	struct efi_file_handle *f;
1613 	static efi_status_t ret;
1614 	u64 addr;
1615 	efi_uintn_t bs;
1616 
1617 	/* In case of failure nothing is returned */
1618 	*buffer = NULL;
1619 	*size = 0;
1620 
1621 	/* Open file */
1622 	f = efi_file_from_path(file_path);
1623 	if (!f)
1624 		return EFI_DEVICE_ERROR;
1625 
1626 	/* Get file size */
1627 	bs = 0;
1628 	EFI_CALL(ret = f->getinfo(f, (efi_guid_t *)&efi_file_info_guid,
1629 				  &bs, info));
1630 	if (ret != EFI_BUFFER_TOO_SMALL) {
1631 		ret =  EFI_DEVICE_ERROR;
1632 		goto error;
1633 	}
1634 
1635 	info = malloc(bs);
1636 	EFI_CALL(ret = f->getinfo(f, (efi_guid_t *)&efi_file_info_guid, &bs,
1637 				  info));
1638 	if (ret != EFI_SUCCESS)
1639 		goto error;
1640 
1641 	/*
1642 	 * When reading the file we do not yet know if it contains an
1643 	 * application, a boottime driver, or a runtime driver. So here we
1644 	 * allocate a buffer as EFI_BOOT_SERVICES_DATA. The caller has to
1645 	 * update the reservation according to the image type.
1646 	 */
1647 	bs = info->file_size;
1648 	ret = efi_allocate_pages(EFI_ALLOCATE_ANY_PAGES,
1649 				 EFI_BOOT_SERVICES_DATA,
1650 				 efi_size_in_pages(bs), &addr);
1651 	if (ret != EFI_SUCCESS) {
1652 		ret = EFI_OUT_OF_RESOURCES;
1653 		goto error;
1654 	}
1655 
1656 	/* Read file */
1657 	EFI_CALL(ret = f->read(f, &bs, (void *)(uintptr_t)addr));
1658 	if (ret != EFI_SUCCESS)
1659 		efi_free_pages(addr, efi_size_in_pages(bs));
1660 	*buffer = (void *)(uintptr_t)addr;
1661 	*size = bs;
1662 error:
1663 	EFI_CALL(f->close(f));
1664 	free(info);
1665 	return ret;
1666 }
1667 
1668 /**
1669  * efi_load_image() - load an EFI image into memory
1670  * @boot_policy:   true for request originating from the boot manager
1671  * @parent_image:  the caller's image handle
1672  * @file_path:     the path of the image to load
1673  * @source_buffer: memory location from which the image is installed
1674  * @source_size:   size of the memory area from which the image is installed
1675  * @image_handle:  handle for the newly installed image
1676  *
1677  * This function implements the LoadImage service.
1678  *
1679  * See the Unified Extensible Firmware Interface (UEFI) specification
1680  * for details.
1681  *
1682  * Return: status code
1683  */
1684 static efi_status_t EFIAPI efi_load_image(bool boot_policy,
1685 					  efi_handle_t parent_image,
1686 					  struct efi_device_path *file_path,
1687 					  void *source_buffer,
1688 					  efi_uintn_t source_size,
1689 					  efi_handle_t *image_handle)
1690 {
1691 	struct efi_device_path *dp, *fp;
1692 	struct efi_loaded_image *info = NULL;
1693 	struct efi_loaded_image_obj **image_obj =
1694 		(struct efi_loaded_image_obj **)image_handle;
1695 	efi_status_t ret;
1696 
1697 	EFI_ENTRY("%d, %p, %pD, %p, %zd, %p", boot_policy, parent_image,
1698 		  file_path, source_buffer, source_size, image_handle);
1699 
1700 	if (!image_handle || !parent_image) {
1701 		ret = EFI_INVALID_PARAMETER;
1702 		goto error;
1703 	}
1704 
1705 	if (!source_buffer && !file_path) {
1706 		ret = EFI_NOT_FOUND;
1707 		goto error;
1708 	}
1709 
1710 	if (!source_buffer) {
1711 		ret = efi_load_image_from_path(file_path, &source_buffer,
1712 					       &source_size);
1713 		if (ret != EFI_SUCCESS)
1714 			goto error;
1715 		/*
1716 		 * split file_path which contains both the device and
1717 		 * file parts:
1718 		 */
1719 		efi_dp_split_file_path(file_path, &dp, &fp);
1720 	} else {
1721 		/* In this case, file_path is the "device" path, i.e.
1722 		 * something like a HARDWARE_DEVICE:MEMORY_MAPPED
1723 		 */
1724 		u64 addr;
1725 		void *dest_buffer;
1726 
1727 		ret = efi_allocate_pages(EFI_ALLOCATE_ANY_PAGES,
1728 					 EFI_RUNTIME_SERVICES_CODE,
1729 					 efi_size_in_pages(source_size), &addr);
1730 		if (ret != EFI_SUCCESS)
1731 			goto error;
1732 		dest_buffer = (void *)(uintptr_t)addr;
1733 		memcpy(dest_buffer, source_buffer, source_size);
1734 		source_buffer = dest_buffer;
1735 
1736 		dp = file_path;
1737 		fp = NULL;
1738 	}
1739 	ret = efi_setup_loaded_image(dp, fp, image_obj, &info);
1740 	if (ret != EFI_SUCCESS)
1741 		goto error_invalid_image;
1742 	ret = efi_load_pe(*image_obj, source_buffer, info);
1743 	if (ret != EFI_SUCCESS)
1744 		goto error_invalid_image;
1745 	/* Update the type of the allocated memory */
1746 	efi_add_memory_map((uintptr_t)source_buffer,
1747 			   efi_size_in_pages(source_size),
1748 			   info->image_code_type, false);
1749 	info->system_table = &systab;
1750 	info->parent_handle = parent_image;
1751 	return EFI_EXIT(EFI_SUCCESS);
1752 error_invalid_image:
1753 	/* The image is invalid. Release all associated resources. */
1754 	efi_free_pages((uintptr_t)source_buffer,
1755 		       efi_size_in_pages(source_size));
1756 	efi_delete_handle(*image_handle);
1757 	*image_handle = NULL;
1758 	free(info);
1759 error:
1760 	return EFI_EXIT(ret);
1761 }
1762 
1763 /**
1764  * efi_start_image() - call the entry point of an image
1765  * @image_handle:   handle of the image
1766  * @exit_data_size: size of the buffer
1767  * @exit_data:      buffer to receive the exit data of the called image
1768  *
1769  * This function implements the StartImage service.
1770  *
1771  * See the Unified Extensible Firmware Interface (UEFI) specification for
1772  * details.
1773  *
1774  * Return: status code
1775  */
1776 efi_status_t EFIAPI efi_start_image(efi_handle_t image_handle,
1777 				    efi_uintn_t *exit_data_size,
1778 				    u16 **exit_data)
1779 {
1780 	struct efi_loaded_image_obj *image_obj =
1781 		(struct efi_loaded_image_obj *)image_handle;
1782 	efi_status_t ret;
1783 
1784 	EFI_ENTRY("%p, %p, %p", image_handle, exit_data_size, exit_data);
1785 
1786 	efi_is_direct_boot = false;
1787 
1788 	/* call the image! */
1789 	if (setjmp(&image_obj->exit_jmp)) {
1790 		/*
1791 		 * We called the entry point of the child image with EFI_CALL
1792 		 * in the lines below. The child image called the Exit() boot
1793 		 * service efi_exit() which executed the long jump that brought
1794 		 * us to the current line. This implies that the second half
1795 		 * of the EFI_CALL macro has not been executed.
1796 		 */
1797 #ifdef CONFIG_ARM
1798 		/*
1799 		 * efi_exit() called efi_restore_gd(). We have to undo this
1800 		 * otherwise __efi_entry_check() will put the wrong value into
1801 		 * app_gd.
1802 		 */
1803 		gd = app_gd;
1804 #endif
1805 		/*
1806 		 * To get ready to call EFI_EXIT below we have to execute the
1807 		 * missed out steps of EFI_CALL.
1808 		 */
1809 		assert(__efi_entry_check());
1810 		debug("%sEFI: %lu returned by started image\n",
1811 		      __efi_nesting_dec(),
1812 		      (unsigned long)((uintptr_t)image_obj->exit_status &
1813 				      ~EFI_ERROR_MASK));
1814 		return EFI_EXIT(image_obj->exit_status);
1815 	}
1816 
1817 	ret = EFI_CALL(image_obj->entry(image_handle, &systab));
1818 
1819 	/*
1820 	 * Usually UEFI applications call Exit() instead of returning.
1821 	 * But because the world doesn't consist of ponies and unicorns,
1822 	 * we're happy to emulate that behavior on behalf of a payload
1823 	 * that forgot.
1824 	 */
1825 	return EFI_CALL(systab.boottime->exit(image_handle, ret, 0, NULL));
1826 }
1827 
1828 /**
1829  * efi_exit() - leave an EFI application or driver
1830  * @image_handle:   handle of the application or driver that is exiting
1831  * @exit_status:    status code
1832  * @exit_data_size: size of the buffer in bytes
1833  * @exit_data:      buffer with data describing an error
1834  *
1835  * This function implements the Exit service.
1836  *
1837  * See the Unified Extensible Firmware Interface (UEFI) specification for
1838  * details.
1839  *
1840  * Return: status code
1841  */
1842 static efi_status_t EFIAPI efi_exit(efi_handle_t image_handle,
1843 				    efi_status_t exit_status,
1844 				    efi_uintn_t exit_data_size,
1845 				    u16 *exit_data)
1846 {
1847 	/*
1848 	 * TODO: We should call the unload procedure of the loaded
1849 	 *	 image protocol.
1850 	 */
1851 	struct efi_loaded_image_obj *image_obj =
1852 		(struct efi_loaded_image_obj *)image_handle;
1853 
1854 	EFI_ENTRY("%p, %ld, %zu, %p", image_handle, exit_status,
1855 		  exit_data_size, exit_data);
1856 
1857 	/* Make sure entry/exit counts for EFI world cross-overs match */
1858 	EFI_EXIT(exit_status);
1859 
1860 	/*
1861 	 * But longjmp out with the U-Boot gd, not the application's, as
1862 	 * the other end is a setjmp call inside EFI context.
1863 	 */
1864 	efi_restore_gd();
1865 
1866 	image_obj->exit_status = exit_status;
1867 	longjmp(&image_obj->exit_jmp, 1);
1868 
1869 	panic("EFI application exited");
1870 }
1871 
1872 /**
1873  * efi_unload_image() - unload an EFI image
1874  * @image_handle: handle of the image to be unloaded
1875  *
1876  * This function implements the UnloadImage service.
1877  *
1878  * See the Unified Extensible Firmware Interface (UEFI) specification for
1879  * details.
1880  *
1881  * Return: status code
1882  */
1883 static efi_status_t EFIAPI efi_unload_image(efi_handle_t image_handle)
1884 {
1885 	struct efi_object *efiobj;
1886 
1887 	EFI_ENTRY("%p", image_handle);
1888 	efiobj = efi_search_obj(image_handle);
1889 	if (efiobj)
1890 		list_del(&efiobj->link);
1891 
1892 	return EFI_EXIT(EFI_SUCCESS);
1893 }
1894 
1895 /**
1896  * efi_exit_caches() - fix up caches for EFI payloads if necessary
1897  */
1898 static void efi_exit_caches(void)
1899 {
1900 #if defined(CONFIG_ARM) && !defined(CONFIG_ARM64)
1901 	/*
1902 	 * Grub on 32bit ARM needs to have caches disabled before jumping into
1903 	 * a zImage, but does not know of all cache layers. Give it a hand.
1904 	 */
1905 	if (efi_is_direct_boot)
1906 		cleanup_before_linux();
1907 #endif
1908 }
1909 
1910 /**
1911  * efi_exit_boot_services() - stop all boot services
1912  * @image_handle: handle of the loaded image
1913  * @map_key:      key of the memory map
1914  *
1915  * This function implements the ExitBootServices service.
1916  *
1917  * See the Unified Extensible Firmware Interface (UEFI) specification
1918  * for details.
1919  *
1920  * All timer events are disabled. For exit boot services events the
1921  * notification function is called. The boot services are disabled in the
1922  * system table.
1923  *
1924  * Return: status code
1925  */
1926 static efi_status_t EFIAPI efi_exit_boot_services(efi_handle_t image_handle,
1927 						  unsigned long map_key)
1928 {
1929 	struct efi_event *evt;
1930 
1931 	EFI_ENTRY("%p, %ld", image_handle, map_key);
1932 
1933 	/* Check that the caller has read the current memory map */
1934 	if (map_key != efi_memory_map_key)
1935 		return EFI_INVALID_PARAMETER;
1936 
1937 	/* Make sure that notification functions are not called anymore */
1938 	efi_tpl = TPL_HIGH_LEVEL;
1939 
1940 	/* Check if ExitBootServices has already been called */
1941 	if (!systab.boottime)
1942 		return EFI_EXIT(EFI_SUCCESS);
1943 
1944 	/* Add related events to the event group */
1945 	list_for_each_entry(evt, &efi_events, link) {
1946 		if (evt->type == EVT_SIGNAL_EXIT_BOOT_SERVICES)
1947 			evt->group = &efi_guid_event_group_exit_boot_services;
1948 	}
1949 	/* Notify that ExitBootServices is invoked. */
1950 	list_for_each_entry(evt, &efi_events, link) {
1951 		if (evt->group &&
1952 		    !guidcmp(evt->group,
1953 			     &efi_guid_event_group_exit_boot_services)) {
1954 			efi_signal_event(evt, false);
1955 			break;
1956 		}
1957 	}
1958 
1959 	/* TODO: Should persist EFI variables here */
1960 
1961 	board_quiesce_devices();
1962 
1963 	/* Fix up caches for EFI payloads if necessary */
1964 	efi_exit_caches();
1965 
1966 	/* This stops all lingering devices */
1967 	bootm_disable_interrupts();
1968 
1969 	/* Disable boot time services */
1970 	systab.con_in_handle = NULL;
1971 	systab.con_in = NULL;
1972 	systab.con_out_handle = NULL;
1973 	systab.con_out = NULL;
1974 	systab.stderr_handle = NULL;
1975 	systab.std_err = NULL;
1976 	systab.boottime = NULL;
1977 
1978 	/* Recalculate CRC32 */
1979 	efi_update_table_header_crc32(&systab.hdr);
1980 
1981 	/* Give the payload some time to boot */
1982 	efi_set_watchdog(0);
1983 	WATCHDOG_RESET();
1984 
1985 	return EFI_EXIT(EFI_SUCCESS);
1986 }
1987 
1988 /**
1989  * efi_get_next_monotonic_count() - get next value of the counter
1990  * @count: returned value of the counter
1991  *
1992  * This function implements the NextMonotonicCount service.
1993  *
1994  * See the Unified Extensible Firmware Interface (UEFI) specification for
1995  * details.
1996  *
1997  * Return: status code
1998  */
1999 static efi_status_t EFIAPI efi_get_next_monotonic_count(uint64_t *count)
2000 {
2001 	static uint64_t mono;
2002 
2003 	EFI_ENTRY("%p", count);
2004 	*count = mono++;
2005 	return EFI_EXIT(EFI_SUCCESS);
2006 }
2007 
2008 /**
2009  * efi_stall() - sleep
2010  * @microseconds: period to sleep in microseconds
2011  *
2012  * This function implements the Stall service.
2013  *
2014  * See the Unified Extensible Firmware Interface (UEFI) specification for
2015  * details.
2016  *
2017  * Return:  status code
2018  */
2019 static efi_status_t EFIAPI efi_stall(unsigned long microseconds)
2020 {
2021 	EFI_ENTRY("%ld", microseconds);
2022 	udelay(microseconds);
2023 	return EFI_EXIT(EFI_SUCCESS);
2024 }
2025 
2026 /**
2027  * efi_set_watchdog_timer() - reset the watchdog timer
2028  * @timeout:       seconds before reset by watchdog
2029  * @watchdog_code: code to be logged when resetting
2030  * @data_size:     size of buffer in bytes
2031  * @watchdog_data: buffer with data describing the reset reason
2032  *
2033  * This function implements the SetWatchdogTimer service.
2034  *
2035  * See the Unified Extensible Firmware Interface (UEFI) specification for
2036  * details.
2037  *
2038  * Return: status code
2039  */
2040 static efi_status_t EFIAPI efi_set_watchdog_timer(unsigned long timeout,
2041 						  uint64_t watchdog_code,
2042 						  unsigned long data_size,
2043 						  uint16_t *watchdog_data)
2044 {
2045 	EFI_ENTRY("%ld, 0x%llx, %ld, %p", timeout, watchdog_code,
2046 		  data_size, watchdog_data);
2047 	return EFI_EXIT(efi_set_watchdog(timeout));
2048 }
2049 
2050 /**
2051  * efi_close_protocol() - close a protocol
2052  * @handle:            handle on which the protocol shall be closed
2053  * @protocol:          GUID of the protocol to close
2054  * @agent_handle:      handle of the driver
2055  * @controller_handle: handle of the controller
2056  *
2057  * This function implements the CloseProtocol service.
2058  *
2059  * See the Unified Extensible Firmware Interface (UEFI) specification for
2060  * details.
2061  *
2062  * Return: status code
2063  */
2064 static efi_status_t EFIAPI efi_close_protocol(efi_handle_t handle,
2065 					      const efi_guid_t *protocol,
2066 					      efi_handle_t agent_handle,
2067 					      efi_handle_t controller_handle)
2068 {
2069 	struct efi_handler *handler;
2070 	struct efi_open_protocol_info_item *item;
2071 	struct efi_open_protocol_info_item *pos;
2072 	efi_status_t r;
2073 
2074 	EFI_ENTRY("%p, %pUl, %p, %p", handle, protocol, agent_handle,
2075 		  controller_handle);
2076 
2077 	if (!agent_handle) {
2078 		r = EFI_INVALID_PARAMETER;
2079 		goto out;
2080 	}
2081 	r = efi_search_protocol(handle, protocol, &handler);
2082 	if (r != EFI_SUCCESS)
2083 		goto out;
2084 
2085 	r = EFI_NOT_FOUND;
2086 	list_for_each_entry_safe(item, pos, &handler->open_infos, link) {
2087 		if (item->info.agent_handle == agent_handle &&
2088 		    item->info.controller_handle == controller_handle) {
2089 			efi_delete_open_info(item);
2090 			r = EFI_SUCCESS;
2091 			break;
2092 		}
2093 	}
2094 out:
2095 	return EFI_EXIT(r);
2096 }
2097 
2098 /**
2099  * efi_open_protocol_information() - provide information about then open status
2100  *                                   of a protocol on a handle
2101  * @handle:       handle for which the information shall be retrieved
2102  * @protocol:     GUID of the protocol
2103  * @entry_buffer: buffer to receive the open protocol information
2104  * @entry_count:  number of entries available in the buffer
2105  *
2106  * This function implements the OpenProtocolInformation service.
2107  *
2108  * See the Unified Extensible Firmware Interface (UEFI) specification for
2109  * details.
2110  *
2111  * Return: status code
2112  */
2113 static efi_status_t EFIAPI efi_open_protocol_information(
2114 			efi_handle_t handle, const efi_guid_t *protocol,
2115 			struct efi_open_protocol_info_entry **entry_buffer,
2116 			efi_uintn_t *entry_count)
2117 {
2118 	unsigned long buffer_size;
2119 	unsigned long count;
2120 	struct efi_handler *handler;
2121 	struct efi_open_protocol_info_item *item;
2122 	efi_status_t r;
2123 
2124 	EFI_ENTRY("%p, %pUl, %p, %p", handle, protocol, entry_buffer,
2125 		  entry_count);
2126 
2127 	/* Check parameters */
2128 	if (!entry_buffer) {
2129 		r = EFI_INVALID_PARAMETER;
2130 		goto out;
2131 	}
2132 	r = efi_search_protocol(handle, protocol, &handler);
2133 	if (r != EFI_SUCCESS)
2134 		goto out;
2135 
2136 	/* Count entries */
2137 	count = 0;
2138 	list_for_each_entry(item, &handler->open_infos, link) {
2139 		if (item->info.open_count)
2140 			++count;
2141 	}
2142 	*entry_count = count;
2143 	*entry_buffer = NULL;
2144 	if (!count) {
2145 		r = EFI_SUCCESS;
2146 		goto out;
2147 	}
2148 
2149 	/* Copy entries */
2150 	buffer_size = count * sizeof(struct efi_open_protocol_info_entry);
2151 	r = efi_allocate_pool(EFI_BOOT_SERVICES_DATA, buffer_size,
2152 			      (void **)entry_buffer);
2153 	if (r != EFI_SUCCESS)
2154 		goto out;
2155 	list_for_each_entry_reverse(item, &handler->open_infos, link) {
2156 		if (item->info.open_count)
2157 			(*entry_buffer)[--count] = item->info;
2158 	}
2159 out:
2160 	return EFI_EXIT(r);
2161 }
2162 
2163 /**
2164  * efi_protocols_per_handle() - get protocols installed on a handle
2165  * @handle:                handle for which the information is retrieved
2166  * @protocol_buffer:       buffer with protocol GUIDs
2167  * @protocol_buffer_count: number of entries in the buffer
2168  *
2169  * This function implements the ProtocolsPerHandleService.
2170  *
2171  * See the Unified Extensible Firmware Interface (UEFI) specification for
2172  * details.
2173  *
2174  * Return: status code
2175  */
2176 static efi_status_t EFIAPI efi_protocols_per_handle(
2177 			efi_handle_t handle, efi_guid_t ***protocol_buffer,
2178 			efi_uintn_t *protocol_buffer_count)
2179 {
2180 	unsigned long buffer_size;
2181 	struct efi_object *efiobj;
2182 	struct list_head *protocol_handle;
2183 	efi_status_t r;
2184 
2185 	EFI_ENTRY("%p, %p, %p", handle, protocol_buffer,
2186 		  protocol_buffer_count);
2187 
2188 	if (!handle || !protocol_buffer || !protocol_buffer_count)
2189 		return EFI_EXIT(EFI_INVALID_PARAMETER);
2190 
2191 	*protocol_buffer = NULL;
2192 	*protocol_buffer_count = 0;
2193 
2194 	efiobj = efi_search_obj(handle);
2195 	if (!efiobj)
2196 		return EFI_EXIT(EFI_INVALID_PARAMETER);
2197 
2198 	/* Count protocols */
2199 	list_for_each(protocol_handle, &efiobj->protocols) {
2200 		++*protocol_buffer_count;
2201 	}
2202 
2203 	/* Copy GUIDs */
2204 	if (*protocol_buffer_count) {
2205 		size_t j = 0;
2206 
2207 		buffer_size = sizeof(efi_guid_t *) * *protocol_buffer_count;
2208 		r = efi_allocate_pool(EFI_BOOT_SERVICES_DATA, buffer_size,
2209 				      (void **)protocol_buffer);
2210 		if (r != EFI_SUCCESS)
2211 			return EFI_EXIT(r);
2212 		list_for_each(protocol_handle, &efiobj->protocols) {
2213 			struct efi_handler *protocol;
2214 
2215 			protocol = list_entry(protocol_handle,
2216 					      struct efi_handler, link);
2217 			(*protocol_buffer)[j] = (void *)protocol->guid;
2218 			++j;
2219 		}
2220 	}
2221 
2222 	return EFI_EXIT(EFI_SUCCESS);
2223 }
2224 
2225 /**
2226  * efi_locate_handle_buffer() - locate handles implementing a protocol
2227  * @search_type: selection criterion
2228  * @protocol:    GUID of the protocol
2229  * @search_key:  registration key
2230  * @no_handles:  number of returned handles
2231  * @buffer:      buffer with the returned handles
2232  *
2233  * This function implements the LocateHandleBuffer service.
2234  *
2235  * See the Unified Extensible Firmware Interface (UEFI) specification for
2236  * details.
2237  *
2238  * Return: status code
2239  */
2240 static efi_status_t EFIAPI efi_locate_handle_buffer(
2241 			enum efi_locate_search_type search_type,
2242 			const efi_guid_t *protocol, void *search_key,
2243 			efi_uintn_t *no_handles, efi_handle_t **buffer)
2244 {
2245 	efi_status_t r;
2246 	efi_uintn_t buffer_size = 0;
2247 
2248 	EFI_ENTRY("%d, %pUl, %p, %p, %p", search_type, protocol, search_key,
2249 		  no_handles, buffer);
2250 
2251 	if (!no_handles || !buffer) {
2252 		r = EFI_INVALID_PARAMETER;
2253 		goto out;
2254 	}
2255 	*no_handles = 0;
2256 	*buffer = NULL;
2257 	r = efi_locate_handle(search_type, protocol, search_key, &buffer_size,
2258 			      *buffer);
2259 	if (r != EFI_BUFFER_TOO_SMALL)
2260 		goto out;
2261 	r = efi_allocate_pool(EFI_BOOT_SERVICES_DATA, buffer_size,
2262 			      (void **)buffer);
2263 	if (r != EFI_SUCCESS)
2264 		goto out;
2265 	r = efi_locate_handle(search_type, protocol, search_key, &buffer_size,
2266 			      *buffer);
2267 	if (r == EFI_SUCCESS)
2268 		*no_handles = buffer_size / sizeof(efi_handle_t);
2269 out:
2270 	return EFI_EXIT(r);
2271 }
2272 
2273 /**
2274  * efi_locate_protocol() - find an interface implementing a protocol
2275  * @protocol:           GUID of the protocol
2276  * @registration:       registration key passed to the notification function
2277  * @protocol_interface: interface implementing the protocol
2278  *
2279  * This function implements the LocateProtocol service.
2280  *
2281  * See the Unified Extensible Firmware Interface (UEFI) specification for
2282  * details.
2283  *
2284  * Return: status code
2285  */
2286 static efi_status_t EFIAPI efi_locate_protocol(const efi_guid_t *protocol,
2287 					       void *registration,
2288 					       void **protocol_interface)
2289 {
2290 	struct list_head *lhandle;
2291 	efi_status_t ret;
2292 
2293 	EFI_ENTRY("%pUl, %p, %p", protocol, registration, protocol_interface);
2294 
2295 	if (!protocol || !protocol_interface)
2296 		return EFI_EXIT(EFI_INVALID_PARAMETER);
2297 
2298 	list_for_each(lhandle, &efi_obj_list) {
2299 		struct efi_object *efiobj;
2300 		struct efi_handler *handler;
2301 
2302 		efiobj = list_entry(lhandle, struct efi_object, link);
2303 
2304 		ret = efi_search_protocol(efiobj, protocol, &handler);
2305 		if (ret == EFI_SUCCESS) {
2306 			*protocol_interface = handler->protocol_interface;
2307 			return EFI_EXIT(EFI_SUCCESS);
2308 		}
2309 	}
2310 	*protocol_interface = NULL;
2311 
2312 	return EFI_EXIT(EFI_NOT_FOUND);
2313 }
2314 
2315 /**
2316  * efi_locate_device_path() - Get the device path and handle of an device
2317  *                            implementing a protocol
2318  * @protocol:    GUID of the protocol
2319  * @device_path: device path
2320  * @device:      handle of the device
2321  *
2322  * This function implements the LocateDevicePath service.
2323  *
2324  * See the Unified Extensible Firmware Interface (UEFI) specification for
2325  * details.
2326  *
2327  * Return: status code
2328  */
2329 static efi_status_t EFIAPI efi_locate_device_path(
2330 			const efi_guid_t *protocol,
2331 			struct efi_device_path **device_path,
2332 			efi_handle_t *device)
2333 {
2334 	struct efi_device_path *dp;
2335 	size_t i;
2336 	struct efi_handler *handler;
2337 	efi_handle_t *handles;
2338 	size_t len, len_dp;
2339 	size_t len_best = 0;
2340 	efi_uintn_t no_handles;
2341 	u8 *remainder;
2342 	efi_status_t ret;
2343 
2344 	EFI_ENTRY("%pUl, %p, %p", protocol, device_path, device);
2345 
2346 	if (!protocol || !device_path || !*device_path || !device) {
2347 		ret = EFI_INVALID_PARAMETER;
2348 		goto out;
2349 	}
2350 
2351 	/* Find end of device path */
2352 	len = efi_dp_instance_size(*device_path);
2353 
2354 	/* Get all handles implementing the protocol */
2355 	ret = EFI_CALL(efi_locate_handle_buffer(BY_PROTOCOL, protocol, NULL,
2356 						&no_handles, &handles));
2357 	if (ret != EFI_SUCCESS)
2358 		goto out;
2359 
2360 	for (i = 0; i < no_handles; ++i) {
2361 		/* Find the device path protocol */
2362 		ret = efi_search_protocol(handles[i], &efi_guid_device_path,
2363 					  &handler);
2364 		if (ret != EFI_SUCCESS)
2365 			continue;
2366 		dp = (struct efi_device_path *)handler->protocol_interface;
2367 		len_dp = efi_dp_instance_size(dp);
2368 		/*
2369 		 * This handle can only be a better fit
2370 		 * if its device path length is longer than the best fit and
2371 		 * if its device path length is shorter of equal the searched
2372 		 * device path.
2373 		 */
2374 		if (len_dp <= len_best || len_dp > len)
2375 			continue;
2376 		/* Check if dp is a subpath of device_path */
2377 		if (memcmp(*device_path, dp, len_dp))
2378 			continue;
2379 		*device = handles[i];
2380 		len_best = len_dp;
2381 	}
2382 	if (len_best) {
2383 		remainder = (u8 *)*device_path + len_best;
2384 		*device_path = (struct efi_device_path *)remainder;
2385 		ret = EFI_SUCCESS;
2386 	} else {
2387 		ret = EFI_NOT_FOUND;
2388 	}
2389 out:
2390 	return EFI_EXIT(ret);
2391 }
2392 
2393 /**
2394  * efi_install_multiple_protocol_interfaces() - Install multiple protocol
2395  *                                              interfaces
2396  * @handle: handle on which the protocol interfaces shall be installed
2397  * @...:    NULL terminated argument list with pairs of protocol GUIDS and
2398  *          interfaces
2399  *
2400  * This function implements the MultipleProtocolInterfaces service.
2401  *
2402  * See the Unified Extensible Firmware Interface (UEFI) specification for
2403  * details.
2404  *
2405  * Return: status code
2406  */
2407 static efi_status_t EFIAPI efi_install_multiple_protocol_interfaces
2408 				(efi_handle_t *handle, ...)
2409 {
2410 	EFI_ENTRY("%p", handle);
2411 
2412 	efi_va_list argptr;
2413 	const efi_guid_t *protocol;
2414 	void *protocol_interface;
2415 	efi_status_t r = EFI_SUCCESS;
2416 	int i = 0;
2417 
2418 	if (!handle)
2419 		return EFI_EXIT(EFI_INVALID_PARAMETER);
2420 
2421 	efi_va_start(argptr, handle);
2422 	for (;;) {
2423 		protocol = efi_va_arg(argptr, efi_guid_t*);
2424 		if (!protocol)
2425 			break;
2426 		protocol_interface = efi_va_arg(argptr, void*);
2427 		r = EFI_CALL(efi_install_protocol_interface(
2428 						handle, protocol,
2429 						EFI_NATIVE_INTERFACE,
2430 						protocol_interface));
2431 		if (r != EFI_SUCCESS)
2432 			break;
2433 		i++;
2434 	}
2435 	efi_va_end(argptr);
2436 	if (r == EFI_SUCCESS)
2437 		return EFI_EXIT(r);
2438 
2439 	/* If an error occurred undo all changes. */
2440 	efi_va_start(argptr, handle);
2441 	for (; i; --i) {
2442 		protocol = efi_va_arg(argptr, efi_guid_t*);
2443 		protocol_interface = efi_va_arg(argptr, void*);
2444 		EFI_CALL(efi_uninstall_protocol_interface(*handle, protocol,
2445 							  protocol_interface));
2446 	}
2447 	efi_va_end(argptr);
2448 
2449 	return EFI_EXIT(r);
2450 }
2451 
2452 /**
2453  * efi_uninstall_multiple_protocol_interfaces() - uninstall multiple protocol
2454  *                                                interfaces
2455  * @handle: handle from which the protocol interfaces shall be removed
2456  * @...:    NULL terminated argument list with pairs of protocol GUIDS and
2457  *          interfaces
2458  *
2459  * This function implements the UninstallMultipleProtocolInterfaces service.
2460  *
2461  * See the Unified Extensible Firmware Interface (UEFI) specification for
2462  * details.
2463  *
2464  * Return: status code
2465  */
2466 static efi_status_t EFIAPI efi_uninstall_multiple_protocol_interfaces(
2467 			efi_handle_t handle, ...)
2468 {
2469 	EFI_ENTRY("%p", handle);
2470 
2471 	efi_va_list argptr;
2472 	const efi_guid_t *protocol;
2473 	void *protocol_interface;
2474 	efi_status_t r = EFI_SUCCESS;
2475 	size_t i = 0;
2476 
2477 	if (!handle)
2478 		return EFI_EXIT(EFI_INVALID_PARAMETER);
2479 
2480 	efi_va_start(argptr, handle);
2481 	for (;;) {
2482 		protocol = efi_va_arg(argptr, efi_guid_t*);
2483 		if (!protocol)
2484 			break;
2485 		protocol_interface = efi_va_arg(argptr, void*);
2486 		r = efi_uninstall_protocol(handle, protocol,
2487 					   protocol_interface);
2488 		if (r != EFI_SUCCESS)
2489 			break;
2490 		i++;
2491 	}
2492 	efi_va_end(argptr);
2493 	if (r == EFI_SUCCESS) {
2494 		/* If the last protocol has been removed, delete the handle. */
2495 		if (list_empty(&handle->protocols)) {
2496 			list_del(&handle->link);
2497 			free(handle);
2498 		}
2499 		return EFI_EXIT(r);
2500 	}
2501 
2502 	/* If an error occurred undo all changes. */
2503 	efi_va_start(argptr, handle);
2504 	for (; i; --i) {
2505 		protocol = efi_va_arg(argptr, efi_guid_t*);
2506 		protocol_interface = efi_va_arg(argptr, void*);
2507 		EFI_CALL(efi_install_protocol_interface(&handle, protocol,
2508 							EFI_NATIVE_INTERFACE,
2509 							protocol_interface));
2510 	}
2511 	efi_va_end(argptr);
2512 
2513 	/* In case of an error always return EFI_INVALID_PARAMETER */
2514 	return EFI_EXIT(EFI_INVALID_PARAMETER);
2515 }
2516 
2517 /**
2518  * efi_calculate_crc32() - calculate cyclic redundancy code
2519  * @data:      buffer with data
2520  * @data_size: size of buffer in bytes
2521  * @crc32_p:   cyclic redundancy code
2522  *
2523  * This function implements the CalculateCrc32 service.
2524  *
2525  * See the Unified Extensible Firmware Interface (UEFI) specification for
2526  * details.
2527  *
2528  * Return: status code
2529  */
2530 static efi_status_t EFIAPI efi_calculate_crc32(const void *data,
2531 					       efi_uintn_t data_size,
2532 					       u32 *crc32_p)
2533 {
2534 	EFI_ENTRY("%p, %zu", data, data_size);
2535 	*crc32_p = crc32(0, data, data_size);
2536 	return EFI_EXIT(EFI_SUCCESS);
2537 }
2538 
2539 /**
2540  * efi_copy_mem() - copy memory
2541  * @destination: destination of the copy operation
2542  * @source:      source of the copy operation
2543  * @length:      number of bytes to copy
2544  *
2545  * This function implements the CopyMem service.
2546  *
2547  * See the Unified Extensible Firmware Interface (UEFI) specification for
2548  * details.
2549  */
2550 static void EFIAPI efi_copy_mem(void *destination, const void *source,
2551 				size_t length)
2552 {
2553 	EFI_ENTRY("%p, %p, %ld", destination, source, (unsigned long)length);
2554 	memmove(destination, source, length);
2555 	EFI_EXIT(EFI_SUCCESS);
2556 }
2557 
2558 /**
2559  * efi_set_mem() - Fill memory with a byte value.
2560  * @buffer: buffer to fill
2561  * @size:   size of buffer in bytes
2562  * @value:  byte to copy to the buffer
2563  *
2564  * This function implements the SetMem service.
2565  *
2566  * See the Unified Extensible Firmware Interface (UEFI) specification for
2567  * details.
2568  */
2569 static void EFIAPI efi_set_mem(void *buffer, size_t size, uint8_t value)
2570 {
2571 	EFI_ENTRY("%p, %ld, 0x%x", buffer, (unsigned long)size, value);
2572 	memset(buffer, value, size);
2573 	EFI_EXIT(EFI_SUCCESS);
2574 }
2575 
2576 /**
2577  * efi_protocol_open() - open protocol interface on a handle
2578  * @handler:            handler of a protocol
2579  * @protocol_interface: interface implementing the protocol
2580  * @agent_handle:       handle of the driver
2581  * @controller_handle:  handle of the controller
2582  * @attributes:         attributes indicating how to open the protocol
2583  *
2584  * Return: status code
2585  */
2586 static efi_status_t efi_protocol_open(
2587 			struct efi_handler *handler,
2588 			void **protocol_interface, void *agent_handle,
2589 			void *controller_handle, uint32_t attributes)
2590 {
2591 	struct efi_open_protocol_info_item *item;
2592 	struct efi_open_protocol_info_entry *match = NULL;
2593 	bool opened_by_driver = false;
2594 	bool opened_exclusive = false;
2595 
2596 	/* If there is no agent, only return the interface */
2597 	if (!agent_handle)
2598 		goto out;
2599 
2600 	/* For TEST_PROTOCOL ignore interface attribute */
2601 	if (attributes != EFI_OPEN_PROTOCOL_TEST_PROTOCOL)
2602 		*protocol_interface = NULL;
2603 
2604 	/*
2605 	 * Check if the protocol is already opened by a driver with the same
2606 	 * attributes or opened exclusively
2607 	 */
2608 	list_for_each_entry(item, &handler->open_infos, link) {
2609 		if (item->info.agent_handle == agent_handle) {
2610 			if ((attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) &&
2611 			    (item->info.attributes == attributes))
2612 				return EFI_ALREADY_STARTED;
2613 		}
2614 		if (item->info.attributes & EFI_OPEN_PROTOCOL_EXCLUSIVE)
2615 			opened_exclusive = true;
2616 	}
2617 
2618 	/* Only one controller can open the protocol exclusively */
2619 	if (opened_exclusive && attributes &
2620 	    (EFI_OPEN_PROTOCOL_EXCLUSIVE | EFI_OPEN_PROTOCOL_BY_DRIVER))
2621 		return EFI_ACCESS_DENIED;
2622 
2623 	/* Prepare exclusive opening */
2624 	if (attributes & EFI_OPEN_PROTOCOL_EXCLUSIVE) {
2625 		/* Try to disconnect controllers */
2626 		list_for_each_entry(item, &handler->open_infos, link) {
2627 			if (item->info.attributes ==
2628 					EFI_OPEN_PROTOCOL_BY_DRIVER)
2629 				EFI_CALL(efi_disconnect_controller(
2630 						item->info.controller_handle,
2631 						item->info.agent_handle,
2632 						NULL));
2633 		}
2634 		opened_by_driver = false;
2635 		/* Check if all controllers are disconnected */
2636 		list_for_each_entry(item, &handler->open_infos, link) {
2637 			if (item->info.attributes & EFI_OPEN_PROTOCOL_BY_DRIVER)
2638 				opened_by_driver = true;
2639 		}
2640 		/* Only one controller can be connected */
2641 		if (opened_by_driver)
2642 			return EFI_ACCESS_DENIED;
2643 	}
2644 
2645 	/* Find existing entry */
2646 	list_for_each_entry(item, &handler->open_infos, link) {
2647 		if (item->info.agent_handle == agent_handle &&
2648 		    item->info.controller_handle == controller_handle)
2649 			match = &item->info;
2650 	}
2651 	/* None found, create one */
2652 	if (!match) {
2653 		match = efi_create_open_info(handler);
2654 		if (!match)
2655 			return EFI_OUT_OF_RESOURCES;
2656 	}
2657 
2658 	match->agent_handle = agent_handle;
2659 	match->controller_handle = controller_handle;
2660 	match->attributes = attributes;
2661 	match->open_count++;
2662 
2663 out:
2664 	/* For TEST_PROTOCOL ignore interface attribute. */
2665 	if (attributes != EFI_OPEN_PROTOCOL_TEST_PROTOCOL)
2666 		*protocol_interface = handler->protocol_interface;
2667 
2668 	return EFI_SUCCESS;
2669 }
2670 
2671 /**
2672  * efi_open_protocol() - open protocol interface on a handle
2673  * @handle:             handle on which the protocol shall be opened
2674  * @protocol:           GUID of the protocol
2675  * @protocol_interface: interface implementing the protocol
2676  * @agent_handle:       handle of the driver
2677  * @controller_handle:  handle of the controller
2678  * @attributes:         attributes indicating how to open the protocol
2679  *
2680  * This function implements the OpenProtocol interface.
2681  *
2682  * See the Unified Extensible Firmware Interface (UEFI) specification for
2683  * details.
2684  *
2685  * Return: status code
2686  */
2687 static efi_status_t EFIAPI efi_open_protocol
2688 			(efi_handle_t handle, const efi_guid_t *protocol,
2689 			 void **protocol_interface, efi_handle_t agent_handle,
2690 			 efi_handle_t controller_handle, uint32_t attributes)
2691 {
2692 	struct efi_handler *handler;
2693 	efi_status_t r = EFI_INVALID_PARAMETER;
2694 
2695 	EFI_ENTRY("%p, %pUl, %p, %p, %p, 0x%x", handle, protocol,
2696 		  protocol_interface, agent_handle, controller_handle,
2697 		  attributes);
2698 
2699 	if (!handle || !protocol ||
2700 	    (!protocol_interface && attributes !=
2701 	     EFI_OPEN_PROTOCOL_TEST_PROTOCOL)) {
2702 		goto out;
2703 	}
2704 
2705 	switch (attributes) {
2706 	case EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL:
2707 	case EFI_OPEN_PROTOCOL_GET_PROTOCOL:
2708 	case EFI_OPEN_PROTOCOL_TEST_PROTOCOL:
2709 		break;
2710 	case EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER:
2711 		if (controller_handle == handle)
2712 			goto out;
2713 		/* fall-through */
2714 	case EFI_OPEN_PROTOCOL_BY_DRIVER:
2715 	case EFI_OPEN_PROTOCOL_BY_DRIVER | EFI_OPEN_PROTOCOL_EXCLUSIVE:
2716 		/* Check that the controller handle is valid */
2717 		if (!efi_search_obj(controller_handle))
2718 			goto out;
2719 		/* fall-through */
2720 	case EFI_OPEN_PROTOCOL_EXCLUSIVE:
2721 		/* Check that the agent handle is valid */
2722 		if (!efi_search_obj(agent_handle))
2723 			goto out;
2724 		break;
2725 	default:
2726 		goto out;
2727 	}
2728 
2729 	r = efi_search_protocol(handle, protocol, &handler);
2730 	if (r != EFI_SUCCESS)
2731 		goto out;
2732 
2733 	r = efi_protocol_open(handler, protocol_interface, agent_handle,
2734 			      controller_handle, attributes);
2735 out:
2736 	return EFI_EXIT(r);
2737 }
2738 
2739 /**
2740  * efi_handle_protocol() - get interface of a protocol on a handle
2741  * @handle:             handle on which the protocol shall be opened
2742  * @protocol:           GUID of the protocol
2743  * @protocol_interface: interface implementing the protocol
2744  *
2745  * This function implements the HandleProtocol service.
2746  *
2747  * See the Unified Extensible Firmware Interface (UEFI) specification for
2748  * details.
2749  *
2750  * Return: status code
2751  */
2752 static efi_status_t EFIAPI efi_handle_protocol(efi_handle_t handle,
2753 					       const efi_guid_t *protocol,
2754 					       void **protocol_interface)
2755 {
2756 	return efi_open_protocol(handle, protocol, protocol_interface, NULL,
2757 				 NULL, EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL);
2758 }
2759 
2760 /**
2761  * efi_bind_controller() - bind a single driver to a controller
2762  * @controller_handle:   controller handle
2763  * @driver_image_handle: driver handle
2764  * @remain_device_path:  remaining path
2765  *
2766  * Return: status code
2767  */
2768 static efi_status_t efi_bind_controller(
2769 			efi_handle_t controller_handle,
2770 			efi_handle_t driver_image_handle,
2771 			struct efi_device_path *remain_device_path)
2772 {
2773 	struct efi_driver_binding_protocol *binding_protocol;
2774 	efi_status_t r;
2775 
2776 	r = EFI_CALL(efi_open_protocol(driver_image_handle,
2777 				       &efi_guid_driver_binding_protocol,
2778 				       (void **)&binding_protocol,
2779 				       driver_image_handle, NULL,
2780 				       EFI_OPEN_PROTOCOL_GET_PROTOCOL));
2781 	if (r != EFI_SUCCESS)
2782 		return r;
2783 	r = EFI_CALL(binding_protocol->supported(binding_protocol,
2784 						 controller_handle,
2785 						 remain_device_path));
2786 	if (r == EFI_SUCCESS)
2787 		r = EFI_CALL(binding_protocol->start(binding_protocol,
2788 						     controller_handle,
2789 						     remain_device_path));
2790 	EFI_CALL(efi_close_protocol(driver_image_handle,
2791 				    &efi_guid_driver_binding_protocol,
2792 				    driver_image_handle, NULL));
2793 	return r;
2794 }
2795 
2796 /**
2797  * efi_connect_single_controller() - connect a single driver to a controller
2798  * @controller_handle:   controller
2799  * @driver_image_handle: driver
2800  * @remain_device_path:  remaining path
2801  *
2802  * Return: status code
2803  */
2804 static efi_status_t efi_connect_single_controller(
2805 			efi_handle_t controller_handle,
2806 			efi_handle_t *driver_image_handle,
2807 			struct efi_device_path *remain_device_path)
2808 {
2809 	efi_handle_t *buffer;
2810 	size_t count;
2811 	size_t i;
2812 	efi_status_t r;
2813 	size_t connected = 0;
2814 
2815 	/* Get buffer with all handles with driver binding protocol */
2816 	r = EFI_CALL(efi_locate_handle_buffer(BY_PROTOCOL,
2817 					      &efi_guid_driver_binding_protocol,
2818 					      NULL, &count, &buffer));
2819 	if (r != EFI_SUCCESS)
2820 		return r;
2821 
2822 	/*  Context Override */
2823 	if (driver_image_handle) {
2824 		for (; *driver_image_handle; ++driver_image_handle) {
2825 			for (i = 0; i < count; ++i) {
2826 				if (buffer[i] == *driver_image_handle) {
2827 					buffer[i] = NULL;
2828 					r = efi_bind_controller(
2829 							controller_handle,
2830 							*driver_image_handle,
2831 							remain_device_path);
2832 					/*
2833 					 * For drivers that do not support the
2834 					 * controller or are already connected
2835 					 * we receive an error code here.
2836 					 */
2837 					if (r == EFI_SUCCESS)
2838 						++connected;
2839 				}
2840 			}
2841 		}
2842 	}
2843 
2844 	/*
2845 	 * TODO: Some overrides are not yet implemented:
2846 	 * - Platform Driver Override
2847 	 * - Driver Family Override Search
2848 	 * - Bus Specific Driver Override
2849 	 */
2850 
2851 	/* Driver Binding Search */
2852 	for (i = 0; i < count; ++i) {
2853 		if (buffer[i]) {
2854 			r = efi_bind_controller(controller_handle,
2855 						buffer[i],
2856 						remain_device_path);
2857 			if (r == EFI_SUCCESS)
2858 				++connected;
2859 		}
2860 	}
2861 
2862 	efi_free_pool(buffer);
2863 	if (!connected)
2864 		return EFI_NOT_FOUND;
2865 	return EFI_SUCCESS;
2866 }
2867 
2868 /**
2869  * efi_connect_controller() - connect a controller to a driver
2870  * @controller_handle:   handle of the controller
2871  * @driver_image_handle: handle of the driver
2872  * @remain_device_path:  device path of a child controller
2873  * @recursive:           true to connect all child controllers
2874  *
2875  * This function implements the ConnectController service.
2876  *
2877  * See the Unified Extensible Firmware Interface (UEFI) specification for
2878  * details.
2879  *
2880  * First all driver binding protocol handles are tried for binding drivers.
2881  * Afterwards all handles that have opened a protocol of the controller
2882  * with EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER are connected to drivers.
2883  *
2884  * Return: status code
2885  */
2886 static efi_status_t EFIAPI efi_connect_controller(
2887 			efi_handle_t controller_handle,
2888 			efi_handle_t *driver_image_handle,
2889 			struct efi_device_path *remain_device_path,
2890 			bool recursive)
2891 {
2892 	efi_status_t r;
2893 	efi_status_t ret = EFI_NOT_FOUND;
2894 	struct efi_object *efiobj;
2895 
2896 	EFI_ENTRY("%p, %p, %pD, %d", controller_handle, driver_image_handle,
2897 		  remain_device_path, recursive);
2898 
2899 	efiobj = efi_search_obj(controller_handle);
2900 	if (!efiobj) {
2901 		ret = EFI_INVALID_PARAMETER;
2902 		goto out;
2903 	}
2904 
2905 	r = efi_connect_single_controller(controller_handle,
2906 					  driver_image_handle,
2907 					  remain_device_path);
2908 	if (r == EFI_SUCCESS)
2909 		ret = EFI_SUCCESS;
2910 	if (recursive) {
2911 		struct efi_handler *handler;
2912 		struct efi_open_protocol_info_item *item;
2913 
2914 		list_for_each_entry(handler, &efiobj->protocols, link) {
2915 			list_for_each_entry(item, &handler->open_infos, link) {
2916 				if (item->info.attributes &
2917 				    EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER) {
2918 					r = EFI_CALL(efi_connect_controller(
2919 						item->info.controller_handle,
2920 						driver_image_handle,
2921 						remain_device_path,
2922 						recursive));
2923 					if (r == EFI_SUCCESS)
2924 						ret = EFI_SUCCESS;
2925 				}
2926 			}
2927 		}
2928 	}
2929 	/*  Check for child controller specified by end node */
2930 	if (ret != EFI_SUCCESS && remain_device_path &&
2931 	    remain_device_path->type == DEVICE_PATH_TYPE_END)
2932 		ret = EFI_SUCCESS;
2933 out:
2934 	return EFI_EXIT(ret);
2935 }
2936 
2937 /**
2938  * efi_reinstall_protocol_interface() - reinstall protocol interface
2939  * @handle:        handle on which the protocol shall be reinstalled
2940  * @protocol:      GUID of the protocol to be installed
2941  * @old_interface: interface to be removed
2942  * @new_interface: interface to be installed
2943  *
2944  * This function implements the ReinstallProtocolInterface service.
2945  *
2946  * See the Unified Extensible Firmware Interface (UEFI) specification for
2947  * details.
2948  *
2949  * The old interface is uninstalled. The new interface is installed.
2950  * Drivers are connected.
2951  *
2952  * Return: status code
2953  */
2954 static efi_status_t EFIAPI efi_reinstall_protocol_interface(
2955 			efi_handle_t handle, const efi_guid_t *protocol,
2956 			void *old_interface, void *new_interface)
2957 {
2958 	efi_status_t ret;
2959 
2960 	EFI_ENTRY("%p, %pUl, %p, %p", handle, protocol, old_interface,
2961 		  new_interface);
2962 
2963 	/* Uninstall protocol but do not delete handle */
2964 	ret = efi_uninstall_protocol(handle, protocol, old_interface);
2965 	if (ret != EFI_SUCCESS)
2966 		goto out;
2967 
2968 	/* Install the new protocol */
2969 	ret = efi_add_protocol(handle, protocol, new_interface);
2970 	/*
2971 	 * The UEFI spec does not specify what should happen to the handle
2972 	 * if in case of an error no protocol interface remains on the handle.
2973 	 * So let's do nothing here.
2974 	 */
2975 	if (ret != EFI_SUCCESS)
2976 		goto out;
2977 	/*
2978 	 * The returned status code has to be ignored.
2979 	 * Do not create an error if no suitable driver for the handle exists.
2980 	 */
2981 	EFI_CALL(efi_connect_controller(handle, NULL, NULL, true));
2982 out:
2983 	return EFI_EXIT(ret);
2984 }
2985 
2986 /**
2987  * efi_get_child_controllers() - get all child controllers associated to a driver
2988  * @efiobj:              handle of the controller
2989  * @driver_handle:       handle of the driver
2990  * @number_of_children:  number of child controllers
2991  * @child_handle_buffer: handles of the the child controllers
2992  *
2993  * The allocated buffer has to be freed with free().
2994  *
2995  * Return: status code
2996  */
2997 static efi_status_t efi_get_child_controllers(
2998 				struct efi_object *efiobj,
2999 				efi_handle_t driver_handle,
3000 				efi_uintn_t *number_of_children,
3001 				efi_handle_t **child_handle_buffer)
3002 {
3003 	struct efi_handler *handler;
3004 	struct efi_open_protocol_info_item *item;
3005 	efi_uintn_t count = 0, i;
3006 	bool duplicate;
3007 
3008 	/* Count all child controller associations */
3009 	list_for_each_entry(handler, &efiobj->protocols, link) {
3010 		list_for_each_entry(item, &handler->open_infos, link) {
3011 			if (item->info.agent_handle == driver_handle &&
3012 			    item->info.attributes &
3013 			    EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER)
3014 				++count;
3015 		}
3016 	}
3017 	/*
3018 	 * Create buffer. In case of duplicate child controller assignments
3019 	 * the buffer will be too large. But that does not harm.
3020 	 */
3021 	*number_of_children = 0;
3022 	*child_handle_buffer = calloc(count, sizeof(efi_handle_t));
3023 	if (!*child_handle_buffer)
3024 		return EFI_OUT_OF_RESOURCES;
3025 	/* Copy unique child handles */
3026 	list_for_each_entry(handler, &efiobj->protocols, link) {
3027 		list_for_each_entry(item, &handler->open_infos, link) {
3028 			if (item->info.agent_handle == driver_handle &&
3029 			    item->info.attributes &
3030 			    EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER) {
3031 				/* Check this is a new child controller */
3032 				duplicate = false;
3033 				for (i = 0; i < *number_of_children; ++i) {
3034 					if ((*child_handle_buffer)[i] ==
3035 					    item->info.controller_handle)
3036 						duplicate = true;
3037 				}
3038 				/* Copy handle to buffer */
3039 				if (!duplicate) {
3040 					i = (*number_of_children)++;
3041 					(*child_handle_buffer)[i] =
3042 						item->info.controller_handle;
3043 				}
3044 			}
3045 		}
3046 	}
3047 	return EFI_SUCCESS;
3048 }
3049 
3050 /**
3051  * efi_disconnect_controller() - disconnect a controller from a driver
3052  * @controller_handle:   handle of the controller
3053  * @driver_image_handle: handle of the driver
3054  * @child_handle:        handle of the child to destroy
3055  *
3056  * This function implements the DisconnectController service.
3057  *
3058  * See the Unified Extensible Firmware Interface (UEFI) specification for
3059  * details.
3060  *
3061  * Return: status code
3062  */
3063 static efi_status_t EFIAPI efi_disconnect_controller(
3064 				efi_handle_t controller_handle,
3065 				efi_handle_t driver_image_handle,
3066 				efi_handle_t child_handle)
3067 {
3068 	struct efi_driver_binding_protocol *binding_protocol;
3069 	efi_handle_t *child_handle_buffer = NULL;
3070 	size_t number_of_children = 0;
3071 	efi_status_t r;
3072 	size_t stop_count = 0;
3073 	struct efi_object *efiobj;
3074 
3075 	EFI_ENTRY("%p, %p, %p", controller_handle, driver_image_handle,
3076 		  child_handle);
3077 
3078 	efiobj = efi_search_obj(controller_handle);
3079 	if (!efiobj) {
3080 		r = EFI_INVALID_PARAMETER;
3081 		goto out;
3082 	}
3083 
3084 	if (child_handle && !efi_search_obj(child_handle)) {
3085 		r = EFI_INVALID_PARAMETER;
3086 		goto out;
3087 	}
3088 
3089 	/* If no driver handle is supplied, disconnect all drivers */
3090 	if (!driver_image_handle) {
3091 		r = efi_disconnect_all_drivers(efiobj, NULL, child_handle);
3092 		goto out;
3093 	}
3094 
3095 	/* Create list of child handles */
3096 	if (child_handle) {
3097 		number_of_children = 1;
3098 		child_handle_buffer = &child_handle;
3099 	} else {
3100 		efi_get_child_controllers(efiobj,
3101 					  driver_image_handle,
3102 					  &number_of_children,
3103 					  &child_handle_buffer);
3104 	}
3105 
3106 	/* Get the driver binding protocol */
3107 	r = EFI_CALL(efi_open_protocol(driver_image_handle,
3108 				       &efi_guid_driver_binding_protocol,
3109 				       (void **)&binding_protocol,
3110 				       driver_image_handle, NULL,
3111 				       EFI_OPEN_PROTOCOL_GET_PROTOCOL));
3112 	if (r != EFI_SUCCESS)
3113 		goto out;
3114 	/* Remove the children */
3115 	if (number_of_children) {
3116 		r = EFI_CALL(binding_protocol->stop(binding_protocol,
3117 						    controller_handle,
3118 						    number_of_children,
3119 						    child_handle_buffer));
3120 		if (r == EFI_SUCCESS)
3121 			++stop_count;
3122 	}
3123 	/* Remove the driver */
3124 	if (!child_handle)
3125 		r = EFI_CALL(binding_protocol->stop(binding_protocol,
3126 						    controller_handle,
3127 						    0, NULL));
3128 	if (r == EFI_SUCCESS)
3129 		++stop_count;
3130 	EFI_CALL(efi_close_protocol(driver_image_handle,
3131 				    &efi_guid_driver_binding_protocol,
3132 				    driver_image_handle, NULL));
3133 
3134 	if (stop_count)
3135 		r = EFI_SUCCESS;
3136 	else
3137 		r = EFI_NOT_FOUND;
3138 out:
3139 	if (!child_handle)
3140 		free(child_handle_buffer);
3141 	return EFI_EXIT(r);
3142 }
3143 
3144 static struct efi_boot_services efi_boot_services = {
3145 	.hdr = {
3146 		.signature = EFI_BOOT_SERVICES_SIGNATURE,
3147 		.revision = EFI_SPECIFICATION_VERSION,
3148 		.headersize = sizeof(struct efi_boot_services),
3149 	},
3150 	.raise_tpl = efi_raise_tpl,
3151 	.restore_tpl = efi_restore_tpl,
3152 	.allocate_pages = efi_allocate_pages_ext,
3153 	.free_pages = efi_free_pages_ext,
3154 	.get_memory_map = efi_get_memory_map_ext,
3155 	.allocate_pool = efi_allocate_pool_ext,
3156 	.free_pool = efi_free_pool_ext,
3157 	.create_event = efi_create_event_ext,
3158 	.set_timer = efi_set_timer_ext,
3159 	.wait_for_event = efi_wait_for_event,
3160 	.signal_event = efi_signal_event_ext,
3161 	.close_event = efi_close_event,
3162 	.check_event = efi_check_event,
3163 	.install_protocol_interface = efi_install_protocol_interface,
3164 	.reinstall_protocol_interface = efi_reinstall_protocol_interface,
3165 	.uninstall_protocol_interface = efi_uninstall_protocol_interface,
3166 	.handle_protocol = efi_handle_protocol,
3167 	.reserved = NULL,
3168 	.register_protocol_notify = efi_register_protocol_notify,
3169 	.locate_handle = efi_locate_handle_ext,
3170 	.locate_device_path = efi_locate_device_path,
3171 	.install_configuration_table = efi_install_configuration_table_ext,
3172 	.load_image = efi_load_image,
3173 	.start_image = efi_start_image,
3174 	.exit = efi_exit,
3175 	.unload_image = efi_unload_image,
3176 	.exit_boot_services = efi_exit_boot_services,
3177 	.get_next_monotonic_count = efi_get_next_monotonic_count,
3178 	.stall = efi_stall,
3179 	.set_watchdog_timer = efi_set_watchdog_timer,
3180 	.connect_controller = efi_connect_controller,
3181 	.disconnect_controller = efi_disconnect_controller,
3182 	.open_protocol = efi_open_protocol,
3183 	.close_protocol = efi_close_protocol,
3184 	.open_protocol_information = efi_open_protocol_information,
3185 	.protocols_per_handle = efi_protocols_per_handle,
3186 	.locate_handle_buffer = efi_locate_handle_buffer,
3187 	.locate_protocol = efi_locate_protocol,
3188 	.install_multiple_protocol_interfaces =
3189 			efi_install_multiple_protocol_interfaces,
3190 	.uninstall_multiple_protocol_interfaces =
3191 			efi_uninstall_multiple_protocol_interfaces,
3192 	.calculate_crc32 = efi_calculate_crc32,
3193 	.copy_mem = efi_copy_mem,
3194 	.set_mem = efi_set_mem,
3195 	.create_event_ex = efi_create_event_ex,
3196 };
3197 
3198 static u16 __efi_runtime_data firmware_vendor[] = L"Das U-Boot";
3199 
3200 struct efi_system_table __efi_runtime_data systab = {
3201 	.hdr = {
3202 		.signature = EFI_SYSTEM_TABLE_SIGNATURE,
3203 		.revision = EFI_SPECIFICATION_VERSION,
3204 		.headersize = sizeof(struct efi_system_table),
3205 	},
3206 	.fw_vendor = firmware_vendor,
3207 	.fw_revision = FW_VERSION << 16 | FW_PATCHLEVEL << 8,
3208 	.con_in = (void *)&efi_con_in,
3209 	.con_out = (void *)&efi_con_out,
3210 	.std_err = (void *)&efi_con_out,
3211 	.runtime = (void *)&efi_runtime_services,
3212 	.boottime = (void *)&efi_boot_services,
3213 	.nr_tables = 0,
3214 	.tables = NULL,
3215 };
3216 
3217 /**
3218  * efi_initialize_system_table() - Initialize system table
3219  *
3220  * Return:	status code
3221  */
3222 efi_status_t efi_initialize_system_table(void)
3223 {
3224 	efi_status_t ret;
3225 
3226 	/* Allocate configuration table array */
3227 	ret = efi_allocate_pool(EFI_RUNTIME_SERVICES_DATA,
3228 				EFI_MAX_CONFIGURATION_TABLES *
3229 				sizeof(struct efi_configuration_table),
3230 				(void **)&systab.tables);
3231 
3232 	/* Set CRC32 field in table headers */
3233 	efi_update_table_header_crc32(&systab.hdr);
3234 	efi_update_table_header_crc32(&efi_runtime_services.hdr);
3235 	efi_update_table_header_crc32(&efi_boot_services.hdr);
3236 
3237 	return ret;
3238 }
3239