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