Skip to content

Commit 7090fc5

Browse files
bikeNomaddpgeorge
authored andcommitted
zephyr: Mount all disks and flash partition, formatting if necessary.
Existing C code in `main.c` only mounts a flash filesystem if one exists, and doesn't do anything if the 'storage' partition is not formatted. This commit moves the mounting logic from `main.c` to frozen code using `modules/_boot.py` and adds the formatting of a previously unformatted partition if the mount fails. Every available disk (in the newly added `DiskAccess.disks` tuple) will be mounted on separate mount points (if they're formatted), and the 'storage' flash partition (if any) will be mounted on /flash (and will be formatted as LFS2 if necessary). Also, `sys.path` will be updated with appropriate 'lib' subdirectories for each mounted filesystem. The current working directory will be changed to the last `DiskAccess.disk` mounted, or to /flash if no disks were mounted. Then `boot.py` and `main.py` will be executed from the current working directory if they exist. Thanks to @VynDragon for the logic in `zephyr/zephyr_storage.c`. Signed-off-by: Ned Konz <[email protected]>
1 parent b1802eb commit 7090fc5

File tree

6 files changed

+183
-53
lines changed

6 files changed

+183
-53
lines changed

docs/zephyr/quickref.rst

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -135,11 +135,14 @@ the ``io-channels`` property containing all the ADC channels)::
135135
Disk Access
136136
-----------
137137

138-
Use the :ref:`zephyr.DiskAccess <zephyr.DiskAccess>` class to support filesystem::
138+
Storage devices such as SD cards are automatically mounted at startup (e.g., at ``/sd``).
139+
For manual mounting, use the :ref:`zephyr.DiskAccess <zephyr.DiskAccess>` class::
139140

140141
import vfs
141142
from zephyr import DiskAccess
142143

144+
print(DiskAccess.disks) # list available disk names, e.g., ('SDHC',)
145+
143146
block_dev = DiskAccess('SDHC') # create a block device object for an SD card
144147
vfs.VfsFat.mkfs(block_dev) # create FAT filesystem object using the disk storage block
145148
vfs.mount(block_dev, '/sd') # mount the filesystem at the SD card subdirectory
@@ -152,12 +155,15 @@ Use the :ref:`zephyr.DiskAccess <zephyr.DiskAccess>` class to support filesystem
152155
Flash Area
153156
----------
154157

155-
Use the :ref:`zephyr.FlashArea <zephyr.FlashArea>` class to support filesystem::
158+
Flash storage is automatically mounted at ``/flash`` at startup with automatic filesystem creation.
159+
For manual mounting, use the :ref:`zephyr.FlashArea <zephyr.FlashArea>` class::
156160

157161
import vfs
158162
from zephyr import FlashArea
159163

160-
block_dev = FlashArea(4, 4096) # creates a block device object in the frdm-k64f flash scratch partition
164+
print(FlashArea.areas) # list available areas, e.g., {'storage': 1, 'scratch': 4}
165+
166+
block_dev = FlashArea(FlashArea.areas['scratch'], 4096) # creates a block device object using the scratch partition
161167
vfs.VfsLfs2.mkfs(block_dev) # create filesystem in lfs2 format using the flash block device
162168
vfs.mount(block_dev, '/flash') # mount the filesystem at the flash subdirectory
163169

@@ -166,8 +172,6 @@ Use the :ref:`zephyr.FlashArea <zephyr.FlashArea>` class to support filesystem::
166172
f.write('Hello world') # write to the file
167173
print(open('/flash/hello.txt').read()) # print contents of the file
168174

169-
The ``FlashAreas``' IDs that are available are listed in the FlashArea module, as ``ID_*``.
170-
171175
Sensor
172176
------
173177

docs/zephyr/tutorial/storage.rst

Lines changed: 48 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,27 @@ Zephyr DiskAccess or FlashArea (flash map) APIs depending on which the board sup
88

99
See `vfs Filesystem Mounting <https://docs.micropython.org/en/latest/library/vfs.html?highlight=vfs#filesystem-mounting>`_.
1010

11+
Automatic Filesystem Mounting
12+
------------------------------
13+
14+
MicroPython on Zephyr automatically attempts to mount available storage at startup:
15+
16+
1. **Flash storage** (if available): Automatically mounted at ``/flash`` using the
17+
littlefs2 filesystem. If the filesystem doesn't exist, it will be created
18+
automatically.
19+
20+
2. **Disk storage** (such as SD cards): Automatically detected and mounted at
21+
``/<disk_name>`` (e.g., ``/sd`` for SD cards).
22+
23+
3. **Working directory**: The working directory is set to the mounted disk if
24+
available, otherwise to ``/flash`` if flash storage is available.
25+
26+
4. **Module search path**: The ``sys.path`` is automatically updated to include
27+
``/<disk>/lib`` for each mounted disk and ``/flash/lib`` for flash storage.
28+
29+
This automatic mounting is performed by the ``_boot.py`` module at startup. For most
30+
use cases, you don't need to manually mount filesystems.
31+
1132
Disk Access
1233
-----------
1334

@@ -19,17 +40,26 @@ For use with SD card controllers, SD cards must be present at boot & not removed
1940
be auto detected and initialized by filesystem at boot. Use the disk driver interface and a
2041
file system to access SD cards via disk access (see below).
2142

43+
The available disk names can be accessed via the ``DiskAccess.disks`` attribute, which contains
44+
a tuple of available disk names (e.g., ``('SDHC',)`` or ``('SD',)``).
45+
2246
Example usage of FatFS with an SD card on the mimxrt1050_evk board::
2347

2448
import vfs
2549
from zephyr import DiskAccess
26-
bdev = zephyr.DiskAccess('SDHC') # create block device object using DiskAccess
50+
51+
# List available disks
52+
print(DiskAccess.disks) # prints available disk names, e.g., ('SDHC',)
53+
54+
bdev = DiskAccess('SDHC') # create block device object using DiskAccess
2755
vfs.VfsFat.mkfs(bdev) # create FAT filesystem object using the disk storage block
2856
vfs.mount(bdev, '/sd') # mount the filesystem at the SD card subdirectory
2957
with open('/sd/hello.txt','w') as f: # open a new file in the directory
3058
f.write('Hello world') # write to the file
3159
print(open('/sd/hello.txt').read()) # print contents of the file
3260

61+
Note: In most cases, disks are automatically mounted at startup and manual mounting is not necessary.
62+
3363

3464
Flash Area
3565
----------
@@ -41,16 +71,26 @@ API is recommended (see below).
4171
This class uses `Zephyr Flash map API <https://docs.zephyrproject.org/latest/reference/storage/flash_map/flash_map.html#>`_ and
4272
implements the `vfs.AbstractBlockDev` protocol.
4373

74+
The available flash area names can be accessed via the ``FlashArea.areas`` dictionary, which maps partition
75+
labels to their IDs (e.g., ``{'storage': 1, 'scratch': 4}``).
76+
4477
Example usage with the internal flash on the reel_board or the rv32m1_vega_ri5cy board::
4578

4679
import vfs
4780
from zephyr import FlashArea
48-
bdev = FlashArea(FlashArea.STORAGE, 4096) # create block device object using FlashArea
49-
vfs.VfsLfs2.mkfs(bdev) # create Little filesystem object using the flash area block
50-
vfs.mount(bdev, '/flash') # mount the filesystem at the flash storage subdirectory
51-
with open('/flash/hello.txt','w') as f: # open a new file in the directory
52-
f.write('Hello world') # write to the file
53-
print(open('/flash/hello.txt').read()) # print contents of the file
81+
82+
# List available flash areas
83+
print(FlashArea.areas) # prints available areas, e.g., {'storage': 1, 'scratch': 4}
84+
85+
bdev = FlashArea(FlashArea.areas['storage'], 4096) # create block device object using FlashArea
86+
vfs.VfsLfs2.mkfs(bdev) # create Little filesystem object using the flash area block
87+
vfs.mount(bdev, '/flash') # mount the filesystem at the flash storage subdirectory
88+
with open('/flash/hello.txt','w') as f: # open a new file in the directory
89+
f.write('Hello world') # write to the file
90+
print(open('/flash/hello.txt').read()) # print contents of the file
91+
92+
Note: In most cases, the flash storage partition is automatically mounted at ``/flash`` at startup with
93+
automatic filesystem creation if needed, so manual mounting is not necessary.
5494

5595
For boards such as the frdm_k64f in which the MicroPython application spills into the default flash storage
56-
partition, use the scratch partition by replacing ``FlashArea.STORAGE`` with the integer value 4.
96+
partition, use the scratch partition by replacing ``'storage'`` with ``'scratch'``.

ports/zephyr/Kconfig

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ config MICROPY_VFS_LFS2
4343

4444
config MICROPY_FROZEN_MODULES
4545
bool "Enable Frozen Modules"
46+
default y if FLASH_MAP || DISK_ACCESS
4647

4748
config MICROPY_FROZEN_MANIFEST
4849
string "Path to Frozen Modules manifest.py"

ports/zephyr/main.c

Lines changed: 5 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -94,39 +94,6 @@ void init_zephyr(void) {
9494
#endif
9595
}
9696

97-
#if MICROPY_VFS
98-
static void vfs_init(void) {
99-
mp_obj_t bdev = NULL;
100-
mp_obj_t mount_point;
101-
const char *mount_point_str = NULL;
102-
qstr path_lib_qstr = MP_QSTRnull;
103-
int ret = 0;
104-
105-
#ifdef CONFIG_DISK_DRIVER_SDMMC
106-
#if KERNEL_VERSION_NUMBER >= ZEPHYR_VERSION(4, 0, 0)
107-
mp_obj_t args[] = { mp_obj_new_str_from_cstr(DT_PROP(DT_INST(0, zephyr_sdmmc_disk), disk_name)) };
108-
#else
109-
mp_obj_t args[] = { mp_obj_new_str_from_cstr(CONFIG_SDMMC_VOLUME_NAME) };
110-
#endif
111-
bdev = MP_OBJ_TYPE_GET_SLOT(&zephyr_disk_access_type, make_new)(&zephyr_disk_access_type, ARRAY_SIZE(args), 0, args);
112-
mount_point_str = "/sd";
113-
path_lib_qstr = MP_QSTR__slash_sd_slash_lib;
114-
#elif defined(CONFIG_FLASH_MAP) && FIXED_PARTITION_EXISTS(storage_partition)
115-
mp_obj_t args[] = { MP_OBJ_NEW_SMALL_INT(FIXED_PARTITION_ID(storage_partition)), MP_OBJ_NEW_SMALL_INT(4096) };
116-
bdev = MP_OBJ_TYPE_GET_SLOT(&zephyr_flash_area_type, make_new)(&zephyr_flash_area_type, ARRAY_SIZE(args), 0, args);
117-
mount_point_str = "/flash";
118-
path_lib_qstr = MP_QSTR__slash_flash_slash_lib;
119-
#endif
120-
121-
if ((bdev != NULL)) {
122-
mount_point = mp_obj_new_str_from_cstr(mount_point_str);
123-
ret = mp_vfs_mount_and_chdir_protected(bdev, mount_point);
124-
mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(path_lib_qstr));
125-
// TODO: if this failed, make a new file system and try to mount again
126-
}
127-
}
128-
#endif // MICROPY_VFS
129-
13097
int real_main(void) {
13198
#if MICROPY_PY_THREAD
13299
struct k_thread *z_thread = (struct k_thread *)k_current_get();
@@ -151,10 +118,12 @@ int real_main(void) {
151118
mp_usbd_init();
152119
#endif
153120

154-
#if MICROPY_VFS
155-
vfs_init();
121+
#if MICROPY_VFS && MICROPY_MODULE_FROZEN_MPY
122+
// Mount and/or create the filesystem
123+
pyexec_frozen_module("_boot.py", false);
156124
#endif
157125

126+
158127
#if MICROPY_MODULE_FROZEN || MICROPY_VFS
159128
// Execute user scripts.
160129
int ret = pyexec_file_if_exists("boot.py");
@@ -181,7 +150,7 @@ int real_main(void) {
181150
}
182151
}
183152

184-
#if MICROPY_MODULE_FROZEN || MICROPY_VFS
153+
#if MICROPY_MODULE_FROZEN_MPY || MICROPY_VFS
185154
soft_reset_exit:
186155
#endif
187156

ports/zephyr/modules/_boot.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
# ruff: noqa: F821
2+
import sys
3+
import os
4+
from micropython import const
5+
import vfs # vfs is always available
6+
import zephyr
7+
8+
# FlashArea depends on CONFIG_FLASH_MAP
9+
FlashArea = getattr(zephyr, "FlashArea", None)
10+
11+
# DiskAccess depends on CONFIG_DISK_ACCESS
12+
DiskAccess = getattr(zephyr, "DiskAccess", None)
13+
14+
_FLASH = const("/flash")
15+
_FLASH_LIB = const("/flash/lib")
16+
_STORAGE_KEY = const("storage")
17+
_FLASH_EXISTS = False
18+
19+
20+
def create_flash_partition():
21+
"""Create an LFS2 filesystem on the partition labeled storage
22+
and mount it on /flash.
23+
Return True if successful, False otherwise.
24+
"""
25+
if _STORAGE_KEY in FlashArea.areas:
26+
# TODO: get the erase block size from DTS instead of 4K.
27+
bdev = FlashArea(FlashArea.areas[_STORAGE_KEY], 4096)
28+
retval = True
29+
try:
30+
vfs.mount(bdev, _FLASH)
31+
except OSError:
32+
try:
33+
vfs.VfsLfs2.mkfs(bdev)
34+
vfs.mount(bdev, _FLASH)
35+
except OSError:
36+
print("Error formatting flash partition")
37+
retval = False
38+
return retval
39+
return False
40+
41+
42+
def mount_all_disks():
43+
"""Now mount all the DiskAreas (if any)."""
44+
retval = False
45+
for da_name in DiskAccess.disks:
46+
mount_name = f"/{da_name.lower()}"
47+
da = DiskAccess(da_name)
48+
try:
49+
vfs.mount(da, mount_name)
50+
sys.path.append(f"{mount_name}/lib")
51+
os.chdir(mount_name)
52+
retval = True
53+
except OSError as e:
54+
print(f"Error mounting {da_name}: {e}")
55+
return retval
56+
57+
58+
if FlashArea and create_flash_partition():
59+
_FLASH_EXISTS = True
60+
61+
# Prefer disks to /flash
62+
if not (DiskAccess and mount_all_disks()):
63+
if _FLASH_EXISTS:
64+
os.chdir(_FLASH)
65+
66+
# Place /flash/lib last on sys.path
67+
if _FLASH_EXISTS:
68+
sys.path.append(_FLASH_LIB)
69+
70+
# Cleanup globals for boot.py/main.py
71+
del FlashArea, DiskAccess, zephyr
72+
del sys, vfs, os, const
73+
del create_flash_partition, mount_all_disks, _FLASH_EXISTS

ports/zephyr/zephyr_storage.c

Lines changed: 47 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,11 @@
4040
#endif
4141

4242
#ifdef CONFIG_DISK_ACCESS
43+
44+
#define DISK_DEFINE_NAME(part) CONCAT(MP_QSTR_, DT_STRING_TOKEN(part, disk_name))
45+
46+
#define FOREACH_DISK(n) MP_ROM_QSTR(DISK_DEFINE_NAME(n)),
47+
4348
typedef struct _zephyr_disk_access_obj_t {
4449
mp_obj_base_t base;
4550
const char *pdrv;
@@ -121,10 +126,43 @@ static mp_obj_t zephyr_disk_access_ioctl(mp_obj_t self_in, mp_obj_t cmd_in, mp_o
121126
}
122127
static MP_DEFINE_CONST_FUN_OBJ_3(zephyr_disk_access_ioctl_obj, zephyr_disk_access_ioctl);
123128

129+
static const mp_rom_obj_tuple_t zephyr_disks_tuple = {
130+
.base = {.type = &mp_type_tuple},
131+
.items = {
132+
#ifdef CONFIG_DISK_DRIVER_SDMMC
133+
DT_FOREACH_STATUS_OKAY(zephyr_sdmmc_disk, FOREACH_DISK)
134+
#endif
135+
#ifdef CONFIG_DISK_DRIVER_MMC
136+
DT_FOREACH_STATUS_OKAY(zephyr_mmc_disk, FOREACH_DISK)
137+
#endif
138+
#ifdef CONFIG_DISK_DRIVER_FLASH
139+
DT_FOREACH_STATUS_OKAY(zephyr_flash_disk, FOREACH_DISK)
140+
#endif
141+
#ifdef CONFIG_DISK_DRIVER_RAM
142+
DT_FOREACH_STATUS_OKAY(zephyr_ram_disk, FOREACH_DISK)
143+
#endif
144+
},
145+
.len = MP_ARRAY_SIZE((mp_rom_obj_t []) {
146+
#ifdef CONFIG_DISK_DRIVER_SDMMC
147+
DT_FOREACH_STATUS_OKAY(zephyr_sdmmc_disk, FOREACH_DISK)
148+
#endif
149+
#ifdef CONFIG_DISK_DRIVER_MMC
150+
DT_FOREACH_STATUS_OKAY(zephyr_mmc_disk, FOREACH_DISK)
151+
#endif
152+
#ifdef CONFIG_DISK_DRIVER_FLASH
153+
DT_FOREACH_STATUS_OKAY(zephyr_flash_disk, FOREACH_DISK)
154+
#endif
155+
#ifdef CONFIG_DISK_DRIVER_RAM
156+
DT_FOREACH_STATUS_OKAY(zephyr_ram_disk, FOREACH_DISK)
157+
#endif
158+
})
159+
};
160+
124161
static const mp_rom_map_elem_t zephyr_disk_access_locals_dict_table[] = {
125162
{ MP_ROM_QSTR(MP_QSTR_readblocks), MP_ROM_PTR(&zephyr_disk_access_readblocks_obj) },
126163
{ MP_ROM_QSTR(MP_QSTR_writeblocks), MP_ROM_PTR(&zephyr_disk_access_writeblocks_obj) },
127164
{ MP_ROM_QSTR(MP_QSTR_ioctl), MP_ROM_PTR(&zephyr_disk_access_ioctl_obj) },
165+
{ MP_ROM_QSTR(MP_QSTR_disks), MP_ROM_PTR(&zephyr_disks_tuple) },
128166
};
129167
static MP_DEFINE_CONST_DICT(zephyr_disk_access_locals_dict, zephyr_disk_access_locals_dict_table);
130168

@@ -140,8 +178,8 @@ MP_DEFINE_CONST_OBJ_TYPE(
140178

141179
#ifdef CONFIG_FLASH_MAP
142180

143-
#define FLASH_AREA_DEFINE_LABEL(part) CONCAT(MP_QSTR_ID_, DT_STRING_TOKEN(part, label))
144-
#define FLASH_AREA_DEFINE_NB(part) CONCAT(MP_QSTR_ID_, DT_FIXED_PARTITION_ID(part))
181+
#define FLASH_AREA_DEFINE_LABEL(part) CONCAT(MP_QSTR_, DT_STRING_TOKEN(part, label))
182+
#define FLASH_AREA_DEFINE_NB(part) CONCAT(MP_QSTR_, DT_FIXED_PARTITION_ID(part))
145183

146184
#define FLASH_AREA_DEFINE_GETNAME(part) COND_CODE_1(DT_NODE_HAS_PROP(part, label), \
147185
(FLASH_AREA_DEFINE_LABEL(part)), (FLASH_AREA_DEFINE_NB(part)))
@@ -254,12 +292,17 @@ static mp_obj_t zephyr_flash_area_ioctl(mp_obj_t self_in, mp_obj_t cmd_in, mp_ob
254292
}
255293
static MP_DEFINE_CONST_FUN_OBJ_3(zephyr_flash_area_ioctl_obj, zephyr_flash_area_ioctl);
256294

295+
static const mp_rom_map_elem_t zephyr_flash_areas_table[] = {
296+
/* Generate list of partition IDs from Zephyr Devicetree */
297+
DT_FOREACH_STATUS_OKAY(fixed_partitions, FOREACH_PARTITION)
298+
};
299+
static MP_DEFINE_CONST_DICT(zephyr_flash_areas_dict, zephyr_flash_areas_table);
300+
257301
static const mp_rom_map_elem_t zephyr_flash_area_locals_dict_table[] = {
258302
{ MP_ROM_QSTR(MP_QSTR_readblocks), MP_ROM_PTR(&zephyr_flash_area_readblocks_obj) },
259303
{ MP_ROM_QSTR(MP_QSTR_writeblocks), MP_ROM_PTR(&zephyr_flash_area_writeblocks_obj) },
260304
{ MP_ROM_QSTR(MP_QSTR_ioctl), MP_ROM_PTR(&zephyr_flash_area_ioctl_obj) },
261-
/* Generate list of partition IDs from Zephyr Devicetree */
262-
DT_FOREACH_STATUS_OKAY(fixed_partitions, FOREACH_PARTITION)
305+
{ MP_ROM_QSTR(MP_QSTR_areas), MP_ROM_PTR(&zephyr_flash_areas_dict) },
263306
};
264307
static MP_DEFINE_CONST_DICT(zephyr_flash_area_locals_dict, zephyr_flash_area_locals_dict_table);
265308

0 commit comments

Comments
 (0)