xref: /rk3399_ARM-atf/common/bl_common.c (revision b3254e8547707ff57ed7766aba53933884bd6a1c)
1 /*
2  * Copyright (c) 2013-2014, ARM Limited and Contributors. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are met:
6  *
7  * Redistributions of source code must retain the above copyright notice, this
8  * list of conditions and the following disclaimer.
9  *
10  * Redistributions in binary form must reproduce the above copyright notice,
11  * this list of conditions and the following disclaimer in the documentation
12  * and/or other materials provided with the distribution.
13  *
14  * Neither the name of ARM nor the names of its contributors may be used
15  * to endorse or promote products derived from this software without specific
16  * prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
22  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 #include <arch.h>
32 #include <arch_helpers.h>
33 #include <assert.h>
34 #include <bl_common.h>
35 #include <debug.h>
36 #include <io_storage.h>
37 #include <platform.h>
38 #include <stdio.h>
39 
40 unsigned long page_align(unsigned long value, unsigned dir)
41 {
42 	unsigned long page_size = 1 << FOUR_KB_SHIFT;
43 
44 	/* Round up the limit to the next page boundary */
45 	if (value & (page_size - 1)) {
46 		value &= ~(page_size - 1);
47 		if (dir == UP)
48 			value += page_size;
49 	}
50 
51 	return value;
52 }
53 
54 static inline unsigned int is_page_aligned (unsigned long addr) {
55 	const unsigned long page_size = 1 << FOUR_KB_SHIFT;
56 
57 	return (addr & (page_size - 1)) == 0;
58 }
59 
60 void change_security_state(unsigned int target_security_state)
61 {
62 	unsigned long scr = read_scr();
63 
64 	if (target_security_state == SECURE)
65 		scr &= ~SCR_NS_BIT;
66 	else if (target_security_state == NON_SECURE)
67 		scr |= SCR_NS_BIT;
68 	else
69 		assert(0);
70 
71 	write_scr(scr);
72 }
73 
74 void __dead2 drop_el(aapcs64_params_t *args,
75 		     unsigned long spsr,
76 		     unsigned long entrypoint)
77 {
78 	write_spsr_el3(spsr);
79 	write_elr_el3(entrypoint);
80 	eret(args->arg0,
81 	     args->arg1,
82 	     args->arg2,
83 	     args->arg3,
84 	     args->arg4,
85 	     args->arg5,
86 	     args->arg6,
87 	     args->arg7);
88 }
89 
90 void __dead2 raise_el(aapcs64_params_t *args)
91 {
92 	smc(args->arg0,
93 	    args->arg1,
94 	    args->arg2,
95 	    args->arg3,
96 	    args->arg4,
97 	    args->arg5,
98 	    args->arg6,
99 	    args->arg7);
100 }
101 
102 /*
103  * TODO: If we are not EL3 then currently we only issue an SMC.
104  * Add support for dropping into EL0 etc. Consider adding support
105  * for switching from S-EL1 to S-EL0/1 etc.
106  */
107 void __dead2 change_el(el_change_info_t *info)
108 {
109 	if (IS_IN_EL3()) {
110 		/*
111 		 * We can go anywhere from EL3. So find where.
112 		 * TODO: Lots to do if we are going non-secure.
113 		 * Flip the NS bit. Restore NS registers etc.
114 		 * Just doing the bare minimal for now.
115 		 */
116 
117 		if (info->security_state == NON_SECURE)
118 			change_security_state(info->security_state);
119 
120 		drop_el(&info->args, info->spsr, info->entrypoint);
121 	} else
122 		raise_el(&info->args);
123 }
124 
125 /* TODO: add a parameter for DAIF. not needed right now */
126 unsigned long make_spsr(unsigned long target_el,
127 			unsigned long target_sp,
128 			unsigned long target_rw)
129 {
130 	unsigned long spsr;
131 
132 	/* Disable all exceptions & setup the EL */
133 	spsr = (DAIF_FIQ_BIT | DAIF_IRQ_BIT | DAIF_ABT_BIT | DAIF_DBG_BIT)
134 		<< PSR_DAIF_SHIFT;
135 	spsr |= PSR_MODE(target_rw, target_el, target_sp);
136 
137 	return spsr;
138 }
139 
140 /*******************************************************************************
141  * The next two functions are the weak definitions. Platform specific
142  * code can override them if it wishes to.
143  ******************************************************************************/
144 
145 /*******************************************************************************
146  * Function that takes a memory layout into which BL31 has been either top or
147  * bottom loaded. Using this information, it populates bl31_mem_layout to tell
148  * BL31 how much memory it has access to and how much is available for use. It
149  * does not need the address where BL31 has been loaded as BL31 will reclaim
150  * all the memory used by BL2.
151  * TODO: Revisit if this and init_bl2_mem_layout can be replaced by a single
152  * routine.
153  ******************************************************************************/
154 void init_bl31_mem_layout(const meminfo_t *bl2_mem_layout,
155 			  meminfo_t *bl31_mem_layout,
156 			  unsigned int load_type)
157 {
158 	if (load_type == BOT_LOAD) {
159 		/*
160 		 * ------------                             ^
161 		 * |   BL2    |                             |
162 		 * |----------|                 ^           |  BL2
163 		 * |          |                 | BL2 free  |  total
164 		 * |          |                 |   size    |  size
165 		 * |----------| BL2 free base   v           |
166 		 * |   BL31   |                             |
167 		 * ------------ BL2 total base              v
168 		 */
169 		unsigned long bl31_size;
170 
171 		bl31_mem_layout->free_base = bl2_mem_layout->free_base;
172 
173 		bl31_size = bl2_mem_layout->free_base - bl2_mem_layout->total_base;
174 		bl31_mem_layout->free_size = bl2_mem_layout->total_size - bl31_size;
175 	} else {
176 		/*
177 		 * ------------                             ^
178 		 * |   BL31   |                             |
179 		 * |----------|                 ^           |  BL2
180 		 * |          |                 | BL2 free  |  total
181 		 * |          |                 |   size    |  size
182 		 * |----------| BL2 free base   v           |
183 		 * |   BL2    |                             |
184 		 * ------------ BL2 total base              v
185 		 */
186 		unsigned long bl2_size;
187 
188 		bl31_mem_layout->free_base = bl2_mem_layout->total_base;
189 
190 		bl2_size = bl2_mem_layout->free_base - bl2_mem_layout->total_base;
191 		bl31_mem_layout->free_size = bl2_mem_layout->free_size + bl2_size;
192 	}
193 
194 	bl31_mem_layout->total_base = bl2_mem_layout->total_base;
195 	bl31_mem_layout->total_size = bl2_mem_layout->total_size;
196 	bl31_mem_layout->attr = load_type;
197 
198 	flush_dcache_range((unsigned long) bl31_mem_layout, sizeof(meminfo_t));
199 	return;
200 }
201 
202 /*******************************************************************************
203  * Function that takes a memory layout into which BL2 has been either top or
204  * bottom loaded along with the address where BL2 has been loaded in it. Using
205  * this information, it populates bl2_mem_layout to tell BL2 how much memory
206  * it has access to and how much is available for use.
207  ******************************************************************************/
208 void init_bl2_mem_layout(meminfo_t *bl1_mem_layout,
209 			 meminfo_t *bl2_mem_layout,
210 			 unsigned int load_type,
211 			 unsigned long bl2_base)
212 {
213 	unsigned tmp;
214 
215 	if (load_type == BOT_LOAD) {
216 		bl2_mem_layout->total_base = bl2_base;
217 		tmp = bl1_mem_layout->free_base - bl2_base;
218 		bl2_mem_layout->total_size = bl1_mem_layout->free_size + tmp;
219 
220 	} else {
221 		bl2_mem_layout->total_base = bl1_mem_layout->free_base;
222 		tmp = bl1_mem_layout->total_base + bl1_mem_layout->total_size;
223 		bl2_mem_layout->total_size = tmp - bl1_mem_layout->free_base;
224 	}
225 
226 	bl2_mem_layout->free_base = bl1_mem_layout->free_base;
227 	bl2_mem_layout->free_size = bl1_mem_layout->free_size;
228 	bl2_mem_layout->attr = load_type;
229 
230 	flush_dcache_range((unsigned long) bl2_mem_layout, sizeof(meminfo_t));
231 	return;
232 }
233 
234 static void dump_load_info(unsigned long image_load_addr,
235 			   unsigned long image_size,
236 			   const meminfo_t *mem_layout)
237 {
238 #if DEBUG
239 	printf("Trying to load image at address 0x%lx, size = 0x%lx\r\n",
240 		image_load_addr, image_size);
241 	printf("Current memory layout:\r\n");
242 	printf("  total region = [0x%lx, 0x%lx]\r\n", mem_layout->total_base,
243 			mem_layout->total_base + mem_layout->total_size);
244 	printf("  free region = [0x%lx, 0x%lx]\r\n", mem_layout->free_base,
245 			mem_layout->free_base + mem_layout->free_size);
246 #endif
247 }
248 
249 /* Generic function to return the size of an image */
250 unsigned long image_size(const char *image_name)
251 {
252 	uintptr_t dev_handle;
253 	uintptr_t image_handle;
254 	uintptr_t image_spec;
255 	size_t image_size = 0;
256 	int io_result = IO_FAIL;
257 
258 	assert(image_name != NULL);
259 
260 	/* Obtain a reference to the image by querying the platform layer */
261 	io_result = plat_get_image_source(image_name, &dev_handle, &image_spec);
262 	if (io_result != IO_SUCCESS) {
263 		WARN("Failed to obtain reference to image '%s' (%i)\n",
264 			image_name, io_result);
265 		return 0;
266 	}
267 
268 	/* Attempt to access the image */
269 	io_result = io_open(dev_handle, image_spec, &image_handle);
270 	if (io_result != IO_SUCCESS) {
271 		WARN("Failed to access image '%s' (%i)\n",
272 			image_name, io_result);
273 		return 0;
274 	}
275 
276 	/* Find the size of the image */
277 	io_result = io_size(image_handle, &image_size);
278 	if ((io_result != IO_SUCCESS) || (image_size == 0)) {
279 		WARN("Failed to determine the size of the image '%s' file (%i)\n",
280 			image_name, io_result);
281 	}
282 	io_result = io_close(image_handle);
283 	/* Ignore improbable/unrecoverable error in 'close' */
284 
285 	/* TODO: Consider maintaining open device connection from this
286 	 * bootloader stage
287 	 */
288 	io_result = io_dev_close(dev_handle);
289 	/* Ignore improbable/unrecoverable error in 'dev_close' */
290 
291 	return image_size;
292 }
293 /*******************************************************************************
294  * Generic function to load an image into the trusted RAM,
295  * given a name, extents of free memory & whether the image should be loaded at
296  * the bottom or top of the free memory. It updates the memory layout if the
297  * load is successful.
298  ******************************************************************************/
299 unsigned long load_image(meminfo_t *mem_layout,
300 			 const char *image_name,
301 			 unsigned int load_type,
302 			 unsigned long fixed_addr)
303 {
304 	uintptr_t dev_handle;
305 	uintptr_t image_handle;
306 	uintptr_t image_spec;
307 	unsigned long temp_image_base = 0;
308 	unsigned long image_base = 0;
309 	long offset = 0;
310 	size_t image_size = 0;
311 	size_t bytes_read = 0;
312 	int io_result = IO_FAIL;
313 
314 	assert(mem_layout != NULL);
315 	assert(image_name != NULL);
316 
317 	/* Obtain a reference to the image by querying the platform layer */
318 	io_result = plat_get_image_source(image_name, &dev_handle, &image_spec);
319 	if (io_result != IO_SUCCESS) {
320 		WARN("Failed to obtain reference to image '%s' (%i)\n",
321 			image_name, io_result);
322 		return 0;
323 	}
324 
325 	/* Attempt to access the image */
326 	io_result = io_open(dev_handle, image_spec, &image_handle);
327 	if (io_result != IO_SUCCESS) {
328 		WARN("Failed to access image '%s' (%i)\n",
329 			image_name, io_result);
330 		return 0;
331 	}
332 
333 	/* Find the size of the image */
334 	io_result = io_size(image_handle, &image_size);
335 	if ((io_result != IO_SUCCESS) || (image_size == 0)) {
336 		WARN("Failed to determine the size of the image '%s' file (%i)\n",
337 			image_name, io_result);
338 		goto fail;
339 	}
340 
341 	/* See if we have enough space */
342 	if (image_size > mem_layout->free_size) {
343 		WARN("Cannot load '%s' file: Not enough space.\n",
344 			image_name);
345 		dump_load_info(0, image_size, mem_layout);
346 		goto fail;
347 	}
348 
349 	switch (load_type) {
350 
351 	case TOP_LOAD:
352 
353 	  /* Load the image in the top of free memory */
354 	  temp_image_base = mem_layout->free_base + mem_layout->free_size;
355 	  temp_image_base -= image_size;
356 
357 	  /* Page align base address and check whether the image still fits */
358 	  image_base = page_align(temp_image_base, DOWN);
359 	  assert(image_base <= temp_image_base);
360 
361 	  if (image_base < mem_layout->free_base) {
362 		WARN("Cannot load '%s' file: Not enough space.\n",
363 			image_name);
364 		dump_load_info(image_base, image_size, mem_layout);
365 		goto fail;
366 	  }
367 
368 	  /* Calculate the amount of extra memory used due to alignment */
369 	  offset = temp_image_base - image_base;
370 
371 	  break;
372 
373 	case BOT_LOAD:
374 
375 	  /* Load the BL2 image in the bottom of free memory */
376 	  temp_image_base = mem_layout->free_base;
377 	  image_base = page_align(temp_image_base, UP);
378 	  assert(image_base >= temp_image_base);
379 
380 	  /* Page align base address and check whether the image still fits */
381 	  if (image_base + image_size >
382 	      mem_layout->free_base + mem_layout->free_size) {
383 		  WARN("Cannot load '%s' file: Not enough space.\n",
384 			  image_name);
385 		  dump_load_info(image_base, image_size, mem_layout);
386 		  goto fail;
387 	  }
388 
389 	  /* Calculate the amount of extra memory used due to alignment */
390 	  offset = image_base - temp_image_base;
391 
392 	  break;
393 
394 	default:
395 	  assert(0);
396 
397 	}
398 
399 	/*
400 	 * Some images must be loaded at a fixed address, not a dynamic one.
401 	 *
402 	 * This has been implemented as a hack on top of the existing dynamic
403 	 * loading mechanism, for the time being.  If the 'fixed_addr' function
404 	 * argument is different from zero, then it will force the load address.
405 	 * So we still have this principle of top/bottom loading but the code
406 	 * determining the load address is bypassed and the load address is
407 	 * forced to the fixed one.
408 	 *
409 	 * This can result in quite a lot of wasted space because we still use
410 	 * 1 sole meminfo structure to represent the extents of free memory,
411 	 * where we should use some sort of linked list.
412 	 *
413 	 * E.g. we want to load BL2 at address 0x04020000, the resulting memory
414 	 *      layout should look as follows:
415 	 * ------------ 0x04040000
416 	 * |          |  <- Free space (1)
417 	 * |----------|
418 	 * |   BL2    |
419 	 * |----------| 0x04020000
420 	 * |          |  <- Free space (2)
421 	 * |----------|
422 	 * |   BL1    |
423 	 * ------------ 0x04000000
424 	 *
425 	 * But in the current hacky implementation, we'll need to specify
426 	 * whether BL2 is loaded at the top or bottom of the free memory.
427 	 * E.g. if BL2 is considered as top-loaded, the meminfo structure
428 	 * will give the following view of the memory, hiding the chunk of
429 	 * free memory above BL2:
430 	 * ------------ 0x04040000
431 	 * |          |
432 	 * |          |
433 	 * |   BL2    |
434 	 * |----------| 0x04020000
435 	 * |          |  <- Free space (2)
436 	 * |----------|
437 	 * |   BL1    |
438 	 * ------------ 0x04000000
439 	 */
440 	if (fixed_addr != 0) {
441 		/* Load the image at the given address. */
442 		image_base = fixed_addr;
443 
444 		/* Check whether the image fits. */
445 		if ((image_base < mem_layout->free_base) ||
446 		    (image_base + image_size >
447 		       mem_layout->free_base + mem_layout->free_size)) {
448 			WARN("Cannot load '%s' file: Not enough space.\n",
449 				image_name);
450 			dump_load_info(image_base, image_size, mem_layout);
451 			goto fail;
452 		}
453 
454 		/* Check whether the fixed load address is page-aligned. */
455 		if (!is_page_aligned(image_base)) {
456 			WARN("Cannot load '%s' file at unaligned address 0x%lx\n",
457 				image_name, fixed_addr);
458 			goto fail;
459 		}
460 
461 		/*
462 		 * Calculate the amount of extra memory used due to fixed
463 		 * loading.
464 		 */
465 		if (load_type == TOP_LOAD) {
466 			unsigned long max_addr, space_used;
467 			/*
468 			 * ------------ max_addr
469 			 * | /wasted/ |                 | offset
470 			 * |..........|..............................
471 			 * |  image   |                 | image_flen
472 			 * |----------| fixed_addr
473 			 * |          |
474 			 * |          |
475 			 * ------------ total_base
476 			 */
477 			max_addr = mem_layout->total_base + mem_layout->total_size;
478 			/*
479 			 * Compute the amount of memory used by the image.
480 			 * Corresponds to all space above the image load
481 			 * address.
482 			 */
483 			space_used = max_addr - fixed_addr;
484 			/*
485 			 * Calculate the amount of wasted memory within the
486 			 * amount of memory used by the image.
487 			 */
488 			offset = space_used - image_size;
489 		} else /* BOT_LOAD */
490 			/*
491 			 * ------------
492 			 * |          |
493 			 * |          |
494 			 * |----------|
495 			 * |  image   |
496 			 * |..........| fixed_addr
497 			 * | /wasted/ |                 | offset
498 			 * ------------ total_base
499 			 */
500 			offset = fixed_addr - mem_layout->total_base;
501 	}
502 
503 	/* We have enough space so load the image now */
504 	/* TODO: Consider whether to try to recover/retry a partially successful read */
505 	io_result = io_read(image_handle, image_base, image_size, &bytes_read);
506 	if ((io_result != IO_SUCCESS) || (bytes_read < image_size)) {
507 		WARN("Failed to load '%s' file (%i)\n", image_name, io_result);
508 		goto fail;
509 	}
510 
511 	/*
512 	 * File has been successfully loaded. Update the free memory
513 	 * data structure & flush the contents of the TZRAM so that
514 	 * the next EL can see it.
515 	 */
516 	/* Update the memory contents */
517 	flush_dcache_range(image_base, image_size);
518 
519 	mem_layout->free_size -= image_size + offset;
520 
521 	/* Update the base of free memory since its moved up */
522 	if (load_type == BOT_LOAD)
523 		mem_layout->free_base += offset + image_size;
524 
525 exit:
526 	io_result = io_close(image_handle);
527 	/* Ignore improbable/unrecoverable error in 'close' */
528 
529 	/* TODO: Consider maintaining open device connection from this bootloader stage */
530 	io_result = io_dev_close(dev_handle);
531 	/* Ignore improbable/unrecoverable error in 'dev_close' */
532 
533 	return image_base;
534 
535 fail:	image_base = 0;
536 	goto exit;
537 }
538 
539 /*******************************************************************************
540  * Run a loaded image from the given entry point. This could result in either
541  * dropping into a lower exception level or jumping to a higher exception level.
542  * The only way of doing the latter is through an SMC. In either case, setup the
543  * parameters for the EL change request correctly.
544  ******************************************************************************/
545 void __dead2 run_image(unsigned long entrypoint,
546 		       unsigned long spsr,
547 		       unsigned long target_security_state,
548 		       void *first_arg,
549 		       void *second_arg)
550 {
551 	el_change_info_t run_image_info;
552 
553 	/* Tell next EL what we want done */
554 	run_image_info.args.arg0 = RUN_IMAGE;
555 	run_image_info.entrypoint = entrypoint;
556 	run_image_info.spsr = spsr;
557 	run_image_info.security_state = target_security_state;
558 
559 	/*
560 	 * If we are EL3 then only an eret can take us to the desired
561 	 * exception level. Else for the time being assume that we have
562 	 * to jump to a higher EL and issue an SMC. Contents of argY
563 	 * will go into the general purpose register xY e.g. arg0->x0
564 	 */
565 	if (IS_IN_EL3()) {
566 		run_image_info.args.arg1 = (unsigned long) first_arg;
567 		run_image_info.args.arg2 = (unsigned long) second_arg;
568 	} else {
569 		run_image_info.args.arg1 = entrypoint;
570 		run_image_info.args.arg2 = spsr;
571 		run_image_info.args.arg3 = (unsigned long) first_arg;
572 		run_image_info.args.arg4 = (unsigned long) second_arg;
573 	}
574 
575 	change_el(&run_image_info);
576 }
577