1 /*
2  * Copyright (c) 2017 Codecoup
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <stdint.h>
8 #include <string.h>
9 #include <zephyr/device.h>
10 #include <zephyr/drivers/flash.h>
11 #include <zephyr/storage/flash_map.h>
12 #include <zephyr/types.h>
13 #include <zephyr/ztest_assert.h>
14 
15 #define TEST_PARTITION		storage_partition
16 #define TEST_PARTITION_ID	FIXED_PARTITION_ID(TEST_PARTITION)
17 #define TEST_PARTITION_SIZE	FIXED_PARTITION_SIZE(TEST_PARTITION)
18 
19 static uint8_t rambuf[TEST_PARTITION_SIZE];
20 
test_flash_ram_erase(const struct device * dev,off_t offset,size_t len)21 static int test_flash_ram_erase(const struct device *dev, off_t offset,
22 				size_t len)
23 {
24 	struct flash_pages_info info;
25 	off_t end_offset = offset + len;
26 
27 	zassert_true(offset >= 0, "invalid offset");
28 	zassert_true(offset + len <= TEST_PARTITION_SIZE,
29 		     "flash address out of bounds");
30 
31 	while (offset < end_offset) {
32 		flash_get_page_info_by_offs(dev, offset, &info);
33 		(void)memset(rambuf + info.start_offset, 0xff, info.size);
34 		offset = info.start_offset + info.size;
35 	}
36 
37 	return 0;
38 }
39 
test_flash_ram_write(const struct device * dev,off_t offset,const void * data,size_t len)40 static int test_flash_ram_write(const struct device *dev, off_t offset,
41 						const void *data, size_t len)
42 {
43 	zassert_true(offset >= 0, "invalid offset");
44 	zassert_true(offset + len <= TEST_PARTITION_SIZE,
45 		     "flash address out of bounds");
46 
47 	memcpy(rambuf + offset, data, len);
48 
49 	return 0;
50 }
51 
test_flash_ram_read(const struct device * dev,off_t offset,void * data,size_t len)52 static int test_flash_ram_read(const struct device *dev, off_t offset,
53 								void *data,
54 								size_t len)
55 {
56 	zassert_true(offset >= 0, "invalid offset");
57 	zassert_true(offset + len <= TEST_PARTITION_SIZE,
58 		     "flash address out of bounds");
59 
60 	memcpy(data, rambuf + offset, len);
61 
62 	return 0;
63 }
64 
test_flash_ram_pages_layout(const struct device * dev,const struct flash_pages_layout ** layout,size_t * layout_size)65 static void test_flash_ram_pages_layout(const struct device *dev,
66 					const struct flash_pages_layout **layout,
67 					size_t *layout_size)
68 {
69 	/* Same as used in Mynewt native "flash" backend */
70 	static struct flash_pages_layout dev_layout[] = {
71 		{ 4, 16 * 1024 },
72 		{ 1, 64 * 1024 },
73 		{ 7, 128 * 1024 },
74 	};
75 
76 	*layout = dev_layout;
77 	*layout_size = ARRAY_SIZE(dev_layout);
78 }
79 
80 static DEVICE_API(flash, flash_ram_api) = {
81 	.erase = test_flash_ram_erase,
82 	.write = test_flash_ram_write,
83 	.read = test_flash_ram_read,
84 	.page_layout = test_flash_ram_pages_layout,
85 };
86 
87 DEVICE_DEFINE(flash_ram_test, "ram_flash_test_drv", NULL, NULL, NULL, NULL,
88 	      POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEVICE, &flash_ram_api);
89