1 /*
2  * Copyright (c) 2018 Intel Corporation.
3  * Copyright (c) 2022, NXP
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include <zephyr/kernel.h>
9 #include <zephyr/sys/printk.h>
10 #include <zephyr/ztest.h>
11 
12 /* This function will allow execute from sram region.
13  * This is needed only for this sample because by default all soc will
14  * disable the execute from SRAM.
15  * An application that requires that the code be executed from SRAM will
16  *  have to configure the region appropriately in arm_mpu_regions.c.
17  */
18 
19 #if (defined(CONFIG_ARM_MPU) && !defined(CONFIG_CPU_HAS_NXP_SYSMPU))
20 #include <cmsis_core.h>
disable_mpu_rasr_xn(void)21 void disable_mpu_rasr_xn(void)
22 {
23 	uint32_t index;
24 	/* Kept the max index as 8(irrespective of soc) because the sram
25 	 * would most likely be set at index 2.
26 	 */
27 	for (index = 0U; index < 8; index++) {
28 		MPU->RNR = index;
29 #if defined(CONFIG_ARMV8_M_BASELINE) || defined(CONFIG_ARMV8_M_MAINLINE)
30 		if (MPU->RBAR & MPU_RBAR_XN_Msk) {
31 			MPU->RBAR ^= MPU_RBAR_XN_Msk;
32 		}
33 #else
34 		if (MPU->RASR & MPU_RASR_XN_Msk) {
35 			MPU->RASR ^= MPU_RASR_XN_Msk;
36 		}
37 #endif /* CONFIG_ARMV8_M_BASELINE || CONFIG_ARMV8_M_MAINLINE */
38 	}
39 
40 }
41 #endif	/* CONFIG_ARM_MPU */
42 
43 /* override the default memcpy as zephyr will call this before relocation happens */
44 __boot_func
z_early_memcpy(void * dst,const void * src,size_t n)45 void  z_early_memcpy(void *dst, const void *src, size_t n)
46 {
47 	/* attempt word-sized copying only if buffers have identical alignment */
48 	unsigned char *d_byte = (unsigned char *)dst;
49 	const unsigned char *s_byte = (const unsigned char *)src;
50 	/* do byte-sized copying until finished */
51 
52 	while (n > 0) {
53 		*(d_byte++) = *(s_byte++);
54 		n--;
55 	}
56 }
57 
58 __boot_func
z_early_memset(void * dst,int c,size_t n)59 void z_early_memset(void *dst, int c, size_t n)
60 {
61 	/* do byte-sized initialization until word-aligned or finished */
62 
63 	unsigned char *d_byte = (unsigned char *)dst;
64 	unsigned char c_byte = (unsigned char)c;
65 
66 	while (n > 0) {
67 		*(d_byte++) = c_byte;
68 		n--;
69 	}
70 }
71 
relocate_code_setup(void)72 void *relocate_code_setup(void)
73 {
74 #if (defined(CONFIG_ARM_MPU) && !defined(CONFIG_CPU_HAS_NXP_SYSMPU))
75 	disable_mpu_rasr_xn();
76 #endif	/* CONFIG_ARM_MPU */
77 	return NULL;
78 }
79 
80 ZTEST_SUITE(code_relocation, NULL, relocate_code_setup, NULL, NULL, NULL);
81