1 /*
2  * Copyright (c) 2024 Espressif Systems (Shanghai) Co., Ltd.
3  * SPDX-License-Identifier: Apache-2.0
4  */
5 
6 #include <string.h>
7 #include <zephyr/kernel.h>
8 #include <rom/ets_sys.h>
9 #include <esp_psram.h>
10 #include <esp_private/esp_psram_extram.h>
11 #include <zephyr/multi_heap/shared_multi_heap.h>
12 
13 #define PSRAM_ADDR (DT_REG_ADDR(DT_NODELABEL(psram0)))
14 
15 extern int _spiram_heap_start;
16 extern int _ext_ram_bss_start;
17 extern int _ext_ram_bss_end;
18 
19 struct shared_multi_heap_region smh_psram = {
20 	.addr = (uintptr_t)&_spiram_heap_start,
21 	.size = CONFIG_ESP_SPIRAM_SIZE,
22 	.attr = SMH_REG_ATTR_EXTERNAL,
23 };
24 
esp_psram_smh_init(void)25 int esp_psram_smh_init(void)
26 {
27 	shared_multi_heap_pool_init();
28 	smh_psram.size = CONFIG_ESP_SPIRAM_SIZE - ((int)&_spiram_heap_start - PSRAM_ADDR);
29 	return shared_multi_heap_add(&smh_psram, NULL);
30 }
31 
esp_init_psram(void)32 void esp_init_psram(void)
33 {
34 	if (esp_psram_init()) {
35 		ets_printf("Failed to Initialize external RAM, aborting.\n");
36 		return;
37 	}
38 
39 	if (esp_psram_get_size() < CONFIG_ESP_SPIRAM_SIZE) {
40 		ets_printf("External RAM size is less than configured.\n");
41 	}
42 
43 	if (IS_ENABLED(CONFIG_ESP_SPIRAM_MEMTEST)) {
44 		if (esp_psram_is_initialized()) {
45 			if (!esp_psram_extram_test()) {
46 				ets_printf("External RAM failed memory test!");
47 				return;
48 			}
49 		}
50 	}
51 
52 	memset(&_ext_ram_bss_start, 0,
53 	       (&_ext_ram_bss_end - &_ext_ram_bss_start) * sizeof(_ext_ram_bss_start));
54 }
55