esp_himem.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. // Copyright 2018 Espressif Systems (Shanghai) PTE LTD
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "freertos/FreeRTOS.h"
  15. #include "freertos/task.h"
  16. #include "esp32/spiram.h"
  17. #include "esp32/rom/cache.h"
  18. #include "sdkconfig.h"
  19. #include "esp32/himem.h"
  20. #include "soc/soc.h"
  21. #include "esp_log.h"
  22. /*
  23. So, why does the API look this way and is so inflexible to not allow any maps beyond the full 32K chunks? Most of
  24. it has to do with the fact that the cache works on the *virtual* addresses What this comes down to is that while it's
  25. allowed to map a range of physical memory into the address space two times, there's no cache consistency between the
  26. two regions.
  27. This means that a write to region A may or may not show up, perhaps delayed, in region B, as it depends on
  28. the time that the writeback to SPI RAM is done on A and the time before the corresponding cache line is invalidated
  29. on B. Note that this goes for every 32-byte cache line: this implies that if a program writes to address X and Y within
  30. A, the write to Y may show up before the write to X does.
  31. It gets even worse when both A and B are written: theoretically, a write to a 32-byte cache line in A can be entirely
  32. undone because of a write to a different addres in B that happens to be in the same 32-byte cache line.
  33. Because of these reasons, we do not allow double mappings at all. This, however, has other implications that make
  34. supporting ranges not really useful. Because the lack of double mappings, applications will need to do their own
  35. management of mapped regions, meaning they will normally map in and out blocks at a time anyway, as mapping more
  36. fluent regions would result in the chance of accidentally mapping two overlapping regions. As this is the case,
  37. to keep the code simple, at the moment we just force these blocks to be equal to the 32K MMU page size. The API
  38. itself does allow for more granular allocations, so if there's a pressing need for a more complex solution in the
  39. future, we can do this.
  40. Note: In the future, we can expand on this api to do a memcpy() between SPI RAM and (internal) memory using the SPI1
  41. peripheral. This needs support for SPI1 to be in the SPI driver, however.
  42. */
  43. #if CONFIG_SPIRAM_BANKSWITCH_ENABLE
  44. #define SPIRAM_BANKSWITCH_RESERVE CONFIG_SPIRAM_BANKSWITCH_RESERVE
  45. #else
  46. #define SPIRAM_BANKSWITCH_RESERVE 0
  47. #endif
  48. #define CACHE_BLOCKSIZE (32*1024)
  49. //Start of the virtual address range reserved for himem use
  50. #define VIRT_HIMEM_RANGE_START (SOC_EXTRAM_DATA_LOW+(128-SPIRAM_BANKSWITCH_RESERVE)*CACHE_BLOCKSIZE)
  51. //Start MMU block reserved for himem use
  52. #define VIRT_HIMEM_RANGE_BLOCKSTART (128-SPIRAM_BANKSWITCH_RESERVE)
  53. //Start physical block
  54. #define PHYS_HIMEM_BLOCKSTART (128-SPIRAM_BANKSWITCH_RESERVE)
  55. #define TAG "esp_himem"
  56. #define HIMEM_CHECK(cond, str, err) if (cond) do {ESP_LOGE(TAG, "%s: %s", __FUNCTION__, str); return err; } while(0)
  57. // Metadata for a block of physical RAM
  58. typedef struct {
  59. unsigned int is_alloced: 1;
  60. unsigned int is_mapped: 1;
  61. } ramblock_t;
  62. //Metadata for a 32-K memory address range
  63. typedef struct {
  64. unsigned int is_alloced: 1;
  65. unsigned int is_mapped: 1;
  66. unsigned int ram_block: 16;
  67. } rangeblock_t;
  68. static ramblock_t *s_ram_descriptor = NULL;
  69. static rangeblock_t *s_range_descriptor = NULL;
  70. static int s_ramblockcnt = 0;
  71. static const int s_rangeblockcnt = SPIRAM_BANKSWITCH_RESERVE;
  72. //Handle for a window of address space
  73. typedef struct esp_himem_rangedata_t {
  74. int block_ct;
  75. int block_start;
  76. } esp_himem_rangedata_t;
  77. //Handle for a range of physical memory
  78. typedef struct esp_himem_ramdata_t {
  79. int block_ct;
  80. uint16_t *block;
  81. } esp_himem_ramdata_t;
  82. static portMUX_TYPE spinlock = portMUX_INITIALIZER_UNLOCKED;
  83. static inline int ramblock_idx_valid(int ramblock_idx)
  84. {
  85. return (ramblock_idx >= 0 && ramblock_idx < s_ramblockcnt);
  86. }
  87. static inline int rangeblock_idx_valid(int rangeblock_idx)
  88. {
  89. return (rangeblock_idx >= 0 && rangeblock_idx < s_rangeblockcnt);
  90. }
  91. static void set_bank(int virt_bank, int phys_bank, int ct)
  92. {
  93. int r;
  94. r = cache_sram_mmu_set( 0, 0, SOC_EXTRAM_DATA_LOW + CACHE_BLOCKSIZE * virt_bank, phys_bank * CACHE_BLOCKSIZE, 32, ct );
  95. assert(r == 0);
  96. r = cache_sram_mmu_set( 1, 0, SOC_EXTRAM_DATA_LOW + CACHE_BLOCKSIZE * virt_bank, phys_bank * CACHE_BLOCKSIZE, 32, ct );
  97. assert(r == 0);
  98. }
  99. size_t esp_himem_get_phys_size(void)
  100. {
  101. int paddr_start = (4096 * 1024) - (CACHE_BLOCKSIZE * SPIRAM_BANKSWITCH_RESERVE);
  102. return esp_spiram_get_size()-paddr_start;
  103. }
  104. size_t esp_himem_get_free_size(void)
  105. {
  106. size_t ret=0;
  107. for (int i = 0; i < s_ramblockcnt; i++) {
  108. if (!s_ram_descriptor[i].is_alloced) ret+=CACHE_BLOCKSIZE;
  109. }
  110. return ret;
  111. }
  112. size_t esp_himem_reserved_area_size(void) {
  113. return CACHE_BLOCKSIZE * SPIRAM_BANKSWITCH_RESERVE;
  114. }
  115. void __attribute__((constructor)) esp_himem_init(void)
  116. {
  117. if (SPIRAM_BANKSWITCH_RESERVE == 0) return;
  118. int maxram=esp_spiram_get_size();
  119. //catch double init
  120. HIMEM_CHECK(s_ram_descriptor != NULL, "already initialized", ); //Looks weird; last arg is empty so it expands to 'return ;'
  121. HIMEM_CHECK(s_range_descriptor != NULL, "already initialized", );
  122. //need to have some reserved banks
  123. HIMEM_CHECK(SPIRAM_BANKSWITCH_RESERVE == 0, "No banks reserved for himem", );
  124. //Start and end of physical reserved memory. Note it starts slightly under
  125. //the 4MiB mark as the reserved banks can't have an unity mapping to be used by malloc
  126. //anymore; we treat them as himem instead.
  127. int paddr_start = (4096 * 1024) - (CACHE_BLOCKSIZE * SPIRAM_BANKSWITCH_RESERVE);
  128. int paddr_end = maxram;
  129. s_ramblockcnt = ((paddr_end - paddr_start) / CACHE_BLOCKSIZE);
  130. //Allocate data structures
  131. s_ram_descriptor = calloc(sizeof(ramblock_t), s_ramblockcnt);
  132. s_range_descriptor = calloc(sizeof(rangeblock_t), SPIRAM_BANKSWITCH_RESERVE);
  133. if (s_ram_descriptor == NULL || s_range_descriptor == NULL) {
  134. ESP_EARLY_LOGE(TAG, "Cannot allocate memory for meta info. Not initializing!");
  135. free(s_ram_descriptor);
  136. free(s_range_descriptor);
  137. return;
  138. }
  139. ESP_EARLY_LOGI(TAG, "Initialized. Using last %d 32KB address blocks for bank switching on %d KB of physical memory.",
  140. SPIRAM_BANKSWITCH_RESERVE, (paddr_end - paddr_start)/1024);
  141. }
  142. //Allocate count not-necessarily consecutive physical RAM blocks, return numbers in blocks[]. Return
  143. //true if blocks can be allocated, false if not.
  144. static bool allocate_blocks(int count, uint16_t *blocks_out)
  145. {
  146. int n = 0;
  147. for (int i = 0; i < s_ramblockcnt && n != count; i++) {
  148. if (!s_ram_descriptor[i].is_alloced) {
  149. blocks_out[n] = i;
  150. n++;
  151. }
  152. }
  153. if (n == count) {
  154. //All blocks could be allocated. Mark as in use.
  155. for (int i = 0; i < count; i++) {
  156. s_ram_descriptor[blocks_out[i]].is_alloced = true;
  157. assert(s_ram_descriptor[blocks_out[i]].is_mapped == false);
  158. }
  159. return true;
  160. } else {
  161. //Error allocating blocks
  162. return false;
  163. }
  164. }
  165. esp_err_t esp_himem_alloc(size_t size, esp_himem_handle_t *handle_out)
  166. {
  167. if (size % CACHE_BLOCKSIZE != 0) {
  168. return ESP_ERR_INVALID_SIZE;
  169. }
  170. int blocks = size / CACHE_BLOCKSIZE;
  171. esp_himem_ramdata_t *r = calloc(sizeof(esp_himem_ramdata_t), 1);
  172. if (!r) {
  173. goto nomem;
  174. }
  175. r->block = calloc(sizeof(uint16_t), blocks);
  176. if (!r->block) {
  177. goto nomem;
  178. }
  179. portENTER_CRITICAL(&spinlock);
  180. int ok = allocate_blocks(blocks, r->block);
  181. portEXIT_CRITICAL(&spinlock);
  182. if (!ok) {
  183. goto nomem;
  184. }
  185. r->block_ct = blocks;
  186. *handle_out = r;
  187. return ESP_OK;
  188. nomem:
  189. if (r) {
  190. free(r->block);
  191. }
  192. free(r);
  193. return ESP_ERR_NO_MEM;
  194. }
  195. esp_err_t esp_himem_free(esp_himem_handle_t handle)
  196. {
  197. //Check if any of the blocks is still mapped; fail if this is the case.
  198. for (int i = 0; i < handle->block_ct; i++) {
  199. assert(ramblock_idx_valid(handle->block[i]));
  200. HIMEM_CHECK(s_ram_descriptor[handle->block[i]].is_mapped, "block in range still mapped", ESP_ERR_INVALID_ARG);
  201. }
  202. //Mark blocks as free
  203. portENTER_CRITICAL(&spinlock);
  204. for (int i = 0; i < handle->block_ct; i++) {
  205. s_ram_descriptor[handle->block[i]].is_alloced = false;
  206. }
  207. portEXIT_CRITICAL(&spinlock);
  208. //Free handle
  209. free(handle->block);
  210. free(handle);
  211. return ESP_OK;
  212. }
  213. esp_err_t esp_himem_alloc_map_range(size_t size, esp_himem_rangehandle_t *handle_out)
  214. {
  215. HIMEM_CHECK(s_ram_descriptor == NULL, "Himem not available!", ESP_ERR_INVALID_STATE);
  216. HIMEM_CHECK(size % CACHE_BLOCKSIZE != 0, "requested size not aligned to blocksize", ESP_ERR_INVALID_SIZE);
  217. int blocks = size / CACHE_BLOCKSIZE;
  218. esp_himem_rangedata_t *r = calloc(sizeof(esp_himem_rangedata_t), 1);
  219. if (!r) {
  220. return ESP_ERR_NO_MEM;
  221. }
  222. r->block_ct = blocks;
  223. r->block_start = -1;
  224. int start_free = 0;
  225. portENTER_CRITICAL(&spinlock);
  226. for (int i = 0; i < s_rangeblockcnt; i++) {
  227. if (s_range_descriptor[i].is_alloced) {
  228. start_free = i + 1; //optimistically assume next block is free...
  229. } else if (i - start_free == blocks - 1) {
  230. //We found a span of blocks that's big enough to allocate the requested range in.
  231. r->block_start = start_free;
  232. break;
  233. }
  234. }
  235. if (r->block_start == -1) {
  236. //Couldn't find enough free blocks
  237. free(r);
  238. portEXIT_CRITICAL(&spinlock);
  239. return ESP_ERR_NO_MEM;
  240. }
  241. //Range is found. Mark the blocks as in use.
  242. for (int i = 0; i < blocks; i++) {
  243. s_range_descriptor[r->block_start + i].is_alloced = 1;
  244. }
  245. portEXIT_CRITICAL(&spinlock);
  246. //All done.
  247. *handle_out = r;
  248. return ESP_OK;
  249. }
  250. esp_err_t esp_himem_free_map_range(esp_himem_rangehandle_t handle)
  251. {
  252. //Check if any of the blocks in the range have a mapping
  253. for (int i = 0; i < handle->block_ct; i++) {
  254. assert(rangeblock_idx_valid(handle->block_start + i));
  255. assert(s_range_descriptor[i + handle->block_start].is_alloced == 1); //should be, if handle is valid
  256. HIMEM_CHECK(s_range_descriptor[i + handle->block_start].is_mapped, "memory still mapped to range", ESP_ERR_INVALID_ARG);
  257. }
  258. //We should be good to free this. Mark blocks as free.
  259. portENTER_CRITICAL(&spinlock);
  260. for (int i = 0; i < handle->block_ct; i++) {
  261. s_range_descriptor[i + handle->block_start].is_alloced = 0;
  262. }
  263. portEXIT_CRITICAL(&spinlock);
  264. free(handle);
  265. return ESP_OK;
  266. }
  267. esp_err_t esp_himem_map(esp_himem_handle_t handle, esp_himem_rangehandle_t range, size_t ram_offset, size_t range_offset, size_t len, int flags, void **out_ptr)
  268. {
  269. int ram_block = ram_offset / CACHE_BLOCKSIZE;
  270. int range_block = range_offset / CACHE_BLOCKSIZE;
  271. int blockcount = len / CACHE_BLOCKSIZE;
  272. HIMEM_CHECK(s_ram_descriptor == NULL, "Himem not available!", ESP_ERR_INVALID_STATE);
  273. //Offsets and length must be block-aligned
  274. HIMEM_CHECK(ram_offset % CACHE_BLOCKSIZE != 0, "ram offset not aligned to blocksize", ESP_ERR_INVALID_ARG);
  275. HIMEM_CHECK(range_offset % CACHE_BLOCKSIZE != 0, "range not aligned to blocksize", ESP_ERR_INVALID_ARG);
  276. HIMEM_CHECK(len % CACHE_BLOCKSIZE != 0, "length not aligned to blocksize", ESP_ERR_INVALID_ARG);
  277. //ram and range should be within allocated range
  278. HIMEM_CHECK(ram_block + blockcount > handle->block_ct, "args not in range of phys ram handle", ESP_ERR_INVALID_SIZE);
  279. HIMEM_CHECK(range_block + blockcount > range->block_ct, "args not in range of range handle", ESP_ERR_INVALID_SIZE);
  280. //Check if ram blocks aren't already mapped, and if memory range is unmapped
  281. for (int i = 0; i < blockcount; i++) {
  282. HIMEM_CHECK(s_ram_descriptor[handle->block[i + ram_block]].is_mapped, "ram already mapped", ESP_ERR_INVALID_STATE);
  283. HIMEM_CHECK(s_range_descriptor[range->block_start + i + range_block].is_mapped, "range already mapped", ESP_ERR_INVALID_STATE);
  284. }
  285. //Map and mark as mapped
  286. portENTER_CRITICAL(&spinlock);
  287. for (int i = 0; i < blockcount; i++) {
  288. assert(ramblock_idx_valid(handle->block[i + ram_block]));
  289. s_ram_descriptor[handle->block[i + ram_block]].is_mapped = 1;
  290. s_range_descriptor[range->block_start + i + range_block].is_mapped = 1;
  291. s_range_descriptor[range->block_start + i + range_block].ram_block = handle->block[i + ram_block];
  292. }
  293. portEXIT_CRITICAL(&spinlock);
  294. for (int i = 0; i < blockcount; i++) {
  295. set_bank(VIRT_HIMEM_RANGE_BLOCKSTART + range->block_start + i + range_block, handle->block[i + ram_block] + PHYS_HIMEM_BLOCKSTART, 1);
  296. }
  297. //Set out pointer
  298. *out_ptr = (void *)(VIRT_HIMEM_RANGE_START + (range->block_start + range_offset) * CACHE_BLOCKSIZE);
  299. return ESP_OK;
  300. }
  301. esp_err_t esp_himem_unmap(esp_himem_rangehandle_t range, void *ptr, size_t len)
  302. {
  303. //Note: doesn't actually unmap, just clears cache and marks blocks as unmapped.
  304. //Future optimization: could actually lazy-unmap here: essentially, do nothing and only clear the cache when we re-use
  305. //the block for a different physical address.
  306. int range_offset = (uint32_t)ptr - VIRT_HIMEM_RANGE_START;
  307. int range_block = (range_offset / CACHE_BLOCKSIZE) - range->block_start;
  308. int blockcount = len / CACHE_BLOCKSIZE;
  309. HIMEM_CHECK(range_offset % CACHE_BLOCKSIZE != 0, "range offset not block-aligned", ESP_ERR_INVALID_ARG);
  310. HIMEM_CHECK(len % CACHE_BLOCKSIZE != 0, "map length not block-aligned", ESP_ERR_INVALID_ARG);
  311. HIMEM_CHECK(range_block + blockcount > range->block_ct, "range out of bounds for handle", ESP_ERR_INVALID_ARG);
  312. portENTER_CRITICAL(&spinlock);
  313. for (int i = 0; i < blockcount; i++) {
  314. int ramblock = s_range_descriptor[range->block_start + i + range_block].ram_block;
  315. assert(ramblock_idx_valid(ramblock));
  316. s_ram_descriptor[ramblock].is_mapped = 0;
  317. s_range_descriptor[range->block_start + i + range_block].is_mapped = 0;
  318. }
  319. esp_spiram_writeback_cache();
  320. portEXIT_CRITICAL(&spinlock);
  321. return ESP_OK;
  322. }