1 /*
2  * SPDX-FileCopyrightText: 2023 Espressif Systems (Shanghai) CO LTD
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <sys/param.h>
8 #include <inttypes.h>
9 #include "sdkconfig.h"
10 #include "esp_check.h"
11 #include "esp_log.h"
12 #include "soc/soc_caps.h"
13 #include "hal/mmu_hal.h"
14 #include "hal/cache_hal.h"
15 #include "esp_cache.h"
16 #include "esp_private/critical_section.h"
17 
18 
19 static const char *TAG = "cache";
20 
21 #if SOC_CACHE_WRITEBACK_SUPPORTED
22 DEFINE_CRIT_SECTION_LOCK_STATIC(s_spinlock);
23 
s_cache_freeze(void)24 void s_cache_freeze(void)
25 {
26 #if SOC_CACHE_FREEZE_SUPPORTED
27     cache_hal_freeze(CACHE_TYPE_DATA | CACHE_TYPE_INSTRUCTION);
28 #endif
29 
30     /**
31      * For writeback supported, but the freeze not supported chip (Now only S2),
32      * as it's single core, the critical section is enough to prevent preemption from an non-IRAM ISR
33      */
34 }
35 
s_cache_unfreeze(void)36 void s_cache_unfreeze(void)
37 {
38 #if SOC_CACHE_FREEZE_SUPPORTED
39     cache_hal_unfreeze(CACHE_TYPE_DATA | CACHE_TYPE_INSTRUCTION);
40 #endif
41 
42     /**
43      * Similarly, for writeback supported, but the freeze not supported chip (Now only S2),
44      * we don't need to do more
45      */
46 }
47 #endif  //#if SOC_CACHE_WRITEBACK_SUPPORTED
48 
49 
esp_cache_msync(void * addr,size_t size,int flags)50 esp_err_t esp_cache_msync(void *addr, size_t size, int flags)
51 {
52     ESP_RETURN_ON_FALSE_ISR(addr, ESP_ERR_INVALID_ARG, TAG, "null pointer");
53     ESP_RETURN_ON_FALSE_ISR(mmu_hal_check_valid_ext_vaddr_region(0, (uint32_t)addr, size, MMU_VADDR_DATA), ESP_ERR_INVALID_ARG, TAG, "invalid address");
54 
55 #if SOC_CACHE_WRITEBACK_SUPPORTED
56     if ((flags & ESP_CACHE_MSYNC_FLAG_UNALIGNED) == 0) {
57         esp_os_enter_critical_safe(&s_spinlock);
58         uint32_t data_cache_line_size = cache_hal_get_cache_line_size(CACHE_TYPE_DATA);
59         esp_os_exit_critical_safe(&s_spinlock);
60 
61         ESP_RETURN_ON_FALSE_ISR(((uint32_t)addr % data_cache_line_size) == 0, ESP_ERR_INVALID_ARG, TAG, "start address isn't aligned with the data cache line size (%d)B", data_cache_line_size);
62         ESP_RETURN_ON_FALSE_ISR((size % data_cache_line_size) == 0, ESP_ERR_INVALID_ARG, TAG, "size isn't aligned with the data cache line size (%d)B", data_cache_line_size);
63         ESP_RETURN_ON_FALSE_ISR((((uint32_t)addr + size) % data_cache_line_size) == 0, ESP_ERR_INVALID_ARG, TAG, "end address isn't aligned with the data cache line size (%d)B", data_cache_line_size);
64     }
65 
66     uint32_t vaddr = (uint32_t)addr;
67 
68     esp_os_enter_critical_safe(&s_spinlock);
69     s_cache_freeze();
70 
71     cache_hal_writeback_addr(vaddr, size);
72     if (flags & ESP_CACHE_MSYNC_FLAG_INVALIDATE) {
73         cache_hal_invalidate_addr(vaddr, size);
74     }
75 
76     s_cache_unfreeze();
77     esp_os_exit_critical_safe(&s_spinlock);
78 #endif
79 
80     return ESP_OK;
81 }
82