1 /*
2  * Copyright (c) 2013-2017, ARM Limited and Contributors. All rights reserved.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
7 #include <arch.h>
8 #include <arch_helpers.h>
9 #include <assert.h>
10 #include <auth_mod.h>
11 #include <bl_common.h>
12 #include <debug.h>
13 #include <errno.h>
14 #include <io_storage.h>
15 #include <platform.h>
16 #include <string.h>
17 #include <utils.h>
18 #include <xlat_tables_defs.h>
19 
page_align(uintptr_t value,unsigned dir)20 uintptr_t page_align(uintptr_t value, unsigned dir)
21 {
22 	/* Round up the limit to the next page boundary */
23 	if (value & (PAGE_SIZE - 1)) {
24 		value &= ~(PAGE_SIZE - 1);
25 		if (dir == UP)
26 			value += PAGE_SIZE;
27 	}
28 
29 	return value;
30 }
31 
32 /******************************************************************************
33  * Determine whether the memory region delimited by 'addr' and 'size' is free,
34  * given the extents of free memory.
35  * Return 1 if it is free, 0 if it is not free or if the input values are
36  * invalid.
37  *****************************************************************************/
is_mem_free(uintptr_t free_base,size_t free_size,uintptr_t addr,size_t size)38 int is_mem_free(uintptr_t free_base, size_t free_size,
39 		uintptr_t addr, size_t size)
40 {
41 	uintptr_t free_end, requested_end;
42 
43 	/*
44 	 * Handle corner cases first.
45 	 *
46 	 * The order of the 2 tests is important, because if there's no space
47 	 * left (i.e. free_size == 0) but we don't ask for any memory
48 	 * (i.e. size == 0) then we should report that the memory is free.
49 	 */
50 	if (size == 0)
51 		return 1;	/* A zero-byte region is always free */
52 	if (free_size == 0)
53 		return 0;
54 
55 	/*
56 	 * Check that the end addresses don't overflow.
57 	 * If they do, consider that this memory region is not free, as this
58 	 * is an invalid scenario.
59 	 */
60 	if (check_uptr_overflow(free_base, free_size - 1))
61 		return 0;
62 	free_end = free_base + (free_size - 1);
63 
64 	if (check_uptr_overflow(addr, size - 1))
65 		return 0;
66 	requested_end = addr + (size - 1);
67 
68 	/*
69 	 * Finally, check that the requested memory region lies within the free
70 	 * region.
71 	 */
72 	return (addr >= free_base) && (requested_end <= free_end);
73 }
74 
75 #if !LOAD_IMAGE_V2
76 /******************************************************************************
77  * Inside a given memory region, determine whether a sub-region of memory is
78  * closer from the top or the bottom of the encompassing region. Return the
79  * size of the smallest chunk of free memory surrounding the sub-region in
80  * 'small_chunk_size'.
81  *****************************************************************************/
choose_mem_pos(uintptr_t mem_start,uintptr_t mem_end,uintptr_t submem_start,uintptr_t submem_end,size_t * small_chunk_size)82 static unsigned int choose_mem_pos(uintptr_t mem_start, uintptr_t mem_end,
83 				  uintptr_t submem_start, uintptr_t submem_end,
84 				  size_t *small_chunk_size)
85 {
86 	size_t top_chunk_size, bottom_chunk_size;
87 
88 	assert(mem_start <= submem_start);
89 	assert(submem_start <= submem_end);
90 	assert(submem_end <= mem_end);
91 	assert(small_chunk_size != NULL);
92 
93 	top_chunk_size = mem_end - submem_end;
94 	bottom_chunk_size = submem_start - mem_start;
95 
96 	if (top_chunk_size < bottom_chunk_size) {
97 		*small_chunk_size = top_chunk_size;
98 		return TOP;
99 	} else {
100 		*small_chunk_size = bottom_chunk_size;
101 		return BOTTOM;
102 	}
103 }
104 
105 /******************************************************************************
106  * Reserve the memory region delimited by 'addr' and 'size'. The extents of free
107  * memory are passed in 'free_base' and 'free_size' and they will be updated to
108  * reflect the memory usage.
109  * The caller must ensure the memory to reserve is free and that the addresses
110  * and sizes passed in arguments are sane.
111  *****************************************************************************/
reserve_mem(uintptr_t * free_base,size_t * free_size,uintptr_t addr,size_t size)112 void reserve_mem(uintptr_t *free_base, size_t *free_size,
113 		 uintptr_t addr, size_t size)
114 {
115 	size_t discard_size;
116 	size_t reserved_size;
117 	unsigned int pos;
118 
119 	assert(free_base != NULL);
120 	assert(free_size != NULL);
121 	assert(is_mem_free(*free_base, *free_size, addr, size));
122 
123 	if (size == 0) {
124 		WARN("Nothing to allocate, requested size is zero\n");
125 		return;
126 	}
127 
128 	pos = choose_mem_pos(*free_base, *free_base + (*free_size - 1),
129 			     addr, addr + (size - 1),
130 			     &discard_size);
131 
132 	reserved_size = size + discard_size;
133 	*free_size -= reserved_size;
134 
135 	if (pos == BOTTOM)
136 		*free_base = addr + size;
137 
138 	VERBOSE("Reserved 0x%zx bytes (discarded 0x%zx bytes %s)\n",
139 	     reserved_size, discard_size,
140 	     pos == TOP ? "above" : "below");
141 }
142 
dump_load_info(uintptr_t image_load_addr,size_t image_size,const meminfo_t * mem_layout)143 static void dump_load_info(uintptr_t image_load_addr,
144 			   size_t image_size,
145 			   const meminfo_t *mem_layout)
146 {
147 	INFO("Trying to load image at address %p, size = 0x%zx\n",
148 		(void *)image_load_addr, image_size);
149 	INFO("Current memory layout:\n");
150 	INFO("  total region = [base = %p, size = 0x%zx]\n",
151 		(void *) mem_layout->total_base, mem_layout->total_size);
152 	INFO("  free region = [base = %p, size = 0x%zx]\n",
153 		(void *) mem_layout->free_base, mem_layout->free_size);
154 }
155 #endif /* LOAD_IMAGE_V2 */
156 
157 /* Generic function to return the size of an image */
image_size(unsigned int image_id)158 size_t image_size(unsigned int image_id)
159 {
160 	uintptr_t dev_handle;
161 	uintptr_t image_handle;
162 	uintptr_t image_spec;
163 	size_t image_size = 0;
164 	int io_result;
165 
166 	/* Obtain a reference to the image by querying the platform layer */
167 	io_result = plat_get_image_source(image_id, &dev_handle, &image_spec);
168 	if (io_result != 0) {
169 		WARN("Failed to obtain reference to image id=%u (%i)\n",
170 			image_id, io_result);
171 		return 0;
172 	}
173 
174 	/* Attempt to access the image */
175 	io_result = io_open(dev_handle, image_spec, &image_handle);
176 	if (io_result != 0) {
177 		WARN("Failed to access image id=%u (%i)\n",
178 			image_id, io_result);
179 		return 0;
180 	}
181 
182 	/* Find the size of the image */
183 	io_result = io_size(image_handle, &image_size);
184 	if ((io_result != 0) || (image_size == 0)) {
185 		WARN("Failed to determine the size of the image id=%u (%i)\n",
186 			image_id, io_result);
187 	}
188 	io_result = io_close(image_handle);
189 	/* Ignore improbable/unrecoverable error in 'close' */
190 
191 	/* TODO: Consider maintaining open device connection from this
192 	 * bootloader stage
193 	 */
194 	io_result = io_dev_close(dev_handle);
195 	/* Ignore improbable/unrecoverable error in 'dev_close' */
196 
197 	return image_size;
198 }
199 
200 #if LOAD_IMAGE_V2
201 
202 /*******************************************************************************
203  * Generic function to load an image at a specific address given
204  * an image ID and extents of free memory.
205  *
206  * If the load is successful then the image information is updated.
207  *
208  * Returns 0 on success, a negative error code otherwise.
209  ******************************************************************************/
load_image(unsigned int image_id,image_info_t * image_data)210 int load_image(unsigned int image_id, image_info_t *image_data)
211 {
212 	uintptr_t dev_handle;
213 	uintptr_t image_handle;
214 	uintptr_t image_spec;
215 	uintptr_t image_base;
216 	size_t image_size;
217 	size_t bytes_read;
218 	int io_result;
219 
220 	assert(image_data != NULL);
221 	assert(image_data->h.version >= VERSION_2);
222 
223 	image_base = image_data->image_base;
224 
225 	/* Obtain a reference to the image by querying the platform layer */
226 	io_result = plat_get_image_source(image_id, &dev_handle, &image_spec);
227 	if (io_result != 0) {
228 		WARN("Failed to obtain reference to image id=%u (%i)\n",
229 			image_id, io_result);
230 		return io_result;
231 	}
232 
233 	/* Attempt to access the image */
234 	io_result = io_open(dev_handle, image_spec, &image_handle);
235 	if (io_result != 0) {
236 		WARN("Failed to access image id=%u (%i)\n",
237 			image_id, io_result);
238 		return io_result;
239 	}
240 
241 	INFO("Loading image id=%u at address %p\n", image_id,
242 		(void *) image_base);
243 
244 	/* Find the size of the image */
245 	io_result = io_size(image_handle, &image_size);
246 	if ((io_result != 0) || (image_size == 0)) {
247 		WARN("Failed to determine the size of the image id=%u (%i)\n",
248 			image_id, io_result);
249 		goto exit;
250 	}
251 
252 	/* Check that the image size to load is within limit */
253 	if (image_size > image_data->image_max_size) {
254 		WARN("Image id=%u size out of bounds\n", image_id);
255 		io_result = -EFBIG;
256 		goto exit;
257 	}
258 
259 	image_data->image_size = image_size;
260 
261 	/* We have enough space so load the image now */
262 	/* TODO: Consider whether to try to recover/retry a partially successful read */
263 	io_result = io_read(image_handle, image_base, image_size, &bytes_read);
264 	if ((io_result != 0) || (bytes_read < image_size)) {
265 		WARN("Failed to load image id=%u (%i)\n", image_id, io_result);
266 		goto exit;
267 	}
268 
269 #if !TRUSTED_BOARD_BOOT
270 	/*
271 	 * File has been successfully loaded.
272 	 * Flush the image to main memory so that it can be executed later by
273 	 * any CPU, regardless of cache and MMU state.
274 	 * When TBB is enabled the image is flushed later, after image
275 	 * authentication.
276 	 */
277 	flush_dcache_range(image_base, image_size);
278 #endif /* TRUSTED_BOARD_BOOT */
279 
280 	INFO("Image id=%u loaded: %p - %p\n", image_id, (void *) image_base,
281 	     (void *) (image_base + image_size));
282 
283 exit:
284 	io_close(image_handle);
285 	/* Ignore improbable/unrecoverable error in 'close' */
286 
287 	/* TODO: Consider maintaining open device connection from this bootloader stage */
288 	io_dev_close(dev_handle);
289 	/* Ignore improbable/unrecoverable error in 'dev_close' */
290 
291 	return io_result;
292 }
293 
load_auth_image_internal(unsigned int image_id,image_info_t * image_data,int is_parent_image)294 static int load_auth_image_internal(unsigned int image_id,
295 				    image_info_t *image_data,
296 				    int is_parent_image)
297 {
298 	int rc;
299 
300 #if TRUSTED_BOARD_BOOT
301 	unsigned int parent_id;
302 
303 	/* Use recursion to authenticate parent images */
304 	rc = auth_mod_get_parent_id(image_id, &parent_id);
305 	if (rc == 0) {
306 		rc = load_auth_image_internal(parent_id, image_data, 1);
307 		if (rc != 0) {
308 			return rc;
309 		}
310 	}
311 #endif /* TRUSTED_BOARD_BOOT */
312 
313 	/* Load the image */
314 	rc = load_image(image_id, image_data);
315 	if (rc != 0) {
316 		return rc;
317 	}
318 
319 #if TRUSTED_BOARD_BOOT
320 	/* Authenticate it */
321 	rc = auth_mod_verify_img(image_id,
322 				 (void *)image_data->image_base,
323 				 image_data->image_size);
324 	if (rc != 0) {
325 		/* Authentication error, zero memory and flush it right away. */
326 		zero_normalmem((void *)image_data->image_base,
327 		       image_data->image_size);
328 		flush_dcache_range(image_data->image_base,
329 				   image_data->image_size);
330 		return -EAUTH;
331 	}
332 
333 	/*
334 	 * File has been successfully loaded and authenticated.
335 	 * Flush the image to main memory so that it can be executed later by
336 	 * any CPU, regardless of cache and MMU state.
337 	 * Do it only for child images, not for the parents (certificates).
338 	 */
339 	if (!is_parent_image) {
340 		flush_dcache_range(image_data->image_base,
341 				   image_data->image_size);
342 	}
343 #endif /* TRUSTED_BOARD_BOOT */
344 
345 	return 0;
346 }
347 
348 /*******************************************************************************
349  * Generic function to load and authenticate an image. The image is actually
350  * loaded by calling the 'load_image()' function. Therefore, it returns the
351  * same error codes if the loading operation failed, or -EAUTH if the
352  * authentication failed. In addition, this function uses recursion to
353  * authenticate the parent images up to the root of trust.
354  ******************************************************************************/
load_auth_image(unsigned int image_id,image_info_t * image_data)355 int load_auth_image(unsigned int image_id, image_info_t *image_data)
356 {
357 	int err;
358 
359 	do {
360 		err = load_auth_image_internal(image_id, image_data, 0);
361 	} while (err != 0 && plat_try_next_boot_source());
362 
363 	return err;
364 }
365 
366 #else /* LOAD_IMAGE_V2 */
367 
368 /*******************************************************************************
369  * Generic function to load an image at a specific address given an image ID and
370  * extents of free memory.
371  *
372  * If the load is successful then the image information is updated.
373  *
374  * If the entry_point_info argument is not NULL then this function also updates:
375  * - the memory layout to mark the memory as reserved;
376  * - the entry point information.
377  *
378  * The caller might pass a NULL pointer for the entry point if they are not
379  * interested in this information. This is typically the case for non-executable
380  * images (e.g. certificates) and executable images that won't ever be executed
381  * on the application processor (e.g. additional microcontroller firmware).
382  *
383  * Returns 0 on success, a negative error code otherwise.
384  ******************************************************************************/
load_image(meminfo_t * mem_layout,unsigned int image_id,uintptr_t image_base,image_info_t * image_data,entry_point_info_t * entry_point_info)385 int load_image(meminfo_t *mem_layout,
386 	       unsigned int image_id,
387 	       uintptr_t image_base,
388 	       image_info_t *image_data,
389 	       entry_point_info_t *entry_point_info)
390 {
391 	uintptr_t dev_handle;
392 	uintptr_t image_handle;
393 	uintptr_t image_spec;
394 	size_t image_size;
395 	size_t bytes_read;
396 	int io_result;
397 
398 	assert(mem_layout != NULL);
399 	assert(image_data != NULL);
400 	assert(image_data->h.version == VERSION_1);
401 
402 	/* Obtain a reference to the image by querying the platform layer */
403 	io_result = plat_get_image_source(image_id, &dev_handle, &image_spec);
404 	if (io_result != 0) {
405 		WARN("Failed to obtain reference to image id=%u (%i)\n",
406 			image_id, io_result);
407 		return io_result;
408 	}
409 
410 	/* Attempt to access the image */
411 	io_result = io_open(dev_handle, image_spec, &image_handle);
412 	if (io_result != 0) {
413 		WARN("Failed to access image id=%u (%i)\n",
414 			image_id, io_result);
415 		return io_result;
416 	}
417 
418 	INFO("Loading image id=%u at address %p\n", image_id,
419 		(void *) image_base);
420 
421 	/* Find the size of the image */
422 	io_result = io_size(image_handle, &image_size);
423 	if ((io_result != 0) || (image_size == 0)) {
424 		WARN("Failed to determine the size of the image id=%u (%i)\n",
425 			image_id, io_result);
426 		goto exit;
427 	}
428 
429 	/* Check that the memory where the image will be loaded is free */
430 	if (!is_mem_free(mem_layout->free_base, mem_layout->free_size,
431 			 image_base, image_size)) {
432 		WARN("Failed to reserve region [base = %p, size = 0x%zx]\n",
433 		     (void *) image_base, image_size);
434 		dump_load_info(image_base, image_size, mem_layout);
435 		io_result = -ENOMEM;
436 		goto exit;
437 	}
438 
439 	/* We have enough space so load the image now */
440 	/* TODO: Consider whether to try to recover/retry a partially successful read */
441 	io_result = io_read(image_handle, image_base, image_size, &bytes_read);
442 	if ((io_result != 0) || (bytes_read < image_size)) {
443 		WARN("Failed to load image id=%u (%i)\n", image_id, io_result);
444 		goto exit;
445 	}
446 
447 	image_data->image_base = image_base;
448 	image_data->image_size = image_size;
449 
450 	/*
451 	 * Update the memory usage info.
452 	 * This is done after the actual loading so that it is not updated when
453 	 * the load is unsuccessful.
454 	 * If the caller does not provide an entry point, bypass the memory
455 	 * reservation.
456 	 */
457 	if (entry_point_info != NULL) {
458 		reserve_mem(&mem_layout->free_base, &mem_layout->free_size,
459 				image_base, image_size);
460 		entry_point_info->pc = image_base;
461 	} else {
462 		INFO("Skip reserving region [base = %p, size = 0x%zx]\n",
463 		     (void *) image_base, image_size);
464 	}
465 
466 #if !TRUSTED_BOARD_BOOT
467 	/*
468 	 * File has been successfully loaded.
469 	 * Flush the image to main memory so that it can be executed later by
470 	 * any CPU, regardless of cache and MMU state.
471 	 * When TBB is enabled the image is flushed later, after image
472 	 * authentication.
473 	 */
474 	flush_dcache_range(image_base, image_size);
475 #endif /* TRUSTED_BOARD_BOOT */
476 
477 	INFO("Image id=%u loaded at address %p, size = 0x%zx\n", image_id,
478 		(void *) image_base, image_size);
479 
480 exit:
481 	io_close(image_handle);
482 	/* Ignore improbable/unrecoverable error in 'close' */
483 
484 	/* TODO: Consider maintaining open device connection from this bootloader stage */
485 	io_dev_close(dev_handle);
486 	/* Ignore improbable/unrecoverable error in 'dev_close' */
487 
488 	return io_result;
489 }
490 
load_auth_image_internal(meminfo_t * mem_layout,unsigned int image_id,uintptr_t image_base,image_info_t * image_data,entry_point_info_t * entry_point_info,int is_parent_image)491 static int load_auth_image_internal(meminfo_t *mem_layout,
492 				    unsigned int image_id,
493 				    uintptr_t image_base,
494 				    image_info_t *image_data,
495 				    entry_point_info_t *entry_point_info,
496 				    int is_parent_image)
497 {
498 	int rc;
499 
500 #if TRUSTED_BOARD_BOOT
501 	unsigned int parent_id;
502 
503 	/* Use recursion to authenticate parent images */
504 	rc = auth_mod_get_parent_id(image_id, &parent_id);
505 	if (rc == 0) {
506 		rc = load_auth_image_internal(mem_layout, parent_id, image_base,
507 				     image_data, NULL, 1);
508 		if (rc != 0) {
509 			return rc;
510 		}
511 	}
512 #endif /* TRUSTED_BOARD_BOOT */
513 
514 	/* Load the image */
515 	rc = load_image(mem_layout, image_id, image_base, image_data,
516 			entry_point_info);
517 	if (rc != 0) {
518 		return rc;
519 	}
520 
521 #if TRUSTED_BOARD_BOOT
522 	/* Authenticate it */
523 	rc = auth_mod_verify_img(image_id,
524 				 (void *)image_data->image_base,
525 				 image_data->image_size);
526 	if (rc != 0) {
527 		/* Authentication error, zero memory and flush it right away. */
528 		zero_normalmem((void *)image_data->image_base,
529 		       image_data->image_size);
530 		flush_dcache_range(image_data->image_base,
531 				   image_data->image_size);
532 		return -EAUTH;
533 	}
534 	/*
535 	 * File has been successfully loaded and authenticated.
536 	 * Flush the image to main memory so that it can be executed later by
537 	 * any CPU, regardless of cache and MMU state.
538 	 * Do it only for child images, not for the parents (certificates).
539 	 */
540 	if (!is_parent_image) {
541 		flush_dcache_range(image_data->image_base,
542 				   image_data->image_size);
543 	}
544 #endif /* TRUSTED_BOARD_BOOT */
545 
546 	return 0;
547 }
548 
549 /*******************************************************************************
550  * Generic function to load and authenticate an image. The image is actually
551  * loaded by calling the 'load_image()' function. Therefore, it returns the
552  * same error codes if the loading operation failed, or -EAUTH if the
553  * authentication failed. In addition, this function uses recursion to
554  * authenticate the parent images up to the root of trust.
555  ******************************************************************************/
load_auth_image(meminfo_t * mem_layout,unsigned int image_id,uintptr_t image_base,image_info_t * image_data,entry_point_info_t * entry_point_info)556 int load_auth_image(meminfo_t *mem_layout,
557 		    unsigned int image_id,
558 		    uintptr_t image_base,
559 		    image_info_t *image_data,
560 		    entry_point_info_t *entry_point_info)
561 {
562 	int err;
563 
564 	do {
565 		err = load_auth_image_internal(mem_layout, image_id, image_base,
566 					       image_data, entry_point_info, 0);
567 	} while (err != 0 && plat_try_next_boot_source());
568 
569 	return err;
570 }
571 
572 #endif /* LOAD_IMAGE_V2 */
573 
574 /*******************************************************************************
575  * Print the content of an entry_point_info_t structure.
576  ******************************************************************************/
print_entry_point_info(const entry_point_info_t * ep_info)577 void print_entry_point_info(const entry_point_info_t *ep_info)
578 {
579 	INFO("Entry point address = %p\n", (void *)ep_info->pc);
580 	INFO("SPSR = 0x%x\n", ep_info->spsr);
581 
582 #define PRINT_IMAGE_ARG(n)					\
583 	VERBOSE("Argument #" #n " = 0x%llx\n",			\
584 		(unsigned long long) ep_info->args.arg##n)
585 
586 	PRINT_IMAGE_ARG(0);
587 	PRINT_IMAGE_ARG(1);
588 	PRINT_IMAGE_ARG(2);
589 	PRINT_IMAGE_ARG(3);
590 #ifndef AARCH32
591 	PRINT_IMAGE_ARG(4);
592 	PRINT_IMAGE_ARG(5);
593 	PRINT_IMAGE_ARG(6);
594 	PRINT_IMAGE_ARG(7);
595 #endif
596 #undef PRINT_IMAGE_ARG
597 }
598