Skip to content

Commit 9af5fc5

Browse files
XuNeoxiaoxiang781216
authored andcommitted
fs/shm: alloc aligned memory if CPU has cache
For kernel builds, shared memory is automatically aligned to page size. For flat and protected builds, we align the memory size to the CPU cache line size. Failure to align memory properly could result in partial data read/write by the CPU and peripherals, potentially causing data corruption during cache flushes or invalidations. Signed-off-by: xuxingliang <[email protected]>
1 parent 22bcb88 commit 9af5fc5

File tree

1 file changed

+28
-13
lines changed

1 file changed

+28
-13
lines changed

fs/shm/shmfs_alloc.c

Lines changed: 28 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
#include <stdbool.h>
2828

2929
#include <nuttx/arch.h>
30+
#include <nuttx/cache.h>
3031
#include <nuttx/kmalloc.h>
3132
#include <nuttx/pgalloc.h>
3233

@@ -47,19 +48,23 @@ FAR struct shmfs_object_s *shmfs_alloc_object(size_t length)
4748
* chunk in kernel heap
4849
*/
4950

50-
size_t alloc_size = sizeof(struct shmfs_object_s) + length;
51-
if (alloc_size < length)
52-
{
53-
/* There must have been an integer overflow */
54-
55-
return NULL;
56-
}
57-
58-
object = fs_heap_zalloc(alloc_size);
51+
object = fs_heap_zalloc(sizeof(struct shmfs_object_s));
5952
if (object)
6053
{
61-
object->paddr = (FAR char *)(object + 1);
62-
allocated = true;
54+
size_t cachesize = up_get_dcache_linesize();
55+
if (cachesize > 0)
56+
{
57+
object->paddr = fs_heap_memalign(cachesize, length);
58+
}
59+
else
60+
{
61+
object->paddr = fs_heap_malloc(length);
62+
}
63+
64+
if (object->paddr)
65+
{
66+
allocated = true;
67+
}
6368
}
6469

6570
#elif defined(CONFIG_BUILD_PROTECTED)
@@ -70,7 +75,15 @@ FAR struct shmfs_object_s *shmfs_alloc_object(size_t length)
7075
object = fs_heap_zalloc(sizeof(struct shmfs_object_s));
7176
if (object)
7277
{
73-
object->paddr = kumm_zalloc(length);
78+
size_t cachesize = up_get_dcache_linesize();
79+
if (cachesize > 0)
80+
{
81+
object->paddr = kumm_memalign(cachesize, length);
82+
}
83+
else
84+
{
85+
object->paddr = kumm_malloc(length);
86+
}
7487

7588
if (object->paddr)
7689
{
@@ -140,7 +153,9 @@ void shmfs_free_object(FAR struct shmfs_object_s *object)
140153

141154
if (object)
142155
{
143-
#if defined (CONFIG_BUILD_PROTECTED)
156+
#if defined(CONFIG_BUILD_FLAT)
157+
fs_heap_free(object->paddr);
158+
#elif defined(CONFIG_BUILD_PROTECTED)
144159
kumm_free(object->paddr);
145160
#elif defined(CONFIG_BUILD_KERNEL)
146161
pages = &object->paddr;

0 commit comments

Comments
 (0)