first commit for chrg

This commit is contained in:
wmano
2025-08-16 22:58:22 +08:00
commit 52a3ed5862
2306 changed files with 1021208 additions and 0 deletions
+53
View File
@@ -0,0 +1,53 @@
menu "RT-Thread Components"
config RT_USING_COMPONENTS_INIT
bool
default n
config RT_USING_USER_MAIN
bool
default n
if RT_USING_USER_MAIN
config RT_MAIN_THREAD_STACK_SIZE
int "Set main thread stack size"
default 6144 if ARCH_CPU_64BIT
default 2048
config RT_MAIN_THREAD_PRIORITY
int "Set main thread priority"
default 4 if RT_THREAD_PRIORITY_8
default 10 if RT_THREAD_PRIORITY_32
default 85 if RT_THREAD_PRIORITY_256
endif
config RT_USING_LEGACY
bool "Support legacy version for compatibility"
default n
if RT_USING_CONSOLE
rsource "finsh/Kconfig"
endif
if !RT_USING_NANO
rsource "dfs/Kconfig"
rsource "fal/Kconfig"
rsource "drivers/Kconfig"
rsource "libc/Kconfig"
rsource "net/Kconfig"
rsource "mprotect/Kconfig"
rsource "utilities/Kconfig"
rsource "vbus/Kconfig"
endif
if ARCH_MM_MMU
rsource "mm/Kconfig"
endif
if RT_USING_SMART
rsource "lwp/Kconfig"
endif
rsource "legacy/Kconfig"
endmenu
+17
View File
@@ -0,0 +1,17 @@
# for module compiling
import os
Import('remove_components')
from building import *
objs = []
cwd = GetCurrentDir()
list = os.listdir(cwd)
for item in list:
if item in remove_components:
continue
if os.path.isfile(os.path.join(cwd, item, 'SConscript')):
objs = objs + SConscript(os.path.join(item, 'SConscript'))
Return('objs')
+210
View File
@@ -0,0 +1,210 @@
menu "DFS: device virtual file system"
config RT_USING_DFS
bool "DFS: device virtual file system"
select RT_USING_MUTEX
default y
help
The device file system is a light weight virtual file system.
if RT_USING_DFS
config DFS_USING_POSIX
bool "Using posix-like functions, open/read/write/close"
default y
config DFS_USING_WORKDIR
bool "Using working directory"
default y
config DFS_FD_MAX
int "The maximal number of opened files"
default 16
choice
prompt "The version of DFS"
default RT_USING_DFS_V2 if RT_USING_SMART
config RT_USING_DFS_V2
bool "DFS v2.0"
select RT_USING_DEVICE_OPS
endchoice
config RT_USING_DFS_ELMFAT
bool "Enable elm-chan fatfs"
default n
help
FatFs is a generic FAT/exFAT file system module for small embedded systems.
if RT_USING_DFS_ELMFAT
menu "elm-chan's FatFs, Generic FAT Filesystem Module"
config RT_DFS_ELM_CODE_PAGE
int "OEM code page"
default 437
config RT_DFS_ELM_WORD_ACCESS
bool "Using RT_DFS_ELM_WORD_ACCESS"
default y
choice
prompt "Support long file name"
default RT_DFS_ELM_USE_LFN_3
config RT_DFS_ELM_USE_LFN_0
bool "0: LFN disable"
config RT_DFS_ELM_USE_LFN_1
bool "1: LFN with static LFN working buffer"
config RT_DFS_ELM_USE_LFN_2
bool "2: LFN with dynamic LFN working buffer on the stack"
config RT_DFS_ELM_USE_LFN_3
bool "3: LFN with dynamic LFN working buffer on the heap"
endchoice
config RT_DFS_ELM_USE_LFN
int
default 0 if RT_DFS_ELM_USE_LFN_0
default 1 if RT_DFS_ELM_USE_LFN_1
default 2 if RT_DFS_ELM_USE_LFN_2
default 3 if RT_DFS_ELM_USE_LFN_3
choice
prompt "Support unicode for long file name"
default RT_DFS_ELM_LFN_UNICODE_0
config RT_DFS_ELM_LFN_UNICODE_0
bool "0: ANSI/OEM in current CP (TCHAR = char)"
config RT_DFS_ELM_LFN_UNICODE_1
bool "1: Unicode in UTF-16 (TCHAR = WCHAR)"
config RT_DFS_ELM_LFN_UNICODE_2
bool "2: Unicode in UTF-8 (TCHAR = char)"
config RT_DFS_ELM_LFN_UNICODE_3
bool "3: Unicode in UTF-32 (TCHAR = DWORD)"
endchoice
config RT_DFS_ELM_LFN_UNICODE
int
default 0 if RT_DFS_ELM_LFN_UNICODE_0
default 1 if RT_DFS_ELM_LFN_UNICODE_1
default 2 if RT_DFS_ELM_LFN_UNICODE_2
default 3 if RT_DFS_ELM_LFN_UNICODE_3
config RT_DFS_ELM_MAX_LFN
int "Maximal size of file name length"
range 12 255
default 255
config RT_DFS_ELM_DRIVES
int "Number of volumes (logical drives) to be used."
default 2
config RT_DFS_ELM_MAX_SECTOR_SIZE
int "Maximum sector size to be handled."
default 512
help
If you use some spi nor flash for fatfs, please set this the erase sector size, for example 4096.
config RT_DFS_ELM_USE_ERASE
bool "Enable sector erase feature"
default n
config RT_DFS_ELM_REENTRANT
bool "Enable the reentrancy (thread safe) of the FatFs module"
default y
config RT_DFS_ELM_MUTEX_TIMEOUT
int "Timeout of thread-safe protection mutex"
range 0 1000000
default 3000
depends on RT_DFS_ELM_REENTRANT
config RT_DFS_ELM_USE_EXFAT
bool "Enable RT_DFS_ELM_USE_EXFAT"
default n
depends on RT_DFS_ELM_USE_LFN >= 1
endmenu
endif
config RT_USING_DFS_DEVFS
bool "Using devfs for device objects"
default y
menuconfig RT_USING_DFS_ROMFS
bool "Enable ReadOnly file system on flash"
default n
if RT_USING_DFS_ROMFS
config RT_USING_DFS_ROMFS_USER_ROOT
bool "Use user's romfs root"
depends on RT_USING_DFS_V1
default n
endif
if RT_USING_SMART
config RT_USING_DFS_PTYFS
bool "Using Pseudo-Teletype Filesystem (UNIX98 PTY)"
depends on RT_USING_DFS_DEVFS
default y
config RT_USING_DFS_PROCFS
bool "Enable proc file system"
default y
endif
config RT_USING_DFS_CROMFS
bool "Enable ReadOnly compressed file system on flash"
default n
# select PKG_USING_ZLIB
config RT_USING_DFS_TMPFS
bool "Enable TMP file system"
default y if RT_USING_SMART
default n
config RT_USING_DFS_MQUEUE
bool "Enable MQUEUE file system"
select RT_USING_DEV_BUS
default y if RT_USING_SMART
default n
if RT_USING_DFS_V2
config RT_USING_PAGECACHE
bool "Enable page cache"
default y if RT_USING_SMART
depends on RT_USING_SMART
if RT_USING_PAGECACHE
menu "page cache config"
config RT_PAGECACHE_COUNT
int "page cache max total pages."
default 4096
config RT_PAGECACHE_ASPACE_COUNT
int "aspace max active pages."
default 1024
config RT_PAGECACHE_PRELOAD
int "max pre load pages."
default 4
config RT_PAGECACHE_HASH_NR
int "page cache hash size."
default 1024
config RT_PAGECACHE_GC_WORK_LEVEL
int "page cache gc work trigger min percentage, default 90%."
default 90
config RT_PAGECACHE_GC_STOP_LEVEL
int "page cache gc to min percentage, default 70%."
default 70
endmenu
endif
endif
endif
endmenu
+15
View File
@@ -0,0 +1,15 @@
# RT-Thread building script for bridge
import os
from building import *
cwd = GetCurrentDir()
objs = []
list = os.listdir(cwd)
for d in list:
path = os.path.join(cwd, d)
if os.path.isfile(os.path.join(path, 'SConscript')):
objs = objs + SConscript(os.path.join(d, 'SConscript'))
Return('objs')
@@ -0,0 +1,22 @@
from building import *
import os
# The set of source files associated with this SConscript file.
src = Glob('src/*.c') + Glob('src/*.cpp')
cwd = GetCurrentDir()
CPPPATH = [cwd + "/include"]
if not GetDepend('RT_USING_SMART'):
SrcRemove(src, ['src/dfs_file_mmap.c'])
group = DefineGroup('Filesystem', src, depend = ['RT_USING_DFS', 'RT_USING_DFS_V2'], CPPPATH = CPPPATH)
if GetDepend('RT_USING_DFS') and GetDepend('RT_USING_DFS_V2'):
# search in the file system implementation
list = os.listdir(cwd)
for item in list:
if os.path.isfile(os.path.join(cwd, item, 'SConscript')):
group = group + SConscript(os.path.join(item, 'SConscript'))
Return('group')
@@ -0,0 +1,4 @@
# files format check exclude path, please follow the instructions below to modify;
dir_path:
- elmfat
@@ -0,0 +1,15 @@
# RT-Thread building script for bridge
import os
from building import *
cwd = GetCurrentDir()
objs = []
list = os.listdir(cwd)
for d in list:
path = os.path.join(cwd, d)
if os.path.isfile(os.path.join(path, 'SConscript')):
objs = objs + SConscript(os.path.join(d, 'SConscript'))
Return('objs')
@@ -0,0 +1,11 @@
# RT-Thread building script for component
from building import *
cwd = GetCurrentDir()
src = Glob('*.c')
CPPPATH = [cwd]
group = DefineGroup('Filesystem', src, depend = ['RT_USING_DFS','RT_USING_DFS_CROMFS'], CPPPATH = CPPPATH)
Return('group')
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,19 @@
/*
* Copyright (c) 2006-2020, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2020/08/21 ShaoJinchun firset version
*/
#ifndef __DFS_CROMFS_H__
#define __DFS_CROMFS_H__
#include <stdint.h>
int dfs_cromfs_init(void);
uint8_t *cromfs_get_partition_data(uint32_t *len);
#endif /*__DFS_CROMFS_H__*/
@@ -0,0 +1,11 @@
# RT-Thread building script for component
from building import *
cwd = GetCurrentDir()
src = Glob('*.c')
CPPPATH = [cwd]
group = DefineGroup('Filesystem', src, depend = ['RT_USING_DFS', 'RT_USING_DFS_DEVFS'], CPPPATH = CPPPATH)
Return('group')
@@ -0,0 +1,555 @@
/*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2018-02-11 Bernard Ignore O_CREAT flag in open.
*/
#include <rthw.h>
#include <rtdbg.h>
#include <rtdevice.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/unistd.h>
#include <dfs.h>
#include <dfs_fs.h>
#include <dfs_file.h>
#include <dfs_dentry.h>
#include <dfs_mnt.h>
static int dfs_devfs_open(struct dfs_file *file)
{
int ret = RT_EOK;
RT_ASSERT(file != RT_NULL);
RT_ASSERT(file->vnode->ref_count > 0);
if (file->vnode->ref_count > 1)
{
if (file->vnode->type == FT_DIRECTORY
&& !(file->flags & O_DIRECTORY))
{
return -ENOENT;
}
file->fpos = 0;
}
if (!S_ISDIR(file->vnode->mode))
{
rt_device_t device = RT_NULL;
struct dfs_dentry *de = file->dentry;
char *device_name = rt_malloc(DFS_PATH_MAX);
if (!device_name)
{
return -ENOMEM;
}
/* skip `/dev` */
rt_snprintf(device_name, DFS_PATH_MAX, "%s%s", de->mnt->fullpath + sizeof("/dev") - 1, de->pathname);
device = rt_device_find(device_name + 1);
if (device)
{
file->vnode->data = device;
#ifdef RT_USING_POSIX_DEVIO
if (device->fops && device->fops->open)
{
ret = device->fops->open(file);
if (ret == RT_EOK || ret == -RT_ENOSYS)
{
ret = RT_EOK;
}
}
else if (device->ops && file->vnode->ref_count == 1)
#else
if (device->ops && file->vnode->ref_count == 1)
#endif /* RT_USING_POSIX_DEVIO */
{
ret = rt_device_open(device, RT_DEVICE_OFLAG_RDWR);
if (ret == RT_EOK || ret == -RT_ENOSYS)
{
ret = RT_EOK;
}
}
}
rt_free(device_name);
}
return ret;
}
static int dfs_devfs_close(struct dfs_file *file)
{
int ret = RT_EOK;
rt_device_t device;
RT_ASSERT(file != RT_NULL);
RT_ASSERT(file->vnode->ref_count > 0);
if (file->vnode && file->vnode->data)
{
/* get device handler */
device = (rt_device_t)file->vnode->data;
#ifdef RT_USING_POSIX_DEVIO
if (device->fops && device->fops->close)
{
ret = device->fops->close(file);
}
else if (file->vnode->ref_count == 1)
#else
if (device->ops && file->vnode->ref_count == 1)
#endif /* RT_USING_POSIX_DEVIO */
{
/* close device handler */
ret = rt_device_close(device);
}
}
return ret;
}
static rt_ubase_t _get_unit_shift(rt_device_t device)
{
rt_ubase_t shift = 0;
/**
* transfer unit size from POSIX RW(in bytes) to rt_device_R/W
* (block size for blk device, otherwise in bytes).
*/
if (device->type == RT_Device_Class_Block)
{
struct rt_device_blk_geometry geometry = {0};
/* default to 512 */
shift = 9;
if (!rt_device_control(device, RT_DEVICE_CTRL_BLK_GETGEOME, &geometry))
{
shift = __rt_ffs(geometry.block_size) - 1;
}
}
return shift;
}
static ssize_t dfs_devfs_read(struct dfs_file *file, void *buf, size_t count, off_t *pos)
{
ssize_t ret = -RT_EIO;
rt_device_t device;
RT_ASSERT(file != RT_NULL);
if (file->vnode && file->vnode->data)
{
/* get device handler */
device = (rt_device_t)file->vnode->data;
#ifdef RT_USING_POSIX_DEVIO
if (device->fops && device->fops->read)
{
ret = device->fops->read(file, buf, count, pos);
}
else
#else
if (device->ops)
#endif /* RT_USING_POSIX_DEVIO */
{
rt_ubase_t shift = _get_unit_shift(device);
ret = rt_device_read(device, *pos, buf, count >> shift);
if (ret > 0)
{
ret <<= shift;
*pos += ret;
}
}
}
return ret;
}
static ssize_t dfs_devfs_write(struct dfs_file *file, const void *buf, size_t count, off_t *pos)
{
ssize_t ret = -RT_EIO;
rt_device_t device;
RT_ASSERT(file != RT_NULL);
if(file->vnode->data)
{
/* get device handler */
device = (rt_device_t)file->vnode->data;
if ((file->dentry->pathname[0] == '/') && (file->dentry->pathname[1] == '\0'))
return -RT_ENOSYS;
#ifdef RT_USING_POSIX_DEVIO
if (device->fops && device->fops->write)
{
ret = device->fops->write(file, buf, count, pos);
}
else
#else
if (device->ops)
#endif /* RT_USING_POSIX_DEVIO */
{
rt_ubase_t shift = _get_unit_shift(device);
/* read device data */
ret = rt_device_write(device, *pos, buf, count >> shift);
if (ret > 0)
{
ret <<= shift;
*pos += ret;
}
}
}
return ret;
}
static int dfs_devfs_ioctl(struct dfs_file *file, int cmd, void *args)
{
int ret = RT_EOK;
rt_device_t device;
RT_ASSERT(file != RT_NULL);
if (file->vnode && file->vnode->data)
{
/* get device handler */
device = (rt_device_t)file->vnode->data;
if ((file->dentry->pathname[0] == '/') && (file->dentry->pathname[1] == '\0'))
return -RT_ENOSYS;
#ifdef RT_USING_POSIX_DEVIO
if (device->fops && device->fops->ioctl)
{
ret = device->fops->ioctl(file, cmd, args);
}
else
#endif /* RT_USING_POSIX_DEVIO */
{
ret = rt_device_control(device, cmd, args);
}
}
return ret;
}
static int dfs_devfs_getdents(struct dfs_file *file, struct dirent *dirp, uint32_t count)
{
int ret = -RT_ENOSYS;
RT_ASSERT(file != RT_NULL);
return ret;
}
static int dfs_devfs_poll(struct dfs_file *file, struct rt_pollreq *req)
{
int mask = 0;
rt_device_t device;
RT_ASSERT(file != RT_NULL);
if (file->vnode && file->vnode->data)
{
/* get device handler */
device = (rt_device_t)file->vnode->data;
#ifdef RT_USING_POSIX_DEVIO
if (device->fops && device->fops->poll)
{
mask = device->fops->poll(file, req);
}
#endif /* RT_USING_POSIX_DEVIO */
}
return mask;
}
static int dfs_devfs_flush(struct dfs_file *file)
{
int ret = RT_EOK;
rt_device_t device;
RT_ASSERT(file != RT_NULL);
if (file->vnode && file->vnode->data)
{
/* get device handler */
device = (rt_device_t)file->vnode->data;
#ifdef RT_USING_POSIX_DEVIO
if (device->fops && device->fops->flush)
{
ret = device->fops->flush(file);
}
#endif /* RT_USING_POSIX_DEVIO */
}
return ret;
}
static off_t dfs_devfs_lseek(struct dfs_file *file, off_t offset, int wherece)
{
off_t ret = -EPERM;
rt_device_t device;
RT_ASSERT(file != RT_NULL);
if (file->vnode && file->vnode->data)
{
/* get device handler */
device = (rt_device_t)file->vnode->data;
#ifdef RT_USING_POSIX_DEVIO
if (device->fops && device->fops->lseek)
{
ret = device->fops->lseek(file, offset, wherece);
}
#endif /* RT_USING_POSIX_DEVIO */
}
return ret;
}
static int dfs_devfs_truncate(struct dfs_file *file, off_t offset)
{
int ret = RT_EOK;
rt_device_t device;
RT_ASSERT(file != RT_NULL);
if (file->vnode && file->vnode->data)
{
/* get device handler */
device = (rt_device_t)file->vnode->data;
#ifdef RT_USING_POSIX_DEVIO
if (device->fops && device->fops->truncate)
{
ret = device->fops->truncate(file, offset);
}
#endif /* RT_USING_POSIX_DEVIO */
}
return ret;
}
static int dfs_devfs_mmap(struct dfs_file *file, struct lwp_avl_struct *mmap)
{
int ret = RT_EOK;
rt_device_t device;
RT_ASSERT(file != RT_NULL);
if (file->vnode && file->vnode->data)
{
/* get device handler */
device = (rt_device_t)file->vnode->data;
#ifdef RT_USING_POSIX_DEVIO
if (device->fops && device->fops->mmap)
{
ret = device->fops->mmap(file, mmap);
}
#endif /* RT_USING_POSIX_DEVIO */
}
return ret;
}
static int dfs_devfs_lock(struct dfs_file *file, struct file_lock *flock)
{
int ret = RT_EOK;
rt_device_t device;
RT_ASSERT(file != RT_NULL);
if (file->vnode && file->vnode->data)
{
/* get device handler */
device = (rt_device_t)file->vnode->data;
#ifdef RT_USING_POSIX_DEVIO
if (device->fops && device->fops->lock)
{
ret = device->fops->lock(file, flock);
}
#endif /* RT_USING_POSIX_DEVIO */
}
return ret;
}
static int dfs_devfs_flock(struct dfs_file *file, int operation, struct file_lock *flock)
{
int ret = RT_EOK;
rt_device_t device;
RT_ASSERT(file != RT_NULL);
if (file->vnode && file->vnode->data)
{
/* get device handler */
device = (rt_device_t)file->vnode->data;
#ifdef RT_USING_POSIX_DEVIO
if (device->fops && device->fops->flock)
{
ret = device->fops->flock(file, operation, flock);
}
#endif /* RT_USING_POSIX_DEVIO */
}
return ret;
}
static const struct dfs_file_ops _dev_fops =
{
.open = dfs_devfs_open,
.close = dfs_devfs_close,
.read = dfs_devfs_read,
.write = dfs_devfs_write,
.ioctl = dfs_devfs_ioctl,
.getdents = dfs_devfs_getdents,
.poll = dfs_devfs_poll,
.flush = dfs_devfs_flush,
.lseek = dfs_devfs_lseek,
.truncate = dfs_devfs_truncate,
.mmap = dfs_devfs_mmap,
.lock = dfs_devfs_lock,
.flock = dfs_devfs_flock,
};
const struct dfs_file_ops *dfs_devfs_fops(void)
{
return &_dev_fops;
}
mode_t dfs_devfs_device_to_mode(struct rt_device *device)
{
mode_t mode = 0;
switch (device->type)
{
case RT_Device_Class_Char:
mode = S_IFCHR | 0666;
break;
case RT_Device_Class_Block:
mode = S_IFBLK | 0666;
break;
case RT_Device_Class_Pipe:
mode = S_IFIFO | 0666;
break;
default:
mode = S_IFCHR | 0666;
break;
}
return mode;
}
static void dfs_devfs_mkdir(const char *fullpath, mode_t mode)
{
int len = rt_strlen(fullpath);
char *path = (char *)rt_malloc(len + 1);
if (path)
{
int index = len - 1;
rt_strcpy(path, fullpath);
if (path[index] == '/')
{
path[index] = '\0';
index --;
}
while (path[index] != '/' && index >= 0)
{
index --;
}
path[index] = '\0';
if (index > 0 && access(path, 0) != 0)
{
int i = 0;
if (path[i] == '/')
{
i ++;
}
while (index > i)
{
if (path[i] == '/')
{
path[i] = '\0';
mkdir(path, mode);
path[i] = '/';
}
i ++;
}
mkdir(path, mode);
}
}
}
void dfs_devfs_device_add(rt_device_t device)
{
int fd;
char path[512];
if (device)
{
rt_snprintf(path, 512, "/dev/%s", device->parent.name);
if (access(path, 0) != 0)
{
mode_t mode = dfs_devfs_device_to_mode(device);
dfs_devfs_mkdir(path, mode);
fd = open(path, O_RDWR | O_CREAT, mode);
if (fd >= 0)
{
close(fd);
}
}
}
}
int dfs_devfs_update(void)
{
int count = rt_object_get_length(RT_Object_Class_Device);
if (count > 0)
{
rt_device_t *devices = rt_malloc(count * sizeof(rt_device_t));
if (devices)
{
rt_object_get_pointers(RT_Object_Class_Device, (rt_object_t *)devices, count);
for (int index = 0; index < count; index ++)
{
dfs_devfs_device_add(devices[index]);
}
rt_free(devices);
}
}
return count;
}
@@ -0,0 +1,18 @@
/*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#ifndef __DEVICE_FS_H__
#define __DEVICE_FS_H__
const struct dfs_file_ops *dfs_devfs_fops(void);
mode_t dfs_devfs_device_to_mode(struct rt_device *device);
void dfs_devfs_device_add(rt_device_t device);
int dfs_devfs_update(void);
#endif
@@ -0,0 +1,664 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2022-10-24 flybreak the first version
* 2023-02-01 xqyjlj fix cannot open the same file repeatedly in 'w' mode
* 2023-09-20 zmq810150896 adds truncate functionality and standardized unlink adaptations
* 2023-12-02 Shell Support of dynamic device
*/
#include <rthw.h>
#include <rtthread.h>
#include <dfs.h>
#include <dfs_fs.h>
#include <dfs_dentry.h>
#include <dfs_file.h>
#include <dfs_mnt.h>
#include <dfs_vfs.h>
#include <devfs.h>
#include <unistd.h>
#define TMPFS_MAGIC 0x0B0B0B0B
#define TMPFS_TYPE_FILE 0x00
#define TMPFS_TYPE_DIR 0x01
#define TMPFS_TYPE_DYN_DEV 0x02 /* dynamic device */
struct devtmpfs_sb;
struct devtmpfs_file
{
char name[DIRENT_NAME_MAX]; /* file name */
rt_uint32_t type; /* file type */
struct dfs_vfs_node node; /* file node in the devtmpfs */
struct devtmpfs_sb *sb; /* superblock ptr */
rt_uint32_t mode;
char *link;
};
struct devtmpfs_sb
{
rt_uint32_t magic; /* TMPFS_MAGIC */
struct devtmpfs_file root; /* root dir */
rt_size_t df_size; /* df size */
struct rt_spinlock lock; /* tmpfs lock */
};
static struct dfs_file_ops _default_fops = { 0 };
static int _path_separate(const char *path, char *parent_path, char *file_name)
{
const char *path_p, *path_q;
RT_ASSERT(path[0] == '/');
file_name[0] = '\0';
path_p = path_q = &path[1];
__next_dir:
while (*path_q != '/' && *path_q != '\0')
{
path_q++;
}
if (path_q != path_p) /*sub dir*/
{
if (*path_q != '\0')
{
path_q++;
path_p = path_q;
goto __next_dir;
}
else /* Last level dir */
{
rt_memcpy(parent_path, path, path_p - path - 1);
parent_path[path_p - path - 1] = '\0';
rt_memcpy(file_name, path_p, path_q - path_p);
file_name[path_q - path_p] = '\0';
}
}
if (parent_path[0] == 0)
{
parent_path[0] = '/';
parent_path[1] = '\0';
}
//LOG_D("parent_path: %s", parent_path);
//LOG_D("file_name: %s", file_name);
return 0;
}
static int _get_subdir(const char *path, char *name)
{
const char *subpath = path;
while (*subpath == '/' && *subpath)
subpath ++;
while (*subpath != '/' && *subpath)
{
*name = *subpath;
name ++;
subpath ++;
}
return 0;
}
#if 0
static int _free_subdir(struct devtmpfs_file *dfile)
{
struct devtmpfs_file *file, *tmp;
struct devtmpfs_sb *superblock;
RT_ASSERT(dfile->type == TMPFS_TYPE_DIR);
dfs_vfs_for_each_subnode(file, tmp, dfile, node)
{
if (file->type == TMPFS_TYPE_DIR)
{
_free_subdir(file);
}
if (file->link)
{
rt_free(file->link);
}
superblock = file->sb;
RT_ASSERT(superblock);
rt_spin_lock(&superblock->lock);
dfs_vfs_remove_node(&file->node);
rt_spin_unlock(&superblock->lock);
rt_free(file);
}
return 0;
}
#endif
static int devtmpfs_mount(struct dfs_mnt *mnt, unsigned long rwflag, const void *data)
{
struct devtmpfs_sb *superblock;
superblock = rt_calloc(1, sizeof(struct devtmpfs_sb));
if (superblock)
{
superblock->df_size = sizeof(struct devtmpfs_sb);
superblock->magic = TMPFS_MAGIC;
superblock->root.name[0] = '/';
superblock->root.sb = superblock;
superblock->root.type = TMPFS_TYPE_DIR;
superblock->root.mode = S_IFDIR | (S_IRUSR | S_IRGRP | S_IROTH) | (S_IXUSR | S_IXGRP | S_IXOTH);
dfs_vfs_init_node(&superblock->root.node);
rt_spin_lock_init(&superblock->lock);
mnt->data = superblock;
}
else
{
return -RT_ERROR;
}
return RT_EOK;
}
static int devtmpfs_unmount(struct dfs_mnt *mnt)
{
#if 0
struct devtmpfs_sb *superblock;
/* FIXME: don't unmount on busy. */
superblock = (struct devtmpfs_sb *)mnt->data;
RT_ASSERT(superblock != NULL);
mnt->data = NULL;
_free_subdir(&(superblock->root));
rt_free(superblock);
#endif
return -RT_ERROR;
}
static struct devtmpfs_file *devtmpfs_file_lookup(struct devtmpfs_sb *superblock, const char *path)
{
const char *subpath, *curpath, *filename = RT_NULL;
char subdir_name[DIRENT_NAME_MAX];
struct devtmpfs_file *file, *curfile, *tmp;
subpath = path;
while (*subpath == '/' && *subpath)
subpath ++;
if (! *subpath) /* is root directory */
{
return &(superblock->root);
}
curpath = subpath;
curfile = &superblock->root;
find_subpath:
while (*subpath != '/' && *subpath)
subpath ++;
if (! *subpath) /* is last directory */
filename = curpath;
else
subpath ++; /* skip '/' */
memset(subdir_name, 0, DIRENT_NAME_MAX);
_get_subdir(curpath, subdir_name);
rt_spin_lock(&superblock->lock);
dfs_vfs_for_each_subnode(file, tmp, curfile, node)
{
if (filename) /* find file */
{
if (rt_strcmp(file->name, filename) == 0)
{
rt_spin_unlock(&superblock->lock);
return file;
}
}
else if (rt_strcmp(file->name, subdir_name) == 0)
{
curpath = subpath;
curfile = file;
rt_spin_unlock(&superblock->lock);
goto find_subpath;
}
}
rt_spin_unlock(&superblock->lock);
/* not found */
return NULL;
}
static int devtmpfs_statfs(struct dfs_mnt *mnt, struct statfs *buf)
{
struct devtmpfs_sb *superblock;
RT_ASSERT(mnt != NULL);
RT_ASSERT(buf != NULL);
superblock = (struct devtmpfs_sb *)mnt->data;
RT_ASSERT(superblock != NULL);
buf->f_bsize = 512;
buf->f_blocks = (superblock->df_size + 511) / 512;
buf->f_bfree = 1;
buf->f_bavail = buf->f_bfree;
return RT_EOK;
}
static int devtmpfs_stat(struct dfs_dentry *dentry, struct stat *st)
{
struct dfs_vnode *vnode;
if (dentry && dentry->vnode)
{
vnode = dentry->vnode;
st->st_dev = (dev_t)(long)(dentry->mnt->dev_id);
st->st_ino = (ino_t)dfs_dentry_full_path_crc32(dentry);
st->st_gid = vnode->gid;
st->st_uid = vnode->uid;
st->st_mode = vnode->mode;
st->st_nlink = vnode->nlink;
st->st_size = vnode->size;
st->st_mtim.tv_nsec = vnode->mtime.tv_nsec;
st->st_mtim.tv_sec = vnode->mtime.tv_sec;
st->st_ctim.tv_nsec = vnode->ctime.tv_nsec;
st->st_ctim.tv_sec = vnode->ctime.tv_sec;
st->st_atim.tv_nsec = vnode->atime.tv_nsec;
st->st_atim.tv_sec = vnode->atime.tv_sec;
}
return RT_EOK;
}
static int devtmpfs_getdents(struct dfs_file *file, struct dirent *dirp, uint32_t count)
{
rt_size_t index, end;
struct dirent *d;
struct devtmpfs_file *d_file, *n_file = RT_NULL, *tmp;
struct devtmpfs_sb *superblock;
RT_ASSERT(file);
RT_ASSERT(file->dentry);
RT_ASSERT(file->dentry->mnt);
superblock = (struct devtmpfs_sb *)file->dentry->mnt->data;
RT_ASSERT(superblock);
d_file = devtmpfs_file_lookup(superblock, file->dentry->pathname);
if (d_file)
{
/* make integer count */
count = (count / sizeof(struct dirent));
if (count == 0)
{
return -EINVAL;
}
end = file->fpos + count;
index = 0;
count = 0;
dfs_vfs_for_each_subnode(n_file, tmp, d_file, node)
{
if (index >= (rt_size_t)file->fpos)
{
d = dirp + count;
if (n_file->type == TMPFS_TYPE_FILE)
{
d->d_type = DT_REG;
}
if (n_file->type == TMPFS_TYPE_DIR)
{
d->d_type = DT_DIR;
}
d->d_reclen = (rt_uint16_t)sizeof(struct dirent);
rt_strncpy(d->d_name, n_file->name, DIRENT_NAME_MAX);
d->d_namlen = rt_strlen(d->d_name);
count += 1;
file->fpos += 1;
}
index += 1;
if (index >= end)
{
break;
}
}
}
return count * sizeof(struct dirent);
}
static int devtmpfs_symlink(struct dfs_dentry *parent_dentry, const char *target, const char *linkpath)
{
int ret = RT_EOK;
struct devtmpfs_file *p_file, *l_file;
struct devtmpfs_sb *superblock;
RT_ASSERT(parent_dentry);
RT_ASSERT(parent_dentry->mnt);
superblock = (struct devtmpfs_sb *)parent_dentry->mnt->data;
RT_ASSERT(superblock);
p_file = devtmpfs_file_lookup(superblock, parent_dentry->pathname);
if (p_file)
{
l_file = (struct devtmpfs_file *)rt_calloc(1, sizeof(struct devtmpfs_file));
if (l_file)
{
superblock->df_size += sizeof(struct devtmpfs_file);
strncpy(l_file->name, linkpath, DIRENT_NAME_MAX - 1);
dfs_vfs_init_node(&l_file->node);
l_file->sb = superblock;
l_file->type = TMPFS_TYPE_FILE;
l_file->mode = p_file->mode;
l_file->mode &= ~S_IFMT;
l_file->mode |= S_IFLNK;
l_file->link = rt_strdup(target);
rt_spin_lock(&superblock->lock);
dfs_vfs_append_node(&p_file->node, &l_file->node);
rt_spin_unlock(&superblock->lock);
}
}
return ret;
}
static int devtmpfs_readlink(struct dfs_dentry *dentry, char *buf, int len)
{
int ret = 0;
struct devtmpfs_file *d_file;
struct devtmpfs_sb *superblock;
RT_ASSERT(dentry);
RT_ASSERT(dentry->mnt);
superblock = (struct devtmpfs_sb *)dentry->mnt->data;
RT_ASSERT(superblock);
d_file = devtmpfs_file_lookup(superblock, dentry->pathname);
if (d_file)
{
if (d_file->link)
{
if (d_file->type == TMPFS_TYPE_DYN_DEV)
{
rt_device_t device = (void *)d_file->link;
buf[0] = '\0';
ret = device->readlink(device, buf, len);
if (ret == 0)
{
buf[len - 1] = '\0';
ret = rt_strlen(buf);
}
else
{
ret = 0;
}
}
else
{
rt_strncpy(buf, (const char *)d_file->link, len);
buf[len - 1] = '\0';
ret = rt_strlen(buf);
}
}
}
return ret;
}
static int devtmpfs_unlink(struct dfs_dentry *dentry)
{
struct devtmpfs_file *d_file;
struct devtmpfs_sb *superblock;
RT_ASSERT(dentry);
RT_ASSERT(dentry->mnt);
superblock = (struct devtmpfs_sb *)dentry->mnt->data;
RT_ASSERT(superblock);
d_file = devtmpfs_file_lookup(superblock, dentry->pathname);
if (d_file)
{
if (d_file->link && d_file->type != TMPFS_TYPE_DYN_DEV)
{
rt_free(d_file->link);
}
rt_spin_lock(&superblock->lock);
dfs_vfs_remove_node(&d_file->node);
rt_spin_unlock(&superblock->lock);
rt_free(d_file);
}
return RT_EOK;
}
static int devtmpfs_setattr(struct dfs_dentry *dentry, struct dfs_attr *attr)
{
struct devtmpfs_file *d_file;
struct devtmpfs_sb *superblock;
RT_ASSERT(dentry);
RT_ASSERT(dentry->mnt);
superblock = (struct devtmpfs_sb *)dentry->mnt->data;
RT_ASSERT(superblock);
d_file = devtmpfs_file_lookup(superblock, dentry->pathname);
if (d_file)
{
d_file->mode &= ~0xFFF;
d_file->mode |= attr->st_mode & 0xFFF;
return RT_EOK;
}
return -RT_ERROR;
}
static struct dfs_vnode *devtmpfs_create_vnode(struct dfs_dentry *dentry, int type, mode_t mode)
{
struct dfs_vnode *vnode = RT_NULL;
struct devtmpfs_sb *superblock;
struct devtmpfs_file *d_file, *p_file;
char parent_path[DFS_PATH_MAX], file_name[DIRENT_NAME_MAX];
if (dentry == NULL || dentry->mnt == NULL || dentry->mnt->data == NULL)
{
return NULL;
}
superblock = (struct devtmpfs_sb *)dentry->mnt->data;
RT_ASSERT(superblock != NULL);
vnode = dfs_vnode_create();
if (vnode)
{
/* find parent file */
_path_separate(dentry->pathname, parent_path, file_name);
if (file_name[0] == '\0') /* it's root dir */
{
dfs_vnode_destroy(vnode);
return NULL;
}
/* open parent directory */
p_file = devtmpfs_file_lookup(superblock, parent_path);
if (p_file == NULL)
{
dfs_vnode_destroy(vnode);
return NULL;
}
/* create a file entry */
d_file = (struct devtmpfs_file *)rt_calloc(1, sizeof(struct devtmpfs_file));
if (d_file == NULL)
{
dfs_vnode_destroy(vnode);
return NULL;
}
superblock->df_size += sizeof(struct devtmpfs_file);
strncpy(d_file->name, file_name, DIRENT_NAME_MAX);
dfs_vfs_init_node(&d_file->node);
d_file->sb = superblock;
vnode->nlink = 1;
vnode->size = 0;
vnode->mode = mode;
vnode->mnt = dentry->mnt;
vnode->fops = &_default_fops;
if (type == FT_DIRECTORY)
{
d_file->type = TMPFS_TYPE_DIR;
vnode->type = FT_DIRECTORY;
vnode->mode &= ~S_IFMT;
vnode->mode |= S_IFDIR;
}
else
{
d_file->type = TMPFS_TYPE_FILE;
vnode->type = FT_DEVICE;
}
d_file->mode = vnode->mode;
rt_spin_lock(&superblock->lock);
dfs_vfs_append_node(&p_file->node, &d_file->node);
rt_spin_unlock(&superblock->lock);
}
return vnode;
}
static struct dfs_vnode *devtmpfs_lookup(struct dfs_dentry *dentry)
{
struct dfs_vnode *vnode = RT_NULL;
struct devtmpfs_sb *superblock;
struct devtmpfs_file *d_file;
if (dentry == NULL || dentry->mnt == NULL || dentry->mnt->data == NULL)
{
return NULL;
}
superblock = (struct devtmpfs_sb *)dentry->mnt->data;
d_file = devtmpfs_file_lookup(superblock, dentry->pathname);
if (d_file)
{
vnode = dfs_vnode_create();
if (vnode)
{
vnode->nlink = 1;
vnode->size = 0;
vnode->mnt = dentry->mnt;
vnode->fops = &_default_fops;
vnode->mode = d_file->mode;
if (d_file->type == TMPFS_TYPE_DIR)
{
vnode->type = FT_DIRECTORY;
}
else if (d_file->link)
{
vnode->type = FT_SYMLINK;
}
else
{
vnode->type = FT_DEVICE;
}
}
}
else
{
rt_device_t device = RT_NULL;
device = rt_device_find(&dentry->pathname[1]);
if (device)
{
vnode = devtmpfs_create_vnode(dentry, FT_REGULAR, dfs_devfs_device_to_mode(device));
if (device->flag & RT_DEVICE_FLAG_DYNAMIC)
{
d_file = devtmpfs_file_lookup(superblock, dentry->pathname);
d_file->type = TMPFS_TYPE_DYN_DEV;
d_file->link = (char *)device;
}
}
}
return vnode;
}
static int devtmpfs_free_vnode(struct dfs_vnode *vnode)
{
return RT_EOK;
}
static const struct dfs_filesystem_ops _devtmpfs_ops =
{
.name = "devtmpfs",
.flags = DFS_FS_FLAG_DEFAULT,
.default_fops = &_default_fops,
.mount = devtmpfs_mount,
.umount = devtmpfs_unmount,
.symlink = devtmpfs_symlink,
.readlink = devtmpfs_readlink,
.unlink = devtmpfs_unlink,
.setattr = devtmpfs_setattr,
.statfs = devtmpfs_statfs,
.stat = devtmpfs_stat,
.lookup = devtmpfs_lookup,
.create_vnode = devtmpfs_create_vnode,
.free_vnode = devtmpfs_free_vnode
};
static struct dfs_filesystem_type _devtmpfs =
{
.fs_ops = &_devtmpfs_ops,
};
int dfs_devtmpfs_init(void)
{
_default_fops = *dfs_devfs_fops();
_default_fops.getdents = devtmpfs_getdents;
/* register file system */
dfs_register(&_devtmpfs);
dfs_mount(RT_NULL, "/dev", "devtmpfs", 0, RT_NULL);
dfs_devfs_update();
return 0;
}
INIT_COMPONENT_EXPORT(dfs_devtmpfs_init);
@@ -0,0 +1,11 @@
# Available style options are described in https://clang.llvm.org/docs/ClangFormatStyleOptions.html
#
# An easy way to create the .clang-format file is:
#
# clang-format -style=llvm -dump-config > .clang-format
#
---
Language: Cpp
DisableFormat: true
---
@@ -0,0 +1,10 @@
# files format check exclude path, please follow the instructions below to modify;
# If you need to exclude an entire folder, add the folder path in dir_path;
# If you need to exclude a file, add the path to the file in file_path.
file_path:
- diskio.h
- ff.c
- ff.h
- ffconf.h
- ffunicode.c
@@ -0,0 +1,369 @@
----------------------------------------------------------------------------
Revision history of FatFs module
----------------------------------------------------------------------------
R0.00 (February 26, 2006)
Prototype.
R0.01 (April 29, 2006)
The first release.
R0.02 (June 01, 2006)
Added FAT12 support.
Removed unbuffered mode.
Fixed a problem on small (<32M) partition.
R0.02a (June 10, 2006)
Added a configuration option (_FS_MINIMUM).
R0.03 (September 22, 2006)
Added f_rename().
Changed option _FS_MINIMUM to _FS_MINIMIZE.
R0.03a (December 11, 2006)
Improved cluster scan algorithm to write files fast.
Fixed f_mkdir() creates incorrect directory on FAT32.
R0.04 (February 04, 2007)
Added f_mkfs().
Supported multiple drive system.
Changed some interfaces for multiple drive system.
Changed f_mountdrv() to f_mount().
R0.04a (April 01, 2007)
Supported multiple partitions on a physical drive.
Added a capability of extending file size to f_lseek().
Added minimization level 3.
Fixed an endian sensitive code in f_mkfs().
R0.04b (May 05, 2007)
Added a configuration option _USE_NTFLAG.
Added FSINFO support.
Fixed DBCS name can result FR_INVALID_NAME.
Fixed short seek (<= csize) collapses the file object.
R0.05 (August 25, 2007)
Changed arguments of f_read(), f_write() and f_mkfs().
Fixed f_mkfs() on FAT32 creates incorrect FSINFO.
Fixed f_mkdir() on FAT32 creates incorrect directory.
R0.05a (February 03, 2008)
Added f_truncate() and f_utime().
Fixed off by one error at FAT sub-type determination.
Fixed btr in f_read() can be mistruncated.
Fixed cached sector is not flushed when create and close without write.
R0.06 (April 01, 2008)
Added fputc(), fputs(), fprintf() and fgets().
Improved performance of f_lseek() on moving to the same or following cluster.
R0.07 (April 01, 2009)
Merged Tiny-FatFs as a configuration option. (_FS_TINY)
Added long file name feature. (_USE_LFN)
Added multiple code page feature. (_CODE_PAGE)
Added re-entrancy for multitask operation. (_FS_REENTRANT)
Added auto cluster size selection to f_mkfs().
Added rewind option to f_readdir().
Changed result code of critical errors.
Renamed string functions to avoid name collision.
R0.07a (April 14, 2009)
Septemberarated out OS dependent code on reentrant cfg.
Added multiple sector size feature.
R0.07c (June 21, 2009)
Fixed f_unlink() can return FR_OK on error.
Fixed wrong cache control in f_lseek().
Added relative path feature.
Added f_chdir() and f_chdrive().
Added proper case conversion to extended character.
R0.07e (November 03, 2009)
Septemberarated out configuration options from ff.h to ffconf.h.
Fixed f_unlink() fails to remove a sub-directory on _FS_RPATH.
Fixed name matching error on the 13 character boundary.
Added a configuration option, _LFN_UNICODE.
Changed f_readdir() to return the SFN with always upper case on non-LFN cfg.
R0.08 (May 15, 2010)
Added a memory configuration option. (_USE_LFN = 3)
Added file lock feature. (_FS_SHARE)
Added fast seek feature. (_USE_FASTSEEK)
Changed some types on the API, XCHAR->TCHAR.
Changed .fname in the FILINFO structure on Unicode cfg.
String functions support UTF-8 encoding files on Unicode cfg.
R0.08a (August 16, 2010)
Added f_getcwd(). (_FS_RPATH = 2)
Added sector erase feature. (_USE_ERASE)
Moved file lock semaphore table from fs object to the bss.
Fixed f_mkfs() creates wrong FAT32 volume.
R0.08b (January 15, 2011)
Fast seek feature is also applied to f_read() and f_write().
f_lseek() reports required table size on creating CLMP.
Extended format syntax of f_printf().
Ignores duplicated directory separators in given path name.
R0.09 (September 06, 2011)
f_mkfs() supports multiple partition to complete the multiple partition feature.
Added f_fdisk().
R0.09a (August 27, 2012)
Changed f_open() and f_opendir() reject null object pointer to avoid crash.
Changed option name _FS_SHARE to _FS_LOCK.
Fixed assertion failure due to OS/2 EA on FAT12/16 volume.
R0.09b (January 24, 2013)
Added f_setlabel() and f_getlabel().
R0.10 (October 02, 2013)
Added selection of character encoding on the file. (_STRF_ENCODE)
Added f_closedir().
Added forced full FAT scan for f_getfree(). (_FS_NOFSINFO)
Added forced mount feature with changes of f_mount().
Improved behavior of volume auto detection.
Improved write throughput of f_puts() and f_printf().
Changed argument of f_chdrive(), f_mkfs(), disk_read() and disk_write().
Fixed f_write() can be truncated when the file size is close to 4GB.
Fixed f_open(), f_mkdir() and f_setlabel() can return incorrect value on error.
R0.10a (January 15, 2014)
Added arbitrary strings as drive number in the path name. (_STR_VOLUME_ID)
Added a configuration option of minimum sector size. (_MIN_SS)
2nd argument of f_rename() can have a drive number and it will be ignored.
Fixed f_mount() with forced mount fails when drive number is >= 1. (appeared at R0.10)
Fixed f_close() invalidates the file object without volume lock.
Fixed f_closedir() returns but the volume lock is left acquired. (appeared at R0.10)
Fixed creation of an entry with LFN fails on too many SFN collisions. (appeared at R0.07)
R0.10b (May 19, 2014)
Fixed a hard error in the disk I/O layer can collapse the directory entry.
Fixed LFN entry is not deleted when delete/rename an object with lossy converted SFN. (appeared at R0.07)
R0.10c (November 09, 2014)
Added a configuration option for the platforms without RTC. (_FS_NORTC)
Changed option name _USE_ERASE to _USE_TRIM.
Fixed volume label created by Mac OS X cannot be retrieved with f_getlabel(). (appeared at R0.09b)
Fixed a potential problem of FAT access that can appear on disk error.
Fixed null pointer dereference on attempting to delete the root direcotry. (appeared at R0.08)
R0.11 (February 09, 2015)
Added f_findfirst(), f_findnext() and f_findclose(). (_USE_FIND)
Fixed f_unlink() does not remove cluster chain of the file. (appeared at R0.10c)
Fixed _FS_NORTC option does not work properly. (appeared at R0.10c)
R0.11a (September 05, 2015)
Fixed wrong media change can lead a deadlock at thread-safe configuration.
Added code page 771, 860, 861, 863, 864, 865 and 869. (_CODE_PAGE)
Removed some code pages actually not exist on the standard systems. (_CODE_PAGE)
Fixed errors in the case conversion teble of code page 437 and 850 (ff.c).
Fixed errors in the case conversion teble of Unicode (cc*.c).
R0.12 (April 12, 2016)
Added support for exFAT file system. (_FS_EXFAT)
Added f_expand(). (_USE_EXPAND)
Changed some members in FINFO structure and behavior of f_readdir().
Added an option _USE_CHMOD.
Removed an option _WORD_ACCESS.
Fixed errors in the case conversion table of Unicode (cc*.c).
R0.12a (July 10, 2016)
Added support for creating exFAT volume with some changes of f_mkfs().
Added a file open method FA_OPEN_APPEND. An f_lseek() following f_open() is no longer needed.
f_forward() is available regardless of _FS_TINY.
Fixed f_mkfs() creates wrong volume. (appeared at R0.12)
Fixed wrong memory read in create_name(). (appeared at R0.12)
Fixed compilation fails at some configurations, _USE_FASTSEEK and _USE_FORWARD.
R0.12b (September 04, 2016)
Made f_rename() be able to rename objects with the same name but case.
Fixed an error in the case conversion teble of code page 866. (ff.c)
Fixed writing data is truncated at the file offset 4GiB on the exFAT volume. (appeared at R0.12)
Fixed creating a file in the root directory of exFAT volume can fail. (appeared at R0.12)
Fixed f_mkfs() creating exFAT volume with too small cluster size can collapse unallocated memory. (appeared at R0.12)
Fixed wrong object name can be returned when read directory at Unicode cfg. (appeared at R0.12)
Fixed large file allocation/removing on the exFAT volume collapses allocation bitmap. (appeared at R0.12)
Fixed some internal errors in f_expand() and f_lseek(). (appeared at R0.12)
R0.12c (March 04, 2017)
Improved write throughput at the fragmented file on the exFAT volume.
Made memory usage for exFAT be able to be reduced as decreasing _MAX_LFN.
Fixed successive f_getfree() can return wrong count on the FAT12/16 volume. (appeared at R0.12)
Fixed configuration option _VOLUMES cannot be set 10. (appeared at R0.10c)
R0.13 (May 21, 2017)
Changed heading character of configuration keywords "_" to "FF_".
Removed ASCII-only configuration, FF_CODE_PAGE = 1. Use FF_CODE_PAGE = 437 instead.
Added f_setcp(), run-time code page configuration. (FF_CODE_PAGE = 0)
Improved cluster allocation time on stretch a deep buried cluster chain.
Improved processing time of f_mkdir() with large cluster size by using FF_USE_LFN = 3.
Improved NoFatChain flag of the fragmented file to be set after it is truncated and got contiguous.
Fixed archive attribute is left not set when a file on the exFAT volume is renamed. (appeared at R0.12)
Fixed exFAT FAT entry can be collapsed when write or lseek operation to the existing file is done. (appeared at R0.12c)
Fixed creating a file can fail when a new cluster allocation to the exFAT directory occures. (appeared at R0.12c)
R0.13a (October 14, 2017)
Added support for UTF-8 encoding on the API. (FF_LFN_UNICODE = 2)
Added options for file name output buffer. (FF_LFN_BUF, FF_SFN_BUF).
Added dynamic memory allocation option for working buffer of f_mkfs() and f_fdisk().
Fixed f_fdisk() and f_mkfs() create the partition table with wrong CHS parameters. (appeared at R0.09)
Fixed f_unlink() can cause lost clusters at fragmented file on the exFAT volume. (appeared at R0.12c)
Fixed f_setlabel() rejects some valid characters for exFAT volume. (appeared at R0.12)
R0.13b (April 07, 2018)
Added support for UTF-32 encoding on the API. (FF_LFN_UNICODE = 3)
Added support for Unix style volume ID. (FF_STR_VOLUME_ID = 2)
Fixed accesing any object on the exFAT root directory beyond the cluster boundary can fail. (appeared at R0.12c)
Fixed f_setlabel() does not reject some invalid characters. (appeared at R0.09b)
R0.13c (October 14, 2018)
Supported stdint.h for C99 and later. (integer.h was included in ff.h)
Fixed reading a directory gets infinite loop when the last directory entry is not empty. (appeared at R0.12)
Fixed creating a sub-directory in the fragmented sub-directory on the exFAT volume collapses FAT chain of the parent directory. (appeared at R0.12)
Fixed f_getcwd() cause output buffer overrun when the buffer has a valid drive number. (appeared at R0.13b)
R0.14 (October 14, 2019)
Added support for 64-bit LBA and GUID partition table (FF_LBA64 = 1)
Changed some API functions, f_mkfs() and f_fdisk().
Fixed f_open() function cannot find the file with file name in length of FF_MAX_LFN characters.
Fixed f_readdir() function cannot retrieve long file names in length of FF_MAX_LFN - 1 characters.
Fixed f_readdir() function returns file names with wrong case conversion. (appeared at R0.12)
Fixed f_mkfs() function can fail to create exFAT volume in the second partition. (appeared at R0.12)
R0.14a (December 5, 2020)
Limited number of recursive calls in f_findnext().
Fixed old floppy disks formatted with MS-DOS 2.x and 3.x cannot be mounted.
Fixed some compiler warnings.
R0.14b (April 17, 2021)
Made FatFs uses standard library <string.h> for copy, compare and search instead of built-in string functions.
Added support for long long integer and floating point to f_printf(). (FF_STRF_LLI and FF_STRF_FP)
Made path name parser ignore the terminating separator to allow "dir/".
Improved the compatibility in Unix style path name feature.
Fixed the file gets dead-locked when f_open() failed with some conditions. (appeared at R0.12a)
Fixed f_mkfs() can create wrong exFAT volume due to a timing dependent error. (appeared at R0.12)
Fixed code page 855 cannot be set by f_setcp().
Fixed some compiler warnings.
R0.15 (November 6, 2022)
Changed user provided synchronization functions in order to completely eliminate the platform dependency from FatFs code.
FF_SYNC_t is removed from the configuration options.
Fixed a potential error in f_mount when FF_FS_REENTRANT.
Fixed file lock control FF_FS_LOCK is not mutal excluded when FF_FS_REENTRANT && FF_VOLUMES > 1 is true.
Fixed f_mkfs() creates broken exFAT volume when the size of volume is >= 2^32 sectors.
Fixed string functions cannot write the unicode characters not in BMP when FF_LFN_UNICODE == 2 (UTF-8).
Fixed a compatibility issue in identification of GPT header.
@@ -0,0 +1,21 @@
FatFs Module Source Files R0.15
FILES
00readme.txt This file.
00history.txt Revision history.
ff.c FatFs module.
ffconf.h Configuration file of FatFs module.
ff.h Common include file for FatFs and application module.
diskio.h Common include file for FatFs and disk I/O module.
diskio.c An example of glue function to attach existing disk I/O module to FatFs.
ffunicode.c Optional Unicode utility functions.
ffsystem.c An example of optional O/S related functions.
Low level disk I/O module is not included in this archive because the FatFs
module is only a generic file system layer and it does not depend on any specific
storage device. You need to provide a low level disk I/O module written to
control the storage device that attached to the target system.
@@ -0,0 +1,11 @@
# RT-Thread building script for component
from building import *
cwd = GetCurrentDir()
src = Glob('*.c')
CPPPATH = [cwd]
group = DefineGroup('Filesystem', src, depend = ['RT_USING_DFS', 'RT_USING_DFS_ELMFAT'], CPPPATH = CPPPATH)
Return('group')
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,24 @@
/*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2010-02-06 Bernard Add elm_init function declaration
*/
#ifndef __DFS_ELM_H__
#define __DFS_ELM_H__
#ifdef __cplusplus
extern "C" {
#endif
int elm_init(void);
#ifdef __cplusplus
}
#endif
#endif
@@ -0,0 +1,77 @@
/*-----------------------------------------------------------------------/
/ Low level disk interface modlue include file (C)ChaN, 2019 /
/-----------------------------------------------------------------------*/
#ifndef _DISKIO_DEFINED
#define _DISKIO_DEFINED
#ifdef __cplusplus
extern "C" {
#endif
/* Status of Disk Functions */
typedef BYTE DSTATUS;
/* Results of Disk Functions */
typedef enum {
RES_OK = 0, /* 0: Successful */
RES_ERROR, /* 1: R/W Error */
RES_WRPRT, /* 2: Write Protected */
RES_NOTRDY, /* 3: Not Ready */
RES_PARERR /* 4: Invalid Parameter */
} DRESULT;
/*---------------------------------------*/
/* Prototypes for disk control functions */
DSTATUS disk_initialize (BYTE pdrv);
DSTATUS disk_status (BYTE pdrv);
DRESULT disk_read (BYTE pdrv, BYTE* buff, LBA_t sector, UINT count);
DRESULT disk_write (BYTE pdrv, const BYTE* buff, LBA_t sector, UINT count);
DRESULT disk_ioctl (BYTE pdrv, BYTE cmd, void* buff);
/* Disk Status Bits (DSTATUS) */
#define STA_NOINIT 0x01 /* Drive not initialized */
#define STA_NODISK 0x02 /* No medium in the drive */
#define STA_PROTECT 0x04 /* Write protected */
/* Command code for disk_ioctrl fucntion */
/* Generic command (Used by FatFs) */
#define CTRL_SYNC 0 /* Complete pending write process (needed at FF_FS_READONLY == 0) */
#define GET_SECTOR_COUNT 1 /* Get media size (needed at FF_USE_MKFS == 1) */
#define GET_SECTOR_SIZE 2 /* Get sector size (needed at FF_MAX_SS != FF_MIN_SS) */
#define GET_BLOCK_SIZE 3 /* Get erase block size (needed at FF_USE_MKFS == 1) */
#define CTRL_TRIM 4 /* Inform device that the data on the block of sectors is no longer used (needed at FF_USE_TRIM == 1) */
/* Generic command (Not used by FatFs) */
#define CTRL_POWER 5 /* Get/Set power status */
#define CTRL_LOCK 6 /* Lock/Unlock media removal */
#define CTRL_EJECT 7 /* Eject media */
#define CTRL_FORMAT 8 /* Create physical format on the media */
/* MMC/SDC specific ioctl command */
#define MMC_GET_TYPE 10 /* Get card type */
#define MMC_GET_CSD 11 /* Get CSD */
#define MMC_GET_CID 12 /* Get CID */
#define MMC_GET_OCR 13 /* Get OCR */
#define MMC_GET_SDSTAT 14 /* Get SD status */
#define ISDIO_READ 55 /* Read data form SD iSDIO register */
#define ISDIO_WRITE 56 /* Write data to SD iSDIO register */
#define ISDIO_MRITE 57 /* Masked write data to SD iSDIO register */
/* ATA/CF specific ioctl command */
#define ATA_GET_REV 20 /* Get F/W revision */
#define ATA_GET_MODEL 21 /* Get model name */
#define ATA_GET_SN 22 /* Get serial number */
#ifdef __cplusplus
}
#endif
#endif
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,431 @@
/*----------------------------------------------------------------------------/
/ FatFs - Generic FAT Filesystem module R0.15 /
/-----------------------------------------------------------------------------/
/
/ Copyright (C) 2022, ChaN, all right reserved.
/
/ FatFs module is an open source software. Redistribution and use of FatFs in
/ source and binary forms, with or without modification, are permitted provided
/ that the following condition is met:
/ 1. Redistributions of source code must retain the above copyright notice,
/ this condition and the following disclaimer.
/
/ This software is provided by the copyright holder and contributors "AS IS"
/ and any warranties related to this software are DISCLAIMED.
/ The copyright owner or contributors be NOT LIABLE for any damages caused
/ by use of this software.
/
/----------------------------------------------------------------------------*/
#ifndef FF_DEFINED
#define FF_DEFINED 80286 /* Revision ID */
#ifdef __cplusplus
extern "C" {
#endif
#include <rtthread.h>
#include "ffconf.h" /* FatFs configuration options */
#if FF_DEFINED != FFCONF_DEF
#error Wrong configuration file (ffconf.h).
#endif
/* Integer types used for FatFs API */
#if defined(_WIN32) /* Windows VC++ (for development only) */
#define FF_INTDEF 2
#include <windows.h>
typedef unsigned __int64 QWORD;
#include <float.h>
#define isnan(v) _isnan(v)
#define isinf(v) (!_finite(v))
#elif (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__cplusplus) /* C99 or later */
#define FF_INTDEF 2
#include <stdint.h>
typedef unsigned int UINT; /* int must be 16-bit or 32-bit */
typedef unsigned char BYTE; /* char must be 8-bit */
typedef uint16_t WORD; /* 16-bit unsigned integer */
typedef uint32_t DWORD; /* 32-bit unsigned integer */
typedef uint64_t QWORD; /* 64-bit unsigned integer */
typedef WORD WCHAR; /* UTF-16 character type */
#else /* Earlier than C99 */
#define FF_INTDEF 1
typedef unsigned int UINT; /* int must be 16-bit or 32-bit */
typedef unsigned char BYTE; /* char must be 8-bit */
typedef unsigned short WORD; /* 16-bit unsigned integer */
typedef unsigned long DWORD; /* 32-bit unsigned integer */
typedef WORD WCHAR; /* UTF-16 character type */
#endif
/* Type of file size and LBA variables */
#if FF_FS_EXFAT
#if FF_INTDEF != 2
#error exFAT feature wants C99 or later
#endif
typedef QWORD FSIZE_t;
#if FF_LBA64
typedef QWORD LBA_t;
#else
typedef DWORD LBA_t;
#endif
#else
#if FF_LBA64
#error exFAT needs to be enabled when enable 64-bit LBA
#endif
typedef DWORD FSIZE_t;
typedef DWORD LBA_t;
#endif
/* Type of path name strings on FatFs API (TCHAR) */
#if FF_USE_LFN && FF_LFN_UNICODE == 1 /* Unicode in UTF-16 encoding */
typedef WCHAR TCHAR;
#define _T(x) L ## x
#define _TEXT(x) L ## x
#elif FF_USE_LFN && FF_LFN_UNICODE == 2 /* Unicode in UTF-8 encoding */
typedef char TCHAR;
#define _T(x) u8 ## x
#define _TEXT(x) u8 ## x
#elif FF_USE_LFN && FF_LFN_UNICODE == 3 /* Unicode in UTF-32 encoding */
typedef DWORD TCHAR;
#define _T(x) U ## x
#define _TEXT(x) U ## x
#elif FF_USE_LFN && (FF_LFN_UNICODE < 0 || FF_LFN_UNICODE > 3)
#error Wrong FF_LFN_UNICODE setting
#else /* ANSI/OEM code in SBCS/DBCS */
typedef char TCHAR;
#define _T(x) x
#define _TEXT(x) x
#endif
/* Definitions of volume management */
#if FF_MULTI_PARTITION /* Multiple partition configuration */
typedef struct {
BYTE pd; /* Physical drive number */
BYTE pt; /* Partition: 0:Auto detect, 1-4:Forced partition) */
} PARTITION;
extern PARTITION VolToPart[]; /* Volume - Partition mapping table */
#endif
#if FF_STR_VOLUME_ID
#ifndef FF_VOLUME_STRS
extern const char* VolumeStr[FF_VOLUMES]; /* User defied volume ID */
#endif
#endif
/* Filesystem object structure (FATFS) */
typedef struct {
BYTE fs_type; /* Filesystem type (0:not mounted) */
BYTE pdrv; /* Volume hosting physical drive */
BYTE ldrv; /* Logical drive number (used only when FF_FS_REENTRANT) */
BYTE n_fats; /* Number of FATs (1 or 2) */
BYTE wflag; /* win[] status (b0:dirty) */
BYTE fsi_flag; /* FSINFO status (b7:disabled, b0:dirty) */
WORD id; /* Volume mount ID */
WORD n_rootdir; /* Number of root directory entries (FAT12/16) */
WORD csize; /* Cluster size [sectors] */
#if FF_MAX_SS != FF_MIN_SS
WORD ssize; /* Sector size (512, 1024, 2048 or 4096) */
#endif
#if FF_USE_LFN
WCHAR* lfnbuf; /* LFN working buffer */
#endif
#if FF_FS_EXFAT
BYTE* dirbuf; /* Directory entry block scratchpad buffer for exFAT */
#endif
#if !FF_FS_READONLY
DWORD last_clst; /* Last allocated cluster */
DWORD free_clst; /* Number of free clusters */
#endif
#if FF_FS_RPATH
DWORD cdir; /* Current directory start cluster (0:root) */
#if FF_FS_EXFAT
DWORD cdc_scl; /* Containing directory start cluster (invalid when cdir is 0) */
DWORD cdc_size; /* b31-b8:Size of containing directory, b7-b0: Chain status */
DWORD cdc_ofs; /* Offset in the containing directory (invalid when cdir is 0) */
#endif
#endif
DWORD n_fatent; /* Number of FAT entries (number of clusters + 2) */
DWORD fsize; /* Number of sectors per FAT */
LBA_t volbase; /* Volume base sector */
LBA_t fatbase; /* FAT base sector */
LBA_t dirbase; /* Root directory base sector (FAT12/16) or cluster (FAT32/exFAT) */
LBA_t database; /* Data base sector */
#if FF_FS_EXFAT
LBA_t bitbase; /* Allocation bitmap base sector */
#endif
LBA_t winsect; /* Current sector appearing in the win[] */
BYTE win[FF_MAX_SS]; /* Disk access window for Directory, FAT (and file data at tiny cfg) */
} FATFS;
/* Object ID and allocation information (FFOBJID) */
typedef struct {
FATFS* fs; /* Pointer to the hosting volume of this object */
WORD id; /* Hosting volume's mount ID */
BYTE attr; /* Object attribute */
BYTE stat; /* Object chain status (b1-0: =0:not contiguous, =2:contiguous, =3:fragmented in this session, b2:sub-directory stretched) */
DWORD sclust; /* Object data start cluster (0:no cluster or root directory) */
FSIZE_t objsize; /* Object size (valid when sclust != 0) */
#if FF_FS_EXFAT
DWORD n_cont; /* Size of first fragment - 1 (valid when stat == 3) */
DWORD n_frag; /* Size of last fragment needs to be written to FAT (valid when not zero) */
DWORD c_scl; /* Containing directory start cluster (valid when sclust != 0) */
DWORD c_size; /* b31-b8:Size of containing directory, b7-b0: Chain status (valid when c_scl != 0) */
DWORD c_ofs; /* Offset in the containing directory (valid when file object and sclust != 0) */
#endif
#if FF_FS_LOCK
UINT lockid; /* File lock ID origin from 1 (index of file semaphore table Files[]) */
#endif
} FFOBJID;
/* File object structure (FIL) */
typedef struct {
FFOBJID obj; /* Object identifier (must be the 1st member to detect invalid object pointer) */
BYTE flag; /* File status flags */
BYTE err; /* Abort flag (error code) */
FSIZE_t fptr; /* File read/write pointer (Zeroed on file open) */
DWORD clust; /* Current cluster of fpter (invalid when fptr is 0) */
LBA_t sect; /* Sector number appearing in buf[] (0:invalid) */
#if !FF_FS_READONLY
LBA_t dir_sect; /* Sector number containing the directory entry (not used at exFAT) */
BYTE* dir_ptr; /* Pointer to the directory entry in the win[] (not used at exFAT) */
#endif
#if FF_USE_FASTSEEK
DWORD* cltbl; /* Pointer to the cluster link map table (nulled on open, set by application) */
#endif
#if !FF_FS_TINY
BYTE buf[FF_MAX_SS]; /* File private data read/write window */
#endif
} FIL;
/* Directory object structure (DIR) */
typedef struct {
FFOBJID obj; /* Object identifier */
DWORD dptr; /* Current read/write offset */
DWORD clust; /* Current cluster */
LBA_t sect; /* Current sector (0:Read operation has terminated) */
BYTE* dir; /* Pointer to the directory item in the win[] */
BYTE fn[12]; /* SFN (in/out) {body[8],ext[3],status[1]} */
#if FF_USE_LFN
DWORD blk_ofs; /* Offset of current entry block being processed (0xFFFFFFFF:Invalid) */
#endif
#if FF_USE_FIND
const TCHAR* pat; /* Pointer to the name matching pattern */
#endif
} DIR;
/* File information structure (FILINFO) */
typedef struct {
FSIZE_t fsize; /* File size */
WORD fdate; /* Modified date */
WORD ftime; /* Modified time */
BYTE fattrib; /* File attribute */
#if FF_USE_LFN
TCHAR altname[FF_SFN_BUF + 1];/* Alternative file name */
TCHAR fname[FF_LFN_BUF + 1]; /* Primary file name */
#else
TCHAR fname[12 + 1]; /* File name */
#endif
} FILINFO;
/* Format parameter structure (MKFS_PARM) */
typedef struct {
BYTE fmt; /* Format option (FM_FAT, FM_FAT32, FM_EXFAT and FM_SFD) */
BYTE n_fat; /* Number of FATs */
UINT align; /* Data area alignment (sector) */
UINT n_root; /* Number of root directory entries */
DWORD au_size; /* Cluster size (byte) */
} MKFS_PARM;
/* File function return code (FRESULT) */
typedef enum {
FR_OK = 0, /* (0) Succeeded */
FR_DISK_ERR, /* (1) A hard error occurred in the low level disk I/O layer */
FR_INT_ERR, /* (2) Assertion failed */
FR_NOT_READY, /* (3) The physical drive cannot work */
FR_NO_FILE, /* (4) Could not find the file */
FR_NO_PATH, /* (5) Could not find the path */
FR_INVALID_NAME, /* (6) The path name format is invalid */
FR_DENIED, /* (7) Access denied due to prohibited access or directory full */
FR_EXIST, /* (8) Access denied due to prohibited access */
FR_INVALID_OBJECT, /* (9) The file/directory object is invalid */
FR_WRITE_PROTECTED, /* (10) The physical drive is write protected */
FR_INVALID_DRIVE, /* (11) The logical drive number is invalid */
FR_NOT_ENABLED, /* (12) The volume has no work area */
FR_NO_FILESYSTEM, /* (13) There is no valid FAT volume */
FR_MKFS_ABORTED, /* (14) The f_mkfs() aborted due to any problem */
FR_TIMEOUT, /* (15) Could not get a grant to access the volume within defined period */
FR_LOCKED, /* (16) The operation is rejected according to the file sharing policy */
FR_NOT_ENOUGH_CORE, /* (17) LFN working buffer could not be allocated */
FR_TOO_MANY_OPEN_FILES, /* (18) Number of open files > FF_FS_LOCK */
FR_INVALID_PARAMETER /* (19) Given parameter is invalid */
} FRESULT;
/*--------------------------------------------------------------*/
/* FatFs Module Application Interface */
/*--------------------------------------------------------------*/
FRESULT f_open (FIL* fp, const TCHAR* path, BYTE mode); /* Open or create a file */
FRESULT f_close (FIL* fp); /* Close an open file object */
FRESULT f_read (FIL* fp, void* buff, UINT btr, UINT* br); /* Read data from the file */
FRESULT f_write (FIL* fp, const void* buff, UINT btw, UINT* bw); /* Write data to the file */
FRESULT f_lseek (FIL* fp, FSIZE_t ofs); /* Move file pointer of the file object */
FRESULT f_truncate (FIL* fp); /* Truncate the file */
FRESULT f_sync (FIL* fp); /* Flush cached data of the writing file */
FRESULT f_opendir (DIR* dp, const TCHAR* path); /* Open a directory */
FRESULT f_closedir (DIR* dp); /* Close an open directory */
FRESULT f_readdir (DIR* dp, FILINFO* fno); /* Read a directory item */
FRESULT f_seekdir(DIR *dj, int offset); /* Seek in directory */
FRESULT f_findfirst (DIR* dp, FILINFO* fno, const TCHAR* path, const TCHAR* pattern); /* Find first file */
FRESULT f_findnext (DIR* dp, FILINFO* fno); /* Find next file */
FRESULT f_mkdir (const TCHAR* path); /* Create a sub directory */
FRESULT f_unlink (const TCHAR* path); /* Delete an existing file or directory */
FRESULT f_rename (const TCHAR* path_old, const TCHAR* path_new); /* Rename/Move a file or directory */
FRESULT f_stat (const TCHAR* path, FILINFO* fno); /* Get file status */
FRESULT f_chmod (const TCHAR* path, BYTE attr, BYTE mask); /* Change attribute of a file/dir */
FRESULT f_utime (const TCHAR* path, const FILINFO* fno); /* Change timestamp of a file/dir */
FRESULT f_chdir (const TCHAR* path); /* Change current directory */
FRESULT f_chdrive (const TCHAR* path); /* Change current drive */
FRESULT f_getcwd (TCHAR* buff, UINT len); /* Get current directory */
FRESULT f_getfree (const TCHAR* path, DWORD* nclst, FATFS** fatfs); /* Get number of free clusters on the drive */
FRESULT f_getlabel (const TCHAR* path, TCHAR* label, DWORD* vsn); /* Get volume label */
FRESULT f_setlabel (const TCHAR* label); /* Set volume label */
FRESULT f_forward (FIL* fp, UINT(*func)(const BYTE*,UINT), UINT btf, UINT* bf); /* Forward data to the stream */
FRESULT f_expand (FIL* fp, FSIZE_t fsz, BYTE opt); /* Allocate a contiguous block to the file */
FRESULT f_mount (FATFS* fs, const TCHAR* path, BYTE opt); /* Mount/Unmount a logical drive */
FRESULT f_mkfs (const TCHAR* path, const MKFS_PARM* opt, void* work, UINT len); /* Create a FAT volume */
FRESULT f_fdisk (BYTE pdrv, const LBA_t ptbl[], void* work); /* Divide a physical drive into some partitions */
FRESULT f_setcp (WORD cp); /* Set current code page */
int f_putc (TCHAR c, FIL* fp); /* Put a character to the file */
int f_puts (const TCHAR* str, FIL* cp); /* Put a string to the file */
int f_printf (FIL* fp, const TCHAR* str, ...); /* Put a formatted string to the file */
TCHAR* f_gets (TCHAR* buff, int len, FIL* fp); /* Get a string from the file */
/* Some API fucntions are implemented as macro */
#define f_eof(fp) ((int)((fp)->fptr == (fp)->obj.objsize))
#define f_error(fp) ((fp)->err)
#define f_tell(fp) ((fp)->fptr)
#define f_size(fp) ((fp)->obj.objsize)
#define f_rewind(fp) f_lseek((fp), 0)
#define f_rewinddir(dp) f_readdir((dp), 0)
#define f_rmdir(path) f_unlink(path)
#define f_unmount(path) f_mount(0, path, 0)
/*--------------------------------------------------------------*/
/* Additional Functions */
/*--------------------------------------------------------------*/
/* RTC function (provided by user) */
#if !FF_FS_READONLY && !FF_FS_NORTC
DWORD get_fattime (void); /* Get current time */
#endif
/* LFN support functions (defined in ffunicode.c) */
#if FF_USE_LFN >= 1
WCHAR ff_oem2uni (WCHAR oem, WORD cp); /* OEM code to Unicode conversion */
WCHAR ff_uni2oem (DWORD uni, WORD cp); /* Unicode to OEM code conversion */
DWORD ff_wtoupper (DWORD uni); /* Unicode upper-case conversion */
#endif
/* O/S dependent functions (samples available in ffsystem.c) */
#if FF_USE_LFN == 3 /* Dynamic memory allocation */
void* ff_memalloc (UINT msize); /* Allocate memory block */
void ff_memfree (void* mblock); /* Free memory block */
#endif
#if FF_FS_REENTRANT /* Sync functions */
int ff_mutex_create (int vol); /* Create a sync object */
void ff_mutex_delete (int vol); /* Delete a sync object */
int ff_mutex_take (int vol); /* Lock sync object */
void ff_mutex_give (int vol); /* Unlock sync object */
#endif
/*--------------------------------------------------------------*/
/* Flags and Offset Address */
/*--------------------------------------------------------------*/
/* File access mode and open method flags (3rd argument of f_open) */
#define FA_READ 0x01
#define FA_WRITE 0x02
#define FA_OPEN_EXISTING 0x00
#define FA_CREATE_NEW 0x04
#define FA_CREATE_ALWAYS 0x08
#define FA_OPEN_ALWAYS 0x10
#define FA_OPEN_APPEND 0x30
/* Fast seek controls (2nd argument of f_lseek) */
#define CREATE_LINKMAP ((FSIZE_t)0 - 1)
/* Format options (2nd argument of f_mkfs) */
#define FM_FAT 0x01
#define FM_FAT32 0x02
#define FM_EXFAT 0x04
#define FM_ANY 0x07
#define FM_SFD 0x08
/* Filesystem type (FATFS.fs_type) */
#define FS_FAT12 1
#define FS_FAT16 2
#define FS_FAT32 3
#define FS_EXFAT 4
/* File attribute bits for directory entry (FILINFO.fattrib) */
#define AM_RDO 0x01 /* Read only */
#define AM_HID 0x02 /* Hidden */
#define AM_SYS 0x04 /* System */
#define AM_DIR 0x10 /* Directory */
#define AM_ARC 0x20 /* Archive */
#ifdef __cplusplus
}
#endif
#endif /* FF_DEFINED */
@@ -0,0 +1,339 @@
/*---------------------------------------------------------------------------/
/ Configurations of FatFs Module
/---------------------------------------------------------------------------*/
#define FFCONF_DEF 80286 /* Revision ID */
/*---------------------------------------------------------------------------/
/ Function Configurations
/---------------------------------------------------------------------------*/
#define FF_FS_READONLY 0
/* This option switches read-only configuration. (0:Read/Write or 1:Read-only)
/ Read-only configuration removes writing API functions, f_write(), f_sync(),
/ f_unlink(), f_mkdir(), f_chmod(), f_rename(), f_truncate(), f_getfree()
/ and optional writing functions as well. */
#define FF_FS_MINIMIZE 0
/* This option defines minimization level to remove some basic API functions.
/
/ 0: Basic functions are fully enabled.
/ 1: f_stat(), f_getfree(), f_unlink(), f_mkdir(), f_truncate() and f_rename()
/ are removed.
/ 2: f_opendir(), f_readdir() and f_closedir() are removed in addition to 1.
/ 3: f_lseek() function is removed in addition to 2. */
#define FF_USE_FIND 0
/* This option switches filtered directory read functions, f_findfirst() and
/ f_findnext(). (0:Disable, 1:Enable 2:Enable with matching altname[] too) */
#define FF_USE_MKFS 1
/* This option switches f_mkfs() function. (0:Disable or 1:Enable) */
#define FF_USE_FASTSEEK 1
/* This option switches fast seek function. (0:Disable or 1:Enable) */
#define FF_USE_EXPAND 0
/* This option switches f_expand function. (0:Disable or 1:Enable) */
#define FF_USE_CHMOD 0
/* This option switches attribute manipulation functions, f_chmod() and f_utime().
/ (0:Disable or 1:Enable) Also FF_FS_READONLY needs to be 0 to enable this option. */
#define FF_USE_LABEL 0
/* This option switches volume label functions, f_getlabel() and f_setlabel().
/ (0:Disable or 1:Enable) */
#define FF_USE_FORWARD 0
/* This option switches f_forward() function. (0:Disable or 1:Enable) */
#define FF_USE_STRFUNC 0
#define FF_PRINT_LLI 0
#define FF_PRINT_FLOAT 0
#define FF_STRF_ENCODE 3
/* FF_USE_STRFUNC switches string functions, f_gets(), f_putc(), f_puts() and
/ f_printf().
/
/ 0: Disable. FF_PRINT_LLI, FF_PRINT_FLOAT and FF_STRF_ENCODE have no effect.
/ 1: Enable without LF-CRLF conversion.
/ 2: Enable with LF-CRLF conversion.
/
/ FF_PRINT_LLI = 1 makes f_printf() support long long argument and FF_PRINT_FLOAT = 1/2
/ makes f_printf() support floating point argument. These features want C99 or later.
/ When FF_LFN_UNICODE >= 1 with LFN enabled, string functions convert the character
/ encoding in it. FF_STRF_ENCODE selects assumption of character encoding ON THE FILE
/ to be read/written via those functions.
/
/ 0: ANSI/OEM in current CP
/ 1: Unicode in UTF-16LE
/ 2: Unicode in UTF-16BE
/ 3: Unicode in UTF-8
*/
/*---------------------------------------------------------------------------/
/ Locale and Namespace Configurations
/---------------------------------------------------------------------------*/
#ifdef RT_DFS_ELM_CODE_PAGE
# define FF_CODE_PAGE RT_DFS_ELM_CODE_PAGE
#else
# define FF_CODE_PAGE 936
#endif
/* This option specifies the OEM code page to be used on the target system.
/ Incorrect code page setting can cause a file open failure.
/
/ 437 - U.S.
/ 720 - Arabic
/ 737 - Greek
/ 771 - KBL
/ 775 - Baltic
/ 850 - Latin 1
/ 852 - Latin 2
/ 855 - Cyrillic
/ 857 - Turkish
/ 860 - Portuguese
/ 861 - Icelandic
/ 862 - Hebrew
/ 863 - Canadian French
/ 864 - Arabic
/ 865 - Nordic
/ 866 - Russian
/ 869 - Greek 2
/ 932 - Japanese (DBCS)
/ 936 - Simplified Chinese (DBCS)
/ 949 - Korean (DBCS)
/ 950 - Traditional Chinese (DBCS)
/ 0 - Include all code pages above and configured by f_setcp()
*/
#if RT_DFS_ELM_USE_LFN
#define FF_USE_LFN RT_DFS_ELM_USE_LFN
#define FF_MAX_LFN RT_DFS_ELM_MAX_LFN
#else
#define FF_USE_LFN 0 /* 0 to 3 */
#define FF_MAX_LFN 255 /* Maximum LFN length to handle (12 to 255) */
#endif
/* The FF_USE_LFN switches the support for LFN (long file name).
/
/ 0: Disable LFN. FF_MAX_LFN has no effect.
/ 1: Enable LFN with static working buffer on the BSS. Always NOT thread-safe.
/ 2: Enable LFN with dynamic working buffer on the STACK.
/ 3: Enable LFN with dynamic working buffer on the HEAP.
/
/ To enable the LFN, ffunicode.c needs to be added to the project. The LFN function
/ requiers certain internal working buffer occupies (FF_MAX_LFN + 1) * 2 bytes and
/ additional (FF_MAX_LFN + 44) / 15 * 32 bytes when exFAT is enabled.
/ The FF_MAX_LFN defines size of the working buffer in UTF-16 code unit and it can
/ be in range of 12 to 255. It is recommended to be set it 255 to fully support LFN
/ specification.
/ When use stack for the working buffer, take care on stack overflow. When use heap
/ memory for the working buffer, memory management functions, ff_memalloc() and
/ ff_memfree() exemplified in ffsystem.c, need to be added to the project. */
#ifdef RT_DFS_ELM_LFN_UNICODE
/* This option switches the character encoding on the API when LFN is enabled.
/
/ 0: ANSI/OEM in current CP (TCHAR = char)
/ 1: Unicode in UTF-16 (TCHAR = WCHAR)
/ 2: Unicode in UTF-8 (TCHAR = char)
/ 3: Unicode in UTF-32 (TCHAR = DWORD)
/
/ Also behavior of string I/O functions will be affected by this option.
/ When LFN is not enabled, this option has no effect. */
#define FF_LFN_UNICODE RT_DFS_ELM_LFN_UNICODE /* 0:ANSI/OEM or 1:Unicode */
#else
#define FF_LFN_UNICODE 0 /* 0:ANSI/OEM or 1:Unicode */
#endif
/* This option switches the character encoding on the API when LFN is enabled.
/
/ 0: ANSI/OEM in current CP (TCHAR = char)
/ 1: Unicode in UTF-16 (TCHAR = WCHAR)
/ 2: Unicode in UTF-8 (TCHAR = char)
/ 3: Unicode in UTF-32 (TCHAR = DWORD)
/
/ Also behavior of string I/O functions will be affected by this option.
/ When LFN is not enabled, this option has no effect. */
#define FF_LFN_BUF 255
#define FF_SFN_BUF 12
/* This set of options defines size of file name members in the FILINFO structure
/ which is used to read out directory items. These values should be suffcient for
/ the file names to read. The maximum possible length of the read file name depends
/ on character encoding. When LFN is not enabled, these options have no effect. */
#define FF_FS_RPATH 0
/* This option configures support for relative path.
/
/ 0: Disable relative path and remove related functions.
/ 1: Enable relative path. f_chdir() and f_chdrive() are available.
/ 2: f_getcwd() function is available in addition to 1.
*/
/*---------------------------------------------------------------------------/
/ Drive/Volume Configurations
/---------------------------------------------------------------------------*/
#ifdef RT_DFS_ELM_DRIVES
#define FF_VOLUMES RT_DFS_ELM_DRIVES
#else
#define FF_VOLUMES 1
#endif
/* Number of volumes (logical drives) to be used. (1-10) */
#define FF_STR_VOLUME_ID 0
#define FF_VOLUME_STRS "RAM","NAND","CF","SD","SD2","USB","USB2","USB3"
/* FF_STR_VOLUME_ID switches support for volume ID in arbitrary strings.
/ When FF_STR_VOLUME_ID is set to 1 or 2, arbitrary strings can be used as drive
/ number in the path name. FF_VOLUME_STRS defines the volume ID strings for each
/ logical drives. Number of items must not be less than FF_VOLUMES. Valid
/ characters for the volume ID strings are A-Z, a-z and 0-9, however, they are
/ compared in case-insensitive. If FF_STR_VOLUME_ID >= 1 and FF_VOLUME_STRS is
/ not defined, a user defined volume string table is needed as:
/
/ const char* VolumeStr[FF_VOLUMES] = {"ram","flash","sd","usb",...
*/
#define FF_MULTI_PARTITION 0
/* This option switches support for multiple volumes on the physical drive.
/ By default (0), each logical drive number is bound to the same physical drive
/ number and only an FAT volume found on the physical drive will be mounted.
/ When this function is enabled (1), each logical drive number can be bound to
/ arbitrary physical drive and partition listed in the VolToPart[]. Also f_fdisk()
/ function will be available. */
#define FF_MIN_SS 512
#ifdef RT_DFS_ELM_MAX_SECTOR_SIZE
#define FF_MAX_SS RT_DFS_ELM_MAX_SECTOR_SIZE
#else
#define FF_MAX_SS 512 /* 512, 1024, 2048 or 4096 */
#endif
/* This set of options configures the range of sector size to be supported. (512,
/ 1024, 2048 or 4096) Always set both 512 for most systems, generic memory card and
/ harddisk, but a larger value may be required for on-board flash memory and some
/ type of optical media. When FF_MAX_SS is larger than FF_MIN_SS, FatFs is configured
/ for variable sector size mode and disk_ioctl() function needs to implement
/ GET_SECTOR_SIZE command. */
#define FF_LBA64 0
/* This option switches support for 64-bit LBA. (0:Disable or 1:Enable)
/ To enable the 64-bit LBA, also exFAT needs to be enabled. (FF_FS_EXFAT == 1) */
#define FF_MIN_GPT 0x10000000
/* Minimum number of sectors to switch GPT as partitioning format in f_mkfs and
/ f_fdisk function. 0x100000000 max. This option has no effect when FF_LBA64 == 0. */
#define FF_USE_TRIM 0
/* This option switches support for ATA-TRIM. (0:Disable or 1:Enable)
/ To enable Trim function, also CTRL_TRIM command should be implemented to the
/ disk_ioctl() function. */
/*---------------------------------------------------------------------------/
/ System Configurations
/---------------------------------------------------------------------------*/
#define FF_FS_TINY 0
/* This option switches tiny buffer configuration. (0:Normal or 1:Tiny)
/ At the tiny configuration, size of file object (FIL) is shrinked FF_MAX_SS bytes.
/ Instead of private sector buffer eliminated from the file object, common sector
/ buffer in the filesystem object (FATFS) is used for the file data transfer. */
#ifdef RT_DFS_ELM_USE_EXFAT
#define FF_FS_EXFAT 1
#else
#define FF_FS_EXFAT 0
#endif
/* This option switches support for exFAT filesystem. (0:Disable or 1:Enable)
/ To enable exFAT, also LFN needs to be enabled. (FF_USE_LFN >= 1)
/ Note that enabling exFAT discards ANSI C (C89) compatibility. */
#define FF_FS_NORTC 0
#define FF_NORTC_MON 1
#define FF_NORTC_MDAY 1
#define FF_NORTC_YEAR 2022
/* The option FF_FS_NORTC switches timestamp feature. If the system does not have
/ an RTC or valid timestamp is not needed, set FF_FS_NORTC = 1 to disable the
/ timestamp feature. Every object modified by FatFs will have a fixed timestamp
/ defined by FF_NORTC_MON, FF_NORTC_MDAY and FF_NORTC_YEAR in local time.
/ To enable timestamp function (FF_FS_NORTC = 0), get_fattime() function need to be
/ added to the project to read current time form real-time clock. FF_NORTC_MON,
/ FF_NORTC_MDAY and FF_NORTC_YEAR have no effect.
/ These options have no effect in read-only configuration (FF_FS_READONLY = 1). */
#define FF_FS_NOFSINFO 0
/* If you need to know correct free space on the FAT32 volume, set bit 0 of this
/ option, and f_getfree() function at the first time after volume mount will force
/ a full FAT scan. Bit 1 controls the use of last allocated cluster number.
/
/ bit0=0: Use free cluster count in the FSINFO if available.
/ bit0=1: Do not trust free cluster count in the FSINFO.
/ bit1=0: Use last allocated cluster number in the FSINFO if available.
/ bit1=1: Do not trust last allocated cluster number in the FSINFO.
*/
#define FF_FS_LOCK 0
/* The option FF_FS_LOCK switches file lock function to control duplicated file open
/ and illegal operation to open objects. This option must be 0 when FF_FS_READONLY
/ is 1.
/
/ 0: Disable file lock function. To avoid volume corruption, application program
/ should avoid illegal open, remove and rename to the open objects.
/ >0: Enable file lock function. The value defines how many files/sub-directories
/ can be opened simultaneously under file lock control. Note that the file
/ lock control is independent of re-entrancy. */
/* #include <somertos.h> // O/S definitions */
#include <rtdef.h>
#ifdef RT_DFS_ELM_REENTRANT
#define FF_FS_REENTRANT 1 /* 0 or 1 */
#else
#define FF_FS_REENTRANT 0 /* 0:Disable or 1:Enable */
#endif
#ifndef RT_DFS_ELM_MUTEX_TIMEOUT
#define RT_DFS_ELM_MUTEX_TIMEOUT 3000
#endif
#define FF_FS_TIMEOUT RT_DFS_ELM_MUTEX_TIMEOUT
//#define FF_SYNC_t rt_mutex_t
/* The option FF_FS_REENTRANT switches the re-entrancy (thread safe) of the FatFs
/ module itself. Note that regardless of this option, file access to different
/ volume is always re-entrant and volume control functions, f_mount(), f_mkfs()
/ and f_fdisk() function, are always not re-entrant. Only file/directory access
/ to the same volume is under control of this featuer.
/
/ 0: Disable re-entrancy. FF_FS_TIMEOUT have no effect.
/ 1: Enable re-entrancy. Also user provided synchronization handlers,
/ ff_mutex_create(), ff_mutex_delete(), ff_mutex_take() and ff_mutex_give()
/ function, must be added to the project. Samples are available in ffsystem.c.
/
/ The FF_FS_TIMEOUT defines timeout period in unit of O/S time tick.
*/
/*--- End of configuration options ---*/
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,11 @@
# RT-Thread building script for component
from building import *
cwd = GetCurrentDir()
src = Glob('*.c')
CPPPATH = [cwd]
group = DefineGroup('Filesystem', src, depend = ['RT_USING_DFS', 'RT_USING_DFS_MQUEUE'], CPPPATH = CPPPATH)
Return('group')
@@ -0,0 +1,241 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2023-07-04 zhkag first Version
*/
#include <rtthread.h>
#include <rthw.h>
#include <dfs.h>
#include <dfs_fs.h>
#include <dfs_file.h>
#include <dfs_dentry.h>
#include <dfs_mnt.h>
#include "dfs_mqueue.h"
static rt_list_t _mqueue_file_list = RT_LIST_OBJECT_INIT(_mqueue_file_list);
struct rt_spinlock mqueue_lock;
void dfs_mqueue_insert_after(rt_list_t *n) {
rt_spin_lock(&mqueue_lock);
rt_list_insert_after(&(_mqueue_file_list), n);
rt_spin_unlock(&mqueue_lock);
}
struct mqueue_file *dfs_mqueue_lookup(const char *path, rt_size_t *size) {
struct mqueue_file *file;
rt_list_t *node;
rt_spin_lock(&mqueue_lock);
rt_list_for_each(node, &_mqueue_file_list) {
file = rt_list_entry(node, struct mqueue_file, list);
if (rt_strncmp(file->name, path, RT_NAME_MAX) == 0) {
*size = file->size;
rt_spin_unlock(&mqueue_lock);
return file;
}
}
rt_spin_unlock(&mqueue_lock);
return RT_NULL;
}
int dfs_mqueue_mount(struct dfs_mnt *mnt, unsigned long rwflag, const void *data) {
return RT_EOK;
}
int dfs_mqueue_umount(struct dfs_mnt *mnt) {
return RT_EOK;
}
int dfs_mqueue_statfs(struct dfs_mnt *mnt, struct statfs *buf) {
return RT_EOK;
}
int dfs_mqueue_close(struct dfs_file *file) {
return RT_EOK;
}
int dfs_mqueue_open(struct dfs_file *file) {
return 0;
}
int dfs_mqueue_stat(struct dfs_dentry *dentry, struct stat *st) {
struct dfs_vnode *vnode = RT_NULL;
if (dentry && dentry->vnode) {
vnode = dentry->vnode;
st->st_dev = 0;
st->st_gid = vnode->gid;
st->st_uid = vnode->uid;
st->st_ino = 0;
st->st_mode = vnode->mode;
st->st_nlink = vnode->nlink;
st->st_size = vnode->size;
st->st_mtim.tv_nsec = vnode->mtime.tv_nsec;
st->st_mtim.tv_sec = vnode->mtime.tv_sec;
st->st_ctim.tv_nsec = vnode->ctime.tv_nsec;
st->st_ctim.tv_sec = vnode->ctime.tv_sec;
st->st_atim.tv_nsec = vnode->atime.tv_nsec;
st->st_atim.tv_sec = vnode->atime.tv_sec;
}
return RT_EOK;
}
int dfs_mqueue_getdents(struct dfs_file *file, struct dirent *dirp, uint32_t count) {
rt_size_t index, end;
struct dirent *d;
count = (count / sizeof(struct dirent));
end = file->fpos + count;
index = 0;
count = 0;
struct mqueue_file *mq_file;
rt_list_t *node;
rt_spin_lock(&mqueue_lock);
rt_list_for_each(node, &_mqueue_file_list) {
if (index >= (rt_size_t)file->fpos) {
mq_file = rt_list_entry(node, struct mqueue_file, list);
d = dirp + count;
d->d_namlen = RT_NAME_MAX;
d->d_reclen = (rt_uint16_t)sizeof(struct dirent);
rt_strncpy(d->d_name, mq_file->name, RT_NAME_MAX);
count += 1;
file->fpos += 1;
}
index += 1;
if (index >= end) {
break;
}
}
rt_spin_unlock(&mqueue_lock);
return count * sizeof(struct dirent);
}
int dfs_mqueue_unlink(struct dfs_dentry *dentry) {
rt_size_t size;
struct mqueue_file *mq_file;
mq_file = dfs_mqueue_lookup(dentry->pathname + 1, &size);
if (mq_file == RT_NULL)
return -ENOENT;
rt_list_remove(&(mq_file->list));
if (mq_file->data != RT_NULL)
rt_mq_delete((rt_mq_t)mq_file->data);
rt_free(mq_file);
return RT_EOK;
}
static struct dfs_vnode *dfs_mqueue_create_vnode(struct dfs_dentry *dentry, int type, mode_t mode) {
struct dfs_vnode *vnode = RT_NULL;
rt_size_t size;
struct mqueue_file *mq_file;
if (dentry == NULL || dentry->mnt == NULL) {
return NULL;
}
vnode = dfs_vnode_create();
if (vnode) {
mq_file = dfs_mqueue_lookup(dentry->pathname + 1, &size);
if (mq_file == RT_NULL) {
mq_file = (struct mqueue_file *)rt_malloc(sizeof(struct mqueue_file));
if (mq_file == RT_NULL) {
return NULL;
}
mq_file->msg_size = 8192;
mq_file->max_msgs = 10;
strncpy(mq_file->name, dentry->pathname + 1, RT_NAME_MAX - 1);
dfs_mqueue_insert_after(&(mq_file->list));
}
vnode->mode = S_IFREG | (S_IRWXU | S_IRWXG | S_IRWXO);
vnode->type = FT_REGULAR;
rt_mq_t mq = rt_mq_create(dentry->pathname + 1, mq_file->msg_size, mq_file->max_msgs,
RT_IPC_FLAG_FIFO);
mq_file->data = (void *)mq;
vnode->data = mq_file;
vnode->size = 0;
}
return vnode;
}
static int dfs_mqueue_free_vnode(struct dfs_vnode *vnode) {
/* nothing to be freed */
if (vnode && vnode->ref_count <= 1) {
vnode->data = NULL;
}
return 0;
}
static const struct dfs_file_ops _mqueue_fops = {
.open = dfs_mqueue_open,
.close = dfs_mqueue_close,
.getdents = dfs_mqueue_getdents,
};
struct dfs_vnode *_dfs_mqueue_lookup(struct dfs_dentry *dentry) {
struct dfs_vnode *vnode = RT_NULL;
rt_size_t size;
// struct tmpfs_sb *superblock;
struct mqueue_file *mq_file;
if (dentry == NULL || dentry->mnt == NULL) {
return NULL;
}
if (dentry->pathname[0] == '/' && dentry->pathname[1] == '\0') {
}
mq_file = dfs_mqueue_lookup(dentry->pathname + 1, &size);
vnode = dfs_vnode_create();
if (mq_file && mq_file->data) {
vnode->mode = S_IFREG | (S_IRWXU | S_IRWXG | S_IRWXO);
vnode->type = FT_REGULAR;
vnode->mnt = dentry->mnt;
vnode->data = mq_file;
vnode->size = mq_file->size;
} else {
vnode->size = 0;
vnode->nlink = 1;
vnode->fops = &_mqueue_fops;
vnode->mnt = dentry->mnt;
vnode->type = FT_DIRECTORY;
vnode->mode = S_IFDIR | (S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
}
return vnode;
}
static const struct dfs_filesystem_ops _mqueue_ops = {
.name = "mqueue",
.flags = DFS_FS_FLAG_DEFAULT,
.default_fops = &_mqueue_fops,
.mount = dfs_mqueue_mount,
.umount = dfs_mqueue_umount,
.statfs = dfs_mqueue_statfs,
.unlink = dfs_mqueue_unlink,
.stat = dfs_mqueue_stat,
.lookup = _dfs_mqueue_lookup,
.create_vnode = dfs_mqueue_create_vnode,
.free_vnode = dfs_mqueue_free_vnode
};
static struct dfs_filesystem_type _mqueue = {
.fs_ops = &_mqueue_ops,
};
int dfs_mqueue_init(void) {
/* register mqueue file system */
dfs_register(&_mqueue);
mkdir("/dev/mqueue", 0x777);
if (dfs_mount(RT_NULL, "/dev/mqueue", "mqueue", 0, 0) != 0)
{
rt_kprintf("Dir /dev/mqueue mount failed!\n");
}
return 0;
}
INIT_ENV_EXPORT(dfs_mqueue_init);
@@ -0,0 +1,28 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2023-07-04 zhkag first Version
*/
#ifndef __DFS_MQUEUE_H__
#define __DFS_MQUEUE_H__
#include <rtthread.h>
struct mqueue_file {
char name[RT_NAME_MAX]; /* file name */
rt_uint16_t msg_size; /**< message size of each message */
rt_uint16_t max_msgs; /**< max number of messages */
rt_list_t list;
rt_uint8_t *data; /* file date ptr */
rt_size_t size; /* file size */
};
struct mqueue_file *dfs_mqueue_lookup(const char *path, rt_size_t *size);
void dfs_mqueue_insert_after(rt_list_t *n);
#endif
@@ -0,0 +1,166 @@
# 进程文件系统 (procfs)
## 数据结构
```c
struct proc_dentry
{
rt_uint32_t mode;
rt_atomic_t ref_count;
struct proc_dentry *parent;
struct dfs_vfs_node node;
const struct dfs_file_ops *fops;
const struct proc_ops *ops;
char *name;
void *data;
};
```
```log
root { mode: S_IFDIR, ref_count: 1, parent: root, name: /, child->next: file1->node }
|
|—— file1 { mode: S_IFREG, ref_count: 1, parent: root, name: file1, node->next: link1->node }
|—— link1 { mode: S_IFLNK, ref_count: 1, parent: root, name: link1, data: fullpath, node->next: dir1->node }
|—— dir1 { mode: S_IFDIR, ref_count: 1, parent: root, name: dir1, node->next: file3->node, child->next: file2->node }
| |
| |—— dir2 { mode: S_IFDIR, ref_count: 1, parent: dir1, name: dir2, node->next: link2->node }
| |—— link2 { mode: S_IFLNK, ref_count: 1, parent: dir1, name: link2, data: fullpath, node->next: file2->node }
| |—— file2 { mode: S_IFREG, ref_count: 1, parent: dir1, name: file2 }
|
|—— file3 { mode: S_IFREG, ref_count: 1, parent: root, name: file3 }
```
## API 介绍
```c
struct proc_dentry *dfs_proc_find(const char *name);
struct proc_dentry *proc_mkdir_data(const char *name, mode_t mode, struct proc_dentry *parent,
const struct dfs_file_ops *fops, void *data);
struct proc_dentry *proc_mkdir_mode(const char *name, mode_t mode, struct proc_dentry *parent);
struct proc_dentry *proc_mkdir(const char *name, struct proc_dentry *parent);
struct proc_dentry *proc_create_data(const char *name, mode_t mode, struct proc_dentry *parent,
const struct dfs_file_ops *fops, void *data);
struct proc_dentry *proc_symlink(const char *name, struct proc_dentry *parent, const char *dest);
struct proc_dentry *proc_acquire(struct proc_dentry *dentry);
void proc_release(struct proc_dentry *dentry);
void proc_remove(struct proc_dentry *dentry);
```
- dfs_proc_find
查找指定节点,并返回节点数据指针
| 入参 | 说明 |
| ---- | ---------------------------------------------------- |
| name | 从 procfs 的 root 起始的完整路径,比如 “/dir1/file2” |
- proc_mkdir_data
创建一个目录,并返回节点数据指针
| 入参 | 说明 |
| ------ | ------------------------------------------------------------ |
| name | 从 procfs 的 root 起始的完整路径,比如 “/dir1/file2”<br />从 parent 起始的完整路径 |
| mode | 权限配置 |
| parent | 指定创建目录的起始节点 |
| fops | 文件操作接口配置 |
| data | 私有数据 |
- proc_mkdir_mode
创建一个目录,并返回节点数据指针
| 入参 | 说明 |
| ------ | ------------------------------------------------------------ |
| name | 从 procfs 的 root 起始的完整路径,比如 “/dir1/file2”<br />从 parent 起始的完整路径 |
| mode | 权限配置 |
| parent | 指定创建目录的起始节点 |
- proc_mkdir
创建一个目录,并返回节点数据指针
| 入参 | 说明 |
| ---- | ------------------------------------------------------------ |
| name | 从 procfs 的 root 起始的完整路径,比如 “/dir1/file2”<br />从 parent 起始的完整路径 |
| mode | 权限配置 |
- proc_create_data
创建一个文件,并返回节点数据指针
| 入参 | 说明 |
| ------ | ------------------------------------------------------------ |
| name | 从 procfs 的 root 起始的完整路径,比如 “/dir1/file2”<br />从 parent 起始的完整路径 |
| mode | 权限配置 |
| parent | 指定创建文件的起始节点 |
| fops | 文件操作接口配置 |
| data | 私有数据 |
- proc_symlink
创建一个符号链接,并返回节点数据指针
| 入参 | 说明 |
| ------ | ------------------------------------------------------------ |
| name | 从 procfs 的 root 起始的完整路径,比如 “/dir1/file2”<br />从 parent 起始的完整路径 |
| parent | 指定创建文件的起始节点 |
| dest | 链接的目标文件完整路径 |
- proc_acquire
引用一个节点,并返回节点数据指针
| 入参 | 说明 |
| ------ | -------------- |
| dentry | 需要引用的节点 |
- proc_release
释放一个节点
| 入参 | 说明 |
| ------ | -------------- |
| dentry | 需要释放的节点 |
- proc_remove
删除一个节点包含子节点
| 入参 | 说明 |
| ------ | -------------- |
| dentry | 需要删除的节点 |
## msh 调试命令
- proc_dump
遍历打印指定节点含子节点的信息(名称、引用计数),比如 `proc_dump /dir1` 或者 `proc_dump`
- proc_remove
删除指定节点含子节点,比如 `proc_remove /dir1` 或者 `proc_remove /file3`
- proc_symlink
创建一个符号链接,`proc_symlink /link3 /mnt`
- proc_echo
创建一个空文件,`proc_echo /file4`
- proc_mkdir
创建一个空目录,`proc_mkdir /dir3`
- proc_pid
创建一个 pid 目录,`proc_pid /101`
@@ -0,0 +1,11 @@
# RT-Thread building script for component
from building import *
cwd = GetCurrentDir()
src = Glob('*.c')
CPPPATH = [cwd]
group = DefineGroup('Filesystem', src, depend = ['RT_USING_DFS', 'RT_USING_DFS_PROCFS'], CPPPATH = CPPPATH)
Return('group')
@@ -0,0 +1,733 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#include "proc.h"
#include "procfs.h"
#include <rthw.h>
#include <rtdbg.h>
#include <fcntl.h>
#include <errno.h>
/*
* This is the root in the proc tree..
*/
static struct proc_dentry _proc_root = {
.mode = S_IFDIR | (S_IRUSR | S_IRGRP | S_IROTH) | (S_IXUSR | S_IXGRP | S_IXOTH),
.ref_count = 1,
.parent = &_proc_root,
.node.sibling = RT_LIST_OBJECT_INIT(_proc_root.node.sibling),
.node.subnode = RT_LIST_OBJECT_INIT(_proc_root.node.subnode),
.fops = RT_NULL,
.name = "/",
.data = RT_NULL,
};
static int _proc_find(struct proc_dentry **parent, const char *name)
{
struct proc_dentry *dentry = RT_NULL, *tmp;
dfs_vfs_for_each_subnode(dentry, tmp, (*parent), node)
{
if (dentry == RT_NULL)
{
break;
}
if (rt_strcmp(dentry->name, name) == 0)
{
*parent = dentry;
return 0;
}
}
return -1;
}
static int proc_find(struct proc_dentry **parent, const char **name, rt_bool_t force_lookup)
{
int ret = 0;
char *tmp = RT_NULL;
if (!(*parent))
{
*parent = &_proc_root;
}
tmp = rt_strdup(*name);
if (tmp)
{
char *begin = tmp, *end = RT_NULL;
if (*begin == '/')
{
begin++;
if (*begin == '\0')
{
rt_free(tmp);
*parent = proc_acquire(*parent);
return ret;
}
}
while (1)
{
end = rt_strstr(begin, "/");
if (end)
{
*end = '\0';
ret = _proc_find(parent, begin);
if (ret < 0 || !S_ISDIR((*parent)->mode))
{
*parent = RT_NULL;
ret = -1;
break;
}
begin = end + 1;
}
else if (force_lookup)
{
ret = _proc_find(parent, begin);
if (ret < 0)
{
if ((*parent)->ops && (*parent)->ops->lookup)
{
*parent = (*parent)->ops->lookup(*parent, begin);
if (*parent == RT_NULL)
{
ret = -1;
}
}
else
{
*parent = RT_NULL;
}
}
else
{
*parent = proc_acquire(*parent);
}
break;
}
else
{
*parent = proc_acquire(*parent);
break;
}
}
*name = *name + (begin - tmp);
rt_free(tmp);
}
return ret;
}
static void *single_start(struct dfs_seq_file *seq, off_t *index)
{
return NULL + (*index == 0);
}
static void *single_next(struct dfs_seq_file *seq, void *data, off_t *index)
{
++*index;
return NULL;
}
static void single_stop(struct dfs_seq_file *seq, void *data)
{
}
static int proc_open(struct dfs_file *file)
{
struct proc_dentry *entry = (struct proc_dentry *)file->vnode->data;
if (entry->single_show)
{
struct dfs_seq_ops *seq_ops = (struct dfs_seq_ops *)rt_calloc(1, sizeof(struct dfs_seq_ops));
if (seq_ops)
{
int ret = 0;
seq_ops->start = single_start;
seq_ops->next = single_next;
seq_ops->stop = single_stop;
seq_ops->show = entry->single_show;
ret = dfs_seq_open(file, seq_ops);
if (ret != 0)
{
rt_free(seq_ops);
}
return ret;
}
}
return dfs_seq_open(file, entry->seq_ops);
}
static int proc_close(struct dfs_file *file)
{
struct dfs_seq_file *seq = file->data;
struct proc_dentry *entry = (struct proc_dentry *)file->vnode->data;
if (seq && entry->single_show && seq->ops)
{
rt_free((void *)seq->ops);
seq->ops = RT_NULL;
}
return dfs_seq_release(file);
}
static const struct dfs_file_ops proc_file_ops = {
.open = proc_open,
.read = dfs_seq_read,
.lseek = dfs_seq_lseek,
.close = proc_close,
};
static struct proc_dentry *proc_create(struct proc_dentry **parent, const char *name, mode_t mode)
{
int ret = 0;
struct proc_dentry *dentry = RT_NULL;
ret = proc_find(parent, &name, 0);
if (ret >= 0)
{
dentry = *parent;
ret = proc_find(&dentry, &name, 1);
if (ret < 0)
{
dentry = rt_calloc(1, sizeof(struct proc_dentry));
if (dentry)
{
dentry->mode = mode;
dentry->ref_count = 1;
dentry->name = rt_strdup(name);
dfs_vfs_init_node(&dentry->node);
}
}
else
{
proc_release(dentry);
dentry = RT_NULL;
}
}
return dentry;
}
/**
* @brief The dentry reference count is incremented by one
*
* @param dentry
*
* @return dentry
*/
struct proc_dentry *proc_acquire(struct proc_dentry *dentry)
{
if (dentry)
{
dentry->ref_count += 1;
}
return dentry;
}
/**
* @brief The dentry reference count is minus one, or release
*
* @param dentry
*
* @return none
*/
void proc_release(struct proc_dentry *dentry)
{
if (dentry)
{
if (dentry->ref_count == 1)
{
if (dentry->name)
{
rt_free(dentry->name);
}
if (S_ISLNK(dentry->mode) && dentry->data)
{
rt_free(dentry->data);
}
rt_free(dentry);
}
else
{
dentry->ref_count -= 1;
}
}
}
static struct proc_dentry *proc_register(struct proc_dentry *parent, struct proc_dentry *child)
{
child->parent = parent;
dfs_vfs_append_node(&parent->node, &child->node);
child->ref_count += 1;
child->pid = parent->pid;
return child;
}
/**
* @brief Make a dir
*
* @param name fullpath based on _proc_root or parent
* @param mode permission configuration
* @param parent can be empty
* @param fops
* @param data
*
* @return dentry
*/
struct proc_dentry *proc_mkdir_data(const char *name, mode_t mode, struct proc_dentry *parent,
const struct dfs_file_ops *fops, void *data)
{
struct proc_dentry *dentry, *_parent = parent;
if (mode == 0)
mode = (S_IRUSR | S_IRGRP | S_IROTH) | (S_IXUSR | S_IXGRP | S_IXOTH);
dentry = proc_create(&_parent, name, S_IFDIR | mode);
if (dentry)
{
dentry->fops = fops;
dentry->data = data;
dentry = proc_register(_parent, dentry);
}
proc_release(_parent);
return dentry;
}
/**
* @brief Make a dir
*
* @param name fullpath based on _proc_root or parent
* @param mode permission configuration
* @param parent can be empty
*
* @return dentry
*/
struct proc_dentry *proc_mkdir_mode(const char *name, mode_t mode, struct proc_dentry *parent)
{
return proc_mkdir_data(name, mode, parent, NULL, NULL);
}
/**
* @brief Make a dir
*
* @param name fullpath based on _proc_root or parent
* @param parent can be empty
*
* @return dentry
*/
struct proc_dentry *proc_mkdir(const char *name, struct proc_dentry *parent)
{
return proc_mkdir_data(name, 0, parent, NULL, NULL);
}
static struct proc_dentry *proc_create_reg(const char *name, mode_t mode, struct proc_dentry **parent)
{
struct proc_dentry *dentry = RT_NULL;
if ((mode & S_IFMT) == 0)
mode |= S_IFREG;
if ((mode & (S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)) == 0)
mode |= S_IRUSR | S_IRGRP | S_IROTH;
if (!S_ISREG(mode))
{
*parent = RT_NULL;
return dentry;
}
return proc_create(parent, name, mode);
}
/**
* @brief Make a file
*
* @param name fullpath based on _proc_root or parent
* @param mode permission configuration
* @param parent can be empty
* @param fops
* @param data
*
* @return dentry
*/
struct proc_dentry *proc_create_data(const char *name, mode_t mode, struct proc_dentry *parent,
const struct dfs_file_ops *fops, void *data)
{
struct proc_dentry *dentry, *_parent = parent;
dentry = proc_create_reg(name, mode, &_parent);
if (dentry)
{
dentry->fops = fops ? fops : &proc_file_ops;
dentry->data = data;
dentry = proc_register(_parent, dentry);
}
proc_release(_parent);
return dentry;
}
/**
* @brief Make a file
*
* @param name fullpath based on _proc_root or parent
* @param mode permission configuration
* @param parent can be empty
* @param show
* @param data
*
* @return dentry
*/
struct proc_dentry *proc_create_single_data(const char *name, mode_t mode, struct proc_dentry *parent,
int (*show)(struct dfs_seq_file *, void *), void *data)
{
struct proc_dentry *dentry, *_parent = parent;
dentry = proc_create_reg(name, mode, &_parent);
if (dentry)
{
dentry->fops = &proc_file_ops;
dentry->single_show = show;
dentry->data = data;
dentry = proc_register(_parent, dentry);
}
proc_release(_parent);
return dentry;
}
/**
* @brief Make a symlink
*
* @param name fullpath based on _proc_root or parent
* @param parent can be empty
* @param dest link file fullpath
*
* @return dentry
*/
struct proc_dentry *proc_symlink(const char *name, struct proc_dentry *parent, const char *dest)
{
struct proc_dentry *dentry, *_parent = parent;
dentry = proc_create(&_parent, name, (S_IFLNK | (S_IRUSR | S_IRGRP | S_IROTH)
| (S_IWUSR | S_IWGRP | S_IWOTH) | (S_IXUSR | S_IXGRP | S_IXOTH)));
if (dentry)
{
dentry->data = (void *)rt_strdup(dest);
if (dentry->data)
{
dentry = proc_register(_parent, dentry);
}
else
{
proc_release(dentry);
dentry = NULL;
}
}
proc_release(_parent);
return dentry;
}
static void remove_proc_subtree(struct proc_dentry *dentry)
{
struct proc_dentry *iter = RT_NULL, *iter_tmp, *tmp = RT_NULL;
dfs_vfs_for_each_subnode(iter, iter_tmp, dentry, node)
{
if (iter == RT_NULL)
{
break;
}
if (tmp)
{
proc_release(tmp);
tmp = RT_NULL;
}
tmp = iter;
if (S_ISDIR(dentry->mode))
{
remove_proc_subtree(iter);
}
}
if (tmp)
{
proc_release(tmp);
tmp = RT_NULL;
}
}
/**
* @brief remove a dentry
*
* @param dentry
*
* @return none
*/
void proc_remove(struct proc_dentry *dentry)
{
if (dentry && dentry != &_proc_root)
{
if (S_ISDIR(dentry->mode))
{
remove_proc_subtree(dentry);
}
dfs_vfs_remove_node(&dentry->node);
proc_release(dentry);
}
}
/**
* @brief find dentry exist
*
* @param name fullpath based on _proc_root
*
* @return dentry
*/
struct proc_dentry *dfs_proc_find(const char *name)
{
struct proc_dentry *dentry = RT_NULL;
proc_find(&dentry, &name, 1);
return dentry;
}
/**
* @brief remove a dentry on parent
*
* @param name fullpath based on parent
* @param parent
*
* @return none
*/
void proc_remove_dentry(const char *name, struct proc_dentry *parent)
{
struct proc_dentry *dentry = parent;
if (proc_find(&dentry, &name, 1) >= 0)
{
proc_remove(dentry);
proc_release(dentry);
}
}
#define _COLOR_RED "\033[31m"
#define _COLOR_GREEN "\033[32m"
#define _COLOR_BLUE "\033[34m"
#define _COLOR_CYAN "\033[36m"
#define _COLOR_WHITE "\033[37m"
#define _COLOR_NORMAL "\033[0m"
static void dump_proc_subtree(struct proc_dentry *dentry, int tab)
{
struct proc_dentry *iter = RT_NULL, *tmp;
dfs_vfs_for_each_subnode(iter, tmp, dentry, node)
{
if (iter == RT_NULL)
{
break;
}
for(int i = 0; i < tab; i ++)
{
rt_kprintf("%-4s", i + 1 >= tab ? "|-" : " ");
}
if (S_ISDIR(iter->mode))
{
rt_kprintf(_COLOR_BLUE "%-20s" _COLOR_NORMAL " %d\n", iter->name, iter->ref_count);
dump_proc_subtree(iter, tab + 1);
}
else if (S_ISLNK(iter->mode))
{
rt_kprintf(_COLOR_CYAN "%-20s" _COLOR_NORMAL " %d\n", iter->name, iter->ref_count);
}
else
{
rt_kprintf("%-20s %d\n", iter->name, iter->ref_count);
}
}
}
static void proc_dump(struct proc_dentry *dentry)
{
if (dentry)
{
if (S_ISDIR(dentry->mode))
{
rt_kprintf(_COLOR_BLUE "%-20s" _COLOR_NORMAL " %d\n", dentry->name, dentry->ref_count);
dump_proc_subtree(dentry, 1);
}
else if (S_ISLNK(dentry->mode))
{
rt_kprintf(_COLOR_CYAN "%-20s" _COLOR_NORMAL " %d\n", dentry->name, dentry->ref_count);
}
else
{
rt_kprintf("%-20s %d\n", dentry->name, dentry->ref_count);
}
}
}
static int msh_proc_dump(int argc, char** argv)
{
const char *name = argc > 1 ? argv[1] : "/";
struct proc_dentry *dentry = RT_NULL;
int ret = proc_find(&dentry, &name, 1);
if (ret >= 0)
{
proc_dump(dentry);
}
proc_release(dentry);
return 0;
}
MSH_CMD_EXPORT_ALIAS(msh_proc_dump, proc_dump, proc dump);
static int msh_proc_remove(int argc, char** argv)
{
if (argc > 1)
{
const char *name = argv[1];
struct proc_dentry *dentry = RT_NULL;
int ret = proc_find(&dentry, &name, 1);
if (ret >= 0)
{
if (dentry != &_proc_root)
{
proc_remove(dentry);
}
else
{
struct proc_dentry *iter = RT_NULL, *iter_tmp, *tmp = RT_NULL;
dfs_vfs_for_each_subnode(iter, iter_tmp, dentry, node)
{
if (iter == RT_NULL)
{
break;
}
if (tmp)
{
proc_remove(tmp);
}
tmp = iter;
}
if (tmp)
{
proc_remove(tmp);
}
}
}
proc_release(dentry);
}
else
{
rt_kprintf("proc_remove path\n");
}
return 0;
}
MSH_CMD_EXPORT_ALIAS(msh_proc_remove, proc_remove, proc remove);
static int msh_proc_symlink(int argc, char** argv)
{
if (argc > 2)
{
struct proc_dentry *entry = proc_symlink(argv[1], 0, argv[2]);
if (entry)
{
proc_release(entry);
}
}
else
{
rt_kprintf("proc_symlink path dest\n");
}
return 0;
}
MSH_CMD_EXPORT_ALIAS(msh_proc_symlink, proc_symlink, proc symlink);
static int msh_proc_echo(int argc, char** argv)
{
if (argc > 1)
{
for(int i = 1; i <= argc - 1; i ++)
{
struct proc_dentry *entry = proc_create_data(argv[i], 0, 0, 0, 0);
if (entry)
{
proc_release(entry);
}
}
}
else
{
rt_kprintf("proc_echo path\n");
}
return 0;
}
MSH_CMD_EXPORT_ALIAS(msh_proc_echo, proc_echo, proc echo);
static int msh_proc_mkdir(int argc, char** argv)
{
if (argc > 1)
{
for(int i = 1; i <= argc - 1; i ++)
{
struct proc_dentry *entry = proc_mkdir(argv[i], 0);
if (entry)
{
proc_release(entry);
}
}
}
else
{
rt_kprintf("proc_mkdir path\n");
}
return 0;
}
MSH_CMD_EXPORT_ALIAS(msh_proc_mkdir, proc_mkdir, proc mkdir);
@@ -0,0 +1,75 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#ifndef __PROC_H__
#define __PROC_H__
#include <dfs_file.h>
#include <dfs_seq_file.h>
#include <dfs_vfs.h>
#ifdef __cplusplus
extern "C"
{
#endif
struct proc_dentry;
struct proc_ops
{
struct proc_dentry *(*lookup)(struct proc_dentry *parent, const char *name);
int (*readlink)(struct proc_dentry *dentry, char *buf, int len);
};
struct proc_dentry
{
rt_uint32_t mode;
rt_atomic_t ref_count;
struct proc_dentry *parent;
struct dfs_vfs_node node;
const struct dfs_file_ops *fops;
const struct proc_ops *ops;
const struct dfs_seq_ops *seq_ops;
int (*single_show)(struct dfs_seq_file *seq, void *data);
int pid;
char *name;
void *data;
};
struct proc_dentry *dfs_proc_find(const char *name);
struct proc_dentry *proc_mkdir_data(const char *name, mode_t mode, struct proc_dentry *parent,
const struct dfs_file_ops *fops, void *data);
struct proc_dentry *proc_mkdir_mode(const char *name, mode_t mode, struct proc_dentry *parent);
struct proc_dentry *proc_mkdir(const char *name, struct proc_dentry *parent);
struct proc_dentry *proc_create_data(const char *name, mode_t mode, struct proc_dentry *parent,
const struct dfs_file_ops *fops, void *data);
struct proc_dentry *proc_create_single_data(const char *name, mode_t mode, struct proc_dentry *parent,
int (*show)(struct dfs_seq_file *, void *), void *data);
struct proc_dentry *proc_symlink(const char *name, struct proc_dentry *parent, const char *dest);
struct proc_dentry *proc_acquire(struct proc_dentry *dentry);
void proc_release(struct proc_dentry *dentry);
void proc_remove(struct proc_dentry *dentry);
void proc_remove_dentry(const char *name, struct proc_dentry *parent);
int proc_pid(int pid);
#ifdef __cplusplus
}
#endif
#endif
@@ -0,0 +1,53 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#include "proc.h"
#include "procfs.h"
#include <rthw.h>
#include <rtdbg.h>
#include <fcntl.h>
#include <errno.h>
#include <dfs_dentry.h>
static char *__proc_cmdline = NULL;
int proc_cmdline_save(const char *cmdline)
{
if (__proc_cmdline)
{
free(__proc_cmdline);
__proc_cmdline = NULL;
}
__proc_cmdline = strdup(cmdline);
return 0;
}
static int single_show(struct dfs_seq_file *seq, void *data)
{
if (__proc_cmdline)
{
dfs_seq_puts(seq, __proc_cmdline);
}
return 0;
}
int proc_cmdline_init(void)
{
struct proc_dentry *dentry = proc_create_single_data("cmdline", 0, NULL, single_show, NULL);
proc_release(dentry);
return 0;
}
INIT_ENV_EXPORT(proc_cmdline_init);
@@ -0,0 +1,86 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#include "proc.h"
#include "procfs.h"
#include <rthw.h>
#include <rtdbg.h>
#include <fcntl.h>
#include <errno.h>
#include <dfs_dentry.h>
static void *seq_start(struct dfs_seq_file *seq, off_t *index)
{
off_t i = *index; // seq->index
return NULL + (i == 0);
}
static void seq_stop(struct dfs_seq_file *seq, void *data)
{
}
static void *seq_next(struct dfs_seq_file *seq, void *data, off_t *index)
{
/* data: The return value of the start or next*/
off_t i = *index + 1; // seq->index
*index = i;
return NULL;
}
static int seq_show(struct dfs_seq_file *seq, void *data)
{
/* data: The return value of the start or next*/
dfs_seq_puts(seq, "rt_weak const struct dfs_seq_ops *cpuinfo_get_seq_ops(void)\n--need your own function--\n");
return 0;
}
static const struct dfs_seq_ops seq_ops = {
.start = seq_start,
.stop = seq_stop,
.next = seq_next,
.show = seq_show,
};
rt_weak const struct dfs_seq_ops *cpuinfo_get_seq_ops(void)
{
return &seq_ops;
}
static int proc_open(struct dfs_file *file)
{
return dfs_seq_open(file, cpuinfo_get_seq_ops());
}
static int proc_close(struct dfs_file *file)
{
return dfs_seq_release(file);
}
static const struct dfs_file_ops file_ops = {
.open = proc_open,
.read = dfs_seq_read,
.lseek = dfs_seq_lseek,
.close = proc_close,
};
int proc_cpuinfo_init(void)
{
struct proc_dentry *dentry = proc_create_data("cpuinfo", 0, NULL, &file_ops, NULL);
proc_release(dentry);
return 0;
}
INIT_ENV_EXPORT(proc_cpuinfo_init);
@@ -0,0 +1,307 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#include "proc.h"
#include "procfs.h"
#include <rthw.h>
#include <rtdbg.h>
#include <fcntl.h>
#include <errno.h>
#include <dfs_dentry.h>
#include <rthw.h>
#include <rtthread.h>
#include <string.h>
#define LIST_FIND_OBJ_NR 8
struct device_show
{
char *buf;
int size;
int len;
int index;
};
typedef struct
{
rt_list_t *list;
rt_list_t **array;
rt_uint8_t type;
int nr; /* input: max nr, can't be 0 */
int nr_out; /* out: got nr */
} list_get_next_t;
static void list_find_init(list_get_next_t *p, rt_uint8_t type, rt_list_t **array, int nr)
{
struct rt_object_information *info;
rt_list_t *list;
info = rt_object_get_information((enum rt_object_class_type)type);
list = &info->object_list;
p->list = list;
p->type = type;
p->array = array;
p->nr = nr;
p->nr_out = 0;
}
static rt_list_t *list_get_next(rt_list_t *current, list_get_next_t *arg)
{
int first_flag = 0;
rt_base_t level;
rt_list_t *node, *list;
rt_list_t **array;
struct rt_object_information *info;
int nr;
arg->nr_out = 0;
if (!arg->nr || !arg->type)
{
return (rt_list_t *)RT_NULL;
}
list = arg->list;
info = rt_list_entry(list, struct rt_object_information, object_list);
if (!current) /* find first */
{
node = list;
first_flag = 1;
}
else
{
node = current;
}
level = rt_spin_lock_irqsave(&info->spinlock);
if (!first_flag)
{
struct rt_object *obj;
/* The node in the list? */
obj = rt_list_entry(node, struct rt_object, list);
if ((obj->type & ~RT_Object_Class_Static) != arg->type)
{
rt_spin_unlock_irqrestore(&info->spinlock, level);
return (rt_list_t *)RT_NULL;
}
}
nr = 0;
array = arg->array;
while (1)
{
node = node->next;
if (node == list)
{
node = (rt_list_t *)RT_NULL;
break;
}
nr++;
*array++ = node;
if (nr == arg->nr)
{
break;
}
}
rt_spin_unlock_irqrestore(&info->spinlock, level);
arg->nr_out = nr;
return node;
}
static char *const device_type_str[RT_Device_Class_Unknown] =
{
"Character Device",
"Block Device",
"Network Interface",
"MTD Device",
"CAN Device",
"RTC",
"Sound Device",
"Graphic Device",
"I2C Bus",
"USB Slave Device",
"USB Host Bus",
"USB OTG Bus",
"SPI Bus",
"SPI Device",
"SDIO Bus",
"PM Pseudo Device",
"Pipe",
"Portal Device",
"Timer Device",
"Miscellaneous Device",
"Sensor Device",
"Touch Device",
"Phy Device",
"Security Device",
"WLAN Device",
"Pin Device",
"ADC Device",
"DAC Device",
"WDT Device",
"PWM Device",
"Bus Device",
};
static void save_info(struct device_show *dev, char *dev_name)
{
char tmp[256] = {0};
int len;
dev->index ++;
rt_snprintf(tmp, 256, "%d %s\n", dev->index, dev_name);
tmp[255] = 0;
len = rt_strlen(tmp);
if (dev->size > dev->len + len)
{
strcat(dev->buf, tmp);
dev->len += len;
}
else
{
if (dev->buf == RT_NULL)
{
dev->buf = rt_calloc(1, 4096);
}
else
{
dev->buf = rt_realloc(dev->buf, dev->size + 4096);
}
if (dev->buf)
{
dev->size += 4096;
strcat(dev->buf, tmp);
dev->len += len;
}
}
}
static void list_device(struct device_show *dev)
{
rt_base_t level;
list_get_next_t find_arg;
struct rt_object_information *info;
rt_list_t *obj_list[LIST_FIND_OBJ_NR];
rt_list_t *next = (rt_list_t *)RT_NULL;
list_find_init(&find_arg, RT_Object_Class_Device, obj_list, sizeof(obj_list) / sizeof(obj_list[0]));
info = rt_list_entry(find_arg.list, struct rt_object_information, object_list);
do
{
next = list_get_next(next, &find_arg);
{
int i;
for (i = 0; i < find_arg.nr_out; i++)
{
struct rt_object *obj;
struct rt_device *device;
obj = rt_list_entry(obj_list[i], struct rt_object, list);
level = rt_spin_lock_irqsave(&info->spinlock);
if ((obj->type & ~RT_Object_Class_Static) != find_arg.type)
{
rt_spin_unlock_irqrestore(&info->spinlock, level);
continue;
}
rt_spin_unlock_irqrestore(&info->spinlock, level);
device = (struct rt_device *)obj;
if (device->type < RT_Device_Class_Unknown)
{
save_info(dev + device->type, device->parent.name);
}
}
}
}
while (next != (rt_list_t *)RT_NULL);
}
static int show_info(struct dfs_seq_file *seq)
{
struct device_show _show[RT_Device_Class_Unknown] = {0};
list_device(_show);
for (int i = 0; i < RT_Device_Class_Unknown; i++)
{
if (_show[i].buf)
{
dfs_seq_printf(seq, "%s:\n", device_type_str[i]);
dfs_seq_write(seq, _show[i].buf, _show[i].len);
dfs_seq_putc(seq, '\n');
rt_free(_show[i].buf);
}
}
return 0;
}
static void *seq_start(struct dfs_seq_file *seq, off_t *index)
{
off_t i = *index; // seq->index
return NULL + (i == 0);
}
static void seq_stop(struct dfs_seq_file *seq, void *data)
{
}
static void *seq_next(struct dfs_seq_file *seq, void *data, off_t *index)
{
/* data: The return value of the start or next*/
off_t i = *index + 1; // seq->index
*index = i;
return NULL;
}
static int seq_show(struct dfs_seq_file *seq, void *data)
{
/* data: The return value of the start or next*/
show_info(seq);
return 0;
}
static const struct dfs_seq_ops seq_ops = {
.start = seq_start,
.stop = seq_stop,
.next = seq_next,
.show = seq_show,
};
int proc_devices_init(void)
{
struct proc_dentry *dentry = proc_create_data("devices", 0, NULL, NULL, NULL);
if (dentry)
{
dentry->seq_ops = &seq_ops;
}
proc_release(dentry);
return 0;
}
INIT_ENV_EXPORT(proc_devices_init);
@@ -0,0 +1,85 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#include "proc.h"
#include "procfs.h"
#include <rthw.h>
#include <rtdbg.h>
#include <fcntl.h>
#include <errno.h>
#include <dfs_dentry.h>
#include <dfs_fs.h>
static void *seq_start(struct dfs_seq_file *seq, off_t *index)
{
off_t i = *index; // seq->index
struct dfs_filesystem_type *fs = dfs_filesystems();
if (fs)
{
while (i--)
{
fs = fs->next;
if (!fs)
{
break;
}
}
}
return fs;
}
static void seq_stop(struct dfs_seq_file *seq, void *data)
{
}
static void *seq_next(struct dfs_seq_file *seq, void *data, off_t *index)
{
/* data: The return value of the start or next*/
off_t i = *index + 1; // seq->index
struct dfs_filesystem_type *fs = (struct dfs_filesystem_type *)data;
*index = i;
return fs->next;
}
static int seq_show(struct dfs_seq_file *seq, void *data)
{
/* data: The return value of the start or next*/
struct dfs_filesystem_type *fs = (struct dfs_filesystem_type *)data;
dfs_seq_printf(seq, "%-9s%s\n", (fs->fs_ops->flags == FS_NEED_DEVICE) ? "" : "nodev", fs->fs_ops->name);
return 0;
}
static const struct dfs_seq_ops seq_ops = {
.start = seq_start,
.stop = seq_stop,
.next = seq_next,
.show = seq_show,
};
int proc_filesystems_init(void)
{
struct proc_dentry *dentry = proc_create_data("filesystems", 0, NULL, NULL, NULL);
if (dentry)
{
dentry->seq_ops = &seq_ops;
}
proc_release(dentry);
return 0;
}
INIT_ENV_EXPORT(proc_filesystems_init);
@@ -0,0 +1,41 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#include "proc.h"
#include "procfs.h"
#include <rthw.h>
#include <rtdbg.h>
#include <fcntl.h>
#include <errno.h>
#include <dfs_dentry.h>
#include <mm_page.h>
extern void rt_memory_info(rt_size_t *total,
rt_size_t *used,
rt_size_t *max_used);
static int single_show(struct dfs_seq_file *seq, void *data)
{
dfs_seq_printf(seq, "0.13 0.16 0.17 1/1035 380436\n");
return 0;
}
int proc_loadavg_init(void)
{
struct proc_dentry *dentry = proc_create_single_data("loadavg", 0, NULL, single_show, NULL);
proc_release(dentry);
return 0;
}
INIT_ENV_EXPORT(proc_loadavg_init);
@@ -0,0 +1,66 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#include "proc.h"
#include "procfs.h"
#include <rthw.h>
#include <rtdbg.h>
#include <fcntl.h>
#include <errno.h>
#include <dfs_dentry.h>
#include <mm_page.h>
extern void rt_memory_info(rt_size_t *total,
rt_size_t *used,
rt_size_t *max_used);
static int single_show(struct dfs_seq_file *seq, void *data)
{
rt_size_t total, used, max_used, freed;
rt_size_t total_sum = 0;
rt_size_t total_freed = 0;
rt_memory_info(&total, &used, &max_used);
total_sum = total_sum + total;
total_freed = total_freed + total - used;
dfs_seq_printf(seq, "%-16s%8d KB\n", "MemMaxUsed:", max_used / 1024);
dfs_seq_printf(seq, "%-16s%8d KB\n", "MemAvailable:", (total - used) / 1024);
dfs_seq_printf(seq, "%-16s%8d KB\n", "Cached:", 0);
dfs_seq_printf(seq, "%-16s%8d KB\n", "SReclaimable:", 0);
rt_page_get_info(&total, &freed);
total_sum = total_sum + total * RT_MM_PAGE_SIZE;
total_freed = total_freed + freed * RT_MM_PAGE_SIZE;
dfs_seq_printf(seq, "%-16s%8d KB\n", "MemTotal:", total_sum / 1024);
dfs_seq_printf(seq, "%-16s%8d KB\n", "MemFree:", total_freed / 1024);
dfs_seq_printf(seq, "%-16s%8d KB\n", "LowPageTotal:", total * RT_MM_PAGE_SIZE / 1024);
dfs_seq_printf(seq, "%-16s%8d KB\n", "lowPageFree:", freed * RT_MM_PAGE_SIZE/ 1024);
rt_page_high_get_info(&total, &freed);
dfs_seq_printf(seq, "%-16s%8d KB\n", "HighPageTotal:", total * RT_MM_PAGE_SIZE / 1024);
dfs_seq_printf(seq, "%-16s%8d KB\n", "HighPageFree:", freed * RT_MM_PAGE_SIZE / 1024);
return 0;
}
int proc_meminfo_init(void)
{
struct proc_dentry *dentry = proc_create_single_data("meminfo", 0, NULL, single_show, NULL);
proc_release(dentry);
return 0;
}
INIT_ENV_EXPORT(proc_meminfo_init);
@@ -0,0 +1,101 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#include "proc.h"
#include "procfs.h"
#include <rthw.h>
#include <rtdbg.h>
#include <fcntl.h>
#include <errno.h>
#include <dfs_dentry.h>
#include <dfs_mnt.h>
const char *mnt_flag(int flag)
{
/*if (flag & MNT_READONLY)
{
return "ro";
}*/
return "rw";
}
static struct dfs_mnt* mnt_show(struct dfs_mnt *mnt, void *parameter)
{
struct dfs_seq_file *seq = (struct dfs_seq_file *)parameter;
if (mnt)
{
if (mnt->dev_id)
{
dfs_seq_printf(seq, "%s %s %s %s 0 0\n", mnt->dev_id->parent.name, mnt->fullpath,
mnt->fs_ops->name, mnt_flag(mnt->flags));
}
else
{
dfs_seq_printf(seq, "%s %s %s %s 0 0\n", mnt->fs_ops->name, mnt->fullpath,
mnt->fs_ops->name, mnt_flag(mnt->flags));
}
}
return RT_NULL;
}
static void *seq_start(struct dfs_seq_file *seq, off_t *index)
{
off_t i = *index; // seq->index
return NULL + (i == 0);
}
static void seq_stop(struct dfs_seq_file *seq, void *data)
{
}
static void *seq_next(struct dfs_seq_file *seq, void *data, off_t *index)
{
/* data: The return value of the start or next*/
off_t i = *index + 1; // seq->index
*index = i;
return NULL;
}
static int seq_show(struct dfs_seq_file *seq, void *data)
{
/* data: The return value of the start or next*/
dfs_mnt_foreach(mnt_show, seq);
return 0;
}
static const struct dfs_seq_ops seq_ops = {
.start = seq_start,
.stop = seq_stop,
.next = seq_next,
.show = seq_show,
};
int proc_mounts_init(void)
{
struct proc_dentry *dentry = proc_create_data("mounts", 0, NULL, NULL, NULL);
if (dentry)
{
dentry->seq_ops = &seq_ops;
}
proc_release(dentry);
return 0;
}
INIT_ENV_EXPORT(proc_mounts_init);
@@ -0,0 +1,109 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#include "proc.h"
#include "procfs.h"
#include <rthw.h>
#include <rtdbg.h>
#include <fcntl.h>
#include <errno.h>
#include <dfs_dentry.h>
#ifdef RT_USING_LWIP
#include "lwip/opt.h"
#endif
#if LWIP_ROUTE
extern int inet_route_foreach(void (*func)(const char *name, uint32_t ip_addr, uint32_t netmask, void *parameter), void *parameter);
#endif
static void *seq_start(struct dfs_seq_file *seq, off_t *index)
{
off_t i = *index; // seq->index
return NULL + (i == 0);
}
static void seq_stop(struct dfs_seq_file *seq, void *data)
{
}
static void *seq_next(struct dfs_seq_file *seq, void *data, off_t *index)
{
/* data: The return value of the start or next*/
off_t i = *index + 1; // seq->index
*index = i;
return NULL;
}
#if LWIP_ROUTE
static void route_show(const char *name, uint32_t ip_addr, uint32_t netmask, void *parameter)
{
struct dfs_seq_file *seq = (struct dfs_seq_file *)parameter;
/* "Iface\tDestination\tGateway "
"\tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU"
"\tWindow\tIRTT"); */
/* "%63s%lx%lx%X%d%d%d%lx%d%d%d\n" */
dfs_seq_printf(seq, "%s ", name);
dfs_seq_printf(seq, "%lx ", ip_addr);
dfs_seq_printf(seq, "%lx ", 0);
dfs_seq_printf(seq, "%X ", 1);
dfs_seq_printf(seq, "%d ", 0);
dfs_seq_printf(seq, "%d ", 0);
dfs_seq_printf(seq, "%d ", 0);
dfs_seq_printf(seq, "%lx ", netmask);
dfs_seq_printf(seq, "%d ", 0);
dfs_seq_printf(seq, "%d ", 0);
dfs_seq_printf(seq, "%d\n", 0);
}
#endif
static int seq_show(struct dfs_seq_file *seq, void *data)
{
/* data: The return value of the start or next*/
dfs_seq_printf(seq, "\n");
#if LWIP_ROUTE
inet_route_foreach(route_show, seq);
#endif
return 0;
}
static const struct dfs_seq_ops seq_ops = {
.start = seq_start,
.stop = seq_stop,
.next = seq_next,
.show = seq_show,
};
int proc_net_init(void)
{
struct proc_dentry *dentry;
dentry = proc_mkdir("net", NULL);
if (!dentry)
return -1;
proc_release(dentry);
dentry = proc_create_data("net/route", 0, NULL, NULL, NULL);
if (dentry)
{
dentry->seq_ops = &seq_ops;
}
proc_release(dentry);
return 0;
}
INIT_ENV_EXPORT(proc_net_init);
@@ -0,0 +1,215 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#include "proc.h"
#include "procfs.h"
#include <rthw.h>
#include <rtdbg.h>
#include <fcntl.h>
#include <errno.h>
#include <dfs_dentry.h>
#include <rthw.h>
#include <rtthread.h>
#include <string.h>
#define LIST_FIND_OBJ_NR 8
typedef struct
{
rt_list_t *list;
rt_list_t **array;
rt_uint8_t type;
int nr; /* input: max nr, can't be 0 */
int nr_out; /* out: got nr */
} list_get_next_t;
static void list_find_init(list_get_next_t *p, rt_uint8_t type, rt_list_t **array, int nr)
{
struct rt_object_information *info;
rt_list_t *list;
info = rt_object_get_information((enum rt_object_class_type)type);
list = &info->object_list;
p->list = list;
p->type = type;
p->array = array;
p->nr = nr;
p->nr_out = 0;
}
static rt_list_t *list_get_next(rt_list_t *current, list_get_next_t *arg)
{
int first_flag = 0;
rt_base_t level;
rt_list_t *node, *list;
rt_list_t **array;
struct rt_object_information *info;
int nr;
arg->nr_out = 0;
if (!arg->nr || !arg->type)
{
return (rt_list_t *)RT_NULL;
}
list = arg->list;
info = rt_list_entry(list, struct rt_object_information, object_list);
if (!current) /* find first */
{
node = list;
first_flag = 1;
}
else
{
node = current;
}
level = rt_spin_lock_irqsave(&info->spinlock);
if (!first_flag)
{
struct rt_object *obj;
/* The node in the list? */
obj = rt_list_entry(node, struct rt_object, list);
if ((obj->type & ~RT_Object_Class_Static) != arg->type)
{
rt_spin_unlock_irqrestore(&info->spinlock, level);
return (rt_list_t *)RT_NULL;
}
}
nr = 0;
array = arg->array;
while (1)
{
node = node->next;
if (node == list)
{
node = (rt_list_t *)RT_NULL;
break;
}
nr++;
*array++ = node;
if (nr == arg->nr)
{
break;
}
}
rt_spin_unlock_irqrestore(&info->spinlock, level);
arg->nr_out = nr;
return node;
}
static int show_info(struct dfs_seq_file *seq)
{
rt_base_t level;
list_get_next_t find_arg;
struct rt_object_information *info;
rt_list_t *obj_list[LIST_FIND_OBJ_NR];
rt_list_t *next = (rt_list_t *)RT_NULL;
list_find_init(&find_arg, RT_Object_Class_Device, obj_list, sizeof(obj_list) / sizeof(obj_list[0]));
info = rt_list_entry(find_arg.list, struct rt_object_information, object_list);
do
{
next = list_get_next(next, &find_arg);
{
int i;
for (i = 0; i < find_arg.nr_out; i++)
{
struct rt_object *obj;
struct rt_device *device;
obj = rt_list_entry(obj_list[i], struct rt_object, list);
level = rt_spin_lock_irqsave(&info->spinlock);
if ((obj->type & ~RT_Object_Class_Static) != find_arg.type)
{
rt_spin_unlock_irqrestore(&info->spinlock, level);
continue;
}
rt_spin_unlock_irqrestore(&info->spinlock, level);
device = (struct rt_device *)obj;
if (device->type == RT_Device_Class_Block)
{
struct rt_device_blk_geometry geometry = { 0 };
rt_device_control(device, RT_DEVICE_CTRL_BLK_GETGEOME, &geometry);
dfs_seq_printf(seq, "%4d %7d %14llu %s\n", 0, 0,
geometry.sector_count, device->parent.name);
}
}
}
} while (next != (rt_list_t *)RT_NULL);
return 0;
}
static void *seq_start(struct dfs_seq_file *seq, off_t *index)
{
off_t i = *index; // seq->index
return NULL + (i == 0);
}
static void seq_stop(struct dfs_seq_file *seq, void *data)
{
}
static void *seq_next(struct dfs_seq_file *seq, void *data, off_t *index)
{
/* data: The return value of the start or next*/
off_t i = *index + 1; // seq->index
*index = i;
return NULL;
}
static int seq_show(struct dfs_seq_file *seq, void *data)
{
dfs_seq_puts(seq, "major minor #blocks name\n\n");
/* data: The return value of the start or next*/
show_info(seq);
return 0;
}
static const struct dfs_seq_ops seq_ops = {
.start = seq_start,
.stop = seq_stop,
.next = seq_next,
.show = seq_show,
};
int proc_partitions_init(void)
{
struct proc_dentry *dentry = proc_create_data("partitions", 0, NULL, NULL, NULL);
if (dentry)
{
dentry->seq_ops = &seq_ops;
}
proc_release(dentry);
return 0;
}
INIT_ENV_EXPORT(proc_partitions_init);
@@ -0,0 +1,449 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#define __RT_IPC_SOURCE__
#include "proc.h"
#include "procfs.h"
#include <rthw.h>
#include <rtdbg.h>
#include <fcntl.h>
#include <errno.h>
#include "lwp_internal.h"
#include <dfs_dentry.h>
#include "lwp_internal.h"
#if defined(RT_USING_SMART)
#include "lwp.h"
#include "lwp_pid.h"
#include <lwp_user_mm.h>
struct pid_dentry
{
const char *name;
mode_t mode;
const struct dfs_file_ops *fops;
const struct proc_ops *ops;
const struct dfs_seq_ops *seq_ops;
int (*single_show)(struct dfs_seq_file *seq, void *data);
void *data;
};
static char stat_transform(int __stat)
{
switch (__stat)
{
case RT_THREAD_RUNNING:
return 'R';
default:
return 'T';
}
}
static int stat_single_show(struct dfs_seq_file *seq, void *data)
{
struct proc_dentry *dentry = (struct proc_dentry *)seq->file->vnode->data;
rt_list_t *list;
int mask = 0;
rt_thread_t thread;
rt_uint64_t user_time_lwp = 0;
rt_uint64_t system_time_lwp = 0;
int lwp_oncpu = RT_CPUS_NR;
int lwp_oncpu_ok = 0;
struct rt_lwp *lwp = RT_NULL;
char** argv = RT_NULL;
char *filename = RT_NULL;
char *dot = RT_NULL;
lwp_pid_lock_take();
lwp = lwp_from_pid_locked(dentry->pid);
argv = lwp_get_command_line_args(lwp);
if (lwp)
{
dfs_seq_printf(seq,"%d ",dentry->pid);
if (argv)
{
filename = strrchr(argv[0], '/');
dot = strchr(argv[0], '.');
if (filename != NULL)
{
filename++;
}
else
{
filename = argv[0];
}
if (dot != NULL)
{
*dot = '\0';
}
if (filename != NULL)
{
dfs_seq_printf(seq,"(%s) ", filename);
}
else
{
dfs_seq_printf(seq,"(%s) ", argv[0]);
}
lwp_free_command_line_args(argv);
}
else
{
dfs_seq_printf(seq,"(%s) ", "");
}
if (lwp->terminated)
{
dfs_seq_printf(seq,"%c ",'Z');
}
else
{
list = lwp->t_grp.next;
while (list != &lwp->t_grp)
{
thread = rt_list_entry(list, struct rt_thread, sibling);
user_time_lwp = user_time_lwp + thread->user_time;
system_time_lwp = system_time_lwp + thread->system_time;
#if RT_CPUS_NR > 1
#define ONCPU(thread) RT_SCHED_CTX(thread).oncpu
#else
#define ONCPU(thread) 0
#endif
if (lwp_oncpu_ok == 0)
{
lwp_oncpu = ONCPU(thread);
lwp_oncpu_ok = 1;
}
if (stat_transform(RT_SCHED_CTX(thread).stat) == 'R')
{
lwp_oncpu = ONCPU(thread);
mask = 1;
}
list = list->next;
}
if (mask == 1)
{
dfs_seq_printf(seq,"%c ",'R');
}
else
{
dfs_seq_printf(seq,"%c ",'S');
}
}
lwp_pid_lock_release();
if (lwp->parent != NULL)
dfs_seq_printf(seq,"%d ",lwp->parent->pid);
else
dfs_seq_printf(seq,"0 ");
dfs_seq_printf(seq, "1 1 0 -1 4194560 48245 133976064 732 425574 ");
dfs_seq_printf(seq,"%llu ",user_time_lwp);//utime
dfs_seq_printf(seq,"%llu ",system_time_lwp);//stime
dfs_seq_printf(seq, "1204291 518742 20 0 1 0 50 ");
dfs_seq_printf(seq, "%d ",rt_aspace_count_vsz(lwp->aspace));//VSZ
dfs_seq_printf(seq, "1422 18446744073709551615 ");
dfs_seq_printf(seq, "1 1 0 0 0 0 671173123 4096 1260 0 0 0 17 ");
dfs_seq_printf(seq, "%d ", lwp_oncpu);//CPU
dfs_seq_printf(seq, "0 0 0 0 0 0 0 0 0 0 0 0 0");
dfs_seq_printf(seq,"\n");
}
else
{
lwp_pid_lock_release();
}
return 0;
}
static int cmdline_single_show(struct dfs_seq_file *seq, void *data)
{
struct proc_dentry *dentry = (struct proc_dentry *)seq->file->vnode->data;
struct rt_lwp *lwp;
char** argv;
lwp_pid_lock_take();
lwp = lwp_from_pid_locked(dentry->pid);
argv = lwp_get_command_line_args(lwp);
lwp_pid_lock_release();
if (argv)
{
for (int i = 0; argv[i] != NULL; i++)
{
dfs_seq_printf(seq, "%s ", argv[i]);
}
dfs_seq_puts(seq, "\n");
lwp_free_command_line_args(argv);
}
else
{
dfs_seq_puts(seq, "error\n");
}
return 0;
}
struct proc_dentry *proc_pid_fd_lookup(struct proc_dentry *parent, const char *name)
{
struct proc_dentry *dentry = RT_NULL;
char num[DIRENT_NAME_MAX];
struct rt_lwp *lwp;
struct dfs_fdtable *table;
lwp_pid_lock_take();
lwp = lwp_from_pid_locked(parent->pid);
table = lwp ? &lwp->fdt : RT_NULL;
lwp_pid_lock_release();
if (!table)
{
return RT_NULL;
}
dfs_file_lock();
for (int i = 0; i < table->maxfd; i++)
{
struct dfs_file *file = table->fds[i];
if (file)
{
rt_snprintf(num, DIRENT_NAME_MAX, "%d", i);
if (rt_strcmp(num, name) == 0)
{
dentry = rt_calloc(1, sizeof(struct proc_dentry));
if (dentry)
{
dentry->mode = (S_IFLNK | (S_IRUSR | S_IRGRP | S_IROTH) | (S_IWUSR | S_IWGRP | S_IWOTH) | (S_IXUSR | S_IXGRP | S_IXOTH));
dentry->ref_count = 1;
dentry->name = rt_strdup(name);
dentry->data = (void *)dfs_dentry_full_path(file->dentry);
if (dentry->data == RT_NULL)
{
//todo add vnode->data
if (file->vnode->type == FT_SOCKET)
dentry->data = (void *)rt_strdup("socket");
else if (file->vnode->type == FT_USER)
dentry->data = (void *)rt_strdup("user");
else if (file->vnode->type == FT_DEVICE)
dentry->data = (void *)rt_strdup("device");
else
dentry->data = (void *)rt_strdup("unknown");
}
dentry->pid = parent->pid;
break;
}
}
}
}
dfs_file_unlock();
return dentry;
}
int proc_pid_fd_getdents(struct dfs_file *file, struct dirent *dirp, uint32_t count)
{
int ret = 0, index = 0;
struct proc_dentry *entry = (struct proc_dentry *)file->vnode->data;
struct rt_lwp *lwp;
struct dfs_fdtable *table;
lwp_pid_lock_take();
lwp = lwp_from_pid_locked(entry->pid);
LWP_LOCK(lwp);
table = lwp ? &lwp->fdt : RT_NULL;
if (!table->fds)
{
LWP_UNLOCK(lwp);
lwp_pid_lock_release();
return 0;
}
count = (count / sizeof(struct dirent));
if (count == 0)
{
LWP_UNLOCK(lwp);
lwp_pid_lock_release();
return -EINVAL;
}
dfs_file_lock();
for (int i = 0; i < table->maxfd; i++)
{
struct dfs_file *df = table->fds[i];
if (df)
{
if (index >= file->fpos)
{
struct dirent *d = dirp + index - file->fpos;
d->d_type = DT_SYMLINK;
d->d_reclen = (rt_uint16_t)sizeof(struct dirent);
rt_snprintf(d->d_name, DIRENT_NAME_MAX, "%d", i);
d->d_namlen = rt_strlen(d->d_name);
ret++;
}
index++;
if (index - file->fpos >= count)
{
break;
}
}
}
dfs_file_unlock();
LWP_UNLOCK(lwp);
lwp_pid_lock_release();
if (ret > 0)
{
file->fpos = index;
ret = ret * sizeof(struct dirent);
}
return ret;
}
static const struct proc_ops proc_pid_fd_ops = {
.lookup = proc_pid_fd_lookup,
};
static const struct dfs_file_ops proc_pid_fd_fops = {
.getdents = proc_pid_fd_getdents,
};
int proc_pid_exe_readlink(struct proc_dentry *dentry, char *buf, int len)
{
struct rt_lwp *lwp;
lwp = lwp_self();
len = rt_snprintf(buf, len, "%s", lwp ? lwp->exe_file : "null");
return len;
}
static const struct proc_ops proc_pid_exe_ops = {
.readlink = proc_pid_exe_readlink,
};
int proc_pid_cwd_readlink(struct proc_dentry *dentry, char *buf, int len)
{
struct rt_lwp *lwp;
lwp = lwp_self();
len = rt_snprintf(buf, len, "%s", lwp ? lwp->working_directory : "null");
return len;
}
static const struct proc_ops proc_pid_cwd_ops = {
.readlink = proc_pid_cwd_readlink,
};
static struct pid_dentry pid_dentry_base[] = {
{"cmdline", S_IFREG | S_IRUSR | S_IRGRP | S_IROTH, 0, 0, 0, cmdline_single_show, 0},
{"cwd", S_IFLNK | S_IRUSR | S_IXUSR, 0, &proc_pid_cwd_ops, 0, 0},
{"exe", S_IFLNK | S_IRUSR | S_IXUSR, 0, &proc_pid_exe_ops, 0, 0},
{"fd", S_IFDIR | S_IRUSR | S_IXUSR, &proc_pid_fd_fops, &proc_pid_fd_ops, 0, 0, 0},
{"mounts", S_IFLNK | S_IRUSR | S_IXUSR, 0, 0, 0, 0, "/proc/mounts"},
{"stat", S_IFREG | S_IRUSR | S_IRGRP | S_IROTH, 0, 0, 0, stat_single_show, 0},
};
int proc_pid(int pid)
{
char pid_str[64] = {0};
struct proc_dentry *dentry;
rt_snprintf(pid_str, 64, "%d", pid);
pid_str[63] = 0;
dentry = proc_mkdir(pid_str, 0);
if (dentry)
{
struct proc_dentry *ent;
dentry->pid = pid;
for (int j = 0; j < sizeof(pid_dentry_base) / sizeof(struct pid_dentry); j++)
{
if (S_ISDIR(pid_dentry_base[j].mode))
{
ent = proc_mkdir_data(pid_dentry_base[j].name, pid_dentry_base[j].mode, dentry,
pid_dentry_base[j].fops, pid_dentry_base[j].data);
}
else if (S_ISLNK(pid_dentry_base[j].mode))
{
if (pid_dentry_base[j].data == RT_NULL)
{
pid_dentry_base[j].data = "NULL";
}
ent = proc_symlink(pid_dentry_base[j].name, dentry, pid_dentry_base[j].data);
}
else
{
ent = proc_create_data(pid_dentry_base[j].name, pid_dentry_base[j].mode, dentry,
pid_dentry_base[j].fops, pid_dentry_base[j].data);
}
if (ent)
{
if (pid_dentry_base[j].ops)
{
ent->ops = pid_dentry_base[j].ops;
}
if (pid_dentry_base[j].seq_ops)
{
ent->seq_ops = pid_dentry_base[j].seq_ops;
}
if (pid_dentry_base[j].single_show)
{
ent->single_show = pid_dentry_base[j].single_show;
}
proc_release(ent);
}
}
proc_release(dentry);
}
return 0;
}
int msh_proc_pid(int argc, char **argv)
{
if (argc > 1)
{
for (int i = 1; i <= argc - 1; i++)
{
proc_pid(atoi(argv[i]));
}
}
return 0;
}
MSH_CMD_EXPORT_ALIAS(msh_proc_pid, proc_pid, proc pid);
#endif
@@ -0,0 +1,66 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#include "proc.h"
#include "procfs.h"
#include <rthw.h>
#include <rtdbg.h>
#include <fcntl.h>
#include <errno.h>
#include <dfs_dentry.h>
#if defined(RT_USING_SMART)
#include <lwp.h>
int proc_self_readlink(struct proc_dentry *dentry, char *buf, int len)
{
struct rt_lwp *lwp = RT_NULL;
lwp = lwp_self();
if (lwp)
{
rt_snprintf(buf, len, "%d", lwp_to_pid(lwp));
buf[len - 1] = 0;
return rt_strlen(buf);
}
else
{
rt_snprintf(buf, len, "null");
buf[len - 1] = 0;
return rt_strlen(buf);
}
return -1;
}
static const struct proc_ops proc_pid_fd_ops = {
.readlink = proc_self_readlink,
};
int proc_self_init(void)
{
struct proc_dentry *ent;
ent = proc_symlink("self", NULL, "NULL");
if (ent)
{
ent->ops = &proc_pid_fd_ops;
}
proc_release(ent);
return 0;
}
INIT_ENV_EXPORT(proc_self_init);
#endif
@@ -0,0 +1,114 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#include "proc.h"
#include "procfs.h"
#include <rthw.h>
#include <rtdbg.h>
#include <fcntl.h>
#include <errno.h>
#include <dfs_dentry.h>
static void *seq_start(struct dfs_seq_file *seq, off_t *index)
{
off_t i = *index; // seq->index
return NULL + (i == 0);
}
static void seq_stop(struct dfs_seq_file *seq, void *data)
{
}
static void *seq_next(struct dfs_seq_file *seq, void *data, off_t *index)
{
/* data: The return value of the start or next*/
off_t i = *index + 1; // seq->index
*index = i;
return NULL;
}
static int seq_show(struct dfs_seq_file *seq, void *data)
{
int i;
rt_cpu_t pcpu;
rt_uint64_t user_total = 0;
rt_uint64_t system_total = 0;
rt_uint64_t idle_total = 0;
for (i = 0; i < RT_CPUS_NR; i++)
{
pcpu = rt_cpu_index(i);
user_total = user_total + pcpu->cpu_stat.user;
system_total = system_total + pcpu->cpu_stat.system;
idle_total = idle_total + pcpu->cpu_stat.idle;
}
dfs_seq_printf(seq, "cpu %llu 0 %llu %llu 0 0 0 0 0 0\n", user_total, system_total, idle_total);
for (i = 0; i < RT_CPUS_NR; i++)
{
pcpu = rt_cpu_index(i);
dfs_seq_printf(seq, "cpu%d ",i);
dfs_seq_printf(seq, "%llu ",pcpu->cpu_stat.user);//user
dfs_seq_printf(seq, "0 ");//nice
dfs_seq_printf(seq, "%llu ",pcpu->cpu_stat.system);//system
dfs_seq_printf(seq, "%llu ",pcpu->cpu_stat.idle);//idle
dfs_seq_printf(seq, "0 ");//iowait
dfs_seq_printf(seq, "0 ");//irq
dfs_seq_printf(seq, "0 ");//softirq
dfs_seq_printf(seq, "0 0 0\n");//steal,guest,guest_nice
}
return 0;
}
static const struct dfs_seq_ops seq_ops = {
.start = seq_start,
.stop = seq_stop,
.next = seq_next,
.show = seq_show,
};
rt_weak const struct dfs_seq_ops *stat_get_seq_ops(void)
{
return &seq_ops;
}
static int proc_open(struct dfs_file *file)
{
return dfs_seq_open(file, stat_get_seq_ops());
}
static int proc_close(struct dfs_file *file)
{
return dfs_seq_release(file);
}
static const struct dfs_file_ops file_ops = {
.open = proc_open,
.read = dfs_seq_read,
.lseek = dfs_seq_lseek,
.close = proc_close,
};
int proc_stat_init(void)
{
struct proc_dentry *dentry = proc_create_data("stat", 0, NULL, &file_ops, NULL);
proc_release(dentry);
return 0;
}
INIT_ENV_EXPORT(proc_stat_init);
@@ -0,0 +1,100 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#include "proc.h"
#include "procfs.h"
#include <rthw.h>
#include <rtdbg.h>
#include <fcntl.h>
#include <errno.h>
#include <dfs_dentry.h>
static void *seq_start(struct dfs_seq_file *seq, off_t *index)
{
off_t i = *index; // seq->index
return NULL + (i == 0);
}
static void seq_stop(struct dfs_seq_file *seq, void *data)
{
}
static void *seq_next(struct dfs_seq_file *seq, void *data, off_t *index)
{
/* data: The return value of the start or next*/
off_t i = *index + 1; // seq->index
*index = i;
return NULL;
}
static int seq_show(struct dfs_seq_file *seq, void *data)
{
/* data: The return value of the start or next*/
dfs_seq_puts(seq, "todo\n");
return 0;
}
static const struct dfs_seq_ops seq_ops = {
.start = seq_start,
.stop = seq_stop,
.next = seq_next,
.show = seq_show,
};
void proc_tty_register_driver(void *driver)
{
//todo
}
void proc_tty_unregister_driver(void *driver)
{
//todo
}
int proc_tty_init(void)
{
struct proc_dentry *dentry;
dentry = proc_mkdir("tty", NULL);
if (!dentry)
return -1;
proc_release(dentry);
dentry = proc_mkdir("tty/ldisc", NULL);
proc_release(dentry);
dentry = proc_mkdir_mode("tty/driver", S_IRUSR|S_IXUSR, NULL);
proc_release(dentry);
dentry = proc_create_data("tty/ldiscs", 0, NULL, NULL, NULL);
if (dentry)
{
dentry->seq_ops = &seq_ops;
}
proc_release(dentry);
dentry = proc_create_data("tty/drivers", 0, NULL, NULL, NULL);
if (dentry)
{
dentry->seq_ops = &seq_ops;
}
proc_release(dentry);
return 0;
}
INIT_ENV_EXPORT(proc_tty_init);
@@ -0,0 +1,38 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#include "proc.h"
#include "procfs.h"
#include <rthw.h>
#include <rtdbg.h>
#include <fcntl.h>
#include <errno.h>
#include <dfs_dentry.h>
static int single_show(struct dfs_seq_file *seq, void *data)
{
dfs_seq_printf(seq, "%lu.%02lu %lu.%02lu\n",
(unsigned long)rt_tick_get_millisecond() / 1000, (unsigned long)(rt_tick_get_millisecond() % 1000) / 100,
(unsigned long)rt_tick_get_millisecond() / 1000, (unsigned long)(rt_tick_get_millisecond() % 1000) / 100);
return 0;
}
int proc_uptime_init(void)
{
struct proc_dentry *dentry = proc_create_single_data("uptime", 0, NULL, single_show, NULL);
proc_release(dentry);
return 0;
}
INIT_ENV_EXPORT(proc_uptime_init);
@@ -0,0 +1,45 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#include "proc.h"
#include "procfs.h"
#include <rthw.h>
#include <rtdbg.h>
#include <fcntl.h>
#include <errno.h>
#include <dfs_dentry.h>
static int single_show(struct dfs_seq_file *seq, void *data)
{
dfs_seq_puts(seq, "\n \\ | /\n");
#ifdef RT_USING_SMART
dfs_seq_puts(seq, "- RT - Thread Smart Operating System\n");
#else
dfs_seq_puts(seq, "- RT - Thread Operating System\n");
#endif
dfs_seq_printf(seq, " / | \\ %d.%d.%d build %s %s\n",
(rt_int32_t)RT_VERSION_MAJOR, (rt_int32_t)RT_VERSION_MINOR, (rt_int32_t)RT_VERSION_PATCH,
__DATE__, __TIME__);
dfs_seq_puts(seq, " 2006 - 2022 Copyright by RT-Thread team\n");
return 0;
}
int proc_version_init(void)
{
struct proc_dentry *dentry = proc_create_single_data("version", 0, NULL, single_show, NULL);
proc_release(dentry);
return 0;
}
INIT_ENV_EXPORT(proc_version_init);
@@ -0,0 +1,447 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#include <rthw.h>
#include <rtdbg.h>
#include <fcntl.h>
#include <errno.h>
#include <dfs.h>
#include <dfs_fs.h>
#include <dfs_file.h>
#include <dfs_posix.h>
#include <dfs_mnt.h>
#include <dfs_dentry.h>
#include "proc.h"
#include "procfs.h"
#define PROC_DEBUG(...) //rt_kprintf
static int dfs_procfs_open(struct dfs_file *file)
{
rt_err_t ret = RT_EOK;
struct proc_dentry *entry = (struct proc_dentry *)file->vnode->data;
RT_ASSERT(file->ref_count > 0);
// this file is opened and in an fdtable
if (file->ref_count > 1)
{
file->fpos = 0;
return ret;
}
if (entry->fops && entry->fops->open)
{
ret = entry->fops->open(file);
}
PROC_DEBUG(" %s %d >> %s ret: %d\n", __func__, __LINE__, file->dentry->pathname, ret);
return ret;
}
static int dfs_procfs_close(struct dfs_file *file)
{
rt_err_t ret = RT_EOK;
struct proc_dentry *entry = (struct proc_dentry *)file->vnode->data;
RT_ASSERT(file->vnode->ref_count > 0);
if (file->vnode->ref_count > 1)
{
return ret;
}
if (entry && entry->fops && entry->fops->close)
{
ret = entry->fops->close(file);
}
PROC_DEBUG(" %s %d >> %s ret: %d\n", __func__, __LINE__, file->dentry->pathname, ret);
return ret;
}
static ssize_t dfs_procfs_read(struct dfs_file *file, void *buf, size_t count, off_t *pos)
{
ssize_t ret = -RT_ERROR;
struct proc_dentry *entry = (struct proc_dentry *)file->vnode->data;
if (entry && entry->fops && entry->fops->read)
{
ret = entry->fops->read(file, buf, count, pos);
}
PROC_DEBUG(" %s %d >> %s ret: %d\n", __func__, __LINE__, file->dentry->pathname, ret);
return ret;
}
static ssize_t dfs_procfs_write(struct dfs_file *file, const void *buf, size_t count, off_t *pos)
{
ssize_t ret = -RT_ERROR;
struct proc_dentry *entry = (struct proc_dentry *)file->vnode->data;
if (entry && entry->fops && entry->fops->write)
{
ret = entry->fops->write(file, buf, count, pos);
}
PROC_DEBUG(" %s %d >> %s ret: %d\n", __func__, __LINE__, file->dentry->pathname, ret);
return ret;
}
static int dfs_procfs_ioctl(struct dfs_file *file, int cmd, void *args)
{
int ret = -RT_ERROR;
struct proc_dentry *entry = (struct proc_dentry *)file->vnode->data;
if (entry && entry->fops && entry->fops->ioctl)
{
ret = entry->fops->ioctl(file, cmd, args);
}
PROC_DEBUG(" %s %d >> %s ret: %d\n", __func__, __LINE__, file->dentry->pathname, ret);
return ret;
}
static int dfs_procfs_getdents(struct dfs_file *file, struct dirent *dirp, uint32_t count)
{
int ret = 0;
rt_uint32_t index = 0;
struct dirent *d;
struct proc_dentry *entry = (struct proc_dentry *)file->vnode->data;
if (entry)
{
struct proc_dentry *iter = RT_NULL, *tmp;
/* make integer count */
count = (count / sizeof(struct dirent));
if (count == 0)
{
return -EINVAL;
}
dfs_vfs_for_each_subnode(iter, tmp, entry, node)
{
if (iter == RT_NULL)
{
break;
}
if (index >= file->fpos)
{
d = dirp + index - file->fpos;
if (S_ISDIR(entry->mode))
{
d->d_type = DT_DIR;
}
else if (S_ISLNK(entry->mode))
{
d->d_type = DT_SYMLINK;
}
else
{
d->d_type = DT_REG;
}
d->d_namlen = rt_strlen(iter->name);
d->d_reclen = (rt_uint16_t)sizeof(struct dirent);
rt_strncpy(d->d_name, iter->name, rt_strlen(iter->name) + 1);
ret ++;
}
index++;
if (index - file->fpos >= count)
{
break;
}
}
if (ret > 0)
{
file->fpos = index;
}
if (entry->fops && entry->fops->getdents && ret < count)
{
int r;
file->fpos -= index;
r = entry->fops->getdents(file, dirp + ret, (count - ret) * sizeof(struct dirent));
ret = ret * sizeof(struct dirent);
if (r > 0)
{
ret += r;
}
file->fpos += index;
}
else
{
ret = ret * sizeof(struct dirent);
}
}
PROC_DEBUG(" %s %d >> %s ret: %d\n", __func__, __LINE__, file->dentry->pathname, ret);
return ret;
}
static int dfs_procfs_poll(struct dfs_file *file, struct rt_pollreq *req)
{
int ret = -RT_ERROR;
struct proc_dentry *entry = (struct proc_dentry *)file->vnode->data;
if (entry && entry->fops && entry->fops->poll)
{
ret = entry->fops->poll(file, req);
}
PROC_DEBUG(" %s %d >> %s ret: %d\n", __func__, __LINE__, file->dentry->pathname, ret);
return ret;
}
static int dfs_procfs_flush(struct dfs_file *file)
{
int ret = -RT_ERROR;
struct proc_dentry *entry = (struct proc_dentry *)file->vnode->data;
if (entry && entry->fops && entry->fops->flush)
{
ret = entry->fops->flush(file);
}
PROC_DEBUG(" %s %d >> %s ret: %d\n", __func__, __LINE__, file->dentry->pathname, ret);
return ret;
}
static int dfs_procfs_mount(struct dfs_mnt *mnt, unsigned long rwflag, const void *data)
{
RT_ASSERT(mnt != RT_NULL);
return RT_EOK;
}
static int dfs_procfs_umount(struct dfs_mnt *mnt)
{
RT_ASSERT(mnt != RT_NULL);
return RT_EOK;
}
static int dfs_procfs_readlink(struct dfs_dentry *dentry, char *buf, int len)
{
int ret = 0;
struct proc_dentry *entry = dfs_proc_find(dentry->pathname);
if (entry)
{
if (S_ISLNK(entry->mode) && entry->data)
{
if (entry->ops && entry->ops->readlink)
{
ret = entry->ops->readlink(entry, buf, len);
}
else
{
rt_strncpy(buf, (const char *)entry->data, len);
buf[len - 1] = '\0';
ret = rt_strlen(buf);
}
}
proc_release(entry);
}
PROC_DEBUG(" %s %d >> %s ret: %d\n", __func__, __LINE__, dentry->pathname, ret);
return ret;
}
static int dfs_procfs_unlink(struct dfs_dentry *dentry)
{
PROC_DEBUG(" %s %d >> %s ret: %d\n", __func__, __LINE__, dentry->pathname, -1);
return -RT_ERROR;
}
static int dfs_procfs_stat(struct dfs_dentry *dentry, struct stat *st)
{
int ret = RT_EOK;
struct dfs_vnode *vnode;
if (dentry && dentry->vnode)
{
vnode = dentry->vnode;
st->st_dev = (dev_t)(rt_ubase_t)(dentry->mnt->dev_id);
st->st_ino = (ino_t)dfs_dentry_full_path_crc32(dentry);
st->st_gid = vnode->gid;
st->st_uid = vnode->uid;
st->st_mode = vnode->mode;
st->st_nlink = vnode->nlink;
st->st_size = vnode->size;
st->st_mtim.tv_nsec = vnode->mtime.tv_nsec;
st->st_mtim.tv_sec = vnode->mtime.tv_sec;
st->st_ctim.tv_nsec = vnode->ctime.tv_nsec;
st->st_ctim.tv_sec = vnode->ctime.tv_sec;
st->st_atim.tv_nsec = vnode->atime.tv_nsec;
st->st_atim.tv_sec = vnode->atime.tv_sec;
}
PROC_DEBUG(" %s %d >> %s ret: %d\n", __func__, __LINE__, dentry->pathname, ret);
return ret;
}
static int dfs_procfs_statfs(struct dfs_mnt *mnt, struct statfs *buf)
{
if (mnt && buf)
{
buf->f_bsize = 512;
buf->f_blocks = 2048 * 64; // 64M
buf->f_bfree = buf->f_blocks;
buf->f_bavail = buf->f_bfree;
}
PROC_DEBUG(" %s %d\n", __func__, __LINE__);
return RT_EOK;
}
static struct dfs_vnode *dfs_procfs_lookup(struct dfs_dentry *dentry)
{
struct dfs_vnode *vnode = RT_NULL;
struct proc_dentry *entry = dfs_proc_find(dentry->pathname);
if (entry)
{
vnode = dfs_vnode_create();
if (vnode)
{
vnode->nlink = 1;
vnode->size = 0;
if (S_ISDIR(entry->mode))
{
vnode->mode = entry->mode;
vnode->type = FT_DIRECTORY;
}
else if (S_ISLNK(entry->mode))
{
vnode->mode = entry->mode;
vnode->type = FT_SYMLINK;
}
else
{
vnode->mode = entry->mode;
vnode->type = FT_REGULAR;
}
vnode->data = entry;
vnode->mnt = dentry->mnt;
}
proc_release(entry);
}
PROC_DEBUG(" %s %d >> %s\n", __func__, __LINE__, dentry->pathname);
return vnode;
}
static struct dfs_vnode *dfs_procfs_create_vnode(struct dfs_dentry *dentry, int type, mode_t mode)
{
return RT_NULL;
}
static int dfs_procfs_free_vnode(struct dfs_vnode *vnode)
{
return 0;
}
static const struct dfs_file_ops _procfs_fops =
{
.open = dfs_procfs_open,
.close = dfs_procfs_close,
.lseek = generic_dfs_lseek,
.read = dfs_procfs_read,
.write = dfs_procfs_write,
.ioctl = dfs_procfs_ioctl,
.getdents = dfs_procfs_getdents,
.poll = dfs_procfs_poll,
.flush = dfs_procfs_flush,
};
static const struct dfs_filesystem_ops _procfs_ops =
{
.name = "procfs",
.default_fops = &_procfs_fops,
.mount = dfs_procfs_mount,
.umount = dfs_procfs_umount,
.readlink = dfs_procfs_readlink,
.unlink = dfs_procfs_unlink,
.stat = dfs_procfs_stat,
.statfs = dfs_procfs_statfs,
.lookup = dfs_procfs_lookup,
.create_vnode = dfs_procfs_create_vnode,
.free_vnode = dfs_procfs_free_vnode,
};
static struct dfs_filesystem_type _procfs =
{
.fs_ops = &_procfs_ops,
};
int dfs_procfs_init(void)
{
/* register procfs file system */
dfs_register(&_procfs);
return 0;
}
INIT_COMPONENT_EXPORT(dfs_procfs_init);
int proc_read_data(struct dfs_file *file, void *buf, size_t count, off_t *pos)
{
if (file->fpos >= file->vnode->size)
{
return 0;
}
if (file->data)
{
count = file->vnode->size - file->fpos >= count ? count : file->vnode->size - file->fpos;
rt_strncpy(buf, file->data + file->fpos, count);
file->fpos += count;
*pos = file->fpos;
}
else
{
return 0;
}
return count;
}
@@ -0,0 +1,19 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#ifndef __PROC_FS_H__
#define __PROC_FS_H__
#include <dfs_file.h>
int dfs_procfs_init(void);
int proc_read_data(struct dfs_file *file, void *buf, size_t count, off_t *pos);
#endif
@@ -0,0 +1,5 @@
# The Pseudo Terminal Filesystem
The device register on ptyfs is also registered in device frameworks with `rt_device_register()`.
It's possible to mount a new ptyfs instance on another path. Each instance is isolated to each other. And they don't share the id system. But generally speaking, you have to mount the ptyfs on `/dev` root, since all the file nodes in ptyfs are devices.
@@ -0,0 +1,11 @@
# RT-Thread building script for component
from building import *
cwd = GetCurrentDir()
src = Glob('*.c')
CPPPATH = [cwd]
group = DefineGroup('Filesystem', src, depend = ['RT_USING_DFS', 'RT_USING_DFS_PTYFS'], CPPPATH = CPPPATH)
Return('group')
@@ -0,0 +1,658 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2023-12-02 Shell init ver.
*/
#define DBG_TAG "filesystem.ptyfs"
#define DBG_LVL DBG_INFO
#include <rtdbg.h>
#include "ptyfs.h"
#include <dfs.h>
#include <dfs_fs.h>
#include <dfs_dentry.h>
#include <dfs_file.h>
#include <dfs_mnt.h>
#include <devfs.h>
#include <rid_bitmap.h>
#include <rthw.h>
#include <rtthread.h>
#include <terminal/terminal.h>
#include <dirent.h>
#include <unistd.h>
#ifndef S_IRWXUGO
#define S_IRWXUGO (S_IRWXU | S_IRWXG | S_IRWXO)
#endif /* S_IRWXUGO */
#ifndef S_IALLUGO
#define S_IALLUGO (S_ISUID | S_ISGID | S_ISVTX | S_IRWXUGO)
#endif /* S_IALLUGO */
#ifndef S_IRUGO
#define S_IRUGO (S_IRUSR | S_IRGRP | S_IROTH)
#endif /* S_IRUGO */
#ifndef S_IWUGO
#define S_IWUGO (S_IWUSR | S_IWGRP | S_IWOTH)
#endif /* S_IWUGO */
#ifndef S_IXUGO
#define S_IXUGO (S_IXUSR | S_IXGRP | S_IXOTH)
#endif /* S_IXUGO */
#define PTYFS_MAGIC 0x9D94A07D
#define PTYFS_TYPE_DIR 0x00
#define PTYFS_TYPE_FILE_PTMX 0x01
#define PTYFS_TYPE_FILE_SLAVE 0x02
/* TODO: using Symbolic permission, but not ours */
#define PTMX_DEFAULT_FILE_MODE (S_IFCHR | 0666)
#define PTS_DEFAULT_FILE_MODE (S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP)
#define ROOT_DEFUALT_FILE_MODE (S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR)
struct ptyfs_sb;
struct ptyfs_file
{
char basename[DIRENT_NAME_MAX]; /* file name */
rt_uint32_t mode; /* file modes allowed */
rt_uint32_t type; /* file type */
rt_list_t subdirs; /* file subdir list */
rt_list_t ent_node; /* entry node in subdir list */
struct ptyfs_sb *sb; /* superblock ptr */
rt_device_t device; /* device binding on this file */
};
struct ptyfs_sb
{
struct rt_device ptmx_device; /* ptmx device */
struct rt_mutex lock; /* tmpfs lock */
struct ptyfs_file root_file; /* root dir */
struct ptyfs_file ptmx_file; /* `/ptmx` file */
struct rid_bitmap ptsno_pool; /* pts number pool */
rt_uint32_t magic; /* PTYFS_MAGIC */
rt_size_t df_size; /* df size */
rt_list_t sibling; /* sb sibling list */
struct dfs_mnt *mount; /* mount data */
/**
* Note: This upper limit is set to protect kernel memory from draining
* out by the application if it keeps allocating pty devices.
*
* Still, current implementation of bitmap can not efficiently use the
* memory
*/
rt_bitmap_t
ptsno_pool_bitset[LWP_PTY_MAX_PARIS_LIMIT / (sizeof(rt_bitmap_t) * 8)];
};
static struct dfs_file_ops _default_fops;
static int _split_out_subdir(const char *path, char *name)
{
const char *subpath = path;
while (*subpath == '/' && *subpath)
{
subpath++;
}
while (*subpath != '/' && *subpath)
{
*name++ = *subpath++;
}
*name = '\0';
return 0;
}
static rt_err_t ptyfile_init(struct ptyfs_file *file, struct ptyfs_sb *sb,
const char *name, rt_uint32_t type,
rt_uint32_t mode, rt_device_t device)
{
if (name)
strncpy(file->basename, name, sizeof(file->basename));
file->type = type;
file->mode = mode;
rt_list_init(&file->subdirs);
rt_list_init(&file->ent_node);
file->sb = sb;
file->device = device;
return 0;
}
static rt_err_t ptyfile_add_to_root(struct ptyfs_sb *sb,
struct ptyfs_file *new_file)
{
struct ptyfs_file *root_file = &sb->root_file;
/* update super block */
sb->df_size += sizeof(struct ptyfs_file);
rt_mutex_take(&sb->lock, RT_WAITING_FOREVER);
rt_list_insert_after(&(root_file->subdirs), &(new_file->ent_node));
rt_mutex_release(&sb->lock);
return 0;
}
static rt_err_t ptyfile_remove_from_root(struct ptyfs_sb *sb,
struct ptyfs_file *rm_file)
{
/* update super block */
sb->df_size -= sizeof(struct ptyfs_file);
rt_mutex_take(&sb->lock, RT_WAITING_FOREVER);
rt_list_remove(&(rm_file->ent_node));
rt_mutex_release(&sb->lock);
return 0;
}
static struct ptyfs_file *ptyfile_lookup(struct ptyfs_sb *superblock,
const char *path)
{
const char *subpath_iter, *curpath_iter, *basename = RT_NULL;
char subdir_name[DIRENT_NAME_MAX];
struct ptyfs_file *curfile, *found_file = RT_NULL;
rt_list_t *list;
int do_path_resolve = 1;
subpath_iter = path;
/* skip starting "/" */
while (*subpath_iter == '/') subpath_iter++;
if (!*subpath_iter)
{
return &(superblock->root_file);
}
curpath_iter = subpath_iter;
curfile = &superblock->root_file;
/* resolve chain of files splited from path one by one */
while (do_path_resolve)
{
do_path_resolve = 0;
/* splitout sub-directory or basename */
while (*subpath_iter != '/' && *subpath_iter) subpath_iter++;
if (!*subpath_iter)
{
basename = curpath_iter;
}
else
{
_split_out_subdir(curpath_iter, subdir_name);
/* skip "/" for next search */
subpath_iter++;
}
rt_mutex_take(&superblock->lock, RT_WAITING_FOREVER);
rt_list_for_each(list, &curfile->subdirs)
{
struct ptyfs_file *file_iter;
file_iter = rt_list_entry(list, struct ptyfs_file, ent_node);
if (basename)
{
if (strcmp(file_iter->basename, basename) == 0)
{
found_file = file_iter;
break;
}
}
else if (strcmp(file_iter->basename, subdir_name) == 0)
{
curpath_iter = subpath_iter;
curfile = file_iter;
do_path_resolve = 1;
break;
}
}
rt_mutex_release(&superblock->lock);
}
return found_file;
}
const char *ptyfs_get_rootpath(rt_device_t ptmx)
{
const char *rc;
struct ptyfs_sb *sb;
/* allocate id for it and register file */
sb = rt_container_of(ptmx, struct ptyfs_sb, ptmx_device);
if (sb->magic != PTYFS_MAGIC)
{
rc = 0;
}
else
{
/* fullpath is always started with /dev/ */
return sb->mount->fullpath + 5;
}
return rc;
}
ptsno_t ptyfs_register_pts(rt_device_t ptmx, rt_device_t pts)
{
ptsno_t rc;
struct ptyfs_sb *sb;
struct ptyfs_file *pts_file;
struct rid_bitmap *ptsno_pool;
/* allocate id for it and register file */
sb = rt_container_of(ptmx, struct ptyfs_sb, ptmx_device);
if (sb->magic != PTYFS_MAGIC)
{
rc = -1;
}
else
{
ptsno_pool = &sb->ptsno_pool;
rc = rid_bitmap_get(ptsno_pool);
if (rc >= 0)
{
pts_file = rt_calloc(1, sizeof(struct ptyfs_file));
if (pts_file)
{
snprintf(pts_file->basename, DIRENT_NAME_MAX, "%lu", (unsigned long)rc);
ptyfile_init(pts_file, sb, 0, PTYFS_TYPE_FILE_SLAVE,
PTS_DEFAULT_FILE_MODE, pts);
ptyfile_add_to_root(sb, pts_file);
}
else
{
rid_bitmap_put(ptsno_pool, rc);
rc = -1;
}
}
/* else rc == -1 */
}
return rc;
}
rt_err_t ptyfs_unregister_pts(rt_device_t ptmx, ptsno_t ptsno)
{
ptsno_t rc;
struct ptyfs_sb *sb;
struct ptyfs_file *pts_file;
struct rid_bitmap *ptsno_pool;
char path_buf[DIRENT_NAME_MAX];
/* allocate id for it and register file */
sb = rt_container_of(ptmx, struct ptyfs_sb, ptmx_device);
if (sb->magic != PTYFS_MAGIC || ptsno < 0)
{
rc = -EINVAL;
}
else
{
/* get path and findout device */
snprintf(path_buf, sizeof(path_buf), "%lu", (unsigned long)ptsno);
pts_file = ptyfile_lookup(sb, path_buf);
if (pts_file)
{
ptyfile_remove_from_root(sb, pts_file);
ptsno_pool = &sb->ptsno_pool;
rid_bitmap_put(ptsno_pool, ptsno);
rc = 0;
}
else
{
rc = -ENOENT;
}
}
return rc;
}
#define DEVFS_PREFIX "/dev/"
#define DEVFS_PREFIX_LEN (sizeof(DEVFS_PREFIX) - 1)
/**
* Create an new instance of ptyfs, and mount on target point
* 2 basic files are created: root, ptmx.
*
* todo: support of mount options?
*/
static int ptyfs_ops_mount(struct dfs_mnt *mnt, unsigned long rwflag,
const void *data)
{
struct ptyfs_sb *sb;
rt_device_t ptmx_device;
rt_err_t rc;
if (strncmp(mnt->fullpath, DEVFS_PREFIX, DEVFS_PREFIX_LEN) != 0)
{
LOG_I("%s() Not mounted on `/dev/'", __func__);
return -EINVAL;
}
sb = rt_calloc(1, sizeof(struct ptyfs_sb));
if (sb)
{
rt_mutex_init(&sb->lock, "ptyfs", RT_IPC_FLAG_PRIO);
/* setup the ptmx device */
ptmx_device = &sb->ptmx_device;
rc = lwp_ptmx_init(ptmx_device, mnt->fullpath + DEVFS_PREFIX_LEN);
if (rc == RT_EOK)
{
/* setup 2 basic files */
ptyfile_init(&sb->root_file, sb, "/", PTYFS_TYPE_DIR,
ROOT_DEFUALT_FILE_MODE, 0);
ptyfile_init(&sb->ptmx_file, sb, "ptmx", PTYFS_TYPE_FILE_PTMX,
PTMX_DEFAULT_FILE_MODE, ptmx_device);
ptyfile_add_to_root(sb, &sb->ptmx_file);
/* setup rid */
rid_bitmap_init(&sb->ptsno_pool, 0, LWP_PTY_MAX_PARIS_LIMIT,
sb->ptsno_pool_bitset, &sb->lock);
/* setup properties and members */
sb->magic = PTYFS_MAGIC;
sb->df_size = sizeof(struct ptyfs_sb);
rt_list_init(&sb->sibling);
/* binding superblocks and mount point */
mnt->data = sb;
sb->mount = mnt;
rc = 0;
}
/* else just return rc */
}
else
{
rc = -ENOMEM;
}
return rc;
}
static int ptyfs_ops_umount(struct dfs_mnt *mnt)
{
/* Not supported yet */
return -1;
}
static int ptyfs_ops_setattr(struct dfs_dentry *dentry, struct dfs_attr *attr)
{
struct ptyfs_file *pty_file;
struct ptyfs_sb *superblock;
RT_ASSERT(dentry);
RT_ASSERT(dentry->mnt);
superblock = (struct ptyfs_sb *)dentry->mnt->data;
RT_ASSERT(superblock);
/* find the device related to current pts slave device */
pty_file = ptyfile_lookup(superblock, dentry->pathname);
if (pty_file && pty_file->type == PTYFS_TYPE_FILE_SLAVE)
{
pty_file->mode &= ~0xFFF;
pty_file->mode |= attr->st_mode & 0xFFF;
return 0;
}
return -1;
}
#define OPTIMAL_BSIZE 1024
static int ptyfs_ops_statfs(struct dfs_mnt *mnt, struct statfs *buf)
{
struct ptyfs_sb *superblock;
RT_ASSERT(mnt != NULL);
RT_ASSERT(buf != NULL);
superblock = (struct ptyfs_sb *)mnt->data;
RT_ASSERT(superblock != NULL);
buf->f_bsize = OPTIMAL_BSIZE;
buf->f_blocks = (superblock->df_size + OPTIMAL_BSIZE - 1) / OPTIMAL_BSIZE;
buf->f_bfree = 1;
buf->f_bavail = buf->f_bfree;
return RT_EOK;
}
static int ptyfs_ops_stat(struct dfs_dentry *dentry, struct stat *st)
{
struct dfs_vnode *vnode;
if (dentry && dentry->vnode)
{
vnode = dentry->vnode;
/* device id ? */
st->st_dev = (dev_t)(long)(dentry->mnt->dev_id);
st->st_ino = (ino_t)dfs_dentry_full_path_crc32(dentry);
st->st_gid = vnode->gid;
st->st_uid = vnode->uid;
st->st_mode = vnode->mode;
st->st_nlink = vnode->nlink;
st->st_size = vnode->size;
st->st_mtim.tv_nsec = vnode->mtime.tv_nsec;
st->st_mtim.tv_sec = vnode->mtime.tv_sec;
st->st_ctim.tv_nsec = vnode->ctime.tv_nsec;
st->st_ctim.tv_sec = vnode->ctime.tv_sec;
st->st_atim.tv_nsec = vnode->atime.tv_nsec;
st->st_atim.tv_sec = vnode->atime.tv_sec;
}
return 0;
}
static struct dfs_vnode *ptyfs_ops_lookup(struct dfs_dentry *dentry)
{
struct dfs_vnode *vnode = RT_NULL;
struct ptyfs_sb *superblock;
struct ptyfs_file *pty_file;
if (dentry == NULL || dentry->mnt == NULL || dentry->mnt->data == NULL)
{
return NULL;
}
superblock = (struct ptyfs_sb *)dentry->mnt->data;
pty_file = ptyfile_lookup(superblock, dentry->pathname);
if (pty_file)
{
vnode = dfs_vnode_create();
if (vnode)
{
vnode->data = pty_file->device;
vnode->nlink = 1;
vnode->size = 0;
vnode->mnt = dentry->mnt;
/* if it's root directory */
vnode->fops = &_default_fops;
vnode->mode = pty_file->mode;
vnode->type = pty_file->type == PTYFS_TYPE_DIR ? FT_DIRECTORY : FT_DEVICE;
}
}
return vnode;
}
static struct dfs_vnode *ptyfs_ops_create_vnode(struct dfs_dentry *dentry,
int type, mode_t mode)
{
struct dfs_vnode *vnode = RT_NULL;
struct ptyfs_sb *sb;
struct ptyfs_file *pty_file;
char *vnode_path;
if (dentry == NULL || dentry->mnt == NULL || dentry->mnt->data == NULL)
{
return NULL;
}
sb = (struct ptyfs_sb *)dentry->mnt->data;
RT_ASSERT(sb != NULL);
vnode = dfs_vnode_create();
if (vnode)
{
vnode_path = dentry->pathname;
/* Query if file existed. Filter out illegal open modes */
pty_file = ptyfile_lookup(sb, vnode_path);
if (!pty_file || (~pty_file->mode & mode))
{
dfs_vnode_destroy(vnode);
return NULL;
}
vnode->data = pty_file->device;
vnode->nlink = 1;
vnode->size = 0;
vnode->mnt = dentry->mnt;
vnode->fops = pty_file->device ? pty_file->device->fops : RT_NULL;
vnode->mode &= pty_file->mode;
if (type == FT_DIRECTORY)
{
vnode->mode |= S_IFDIR;
vnode->type = FT_DIRECTORY;
LOG_I("%s: S_IFDIR created", __func__);
}
else if (type == FT_REGULAR)
{
vnode->mode |= S_IFCHR;
vnode->type = FT_DEVICE;
LOG_I("%s: S_IFDIR created", __func__);
}
else
{
/* unsupported types */
dfs_vnode_destroy(vnode);
return NULL;
}
}
return vnode;
}
static int ptyfs_ops_free_vnode(struct dfs_vnode *vnode)
{
return RT_EOK;
}
static int devpty_deffops_getdents(struct dfs_file *file, struct dirent *dirp,
uint32_t count)
{
struct ptyfs_file *d_file;
struct ptyfs_sb *superblock;
RT_ASSERT(file);
RT_ASSERT(file->dentry);
RT_ASSERT(file->dentry->mnt);
superblock = (struct ptyfs_sb *)file->dentry->mnt->data;
RT_ASSERT(superblock);
d_file = ptyfile_lookup(superblock, file->dentry->pathname);
if (d_file)
{
rt_size_t index, end;
struct dirent *d;
struct ptyfs_file *n_file;
rt_list_t *list;
/* make integer count */
count = (count / sizeof(struct dirent));
if (count == 0)
{
return -EINVAL;
}
end = file->fpos + count;
index = 0;
count = 0;
rt_list_for_each(list, &d_file->subdirs)
{
if (index >= (rt_size_t)file->fpos)
{
n_file = rt_list_entry(list, struct ptyfs_file, ent_node);
d = dirp + count;
if (n_file->type == PTYFS_TYPE_DIR)
{
d->d_type = DT_DIR;
}
else
{
/* ptmx(5,2) or slave(136,[0,1048575]) device, on Linux */
d->d_type = DT_CHR;
}
d->d_reclen = (rt_uint16_t)sizeof(struct dirent);
rt_strncpy(d->d_name, n_file->basename, DIRENT_NAME_MAX);
d->d_namlen = rt_strlen(d->d_name);
count += 1;
file->fpos += 1;
}
index += 1;
if (index >= end)
{
break;
}
}
}
return count * sizeof(struct dirent);
}
static const struct dfs_filesystem_ops _ptyfs_ops = {
.name = "ptyfs",
.flags = DFS_FS_FLAG_DEFAULT,
.default_fops = &_default_fops,
.mount = ptyfs_ops_mount,
.umount = ptyfs_ops_umount,
/* don't allow to create symbolic link */
.symlink = RT_NULL,
.readlink = RT_NULL,
.unlink = RT_NULL,
.setattr = ptyfs_ops_setattr,
.statfs = ptyfs_ops_statfs,
.stat = ptyfs_ops_stat,
.lookup = ptyfs_ops_lookup,
.create_vnode = ptyfs_ops_create_vnode,
.free_vnode = ptyfs_ops_free_vnode,
};
static struct dfs_filesystem_type _devptyfs = {
.fs_ops = &_ptyfs_ops,
};
static int _ptyfs_init(void)
{
_default_fops = *dfs_devfs_fops();
_default_fops.getdents = devpty_deffops_getdents;
/* register file system */
dfs_register(&_devptyfs);
return 0;
}
INIT_COMPONENT_EXPORT(_ptyfs_init);
@@ -0,0 +1,22 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2023-12-02 Shell init ver.
*/
#ifndef __FS_PTYFS_H__
#define __FS_PTYFS_H__
#include <rtthread.h>
typedef rt_base_t ptsno_t;
ptsno_t ptyfs_register_pts(rt_device_t ptmx, rt_device_t pts);
rt_err_t ptyfs_unregister_pts(rt_device_t ptmx, ptsno_t ptsno);
const char *ptyfs_get_rootpath(rt_device_t ptmx);
#endif /* __FS_PTYFS_H__ */
@@ -0,0 +1,9 @@
from building import *
cwd = GetCurrentDir()
src = Glob('*.c')
CPPPATH = [cwd]
group = DefineGroup('Filesystem', src, depend = ['RT_USING_DFS', 'RT_USING_MEMHEAP', 'RT_USING_DFS_RAMFS'], CPPPATH = CPPPATH)
Return('group')
@@ -0,0 +1,479 @@
/*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2013-04-15 Bernard the first version
* 2013-05-05 Bernard remove CRC for ramfs persistence
* 2013-05-22 Bernard fix the no entry issue.
*/
#include <rtthread.h>
#include <dfs.h>
#include <dfs_fs.h>
#include <dfs_file.h>
#include "dfs_ramfs.h"
int dfs_ramfs_mount(struct dfs_filesystem *fs,
unsigned long rwflag,
const void *data)
{
struct dfs_ramfs *ramfs;
if (data == NULL)
return -EIO;
ramfs = (struct dfs_ramfs *)data;
fs->data = ramfs;
return RT_EOK;
}
int dfs_ramfs_unmount(struct dfs_filesystem *fs)
{
fs->data = NULL;
return RT_EOK;
}
int dfs_ramfs_statfs(struct dfs_filesystem *fs, struct statfs *buf)
{
struct dfs_ramfs *ramfs;
ramfs = (struct dfs_ramfs *)fs->data;
RT_ASSERT(ramfs != NULL);
RT_ASSERT(buf != NULL);
buf->f_bsize = 512;
buf->f_blocks = ramfs->memheap.pool_size / 512;
buf->f_bfree = ramfs->memheap.available_size / 512;
return RT_EOK;
}
int dfs_ramfs_ioctl(struct dfs_file *file, int cmd, void *args)
{
return -EIO;
}
struct ramfs_dirent *dfs_ramfs_lookup(struct dfs_ramfs *ramfs,
const char *path,
rt_size_t *size)
{
const char *subpath;
struct ramfs_dirent *dirent;
subpath = path;
while (*subpath == '/' && *subpath)
subpath ++;
if (! *subpath) /* is root directory */
{
*size = 0;
return &(ramfs->root);
}
for (dirent = rt_list_entry(ramfs->root.list.next, struct ramfs_dirent, list);
dirent != &(ramfs->root);
dirent = rt_list_entry(dirent->list.next, struct ramfs_dirent, list))
{
if (rt_strcmp(dirent->name, subpath) == 0)
{
*size = dirent->size;
return dirent;
}
}
/* not found */
return NULL;
}
int dfs_ramfs_read(struct dfs_file *file, void *buf, size_t count)
{
rt_size_t length;
struct ramfs_dirent *dirent;
dirent = (struct ramfs_dirent *)file->vnode->data;
RT_ASSERT(dirent != NULL);
if (count < file->vnode->size - file->pos)
length = count;
else
length = file->vnode->size - file->pos;
if (length > 0)
rt_memcpy(buf, &(dirent->data[file->pos]), length);
/* update file current position */
file->pos += length;
return length;
}
int dfs_ramfs_write(struct dfs_file *fd, const void *buf, size_t count)
{
struct ramfs_dirent *dirent;
struct dfs_ramfs *ramfs;
dirent = (struct ramfs_dirent *)fd->vnode->data;
RT_ASSERT(dirent != NULL);
ramfs = dirent->fs;
RT_ASSERT(ramfs != NULL);
if (count + fd->pos > fd->vnode->size)
{
rt_uint8_t *ptr;
ptr = rt_memheap_realloc(&(ramfs->memheap), dirent->data, fd->pos + count);
if (ptr == NULL)
{
rt_set_errno(-ENOMEM);
return 0;
}
/* update dirent and file size */
dirent->data = ptr;
dirent->size = fd->pos + count;
fd->vnode->size = dirent->size;
}
if (count > 0)
rt_memcpy(dirent->data + fd->pos, buf, count);
/* update file current position */
fd->pos += count;
return count;
}
int dfs_ramfs_lseek(struct dfs_file *file, off_t offset)
{
if (offset <= (off_t)file->vnode->size)
{
file->pos = offset;
return file->pos;
}
return -EIO;
}
int dfs_ramfs_close(struct dfs_file *file)
{
RT_ASSERT(file->vnode->ref_count > 0);
if (file->vnode->ref_count > 1)
{
return 0;
}
file->vnode->data = NULL;
return RT_EOK;
}
int dfs_ramfs_open(struct dfs_file *file)
{
rt_size_t size;
struct dfs_ramfs *ramfs;
struct ramfs_dirent *dirent;
struct dfs_filesystem *fs;
RT_ASSERT(file->vnode->ref_count > 0);
if (file->vnode->ref_count > 1)
{
if (file->vnode->type == FT_DIRECTORY
&& !(file->flags & O_DIRECTORY))
{
return -ENOENT;
}
file->pos = 0;
return 0;
}
fs = file->vnode->fs;
ramfs = (struct dfs_ramfs *)fs->data;
RT_ASSERT(ramfs != NULL);
if (file->flags & O_DIRECTORY)
{
if (file->flags & O_CREAT)
{
return -ENOSPC;
}
/* open directory */
dirent = dfs_ramfs_lookup(ramfs, file->vnode->path, &size);
if (dirent == NULL)
return -ENOENT;
if (dirent == &(ramfs->root)) /* it's root directory */
{
if (!(file->flags & O_DIRECTORY))
{
return -ENOENT;
}
}
file->vnode->type = FT_DIRECTORY;
}
else
{
dirent = dfs_ramfs_lookup(ramfs, file->vnode->path, &size);
if (dirent == &(ramfs->root)) /* it's root directory */
{
return -ENOENT;
}
if (dirent == NULL)
{
if (file->flags & O_CREAT || file->flags & O_WRONLY)
{
char *name_ptr;
/* create a file entry */
dirent = (struct ramfs_dirent *)
rt_memheap_alloc(&(ramfs->memheap),
sizeof(struct ramfs_dirent));
if (dirent == NULL)
{
return -ENOMEM;
}
/* remove '/' separator */
name_ptr = file->vnode->path;
while (*name_ptr == '/' && *name_ptr)
{
name_ptr++;
}
strncpy(dirent->name, name_ptr, RAMFS_NAME_MAX);
rt_list_init(&(dirent->list));
dirent->data = NULL;
dirent->size = 0;
dirent->fs = ramfs;
file->vnode->type = FT_DIRECTORY;
/* add to the root directory */
rt_list_insert_after(&(ramfs->root.list), &(dirent->list));
}
else
return -ENOENT;
}
/* Creates a new file.
* If the file is existing, it is truncated and overwritten.
*/
if (file->flags & O_TRUNC)
{
dirent->size = 0;
if (dirent->data != NULL)
{
rt_memheap_free(dirent->data);
dirent->data = NULL;
}
}
}
file->vnode->data = dirent;
file->vnode->size = dirent->size;
if (file->flags & O_APPEND)
{
file->pos = file->vnode->size;
}
else
{
file->pos = 0;
}
return 0;
}
int dfs_ramfs_stat(struct dfs_filesystem *fs,
const char *path,
struct stat *st)
{
rt_size_t size;
struct ramfs_dirent *dirent;
struct dfs_ramfs *ramfs;
ramfs = (struct dfs_ramfs *)fs->data;
dirent = dfs_ramfs_lookup(ramfs, path, &size);
if (dirent == NULL)
return -ENOENT;
st->st_dev = 0;
st->st_mode = S_IFREG | S_IRUSR | S_IRGRP | S_IROTH |
S_IWUSR | S_IWGRP | S_IWOTH;
st->st_size = dirent->size;
st->st_mtime = 0;
return RT_EOK;
}
int dfs_ramfs_getdents(struct dfs_file *file,
struct dirent *dirp,
uint32_t count)
{
rt_size_t index, end;
struct dirent *d;
struct ramfs_dirent *dirent;
struct dfs_ramfs *ramfs;
dirent = (struct ramfs_dirent *)file->vnode->data;
ramfs = dirent->fs;
RT_ASSERT(ramfs != RT_NULL);
if (dirent != &(ramfs->root))
return -EINVAL;
/* make integer count */
count = (count / sizeof(struct dirent));
if (count == 0)
return -EINVAL;
end = file->pos + count;
index = 0;
count = 0;
for (dirent = rt_list_entry(dirent->list.next, struct ramfs_dirent, list);
dirent != &(ramfs->root) && index < end;
dirent = rt_list_entry(dirent->list.next, struct ramfs_dirent, list))
{
if (index >= (rt_size_t)file->pos)
{
d = dirp + count;
d->d_type = DT_REG;
d->d_namlen = RT_NAME_MAX;
d->d_reclen = (rt_uint16_t)sizeof(struct dirent);
rt_strncpy(d->d_name, dirent->name, RAMFS_NAME_MAX);
count += 1;
file->pos += 1;
}
index += 1;
}
return count * sizeof(struct dirent);
}
int dfs_ramfs_unlink(struct dfs_filesystem *fs, const char *path)
{
rt_size_t size;
struct dfs_ramfs *ramfs;
struct ramfs_dirent *dirent;
ramfs = (struct dfs_ramfs *)fs->data;
RT_ASSERT(ramfs != NULL);
dirent = dfs_ramfs_lookup(ramfs, path, &size);
if (dirent == NULL)
return -ENOENT;
rt_list_remove(&(dirent->list));
if (dirent->data != NULL)
rt_memheap_free(dirent->data);
rt_memheap_free(dirent);
return RT_EOK;
}
int dfs_ramfs_rename(struct dfs_filesystem *fs,
const char *oldpath,
const char *newpath)
{
struct ramfs_dirent *dirent;
struct dfs_ramfs *ramfs;
rt_size_t size;
ramfs = (struct dfs_ramfs *)fs->data;
RT_ASSERT(ramfs != NULL);
dirent = dfs_ramfs_lookup(ramfs, newpath, &size);
if (dirent != NULL)
return -EEXIST;
dirent = dfs_ramfs_lookup(ramfs, oldpath, &size);
if (dirent == NULL)
return -ENOENT;
strncpy(dirent->name, newpath, RAMFS_NAME_MAX);
return RT_EOK;
}
static const struct dfs_file_ops _ram_fops =
{
dfs_ramfs_open,
dfs_ramfs_close,
dfs_ramfs_ioctl,
dfs_ramfs_read,
dfs_ramfs_write,
NULL, /* flush */
dfs_ramfs_lseek,
dfs_ramfs_getdents,
};
static const struct dfs_filesystem_ops _ramfs =
{
"ram",
DFS_FS_FLAG_DEFAULT,
&_ram_fops,
dfs_ramfs_mount,
dfs_ramfs_unmount,
NULL, /* mkfs */
dfs_ramfs_statfs,
dfs_ramfs_unlink,
dfs_ramfs_stat,
dfs_ramfs_rename,
};
int dfs_ramfs_init(void)
{
/* register ram file system */
dfs_register(&_ramfs);
return 0;
}
INIT_COMPONENT_EXPORT(dfs_ramfs_init);
struct dfs_ramfs *dfs_ramfs_create(rt_uint8_t *pool, rt_size_t size)
{
struct dfs_ramfs *ramfs;
rt_uint8_t *data_ptr;
rt_err_t result;
size = RT_ALIGN_DOWN(size, RT_ALIGN_SIZE);
ramfs = (struct dfs_ramfs *)pool;
data_ptr = (rt_uint8_t *)(ramfs + 1);
size = size - sizeof(struct dfs_ramfs);
size = RT_ALIGN_DOWN(size, RT_ALIGN_SIZE);
result = rt_memheap_init(&ramfs->memheap, "ramfs", data_ptr, size);
if (result != RT_EOK)
return NULL;
/* detach this memheap object from the system */
rt_object_detach((rt_object_t) & (ramfs->memheap));
/* initialize ramfs object */
ramfs->magic = RAMFS_MAGIC;
ramfs->memheap.parent.type = RT_Object_Class_MemHeap | RT_Object_Class_Static;
/* initialize root directory */
rt_memset(&(ramfs->root), 0x00, sizeof(ramfs->root));
rt_list_init(&(ramfs->root.list));
ramfs->root.size = 0;
strcpy(ramfs->root.name, ".");
ramfs->root.fs = ramfs;
return ramfs;
}
@@ -0,0 +1,47 @@
/*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2013-04-15 Bernard the first version
* 2013-05-05 Bernard remove CRC for ramfs persistence
*/
#ifndef __DFS_RAMFS_H__
#define __DFS_RAMFS_H__
#include <rtthread.h>
#include <rtservice.h>
#define RAMFS_NAME_MAX 32
#define RAMFS_MAGIC 0x0A0A0A0A
struct ramfs_dirent
{
rt_list_t list;
struct dfs_ramfs *fs; /* file system ref */
char name[RAMFS_NAME_MAX]; /* dirent name */
rt_uint8_t *data;
rt_size_t size; /* file size */
};
/**
* DFS ramfs object
*/
struct dfs_ramfs
{
rt_uint32_t magic;
struct rt_memheap memheap;
struct ramfs_dirent root;
};
int dfs_ramfs_init(void);
struct dfs_ramfs *dfs_ramfs_create(rt_uint8_t *pool, rt_size_t size);
#endif
@@ -0,0 +1,11 @@
# RT-Thread building script for component
from building import *
cwd = GetCurrentDir()
src = Glob('*.c')
CPPPATH = [cwd]
group = DefineGroup('Filesystem', src, depend = ['RT_USING_DFS','RT_USING_DFS_ROMFS'], CPPPATH = CPPPATH)
Return('group')
@@ -0,0 +1,398 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#include <rtthread.h>
#include <dfs.h>
#include <dfs_fs.h>
#include <dfs_dentry.h>
#include <dfs_file.h>
#include <dfs_mnt.h>
#include "dfs_romfs.h"
#include <errno.h>
#include <fcntl.h>
#include <rtdbg.h>
static const struct dfs_file_ops _rom_fops;
static const mode_t romfs_modemap[] =
{
S_IFREG | 0644, /* regular file */
S_IFDIR | 0644, /* directory */
0, /* hard link */
S_IFLNK | 0777, /* symlink */
S_IFBLK | 0600, /* blockdev */
S_IFCHR | 0600, /* chardev */
S_IFSOCK | 0644, /* socket */
S_IFIFO | 0644 /* FIFO */
};
static int dfs_romfs_mount(struct dfs_mnt *mnt, unsigned long rwflag, const void *data)
{
struct romfs_dirent *root_dirent;
if (data == NULL)
return -1;
root_dirent = (struct romfs_dirent *)data;
mnt->data = root_dirent;
return 0;
}
static int dfs_romfs_umount(struct dfs_mnt *fs)
{
return RT_EOK;
}
int dfs_romfs_ioctl(struct dfs_file *file, int cmd, void *args)
{
int ret = RT_EOK;
struct romfs_dirent *dirent;
dirent = (struct romfs_dirent *)file->data;
RT_ASSERT(dirent != NULL);
switch (cmd)
{
case RT_FIOGETADDR:
{
*(rt_ubase_t*)args = (rt_ubase_t)dirent->data;
break;
}
case RT_FIOFTRUNCATE:
{
break;
}
default:
ret = -RT_EINVAL;
break;
}
return ret;
}
rt_inline int check_dirent(struct romfs_dirent *dirent)
{
if (dirent == NULL
||(dirent->type != ROMFS_DIRENT_FILE && dirent->type != ROMFS_DIRENT_DIR)
|| dirent->size == ~0)
return -1;
return 0;
}
struct romfs_dirent *__dfs_romfs_lookup(struct romfs_dirent *root_dirent, const char *path, rt_size_t *size)
{
rt_size_t index, found;
const char *subpath, *subpath_end;
struct romfs_dirent *dirent;
rt_size_t dirent_size;
/* Check the root_dirent. */
if (check_dirent(root_dirent) != 0)
return NULL;
if (path[0] == '/' && path[1] == '\0')
{
*size = root_dirent->size;
return root_dirent;
}
/* goto root directy entries */
dirent = (struct romfs_dirent *)root_dirent->data;
dirent_size = root_dirent->size;
/* get the end position of this subpath */
subpath_end = path;
/* skip /// */
while (*subpath_end && *subpath_end == '/')
subpath_end ++;
subpath = subpath_end;
while ((*subpath_end != '/') && *subpath_end)
subpath_end ++;
while (dirent != NULL)
{
found = 0;
/* search in folder */
for (index = 0; index < dirent_size; index ++)
{
if (check_dirent(&dirent[index]) != 0)
return NULL;
if (rt_strlen(dirent[index].name) == (subpath_end - subpath) &&
rt_strncmp(dirent[index].name, subpath, (subpath_end - subpath)) == 0)
{
dirent_size = dirent[index].size;
/* skip /// */
while (*subpath_end && *subpath_end == '/')
subpath_end ++;
subpath = subpath_end;
while ((*subpath_end != '/') && *subpath_end)
subpath_end ++;
if (!(*subpath))
{
*size = dirent_size;
return &dirent[index];
}
if (dirent[index].type == ROMFS_DIRENT_DIR)
{
/* enter directory */
dirent = (struct romfs_dirent *)dirent[index].data;
found = 1;
break;
}
else
{
/* return file dirent */
return &dirent[index];
}
}
}
if (!found)
break; /* not found */
}
/* not found */
return NULL;
}
static struct dfs_vnode *dfs_romfs_lookup (struct dfs_dentry *dentry)
{
rt_size_t size;
struct dfs_vnode *vnode = RT_NULL;
struct romfs_dirent *root_dirent = RT_NULL, *dirent = RT_NULL;
RT_ASSERT(dentry != RT_NULL);
RT_ASSERT(dentry->mnt != RT_NULL);
root_dirent = (struct romfs_dirent *)dentry->mnt->data;
if (check_dirent(root_dirent) == 0)
{
/* create a vnode */
DLOG(msg, "rom", "vnode", DLOG_MSG, "dfs_vnode_create()");
vnode = dfs_vnode_create();
if (vnode)
{
dirent = __dfs_romfs_lookup(root_dirent, dentry->pathname, &size);
if (dirent)
{
vnode->nlink = 1;
vnode->size = dirent->size;
if (dirent->type == ROMFS_DIRENT_DIR)
{
vnode->mode = romfs_modemap[ROMFS_DIRENT_DIR] | (S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
vnode->type = FT_DIRECTORY;
}
else if (dirent->type == ROMFS_DIRENT_FILE)
{
vnode->mode = romfs_modemap[ROMFS_DIRENT_FILE] | (S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
vnode->type = FT_REGULAR;
}
DLOG(msg, "rom", "rom", DLOG_MSG, "vnode->data = dirent");
vnode->data = dirent;
vnode->mnt = dentry->mnt;
}
else
{
/* no-entry */
DLOG(msg, "rom", "vnode", DLOG_MSG, "dfs_vnode_destroy, no-dentry");
dfs_vnode_destroy(vnode);
vnode = RT_NULL;
}
}
}
return vnode;
}
static int dfs_romfs_free_vnode(struct dfs_vnode *vnode)
{
/* nothing to be freed */
if (vnode->ref_count <= 1)
{
vnode->data = NULL;
}
return 0;
}
static ssize_t dfs_romfs_read(struct dfs_file *file, void *buf, size_t count, off_t *pos)
{
rt_size_t length;
struct romfs_dirent *dirent;
dirent = (struct romfs_dirent *)file->vnode->data;
RT_ASSERT(dirent != NULL);
if (check_dirent(dirent) != 0)
{
return -EIO;
}
if (count < file->vnode->size - *pos)
length = count;
else
length = file->vnode->size - *pos;
if (length > 0)
memcpy(buf, &(dirent->data[*pos]), length);
/* update file current position */
*pos += length;
return length;
}
static int dfs_romfs_close(struct dfs_file *file)
{
return RT_EOK;
}
int dfs_romfs_open(struct dfs_file *file)
{
rt_size_t size;
struct romfs_dirent *dirent;
struct romfs_dirent *root_dirent;
struct dfs_mnt *mnt;
if (file->flags & (O_CREAT | O_WRONLY | O_APPEND | O_TRUNC | O_RDWR))
{
return -EINVAL;
}
mnt = file->dentry->mnt;
RT_ASSERT(mnt != RT_NULL);
root_dirent = (struct romfs_dirent *)mnt->data;
if (check_dirent(root_dirent) != 0)
{
return -EIO;
}
/* get rom dirent */
dirent = __dfs_romfs_lookup(root_dirent, file->dentry->pathname, &size);
if (dirent == NULL)
{
return -ENOENT;
}
file->data = dirent;
file->fops = &_rom_fops;
file->fpos = 0;
return RT_EOK;
}
static int dfs_romfs_stat(struct dfs_dentry *dentry, struct stat *st)
{
rt_err_t ret = dfs_file_lock();
if (ret == RT_EOK)
{
st->st_dev = 0;
st->st_mode = dentry->vnode->mode;
st->st_size = dentry->vnode->size;
st->st_nlink = dentry->vnode->nlink;
st->st_mtime = 0;
dfs_file_unlock();
}
return RT_EOK;
}
static int dfs_romfs_getdents(struct dfs_file *file, struct dirent *dirp, uint32_t count)
{
rt_size_t index;
const char *name;
struct dirent *d;
struct romfs_dirent *dirent, *sub_dirent;
dirent = (struct romfs_dirent *)file->vnode->data;
if (check_dirent(dirent) != 0)
{
return -EIO;
}
RT_ASSERT(dirent->type == ROMFS_DIRENT_DIR);
/* enter directory */
dirent = (struct romfs_dirent *)dirent->data;
/* make integer count */
count = (count / sizeof(struct dirent));
if (count == 0)
{
return -EINVAL;
}
index = 0;
for (index = 0; index < count && file->fpos < file->vnode->size; index++)
{
d = dirp + index;
sub_dirent = &dirent[file->fpos];
name = sub_dirent->name;
/* fill dirent */
if (sub_dirent->type == ROMFS_DIRENT_DIR)
d->d_type = DT_DIR;
else
d->d_type = DT_REG;
d->d_namlen = rt_strlen(name);
d->d_reclen = (rt_uint16_t)sizeof(struct dirent);
rt_strncpy(d->d_name, name, DIRENT_NAME_MAX);
/* move to next position */
++ file->fpos;
}
return index * sizeof(struct dirent);
}
static const struct dfs_file_ops _rom_fops =
{
.open = dfs_romfs_open,
.close = dfs_romfs_close,
.ioctl = dfs_romfs_ioctl,
.lseek = generic_dfs_lseek,
.read = dfs_romfs_read,
.getdents = dfs_romfs_getdents,
};
static const struct dfs_filesystem_ops _romfs_ops =
{
.name ="rom",
.flags = 0,
.default_fops = &_rom_fops,
.mount = dfs_romfs_mount,
.umount = dfs_romfs_umount,
.stat = dfs_romfs_stat,
.lookup = dfs_romfs_lookup,
.free_vnode = dfs_romfs_free_vnode
};
static struct dfs_filesystem_type _romfs =
{
.fs_ops = &_romfs_ops,
};
int dfs_romfs_init(void)
{
/* register rom file system */
dfs_register(&_romfs);
return 0;
}
INIT_COMPONENT_EXPORT(dfs_romfs_init);
@@ -0,0 +1,31 @@
/*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2019/01/13 Bernard code cleanup
*/
#ifndef __DFS_ROMFS_H__
#define __DFS_ROMFS_H__
#include <rtthread.h>
#define ROMFS_DIRENT_FILE 0x00
#define ROMFS_DIRENT_DIR 0x01
struct romfs_dirent
{
rt_uint32_t type; /* dirent type */
const char *name; /* dirent name */
const rt_uint8_t *data; /* file date ptr */
rt_size_t size; /* file size */
};
int dfs_romfs_init(void);
extern const struct romfs_dirent romfs_root;
#endif
@@ -0,0 +1,42 @@
/*
* Copyright (c) 2006-2022, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#include <rtthread.h>
#include <dfs_romfs.h>
static const unsigned char _dummy_dummy_txt[] =
{
0x74, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x21, 0x0d, 0x0a,
};
static const struct romfs_dirent _dummy[] =
{
{ROMFS_DIRENT_FILE, "dummy.txt", _dummy_dummy_txt, sizeof(_dummy_dummy_txt)},
};
static const unsigned char _dummy_txt[] =
{
0x74, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x21, 0x0d, 0x0a,
};
rt_weak const struct romfs_dirent _root_dirent[] =
{
{ROMFS_DIRENT_DIR, "dev", RT_NULL, 0},
{ROMFS_DIRENT_DIR, "mnt", RT_NULL, 0},
{ROMFS_DIRENT_DIR, "proc", RT_NULL, 0},
{ROMFS_DIRENT_DIR, "etc", RT_NULL, 0},
{ROMFS_DIRENT_DIR, "bin", RT_NULL, 0},
{ROMFS_DIRENT_DIR, "dummy", (rt_uint8_t *)_dummy, sizeof(_dummy) / sizeof(_dummy[0])},
{ROMFS_DIRENT_FILE, "dummy.txt", _dummy_txt, sizeof(_dummy_txt)},
};
rt_weak const struct romfs_dirent romfs_root =
{
ROMFS_DIRENT_DIR, "/", (rt_uint8_t *)_root_dirent, sizeof(_root_dirent) / sizeof(_root_dirent[0])
};
@@ -0,0 +1,96 @@
/*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#include <rtthread.h>
#include <dfs.h>
#include <dfs_fs.h>
#include <dfs_file.h>
#include "dfs_skt_fs.h"
int dfs_skt_mount(struct dfs_filesystem *fs, unsigned long rwflag, const void *data)
{
return RT_EOK;
}
int dfs_skt_unmount(struct dfs_filesystem *fs)
{
return RT_EOK;
}
int dfs_skt_ioctl(struct dfs_file *file, int cmd, void *args)
{
return -RT_EIO;
}
int dfs_skt_read(struct dfs_file *file, void *buf, rt_size_t count)
{
return count;
}
int dfs_skt_lseek(struct dfs_file *file, rt_off_t offset)
{
return -RT_EIO;
}
int dfs_skt_close(struct dfs_file *file)
{
return RT_EOK;
}
int dfs_skt_open(struct dfs_file *file)
{
return RT_EOK;
}
int dfs_skt_stat(struct dfs_filesystem *fs, const char *path, struct stat *st)
{
return RT_EOK;
}
int dfs_skt_getdents(struct dfs_file *file, struct dirent *dirp, rt_uint32_t count)
{
return count * sizeof(struct dirent);
}
static const struct dfs_file_ops _skt_fops =
{
dfs_skt_open,
dfs_skt_close,
dfs_skt_ioctl,
dfs_skt_read,
NULL, /* write */
NULL, /* flush */
dfs_skt_lseek,
dfs_skt_getdents,
};
static const struct dfs_filesystem_ops _skt_fs =
{
"skt",
DFS_FS_FLAG_DEFAULT,
&_skt_fops,
dfs_skt_mount,
dfs_skt_unmount,
NULL, /* mkfs */
NULL, /* statfs */
NULL, /* unlink */
dfs_skt_stat,
NULL, /* rename */
};
int dfs_skt_init(void)
{
/* register rom file system */
dfs_register(&_skt_fs);
return 0;
}
INIT_COMPONENT_EXPORT(dfs_skt_init);
@@ -0,0 +1,17 @@
/*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#ifndef __SKELETON_H__
#define __SKELETON_H__
#include <rtthread.h>
int dfs_skt_init(void);
#endif
@@ -0,0 +1,9 @@
from building import *
cwd = GetCurrentDir()
src = Glob('*.c')
CPPPATH = [cwd]
group = DefineGroup('Filesystem', src, depend = ['RT_USING_DFS', 'RT_USING_DFS_TMPFS'], CPPPATH = CPPPATH)
Return('group')
@@ -0,0 +1,899 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2022-10-24 flybreak the first version
* 2023-02-01 xqyjlj fix cannot open the same file repeatedly in 'w' mode
* 2023-09-20 zmq810150896 adds truncate functionality and standardized unlink adaptations
*/
#include <rthw.h>
#include <rtthread.h>
#include <dfs.h>
#include <dfs_fs.h>
#include <dfs_dentry.h>
#include <dfs_file.h>
#include <dfs_mnt.h>
#ifdef RT_USING_SMART
#include <lwp.h>
#include <lwp_user_mm.h>
#endif
#include "dfs_tmpfs.h"
#define DBG_TAG "tmpfs"
#define DBG_LVL DBG_INFO
#include <rtdbg.h>
#ifdef RT_USING_PAGECACHE
#include "dfs_pcache.h"
#endif
#ifdef RT_USING_PAGECACHE
static ssize_t dfs_tmp_page_read(struct dfs_file *file, struct dfs_page *page);
static ssize_t dfs_tmp_page_write(struct dfs_page *page);
static struct dfs_aspace_ops dfs_tmp_aspace_ops =
{
.read = dfs_tmp_page_read,
.write = dfs_tmp_page_write,
};
#endif
static int _path_separate(const char *path, char *parent_path, char *file_name)
{
const char *path_p, *path_q;
RT_ASSERT(path[0] == '/');
file_name[0] = '\0';
path_p = path_q = &path[1];
__next_dir:
while (*path_q != '/' && *path_q != '\0')
{
path_q++;
}
if (path_q != path_p) /*sub dir*/
{
if (*path_q != '\0')
{
path_q++;
path_p = path_q;
goto __next_dir;
}
else /* Last level dir */
{
rt_memcpy(parent_path, path, path_p - path - 1);
parent_path[path_p - path - 1] = '\0';
rt_memcpy(file_name, path_p, path_q - path_p);
file_name[path_q - path_p] = '\0';
}
}
if (parent_path[0] == 0)
{
parent_path[0] = '/';
parent_path[1] = '\0';
}
LOG_D("parent_path: %s", parent_path);
LOG_D("file_name: %s", file_name);
return 0;
}
static int _get_subdir(const char *path, char *name)
{
const char *subpath = path;
while (*subpath == '/' && *subpath)
subpath ++;
while (*subpath != '/' && *subpath)
{
*name = *subpath;
name ++;
subpath ++;
}
return 0;
}
static int _free_subdir(struct tmpfs_file *dfile)
{
struct tmpfs_file *file = RT_NULL, *tmp;
struct tmpfs_sb *superblock;
RT_ASSERT(dfile->type == TMPFS_TYPE_DIR);
dfs_vfs_for_each_subnode(file, tmp, dfile, node)
{
if (file->type == TMPFS_TYPE_DIR)
{
_free_subdir(file);
}
if (file->data != NULL)
{
/* TODO: fix for rt-smart */
rt_free(file->data);
}
superblock = file->sb;
RT_ASSERT(superblock != NULL);
rt_spin_lock(&superblock->lock);
dfs_vfs_remove_node(&file->node);
rt_spin_unlock(&superblock->lock);
rt_free(file);
}
return 0;
}
static int dfs_tmpfs_mount(struct dfs_mnt *mnt,
unsigned long rwflag,
const void *data)
{
struct tmpfs_sb *superblock;
superblock = rt_calloc(1, sizeof(struct tmpfs_sb));
if (superblock)
{
superblock->df_size = sizeof(struct tmpfs_sb);
superblock->magic = TMPFS_MAGIC;
superblock->root.name[0] = '/';
superblock->root.sb = superblock;
superblock->root.type = TMPFS_TYPE_DIR;
dfs_vfs_init_node(&superblock->root.node);
rt_spin_lock_init(&superblock->lock);
mnt->data = superblock;
}
else
{
return -1;
}
return RT_EOK;
}
static int dfs_tmpfs_unmount(struct dfs_mnt *mnt)
{
struct tmpfs_sb *superblock;
/* FIXME: don't unmount on busy. */
superblock = (struct tmpfs_sb *)mnt->data;
RT_ASSERT(superblock != NULL);
mnt->data = NULL;
_free_subdir(&(superblock->root));
rt_free(superblock);
return RT_EOK;
}
int dfs_tmpfs_statfs(struct dfs_mnt *mnt, struct statfs *buf)
{
struct tmpfs_sb *superblock;
superblock = (struct tmpfs_sb *)mnt->data;
RT_ASSERT(superblock != NULL);
RT_ASSERT(buf != NULL);
buf->f_bsize = 512;
buf->f_blocks = (superblock->df_size + 511) / 512;
buf->f_bfree = 1;
buf->f_bavail = buf->f_bfree;
return RT_EOK;
}
int dfs_tmpfs_ioctl(struct dfs_file *file, int cmd, void *args)
{
struct tmpfs_file *d_file;
struct tmpfs_sb *superblock;
d_file = (struct tmpfs_file *)file->vnode->data;
RT_ASSERT(d_file != NULL);
superblock = d_file->sb;
RT_ASSERT(superblock != NULL);
RT_UNUSED(superblock);
switch (cmd)
{
#ifdef RT_USING_SMART
case RT_FIOMMAP2:
{
struct dfs_mmap2_args *mmap2 = (struct dfs_mmap2_args *)args;
if (mmap2)
{
if (mmap2->length > file->vnode->size)
{
return -RT_ENOMEM;
}
LOG_D("tmpfile mmap ptr:%x , size:%d\n", d_file->data, mmap2->length);
mmap2->ret = lwp_map_user_phy(lwp_self(), RT_NULL, d_file->data, mmap2->length, 0);
}
return RT_EOK;
break;
}
#endif
default:
break;
}
return -EIO;
}
struct tmpfs_file *dfs_tmpfs_lookup(struct tmpfs_sb *superblock,
const char *path,
rt_size_t *size)
{
const char *subpath, *curpath, *filename = RT_NULL;
char subdir_name[TMPFS_NAME_MAX];
struct tmpfs_file *file, *curfile, *tmp;
subpath = path;
while (*subpath == '/' && *subpath)
subpath ++;
if (! *subpath) /* is root directory */
{
*size = 0;
return &(superblock->root);
}
curpath = subpath;
curfile = &superblock->root;
find_subpath:
while (*subpath != '/' && *subpath)
subpath ++;
if (! *subpath) /* is last directory */
filename = curpath;
else
subpath ++; /* skip '/' */
memset(subdir_name, 0, TMPFS_NAME_MAX);
_get_subdir(curpath, subdir_name);
rt_spin_lock(&superblock->lock);
dfs_vfs_for_each_subnode(file, tmp, curfile, node)
{
if (filename) /* find file */
{
if (rt_strcmp(file->name, filename) == 0)
{
*size = file->size;
rt_spin_unlock(&superblock->lock);
return file;
}
}
else if (rt_strcmp(file->name, subdir_name) == 0)
{
*size = file->size;
curpath = subpath;
curfile = file;
rt_spin_unlock(&superblock->lock);
goto find_subpath;
}
}
rt_spin_unlock(&superblock->lock);
/* not found */
return NULL;
}
static ssize_t dfs_tmpfs_read(struct dfs_file *file, void *buf, size_t count, off_t *pos)
{
ssize_t length;
struct tmpfs_file *d_file;
d_file = (struct tmpfs_file *)file->vnode->data;
RT_ASSERT(d_file != NULL);
rt_mutex_take(&file->vnode->lock, RT_WAITING_FOREVER);
ssize_t size = (ssize_t)file->vnode->size;
if ((ssize_t)count < size - *pos)
length = count;
else
length = size - *pos;
if (length > 0)
memcpy(buf, &(d_file->data[*pos]), length);
/* update file current position */
*pos += length;
rt_mutex_release(&file->vnode->lock);
return length;
}
static ssize_t _dfs_tmpfs_write(struct tmpfs_file *d_file, const void *buf, size_t count, off_t *pos)
{
struct tmpfs_sb *superblock;
RT_ASSERT(d_file != NULL);
superblock = d_file->sb;
RT_ASSERT(superblock != NULL);
if (count + *pos > d_file->size)
{
rt_uint8_t *ptr;
ptr = rt_realloc(d_file->data, *pos + count);
if (ptr == NULL)
{
rt_set_errno(-ENOMEM);
return 0;
}
rt_spin_lock(&superblock->lock);
superblock->df_size += (*pos - d_file->size + count);
rt_spin_unlock(&superblock->lock);
/* update d_file and file size */
d_file->data = ptr;
d_file->size = *pos + count;
LOG_D("tmpfile ptr:%x, size:%d", ptr, d_file->size);
}
if (count > 0)
memcpy(d_file->data + *pos, buf, count);
/* update file current position */
*pos += count;
return count;
}
static ssize_t dfs_tmpfs_write(struct dfs_file *file, const void *buf, size_t count, off_t *pos)
{
struct tmpfs_file *d_file;
d_file = (struct tmpfs_file *)file->vnode->data;
RT_ASSERT(d_file != NULL);
rt_mutex_take(&file->vnode->lock, RT_WAITING_FOREVER);
count = _dfs_tmpfs_write(d_file, buf, count, pos);
rt_mutex_release(&file->vnode->lock);
return count;
}
static off_t dfs_tmpfs_lseek(struct dfs_file *file, off_t offset, int wherece)
{
switch (wherece)
{
case SEEK_SET:
break;
case SEEK_CUR:
offset += file->fpos;
break;
case SEEK_END:
offset += file->vnode->size;
break;
default:
return -EINVAL;
}
if (offset <= (off_t)file->vnode->size)
{
return offset;
}
return -EIO;
}
static int dfs_tmpfs_close(struct dfs_file *file)
{
struct tmpfs_file *d_file;
RT_ASSERT(file->vnode->ref_count > 0);
if (file->vnode->ref_count != 1)
return 0;
d_file = (struct tmpfs_file *)file->vnode->data;
if (d_file == NULL)
return -ENOENT;
if (d_file->fre_memory == RT_TRUE)
{
if (d_file->data != NULL)
{
rt_free(d_file->data);
d_file->data = RT_NULL;
}
rt_free(d_file);
}
rt_mutex_detach(&file->vnode->lock);
return RT_EOK;
}
static int dfs_tmpfs_open(struct dfs_file *file)
{
struct tmpfs_file *d_file;
d_file = (struct tmpfs_file *)file->vnode->data;
RT_ASSERT(d_file != RT_NULL);
/* Creates a new file.
* If the file is existing, it is truncated and overwritten.
*/
if (file->flags & O_TRUNC)
{
d_file->size = 0;
file->vnode->size = d_file->size;
file->fpos = file->vnode->size;
if (d_file->data != NULL)
{
/* ToDo: fix for rt-smart. */
rt_free(d_file->data);
d_file->data = NULL;
}
}
if (file->flags & O_APPEND)
{
file->fpos = file->vnode->size;
}
else
{
file->fpos = 0;
}
RT_ASSERT(file->vnode->ref_count > 0);
if(file->vnode->ref_count == 1)
{
rt_mutex_init(&file->vnode->lock, file->dentry->pathname, RT_IPC_FLAG_PRIO);
}
return 0;
}
static int dfs_tmpfs_stat(struct dfs_dentry *dentry, struct stat *st)
{
rt_size_t size;
struct tmpfs_file *d_file;
struct tmpfs_sb *superblock;
superblock = (struct tmpfs_sb *)dentry->mnt->data;
d_file = dfs_tmpfs_lookup(superblock, dentry->pathname, &size);
if (d_file == NULL)
return -ENOENT;
st->st_dev = (dev_t)(size_t)(dentry->mnt->dev_id);
st->st_ino = (ino_t)dfs_dentry_full_path_crc32(dentry);
if (d_file->type == TMPFS_TYPE_DIR)
{
st->st_mode = S_IFDIR | (S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
}
else
{
st->st_mode = S_IFREG | (S_IRWXU | S_IRWXG | S_IRWXO);
}
st->st_size = d_file->size;
st->st_mtime = 0;
return RT_EOK;
}
static int dfs_tmpfs_getdents(struct dfs_file *file,
struct dirent *dirp,
uint32_t count)
{
rt_size_t index, end;
struct dirent *d;
struct tmpfs_file *d_file, *n_file, *tmp;
struct tmpfs_sb *superblock;
d_file = (struct tmpfs_file *)file->vnode->data;
rt_mutex_take(&file->vnode->lock, RT_WAITING_FOREVER);
superblock = d_file->sb;
RT_ASSERT(superblock != RT_NULL);
RT_UNUSED(superblock);
/* make integer count */
count = (count / sizeof(struct dirent));
if (count == 0)
{
rt_mutex_release(&file->vnode->lock);
return -EINVAL;
}
end = file->fpos + count;
index = 0;
count = 0;
dfs_vfs_for_each_subnode(n_file, tmp, d_file, node)
{
if (index >= (rt_size_t)file->fpos)
{
d = dirp + count;
if (d_file->type == TMPFS_TYPE_FILE)
{
d->d_type = DT_REG;
}
if (d_file->type == TMPFS_TYPE_DIR)
{
d->d_type = DT_DIR;
}
d->d_namlen = RT_NAME_MAX;
d->d_reclen = (rt_uint16_t)sizeof(struct dirent);
rt_strncpy(d->d_name, n_file->name, TMPFS_NAME_MAX);
count += 1;
file->fpos += 1;
}
index += 1;
if (index >= end)
{
break;
}
}
rt_mutex_release(&file->vnode->lock);
return count * sizeof(struct dirent);
}
static int dfs_tmpfs_unlink(struct dfs_dentry *dentry)
{
rt_size_t size;
struct tmpfs_sb *superblock;
struct tmpfs_file *d_file;
superblock = (struct tmpfs_sb *)dentry->mnt->data;
RT_ASSERT(superblock != NULL);
d_file = dfs_tmpfs_lookup(superblock, dentry->pathname, &size);
if (d_file == NULL)
return -ENOENT;
rt_spin_lock(&superblock->lock);
dfs_vfs_remove_node(&d_file->node);
rt_spin_unlock(&superblock->lock);
if (rt_atomic_load(&(dentry->ref_count)) == 1)
{
if (d_file->data != NULL)
{
rt_free(d_file->data);
d_file->data = RT_NULL;
}
rt_free(d_file);
}
else
{
d_file->fre_memory = RT_TRUE;
}
return RT_EOK;
}
static int dfs_tmpfs_rename(struct dfs_dentry *old_dentry, struct dfs_dentry *new_dentry)
{
struct tmpfs_file *d_file, *p_file;
struct tmpfs_sb *superblock;
rt_size_t size;
char *parent_path;
char file_name[TMPFS_NAME_MAX];
superblock = (struct tmpfs_sb *)old_dentry->mnt->data;
RT_ASSERT(superblock != NULL);
d_file = dfs_tmpfs_lookup(superblock, new_dentry->pathname, &size);
if (d_file != NULL)
return -EEXIST;
d_file = dfs_tmpfs_lookup(superblock, old_dentry->pathname, &size);
if (d_file == NULL)
return -ENOENT;
parent_path = rt_malloc(DFS_PATH_MAX);
if (!parent_path)
{
return -ENOMEM;
}
/* find parent file */
_path_separate(new_dentry->pathname, parent_path, file_name);
if (file_name[0] == '\0') /* it's root dir */
{
rt_free(parent_path);
return -ENOENT;
}
/* open parent directory */
p_file = dfs_tmpfs_lookup(superblock, parent_path, &size);
RT_ASSERT(p_file != NULL);
rt_spin_lock(&superblock->lock);
dfs_vfs_remove_node(&d_file->node);
rt_spin_unlock(&superblock->lock);
strncpy(d_file->name, file_name, TMPFS_NAME_MAX);
rt_spin_lock(&superblock->lock);
dfs_vfs_append_node(&p_file->node, &d_file->node);
rt_spin_unlock(&superblock->lock);
rt_free(parent_path);
return RT_EOK;
}
static struct dfs_vnode *_dfs_tmpfs_lookup(struct dfs_dentry *dentry)
{
struct dfs_vnode *vnode = RT_NULL;
rt_size_t size;
struct tmpfs_sb *superblock;
struct tmpfs_file *d_file;
if (dentry == NULL || dentry->mnt == NULL || dentry->mnt->data == NULL)
{
return NULL;
}
superblock = (struct tmpfs_sb *)dentry->mnt->data;
d_file = dfs_tmpfs_lookup(superblock, dentry->pathname, &size);
if (d_file)
{
vnode = dfs_vnode_create();
if (vnode)
{
if (d_file->type == TMPFS_TYPE_DIR)
{
vnode->mode = S_IFDIR | (S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
vnode->type = FT_DIRECTORY;
}
else
{
vnode->mode = S_IFREG | (S_IRWXU | S_IRWXG | S_IRWXO);
vnode->type = FT_REGULAR;
#ifdef RT_USING_PAGECACHE
vnode->aspace = dfs_aspace_create(dentry, vnode, &dfs_tmp_aspace_ops);
#endif
}
vnode->mnt = dentry->mnt;
vnode->data = d_file;
vnode->size = d_file->size;
}
}
return vnode;
}
static struct dfs_vnode *dfs_tmpfs_create_vnode(struct dfs_dentry *dentry, int type, mode_t mode)
{
struct dfs_vnode *vnode = RT_NULL;
rt_size_t size;
struct tmpfs_sb *superblock;
struct tmpfs_file *d_file, *p_file;
char *parent_path;
char file_name[TMPFS_NAME_MAX];
if (dentry == NULL || dentry->mnt == NULL || dentry->mnt->data == NULL)
{
return NULL;
}
superblock = (struct tmpfs_sb *)dentry->mnt->data;
RT_ASSERT(superblock != NULL);
parent_path = rt_malloc(DFS_PATH_MAX);
if (!parent_path)
{
return NULL;
}
vnode = dfs_vnode_create();
if (vnode)
{
/* find parent file */
_path_separate(dentry->pathname, parent_path, file_name);
if (file_name[0] == '\0') /* it's root dir */
{
rt_free(parent_path);
dfs_vnode_destroy(vnode);
return NULL;
}
/* open parent directory */
p_file = dfs_tmpfs_lookup(superblock, parent_path, &size);
if (p_file == NULL)
{
rt_free(parent_path);
dfs_vnode_destroy(vnode);
return NULL;
}
/* create a file entry */
d_file = (struct tmpfs_file *)rt_calloc(1, sizeof(struct tmpfs_file));
if (d_file == NULL)
{
rt_free(parent_path);
dfs_vnode_destroy(vnode);
return NULL;
}
superblock->df_size += sizeof(struct tmpfs_file);
strncpy(d_file->name, file_name, TMPFS_NAME_MAX);
dfs_vfs_init_node(&d_file->node);
d_file->data = NULL;
d_file->size = 0;
d_file->sb = superblock;
d_file->fre_memory = RT_FALSE;
if (type == FT_DIRECTORY)
{
d_file->type = TMPFS_TYPE_DIR;
vnode->mode = S_IFDIR | (S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
vnode->type = FT_DIRECTORY;
}
else
{
d_file->type = TMPFS_TYPE_FILE;
vnode->mode = S_IFREG | (S_IRWXU | S_IRWXG | S_IRWXO);
vnode->type = FT_REGULAR;
#ifdef RT_USING_PAGECACHE
vnode->aspace = dfs_aspace_create(dentry, vnode, &dfs_tmp_aspace_ops);
#endif
}
rt_spin_lock(&superblock->lock);
dfs_vfs_append_node(&p_file->node, &d_file->node);
rt_spin_unlock(&superblock->lock);
vnode->mnt = dentry->mnt;
vnode->data = d_file;
vnode->size = d_file->size;
}
rt_free(parent_path);
return vnode;
}
static int dfs_tmpfs_free_vnode(struct dfs_vnode *vnode)
{
/* nothing to be freed */
if (vnode && vnode->ref_count <= 1)
{
vnode->data = NULL;
}
return 0;
}
#ifdef RT_USING_PAGECACHE
static ssize_t dfs_tmp_page_read(struct dfs_file *file, struct dfs_page *page)
{
int ret = -EINVAL;
if (page->page)
{
off_t fpos = page->fpos;
ret = dfs_tmpfs_read(file, page->page, page->size, &fpos);
}
return ret;
}
ssize_t dfs_tmp_page_write(struct dfs_page *page)
{
off_t pos;
size_t count = 0;
struct tmpfs_file *d_file;
if (page->aspace->vnode->type == FT_DIRECTORY)
{
return -EISDIR;
}
d_file = (struct tmpfs_file *)(page->aspace->vnode->data);
RT_ASSERT(d_file != RT_NULL);
rt_mutex_take(&page->aspace->vnode->lock, RT_WAITING_FOREVER);
if (page->len > 0)
{
pos = page->fpos;
count = _dfs_tmpfs_write(d_file, page->page, page->len, &pos);
}
rt_mutex_release(&page->aspace->vnode->lock);
return count;
}
#endif
static int dfs_tmpfs_truncate(struct dfs_file *file, off_t offset)
{
struct tmpfs_file *d_file = RT_NULL;
struct tmpfs_sb *superblock = RT_NULL;
rt_uint8_t *ptr = RT_NULL;
d_file = (struct tmpfs_file *)file->vnode->data;
RT_ASSERT(d_file != RT_NULL);
superblock = d_file->sb;
RT_ASSERT(superblock != RT_NULL);
ptr = rt_realloc(d_file->data, offset);
if (ptr == RT_NULL)
{
rt_set_errno(-ENOMEM);
return 0;
}
rt_spin_lock(&superblock->lock);
superblock->df_size = offset;
rt_spin_unlock(&superblock->lock);
/* update d_file and file size */
d_file->data = ptr;
d_file->size = offset;
file->vnode->size = d_file->size;
LOG_D("tmpfile ptr:%x, size:%d", ptr, d_file->size);
return 0;
}
static const struct dfs_file_ops _tmp_fops =
{
.open = dfs_tmpfs_open,
.close = dfs_tmpfs_close,
.ioctl = dfs_tmpfs_ioctl,
.read = dfs_tmpfs_read,
.write = dfs_tmpfs_write,
.lseek = dfs_tmpfs_lseek,
.getdents = dfs_tmpfs_getdents,
.truncate = dfs_tmpfs_truncate,
};
static const struct dfs_filesystem_ops _tmpfs_ops =
{
.name = "tmp",
.flags = DFS_FS_FLAG_DEFAULT,
.default_fops = &_tmp_fops,
.mount = dfs_tmpfs_mount,
.umount = dfs_tmpfs_unmount,
.statfs = dfs_tmpfs_statfs,
.unlink = dfs_tmpfs_unlink,
.stat = dfs_tmpfs_stat,
.rename = dfs_tmpfs_rename,
.lookup = _dfs_tmpfs_lookup,
.create_vnode = dfs_tmpfs_create_vnode,
.free_vnode = dfs_tmpfs_free_vnode
};
static struct dfs_filesystem_type _tmpfs =
{
.fs_ops = &_tmpfs_ops,
};
int dfs_tmpfs_init(void)
{
/* register tmp file system */
dfs_register(&_tmpfs);
return 0;
}
INIT_COMPONENT_EXPORT(dfs_tmpfs_init);
@@ -0,0 +1,49 @@
/*
* Copyright (c) 2006-2018, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2022-10-24 flybreak the first version
*/
#ifndef __DFS_TMPFS_H__
#define __DFS_TMPFS_H__
#include <rtthread.h>
#include <dfs_vfs.h>
#define TMPFS_NAME_MAX 32
#define TMPFS_MAGIC 0x0B0B0B0B
#define TMPFS_TYPE_FILE 0x00
#define TMPFS_TYPE_DIR 0x01
struct tmpfs_sb;
struct tmpfs_file
{
rt_uint32_t type; /* file type */
char name[TMPFS_NAME_MAX]; /* file name */
struct dfs_vfs_node node; /* file node in the tmpfs */
struct tmpfs_sb *sb; /* superblock ptr */
rt_uint8_t *data; /* file date ptr */
rt_size_t size; /* file size */
rt_bool_t fre_memory;/* Whether to release memory upon close */
};
struct tmpfs_sb
{
rt_uint32_t magic; /* TMPFS_MAGIC */
struct tmpfs_file root; /* root dir */
rt_size_t df_size; /* df size */
rt_list_t sibling; /* sb sibling list */
struct rt_spinlock lock; /* tmpfs lock */
};
int dfs_tmpfs_init(void);
#endif
@@ -0,0 +1,151 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2005-02-22 Bernard The first version.
* 2023-05-05 Bernard change to dfs v2.0
*/
#ifndef __DFS_H__
#define __DFS_H__
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "../../libc/compilers/common/include/dirent.h"
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/statfs.h>
#include <sys/time.h>
#include <sys/errno.h>
#include <rtatomic.h>
#include <rtdevice.h>
#ifndef ATTR_MODE_SET
#define ATTR_MODE_SET (1 << 6)
#endif
#ifndef ATTR_ATIME_SET
#define ATTR_ATIME_SET (1 << 7)
#endif
#ifndef ATTR_MTIME_SET
#define ATTR_MTIME_SET (1 << 8)
#endif
#ifndef ATTR_UID_SET
#define ATTR_UID_SET (1 << 9)
#endif
#ifndef ATTR_GID_SET
#define ATTR_GID_SET (1 << 10)
#endif
#ifndef AT_SYMLINK_NOFOLLOW
#define AT_SYMLINK_NOFOLLOW 0x100
#endif
#ifndef UTIME_NOW
#define UTIME_NOW 0x3fffffff
#endif
#ifndef UTIME_OMIT
#define UTIME_OMIT 0x3ffffffe
#endif
#ifndef DFS_FD_MAX
#define DFS_FD_MAX 16
#endif
/*
* skip stdin/stdout/stderr normally
*/
#ifndef DFS_STDIO_OFFSET
#define DFS_STDIO_OFFSET 3
#endif
#ifndef DFS_PATH_MAX
#define DFS_PATH_MAX 4096
#endif
#ifndef SECTOR_SIZE
#define SECTOR_SIZE 512
#endif
#define DFS_FS_FLAG_DEFAULT 0x00 /* default flag */
#define DFS_FS_FLAG_FULLPATH 0x01 /* set full path to underlaying file system */
/* File flags */
#define DFS_F_FREAD 0x01
#define DFS_F_FWRITE 0x02
#ifdef __cplusplus
extern "C" {
#endif
rt_inline int dfs_fflags(int oflags)
{
int rw = oflags & O_ACCMODE;
oflags &= ~O_ACCMODE;
return (rw + 1) | oflags;
}
rt_inline int dfs_oflags(int fflags)
{
int rw = fflags & (DFS_F_FREAD | DFS_F_FWRITE);
fflags &= ~(DFS_F_FREAD | DFS_F_FWRITE);
return (rw - 1) | fflags;
}
struct dfs_fdtable
{
uint32_t maxfd;
struct dfs_file **fds;
};
/* Initialization of dfs */
int dfs_init(void);
char *dfs_normalize_path(const char *directory, const char *filename);
const char *dfs_subdir(const char *directory, const char *filename);
rt_err_t dfs_lock(void);
void dfs_unlock(void);
rt_err_t dfs_file_lock(void);
void dfs_file_unlock(void);
int dfs_fdtable_dup(struct dfs_fdtable *fdt_dst, struct dfs_fdtable *fdt_src, int fd_src);
int dfs_fdtable_drop_fd(struct dfs_fdtable *fdtab, int fd);
#ifdef DFS_USING_POSIX
/* FD APIs */
int fdt_fd_new(struct dfs_fdtable *fdt);
struct dfs_file *fdt_get_file(struct dfs_fdtable* fdt, int fd);
void fdt_fd_release(struct dfs_fdtable* fdt, int fd);
int fd_new(void);
int fdt_fd_associate_file(struct dfs_fdtable *fdt, int fd, struct dfs_file *file);
struct dfs_file *fd_get(int fd);
void fd_release(int fd);
void fd_init(struct dfs_file *fd);
struct dfs_fdtable *dfs_fdtable_get(void);
struct dfs_fdtable *dfs_fdtable_get_global(void);
int dfs_dup(int oldfd, int startfd);
#endif /* DFS_USING_POSIX */
struct dfs_file* dfs_file_create(void);
void dfs_file_destroy(struct dfs_file *file);
#ifdef __cplusplus
}
#endif
#endif
@@ -0,0 +1,65 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2023-05-05 Bernard Implement dentry in dfs v2.0
*/
#ifndef __DFS_DENTRY_H__
#define __DFS_DENTRY_H__
#include "dfs_file.h"
#include "dfs_fs.h"
#ifdef __cplusplus
extern "C"
{
#endif
struct dfs_mnt;
struct dfs_vnode;
struct dfs_dentry
{
rt_list_t hashlist;
uint32_t flags;
#define DENTRY_IS_MOUNTED 0x1 /* dentry is mounted */
#define DENTRY_IS_ALLOCED 0x2 /* dentry is allocated */
#define DENTRY_IS_ADDHASH 0x4 /* dentry was added into hash table */
#define DENTRY_IS_OPENED 0x8 /* dentry was opened. */
char *pathname; /* the pathname under mounted file sytem */
struct dfs_vnode *vnode; /* the vnode of this dentry */
struct dfs_mnt *mnt; /* which mounted file system does this dentry belong to */
rt_atomic_t ref_count; /* the reference count */
};
struct dfs_dentry *dfs_dentry_create(struct dfs_mnt *mnt, char *fullpath);
struct dfs_dentry *dfs_dentry_create_rela(struct dfs_mnt *mnt, char *rela_path);
struct dfs_dentry *dfs_dentry_unref(struct dfs_dentry *dentry);
struct dfs_dentry *dfs_dentry_ref(struct dfs_dentry *dentry);
void dfs_dentry_insert(struct dfs_dentry *dentry);
struct dfs_dentry *dfs_dentry_lookup(struct dfs_mnt *mnt, const char *path, uint32_t flags);
/* get full path of a dentry */
char* dfs_dentry_full_path(struct dfs_dentry* dentry);
/* get pathname (with mnt path) of a dentry */
char* dfs_dentry_pathname(struct dfs_dentry* dentry);
/* get full path crc32 */
uint32_t dfs_dentry_full_path_crc32(struct dfs_dentry* dentry);
int dfs_dentry_init(void);
#ifdef __cplusplus
}
#endif
#endif /*__DFS_DENTRY_H__*/
@@ -0,0 +1,204 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2005-01-26 Bernard The first version.
* 2023-05-05 Bernard Change to dfs v2.0
*/
#ifndef __DFS_FILE_H__
#define __DFS_FILE_H__
#include <dfs.h>
#include <dfs_fs.h>
#ifdef __cplusplus
extern "C"
{
#endif
#define STDIN_FILENO 0 /* standard input file descriptor */
#define STDOUT_FILENO 1 /* standard output file descriptor */
#define STDERR_FILENO 2 /* standard error file descriptor */
struct dfs_file;
struct dfs_vnode;
struct dfs_dentry;
struct dfs_attr;
struct rt_pollreq;
struct dirent;
struct lwp_avl_struct;
struct file_lock;
struct dfs_aspace;
struct dfs_file_ops
{
int (*open)(struct dfs_file *file);
int (*close)(struct dfs_file *file);
int (*ioctl)(struct dfs_file *file, int cmd, void *arg);
ssize_t (*read)(struct dfs_file *file, void *buf, size_t count, off_t *pos);
ssize_t (*write)(struct dfs_file *file, const void *buf, size_t count, off_t *pos);
int (*flush)(struct dfs_file *file);
off_t (*lseek)(struct dfs_file *file, off_t offset, int wherece);
int (*truncate)(struct dfs_file *file, off_t offset);
int (*getdents)(struct dfs_file *file, struct dirent *dirp, uint32_t count);
int (*poll)(struct dfs_file *file, struct rt_pollreq *req);
int (*mmap)(struct dfs_file *file, struct lwp_avl_struct *mmap);
int (*lock)(struct dfs_file *file, struct file_lock *flock);
int (*flock)(struct dfs_file *file, int, struct file_lock *flock);
};
struct dfs_vnode
{
uint32_t flags;
uint32_t mode;
int type; /* node type */
rt_atomic_t ref_count; /* reference count */
struct dfs_mnt *mnt; /* which mounted file system does this vnode belong to */
size_t size;
uint32_t nlink;
const struct dfs_file_ops *fops;
unsigned int uid;
unsigned int gid;
struct timespec atime;
struct timespec mtime;
struct timespec ctime;
struct dfs_aspace *aspace;
struct rt_mutex lock;
void *data; /* private data of this file system */
};
/* file descriptor */
#define DFS_FD_MAGIC 0xfdfd
struct dfs_file
{
uint16_t magic;
uint16_t mode;
uint32_t flags;
rt_atomic_t ref_count;
off_t fpos;
struct rt_mutex pos_lock;
const struct dfs_file_ops *fops;
struct dfs_dentry *dentry; /* dentry of this file */
struct dfs_vnode *vnode; /* vnode of this file */
void *mmap_context; /* used by mmap routine */
void *data;
};
#define DFS_FILE_POS(dfs_file) ((dfs_file)->fpos)
/* file is open for reading */
#define FMODE_READ 0x1
/* file is open for writing */
#define FMODE_WRITE 0x2
/* file is seekable */
#define FMODE_LSEEK 0x4
/* file can be accessed using pread */
#define FMODE_PREAD 0x8
/* file can be accessed using pwrite */
#define FMODE_PWRITE 0x10
/* File is opened for execution with sys_execve / sys_uselib */
#define FMODE_EXEC 0x20
/* File is opened with O_NDELAY (only set for block devices) */
#define FMODE_NDELAY 0x40
/* File is opened with O_EXCL (only set for block devices) */
#define FMODE_EXCL 0x80
/* dfs_vnode.c */
int dfs_vnode_init(struct dfs_vnode *vnode, int type, const struct dfs_file_ops *fops);
struct dfs_vnode *dfs_vnode_create(void);
int dfs_vnode_destroy(struct dfs_vnode* vnode);
struct dfs_vnode *dfs_vnode_ref(struct dfs_vnode *vnode);
void dfs_vnode_unref(struct dfs_vnode *vnode);
/*dfs_file.c*/
#ifdef RT_USING_SMART
struct dfs_mmap2_args
{
void *addr;
size_t length;
int prot;
int flags;
off_t pgoffset;
size_t min_align_size;
struct rt_lwp *lwp;
void *ret;
};
#endif
void dfs_file_init(struct dfs_file *file);
void dfs_file_deinit(struct dfs_file *file);
int dfs_file_open(struct dfs_file *file, const char *path, int flags, mode_t mode);
int dfs_file_close(struct dfs_file *file);
off_t dfs_file_get_fpos(struct dfs_file *file);
void dfs_file_set_fpos(struct dfs_file *file, off_t fpos);
ssize_t dfs_file_pread(struct dfs_file *file, void *buf, size_t len, off_t offset);
ssize_t dfs_file_read(struct dfs_file *file, void *buf, size_t len);
ssize_t dfs_file_pwrite(struct dfs_file *file, const void *buf, size_t len, off_t offset);
ssize_t dfs_file_write(struct dfs_file *file, const void *buf, size_t len);
off_t generic_dfs_lseek(struct dfs_file *file, off_t offset, int whence);
off_t dfs_file_lseek(struct dfs_file *file, off_t offset, int wherece);
int dfs_file_stat(const char *path, struct stat *buf);
int dfs_file_lstat(const char *path, struct stat *buf);
int dfs_file_setattr(const char *path, struct dfs_attr *attr);
int dfs_file_fstat(struct dfs_file *file, struct stat *buf);
int dfs_file_ioctl(struct dfs_file *file, int cmd, void *args);
int dfs_file_fcntl(int fd, int cmd, unsigned long arg);
int dfs_file_fsync(struct dfs_file *file);
int dfs_file_unlink(const char *path);
int dfs_file_link(const char *oldname, const char *newname);
int dfs_file_symlink(const char *oldname, const char *name);
int dfs_file_readlink(const char *path, char *buf, int bufsize);
int dfs_file_rename(const char *old_file, const char *new_file);
int dfs_file_ftruncate(struct dfs_file *file, off_t length);
int dfs_file_getdents(struct dfs_file *file, struct dirent *dirp, size_t nbytes);
int dfs_file_mkdir(const char *path, mode_t mode);
int dfs_file_rmdir(const char *pathname);
int dfs_file_isdir(const char *path);
int dfs_file_access(const char *path, mode_t mode);
int dfs_file_chdir(const char *path);
char *dfs_file_getcwd(char *buf, size_t size);
#ifdef RT_USING_SMART
int dfs_file_mmap2(struct dfs_file *file, struct dfs_mmap2_args *mmap2);
int dfs_file_mmap(struct dfs_file *file, struct dfs_mmap2_args *mmap2);
#endif
/* 0x5254 is just a magic number to make these relatively unique ("RT") */
#define RT_FIOFTRUNCATE 0x52540000U
#define RT_FIOGETADDR 0x52540001U
#define RT_FIOMMAP2 0x52540002U
/* dfs_file_realpath mode */
#define DFS_REALPATH_EXCEPT_LAST 0
#define DFS_REALPATH_EXCEPT_NONE 1
#define DFS_REALPATH_ONLY_LAST 3
char *dfs_file_realpath(struct dfs_mnt **mnt, const char *fullpath, int mode);
#ifdef __cplusplus
}
#endif
#endif
@@ -0,0 +1,141 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2005-02-22 Bernard The first version.
* 2023-05-05 Bernard Change to dfs v2.0
*/
#ifndef __DFS_FS_H__
#define __DFS_FS_H__
#include <dfs.h>
#include <dfs_file.h>
#ifdef __cplusplus
extern "C"
{
#endif
#define MS_RDONLY 1
#define MS_NOSUID 2
#define MS_NODEV 4
#define MS_NOEXEC 8
#define MS_SYNCHRONOUS 16
#define MS_REMOUNT 32
#define MS_MANDLOCK 64
#define MS_DIRSYNC 128
#define MS_NOATIME 1024
#define MS_NODIRATIME 2048
#define MS_BIND 4096
#define MS_MOVE 8192
#define MS_REC 16384
#define MS_SILENT 32768
#define MS_POSIXACL (1<<16)
#define MS_UNBINDABLE (1<<17)
#define MS_PRIVATE (1<<18)
#define MS_SLAVE (1<<19)
#define MS_SHARED (1<<20)
#define MS_RELATIME (1<<21)
#define MS_KERNMOUNT (1<<22)
#define MS_I_VERSION (1<<23)
#define MS_STRICTATIME (1<<24)
#define MS_LAZYTIME (1<<25)
#define MS_NOREMOTELOCK (1<<27)
#define MS_NOSEC (1<<28)
#define MS_BORN (1<<29)
#define MS_ACTIVE (1<<30)
#define MS_NOUSER (1U<<31)
#define MS_RMT_MASK (MS_RDONLY|MS_SYNCHRONOUS|MS_MANDLOCK|MS_I_VERSION|MS_LAZYTIME)
/* file system partition table */
struct dfs_partition
{
uint8_t type; /* file system type */
off_t offset; /* partition start offset */
size_t size; /* partition size */
rt_sem_t lock;
};
struct dfs_attr
{
unsigned int ia_valid;
uid_t st_uid;
gid_t st_gid;
mode_t st_mode;
struct timespec ia_atime;
struct timespec ia_mtime;
};
struct dfs_mnt;
struct dfs_dentry;
struct dfs_vnode;
struct statfs;
struct dfs_filesystem_ops
{
const char *name;
uint32_t flags;
#define FS_NEED_DEVICE 0x1
const struct dfs_file_ops *default_fops;
int (*mount)(struct dfs_mnt *mnt, unsigned long rwflag, const void *data);
int (*umount)(struct dfs_mnt *mnt);
int (*mkfs)(rt_device_t devid, const char *fs_name);
int (*readlink)(struct dfs_dentry *dentry, char *buf, int len);
int (*link)(struct dfs_dentry *src_dentry, struct dfs_dentry *dst_dentry); /*hard link interface */
int (*unlink)(struct dfs_dentry *dentry);
int (*symlink)(struct dfs_dentry *parent_dentry, const char *target, const char *newpath); /*soft link interface*/
int (*rename)(struct dfs_dentry *old_dentry, struct dfs_dentry *new_dentry);
int (*stat)(struct dfs_dentry *dentry, struct stat *buf);
int (*statfs)(struct dfs_mnt *mnt, struct statfs *buf);
int (*setattr) (struct dfs_dentry *dentry, struct dfs_attr *attr);
struct dfs_vnode* (*lookup)(struct dfs_dentry *dentry);
struct dfs_vnode* (*create_vnode)(struct dfs_dentry *dentry, int type, mode_t mode);
int (*free_vnode)(struct dfs_vnode* vnode);
};
struct dfs_filesystem_type
{
const struct dfs_filesystem_ops *fs_ops;
struct dfs_filesystem_type *next;
};
struct dfs_filesystem_type *dfs_filesystems(void);
int dfs_unregister(struct dfs_filesystem_type *fs);
int dfs_register(struct dfs_filesystem_type *fs);
const char *dfs_filesystem_get_mounted_path(struct rt_device *device);
int dfs_remount(const char *path, rt_ubase_t flags, void *data);
int dfs_mount(const char *device_name,
const char *path,
const char *filesystemtype,
unsigned long rwflag,
const void *data);
int dfs_umount(const char *specialfile, int flags);
int dfs_unmount(const char *specialfile);
int dfs_is_mounted(struct dfs_mnt *mnt);
int dfs_mkfs(const char *fs_name, const char *device_name);
int dfs_statfs(const char *path, struct statfs *buffer);
int dfs_filesystem_get_partition(struct dfs_partition *part,
uint8_t *buf,
uint32_t pindex);
#ifdef __cplusplus
}
#endif
#endif
@@ -0,0 +1,80 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2023-05-05 Bernard Implement dentry in dfs v2.0
*/
#ifndef DFS_MNT_H__
#define DFS_MNT_H__
#include <rtservice.h>
#include <rtthread.h>
#ifdef __cplusplus
extern "C"
{
#endif
struct dfs_mnt;
struct dfs_dentry;
struct dfs_filesystem_ops;
struct dfs_mnt
{
struct dfs_mnt *parent; /* the parent mounted file system */
rt_list_t sibling; /* the sibling node for mounted list */
rt_list_t child; /* the child node for mounted list */
char *fullpath; /* the fullpath of this mounted file system */
int flags; /* the falgs of this mounted file system */
#define MNT_IS_ALLOCED 0x1 /* the mnt struct is allocated */
#define MNT_IS_ADDLIST 0x2 /* the mnt struct is added into list */
#define MNT_IS_MOUNTED 0x4 /* the mnt struct is mounted */
#define MNT_IS_UMOUNT 0x8 /* the mnt is unmount */
#define MNT_IS_LOCKED 0x10 /* the mnt is locked */
#define MNT_FORCE 0x20 /* the mnt force unmount */
#define MNT_LAZY_UMNT 0x40 /* the mnt has pending umount */
#define MNT_RDONLY 0x80 /* the mnt is read only */
rt_atomic_t ref_count; /* reference count */
rt_device_t dev_id; /* the mounted device id */
const struct dfs_filesystem_ops *fs_ops;
void *data;
};
struct dfs_mnt *dfs_mnt_create(const char *path);
int dfs_mnt_destroy(struct dfs_mnt* mnt);
int dfs_mnt_list(struct dfs_mnt* mnt);
int dfs_mnt_insert(struct dfs_mnt* mnt, struct dfs_mnt* child);
struct dfs_mnt *dfs_mnt_dev_lookup(rt_device_t dev_id);
struct dfs_mnt *dfs_mnt_lookup(const char *path);
const char *dfs_mnt_get_mounted_path(struct rt_device *device);
struct dfs_mnt* dfs_mnt_ref(struct dfs_mnt* mnt);
int dfs_mnt_unref(struct dfs_mnt* mnt);
int dfs_mnt_umount(struct dfs_mnt *mnt, int flags);
int dfs_mnt_setflags(struct dfs_mnt *mnt, int flags);
rt_bool_t dfs_mnt_has_child_mnt(struct dfs_mnt *mnt, const char* fullpath);
int dfs_mnt_foreach(struct dfs_mnt* (*func)(struct dfs_mnt *mnt, void *parameter), void *parameter);
int dfs_mnt_umount_iter(rt_bool_t (*filter)(struct dfs_mnt *mnt, void *parameter), void *parameter);
typedef void (*dfs_mnt_umnt_cb_t)(struct dfs_mnt *mnt);
RT_OBJECT_HOOKLIST_DECLARE(dfs_mnt_umnt_cb_t, dfs_mnt_umnt);
#ifdef __cplusplus
}
#endif
#endif
@@ -0,0 +1,134 @@
/*
* Copyright (c) 2006-2025 RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2023-05-05 RTT Implement dentry in dfs v2.0
*/
#ifndef DFS_PAGE_CACHE_H__
#define DFS_PAGE_CACHE_H__
#include <rtthread.h>
#ifdef RT_USING_PAGECACHE
#include <dfs_file.h>
#include <avl.h>
#ifdef __cplusplus
extern "C"
{
#endif
struct rt_varea;
struct rt_aspace;
struct dfs_vnode;
struct dfs_dentry;
struct dfs_aspace;
/* Memory mapping structure for page cache */
struct dfs_mmap
{
rt_list_t mmap_node; /* List node for address space's mmap list */
struct rt_aspace *aspace; /* Address space this mapping belongs to */
void *vaddr; /* Virtual address where the page is mapped */
};
/* Page structure for file system page cache */
struct dfs_page
{
rt_list_t space_node; /* Node for address space's page list */
rt_list_t dirty_node; /* Node for dirty page list */
struct util_avl_struct avl_node; /* Node for AVL tree in address space */
rt_list_t mmap_head; /* Head of memory mappings list */
rt_atomic_t ref_count; /* Reference count for this page */
void *page; /* Pointer to physical page data */
off_t fpos; /* File position this page represents */
size_t size; /* Total size of the page */
size_t len; /* Valid data length in the page */
int is_dirty; /* Dirty flag indicating if page needs writeback */
rt_tick_t tick_ms; /* Last access timestamp */
struct dfs_aspace *aspace; /* Address space this page belongs to */
};
/* Address space operations interface */
struct dfs_aspace_ops
{
ssize_t (*read)(struct dfs_file *file, struct dfs_page *page); /* Read operation for page cache */
ssize_t (*write)(struct dfs_page *page); /* Write operation for page cache */
};
/* Address space structure for page cache management */
struct dfs_aspace
{
rt_list_t hash_node, cache_node; /* Nodes for hash table and cache lists */
char *fullpath, *pathname; /* Full path and relative path strings */
struct dfs_mnt *mnt; /* Mount point this space belongs to */
rt_list_t list_active, list_inactive; /* Active and inactive page lists */
rt_list_t list_dirty; /* Dirty page list */
size_t pages_count; /* Total pages in this space */
struct util_avl_root avl_root; /* AVL tree root for page lookup */
struct dfs_page *avl_page; /* Current AVL tree page */
rt_bool_t is_active; /* Active/inactive status flag */
struct rt_mutex lock; /* Mutex for thread safety */
rt_atomic_t ref_count; /* Reference counter */
struct dfs_vnode *vnode; /* Associated vnode */
const struct dfs_aspace_ops *ops; /* Operations interface */
};
#ifndef RT_PAGECACHE_HASH_NR
#define RT_PAGECACHE_HASH_NR 1024
#endif
/* Global page cache management structure */
struct dfs_pcache
{
rt_list_t head[RT_PAGECACHE_HASH_NR]; /* Hash table buckets for address spaces */
rt_list_t list_active, list_inactive; /* Active and inactive space lists */
rt_atomic_t pages_count; /* Total cached pages count */
struct rt_mutex lock; /* Global lock for thread safety */
struct rt_messagequeue *mqueue; /* Message queue for sending GC/WB command.*/
rt_tick_t last_time_wb; /* Last writeback timestamp */
};
struct dfs_aspace *dfs_aspace_create(struct dfs_dentry *dentry, struct dfs_vnode *vnode, const struct dfs_aspace_ops *ops);
int dfs_aspace_destroy(struct dfs_aspace *aspace);
int dfs_aspace_read(struct dfs_file *file, void *buf, size_t count, off_t *pos);
int dfs_aspace_write(struct dfs_file *file, const void *buf, size_t count, off_t *pos);
int dfs_aspace_flush(struct dfs_aspace *aspace);
int dfs_aspace_clean(struct dfs_aspace *aspace);
void *dfs_aspace_mmap(struct dfs_file *file, struct rt_varea *varea, void *vaddr);
int dfs_aspace_unmap(struct dfs_file *file, struct rt_varea *varea);
int dfs_aspace_page_unmap(struct dfs_file *file, struct rt_varea *varea, void *vaddr);
int dfs_aspace_page_dirty(struct dfs_file *file, struct rt_varea *varea, void *vaddr);
off_t dfs_aspace_fpos(struct rt_varea *varea, void *vaddr);
void *dfs_aspace_vaddr(struct rt_varea *varea, off_t fpos);
int dfs_aspace_mmap_read(struct dfs_file *file, struct rt_varea *varea, void *data);
int dfs_aspace_mmap_write(struct dfs_file *file, struct rt_varea *varea, void *data);
void dfs_pcache_release(size_t count);
void dfs_pcache_unmount(struct dfs_mnt *mnt);
void dfs_pcache_clean(struct dfs_mnt *mnt);
#ifdef __cplusplus
}
#endif
#endif
#endif
@@ -0,0 +1,32 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2009-05-27 Yi.qiu The first version.
* 2010-07-18 Bernard add stat and statfs structure definitions.
* 2011-05-16 Yi.qiu Change parameter name of rename, "new" is C++ key word.
* 2017-12-27 Bernard Add fcntl API.
* 2018-02-07 Bernard Change the 3rd parameter of open/fcntl/ioctl to '...'
*/
#ifndef __DFS_POSIX_H__
#define __DFS_POSIX_H__
#include <fcntl.h>
#include <errno.h>
#include <dfs.h>
#include <dfs_file.h>
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif
@@ -0,0 +1,78 @@
/*
* Copyright (c) 2006-2025 RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#ifndef __DFS_SEQ_FILE_H__
#define __DFS_SEQ_FILE_H__
#include <dfs.h>
#include <dfs_fs.h>
struct dfs_seq_ops;
/**
* Sequence file control structure
*/
struct dfs_seq_file
{
char *buf; /* Data buffer pointer */
size_t size; /* Total buffer size in bytes */
size_t from; /* Start offset of valid data in buffer */
size_t count; /* Length of valid data in buffer */
size_t pad_until; /* Padding target position for alignment */
off_t index; /* Current item index in sequence */
off_t read_pos; /* Current read position in file */
struct rt_mutex lock; /* Mutex for thread safety */
const struct dfs_seq_ops *ops; /* Operation function table */
const struct dfs_file *file; /* Associated file object */
void *data; /* Private data pointer */
};
/**
* Sequence file operations structure
*/
struct dfs_seq_ops
{
void *(*start)(struct dfs_seq_file *seq, off_t *index); /* Start sequence traversal */
void (*stop)(struct dfs_seq_file *seq, void *data); /* Stop sequence traversal */
void *(*next)(struct dfs_seq_file *seq, void *data, off_t *index); /* Get next item in sequence */
int (*show)(struct dfs_seq_file *seq, void *data); /* Show current item */
};
/**
* check if the buffer is full
*/
static inline rt_bool_t dfs_seq_is_full(struct dfs_seq_file *seq)
{
return seq->count == seq->size;
}
/**
* set padding width size
*/
static inline void dfs_seq_setwidth(struct dfs_seq_file *seq, size_t size)
{
seq->pad_until = seq->count + size;
}
int dfs_seq_open(struct dfs_file *file, const struct dfs_seq_ops *ops);
ssize_t dfs_seq_read(struct dfs_file *file, void *buf, size_t size, off_t *pos);
off_t dfs_seq_lseek(struct dfs_file *file, off_t offset, int whence);
int dfs_seq_release(struct dfs_file *file);
int dfs_seq_write(struct dfs_seq_file *seq, const void *data, size_t len);
void dfs_seq_vprintf(struct dfs_seq_file *seq, const char *fmt, va_list args);
void dfs_seq_printf(struct dfs_seq_file *seq, const char *fmt, ...);
void dfs_seq_putc(struct dfs_seq_file *seq, char c);
void dfs_seq_puts(struct dfs_seq_file *seq, const char *s);
void dfs_seq_pad(struct dfs_seq_file *seq, char c);
#endif
@@ -0,0 +1,50 @@
/*
* Copyright (c) 2006-2024, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#ifndef __DFS_VFS_H__
#define __DFS_VFS_H__
#include "dfs_file.h"
#include "dfs_fs.h"
#ifdef __cplusplus
extern "C"
{
#endif
struct dfs_vfs_node
{
rt_list_t subnode; /* file subnode list */
rt_list_t sibling; /* file sibling list */
};
rt_inline void dfs_vfs_init_node(struct dfs_vfs_node *node)
{
rt_list_init(&node->subnode);
rt_list_init(&node->sibling);
}
rt_inline void dfs_vfs_append_node(struct dfs_vfs_node *dir, struct dfs_vfs_node *node)
{
rt_list_insert_after(&(dir->subnode), &(node->sibling));
}
rt_inline void dfs_vfs_remove_node(struct dfs_vfs_node *node)
{
rt_list_remove(&(node->sibling));
}
#define dfs_vfs_for_each_subnode(node, tmp, dir, member) \
rt_list_for_each_entry_safe(node, tmp, &dir->member.subnode, member.sibling)
#ifdef __cplusplus
}
#endif
#endif /*__DFS_VFS_H__*/
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,515 @@
/*
* Copyright (c) 2006-2025 RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2022-10-10 Bernard The first version of rewrite dfs
*/
#include <rtthread.h>
#include "dfs.h"
#include "dfs_file.h"
#include "dfs_private.h"
#include "dfs_dentry.h"
#include "dfs_mnt.h"
#define DBG_TAG "DFS.dentry"
#define DBG_LVL DBG_WARNING
#include <rtdbg.h>
#define DFS_DENTRY_HASH_NR 32
struct dentry_hash_head
{
rt_list_t head[DFS_DENTRY_HASH_NR];
};
static struct dentry_hash_head hash_head;
/**
* @brief Calculate hash value for a dentry based on mount point and path
*
* @param[in] mnt Pointer to the mount point structure
* @param[in] path Path string to be hashed (can be NULL)
*
* @return uint32_t Calculated hash value within range [0, DFS_DENTRY_HASH_NR-1]
*/
static uint32_t _dentry_hash(struct dfs_mnt *mnt, const char *path)
{
uint32_t val = 0;
if (path)
{
while (*path)
{
val = ((val << 5) + val) + *path++;
}
}
return (val ^ (unsigned long) mnt) & (DFS_DENTRY_HASH_NR - 1);
}
/**
* @brief Create a new directory entry (dentry) structure
*
* @param[in] mnt Pointer to the mount point structure
* @param[in] path Path string for the dentry (absolute or relative)
* @param[in] is_rela_path Flag indicating if path is relative (RT_TRUE) or absolute (RT_FALSE)
*
* @return struct dfs_dentry* Pointer to newly created dentry, or NULL if creation failed
*
* @note The created dentry will have its ref_count initialized to 1 and DENTRY_IS_ALLOCED flag set
*/
static struct dfs_dentry *_dentry_create(struct dfs_mnt *mnt, char *path, rt_bool_t is_rela_path)
{
struct dfs_dentry *dentry = RT_NULL;
if (mnt == RT_NULL || path == RT_NULL)
{
return dentry;
}
dentry = (struct dfs_dentry *)rt_calloc(1, sizeof(struct dfs_dentry));
if (dentry)
{
char *dentry_path = path;
if (!is_rela_path)
{
int mntpoint_len = strlen(mnt->fullpath);
if (rt_strncmp(mnt->fullpath, dentry_path, mntpoint_len) == 0)
{
dentry_path += mntpoint_len;
}
}
dentry->pathname = strlen(dentry_path) ? rt_strdup(dentry_path) : rt_strdup(path);
dentry->mnt = dfs_mnt_ref(mnt);
rt_atomic_store(&(dentry->ref_count), 1);
dentry->flags |= DENTRY_IS_ALLOCED;
LOG_I("create a dentry:%p for %s", dentry, mnt->fullpath);
}
return dentry;
}
/**
* @brief Create a new directory entry (dentry) with absolute path
*
* @param[in] mnt Pointer to the mount point structure
* @param[in] fullpath Absolute path string for the dentry
*
* @return struct dfs_dentry* Pointer to newly created dentry, or NULL if creation failed
*
* @note This is a wrapper for _dentry_create() with is_rela_path set to RT_FALSE
* @see _dentry_create()
*/
struct dfs_dentry *dfs_dentry_create(struct dfs_mnt *mnt, char *fullpath)
{
return _dentry_create(mnt, fullpath, RT_FALSE);
}
/**
* @brief Create a new directory entry (dentry) with relative path
*
* @param[in] mnt Pointer to the mount point structure
* @param[in] rela_path Relative path string for the dentry
*
* @return struct dfs_dentry* Pointer to newly created dentry, or NULL if creation failed
*
* @note This is a wrapper for _dentry_create() with is_rela_path set to RT_TRUE
* @see _dentry_create()
*/
struct dfs_dentry *dfs_dentry_create_rela(struct dfs_mnt *mnt, char *rela_path)
{
return _dentry_create(mnt, rela_path, RT_TRUE);;
}
/**
* @brief Increase reference count for a directory entry (dentry)
*
* @param[in,out] dentry Pointer to the directory entry structure to be referenced
*
* @return struct dfs_dentry* The same dentry pointer that was passed in
*
* @note This function will also increase reference count for associated vnode if exists
*/
struct dfs_dentry * dfs_dentry_ref(struct dfs_dentry *dentry)
{
if (dentry)
{
int ret = dfs_file_lock();
if (ret == RT_EOK)
{
rt_atomic_add(&(dentry->ref_count), 1);
if (dentry->vnode)
{
rt_atomic_add(&(dentry->vnode->ref_count), 1);
}
dfs_file_unlock();
}
}
return dentry;
}
/**
* @brief Decrease reference count for a directory entry (dentry) and free if count reaches zero
*
* @param[in,out] dentry Pointer to the directory entry structure to be unreferenced
*
* @return struct dfs_dentry* The same dentry pointer if ref_count > 0, NULL if freed
*/
struct dfs_dentry *dfs_dentry_unref(struct dfs_dentry *dentry)
{
rt_err_t ret = RT_EOK;
if (dentry)
{
ret = dfs_file_lock();
if (ret == RT_EOK)
{
if (dentry->flags & DENTRY_IS_ALLOCED)
{
rt_atomic_sub(&(dentry->ref_count), 1);
}
if (rt_atomic_load(&(dentry->ref_count)) == 0)
{
DLOG(msg, "dentry", "dentry", DLOG_MSG, "free dentry, ref_count=0");
if (dentry->flags & DENTRY_IS_ADDHASH)
{
rt_list_remove(&dentry->hashlist);
}
/* release vnode */
if (dentry->vnode)
{
dfs_vnode_unref(dentry->vnode);
}
/* release mnt */
DLOG(msg, "dentry", "mnt", DLOG_MSG, "dfs_mnt_unref(dentry->mnt)");
if (dentry->mnt)
{
dfs_mnt_unref(dentry->mnt);
}
dfs_file_unlock();
LOG_I("free a dentry: %p", dentry);
rt_free(dentry->pathname);
rt_free(dentry);
dentry = RT_NULL;
}
else
{
if (dentry->vnode)
{
rt_atomic_sub(&(dentry->vnode->ref_count), 1);
}
dfs_file_unlock();
DLOG(note, "dentry", "dentry ref_count=%d", rt_atomic_load(&(dentry->ref_count)));
}
}
}
return dentry;
}
/**
* @brief Look up a directory entry (dentry) in hash table by mount point and path
*
* @param[in] mnt Pointer to the mount point structure to search for
* @param[in] path Path string to search for
*
* @return struct dfs_dentry* Pointer to found dentry (with increased ref_count), or NULL if not found
*/
static struct dfs_dentry *_dentry_hash_lookup(struct dfs_mnt *mnt, const char *path)
{
rt_err_t ret = RT_EOK;
struct dfs_dentry *entry = RT_NULL;
ret = dfs_file_lock();
if (ret == RT_EOK)
{
rt_list_for_each_entry(entry, &hash_head.head[_dentry_hash(mnt, path)], hashlist)
{
if (entry->mnt == mnt && !strcmp(entry->pathname, path))
{
dfs_dentry_ref(entry);
dfs_file_unlock();
return entry;
}
}
dfs_file_unlock();
}
return RT_NULL;
}
/**
* @brief Insert a directory entry (dentry) into the hash table
*
* @param[in,out] dentry Pointer to the directory entry to be inserted
*/
void dfs_dentry_insert(struct dfs_dentry *dentry)
{
dfs_file_lock();
rt_list_insert_after(&hash_head.head[_dentry_hash(dentry->mnt, dentry->pathname)], &dentry->hashlist);
dentry->flags |= DENTRY_IS_ADDHASH;
dfs_file_unlock();
}
/**
* @brief Look up a directory entry (dentry) in the filesystem
*
* @param[in] mnt Pointer to the mount point structure
* @param[in] path Path string to look up
* @param[in] flags Additional lookup flags (currently unused)
*
* @return struct dfs_dentry* Pointer to found/created dentry (with increased ref_count), or NULL if not found
*
* @note This function first searches for dentry in hash table,
* If not found and filesystem supports lookup operation:
* - Creates new dentry
* - Calls filesystem's lookup operation to get vnode
* - If vnode is successfully obtained, adds dentry to hash table
*/
struct dfs_dentry *dfs_dentry_lookup(struct dfs_mnt *mnt, const char *path, uint32_t flags)
{
struct dfs_dentry *dentry;
struct dfs_vnode *vnode = RT_NULL;
int mntpoint_len = strlen(mnt->fullpath);
if (rt_strncmp(mnt->fullpath, path, mntpoint_len) == 0)
{
path += mntpoint_len;
if ((*path) == '\0')
{
/* root */
path = "/";
}
}
dfs_file_lock();
dentry = _dentry_hash_lookup(mnt, path);
if (!dentry)
{
if (mnt->fs_ops->lookup)
{
DLOG(activate, "dentry");
/* not in hash table, create it */
DLOG(msg, "dentry", "dentry", DLOG_MSG, "dfs_dentry_create_rela(mnt=%s, path=%s)", mnt->fullpath, path);
dentry = dfs_dentry_create_rela(mnt, (char*)path);
if (dentry)
{
DLOG(msg, "dentry", mnt->fs_ops->name, DLOG_MSG, "vnode=fs_ops->lookup(dentry)");
if (dfs_is_mounted(mnt) == 0)
{
vnode = mnt->fs_ops->lookup(dentry);
}
if (vnode)
{
DLOG(msg, mnt->fs_ops->name, "dentry", DLOG_MSG_RET, "return vnode");
dentry->vnode = vnode; /* the refcount of created vnode is 1. no need to reference */
dfs_file_lock();
rt_list_insert_after(&hash_head.head[_dentry_hash(mnt, path)], &dentry->hashlist);
dentry->flags |= DENTRY_IS_ADDHASH;
dfs_file_unlock();
if (dentry->flags & (DENTRY_IS_ALLOCED | DENTRY_IS_ADDHASH)
&& !(dentry->flags & DENTRY_IS_OPENED))
{
rt_err_t ret = dfs_file_lock();
if (ret == RT_EOK)
{
dentry->flags |= DENTRY_IS_OPENED;
dfs_file_unlock();
}
}
}
else
{
DLOG(msg, mnt->fs_ops->name, "dentry", DLOG_MSG_RET, "no dentry");
DLOG(msg, "dentry", "dentry", DLOG_MSG, "dfs_dentry_unref(dentry)");
dfs_dentry_unref(dentry);
dentry = RT_NULL;
}
}
DLOG(deactivate, "dentry");
}
}
else
{
DLOG(note, "dentry", "found dentry");
}
dfs_file_unlock();
return dentry;
}
/**
* @brief Get the full path of a directory entry by combining mount point and relative path
*
* @param[in] dentry Pointer to the directory entry structure
*
* @return char* Newly allocated string containing full path, or NULL if allocation failed
*
* @note The caller is responsible for freeing the returned string using rt_free()
* @note Handles path concatenation with or without additional '/' separator
*/
char* dfs_dentry_full_path(struct dfs_dentry* dentry)
{
char *path = NULL;
if (dentry && dentry->mnt)
{
int mnt_len = strlen(dentry->mnt->fullpath);
int path_len = strlen(dentry->pathname);
path = (char *) rt_malloc(mnt_len + path_len + 3);
if (path)
{
if (dentry->pathname[0] == '/' || dentry->mnt->fullpath[mnt_len - 1] == '/')
{
rt_snprintf(path, mnt_len + path_len + 2, "%s%s", dentry->mnt->fullpath,
dentry->pathname);
}
else
{
rt_snprintf(path, mnt_len + path_len + 2, "%s/%s", dentry->mnt->fullpath,
dentry->pathname);
}
}
}
return path;
}
/**
* @brief Get the parent directory path of a dentry by combining mount point and path
*
* @param[in] dentry Pointer to the directory entry structure
*
* @return char* Newly allocated string containing parent path, or NULL if allocation failed
*
* @note The caller is responsible for freeing the returned string using rt_free()
* @note Handles both absolute and relative paths correctly
* @note Returns mount point path if dentry is at root directory
*/
char* dfs_dentry_pathname(struct dfs_dentry* dentry)
{
char *pathname = RT_NULL;
char *index = RT_NULL;
index = strrchr(dentry->pathname, '/');
if (index)
{
int length = index - dentry->pathname;
int path_length = strlen(dentry->mnt->fullpath) + length + 3;
pathname = (char*) rt_malloc(path_length);
if (pathname)
{
if (dentry->pathname[0] == '/')
{
rt_snprintf(pathname, path_length - 1, "%s%.*s", dentry->mnt->fullpath,
length, dentry->pathname);
}
else
{
rt_snprintf(pathname, path_length - 1, "%s/%.*s", dentry->mnt->fullpath,
length, dentry->pathname);
}
}
}
else
{
pathname = rt_strdup(dentry->mnt->fullpath);
}
return pathname;
}
/**
* @brief Calculate CRC32 checksum for the full path of a directory entry
*
* @param[in] dentry Pointer to the directory entry structure
*
* @return uint32_t CRC32 checksum value of the full path
*
* @note Uses standard CRC32 polynomial 0xEDB88320
*/
uint32_t dfs_dentry_full_path_crc32(struct dfs_dentry* dentry)
{
uint32_t crc32 = 0xFFFFFFFF;
char *fullpath = dfs_dentry_full_path(dentry);
if (fullpath)
{
int i = 0;
while(fullpath[i] != '\0')
{
for (uint8_t b = 1; b; b <<= 1)
{
crc32 ^= (fullpath[i] & b) ? 1 : 0;
crc32 = (crc32 & 1) ? crc32 >> 1 ^ 0xEDB88320 : crc32 >> 1;
}
i ++;
}
rt_free(fullpath);
}
return crc32;
}
/**
* @brief Initialize the dentry hash table
*
* @return int Always returns 0 indicating success
*
* @note Initializes all hash buckets in the dentry hash table
*/
int dfs_dentry_init(void)
{
int i = 0;
for(i = 0; i < DFS_DENTRY_HASH_NR; i++)
{
rt_list_init(&hash_head.head[i]);
}
return 0;
}
/**
* @brief Dump all directory entries in the hash table for debugging
*
* @param[in] argc Number of command line arguments (unused)
* @param[in] argv Array of command line arguments (unused)
*
* @return int Always returns 0 indicating success
*
* @note Prints each dentry's full path, memory address and reference count
*/
int dfs_dentry_dump(int argc, char** argv)
{
int index = 0;
struct dfs_dentry *entry = RT_NULL;
dfs_lock();
for (index = 0; index < DFS_DENTRY_HASH_NR; index ++)
{
rt_list_for_each_entry(entry, &hash_head.head[index], hashlist)
{
printf("dentry: %s%s @ %p, ref_count = %zd\n", entry->mnt->fullpath, entry->pathname, entry, (size_t)rt_atomic_load(&entry->ref_count));
}
}
dfs_unlock();
return 0;
}
MSH_CMD_EXPORT_ALIAS(dfs_dentry_dump, dentry_dump, dump dentry in the system);
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,693 @@
/*
* Copyright (c) 2006-2025 RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#include "dfs_file.h"
#include "dfs_dentry.h"
#include "dfs_mnt.h"
#define DBG_TAG "dfs.mmap"
#define DBG_LVL DBG_WARNING
#include <rtdbg.h>
#if defined(RT_USING_SMART) && defined(ARCH_MM_MMU) && defined(RT_USING_PAGECACHE)
#include "dfs_pcache.h"
#include <lwp.h>
#include <sys/mman.h>
#include <lwp_user_mm.h>
#include <mm_aspace.h>
#include <mm_fault.h>
#include <mm_flag.h>
#include <mm_page.h>
#include <mmu.h>
#include <page.h>
#include <tlb.h>
static rt_mem_obj_t dfs_get_mem_obj(struct dfs_file *file);
static void *dfs_mem_obj_get_file(rt_mem_obj_t mem_obj);
/**
* @brief Perform memory mapping operation
*
* @param[in] lwp Pointer to the lightweight process structure
* @param[in] map_vaddr Requested virtual address for mapping (may be NULL)
* @param[in] map_size Size of the memory region to map
* @param[in] attr Memory attributes for the mapping
* @param[in] flags Memory mapping flags
* @param[in] pgoffset Offset in pages from the start of the memory object
* @param[in] data Pointer to the file descriptor to be mapped
* @param[out] code Pointer to store the operation result code
*
* @return void* The mapped virtual address on success, NULL on failure
*
* @note This is a low-level mapping function that interacts directly with the address space manager.
* The actual mapping is performed by rt_aspace_map().
*/
static void *_do_mmap(struct rt_lwp *lwp, void *map_vaddr, size_t map_size, size_t attr,
mm_flag_t flags, off_t pgoffset, void *data, rt_err_t *code)
{
int ret = 0;
void *vaddr = map_vaddr;
rt_mem_obj_t mem_obj = dfs_get_mem_obj(data);
ret = rt_aspace_map(lwp->aspace, &vaddr, map_size,
attr, flags, mem_obj, pgoffset);
if (ret != RT_EOK)
{
vaddr = RT_NULL;
LOG_E("failed to map %lx with size %lx with errno %d", map_vaddr,
map_size, ret);
}
if (code)
{
*code = ret;
}
return vaddr;
}
/**
* @brief Map data to user space address
*
* @param[in,out] mmap2 Pointer to memory mapping arguments structure
* - Input: Contains mapping parameters (addr, length, etc.)
* - Output: Contains the mapped address in ret field if successful
* @param[in] data Pointer to the file descriptor to be mapped
* @param[out] code Pointer to store the error code if mapping fails
*
* @return void* The mapped virtual address on success, NULL on failure
*
* @note This function performs page alignment on the mapping parameters and
* converts user-space flags/attributes to kernel-space before mapping.
*/
static void *_map_data_to_uspace(struct dfs_mmap2_args *mmap2, void *data, rt_err_t *code)
{
size_t offset = 0;
void *map_vaddr = mmap2->addr;
size_t map_size = mmap2->length;
struct rt_lwp *lwp = mmap2->lwp;
rt_size_t k_attr;
rt_size_t k_flags;
if (map_size)
{
offset = (size_t)map_vaddr & ARCH_PAGE_MASK;
map_size += (offset + ARCH_PAGE_SIZE - 1);
map_size &= ~ARCH_PAGE_MASK;
map_vaddr = (void *)((size_t)map_vaddr & ~ARCH_PAGE_MASK);
k_flags = lwp_user_mm_flag_to_kernel(mmap2->flags);
k_flags = MMF_CREATE(k_flags, mmap2->min_align_size);
k_attr = lwp_user_mm_attr_to_kernel(mmap2->prot);
map_vaddr = _do_mmap(lwp, map_vaddr, map_size, k_attr, k_flags, mmap2->pgoffset, data, code);
}
return map_vaddr;
}
static void hint_free(rt_mm_va_hint_t hint)
{
}
/**
* @brief Handle page fault for memory mapped file
*
* @param[in] varea Pointer to the virtual memory area structure
* @param[in,out] msg Pointer to the page fault message structure
* - Input: Contains fault information (fault_vaddr, etc.)
* - Output: Contains response status and mapped page address
*
* @note This function is called when a page fault occurs in a memory mapped file region.
* It attempts to map the faulting page and updates the response accordingly.
*/
static void on_page_fault(struct rt_varea *varea, struct rt_aspace_fault_msg *msg)
{
void *page;
struct dfs_file *file = dfs_mem_obj_get_file(varea->mem_obj);
if (file)
{
LOG_I("%s varea: %p", __func__, varea);
LOG_I("varea start: %p size: 0x%x offset: 0x%x attr: 0x%x flag: 0x%x",
varea->start, varea->size, varea->offset, varea->attr, varea->flag);
LOG_I("fault vaddr: %p", msg->fault_vaddr);
if (file->dentry)
{
LOG_I("file: %s%s", file->dentry->mnt->fullpath, file->dentry->pathname);
}
page = dfs_aspace_mmap(file, varea, msg->fault_vaddr);
if (page)
{
msg->response.status = MM_FAULT_STATUS_OK_MAPPED;
msg->response.size = ARCH_PAGE_SIZE;
msg->response.vaddr = page;
}
else
{
LOG_E("%s varea %p mmap failed at vaddr %p", __func__, varea, msg->fault_vaddr);
}
}
else
{
LOG_E("%s varea %p not a file, vaddr %p", __func__, varea, varea->start);
}
}
/**
* @brief Handle virtual memory area opening event
*
* @param[in] varea Pointer to the virtual memory area structure
*
* @note This function is called when a virtual memory area is opened.
* It increments the reference count of the associated file and
* initializes varea->data to NULL.
*/
static void on_varea_open(struct rt_varea *varea)
{
struct dfs_file *file = dfs_mem_obj_get_file(varea->mem_obj);
varea->data = RT_NULL;
rt_atomic_add(&(file->ref_count), 1);
}
/**
* @brief Handle virtual memory area closing event
*
* @param[in] varea Pointer to the virtual memory area structure
*
* @note This function is called when a virtual memory area is closed.
* It performs cleanup operations including:
* - Unmapping the file from memory
* - Decrementing file reference count
* - Closing and destroying file if reference count reaches zero
*/
static void on_varea_close(struct rt_varea *varea)
{
struct dfs_file *file = dfs_mem_obj_get_file(varea->mem_obj);
if (file)
{
LOG_I("%s varea: %p", __func__, varea);
LOG_I("varea start: %p size: 0x%x offset: 0x%x attr: 0x%x flag: 0x%x",
varea->start, varea->size, varea->offset, varea->attr, varea->flag);
if (file->dentry)
{
LOG_I("file: %s%s", file->dentry->mnt->fullpath, file->dentry->pathname);
}
dfs_aspace_unmap(file, varea);
dfs_file_lock();
if (rt_atomic_load(&(file->ref_count)) == 1)
{
dfs_file_close(file);
dfs_file_destroy(file);
}
else
{
rt_atomic_sub(&(file->ref_count), 1);
}
dfs_file_unlock();
}
else
{
LOG_E("%s varea %p not a file, vaddr %p", __func__, varea, varea->start);
}
}
/**
* @brief Get the name of the memory mapped file
*
* @param[in] varea Pointer to the virtual memory area structure
*
* @return const char* The name of the mapped file if available,
* otherwise returns "file-mapper" as default name
*
* @note This function retrieves the file name from the dentry structure
* associated with the memory mapped file.
*/
static const char *get_name(rt_varea_t varea)
{
struct dfs_file *file = dfs_mem_obj_get_file(varea->mem_obj);
return (file && file->dentry) ? file->dentry->pathname : "file-mapper";
}
/**
* @brief Read data from memory mapped file page
*
* @param[in] varea Pointer to the virtual memory area structure
* @param[in,out] msg Pointer to the I/O message structure
* - Input: Contains read request information
* - Output: Contains response status and read data
*
* @note This function handles page read operations for memory mapped files.
* If the read size is less than page size, it zero-fills the remaining space.
*/
void page_read(struct rt_varea *varea, struct rt_aspace_io_msg *msg)
{
rt_ubase_t ret;
struct dfs_file *file = dfs_mem_obj_get_file(varea->mem_obj);
if (file)
{
LOG_I("%s varea: %p", __func__, varea);
LOG_I("varea start: %p size: 0x%x offset: 0x%x attr: 0x%x flag: 0x%x",
varea->start, varea->size, varea->offset, varea->attr, varea->flag);
ret = dfs_aspace_mmap_read(file, varea, msg);
if (ret >= 0)
{
msg->response.status = MM_FAULT_STATUS_OK;
if (ret < ARCH_PAGE_SIZE)
{
memset((char *)msg->buffer_vaddr + ret, 0, ARCH_PAGE_SIZE - ret);
}
}
}
else
{
LOG_E("%s varea %p not a file, vaddr %p", __func__, varea, varea->start);
}
}
/**
* @brief Write data to memory mapped file page
*
* @param[in] varea Pointer to the virtual memory area structure
* @param[in,out] msg Pointer to the I/O message structure
* - Input: Contains write request information
* - Output: Contains response status and write result
*
* @note This function handles page write operations for memory mapped files.
* If the write size is less than page size, it zero-fills the remaining space.
*/
void page_write(struct rt_varea *varea, struct rt_aspace_io_msg *msg)
{
rt_ubase_t ret;
struct dfs_file *file = dfs_mem_obj_get_file(varea->mem_obj);
if (file)
{
LOG_I("%s varea: %p", __func__, varea);
LOG_I("varea start: %p size: 0x%x offset: 0x%x attr: 0x%x flag: 0x%x",
varea->start, varea->size, varea->offset, varea->attr, varea->flag);
ret = dfs_aspace_mmap_write(file, varea, msg);
if (ret > 0)
{
msg->response.status = MM_FAULT_STATUS_OK;
if (ret < ARCH_PAGE_SIZE)
{
memset((char *)msg->buffer_vaddr + ret, 0, ARCH_PAGE_SIZE - ret);
}
}
}
else
{
LOG_E("%s varea %p not a file, vaddr %p", __func__, varea, varea->start);
}
}
/**
* @brief Unmap pages from virtual memory area
*
* @param[in] varea Pointer to the virtual memory area structure
* @param[in] rm_start Starting address of the range to unmap (must be page aligned)
* @param[in] rm_end Ending address of the range to unmap (must be page aligned)
*
* @return rt_err_t Error code:
* - RT_EOK: Success
* - -RT_ERROR: Failure (varea not associated with a file)
*
* @note This function performs page-by-page unmapping.
* Both rm_start and rm_end must be page-aligned (checked by RT_ASSERT).
*/
static rt_err_t unmap_pages(rt_varea_t varea, void *rm_start, void *rm_end)
{
struct dfs_file *file = dfs_mem_obj_get_file(varea->mem_obj);
if (file)
{
LOG_I("%s varea: %p start: %p end: %p", __func__, varea, rm_start, rm_end);
RT_ASSERT(!((rt_ubase_t)rm_start & ARCH_PAGE_MASK));
RT_ASSERT(!((rt_ubase_t)rm_end & ARCH_PAGE_MASK));
while (rm_start != rm_end)
{
dfs_aspace_page_unmap(file, varea, rm_start);
rm_start += ARCH_PAGE_SIZE;
}
return RT_EOK;
}
else
{
LOG_E("%s varea %p not a file, vaddr %p", __func__, varea, varea->start);
}
return -RT_ERROR;
}
/**
* @brief Handle virtual memory area shrinking operation
*
* @param[in] varea Pointer to the virtual memory area structure
* @param[in] new_vaddr New starting address after shrinking
* @param[in] size New size of the virtual memory area
*
* @return rt_err_t Error code:
* - RT_EOK: Success
* - Other errors from unmap_pages()
*
* @note This function determines the range of pages to unmap based on whether
* the varea is shrinking from the start or end.
*/
rt_err_t on_varea_shrink(struct rt_varea *varea, void *new_vaddr, rt_size_t size)
{
char *varea_start = varea->start;
void *rm_start;
void *rm_end;
LOG_I("%s varea: %p", __func__, varea);
LOG_I("varea start: %p size: 0x%x offset: 0x%x attr: 0x%x flag: 0x%x",
varea->start, varea->size, varea->offset, varea->attr, varea->flag);
LOG_I("new_vaddr: %p size: %p", new_vaddr, size);
if (varea_start == (char *)new_vaddr)
{
rm_start = varea_start + size;
rm_end = varea_start + varea->size;
}
else
{
rm_start = varea_start;
rm_end = new_vaddr;
}
return unmap_pages(varea, rm_start, rm_end);
}
/**
* @brief Handle virtual memory area expansion operation
*
* @param[in] varea Pointer to the virtual memory area structure
* @param[in] new_vaddr New starting address after expansion
* @param[in] size New size of the expanded virtual memory area
*
* @return rt_err_t returns RT_EOK (success).
*
* @note This function is currently not implemented.
*/
rt_err_t on_varea_expand(struct rt_varea *varea, void *new_vaddr, rt_size_t size)
{
LOG_I("%s varea: %p", __func__, varea);
LOG_I("varea start: %p size: 0x%x offset: 0x%x attr: 0x%x flag: 0x%x",
varea->start, varea->size, varea->offset, varea->attr, varea->flag);
LOG_I("new_vaddr: %p size: %p", new_vaddr, size);
return RT_EOK;
}
/**
* @brief Handle virtual memory area splitting operation
*
* @param[in] existed Pointer to the existing virtual memory area to be split
* @param[in] unmap_start Starting address of the range to unmap
* @param[in] unmap_len Length of the range to unmap
* @param[in,out] subset Pointer to the new subset virtual memory area
* - Input: Contains new varea parameters
* - Output: Contains initialized varea after splitting
*
* @return rt_err_t Error code:
* - RT_EOK: Success
* - -RT_ERROR: Failure (varea not associated with a file)
*
* @note This function splits an existing virtual memory area into two parts.
* It unmaps the specified range and initializes the new subset area.
*/
rt_err_t on_varea_split(struct rt_varea *existed, void *unmap_start, rt_size_t unmap_len, struct rt_varea *subset)
{
rt_err_t rc;
struct dfs_file *file = dfs_mem_obj_get_file(existed->mem_obj);
if (file)
{
LOG_I("%s varea: %p", __func__, existed);
LOG_I("varea start: %p size: 0x%x offset: 0x%x attr: 0x%x flag: 0x%x",
existed->start, existed->size, existed->offset, existed->attr, existed->flag);
LOG_I("unmap_start: %p unmap_len: %p", unmap_start, unmap_len);
if (file->dentry)
{
LOG_I("file: %s%s", file->dentry->mnt->fullpath, file->dentry->pathname);
}
rc = unmap_pages(existed, unmap_start, (char *)unmap_start + unmap_len);
if (!rc)
{
rc = unmap_pages(existed, subset->start, (char *)subset->start + subset->size);
if (!rc)
on_varea_open(subset);
}
return rc;
}
else
{
LOG_E("%s varea %p not a file, vaddr %p", __func__, existed, existed->start);
}
return -RT_ERROR;
}
/**
* @brief Handle virtual memory area merging operation
*
* @param[in] merge_to Pointer to the target virtual memory area that will receive the merge
* @param[in] merge_from Pointer to the source virtual memory area to be merged
*
* @return rt_err_t Error code:
* - RT_EOK: Success
* - -RT_ERROR: Failure (varea not associated with a file)
*/
rt_err_t on_varea_merge(struct rt_varea *merge_to, struct rt_varea *merge_from)
{
struct dfs_file *file = dfs_mem_obj_get_file(merge_from->mem_obj);
if (file)
{
LOG_I("%s varea: %p", __func__, merge_from);
LOG_I("varea start: %p size: 0x%x offset: 0x%x attr: 0x%x flag: 0x%x",
merge_from->start, merge_from->size, merge_from->offset, merge_from->attr, merge_from->flag);
if (file->dentry)
{
LOG_I("file: %s%s", file->dentry->mnt->fullpath, file->dentry->pathname);
}
dfs_aspace_unmap(file, merge_from);
on_varea_close(merge_from);
return RT_EOK;
}
else
{
LOG_E("%s varea %p not a file, vaddr %p", __func__, merge_from, merge_from->start);
}
return -RT_ERROR;
}
/**
* @brief Handle virtual memory area remapping operation
*
* @param[in] varea Pointer to the virtual memory area structure
* @param[in] new_size New size of the virtual memory area after remapping
* @param[in] flags Remapping flags (e.g., MREMAP_MAYMOVE)
* @param[in] new_address New starting address after remapping (optional)
*
* @return void* Pointer to the new virtual memory area after remapping
* - Returns RT_NULL if remapping fails
*
* @note This function remaps a virtual memory area to a new address or size.
* It currently supports the MREMAP_MAYMOVE flag.
*/
void *on_varea_mremap(struct rt_varea *varea, rt_size_t new_size, int flags, void *new_address)
{
void *vaddr = RT_NULL;
struct dfs_file *file = dfs_mem_obj_get_file(varea->mem_obj);
#ifndef MREMAP_MAYMOVE
#define MREMAP_MAYMOVE 1
#endif
if (file && flags == MREMAP_MAYMOVE)
{
int ret;
rt_mem_obj_t mem_obj = dfs_get_mem_obj(file);
vaddr = new_address ? new_address : varea->start;
new_size = (new_size + ARCH_PAGE_SIZE - 1);
new_size &= ~ARCH_PAGE_MASK;
ret = rt_aspace_map(varea->aspace, &vaddr, new_size, varea->attr, varea->flag, mem_obj, varea->offset);
if (ret != RT_EOK)
{
LOG_E("failed to map %lx with size %lx with errno %d", vaddr, new_size, ret);
vaddr = RT_NULL;
}
else
{
LOG_I("old: %p size: %p new: %p size: %p", varea->start, varea->size, vaddr, new_size);
}
}
return vaddr;
}
/**
* @brief Memory object operations structure
*
* Defines function pointers for various virtual memory area (varea) operations,
* including memory management, page fault handling, and lifecycle callbacks.
*/
static struct rt_mem_obj _mem_obj =
{
.hint_free = hint_free, /* Free memory hint function */
.on_page_fault = on_page_fault, /* Page fault handler */
.on_varea_open = on_varea_open, /* Varea open callback */
.on_varea_close = on_varea_close, /* Varea close callback */
.get_name = get_name, /* Get mapped file name */
.page_read = page_read, /* Page read operation */
.page_write = page_write, /* Page write operation */
.on_varea_shrink = on_varea_shrink, /* Varea shrink handler */
.on_varea_expand = on_varea_expand, /* Varea expand handler */
.on_varea_split = on_varea_split, /* Varea split handler */
.on_varea_merge = on_varea_merge, /* Varea merge handler */
.on_varea_mremap = on_varea_mremap, /* Varea remap handler */
};
/**
* @brief DFS memory object structure
*
* Contains a standard memory object and an associated file pointer,
* used to maintain the relationship between memory mappings and files.
*/
struct dfs_mem_obj {
struct rt_mem_obj mem_obj; /* Base memory object */
void *file; /* Associated file pointer */
};
/**
* @brief Get or create memory mapping object for a file
*
* @param[in] file Pointer to the file descriptor structure
*
* @return rt_mem_obj_t Memory mapping object associated with the file
* - Returns existing object if already created
* - Creates and initializes new object if not exists
*/
static rt_mem_obj_t dfs_get_mem_obj(struct dfs_file *file)
{
rt_mem_obj_t mobj = file->mmap_context;
if (!mobj)
{
struct dfs_mem_obj *dfs_mobj;
dfs_file_lock();
dfs_mobj = rt_malloc(sizeof(*dfs_mobj));
if (dfs_mobj)
{
dfs_mobj->file = file;
mobj = &dfs_mobj->mem_obj;
memcpy(mobj, &_mem_obj, sizeof(*mobj));
file->mmap_context = mobj;
}
dfs_file_unlock();
}
return mobj;
}
/**
* @brief Get the file descriptor from memory mapping object
*
* @param[in] mem_obj Pointer to the memory mapping object
*
* @return void* Pointer to the associated file descriptor structure
*
* @note This function uses rt_container_of macro to get the containing
* dfs_mem_obj structure from its mem_obj member.
*/
static void *dfs_mem_obj_get_file(rt_mem_obj_t mem_obj)
{
struct dfs_mem_obj *dfs_mobj;
dfs_mobj = rt_container_of(mem_obj, struct dfs_mem_obj, mem_obj);
return dfs_mobj->file;
}
/**
* @brief Map a file into memory
*
* @param[in] file Pointer to the file descriptor structure
* @param[in,out] mmap2 Pointer to memory mapping arguments structure
* - Input: Contains mapping parameters (addr, length, etc.)
* - Output: Contains the mapped address in ret field if successful
*
* @return int Error code:
* - EINVAL: Invalid parameters
* - Other errors from underlying mapping operations
*
* @note This function creates a virtual address area in user space (lwp) for the file mapping.
* The actual mapping is performed by _map_data_to_uspace().
*/
int dfs_file_mmap(struct dfs_file *file, struct dfs_mmap2_args *mmap2)
{
rt_err_t ret = -EINVAL;
void *map_vaddr;
LOG_I("mmap2 args addr: %p length: 0x%x prot: %d flags: 0x%x pgoffset: 0x%x",
mmap2->addr, mmap2->length, mmap2->prot, mmap2->flags, mmap2->pgoffset);
if (file && file->vnode)
{
if (file->vnode->aspace)
{
/* create a va area in user space (lwp) */
map_vaddr = _map_data_to_uspace(mmap2, file, &ret);
if (map_vaddr)
{
mmap2->ret = map_vaddr;
LOG_I("file: %s%s", file->dentry->mnt->fullpath, file->dentry->pathname);
}
}
else
{
LOG_E("File mapping is not supported, file: %s%s", file->dentry->mnt->fullpath, file->dentry->pathname);
}
}
return ret;
}
#else
int dfs_file_mmap(struct dfs_file *file, struct dfs_mmap2_args *mmap2)
{
LOG_E("File mapping support is not enabled, file: %s%s", file->dentry->mnt->fullpath, file->dentry->pathname);
LOG_E("mmap2 args addr: %p length: 0x%x prot: %d flags: 0x%x pgoffset: 0x%x",
mmap2->addr, mmap2->length, mmap2->prot, mmap2->flags, mmap2->pgoffset);
return -EPERM;
}
#endif
@@ -0,0 +1,726 @@
/*
* Copyright (c) 2006-2025 RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2005-02-22 Bernard The first version.
* 2010-06-30 Bernard Optimize for RT-Thread RTOS
* 2011-03-12 Bernard fix the filesystem lookup issue.
* 2017-11-30 Bernard fix the filesystem_operation_table issue.
* 2017-12-05 Bernard fix the fs type search issue in mkfs.
* 2023-05-05 Bernard change to dfs v2.0
*/
#include <dfs_fs.h>
#include <dfs_file.h>
#include <dfs_dentry.h>
#include <dfs_mnt.h>
#include "dfs_private.h"
#ifdef RT_USING_PAGECACHE
#include "dfs_pcache.h"
#endif
#define DBG_TAG "DFS.fs"
#define DBG_LVL DBG_INFO
#include <rtdbg.h>
static struct dfs_filesystem_type *file_systems = NULL;
extern rt_list_t _mnt_list;
/**
* @addtogroup group_fs_api
*/
/*@{*/
/**
* @brief Find a filesystem type by name
*
* This function searches the global filesystem type list for a filesystem
* matching the given name. It returns a pointer to the pointer that holds
* the matching filesystem type (or the end-of-list pointer if not found).
*
* @param[in] name The name of the filesystem type to find
* @return struct dfs_filesystem_type** Pointer to the pointer containing
* the matching filesystem type, or the end-of-list pointer if not found
*/
static struct dfs_filesystem_type **_find_filesystem(const char *name)
{
struct dfs_filesystem_type **type;
for (type = &file_systems; *type; type = &(*type)->next)
{
if (strcmp((*type)->fs_ops->name, name) == 0)
break;
}
return type;
}
/**
* @brief Get the list of registered filesystem types
*
* This function returns a pointer to the head of the global filesystem type list.
*
* @return struct dfs_filesystem_type* Pointer to the head of the filesystem type list
*/
struct dfs_filesystem_type *dfs_filesystems(void)
{
return file_systems;
}
/**
* @brief Register a filesystem type
*
* This function registers a new filesystem type with the global filesystem type list.
*
* @param[in] fs Pointer to the filesystem type to register
* @return int 0 on success, or a negative error code on failure
*/
int dfs_register(struct dfs_filesystem_type *fs)
{
int ret = 0;
struct dfs_filesystem_type **type = _find_filesystem(fs->fs_ops->name);
LOG_D("register %s file system.", fs->fs_ops->name);
if (*type)
{
ret = -EBUSY;
}
else
{
*type = fs;
}
return ret;
}
/**
* @brief Unregister a filesystem type
*
* This function unregisters a filesystem type from the global filesystem type list.
*
* @param[in] fs Pointer to the filesystem type to unregister
* @return int 0 on success, or a negative error code on failure
*/
int dfs_unregister(struct dfs_filesystem_type *fs)
{
int ret = 0;
struct dfs_filesystem_type **type;
if (fs)
{
LOG_D("unregister %s file system.", fs->fs_ops->name);
for (type = &file_systems; *type; type = &(*type)->next)
{
if (strcmp((*type)->fs_ops->name, fs->fs_ops->name) == 0)
{
*type = (*type)->next;
break;
}
}
if (!*type) ret = -EINVAL;
}
return ret;
}
#define REMNT_UNSUPP_FLAGS (~(MS_REMOUNT | MS_RMT_MASK)) /* remount unsupported flags */
/**
* @brief Remount a filesystem
*
* This function remounts a filesystem at the specified path with the given flags.
*
* @param[in] path The path of the filesystem to remount
* @param[in] flags The remount flags (see MS_REMOUNT and MS_RMT_MASK)
* @param[in] data Pointer to additional data required for remounting
* @return int 0 on success, or a negative error code on failure
*/
int dfs_remount(const char *path, rt_ubase_t flags, void *data)
{
int rc = 0;
char *fullpath = RT_NULL;
struct dfs_mnt *mnt = RT_NULL;
if (flags & REMNT_UNSUPP_FLAGS)
{
return -EINVAL;
}
fullpath = dfs_normalize_path(RT_NULL, path);
if (!fullpath)
{
rc = -ENOENT;
}
else
{
DLOG(msg, "dfs", "mnt", DLOG_MSG, "mnt = dfs_mnt_lookup(%s)", fullpath);
mnt = dfs_mnt_lookup(fullpath);
if (mnt)
{
dfs_lock();
dfs_mnt_setflags(mnt, flags);
dfs_unlock();
}
else
{
struct stat buf = {0};
if (dfs_file_stat(fullpath, &buf) == 0 && S_ISBLK(buf.st_mode))
{
/* path was not already mounted on target */
rc = -EINVAL;
}
else
{
/* path is not a directory */
rc = -ENOTDIR;
}
}
}
return rc;
}
/*
* parent(mount path)
* mnt_parent <- - - - - - - +
* | |
* |- mnt_child <- - - - - -+ (1 refcount)
* | |
* |- parent - - + (1 refcount)
*/
/**
* @brief Mount a filesystem at the specified path
*
* This function mounts a filesystem of the specified type at the given path with optional device.
* It handles both root filesystem mounting and regular filesystem mounting scenarios.
*
* @param[in] device_name The name of the device to mount (optional)
* @param[in] path The path of the mount point
* @param[in] filesystemtype The type of the filesystem to mount
* @param[in] rwflag The read/write flags (see MS_RDONLY, MS_RDWR, etc.)
* @param[in] data Pointer to additional data required for mounting
*
* @return int RT_EOK on success, negative error code on failure:
* - EPERM: Path normalization failed or mount operation failed
* - ENODEV: Filesystem type not found or device not available
* - ENOMEM: Memory allocation failure
* - EIO: Filesystem lacks mount method
* - ENOTDIR: Mount point doesn't exist
* - EEXIST: Mount point already mounted
*
* @note Special handling for root filesystem ("/")
* @note Automatic reference counting management for mount points
*/
int dfs_mount(const char *device_name,
const char *path,
const char *filesystemtype,
unsigned long rwflag,
const void *data)
{
int ret = RT_EOK;
char *fullpath = RT_NULL;
rt_device_t dev_id = RT_NULL;
struct dfs_mnt *mnt_parent = RT_NULL, *mnt_child = RT_NULL;
struct dfs_dentry *mntpoint_dentry = RT_NULL;
struct dfs_filesystem_type *type = *_find_filesystem(filesystemtype);
/* normalize the mount path */
if (type)
{
fullpath = dfs_normalize_path(RT_NULL, path);
if (!fullpath)
{
rt_set_errno(EPERM);
ret = -1;
}
}
else
{
rt_set_errno(ENODEV);
ret = -1;
}
/* Main mounting procedure */
if (fullpath)
{
DLOG(note, "mnt", "mount %s(%s) on path: %s", device_name, filesystemtype, fullpath);
/* open specific device */
if (device_name) dev_id = rt_device_find(device_name);
/* Check device requirements */
if (!(type->fs_ops->flags & FS_NEED_DEVICE) ||
((type->fs_ops->flags & FS_NEED_DEVICE) && dev_id))
{
DLOG(msg, "dfs", "mnt", DLOG_MSG, "mnt_parent = dfs_mnt_lookup(%s)", fullpath);
mnt_parent = dfs_mnt_lookup(fullpath); /* Find parent mount point */
/* Handle root filesystem mounting */
if ((!mnt_parent && (strcmp(fullpath, "/") == 0 || strcmp(fullpath, "/dev") == 0))
|| (mnt_parent && strcmp(fullpath, "/") == 0 && strcmp(mnt_parent->fullpath, fullpath) != 0))
{
LOG_D("no mnt found @ mount point %s, should be root.", fullpath);
DLOG(msg, "mnt", "dfs", DLOG_MSG_RET, "no mnt");
/* it's the root file system */
/* the mount point dentry is the same as root dentry. */
/* Create root filesystem mount point */
DLOG(msg, "dfs", "mnt", DLOG_MSG, "mnt_parent = dfs_mnt_create(path)");
mnt_parent = dfs_mnt_create(fullpath); /* mnt->ref_count should be 1. */
if (mnt_parent)
{
DLOG(msg, "mnt", "dfs", DLOG_MSG_RET, "return mnt, ref_count=1");
mnt_parent->fs_ops = type->fs_ops;
mnt_parent->dev_id = dev_id;
if (mnt_parent->fs_ops->mount)
{
DLOG(msg, "dfs", type->fs_ops->name, DLOG_MSG, "fs_ops->mount(mnt_parent, rwflag, data)");
ret = mnt_parent->fs_ops->mount(mnt_parent, rwflag, data);
if (ret == RT_EOK)
{
DLOG(msg, type->fs_ops->name, "dfs", DLOG_MSG_RET, "mount OK, ret root_dentry");
/* Mark as mounted and insert into mount table */
mnt_child = mnt_parent;
mnt_child->flags |= MNT_IS_MOUNTED;
DLOG(note_right, "mnt", "mount sucessfully");
DLOG(msg, "dfs", "mnt", DLOG_MSG, "dfs_mnt_insert(, mnt_child)");
dfs_mnt_insert(RT_NULL, mnt_child);
/* unref it, because the ref_count = 1 when create */
DLOG(msg, "dfs", "mnt", DLOG_MSG, "dfs_mnt_unref(mnt_parent)");
dfs_mnt_unref(mnt_parent);
/*
* About root mnt:
* There are two ref_count:
* 1. the gobal root reference.
* 1. the mnt->parent reference.
*/
}
else
{
LOG_W("mount %s failed with file system type: %s", fullpath, type->fs_ops->name);
DLOG(msg, "dfs", "mnt", DLOG_MSG, "dfs_mnt_destroy(mnt_parent)");
dfs_mnt_destroy(mnt_parent);
mnt_parent = RT_NULL;
rt_set_errno(EPERM);
ret = -1;
}
}
else
{
LOG_W("no mount method on file system type: %s", type->fs_ops->name);
DLOG(msg, "dfs", "mnt", DLOG_MSG, "dfs_mnt_destroy(mnt_parent), no mount method");
dfs_mnt_destroy(mnt_parent);
mnt_parent = RT_NULL;
rt_set_errno(EIO);
ret = -1;
}
}
else
{
LOG_E("create a mnt point failed.");
rt_set_errno(ENOMEM);
ret = -1;
}
}
else if (mnt_parent && (strcmp(mnt_parent->fullpath, fullpath) != 0)) /* Handle regular filesystem mounting */
{
DLOG(msg, "dfs", "dentry", DLOG_MSG, "mntpoint_dentry = dfs_dentry_lookup(mnt_parent, %s, 0)", fullpath);
mntpoint_dentry = dfs_dentry_lookup(mnt_parent, fullpath, 0); /* Find mount point directory entry */
if (mntpoint_dentry)
{
DLOG(msg, "dentry", "dfs", DLOG_MSG_RET, "dentry exist");
DLOG(msg, "dfs", "mnt", DLOG_MSG, "mnt_child = dfs_mnt_create(path)");
mnt_child = dfs_mnt_create(fullpath); /* Create child mount point */
if (mnt_child)
{
LOG_D("create mnt point %p", mnt_child);
mnt_child->fs_ops = type->fs_ops;
mnt_child->dev_id = dev_id;
if (mnt_child->fs_ops->mount)
{
DLOG(msg, "dfs", type->fs_ops->name, DLOG_MSG, "root_dentry = fs_ops->mount(mnt_child, rwflag, data)");
ret = mnt_child->fs_ops->mount(mnt_child, rwflag, data);
if (ret == RT_EOK)
{
mnt_child->flags |= MNT_IS_MOUNTED;
LOG_D("mount %s sucessfully", fullpath);
DLOG(msg, mnt_child->fs_ops->name, "dfs", DLOG_MSG_RET, "mount OK");
DLOG(msg, "dfs", "mnt", DLOG_MSG, "dfs_mnt_insert(mnt_parent, mnt_child)");
dfs_mnt_insert(mnt_parent, mnt_child);
/* unref it, because the ref_count = 1 when create */
DLOG(msg, "dfs", "mnt", DLOG_MSG, "dfs_mnt_unref(mnt_child)");
dfs_mnt_unref(mnt_child);
}
else
{
LOG_W("mount %s failed with file system type: %s", fullpath, type->fs_ops->name);
DLOG(msg, mnt_child->fs_ops->name, "dfs", DLOG_MSG_RET, "mount failed");
dfs_mnt_destroy(mnt_child);
rt_set_errno(EPERM);
ret = -1;
}
}
else
{
LOG_W("no mount method on file system type: %s", type->fs_ops->name);
dfs_mnt_destroy(mnt_child);
rt_set_errno(EIO);
ret = -1;
}
}
else
{
LOG_E("create a mnt point failed.");
rt_set_errno(ENOMEM);
ret = -1;
}
dfs_dentry_unref(mntpoint_dentry);
}
else
{
LOG_W("no mount point (%s) in file system: %s", fullpath, mnt_parent->fullpath);
rt_set_errno(ENOTDIR);
ret = -1;
}
}
else
{
LOG_E("mount point (%s) already mounted!", fullpath);
rt_set_errno(EEXIST);
ret = -1;
}
}
else
{
LOG_E("No device found for this file system.");
rt_set_errno(ENODEV);
ret = -1;
}
rt_free(fullpath);
}
return ret;
}
/**
* @brief Unmount a filesystem from the specified path
*
* This function unmounts a filesystem from the given path. It performs the following operations:
* 1. Normalizes the target path
* 2. Looks up the mount point
* 3. Checks if the filesystem can be safely unmounted
* 4. Performs cleanup operations if unmounting is successful
*
* @param[in] specialfile The path of the filesystem to unmount
* @param[in] flags Unmount flags (MNT_FORCE for forced unmount)
*
* @return int RT_EOK on success, negative error code on failure:
* - EBUSY: Filesystem is busy (in use or has child mounts)
* - EINVAL: Path is not a mount point
* - ENOTDIR: Invalid path format
*
* @note Forced unmount (MNT_FORCE) can unmount even if reference count > 1
* @note Automatically handles page cache cleanup if RT_USING_PAGECACHE is enabled
* @note The function will fail if:
* - The mount point is locked (MNT_IS_LOCKED)
* - There are child mounts present
* - Reference count > 1 and MNT_FORCE not specified
*/
int dfs_umount(const char *specialfile, int flags)
{
int ret = -1;
char *fullpath = RT_NULL;
struct dfs_mnt *mnt = RT_NULL;
fullpath = dfs_normalize_path(NULL, specialfile);
if (fullpath)
{
DLOG(msg, "dfs", "mnt", DLOG_MSG, "mnt = dfs_mnt_lookup(%s)", fullpath);
mnt = dfs_mnt_lookup(fullpath);
if (mnt)
{
if (strcmp(mnt->fullpath, fullpath) == 0)
{
/* is the mount point */
rt_base_t ref_count = rt_atomic_load(&(mnt->ref_count));
if (!(mnt->flags & MNT_IS_LOCKED) && rt_list_isempty(&mnt->child) && (ref_count == 1 || (flags & MNT_FORCE)))
{
#ifdef RT_USING_PAGECACHE
dfs_pcache_unmount(mnt);
#endif
/* destroy this mount point */
DLOG(msg, "dfs", "mnt", DLOG_MSG, "dfs_mnt_destroy(mnt)");
ret = dfs_mnt_destroy(mnt);
}
else
{
LOG_I("the file system is busy!");
ret = -EBUSY;
}
}
else
{
LOG_I("the path:%s is not a mountpoint!", fullpath);
ret = -EINVAL;
}
}
else
{
LOG_I("no filesystem found.");
}
rt_free(fullpath);
}
else
{
rt_set_errno(-ENOTDIR);
}
return ret;
}
/* for compatibility */
int dfs_unmount(const char *specialfile)
{
return dfs_umount(specialfile, 0);
}
/**
* @brief Check if a mount point is mounted
*
* This function checks if the given mount point is mounted. It returns 0 if the mount point is mounted,
* and -1 otherwise.
*
* @param[in] mnt The mount point to check
*
* @return int 0 if mounted, -1 otherwise
*/
int dfs_is_mounted(struct dfs_mnt *mnt)
{
int ret = 0;
if (mnt && !(mnt->flags & MNT_IS_MOUNTED))
{
ret = -1;
}
return ret;
}
/**
* @brief Create a filesystem on the specified device
*
* This function creates a filesystem of the specified type on the given device.
* It performs the following operations:
* 1. Looks up the filesystem type
* 2. Validates device requirements
* 3. Calls the filesystem-specific mkfs operation
* 4. Handles page cache cleanup if successful (when RT_USING_PAGECACHE is enabled)
*
* @param[in] fs_name Name of the filesystem type to create (e.g., "elm", "romfs")
* @param[in] device_name Name of the device to create filesystem on (optional)
*
* @return int RT_EOK on success, negative error code on failure:
* - RT_ERROR: General error
* - ENODEV: Filesystem type not found or device not available
*
* @note For filesystems that don't require a device (FS_NEED_DEVICE not set),
* the device_name parameter can be NULL
* @note Automatically unmounts any existing filesystem on the device
* when RT_USING_PAGECACHE is enabled
* @note The function will fail if:
* - The filesystem type is not found
* - Device is required but not found
* - The filesystem doesn't implement mkfs operation
*/
int dfs_mkfs(const char *fs_name, const char *device_name)
{
rt_device_t dev_id = NULL;
struct dfs_filesystem_type *type;
int ret = -RT_ERROR;
type = *_find_filesystem(fs_name);
if (!type)
{
rt_kprintf("no file system: %s found!\n", fs_name);
return ret;
}
else
{
if (type->fs_ops->flags & FS_NEED_DEVICE)
{
/* check device name, and it should not be NULL */
if (device_name != NULL)
dev_id = rt_device_find(device_name);
if (dev_id == NULL)
{
rt_set_errno(-ENODEV);
rt_kprintf("Device (%s) was not found", device_name);
return ret;
}
}
else
{
dev_id = RT_NULL;
}
}
if (type->fs_ops->mkfs)
{
ret = type->fs_ops->mkfs(dev_id, type->fs_ops->name);
#ifdef RT_USING_PAGECACHE
if (ret == RT_EOK)
{
struct dfs_mnt *mnt = RT_NULL;
mnt = dfs_mnt_dev_lookup(dev_id);
if (mnt)
{
dfs_pcache_unmount(mnt);
}
}
#endif
}
return ret;
}
/**
* @brief Get filesystem statistics for the specified path
*
* This function retrieves filesystem statistics (like total/available space)
* for the filesystem containing the given path. It performs the following operations:
* 1. Normalizes the input path
* 2. Looks up the mount point for the path
* 3. Calls the filesystem-specific statfs operation if available
*
* @param[in] path The path to query filesystem statistics for
* @param[out] buffer Pointer to statfs structure to store the results
*
* @return int RT_EOK on success, negative error code on failure:
* - RT_ERROR: General error (invalid path or filesystem not found)
*
* @note The function will fail if:
* - The path cannot be normalized
* - No mount point is found for the path
* - The filesystem doesn't implement statfs operation
* - The filesystem is not currently mounted
* @note The buffer parameter must point to valid memory allocated by the caller
*/
int dfs_statfs(const char *path, struct statfs *buffer)
{
struct dfs_mnt *mnt;
char *fullpath;
int ret = -RT_ERROR;
fullpath = dfs_normalize_path(NULL, path);
if (!fullpath)
{
return ret;
}
DLOG(msg, "dfs_file", "mnt", DLOG_MSG, "dfs_mnt_lookup(%s)", fullpath);
mnt = dfs_mnt_lookup(fullpath);
if (mnt)
{
if (mnt->fs_ops->statfs)
{
if (dfs_is_mounted(mnt) == 0)
{
ret = mnt->fs_ops->statfs(mnt, buffer);
}
}
}
return ret;
}
/**
* this function will return the mounted path for specified device.
*
* @param[in] device the device object which is mounted.
*
* @return the mounted path or NULL if none device mounted.
*/
const char *dfs_filesystem_get_mounted_path(struct rt_device *device)
{
const char *path = NULL;
return path;
}
/**
* this function will fetch the partition table on specified buffer.
*
* @param[out] part the returned partition structure.
* @param[in] buf the buffer contains partition table.
* @param[in] pindex the index of partition table to fetch.
*
* @return RT_EOK on successful or -RT_ERROR on failed.
*/
int dfs_filesystem_get_partition(struct dfs_partition *part,
uint8_t *buf,
uint32_t pindex)
{
#define DPT_ADDRESS 0x1be /* device partition offset in Boot Sector */
#define DPT_ITEM_SIZE 16 /* partition item size */
uint8_t *dpt;
uint8_t type;
RT_ASSERT(part != NULL);
RT_ASSERT(buf != NULL);
dpt = buf + DPT_ADDRESS + pindex * DPT_ITEM_SIZE;
/* check if it is a valid partition table */
if ((*dpt != 0x80) && (*dpt != 0x00))
return -EIO;
/* get partition type */
type = *(dpt + 4);
if (type == 0)
return -EIO;
/* set partition information
* size is the number of 512-Byte */
part->type = type;
part->offset = *(dpt + 8) | *(dpt + 9) << 8 | *(dpt + 10) << 16 | *(dpt + 11) << 24;
part->size = *(dpt + 12) | *(dpt + 13) << 8 | *(dpt + 14) << 16 | *(dpt + 15) << 24;
rt_kprintf("found part[%d], begin: %ld, size: ",
pindex, part->offset * 512);
if ((part->size >> 11) == 0)
rt_kprintf("%ld%s", part->size >> 1, "KB\n"); /* KB */
else
{
unsigned int part_size;
part_size = part->size >> 11; /* MB */
if ((part_size >> 10) == 0)
rt_kprintf("%d.%ld%s", part_size, (part->size >> 1) & 0x3FF, "MB\n");
else
rt_kprintf("%d.%d%s", part_size >> 10, part_size & 0x3FF, "GB\n");
}
return RT_EOK;
}
/* @} */
@@ -0,0 +1,686 @@
/*
* Copyright (c) 2006-2025 RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2023-05-05 Bernard Implement mnt in dfs v2.0
*/
#include <rtthread.h>
#include "dfs_private.h"
#include <dfs.h>
#include <dfs_dentry.h>
#include <dfs_mnt.h>
#include <dfs_pcache.h>
#define DBG_TAG "DFS.mnt"
#define DBG_LVL DBG_WARNING
#include <rtdbg.h>
static struct dfs_mnt *_root_mnt = RT_NULL;
RT_OBJECT_HOOKLIST_DEFINE(dfs_mnt_umnt);
/*
* mnt tree structure
*
* mnt_root <----------------------------------------+
* | (child) +----------+ |
* v (sibling) v | |
* mnt_child0 -> mnt_child1 | |
* | (child) | |
* v / (parent) | (root)
* mnt_child10 ---/
*
*/
/**
* @brief Create a new dfs_mnt structure instance.
*
* This function allocates memory to create a new dfs_mnt structure instance and initializes it.
* If the memory allocation is successful, it copies the input path string into the instance and initializes related lists and flags.
*
* @param[in] path The path string to be mounted. This path information will be copied to the newly created dfs_mnt instance.
*
* @return If the memory allocation is successful, returns a pointer to the newly created dfs_mnt structure;
* if the memory allocation fails, returns RT_NULL.
*/
struct dfs_mnt *dfs_mnt_create(const char *path)
{
struct dfs_mnt *mnt = rt_calloc(1, sizeof(struct dfs_mnt));
if (mnt)
{
LOG_I("create mnt at %s", path);
mnt->fullpath = rt_strdup(path);
rt_list_init(&mnt->sibling);
rt_list_init(&mnt->child);
mnt->flags |= MNT_IS_ALLOCED;
rt_atomic_store(&(mnt->ref_count), 1);
}
else
{
rt_set_errno(-ENOMEM);
}
return mnt;
}
/**
* @brief Insert a child mount point into the mount tree.
*
* This function inserts a child mount point into the specified parent mount point's child list.
* If the parent mount point is not provided, it will try to find the appropriate mount point based on the child's path.
* If the child mount point is the root, it will update the global root mount point accordingly.
*
* @param[in,out] mnt Pointer to the parent dfs_mnt structure. If NULL, it will be updated to the appropriate mount point.
* @param[in] child Pointer to the child dfs_mnt structure to be inserted.
*
* @return Always returns 0 to indicate success.
*/
int dfs_mnt_insert(struct dfs_mnt* mnt, struct dfs_mnt* child)
{
if (child)
{
if (mnt == RT_NULL)
{
/* insert into root */
mnt = dfs_mnt_lookup(child->fullpath);
if (mnt == RT_NULL || (strcmp(child->fullpath, "/") == 0))
{
/* it's root mnt */
mnt = child;
mnt->flags |= MNT_IS_LOCKED;
/* ref to gobal root */
if (_root_mnt)
{
child = _root_mnt;
rt_atomic_sub(&(_root_mnt->parent->ref_count), 1);
rt_atomic_sub(&(_root_mnt->ref_count), 1);
_root_mnt->flags &= ~MNT_IS_LOCKED;
_root_mnt = dfs_mnt_ref(mnt);
mnt->parent = dfs_mnt_ref(mnt);
mnt->flags |= MNT_IS_ADDLIST;
mkdir("/dev", 0777);
}
else
{
_root_mnt = dfs_mnt_ref(mnt);
}
}
}
if (mnt)
{
child->flags |= MNT_IS_ADDLIST;
if (child != mnt)
{
/* not the root, insert into the child list */
rt_list_insert_before(&mnt->child, &child->sibling);
/* child ref self */
dfs_mnt_ref(child);
}
/* parent ref parent */
child->parent = dfs_mnt_ref(mnt);
}
}
return 0;
}
/**
* @brief Remove a mount point from the mount tree.
*
* This function attempts to remove a specified mount point from the mount tree.
* It can only remove a mount point if it has no child mount points. If the mount point
* has children, it logs a warning message instead of performing the removal.
*
* @param[in] mnt Pointer to the dfs_mnt structure representing the mount point to be removed.
*
* @return Returns RT_EOK if the mount point is successfully removed.
* Returns -RT_ERROR if the mount point has child mount points and cannot be removed.
*/
int dfs_mnt_remove(struct dfs_mnt* mnt)
{
int ret = -RT_ERROR;
if (rt_list_isempty(&mnt->child))
{
rt_list_remove(&mnt->sibling);
if (mnt->parent)
{
/* parent unref parent */
rt_atomic_sub(&(mnt->parent->ref_count), 1);
}
ret = RT_EOK;
}
else
{
LOG_W("remove a mnt point:%s with child.", mnt->fullpath);
}
return ret;
}
/**
* @brief Recursively search for a mount point associated with a specific device ID in the mount tree.
*
* This function traverses the mount tree starting from the given mount point `mnt` to find
* a mount point that is associated with the specified device ID `dev_id`. It uses a depth-first
* search algorithm to iterate through the child mount points.
*
* @param[in] mnt Pointer to the root dfs_mnt structure from which the search will start.
* @param[in] dev_id Pointer to the device ID to search for.
*
* @return If a mount point associated with the given device ID is found, returns a pointer to the corresponding dfs_mnt structure.
* Otherwise, returns RT_NULL.
*/
static struct dfs_mnt *_dfs_mnt_dev_lookup(struct dfs_mnt *mnt, rt_device_t dev_id)
{
struct dfs_mnt *ret = RT_NULL, *iter = RT_NULL;
rt_list_for_each_entry(iter, &mnt->child, sibling)
{
if (iter->dev_id == dev_id)
{
ret = iter;
break;
}
else
{
ret = _dfs_mnt_dev_lookup(iter, dev_id);
if (ret)
{
break;
}
}
}
return ret;
}
/**
* @brief Search for a mount point associated with a specific device ID in the mount tree.
*
* This function initiates a search for a mount point that is associated with the specified
* device ID `dev_id` starting from the root mount point. It first checks the root mount point
* directly, and if not found, it recursively searches the entire mount tree using the
* internal helper function `_dfs_mnt_dev_lookup`.
*
* @param[in] dev_id Pointer to the device ID to search for.
*
* @return If a mount point associated with the given device ID is found, returns a pointer to the corresponding dfs_mnt structure.
* Otherwise, returns RT_NULL.
*/
struct dfs_mnt *dfs_mnt_dev_lookup(rt_device_t dev_id)
{
struct dfs_mnt *mnt = _root_mnt;
struct dfs_mnt *ret = RT_NULL;
if (mnt)
{
dfs_lock();
if (mnt->dev_id == dev_id)
{
dfs_unlock();
return mnt;
}
ret = _dfs_mnt_dev_lookup(mnt, dev_id);
dfs_unlock();
}
return ret;
}
/**
* @brief Look up the mount point associated with a given full path.
*
* This function searches the mount tree starting from the root mount point to find
* the most specific mount point that matches the given full path. It traverses down
* the mount tree to identify the deepest mount point that is a prefix of the given path.
*
* @param[in] fullpath The full path string for which to find the associated mount point.
*
* @return If a matching mount point is found, returns a pointer to the corresponding dfs_mnt structure.
* Otherwise, returns RT_NULL.
*/
struct dfs_mnt *dfs_mnt_lookup(const char *fullpath)
{
struct dfs_mnt *mnt = _root_mnt;
struct dfs_mnt *iter = RT_NULL;
if (mnt)
{
int mnt_len = rt_strlen(mnt->fullpath);
dfs_lock();
if ((strncmp(mnt->fullpath, fullpath, mnt_len) == 0) &&
(mnt_len == 1 || (fullpath[mnt_len] == '\0') || (fullpath[mnt_len] == '/')))
{
while (!rt_list_isempty(&mnt->child))
{
rt_list_for_each_entry(iter, &mnt->child, sibling)
{
mnt_len = rt_strlen(iter->fullpath);
if ((strncmp(iter->fullpath, fullpath, mnt_len) == 0) &&
((fullpath[mnt_len] == '\0') || (fullpath[mnt_len] == '/')))
{
mnt = iter;
break;
}
}
if (mnt != iter) break;
}
}
else
{
mnt = RT_NULL;
}
dfs_unlock();
if (mnt)
{
LOG_D("mnt_lookup: %s path @ mount point %p", fullpath, mnt);
DLOG(note, "mnt", "found mnt(%s)", mnt->fs_ops->name);
}
}
return mnt;
}
/**
* @brief Increase the reference count of a dfs_mnt structure instance.
*
* This function increments the reference count of the specified dfs_mnt structure.
* The reference count is used to track how many parts of the system are currently
* using this mount point.
*
* @param[in,out] mnt Pointer to the dfs_mnt structure whose reference count is to be increased.
* If the pointer is valid, the reference count within the structure will be modified.
* @return Returns the same pointer to the dfs_mnt structure that was passed in.
* If the input pointer is NULL, it simply returns NULL.
*/
struct dfs_mnt* dfs_mnt_ref(struct dfs_mnt* mnt)
{
if (mnt)
{
rt_atomic_add(&(mnt->ref_count), 1);
DLOG(note, "mnt", "mnt(%s),ref_count=%d", mnt->fs_ops->name, rt_atomic_load(&(mnt->ref_count)));
}
return mnt;
}
/**
* @brief Decrease the reference count of a dfs_mnt structure instance and free it if necessary.
*
* This function decrements the reference count of the specified dfs_mnt structure.
* If the reference count reaches zero after the decrement, it will perform the unmount operation,
* trigger the unmount hook, free the allocated path memory, and finally free the dfs_mnt structure itself.
*
* @param[in,out] mnt Pointer to the dfs_mnt structure whose reference count is to be decreased.
* If the reference count reaches zero, the structure will be freed.
*
* @return returns RT_EOK to indicate success.
*/
int dfs_mnt_unref(struct dfs_mnt *mnt)
{
rt_err_t ret = RT_EOK;
rt_base_t ref_count;
if (mnt)
{
ref_count = rt_atomic_sub(&(mnt->ref_count), 1) - 1;
if (ref_count == 0)
{
dfs_lock();
if (mnt->flags & MNT_IS_UMOUNT)
{
mnt->fs_ops->umount(mnt);
RT_OBJECT_HOOKLIST_CALL(dfs_mnt_umnt, (mnt));
}
/* free full path */
rt_free(mnt->fullpath);
mnt->fullpath = RT_NULL;
/* destroy self and the ref_count should be 0 */
DLOG(msg, "mnt", "mnt", DLOG_MSG, "free mnt(%s)", mnt->fs_ops->name);
rt_free(mnt);
dfs_unlock();
}
else
{
DLOG(note, "mnt", "mnt(%s),ref_count=%d", mnt->fs_ops->name, rt_atomic_load(&(mnt->ref_count)));
}
}
return ret;
}
/**
* @brief Set specific flags for a dfs_mnt structure instance.
*
* This function sets specific flags for the given dfs_mnt structure.
* If the MS_RDONLY flag is included in the input flags, it sets the MNT_RDONLY flag
* for the mount point and cleans the page cache if the page cache feature is enabled.
*
* @param[in,out] mnt Pointer to the dfs_mnt structure for which flags are to be set.
* The structure's `flags` member will be modified if necessary.
* @param[in] flags The flags to be set for the mount point. This includes the MS_RDONLY flag.
*
* @return returns 0 to indicate success.
*/
int dfs_mnt_setflags(struct dfs_mnt *mnt, int flags)
{
int error = 0;
if (flags & MS_RDONLY)
{
mnt->flags |= MNT_RDONLY;
#ifdef RT_USING_PAGECACHE
dfs_pcache_clean(mnt);
#endif
}
return error;
}
/**
* @brief Destroy a dfs_mnt structure instance and unmount it if necessary.
*
* This function attempts to destroy the specified dfs_mnt structure instance.
* If the mount point is currently mounted, it marks the mount point as unmounted,
* sets the unmount flag, and removes it from the mount list if it was added.
* Finally, it decreases the reference count of the mount point and frees the
* structure if the reference count reaches zero.
*
* @param[in,out] mnt Pointer to the dfs_mnt structure to be destroyed.
*
* @return Returns RT_EOK to indicate success.
*/
int dfs_mnt_destroy(struct dfs_mnt* mnt)
{
rt_err_t ret = RT_EOK;
if (mnt)
{
if (mnt->flags & MNT_IS_MOUNTED)
{
mnt->flags &= ~MNT_IS_MOUNTED;
mnt->flags |= MNT_IS_UMOUNT;
/* remote it from mnt list */
if (mnt->flags & MNT_IS_ADDLIST)
{
dfs_mnt_remove(mnt);
}
}
dfs_mnt_unref(mnt);
}
return ret;
}
/**
* @brief Recursively traverse the mount point tree and apply a callback function.
*
* This function performs a depth-first traversal of the mount point tree starting from the given mount point.
* It applies the specified callback function to each mount point in the tree. If the callback function returns
* a non-NULL pointer, the traversal stops and the result is returned immediately.
*
* @param[in] mnt Pointer to the root dfs_mnt structure from which the traversal will start.
* If NULL, the function will return RT_NULL without performing any traversal.
* @param[in] func Pointer to the callback function to be applied to each mount point.
* The callback function takes a pointer to a dfs_mnt structure and a generic parameter,
* and returns a pointer to a dfs_mnt structure or RT_NULL.
* @param[in] parameter Generic pointer to a parameter that will be passed to the callback function.
*
* @return If the callback function returns a non-NULL pointer during the traversal, returns that pointer.
* Otherwise, returns RT_NULL.
*/
static struct dfs_mnt* _dfs_mnt_foreach(struct dfs_mnt *mnt, struct dfs_mnt* (*func)(struct dfs_mnt *mnt, void *parameter), void *parameter)
{
struct dfs_mnt *iter, *ret = NULL;
if (mnt)
{
ret = func(mnt, parameter);
if (ret == RT_NULL)
{
if (!rt_list_isempty(&mnt->child))
{
/* for each in mount point list */
rt_list_for_each_entry(iter, &mnt->child, sibling)
{
ret = _dfs_mnt_foreach(iter, func, parameter);
if (ret != RT_NULL)
{
break;
}
}
}
}
}
else
{
ret = RT_NULL;
}
return ret;
}
/**
* @brief Compare a mount point's device ID with a given device object.
*
* This function checks if the device ID associated with a specified mount point
* matches the given device object. If a match is found, it returns a pointer to
* the corresponding dfs_mnt structure; otherwise, it returns RT_NULL.
*
* @param[in] mnt Pointer to the dfs_mnt structure representing the mount point to be checked.
* @param[in] device Pointer to the device object to compare against the mount point's device ID.
*
* @return If the device ID of the mount point matches the given device object, returns a pointer to the dfs_mnt structure.
* Otherwise, returns RT_NULL.
*/
static struct dfs_mnt* _mnt_cmp_devid(struct dfs_mnt *mnt, void *device)
{
struct dfs_mnt *ret = RT_NULL;
struct rt_device *dev = (struct rt_device*)device;
if (dev && mnt)
{
if (mnt->dev_id == dev)
{
ret = mnt;
}
}
return ret;
}
/**
* this function will return the mounted path for specified device.
*
* @param[in] device the device object which is mounted.
*
* @return the mounted path or NULL if none device mounted.
*/
const char *dfs_mnt_get_mounted_path(struct rt_device *device)
{
const char* path = RT_NULL;
if (_root_mnt)
{
struct dfs_mnt* mnt;
dfs_lock();
mnt = _dfs_mnt_foreach(_root_mnt, _mnt_cmp_devid, device);
dfs_unlock();
if (mnt) path = mnt->fullpath;
}
return path;
}
/**
* @brief Print information about a mount point to the console.
*
* This function is designed to be used as a callback in the mount point tree traversal.
* It prints the file system name, device name (or `(NULL)` if no device is associated),
* mount path, and reference count of the specified mount point to the console using `rt_kprintf`.
*
* @param[in] mnt Pointer to the dfs_mnt structure representing the mount point to be printed.
* If NULL, the function does nothing.
* @param[in] parameter A generic pointer to a parameter. This parameter is not used in this function.
*
* @return Always returns RT_NULL as it is a callback function mainly used for side - effects (printing).
*/
static struct dfs_mnt* _mnt_dump(struct dfs_mnt *mnt, void *parameter)
{
if (mnt)
{
if (mnt->dev_id)
{
rt_kprintf("%-10s %-6s %-10s %d\n",
mnt->fs_ops->name, mnt->dev_id->parent.name, mnt->fullpath, rt_atomic_load(&(mnt->ref_count)));
}
else
{
rt_kprintf("%-10s (NULL) %-10s %d\n",
mnt->fs_ops->name, mnt->fullpath, rt_atomic_load(&(mnt->ref_count)));
}
}
return RT_NULL;
}
/**
* @brief Compare a mount point's full path with a given path.
*
* This function is designed to be used as a callback in the mount point tree traversal.
* It compares the full path of the specified mount point with the given path.
* If the mount point's full path starts with the given path, it returns a pointer to the dfs_mnt structure;
* otherwise, it returns RT_NULL.
*
* @param[in] mnt Pointer to the dfs_mnt structure representing the mount point to be checked.
* If NULL, the function will not perform the comparison and return RT_NULL.
* @param[in] parameter A generic pointer to a parameter, which should be cast to a `const char*`
* representing the path to compare against the mount point's full path.
*
* @return If the mount point's full path starts with the given path, returns a pointer to the dfs_mnt structure.
* Otherwise, returns RT_NULL.
*/
static struct dfs_mnt* _mnt_cmp_path(struct dfs_mnt* mnt, void *parameter)
{
const char* fullpath = (const char*)parameter;
struct dfs_mnt *ret = RT_NULL;
if (strncmp(mnt->fullpath, fullpath, rt_strlen(fullpath)) == 0)
{
ret = mnt;
}
return ret;
}
/**
* @brief Check if a mount point has a child mount point matching the given path.
*
* This function checks whether the specified mount point has a child mount point
* whose full path starts with the given path. It uses a depth-first traversal of
* the mount point tree starting from the provided mount point and applies the
* `_mnt_cmp_path` callback function to each mount point.
*
* @param[in] mnt Pointer to the root dfs_mnt structure from which the search will start.
* If NULL, the function will return RT_FALSE without performing any search.
* @param[in] fullpath The full path string to compare against the child mount points' paths.
* If NULL, the function will return RT_FALSE without performing any search.
*
* @return Returns RT_TRUE if a child mount point with a matching path is found.
* Returns RT_FALSE if no matching child mount point is found, or if either input parameter is NULL.
*/
rt_bool_t dfs_mnt_has_child_mnt(struct dfs_mnt *mnt, const char* fullpath)
{
int ret = RT_FALSE;
if (mnt && fullpath)
{
struct dfs_mnt *m = RT_NULL;
dfs_lock();
m = _dfs_mnt_foreach(mnt, _mnt_cmp_path, (void*)fullpath);
dfs_unlock();
if (m)
{
ret = RT_TRUE;
}
}
return ret;
}
/**
* @brief List all mount points starting from a specified mount point.
*
* This function lists information about all mount points in the mount point tree,
* starting from the specified mount point. If the input mount point is NULL,
* it starts from the root mount point. It uses the `_dfs_mnt_foreach` function
* with the `_mnt_dump` callback to print mount point information.
*
* @param[in] mnt Pointer to the dfs_mnt structure from which to start listing mount points.
* If NULL, the function will start from the root mount point.
*
* @return Always returns 0 to indicate success.
*/
int dfs_mnt_list(struct dfs_mnt *mnt)
{
if (!mnt) mnt = _root_mnt;
/* lock file system */
dfs_lock();
_dfs_mnt_foreach(mnt, _mnt_dump, RT_NULL);
/* unlock file system */
dfs_unlock();
return 0;
}
/**
* @brief Traverse all mount points in the mount tree and apply a callback function.
*
* @param[in] func Pointer to the callback function to be applied to each mount point.
* The callback function takes a pointer to a `dfs_mnt` structure and a generic parameter,
* and returns a pointer to a `dfs_mnt` structure or `RT_NULL`.
* @param[in] parameter Generic pointer to a parameter that will be passed to the callback function.
*
* @return Always returns 0.
*/
int dfs_mnt_foreach(struct dfs_mnt* (*func)(struct dfs_mnt *mnt, void *parameter), void *parameter)
{
/* lock file system */
dfs_lock();
_dfs_mnt_foreach(_root_mnt, func, parameter);
/* unlock file system */
dfs_unlock();
return 0;
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,19 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#ifndef DFS_PRIVATE_H__
#define DFS_PRIVATE_H__
#include <dfs.h>
#define NO_WORKING_DIR "system does not support working directory\n"
extern char working_directory[];
#endif
@@ -0,0 +1,516 @@
/*
* Copyright (c) 2006-2025 RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
#include <dfs_seq_file.h>
#include <dfs_dentry.h>
#define DBG_TAG "DFS.seq"
#define DBG_LVL DBG_WARNING
#include <rtdbg.h>
#ifndef PAGE_SIZE
#define PAGE_SIZE 4096
#endif
/**
* @brief Handle buffer overflow condition in sequence file
*
* @param[in,out] seq Pointer to sequence file structure
*
* @details Sets the count to size to indicate buffer is full
*/
static void dfs_seq_overflow(struct dfs_seq_file *seq)
{
seq->count = seq->size;
}
/**
* @brief Allocate memory for sequence file operations
*
* @param[in] size Size of memory to allocate in bytes
*
* @return void* Pointer to allocated memory, or NULL if allocation fails
*/
static void *dfs_seq_alloc(unsigned long size)
{
return rt_calloc(1, size);
}
/**
* @brief Initialize and open a sequence file
*
* @param[in] file Pointer to the file structure to be initialized
* @param[in] ops Pointer to sequence operations structure containing callback functions
*
* @return int 0 on success, negative error code on failure:
* -EINVAL if ops is NULL
* -ENOMEM if memory allocation fails
*/
int dfs_seq_open(struct dfs_file *file, const struct dfs_seq_ops *ops)
{
struct dfs_seq_file *seq;
if (!ops)
{
LOG_E("dfs_seq_open: ops = null, pathname: %s\n", file->dentry->pathname);
return -EINVAL;
}
if (file->data)
{
LOG_W("dfs_seq_open: file->data != null\n");
}
seq = rt_calloc(1, sizeof(struct dfs_seq_file));
if (!seq)
return -ENOMEM;
file->data = seq;
rt_mutex_init(&seq->lock, "dfs_seq", RT_IPC_FLAG_PRIO);
seq->ops = ops;
seq->file = file;
return 0;
}
/**
* @brief Traverse sequence file data with specified offset
*
* This function traverses the sequence file data starting from the specified offset.
* It handles buffer overflow conditions by dynamically resizing the buffer when needed.
*
* @param[in,out] seq Pointer to sequence file structure
* @param[in] offset Position to start traversing from
*
* @return int 0 on success, negative error code on failure:
* -ENOMEM if memory allocation fails
* -EAGAIN if buffer needs to be resized
*
* @note Data output loop: start() -> show() -> next() -> show() -> ... -> next() -> stop()
*/
static int dfs_seq_traverse(struct dfs_seq_file *seq, off_t offset)
{
off_t pos = 0;
int error = 0;
void *p;
seq->index = 0;
seq->count = seq->from = 0;
if (!offset)
return 0;
if (!seq->buf)
{
seq->buf = dfs_seq_alloc(seq->size = PAGE_SIZE);
if (!seq->buf)
return -ENOMEM;
}
p = seq->ops->start(seq, &seq->index);
while (p)
{
error = seq->ops->show(seq, p);
if (error < 0)
break;
if (error)
{
error = 0;
seq->count = 0;
}
if (dfs_seq_is_full(seq))
goto Eoverflow;
p = seq->ops->next(seq, p, &seq->index);
if (pos + seq->count > offset)
{
seq->from = offset - pos;
seq->count -= seq->from;
break;
}
pos += seq->count;
seq->count = 0;
if (pos == offset)
break;
}
seq->ops->stop(seq, p);
return error;
Eoverflow:
seq->ops->stop(seq, p);
rt_free(seq->buf);
seq->count = 0;
seq->buf = dfs_seq_alloc(seq->size <<= 1);
return !seq->buf ? -ENOMEM : -EAGAIN;
}
/**
* @brief Read data from sequence file
*
* @param[in] file Pointer to the file structure
* @param[out] buf Buffer to store the read data
* @param[in] size Size of the buffer in bytes
* @param[in,out] pos Current file position (updated after read)
*
* @return ssize_t Number of bytes read on success, negative error code on failure:
* -EFAULT if buffer error occurs
* -ENOMEM if memory allocation fails
* 0 if size is 0
*
* @details This function implements the core sequence file reading logic with following steps:
* 1. Reset iterator if reading from start
* 2. Synchronize position if needed
* 3. Allocate buffer if not exists
* 4. Copy remaining data from previous read
* 5. Start iteration and fill buffer with new data
* 6. Handle buffer overflow by doubling size
* 7. Copy data to user buffer and update positions
*/
ssize_t dfs_seq_read(struct dfs_file *file, void *buf, size_t size, off_t *pos)
{
struct dfs_seq_file *seq = file->data;
size_t copied = 0;
size_t n;
void *p;
int err = 0;
if (!size)
return 0;
rt_mutex_take(&seq->lock, RT_WAITING_FOREVER);
/*
* if request is to read from zero offset, reset iterator to first
* record as it might have been already advanced by previous requests
*/
if (*pos == 0)
{
seq->index = 0;
seq->count = 0;
}
/* Don't assume ki_pos is where we left it */
if (*pos != seq->read_pos)
{
while ((err = dfs_seq_traverse(seq, *pos)) == -EAGAIN)
;
if (err)
{
/* With prejudice... */
seq->read_pos = 0;
seq->index = 0;
seq->count = 0;
goto Done;
}
else
{
seq->read_pos = *pos;
}
}
/* grab buffer if we didn't have one */
if (!seq->buf)
{
seq->buf = dfs_seq_alloc(seq->size = PAGE_SIZE);
if (!seq->buf)
goto Enomem;
}
/* something left in the buffer - copy it out first */
if (seq->count)
{
n = seq->count > size ? size : seq->count;
rt_memcpy((char *)buf + copied, seq->buf + seq->from, n);
size -= n;
seq->count -= n;
seq->from += n;
copied += n;
if (seq->count) /* hadn't managed to copy everything */
goto Done;
}
/* get a non-empty record in the buffer */
seq->from = 0;
p = seq->ops->start(seq, &seq->index);
while (p)
{
err = seq->ops->show(seq, p);
if (err < 0) /* hard error */
break;
if (err) /* ->show() says "skip it" */
seq->count = 0;
if (!seq->count)
{ /* empty record */
p = seq->ops->next(seq, p, &seq->index);
continue;
}
if (!dfs_seq_is_full(seq)) /* got it */
goto Fill;
/* need a bigger buffer */
seq->ops->stop(seq, p);
rt_free(seq->buf);
seq->count = 0;
seq->buf = dfs_seq_alloc(seq->size <<= 1);
if (!seq->buf)
goto Enomem;
p = seq->ops->start(seq, &seq->index);
}
/* EOF or an error */
seq->ops->stop(seq, p);
seq->count = 0;
goto Done;
Fill:
/* one non-empty record is in the buffer; if they want more, */
/* try to fit more in, but in any case we need to advance */
/* the iterator once for every record shown. */
while (1)
{
size_t offs = seq->count;
off_t pos = seq->index;
p = seq->ops->next(seq, p, &seq->index);
if (pos == seq->index)
{
LOG_W(".next function %p did not update position index\n", seq->ops->next);
seq->index++;
}
if (!p) /* no next record for us */
break;
if (seq->count >= size)
break;
err = seq->ops->show(seq, p);
if (err > 0)
{ /* ->show() says "skip it" */
seq->count = offs;
}
else if (err || dfs_seq_is_full(seq))
{
seq->count = offs;
break;
}
}
seq->ops->stop(seq, p);
n = seq->count > size ? size : seq->count;
rt_memcpy((char *)buf + copied, seq->buf, n);
size -= n;
copied += n;
seq->count -= n;
seq->from = n;
Done:
if (!copied)
{
copied = seq->count ? -EFAULT : err;
}
else
{
*pos += copied;
seq->read_pos += copied;
}
rt_mutex_release(&seq->lock);
return copied;
Enomem:
err = -ENOMEM;
goto Done;
}
/**
* @brief Reposition the file offset for sequence file
*
* @param[in] file Pointer to the file structure
* @param[in] offset Offset value according to whence
* @param[in] whence Reference position for offset:
* - SEEK_SET: from file beginning
* - SEEK_CUR: from current position
* @return off_t New file offset on success, negative error code on failure:
* -EINVAL for invalid parameters
*/
off_t dfs_seq_lseek(struct dfs_file *file, off_t offset, int whence)
{
struct dfs_seq_file *seq = file->data;
off_t retval = -EINVAL;
rt_mutex_take(&seq->lock, RT_WAITING_FOREVER);
switch (whence)
{
case SEEK_CUR:
offset += file->fpos;
case SEEK_SET:
if (offset < 0)
break;
retval = offset;
if (offset != seq->read_pos)
{
while ((retval = dfs_seq_traverse(seq, offset)) == -EAGAIN);
if (retval)
{
/* with extreme prejudice... */
retval = 0;
seq->read_pos = 0;
seq->index = 0;
seq->count = 0;
}
else
{
seq->read_pos = offset;
retval = offset;
}
}
}
rt_mutex_release(&seq->lock);
return retval;
}
/**
* @brief Release resources associated with a sequence file
*
* @param[in] file Pointer to the file structure to be released
*
* @return int Always returns 0 indicating success
*/
int dfs_seq_release(struct dfs_file *file)
{
struct dfs_seq_file *seq = file->data;
if (seq)
{
rt_mutex_detach(&seq->lock);
if (seq->buf)
{
rt_free(seq->buf);
}
rt_free(seq);
}
return 0;
}
/**
* @brief Format and write data to sequence file buffer using variable arguments
*
* @param[in,out] seq Pointer to sequence file structure
* @param[in] f Format string (printf-style)
* @param[in] args Variable arguments list
*
* @details This function:
* - Formats data using vsnprintf
* - Triggers overflow if buffer is full
*/
void dfs_seq_vprintf(struct dfs_seq_file *seq, const char *f, va_list args)
{
int len;
if (seq->count < seq->size)
{
len = vsnprintf(seq->buf + seq->count, seq->size - seq->count, f, args);
if (seq->count + len < seq->size)
{
seq->count += len;
return;
}
}
dfs_seq_overflow(seq);
}
/**
* @brief Format and print data to sequence file buffer (printf-style)
*
* @param[in,out] seq Pointer to sequence file structure
* @param[in] f Format string (printf-style)
* @param[in] ... Variable arguments matching format string
*/
void dfs_seq_printf(struct dfs_seq_file *seq, const char *f, ...)
{
va_list args;
va_start(args, f);
dfs_seq_vprintf(seq, f, args);
va_end(args);
}
/**
* @brief Write a single character to sequence file buffer
*
* @param[in,out] seq Pointer to sequence file structure
* @param[in] c Character to be written
*/
void dfs_seq_putc(struct dfs_seq_file *seq, char c)
{
if (seq->count < seq->size)
{
seq->buf[seq->count++] = c;
}
}
/**
* @brief Write a string to sequence file buffer
*
* @param[in,out] seq Pointer to sequence file structure
* @param[in] s Null-terminated string to be written
*/
void dfs_seq_puts(struct dfs_seq_file *seq, const char *s)
{
int len = strlen(s);
if (seq->count + len >= seq->size)
{
dfs_seq_overflow(seq);
return;
}
rt_memcpy(seq->buf + seq->count, s, len);
seq->count += len;
}
/**
* @brief Write arbitrary binary data to sequence file buffer
*
* @param[in,out] seq Pointer to sequence file structure
* @param[in] data Pointer to data to be written
* @param[in] len Length of data in bytes
*
* @return int 0 on success, -1 if buffer overflow occurs
*/
int dfs_seq_write(struct dfs_seq_file *seq, const void *data, size_t len)
{
if (seq->count + len < seq->size)
{
rt_memcpy(seq->buf + seq->count, data, len);
seq->count += len;
return 0;
}
dfs_seq_overflow(seq);
return -1;
}
/**
* @brief Pad the sequence file buffer with spaces and optionally append a character
*
* @param[in,out] seq Pointer to sequence file structure
* @param[in] c Optional character to append after padding (if not '\0')
*/
void dfs_seq_pad(struct dfs_seq_file *seq, char c)
{
int size = seq->pad_until - seq->count;
if (size > 0)
{
if (size + seq->count > seq->size)
{
dfs_seq_overflow(seq);
return;
}
rt_memset(seq->buf + seq->count, ' ', size);
seq->count += size;
}
if (c)
{
dfs_seq_putc(seq, c);
}
}
@@ -0,0 +1,180 @@
/*
* Copyright (c) 2006-2025 RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2023-05-05 Bernard Implement vnode in dfs v2.0
*/
#include <dfs_file.h>
#include <dfs_mnt.h>
#ifdef RT_USING_PAGECACHE
#include "dfs_pcache.h"
#endif
#define DBG_TAG "DFS.vnode"
#define DBG_LVL DBG_WARNING
#include <rtdbg.h>
/**
* @brief Initialize a virtual node (vnode) structure
*
* @param[in,out] vnode Pointer to the vnode to be initialized
* @param[in] type Type of the vnode
* @param[in] fops Pointer to file operations structure
*
* @return int Always returns 0 indicating success
*/
int dfs_vnode_init(struct dfs_vnode *vnode, int type, const struct dfs_file_ops *fops)
{
if (vnode)
{
rt_memset(vnode, 0, sizeof(struct dfs_vnode));
vnode->type = type;
rt_atomic_store(&(vnode->ref_count), 1);
vnode->mnt = RT_NULL;
vnode->fops = fops;
}
return 0;
}
/**
* @brief Create and initialize a new virtual node (vnode)
*
* @return struct dfs_vnode* Pointer to the newly created vnode, or NULL if creation failed
*/
struct dfs_vnode *dfs_vnode_create(void)
{
struct dfs_vnode *vnode = rt_calloc(1, sizeof(struct dfs_vnode));
if (!vnode)
{
LOG_E("create a vnode failed.");
return RT_NULL;
}
rt_atomic_store(&(vnode->ref_count), 1);
LOG_I("create a vnode: %p", vnode);
return vnode;
}
/**
* @brief Destroy a virtual node (vnode) and free its resources
*
* @param[in] vnode Pointer to the vnode to be destroyed
*
* @return int Always returns 0. Note that this does not guarantee success, as errors may occur internally.
*/
int dfs_vnode_destroy(struct dfs_vnode* vnode)
{
rt_err_t ret = RT_EOK;
if (vnode)
{
ret = dfs_file_lock();
if (ret == RT_EOK)
{
if (rt_atomic_load(&(vnode->ref_count)) == 1)
{
LOG_I("free a vnode: %p", vnode);
#ifdef RT_USING_PAGECACHE
if (vnode->aspace)
{
dfs_aspace_destroy(vnode->aspace);
}
#endif
if (vnode->mnt)
{
DLOG(msg, "vnode", vnode->mnt->fs_ops->name, DLOG_MSG, "fs_ops->free_vnode");
vnode->mnt->fs_ops->free_vnode(vnode);
}
else
{
DLOG(msg, "vnode", "vnode", DLOG_MSG, "destroy vnode(mnt=NULL)");
}
dfs_file_unlock();
rt_free(vnode);
}
else
{
dfs_file_unlock();
}
}
}
return 0;
}
/**
* @brief Increase reference count of a virtual node (vnode)
*
* @param[in,out] vnode Pointer to the vnode to be referenced
*
* @return struct dfs_vnode* The same vnode pointer that was passed in
*/
struct dfs_vnode *dfs_vnode_ref(struct dfs_vnode *vnode)
{
if (vnode)
{
rt_atomic_add(&(vnode->ref_count), 1);
DLOG(note, "vnode", "vnode ref_count=%d", rt_atomic_load(&(vnode->ref_count)));
}
return vnode;
}
/**
* @brief Decrease reference count of a virtual node (vnode) and potentially free it
*
* @param[in,out] vnode Pointer to the vnode to be unreferenced
*/
void dfs_vnode_unref(struct dfs_vnode *vnode)
{
rt_err_t ret = RT_EOK;
if (vnode)
{
ret = dfs_file_lock();
if (ret == RT_EOK)
{
rt_atomic_sub(&(vnode->ref_count), 1);
DLOG(note, "vnode", "vnode ref_count=%d", rt_atomic_load(&(vnode->ref_count)));
#ifdef RT_USING_PAGECACHE
if (vnode->aspace)
{
dfs_aspace_destroy(vnode->aspace);
}
#endif
if (rt_atomic_load(&(vnode->ref_count)) == 0)
{
LOG_I("free a vnode: %p", vnode);
DLOG(msg, "vnode", "vnode", DLOG_MSG, "free vnode, ref_count=0");
if (vnode->mnt)
{
DLOG(msg, "vnode", vnode->mnt->fs_ops->name, DLOG_MSG, "fs_ops->free_vnode");
vnode->mnt->fs_ops->free_vnode(vnode);
}
dfs_file_unlock();
rt_free(vnode);
}
else
{
dfs_file_unlock();
DLOG(note, "vnode", "vnode ref_count=%d", rt_atomic_load(&(vnode->ref_count)));
}
}
}
return;
}
+47
View File
@@ -0,0 +1,47 @@
menu "Device Drivers"
rsource "core/Kconfig"
rsource "ipc/Kconfig"
rsource "serial/Kconfig"
rsource "can/Kconfig"
rsource "cputime/Kconfig"
rsource "i2c/Kconfig"
rsource "phy/Kconfig"
rsource "misc/Kconfig"
rsource "mtd/Kconfig"
rsource "pm/Kconfig"
rsource "rtc/Kconfig"
rsource "sdio/Kconfig"
rsource "spi/Kconfig"
rsource "watchdog/Kconfig"
rsource "audio/Kconfig"
rsource "sensor/Kconfig"
rsource "touch/Kconfig"
rsource "graphic/Kconfig"
rsource "hwcrypto/Kconfig"
rsource "wlan/Kconfig"
rsource "led/Kconfig"
rsource "mailbox/Kconfig"
rsource "phye/Kconfig"
rsource "ata/Kconfig"
rsource "nvme/Kconfig"
rsource "block/Kconfig"
rsource "scsi/Kconfig"
rsource "regulator/Kconfig"
rsource "reset/Kconfig"
rsource "thermal/Kconfig"
rsource "virtio/Kconfig"
rsource "dma/Kconfig"
rsource "mfd/Kconfig"
rsource "ofw/Kconfig"
rsource "pci/Kconfig"
rsource "pic/Kconfig"
rsource "pin/Kconfig"
rsource "pinctrl/Kconfig"
rsource "ktime/Kconfig"
rsource "clk/Kconfig"
rsource "hwtimer/Kconfig"
rsource "usb/Kconfig"
endmenu
+14
View File
@@ -0,0 +1,14 @@
# for module compiling
import os
from building import *
cwd = GetCurrentDir()
objs = []
list = os.listdir(cwd)
for d in list:
path = os.path.join(cwd, d)
if os.path.isfile(os.path.join(path, 'SConscript')):
objs = objs + SConscript(os.path.join(d, 'SConscript'))
Return('objs')
+22
View File
@@ -0,0 +1,22 @@
menuconfig RT_USING_ATA
bool "Using Advanced Technology Attachment (ATA) device drivers"
depends on RT_USING_DM
depends on RT_USING_BLK
depends on RT_USING_DMA
default n
config RT_ATA_AHCI
bool "Advanced Host Controller Interface (AHCI)"
depends on RT_USING_ATA
depends on RT_USING_SCSI
default y
config RT_ATA_AHCI_PCI
bool "AHCI support on PCI bus"
depends on RT_ATA_AHCI
depends on RT_USING_PCI
default n
if RT_USING_ATA
osource "$(SOC_DM_ATA_DIR)/Kconfig"
endif
@@ -0,0 +1,21 @@
from building import *
group = []
if not GetDepend(['RT_USING_ATA']):
Return('group')
cwd = GetCurrentDir()
CPPPATH = [cwd + '/../include']
src = []
if GetDepend(['RT_ATA_AHCI']):
src += ['ahci.c']
if GetDepend(['RT_ATA_AHCI_PCI']):
src += ['ahci-pci.c']
group = DefineGroup('DeviceDrivers', src, depend = [''], CPPPATH = CPPPATH)
Return('group')
+206
View File
@@ -0,0 +1,206 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2023-02-25 GuEe-GUI the first version
*/
#include <rtthread.h>
#include <rtdevice.h>
#define AHCI_REG_BAR 5
struct pci_ahci_quirk
{
int bar_idx;
rt_bool_t bar_offset;
const struct rt_ahci_ops *ops;
};
struct pci_ahci_host
{
struct rt_ahci_host parent;
const struct pci_ahci_quirk *quirk;
rt_bool_t is_msi;
};
#define raw_to_pci_ahci_host(raw) rt_container_of(raw, struct pci_ahci_host, parent)
static rt_err_t pci_ahci_init(struct rt_ahci_host *host)
{
struct rt_pci_device *pdev;
pdev = rt_container_of(host->parent.dev, struct rt_pci_device, parent);
if (pdev->vendor == PCI_VENDOR_ID_JMICRON)
{
rt_pci_write_config_u8(pdev, 0x41, 0xa1);
}
return RT_EOK;
}
static const struct rt_ahci_ops pci_ahci_ops =
{
.host_init = pci_ahci_init,
};
static rt_err_t pci_ahci_intel_init(struct rt_ahci_host *host)
{
rt_uint16_t val;
struct rt_pci_device *pdev;
pdev = rt_container_of(host->parent.dev, struct rt_pci_device, parent);
rt_pci_read_config_u16(pdev, 0x92, &val);
rt_pci_write_config_u16(pdev, 0x92, val & ~0xf);
rt_thread_mdelay(10);
rt_pci_write_config_u16(pdev, 0x92, val | 0xf);
return RT_EOK;
}
static const struct rt_ahci_ops pci_ahci_intel_ops =
{
.host_init = pci_ahci_intel_init,
};
static rt_err_t pci_ahci_probe(struct rt_pci_device *pdev)
{
rt_err_t err;
int bar_idx;
struct rt_ahci_host *ahci;
struct pci_ahci_host *pci_ahci = rt_calloc(1, sizeof(*pci_ahci));
const struct pci_ahci_quirk *quirk = pdev->id->data;
if (!pci_ahci)
{
return -RT_ENOMEM;
}
pci_ahci->quirk = quirk;
ahci = &pci_ahci->parent;
ahci->parent.dev = &pdev->parent;
bar_idx = quirk && quirk->bar_offset ? quirk->bar_idx : AHCI_REG_BAR;
ahci->regs = rt_pci_iomap(pdev, bar_idx);
if (!ahci->regs)
{
err = -RT_EIO;
goto _fail;
}
ahci->ops = quirk && quirk->ops ? quirk->ops : &pci_ahci_ops;
if (rt_pci_msi_enable(pdev) > 0)
{
pci_ahci->is_msi = RT_TRUE;
}
else
{
rt_pci_irq_unmask(pdev);
}
ahci->irq = pdev->irq;
rt_pci_set_master(pdev);
if ((err = rt_ahci_host_register(ahci)))
{
goto _disable;
}
pdev->parent.user_data = pci_ahci;
return RT_EOK;
_disable:
if (pci_ahci->is_msi)
{
rt_pci_msix_disable(pdev);
}
else
{
rt_pci_irq_mask(pdev);
}
rt_pci_clear_master(pdev);
rt_iounmap(ahci->regs);
_fail:
rt_free(pci_ahci);
return err;
}
static rt_err_t pci_ahci_remove(struct rt_pci_device *pdev)
{
struct rt_ahci_host *ahci;
struct pci_ahci_host *pci_ahci = pdev->parent.user_data;
ahci = &pci_ahci->parent;
rt_ahci_host_unregister(ahci);
if (pci_ahci->is_msi)
{
rt_pci_msi_disable(pdev);
}
else
{
/* INTx is shared, don't mask all */
rt_hw_interrupt_umask(pdev->irq);
rt_pci_irq_mask(pdev);
}
rt_pci_clear_master(pdev);
rt_iounmap(ahci->regs);
rt_free(pci_ahci);
return RT_EOK;
}
static rt_err_t pci_ahci_shutdown(struct rt_pci_device *pdev)
{
return pci_ahci_remove(pdev);
}
static struct pci_ahci_quirk intel_quirk =
{
.ops = &pci_ahci_intel_ops,
};
static struct pci_ahci_quirk cavium_sata_quirk =
{
.bar_idx = 0,
.bar_offset = RT_TRUE,
};
static const struct rt_pci_device_id pci_ahci_ids[] =
{
{ RT_PCI_DEVICE_ID(PCI_VENDOR_ID_INTEL, 0x2922), .data = &intel_quirk },
{ RT_PCI_DEVICE_ID(PCI_VENDOR_ID_ASMEDIA, 0x0611) },
{ RT_PCI_DEVICE_ID(PCI_VENDOR_ID_MARVELL, 0x6121) },
{ RT_PCI_DEVICE_ID(PCI_VENDOR_ID_MARVELL, 0x6145) },
{ RT_PCI_DEVICE_ID(PCI_VENDOR_ID_CAVIUM, 0xa01c), .data = &cavium_sata_quirk },
{ RT_PCI_DEVICE_CLASS(PCIS_STORAGE_SATA_AHCI, ~0) },
{ /* sentinel */ }
};
static struct rt_pci_driver pci_ahci_driver =
{
.name = "ahci-pci",
.ids = pci_ahci_ids,
.probe = pci_ahci_probe,
.remove = pci_ahci_remove,
.shutdown = pci_ahci_shutdown,
};
RT_PCI_DRIVER_EXPORT(pci_ahci_driver);
+896
View File
@@ -0,0 +1,896 @@
/*
* Copyright (c) 2006-2023, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2023-02-25 GuEe-GUI the first version
*/
#include <rthw.h>
#include <rtthread.h>
#include <rtdevice.h>
#define DBG_TAG "rtdm.ahci"
#define DBG_LVL DBG_INFO
#include <rtdbg.h>
#define HWREG32_FLUSH(base, value) \
do { \
rt_uint32_t __value = value; \
HWREG32(base) = __value; \
__value = HWREG32(base); \
} while (0)
static void ahci_fill_cmd_slot(struct rt_ahci_port *port, rt_uint32_t opts)
{
rt_ubase_t dma_addr = port->cmd_tbl_dma;
struct rt_ahci_cmd_hdr *cmd_slot = port->cmd_slot;
cmd_slot->opts = rt_cpu_to_le32(opts);
cmd_slot->status = 0;
cmd_slot->tbl_addr_lo = rt_cpu_to_le32(rt_lower_32_bits(dma_addr));
cmd_slot->tbl_addr_hi = rt_cpu_to_le32(rt_upper_32_bits(dma_addr));
}
static int ahci_fill_sg(struct rt_ahci_host *host, int id,
void *buffer, rt_size_t buffer_size)
{
int sg_count;
rt_ubase_t dma_addr;
struct rt_ahci_port *port = &host->ports[id];
struct rt_ahci_sg *ahci_sg = port->cmd_tbl_sg;
sg_count = ((buffer_size - 1) / RT_ACHI_PRDT_BYTES_MAX) + 1;
if (sg_count > RT_AHCI_MAX_SG)
{
return -1;
}
dma_addr = (rt_ubase_t)rt_kmem_v2p(buffer);
for (int i = 0; i < sg_count; ++i, ++ahci_sg)
{
ahci_sg->addr_lo = rt_cpu_to_le32(rt_lower_32_bits(dma_addr));
ahci_sg->addr_hi = rt_cpu_to_le32(rt_upper_32_bits(dma_addr));
if (ahci_sg->addr_hi && !(host->cap & RT_AHCI_CAP_64))
{
return -1;
}
ahci_sg->flags_size = rt_cpu_to_le32(0x3fffff &
(rt_min_t(rt_uint32_t, buffer_size, RT_ACHI_PRDT_BYTES_MAX) - 1));
dma_addr += RT_ACHI_PRDT_BYTES_MAX;
buffer_size -= RT_ACHI_PRDT_BYTES_MAX;
}
return sg_count;
}
static rt_err_t ahci_request_io(struct rt_ahci_host *host, int id,
void *fis, rt_size_t fis_size,
void *buffer, rt_size_t buffer_size, rt_bool_t is_read)
{
int sg_count;
rt_err_t err;
struct rt_ahci_port *port = &host->ports[id];
if ((HWREG32(port->regs + RT_AHCI_PORT_SSTS) & 0xf) != RT_AHCI_PORT_SSTS_DET_PHYRDY)
{
return -RT_EIO;
}
if ((sg_count = ahci_fill_sg(host, id, buffer, buffer_size)) <= 0)
{
return -RT_EINVAL;
}
rt_memcpy(port->cmd_tbl, fis, fis_size);
ahci_fill_cmd_slot(port, (fis_size >> 2) | (sg_count << 16) | (!is_read << 6));
if (!is_read)
{
rt_hw_cpu_dcache_ops(RT_HW_CACHE_FLUSH, buffer, buffer_size);
}
HWREG32_FLUSH(port->regs + RT_AHCI_PORT_CI, 1);
err = rt_completion_wait(&port->done, rt_tick_from_millisecond(10000));
if (!err && is_read)
{
rt_hw_cpu_dcache_ops(RT_HW_CACHE_INVALIDATE, buffer, buffer_size);
}
return err;
}
static rt_err_t ahci_scsi_cmd_rw(struct rt_ahci_host *host, int id,
rt_off_t lba, void *buffer, rt_ssize_t size, rt_bool_t is_read)
{
rt_err_t err;
rt_uint8_t fis[20];
struct rt_ahci_port *port = &host->ports[id];
rt_memset(fis, 0, sizeof(fis));
fis[0] = RT_AHCI_FIS_TYPE_REG_H2D;
fis[1] = 1 << 7; /* Command */
fis[2] = is_read ? RT_AHCI_ATA_CMD_READ_EXT : RT_AHCI_ATA_CMD_WRITE_EXT;
while (size > 0)
{
rt_size_t t_size, t_lba;
t_lba = rt_min_t(rt_size_t, host->max_blocks, size);
t_size = port->block_size * t_lba;
fis[3] = 0xe0; /* Features */
fis[4] = (lba >> 0) & 0xff; /* LBA low register */
fis[5] = (lba >> 8) & 0xff; /* LBA mid register */
fis[6] = (lba >> 16) & 0xff; /* LBA high register */
fis[7] = 1 << 6; /* Device */
fis[8] = ((lba >> 24) & 0xff); /* LBA register, 31:24 */
fis[9] = ((lba >> 32) & 0xff); /* LBA register, 39:32 */
fis[10] = ((lba >> 40) & 0xff); /* LBA register, 47:40 */
fis[12] = (t_lba >> 0) & 0xff; /* Count register, 7:0 */
fis[13] = (t_lba >> 8) & 0xff; /* Count register, 15:8 */
if ((err = ahci_request_io(host, id, fis, sizeof(fis), buffer, t_size, is_read)))
{
return err;
}
size -= t_lba;
lba += t_lba;
buffer += t_size;
}
return RT_EOK;
}
static rt_err_t ahci_scsi_synchronize_cache(struct rt_ahci_host *host, int id,
rt_off_t lba, rt_size_t size)
{
rt_uint8_t fis[20];
rt_uint16_t *ataid;
struct rt_ahci_port *port = &host->ports[id];
ataid = port->ataid;
if (!rt_ahci_ata_id_wcache_enabled(ataid) &&
!rt_ahci_ata_id_has_flush(ataid) &&
!rt_ahci_ata_id_has_flush_ext(ataid))
{
return -RT_ENOSYS;
}
rt_memset(fis, 0, sizeof(fis));
fis[0] = RT_AHCI_FIS_TYPE_REG_H2D;
fis[1] = 1 << 7; /* Command */
if (rt_ahci_ata_id_has_flush_ext(ataid))
{
fis[2] = RT_AHCI_ATA_CMD_FLUSH_EXT;
}
else
{
fis[2] = RT_AHCI_ATA_CMD_FLUSH;
}
rt_memcpy(port->cmd_tbl, fis, 20);
ahci_fill_cmd_slot(port, 5);
HWREG32_FLUSH(port->regs + RT_AHCI_PORT_CI, 1);
return rt_completion_wait(&port->done, rt_tick_from_millisecond(5000));
}
static rt_err_t ahci_scsi_cmd_write_same(struct rt_ahci_host *host, int id,
rt_off_t lba, rt_size_t size)
{
rt_uint8_t fis[20];
struct rt_ahci_port *port = &host->ports[id];
rt_memset(fis, 0, sizeof(fis));
fis[0] = RT_AHCI_FIS_TYPE_REG_H2D;
fis[1] = 1 << 7; /* Command */
fis[2] = RT_AHCI_ATA_CMD_DSM;
fis[3] = RT_AHCI_ATA_DSM_TRIM; /* Features */
fis[4] = (lba >> 0) & 0xff; /* LBA low register */
fis[5] = (lba >> 8) & 0xff; /* LBA mid register */
fis[6] = (lba >> 16) & 0xff; /* LBA high register */
fis[7] = 1 << 6; /* Device */
fis[8] = ((lba >> 24) & 0xff); /* LBA register, 31:24 */
fis[9] = ((lba >> 32) & 0xff); /* LBA register, 39:32 */
fis[10] = ((lba >> 40) & 0xff); /* LBA register, 47:40 */
fis[12] = (size >> 0) & 0xff; /* Count register, 7:0 */
fis[13] = (size >> 8) & 0xff; /* Count register, 15:8 */
HWREG32_FLUSH(port->regs + RT_AHCI_PORT_CI, 1);
return rt_completion_wait(&port->done, rt_tick_from_millisecond(5000));
}
static rt_err_t ahci_scsi_cmd_read_capacity(struct rt_ahci_host *host, int id,
rt_size_t *out_last_block, rt_size_t *out_block_size)
{
struct rt_ahci_port *port = &host->ports[id];
if (!port->ataid)
{
return -RT_EIO;
}
*out_last_block = rt_ahci_ata_id_n_sectors(port->ataid) - 1;
*out_block_size = port->block_size;
return RT_EOK;
}
static rt_err_t ahci_scsi_cmd_test_unit_ready(struct rt_ahci_host *host, int id)
{
struct rt_ahci_port *port = &host->ports[id];
return port->ataid ? RT_EOK : -RT_EIO;
}
static rt_err_t ahci_scsi_cmd_inquiry(struct rt_ahci_host *host, int id,
char *prodid, rt_size_t prodid_len, char *prodrev, rt_size_t prodrev_len)
{
rt_err_t err;
rt_uint8_t fis[20];
rt_uint16_t *ataid;
struct rt_ahci_port *port = &host->ports[id];
if (!port->link)
{
return -RT_EIO;
}
if (!port->ataid && !(port->ataid = rt_malloc(RT_AHCI_ATA_ID_WORDS * 2)))
{
return -RT_ENOMEM;
}
ataid = port->ataid;
rt_memset(fis, 0, sizeof(fis));
fis[0] = RT_AHCI_FIS_TYPE_REG_H2D;
fis[1] = 1 << 7; /* Command */
fis[2] = RT_AHCI_ATA_CMD_ID_ATA;
if ((err = ahci_request_io(host, id, fis, sizeof(fis),
ataid, RT_AHCI_ATA_ID_WORDS * 2, RT_TRUE)))
{
return err;
}
for (int i = 0; i < RT_AHCI_ATA_ID_WORDS; ++i)
{
ataid[i] = rt_le16_to_cpu(ataid[i]);
}
for (int i = 0; i < prodid_len / 2; ++i)
{
rt_uint16_t src = ataid[RT_AHCI_ATA_ID_PROD + i];
prodid[i] = (src & 0x00ff) << 8 | (src & 0xff00) >> 8;
}
for (int i = 0; i < prodrev_len / 2; ++i)
{
rt_uint16_t src = ataid[RT_AHCI_ATA_ID_FW_REV + i];
prodrev[i] = (src & 0x00ff) << 8 | (src & 0xff00) >> 8;
}
return err;
}
static rt_err_t ahci_scsi_transfer(struct rt_scsi_device *sdev,
struct rt_scsi_cmd *cmd)
{
rt_err_t err;
struct rt_ahci_host *host;
host = rt_container_of(sdev->host, struct rt_ahci_host, parent);
switch (cmd->op.unknow.opcode)
{
case RT_SCSI_CMD_REQUEST_SENSE:
{
struct rt_scsi_request_sense_data *request_sense = &cmd->data.request_sense;
request_sense->error_code = 0x72;
err = RT_EOK;
}
break;
case RT_SCSI_CMD_READ10:
{
struct rt_scsi_read10 *read10 = &cmd->op.read10;
err = ahci_scsi_cmd_rw(host, sdev->id,
rt_be32_to_cpu(read10->lba),
cmd->data.ptr,
rt_be16_to_cpu(read10->size),
RT_TRUE);
}
break;
case RT_SCSI_CMD_READ16:
{
struct rt_scsi_read16 *read16 = &cmd->op.read16;
err = ahci_scsi_cmd_rw(host, sdev->id,
rt_be64_to_cpu(read16->lba),
cmd->data.ptr,
rt_be32_to_cpu(read16->size),
RT_TRUE);
}
break;
case RT_SCSI_CMD_READ12:
{
struct rt_scsi_read12 *read12 = &cmd->op.read12;
err = ahci_scsi_cmd_rw(host, sdev->id,
rt_be32_to_cpu(read12->lba),
cmd->data.ptr,
rt_be32_to_cpu(read12->size),
RT_TRUE);
}
break;
case RT_SCSI_CMD_WRITE10:
{
struct rt_scsi_write10 *write10 = &cmd->op.write10;
err = ahci_scsi_cmd_rw(host, sdev->id,
rt_be32_to_cpu(write10->lba),
cmd->data.ptr,
rt_be16_to_cpu(write10->size),
RT_FALSE);
}
break;
case RT_SCSI_CMD_WRITE16:
{
struct rt_scsi_write16 *write16 = &cmd->op.write16;
err = ahci_scsi_cmd_rw(host, sdev->id,
rt_be64_to_cpu(write16->lba),
cmd->data.ptr,
rt_be32_to_cpu(write16->size),
RT_FALSE);
}
break;
case RT_SCSI_CMD_WRITE12:
{
struct rt_scsi_write12 *write12 = &cmd->op.write12;
err = ahci_scsi_cmd_rw(host, sdev->id,
rt_be32_to_cpu(write12->lba),
cmd->data.ptr,
rt_be32_to_cpu(write12->size),
RT_FALSE);
}
break;
case RT_SCSI_CMD_SYNCHRONIZE_CACHE10:
{
struct rt_scsi_synchronize_cache10 *synchronize_cache10 = &cmd->op.synchronize_cache10;
err = ahci_scsi_synchronize_cache(host, sdev->id,
rt_be32_to_cpu(synchronize_cache10->lba),
rt_be16_to_cpu(synchronize_cache10->size));
}
break;
case RT_SCSI_CMD_SYNCHRONIZE_CACHE16:
{
struct rt_scsi_synchronize_cache16 *synchronize_cache16 = &cmd->op.synchronize_cache16;
err = ahci_scsi_synchronize_cache(host, sdev->id,
rt_be64_to_cpu(synchronize_cache16->lba),
rt_be32_to_cpu(synchronize_cache16->size));
}
break;
case RT_SCSI_CMD_WRITE_SAME10:
{
struct rt_scsi_write_same10 *write_same10 = &cmd->op.write_same10;
err = ahci_scsi_cmd_write_same(host, sdev->id,
rt_be32_to_cpu(write_same10->lba), rt_be16_to_cpu(write_same10->size));
}
break;
case RT_SCSI_CMD_WRITE_SAME16:
{
struct rt_scsi_write_same16 *write_same16 = &cmd->op.write_same16;
err = ahci_scsi_cmd_write_same(host, sdev->id,
rt_be64_to_cpu(write_same16->lba), rt_be32_to_cpu(write_same16->size));
}
break;
case RT_SCSI_CMD_READ_CAPACITY10:
{
rt_size_t last_block, block_size;
struct rt_scsi_read_capacity10_data *data = &cmd->data.read_capacity10;
err = ahci_scsi_cmd_read_capacity(host, sdev->id, &last_block, &block_size);
if (!err)
{
if (last_block > 0x100000000ULL)
{
last_block = 0xffffffff;
}
data->last_block = rt_cpu_to_be32(last_block);
data->block_size = rt_cpu_to_be32(block_size);
}
}
break;
case RT_SCSI_CMD_READ_CAPACITY16:
{
rt_size_t last_block, block_size;
struct rt_scsi_read_capacity16_data *data = &cmd->data.read_capacity16;
err = ahci_scsi_cmd_read_capacity(host, sdev->id, &last_block, &block_size);
if (!err)
{
data->last_block = rt_cpu_to_be64(last_block);
data->block_size = rt_cpu_to_be32(block_size);
}
}
break;
case RT_SCSI_CMD_TEST_UNIT_READY:
err = ahci_scsi_cmd_test_unit_ready(host, sdev->id);
break;
case RT_SCSI_CMD_INQUIRY:
{
struct rt_ahci_port *port = &host->ports[sdev->id];
struct rt_scsi_inquiry_data *inquiry = &cmd->data.inquiry;
err = ahci_scsi_cmd_inquiry(host, sdev->id,
inquiry->prodid, sizeof(inquiry->prodid),
inquiry->prodrev, sizeof(inquiry->prodrev));
if (!err)
{
rt_memcpy(inquiry->vendor, "ATA ", sizeof(inquiry->vendor));
if (HWREG32(port->regs + RT_AHCI_PORT_SIG) != RT_AHCI_PORT_SIG_SATA_CDROM)
{
port->block_size = 512;
inquiry->devtype = SCSI_DEVICE_TYPE_DIRECT;
}
else
{
port->block_size = 2048;
inquiry->devtype = SCSI_DEVICE_TYPE_CDROM;
}
inquiry->rmb = 0;
inquiry->length = 95 - 4;
}
}
break;
case RT_SCSI_CMD_MODE_SENSE:
case RT_SCSI_CMD_MODE_SENSE10:
case RT_SCSI_CMD_MODE_SELECT:
case RT_SCSI_CMD_MODE_SELECT10:
return -RT_ENOSYS;
default:
return -RT_EINVAL;
}
return err;
}
static struct rt_scsi_ops ahci_scsi_ops =
{
.transfer = ahci_scsi_transfer,
};
static void ahci_isr(int irqno, void *param)
{
int id;
rt_uint32_t isr;
rt_bitmap_t int_map;
struct rt_ahci_port *port;
struct rt_ahci_host *host = param;
int_map = HWREG32(host->regs + RT_AHCI_HBA_INTS);
rt_bitmap_for_each_set_bit(&int_map, id, host->ports_nr)
{
port = &host->ports[id];
isr = HWREG32(port->regs + RT_AHCI_PORT_INTS);
if (port->link)
{
if (host->ops->port_isr)
{
host->ops->port_isr(host, port, isr);
}
rt_completion_done(&port->done);
}
HWREG32(port->regs + RT_AHCI_PORT_INTS) = isr;
}
HWREG32(host->regs + RT_AHCI_HBA_INTS) = int_map;
}
rt_err_t rt_ahci_host_register(struct rt_ahci_host *host)
{
rt_err_t err;
rt_uint32_t value;
char dev_name[RT_NAME_MAX];
struct rt_scsi_host *scsi;
if (!host || !host->parent.dev || !host->ops)
{
return -RT_EINVAL;
}
host->max_blocks = host->max_blocks ? : 0x80;
/*
* 1. Reset HBA.
*/
err = -RT_EIO;
value = HWREG32(host->regs + RT_AHCI_HBA_GHC);
if (!(value & RT_AHCI_GHC_RESET))
{
HWREG32_FLUSH(host->regs + RT_AHCI_HBA_GHC, value | RT_AHCI_GHC_RESET);
}
for (int i = 0; i < 5; ++i)
{
rt_thread_mdelay(200);
if (!(HWREG32(host->regs + RT_AHCI_HBA_GHC) & RT_AHCI_GHC_RESET))
{
err = RT_EOK;
break;
}
}
if (err)
{
goto _fail;
}
/*
* 2. Enable AHCI and get the ports' information.
*/
HWREG32_FLUSH(host->regs + RT_AHCI_HBA_GHC, RT_AHCI_GHC_AHCI_EN);
host->cap = HWREG32(host->regs + RT_AHCI_HBA_CAP);
host->cap &= RT_AHCI_CAP_SPM | RT_AHCI_CAP_SSS | RT_AHCI_CAP_SIS;
HWREG32(host->regs + RT_AHCI_HBA_CAP) = host->cap;
host->cap = HWREG32(host->regs + RT_AHCI_HBA_CAP);
HWREG32_FLUSH(host->regs + RT_AHCI_HBA_PI, 0xf);
if (host->ops->host_init && (err = host->ops->host_init(host)))
{
goto _fail;
}
host->ports_nr = (host->cap & RT_AHCI_CAP_NP) + 1;
host->ports_map = HWREG32(host->regs + RT_AHCI_HBA_PI);
/* Check implemented in firmware */
rt_dm_dev_prop_read_u32(host->parent.dev, "ports-implemented", &host->ports_map);
for (int i = 0; i < host->ports_nr; ++i)
{
struct rt_ahci_port *port;
if (!(host->ports_map & RT_BIT(i)))
{
continue;
}
port = &host->ports[i];
/*
* 3. Alloc port io memory.
*/
port->regs = host->regs + 0x100 + (i * 0x80);
/*
* 4. Make port stop.
*/
value = HWREG32(port->regs + RT_AHCI_PORT_CMD);
if (value & (RT_AHCI_PORT_CMD_LIST_ON | RT_AHCI_PORT_CMD_FIS_ON |
RT_AHCI_PORT_CMD_FIS_RX | RT_AHCI_PORT_CMD_START))
{
value &= ~(RT_AHCI_PORT_CMD_LIST_ON | RT_AHCI_PORT_CMD_FIS_ON |
RT_AHCI_PORT_CMD_FIS_RX | RT_AHCI_PORT_CMD_START);
HWREG32_FLUSH(port->regs + RT_AHCI_PORT_CMD, value);
rt_thread_mdelay(500);
}
if (host->ops->port_init && (err = host->ops->port_init(host, port)))
{
LOG_E("Init port[%d] error = %s", rt_strerror(err));
continue;
}
value = HWREG32(port->regs + RT_AHCI_PORT_CMD);
value |= RT_AHCI_PORT_CMD_SPIN_UP;
HWREG32(port->regs + RT_AHCI_PORT_CMD) = value;
/*
* 5. Enable port's SATA link.
*/
if (host->ops->port_link_up)
{
err = host->ops->port_link_up(host, port);
}
else
{
err = -RT_ETIMEOUT;
for (int retry = 0; retry < 5; ++retry)
{
value = HWREG32(port->regs + RT_AHCI_PORT_SSTS);
if ((value & RT_AHCI_PORT_SSTS_DET_MASK) == RT_AHCI_PORT_SSTS_DET_PHYRDY)
{
err = RT_EOK;
break;
}
rt_thread_mdelay(2);
}
}
if (err)
{
if (HWREG32(port->regs + RT_AHCI_PORT_SSTS) & RT_AHCI_PORT_SSTS_DET_MASK)
{
LOG_E("SATA[%d] link error = %s", i, rt_strerror(err));
}
else
{
LOG_D("SATA[%d] not device", i);
}
continue;
}
/* Clear error status */
if ((value = HWREG32(port->regs + RT_AHCI_PORT_SERR)))
{
HWREG32(port->regs + RT_AHCI_PORT_SERR) = value;
}
for (int retry = 0; retry < 5; ++retry)
{
value = HWREG32(port->regs + RT_AHCI_PORT_TFD);
if (!(value & (RT_AHCI_PORT_TFDATA_BSY | RT_AHCI_PORT_TFDATA_DRQ)))
{
break;
}
rt_thread_mdelay(2);
value = HWREG32(port->regs + RT_AHCI_PORT_SSTS);
if ((value & RT_AHCI_PORT_SSTS_DET_MASK) == RT_AHCI_PORT_SSTS_DET_PHYRDY)
{
break;
}
}
value = HWREG32(port->regs + RT_AHCI_PORT_SSTS) & RT_AHCI_PORT_SSTS_DET_MASK;
if (value == RT_AHCI_PORT_SSTS_DET_COMINIT)
{
/* Retry to setup */
--i;
continue;
}
/* Clear error */
value = HWREG32(port->regs + RT_AHCI_PORT_SERR);
HWREG32(port->regs + RT_AHCI_PORT_SERR) = value;
/* Clear pending IRQ */
if ((value = HWREG32(port->regs + RT_AHCI_PORT_INTS)))
{
HWREG32(port->regs + RT_AHCI_PORT_INTS) = value;
}
HWREG32(host->regs + RT_AHCI_HBA_INTS) = RT_BIT(i);
value = HWREG32(port->regs + RT_AHCI_PORT_SSTS);
if ((value & RT_AHCI_PORT_SSTS_DET_MASK) == RT_AHCI_PORT_SSTS_DET_PHYRDY)
{
port->link = RT_TRUE;
}
}
HWREG32(host->regs + RT_AHCI_HBA_GHC) |= RT_AHCI_GHC_IRQ_EN;
for (int i = 0; i < host->ports_nr; ++i)
{
void *dma;
rt_ubase_t dma_addr;
rt_tick_t timeout;
struct rt_ahci_port *port = &host->ports[i];
if (!port->link)
{
continue;
}
/*
* 6. Alloc transport memory, Port x Command List and FIS Base Address.
*/
port->dma = rt_dma_alloc_coherent(host->parent.dev,
RT_AHCI_DMA_SIZE, &port->dma_handle);
if (!port->dma)
{
LOG_E("No memory to setup port[%d]", i);
break;
}
dma = port->dma;
rt_memset(dma, 0, RT_AHCI_DMA_SIZE);
port->cmd_slot = dma;
dma += (RT_AHCI_CMD_SLOT_SIZE + 224);
port->rx_fis = dma;
dma += RT_AHCI_RX_FIS_SIZE;
port->cmd_tbl = dma;
port->cmd_tbl_dma = (rt_ubase_t)rt_kmem_v2p(dma);
dma += RT_AHCI_CMD_TBL_HDR;
port->cmd_tbl_sg = dma;
dma_addr = (rt_ubase_t)rt_kmem_v2p(port->cmd_slot);
HWREG32_FLUSH(port->regs + RT_AHCI_PORT_CLB, rt_lower_32_bits(dma_addr));
HWREG32_FLUSH(port->regs + RT_AHCI_PORT_CLBU, rt_upper_32_bits(dma_addr));
dma_addr = (rt_ubase_t)rt_kmem_v2p(port->rx_fis);
HWREG32_FLUSH(port->regs + RT_AHCI_PORT_FB, rt_lower_32_bits(dma_addr));
HWREG32_FLUSH(port->regs + RT_AHCI_PORT_FBU, rt_upper_32_bits(dma_addr));
if (host->ops->port_dma_init && (err = host->ops->port_dma_init(host, port)))
{
LOG_E("Init port[%d] DMA error = %s", rt_strerror(err));
}
HWREG32_FLUSH(port->regs + RT_AHCI_PORT_CMD, RT_AHCI_PORT_CMD_ACTIVE |
RT_AHCI_PORT_CMD_FIS_RX | RT_AHCI_PORT_CMD_POWER_ON |
RT_AHCI_PORT_CMD_SPIN_UP | RT_AHCI_PORT_CMD_START);
/* Wait spinup */
err = -RT_ETIMEOUT;
timeout = rt_tick_from_millisecond(20000);
timeout += rt_tick_get();
do {
if (!(HWREG32(port->regs + RT_AHCI_PORT_TFD) & RT_AHCI_PORT_TFDATA_BSY))
{
err = RT_EOK;
break;
}
rt_hw_cpu_relax();
} while (rt_tick_get() < timeout);
if (err)
{
rt_dma_free_coherent(host->parent.dev, RT_AHCI_DMA_SIZE, port->dma,
port->dma_handle);
port->dma = RT_NULL;
LOG_E("Start up port[%d] fail", i);
continue;
}
port->int_enabled |= RT_AHCI_PORT_INTE_HBUS_ERR | RT_AHCI_PORT_INTE_IF_ERR |
RT_AHCI_PORT_INTE_CONNECT | RT_AHCI_PORT_INTE_PHYRDY |
RT_AHCI_PORT_INTE_UNK_FIS | RT_AHCI_PORT_INTE_BAD_PMP |
RT_AHCI_PORT_INTE_TF_ERR | RT_AHCI_PORT_INTE_HBUS_DATA_ERR |
RT_AHCI_PORT_INTE_SG_DONE | RT_AHCI_PORT_INTE_SDB_FIS |
RT_AHCI_PORT_INTE_DMAS_FIS | RT_AHCI_PORT_INTE_PIOS_FIS |
RT_AHCI_PORT_INTE_D2H_REG_FIS;
HWREG32(port->regs + RT_AHCI_PORT_INTE) = port->int_enabled;
rt_completion_init(&port->done);
}
rt_snprintf(dev_name, sizeof(dev_name), "ahci-%s",
rt_dm_dev_get_name(host->parent.dev));
rt_hw_interrupt_install(host->irq, ahci_isr, host, dev_name);
rt_hw_interrupt_umask(host->irq);
scsi = &host->parent;
scsi->max_lun = rt_max_t(rt_size_t, scsi->max_lun, 1);
scsi->max_id = host->ports_nr;
scsi->ops = &ahci_scsi_ops;
if ((err = rt_scsi_host_register(scsi)))
{
goto _fail;
}
return RT_EOK;
_fail:
rt_hw_interrupt_mask(host->irq);
rt_pic_detach_irq(host->irq, host);
return err;
}
rt_err_t rt_ahci_host_unregister(struct rt_ahci_host *host)
{
rt_err_t err;
struct rt_scsi_host *scsi;
if (!host)
{
return -RT_EINVAL;
}
scsi = &host->parent;
if ((err = rt_scsi_host_unregister(scsi)))
{
return err;
}
rt_hw_interrupt_mask(host->irq);
rt_pic_detach_irq(host->irq, host);
for (int i = 0; i < host->ports_nr; ++i)
{
struct rt_ahci_port *port = &host->ports[i];
if (port->ataid)
{
rt_free(port->ataid);
}
HWREG32(port->regs) &= ~(RT_AHCI_PORT_CMD_ACTIVE | RT_AHCI_PORT_CMD_POWER_ON |
RT_AHCI_PORT_CMD_SPIN_UP | RT_AHCI_PORT_CMD_START);
if (port->dma)
{
rt_dma_free_coherent(host->parent.dev, RT_AHCI_DMA_SIZE, port->dma,
port->dma_handle);
}
}
HWREG32(host->regs + RT_AHCI_HBA_GHC) &= ~(RT_AHCI_GHC_AHCI_EN | RT_AHCI_GHC_IRQ_EN);
return RT_EOK;
}
@@ -0,0 +1,21 @@
config RT_USING_AUDIO
bool "Using Audio device drivers"
default n
if RT_USING_AUDIO
config RT_AUDIO_REPLAY_MP_BLOCK_SIZE
int "Replay memory pool block size"
default 4096
config RT_AUDIO_REPLAY_MP_BLOCK_COUNT
int "Replay memory pool block count"
default 2
config RT_AUDIO_RECORD_PIPE_SIZE
int "Record pipe size"
default 2048
config RT_UTEST_USING_AUDIO_DRIVER
bool "Enable rt_audio_api testcase"
default n
endif
@@ -0,0 +1,14 @@
from building import *
cwd = GetCurrentDir()
src = Glob('*.c')
CPPPATH = [cwd]
group = DefineGroup('DeviceDrivers', src, depend = ['RT_USING_AUDIO'], CPPPATH = CPPPATH)
list = os.listdir(cwd)
for item in list:
if os.path.isfile(os.path.join(cwd, item, 'SConscript')):
group = group + SConscript(os.path.join(item, 'SConscript'))
Return('group')
@@ -0,0 +1,784 @@
/*
* Copyright (c) 2006-2025 RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2017-05-09 Urey first version
* 2019-07-09 Zero-Free improve device ops interface and data flows
* 2025-03-04 wumingzi add doxygen comments.
*/
#include <stdio.h>
#include <string.h>
#include <rthw.h>
#include <rtdevice.h>
#define DBG_TAG "audio"
#define DBG_LVL DBG_INFO
#include <rtdbg.h>
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
/**
* @addtogroup group_drivers_audio
*/
/** @{ */
enum
{
REPLAY_EVT_NONE = 0x00,
REPLAY_EVT_START = 0x01,
REPLAY_EVT_STOP = 0x02,
};
/**
* @brief Send a replay frame to the audio hardware device
*
* This function handles sending audio data from the memory queue to the hardware buffer for playback.
* If there is no data available in the queue, it sends zero frames. Otherwise, it copies data from the memory pool
* to the hardware device FIFO and manages the read index and position accordingly.
*
* @param[in] audio pointer to the audio device structure
*
* @return error code, RT_EOK is successful otherwise means failure
*
* @note This function may temporarily disable interrupts or perform time-consuming operations like memcpy,
* which could affect system responsiveness
*/
static rt_err_t _audio_send_replay_frame(struct rt_audio_device *audio)
{
rt_err_t result = RT_EOK;
rt_uint8_t *data;
rt_size_t dst_size, src_size;
rt_uint16_t position, remain_bytes = 0, index = 0;
struct rt_audio_buf_info *buf_info;
RT_ASSERT(audio != RT_NULL);
buf_info = &audio->replay->buf_info;
/* save current pos */
position = audio->replay->pos;
dst_size = buf_info->block_size;
/* check replay queue is empty */
if (rt_data_queue_peek(&audio->replay->queue, (const void **)&data, &src_size) != RT_EOK)
{
/* ack stop event */
if (audio->replay->event & REPLAY_EVT_STOP)
rt_completion_done(&audio->replay->cmp);
/* send zero frames */
rt_memset(&buf_info->buffer[audio->replay->pos], 0, dst_size);
audio->replay->pos += dst_size;
audio->replay->pos %= buf_info->total_size;
}
else
{
rt_memset(&buf_info->buffer[audio->replay->pos], 0, dst_size);
/* copy data from memory pool to hardware device fifo */
while (index < dst_size)
{
result = rt_data_queue_peek(&audio->replay->queue, (const void **)&data, &src_size);
if (result != RT_EOK)
{
LOG_D("under run %d, remain %d", audio->replay->pos, remain_bytes);
audio->replay->pos -= remain_bytes;
audio->replay->pos += dst_size;
audio->replay->pos %= buf_info->total_size;
audio->replay->read_index = 0;
result = -RT_EEMPTY;
break;
}
remain_bytes = MIN((dst_size - index), (src_size - audio->replay->read_index));
rt_memcpy(&buf_info->buffer[audio->replay->pos],
&data[audio->replay->read_index], remain_bytes);
index += remain_bytes;
audio->replay->read_index += remain_bytes;
audio->replay->pos += remain_bytes;
audio->replay->pos %= buf_info->total_size;
if (audio->replay->read_index == src_size)
{
/* free memory */
audio->replay->read_index = 0;
rt_data_queue_pop(&audio->replay->queue, (const void **)&data, &src_size, RT_WAITING_NO);
rt_mp_free(data);
/* notify transmitted complete. */
if (audio->parent.tx_complete != RT_NULL)
audio->parent.tx_complete(&audio->parent, (void *)data);
}
}
}
if (audio->ops->transmit != RT_NULL)
{
if (audio->ops->transmit(audio, &buf_info->buffer[position], RT_NULL, dst_size) != dst_size)
result = -RT_ERROR;
}
return result;
}
/**
* @brief Write replay frame into audio device replay queue
*
* @param[in] audio pointer to audio device
*
* @return error code, RT_EOK is successful otherwise means failure
*/
static rt_err_t _audio_flush_replay_frame(struct rt_audio_device *audio)
{
rt_err_t result = RT_EOK;
if (audio->replay->write_index)
{
result = rt_data_queue_push(&audio->replay->queue,
(const void **)audio->replay->write_data,
audio->replay->write_index,
RT_WAITING_FOREVER);
audio->replay->write_index = 0;
}
return result;
}
/**
* @brief Replay audio
*
* @param[in] audio pointer to audio device
*
* @return error code, RT_EOK is successful otherwise means failure
*/
static rt_err_t _aduio_replay_start(struct rt_audio_device *audio)
{
rt_err_t result = RT_EOK;
if (audio->replay->activated != RT_TRUE)
{
/* start playback hardware device */
if (audio->ops->start)
result = audio->ops->start(audio, AUDIO_STREAM_REPLAY);
audio->replay->activated = RT_TRUE;
LOG_D("start audio replay device");
}
return result;
}
/**
* @brief Stop replaying audio
*
* When audio->replay->queue is empty and the audio->replay->event was set REPLAY_EVT_STOP,
* _audio_send_replay_frame will send completion to stop replaying audio.
*
* @param[in] audio pointer to audio device
*
* @return error code, RT_EOK is successful otherwise means failure
*/
static rt_err_t _aduio_replay_stop(struct rt_audio_device *audio)
{
rt_err_t result = RT_EOK;
if (audio->replay->activated == RT_TRUE)
{
/* flush replay remian frames */
_audio_flush_replay_frame(audio);
/* notify irq(or thread) to stop the data transmission */
audio->replay->event |= REPLAY_EVT_STOP;
/* waiting for the remaining data transfer to complete */
rt_completion_init(&audio->replay->cmp);
rt_completion_wait(&audio->replay->cmp, RT_WAITING_FOREVER);
audio->replay->event &= ~REPLAY_EVT_STOP;
/* stop playback hardware device */
if (audio->ops->stop)
result = audio->ops->stop(audio, AUDIO_STREAM_REPLAY);
audio->replay->activated = RT_FALSE;
LOG_D("stop audio replay device");
}
return result;
}
/**
* @brief Open audio pipe and start to record audio
*
* @param[in] audio pointer to audio device
*
* @return error code, RT_EOK is successful otherwise means failure
*/
static rt_err_t _audio_record_start(struct rt_audio_device *audio)
{
rt_err_t result = RT_EOK;
if (audio->record->activated != RT_TRUE)
{
/* open audio record pipe */
rt_device_open(RT_DEVICE(&audio->record->pipe), RT_DEVICE_OFLAG_RDONLY);
/* start record hardware device */
if (audio->ops->start)
result = audio->ops->start(audio, AUDIO_STREAM_RECORD);
audio->record->activated = RT_TRUE;
LOG_D("start audio record device");
}
return result;
}
/**
* @brief stop recording audio and closeaudio pipe
*
* @param[in] audio pointer to audio device
*
* @return error code, RT_EOK is successful otherwise means failure
*/
static rt_err_t _audio_record_stop(struct rt_audio_device *audio)
{
rt_err_t result = RT_EOK;
if (audio->record->activated == RT_TRUE)
{
/* stop record hardware device */
if (audio->ops->stop)
result = audio->ops->stop(audio, AUDIO_STREAM_RECORD);
/* close audio record pipe */
rt_device_close(RT_DEVICE(&audio->record->pipe));
audio->record->activated = RT_FALSE;
LOG_D("stop audio record device");
}
return result;
}
/**
* @brief Init audio pipe
*
* In kernel, this function will set replay or record function depending on device
* flag. For replaying, it will malloc for managing audio replay struct meanwhile
* creating mempool and dataqueue.For recording, it will creat audio pipe and
* it's ringbuffer.
* In driver, this function will only execute hardware driver initialization code
* and get hardware buffer infomation.
*
* @param[in] dev pointer to audio device
*
* @return error code, RT_EOK is successful otherwise means failure
*/
static rt_err_t _audio_dev_init(struct rt_device *dev)
{
rt_err_t result = RT_EOK;
struct rt_audio_device *audio;
RT_ASSERT(dev != RT_NULL);
audio = (struct rt_audio_device *) dev;
/* initialize replay & record */
audio->replay = RT_NULL;
audio->record = RT_NULL;
/* initialize replay */
if (dev->flag & RT_DEVICE_FLAG_WRONLY)
{
struct rt_audio_replay *replay = (struct rt_audio_replay *) rt_malloc(sizeof(struct rt_audio_replay));
if (replay == RT_NULL)
return -RT_ENOMEM;
rt_memset(replay, 0, sizeof(struct rt_audio_replay));
/* init memory pool for replay */
replay->mp = rt_mp_create("adu_mp", RT_AUDIO_REPLAY_MP_BLOCK_COUNT, RT_AUDIO_REPLAY_MP_BLOCK_SIZE);
if (replay->mp == RT_NULL)
{
rt_free(replay);
LOG_E("create memory pool for replay failed");
return -RT_ENOMEM;
}
/* init queue for audio replay */
rt_data_queue_init(&replay->queue, CFG_AUDIO_REPLAY_QUEUE_COUNT, 0, RT_NULL);
/* init mutex lock for audio replay */
rt_mutex_init(&replay->lock, "replay", RT_IPC_FLAG_PRIO);
replay->activated = RT_FALSE;
audio->replay = replay;
}
/* initialize record */
if (dev->flag & RT_DEVICE_FLAG_RDONLY)
{
struct rt_audio_record *record = (struct rt_audio_record *) rt_malloc(sizeof(struct rt_audio_record));
rt_uint8_t *buffer;
if (record == RT_NULL)
return -RT_ENOMEM;
rt_memset(record, 0, sizeof(struct rt_audio_record));
/* init pipe for record*/
buffer = rt_malloc(RT_AUDIO_RECORD_PIPE_SIZE);
if (buffer == RT_NULL)
{
rt_free(record);
LOG_E("malloc memory for for record pipe failed");
return -RT_ENOMEM;
}
rt_audio_pipe_init(&record->pipe, "record",
(rt_int32_t)(RT_PIPE_FLAG_FORCE_WR | RT_PIPE_FLAG_BLOCK_RD),
buffer,
RT_AUDIO_RECORD_PIPE_SIZE);
record->activated = RT_FALSE;
audio->record = record;
}
/* initialize hardware configuration */
if (audio->ops->init)
audio->ops->init(audio);
/* get replay buffer information */
if (audio->ops->buffer_info)
audio->ops->buffer_info(audio, &audio->replay->buf_info);
return result;
}
/**
* @brief Start record audio
*
* @param[in] dev pointer to audio device
*
* @param[in] oflag device flag
*
* @return error code, RT_EOK is successful otherwise means failure
*/
static rt_err_t _audio_dev_open(struct rt_device *dev, rt_uint16_t oflag)
{
struct rt_audio_device *audio;
RT_ASSERT(dev != RT_NULL);
audio = (struct rt_audio_device *) dev;
/* check device flag with the open flag */
if ((oflag & RT_DEVICE_OFLAG_RDONLY) && !(dev->flag & RT_DEVICE_FLAG_RDONLY))
return -RT_EIO;
if ((oflag & RT_DEVICE_OFLAG_WRONLY) && !(dev->flag & RT_DEVICE_FLAG_WRONLY))
return -RT_EIO;
/* get open flags */
dev->open_flag = oflag & 0xff;
/* initialize the Rx/Tx structure according to open flag */
if (oflag & RT_DEVICE_OFLAG_WRONLY)
{
if (audio->replay->activated != RT_TRUE)
{
LOG_D("open audio replay device, oflag = %x\n", oflag);
audio->replay->write_index = 0;
audio->replay->read_index = 0;
audio->replay->pos = 0;
audio->replay->event = REPLAY_EVT_NONE;
}
dev->open_flag |= RT_DEVICE_OFLAG_WRONLY;
}
if (oflag & RT_DEVICE_OFLAG_RDONLY)
{
/* open record pipe */
if (audio->record->activated != RT_TRUE)
{
LOG_D("open audio record device ,oflag = %x\n", oflag);
_audio_record_start(audio);
audio->record->activated = RT_TRUE;
}
dev->open_flag |= RT_DEVICE_OFLAG_RDONLY;
}
return RT_EOK;
}
/**
* @brief Stop record, replay or both.
*
* @param[in] dev pointer to audio device
*
* @return useless param
*/
static rt_err_t _audio_dev_close(struct rt_device *dev)
{
struct rt_audio_device *audio;
RT_ASSERT(dev != RT_NULL);
audio = (struct rt_audio_device *) dev;
if (dev->open_flag & RT_DEVICE_OFLAG_WRONLY)
{
/* stop replay stream */
_aduio_replay_stop(audio);
dev->open_flag &= ~RT_DEVICE_OFLAG_WRONLY;
}
if (dev->open_flag & RT_DEVICE_OFLAG_RDONLY)
{
/* stop record stream */
_audio_record_stop(audio);
dev->open_flag &= ~RT_DEVICE_OFLAG_RDONLY;
}
return RT_EOK;
}
/**
* @brief Read audio device
*
* @param[in] dev pointer to device
*
* @param[in] pos position when reading
*
* @param[out] buffer a data buffer to save the read data
*
* @param[in] size buffer size
*
* @return the actually read size on successfully, otherwise 0 will be returned.
*
* @note
*/
static rt_ssize_t _audio_dev_read(struct rt_device *dev, rt_off_t pos, void *buffer, rt_size_t size)
{
struct rt_audio_device *audio;
RT_ASSERT(dev != RT_NULL);
audio = (struct rt_audio_device *) dev;
if (!(dev->open_flag & RT_DEVICE_OFLAG_RDONLY) || (audio->record == RT_NULL))
return 0;
return rt_device_read(RT_DEVICE(&audio->record->pipe), pos, buffer, size);
}
/**
* @brief Write data into replay data queue and replay it
*
* @param[in] dev pointer to device
*
* @param[in] pos useless param
*
* @param[in] buffer a data buffer to be written into data queue
*
* @param[in] size buffer size
*
* @return the actually read size on successfully, otherwise 0 will be returned.
*
* @note This function will take mutex.
*/
static rt_ssize_t _audio_dev_write(struct rt_device *dev, rt_off_t pos, const void *buffer, rt_size_t size)
{
struct rt_audio_device *audio;
rt_uint8_t *ptr;
rt_uint16_t block_size, remain_bytes, index = 0;
RT_ASSERT(dev != RT_NULL);
audio = (struct rt_audio_device *) dev;
if (!(dev->open_flag & RT_DEVICE_OFLAG_WRONLY) || (audio->replay == RT_NULL))
return 0;
/* push a new frame to replay data queue */
ptr = (rt_uint8_t *)buffer;
block_size = RT_AUDIO_REPLAY_MP_BLOCK_SIZE;
rt_mutex_take(&audio->replay->lock, RT_WAITING_FOREVER);
while (index < size)
{
/* request buffer from replay memory pool */
if (audio->replay->write_index % block_size == 0)
{
audio->replay->write_data = rt_mp_alloc(audio->replay->mp, RT_WAITING_FOREVER);
rt_memset(audio->replay->write_data, 0, block_size);
}
/* copy data to replay memory pool */
remain_bytes = MIN((block_size - audio->replay->write_index), (size - index));
rt_memcpy(&audio->replay->write_data[audio->replay->write_index], &ptr[index], remain_bytes);
index += remain_bytes;
audio->replay->write_index += remain_bytes;
audio->replay->write_index %= block_size;
if (audio->replay->write_index == 0)
{
rt_data_queue_push(&audio->replay->queue,
audio->replay->write_data,
block_size,
RT_WAITING_FOREVER);
}
}
rt_mutex_release(&audio->replay->lock);
/* check replay state */
if (audio->replay->activated != RT_TRUE)
{
_aduio_replay_start(audio);
audio->replay->activated = RT_TRUE;
}
return index;
}
/**
* @brief Control audio device
*
* @param[in] dev pointer to device
*
* @param[in] cmd audio cmd, it can be one of value in @ref group_audio_control
*
* @param[in] args command argument
*
* @return error code, RT_EOK is successful otherwise means failure
*/
static rt_err_t _audio_dev_control(struct rt_device *dev, int cmd, void *args)
{
rt_err_t result = RT_EOK;
struct rt_audio_device *audio;
RT_ASSERT(dev != RT_NULL);
audio = (struct rt_audio_device *) dev;
/* dev stat...*/
switch (cmd)
{
case AUDIO_CTL_GETCAPS:
{
struct rt_audio_caps *caps = (struct rt_audio_caps *) args;
LOG_D("AUDIO_CTL_GETCAPS: main_type = %d,sub_type = %d", caps->main_type, caps->sub_type);
if (audio->ops->getcaps != RT_NULL)
{
result = audio->ops->getcaps(audio, caps);
}
break;
}
case AUDIO_CTL_CONFIGURE:
{
struct rt_audio_caps *caps = (struct rt_audio_caps *) args;
LOG_D("AUDIO_CTL_CONFIGURE: main_type = %d,sub_type = %d", caps->main_type, caps->sub_type);
if (audio->ops->configure != RT_NULL)
{
result = audio->ops->configure(audio, caps);
}
break;
}
case AUDIO_CTL_START:
{
int stream = *(int *) args;
LOG_D("AUDIO_CTL_START: stream = %d", stream);
if (stream == AUDIO_STREAM_REPLAY)
{
result = _aduio_replay_start(audio);
}
else
{
result = _audio_record_start(audio);
}
break;
}
case AUDIO_CTL_STOP:
{
int stream = *(int *) args;
LOG_D("AUDIO_CTL_STOP: stream = %d", stream);
if (stream == AUDIO_STREAM_REPLAY)
{
result = _aduio_replay_stop(audio);
}
else
{
result = _audio_record_stop(audio);
}
break;
}
default:
break;
}
return result;
}
#ifdef RT_USING_DEVICE_OPS
const static struct rt_device_ops audio_ops =
{
_audio_dev_init,
_audio_dev_open,
_audio_dev_close,
_audio_dev_read,
_audio_dev_write,
_audio_dev_control
};
#endif
/**
* @brief Register and initialize audio device
*
* @param[in] audio pointer to audio deive
*
* @param[in] name device name
*
* @param[in] flag device flags
*
* @param[in] data user data
*
* @return error code, RT_EOK is successful otherwise means failure
*/
rt_err_t rt_audio_register(struct rt_audio_device *audio, const char *name, rt_uint32_t flag, void *data)
{
rt_err_t result = RT_EOK;
struct rt_device *device;
RT_ASSERT(audio != RT_NULL);
device = &(audio->parent);
device->type = RT_Device_Class_Sound;
device->rx_indicate = RT_NULL;
device->tx_complete = RT_NULL;
#ifdef RT_USING_DEVICE_OPS
device->ops = &audio_ops;
#else
device->init = _audio_dev_init;
device->open = _audio_dev_open;
device->close = _audio_dev_close;
device->read = _audio_dev_read;
device->write = _audio_dev_write;
device->control = _audio_dev_control;
#endif
device->user_data = data;
/* register a character device */
result = rt_device_register(device, name, flag | RT_DEVICE_FLAG_REMOVABLE);
/* initialize audio device */
if (result == RT_EOK)
result = rt_device_init(device);
return result;
}
/**
* @brief Set audio sample rate
*
* @param[in] bitValue audio sample rate, it can be one of value in @ref group_audio_samp_rates
*
* @return speed has been set
*/
int rt_audio_samplerate_to_speed(rt_uint32_t bitValue)
{
int speed = 0;
switch (bitValue)
{
case AUDIO_SAMP_RATE_8K:
speed = 8000;
break;
case AUDIO_SAMP_RATE_11K:
speed = 11052;
break;
case AUDIO_SAMP_RATE_16K:
speed = 16000;
break;
case AUDIO_SAMP_RATE_22K:
speed = 22050;
break;
case AUDIO_SAMP_RATE_32K:
speed = 32000;
break;
case AUDIO_SAMP_RATE_44K:
speed = 44100;
break;
case AUDIO_SAMP_RATE_48K:
speed = 48000;
break;
case AUDIO_SAMP_RATE_96K:
speed = 96000;
break;
case AUDIO_SAMP_RATE_128K:
speed = 128000;
break;
case AUDIO_SAMP_RATE_160K:
speed = 160000;
break;
case AUDIO_SAMP_RATE_172K:
speed = 176400;
break;
case AUDIO_SAMP_RATE_192K:
speed = 192000;
break;
default:
break;
}
return speed;
}
/**
* @brief Send a replay frame to the audio hardware device
*
* See _audio_send_replay_frame for details
*
* @param[in] audio pointer to audio device
*
* @return void
*/
void rt_audio_tx_complete(struct rt_audio_device *audio)
{
/* try to send next frame */
_audio_send_replay_frame(audio);
}
/**
* @brief Receive recording from audio device
*
* @param[in] audio pointer to audio device
*
* @param[in] pbuf pointer ro data to be received
*
* @param[in] len buffer size
*
* @return void
*/
void rt_audio_rx_done(struct rt_audio_device *audio, rt_uint8_t *pbuf, rt_size_t len)
{
/* save data to record pipe */
rt_device_write(RT_DEVICE(&audio->record->pipe), 0, pbuf, len);
/* invoke callback */
if (audio->parent.rx_indicate != RT_NULL)
audio->parent.rx_indicate(&audio->parent, len);
}
/** @} group_drivers_audio */
@@ -0,0 +1,370 @@
/*
* Copyright (c) 2006-2025 RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2012-09-30 Bernard first version.
* 2025-03-04 wumingzi add doxygen comments.
*/
#include <rthw.h>
#include <rtdevice.h>
#include "dev_audio_pipe.h"
static void _rt_audio_pipe_resume_writer(struct rt_audio_pipe *pipe)
{
if (!rt_list_isempty(&pipe->suspended_write_list))
{
rt_thread_t thread;
RT_ASSERT(pipe->flag & RT_PIPE_FLAG_BLOCK_WR);
/* get suspended thread */
thread = RT_THREAD_LIST_NODE_ENTRY(pipe->suspended_write_list.next);
/* resume the write thread */
rt_thread_resume(thread);
rt_schedule();
}
}
/**
* @brief Read audio pipe
*
* @param[in] dev pointer to audio device will be read
*
* @param[in] pos useless param
*
* @param[in] buffer pointer to ringbuffer of audio pipe to be read
*
* @param[in] size number of bytes will be read
*
* @return number of read bytes
*
* @note This function will execute time-consuming or affecting the
* system operations like memcpy and disable interrupt.
*/
static rt_ssize_t rt_audio_pipe_read(rt_device_t dev,
rt_off_t pos,
void *buffer,
rt_size_t size)
{
rt_base_t level;
rt_thread_t thread;
struct rt_audio_pipe *pipe;
rt_size_t read_nbytes;
pipe = (struct rt_audio_pipe *)dev;
RT_ASSERT(pipe != RT_NULL);
if (!(pipe->flag & RT_PIPE_FLAG_BLOCK_RD))
{
level = rt_hw_interrupt_disable();
read_nbytes = rt_ringbuffer_get(&(pipe->ringbuffer), (rt_uint8_t *)buffer, size);
/* if the ringbuffer is empty, there won't be any writer waiting */
if (read_nbytes)
_rt_audio_pipe_resume_writer(pipe);
rt_hw_interrupt_enable(level);
return read_nbytes;
}
thread = rt_thread_self();
/* current context checking */
RT_DEBUG_NOT_IN_INTERRUPT;
do
{
level = rt_hw_interrupt_disable();
read_nbytes = rt_ringbuffer_get(&(pipe->ringbuffer), (rt_uint8_t *)buffer, size);
if (read_nbytes == 0)
{
rt_thread_suspend(thread);
/* waiting on suspended read list */
rt_list_insert_before(&(pipe->suspended_read_list),
&RT_THREAD_LIST_NODE(thread));
rt_hw_interrupt_enable(level);
rt_schedule();
}
else
{
_rt_audio_pipe_resume_writer(pipe);
rt_hw_interrupt_enable(level);
break;
}
}
while (read_nbytes == 0);
return read_nbytes;
}
/**
* @brief Resume audio pipe reader thread
*
* @param[in] pipe pointer to suspended audio pipe thread
*/
static void _rt_audio_pipe_resume_reader(struct rt_audio_pipe *pipe)
{
if (pipe->parent.rx_indicate)
pipe->parent.rx_indicate(&pipe->parent,
rt_ringbuffer_data_len(&pipe->ringbuffer));
if (!rt_list_isempty(&pipe->suspended_read_list))
{
rt_thread_t thread;
RT_ASSERT(pipe->flag & RT_PIPE_FLAG_BLOCK_RD);
/* get suspended thread */
thread = RT_THREAD_LIST_NODE_ENTRY(pipe->suspended_read_list.next);
/* resume the read thread */
rt_thread_resume(thread);
rt_schedule();
}
}
/**
* @brief Write data into audio pipe
*
* @param[in] dev pointer to audio pipe that has been configured
*
* @param[in] pos useless param
*
* @param[in] buffer pointer to buffer of ringbuffer
*
* @param[in] size size of data will be written
*
* @return number of written bytes
*
* @note The function will disable interrupt and may suspend current thread
*/
static rt_ssize_t rt_audio_pipe_write(rt_device_t dev,
rt_off_t pos,
const void *buffer,
rt_size_t size)
{
rt_base_t level;
rt_thread_t thread;
struct rt_audio_pipe *pipe;
rt_size_t write_nbytes;
pipe = (struct rt_audio_pipe *)dev;
RT_ASSERT(pipe != RT_NULL);
if ((pipe->flag & RT_PIPE_FLAG_FORCE_WR) ||
!(pipe->flag & RT_PIPE_FLAG_BLOCK_WR))
{
level = rt_hw_interrupt_disable();
if (pipe->flag & RT_PIPE_FLAG_FORCE_WR)
write_nbytes = rt_ringbuffer_put_force(&(pipe->ringbuffer),
(const rt_uint8_t *)buffer, size);
else
write_nbytes = rt_ringbuffer_put(&(pipe->ringbuffer),
(const rt_uint8_t *)buffer, size);
_rt_audio_pipe_resume_reader(pipe);
rt_hw_interrupt_enable(level);
return write_nbytes;
}
thread = rt_thread_self();
/* current context checking */
RT_DEBUG_NOT_IN_INTERRUPT;
do
{
level = rt_hw_interrupt_disable();
write_nbytes = rt_ringbuffer_put(&(pipe->ringbuffer), (const rt_uint8_t *)buffer, size);
if (write_nbytes == 0)
{
/* pipe full, waiting on suspended write list */
rt_thread_suspend(thread);
/* waiting on suspended read list */
rt_list_insert_before(&(pipe->suspended_write_list),
&RT_THREAD_LIST_NODE(thread));
rt_hw_interrupt_enable(level);
rt_schedule();
}
else
{
_rt_audio_pipe_resume_reader(pipe);
rt_hw_interrupt_enable(level);
break;
}
}
while (write_nbytes == 0);
return write_nbytes;
}
/**
* @brief Control audio pipe
*
* @param[in] dev pointer to pipe
*
* @param[in] cmd control command
*
* @param[in] args control argument
*
* @return error code, RT_EOK is successful otherwise means failure
*/
static rt_err_t rt_audio_pipe_control(rt_device_t dev, int cmd, void *args)
{
struct rt_audio_pipe *pipe;
pipe = (struct rt_audio_pipe *)dev;
if (cmd == PIPE_CTRL_GET_SPACE && args)
*(rt_size_t *)args = rt_ringbuffer_space_len(&pipe->ringbuffer);
return RT_EOK;
}
#ifdef RT_USING_DEVICE_OPS
const static struct rt_device_ops audio_pipe_ops =
{
RT_NULL,
RT_NULL,
RT_NULL,
rt_audio_pipe_read,
rt_audio_pipe_write,
rt_audio_pipe_control
};
#endif
/**
* @brief Init audio pipe
*
* This function will initialize a pipe device and put it under control of
* resource management.
*
* @param pipe the pipe device
*
* @param name the name of pipe device
*
* @param flag the attribute of the pipe device
*
* @param buf the buffer of pipe device
*
* @param size the size of pipe device buffer
*
* @return the operation status, RT_EOK on successful
*/
rt_err_t rt_audio_pipe_init(struct rt_audio_pipe *pipe,
const char *name,
rt_int32_t flag,
rt_uint8_t *buf,
rt_size_t size)
{
RT_ASSERT(pipe);
RT_ASSERT(buf);
/* initialize suspended list */
rt_list_init(&pipe->suspended_read_list);
rt_list_init(&pipe->suspended_write_list);
/* initialize ring buffer */
rt_ringbuffer_init(&pipe->ringbuffer, buf, size);
pipe->flag = flag;
/* create pipe */
pipe->parent.type = RT_Device_Class_Pipe;
#ifdef RT_USING_DEVICE_OPS
pipe->parent.ops = &audio_pipe_ops;
#else
pipe->parent.init = RT_NULL;
pipe->parent.open = RT_NULL;
pipe->parent.close = RT_NULL;
pipe->parent.read = rt_audio_pipe_read;
pipe->parent.write = rt_audio_pipe_write;
pipe->parent.control = rt_audio_pipe_control;
#endif
return rt_device_register(&(pipe->parent), name, RT_DEVICE_FLAG_RDWR);
}
/**
* @brief This function will detach a pipe device from resource management
*
* @param pipe the pipe device
*
* @return the operation status, RT_EOK on successful
*/
rt_err_t rt_audio_pipe_detach(struct rt_audio_pipe *pipe)
{
return rt_device_unregister(&pipe->parent);
}
/**
* @brief Creat audio pipe
*
* @param[in] name pipe name
*
* @param[in] flag pipe flags, it can be one of enum rt_audio_pipe_flag items
*
* @param[in] size ringbuffer size
*
* @return error code, RT_EOK on initialization successfully
*
* @note depend on RT_USING_HEAP
*/
#ifdef RT_USING_HEAP
rt_err_t rt_audio_pipe_create(const char *name, rt_int32_t flag, rt_size_t size)
{
rt_uint8_t *rb_memptr = RT_NULL;
struct rt_audio_pipe *pipe = RT_NULL;
/* get aligned size */
size = RT_ALIGN(size, RT_ALIGN_SIZE);
pipe = (struct rt_audio_pipe *)rt_calloc(1, sizeof(struct rt_audio_pipe));
if (pipe == RT_NULL)
return -RT_ENOMEM;
/* create ring buffer of pipe */
rb_memptr = (rt_uint8_t *)rt_malloc(size);
if (rb_memptr == RT_NULL)
{
rt_free(pipe);
return -RT_ENOMEM;
}
return rt_audio_pipe_init(pipe, name, flag, rb_memptr, size);
}
/**
* @brief Detachaudio pipe and free its ringbuffer
*
* @param[in] pipe pointer to the pipe will be destory
*
* @note depend on RT_USING_HEAP
*/
void rt_audio_pipe_destroy(struct rt_audio_pipe *pipe)
{
if (pipe == RT_NULL)
return;
/* un-register pipe device */
rt_audio_pipe_detach(pipe);
/* release memory */
rt_free(pipe->ringbuffer.buffer_ptr);
rt_free(pipe);
return;
}
#endif /* RT_USING_HEAP */
@@ -0,0 +1,83 @@
/*
* Copyright (c) 2006-2025 RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2025-03-04 wumingzi add doxygen comments.
*/
#ifndef __DEV_AUDIO_PIPE_H__
#define __DEV_AUDIO_PIPE_H__
/**
* Pipe Device
*/
#include <rtdevice.h>
#ifndef RT_PIPE_BUFSZ
#define PIPE_BUFSZ 512
#else
#define PIPE_BUFSZ RT_PIPE_BUFSZ
#endif
/**
* @brief Portal device
*/
struct rt_audio_portal_device
{
struct rt_device parent;
struct rt_device *write_dev;
struct rt_device *read_dev;
};
/**
* @brief Aduio pipe flags
*/
enum rt_audio_pipe_flag
{
RT_PIPE_FLAG_NONBLOCK_RDWR = 0x00, /**< both read and write won't block */
RT_PIPE_FLAG_BLOCK_RD = 0x01, /**< read would block */
RT_PIPE_FLAG_BLOCK_WR = 0x02, /**< write would block */
RT_PIPE_FLAG_FORCE_WR = 0x04, /**< write to this pipe will discard some data when the pipe is full.
* When this flag is set, RT_PIPE_FLAG_BLOCK_WR will be ignored since write
* operation will always be success. */
};
/**
* @brief Audio buffer info
*
* The preferred number and size of audio pipeline buffer for the audio device, it
* will be used in rt_audio_replay struct.
*
*/
struct rt_audio_pipe
{
struct rt_device parent;
struct rt_ringbuffer ringbuffer; /**< ring buffer in pipe device */
rt_int32_t flag;
rt_list_t suspended_read_list; /**< suspended thread list for reading */
rt_list_t suspended_write_list; /**< suspended thread list for writing */
struct rt_audio_portal_device *write_portal;
struct rt_audio_portal_device *read_portal;
};
#define PIPE_CTRL_GET_SPACE 0x14 /**< get the remaining size of a pipe device */
rt_err_t rt_audio_pipe_init(struct rt_audio_pipe *pipe,
const char *name,
rt_int32_t flag,
rt_uint8_t *buf,
rt_size_t size);
rt_err_t rt_audio_pipe_detach(struct rt_audio_pipe *pipe);
#ifdef RT_USING_HEAP
rt_err_t rt_audio_pipe_create(const char *name, rt_int32_t flag, rt_size_t size);
void rt_audio_pipe_destroy(struct rt_audio_pipe *pipe);
#endif /* RT_USING_HEAP */
#endif /* __DEV_AUDIO_PIPE_H__ */
@@ -0,0 +1,13 @@
Import('rtconfig')
from building import *
cwd = GetCurrentDir()
src = []
CPPPATH = [cwd]
if GetDepend('RT_UTEST_USING_ALL_CASES') or GetDepend('RT_UTEST_USING_AUDIO_DRIVER'):
src += Glob('tc_*.c')
group = DefineGroup('utestcases', src, depend = ['RT_USING_UTESTCASES', 'RT_USING_AUDIO'], CPPPATH = CPPPATH)
Return('group')
@@ -0,0 +1,50 @@
/*
* Copyright (c) 2006-2025 RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2025-05-02 wumingzi first version
*/
#include <rtthread.h>
#include <rtdevice.h>
#include <rttypes.h>
#include "utest.h"
/* DMA buffer of audio player device refresh is triggered only when the amount of transmitted data is
* greater than the size of a single block in the data queue */
#define TX_DMA_BLOCK_SIZE RT_AUDIO_REPLAY_MP_BLOCK_SIZE
#define TX_DMA_FIFO_SIZE (RT_AUDIO_REPLAY_MP_BLOCK_SIZE * 2)
#define RX_DMA_BLOCK_SIZE RT_AUDIO_RECORD_PIPE_SIZE
#define RX_DMA_FIFO_SIZE (RT_AUDIO_RECORD_PIPE_SIZE * 2)
#define SOUND_PLAYER_DEVICE_NAME "sound0"
#define SOUND_MIC_DEVICE_NAME "mic0"
#define PLAYER_SAMPLEBITS 16
#define PLAYER_SAMPLERATE 16000
#define PLAYER_CHANNEL 2
#define PLAYER_VOLUME 30
#define MIC_SAMPLEBITS 16
#define MIC_SAMPLERATE 16000
#define MIC_CHANNEL 2
#define MIC_TIME_MS 5000
extern rt_uint8_t audio_fsm_step ;
struct mic_device
{
struct rt_audio_device audio;
struct rt_audio_configure config;
rt_uint8_t *rx_fifo;
};
struct sound_device
{
struct rt_audio_device audio;
struct rt_audio_configure config;
rt_uint8_t volume;
rt_uint8_t *tx_fifo;
};
@@ -0,0 +1,136 @@
/*
* Copyright (c) 2006-2025 RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2025-05-02 wumingzi First version
*/
#include "tc_audio_common.h"
#define THREAD_PRIORITY 9
#define THREAD_TIMESLICE 5
#define thread_simulate_intr_create_stacksize 1024
static rt_thread_t thread_simulate_intr_handle;
static struct mic_device mic_dev;
/* Simulate callback function */
static void thread_simulate_intr(void *parameter)
{
/* Send the data(0xAA) from DMA buffer to kernel */
rt_memset((void*)&mic_dev.rx_fifo[0], 0xAA, RX_DMA_BLOCK_SIZE);
rt_audio_rx_done((struct rt_audio_device *)&(mic_dev.audio), mic_dev.rx_fifo, RX_DMA_BLOCK_SIZE);
audio_fsm_step = 1;
while (1)
{
if(audio_fsm_step == 2)
{
/* Send the the data(0x55) from DMA buffer to kernel */
rt_memset((void*)&mic_dev.rx_fifo[RX_DMA_BLOCK_SIZE], 0x55, RX_DMA_BLOCK_SIZE);
rt_audio_rx_done(&mic_dev.audio, &mic_dev.rx_fifo[RX_DMA_BLOCK_SIZE], RX_DMA_BLOCK_SIZE);
audio_fsm_step = 3;
break;
}
if(audio_fsm_step == 4)
{
rt_thread_mdelay(10);
rt_audio_rx_done(&mic_dev.audio, &mic_dev.rx_fifo[RX_DMA_BLOCK_SIZE], RX_DMA_BLOCK_SIZE);
break;
}
rt_thread_mdelay(10);
}
while(1)
{
rt_thread_mdelay(10);
}
}
static void thread_simulate_intr_create(void)
{
thread_simulate_intr_handle = rt_thread_create(
"thread_simulate_intr",
thread_simulate_intr,
RT_NULL,
thread_simulate_intr_create_stacksize,
THREAD_PRIORITY - 1, THREAD_TIMESLICE);
if (thread_simulate_intr_handle == RT_NULL)
{
rt_kprintf("Error: Failed to create thread!\n");
return;
}
if (rt_thread_startup(thread_simulate_intr_handle) != RT_EOK)
{
rt_kprintf("Error: Failed to start thread!\n");
thread_simulate_intr_handle = RT_NULL;
}
}
static rt_err_t mic_device_init(struct rt_audio_device *audio)
{
return RT_EOK;
}
/* Simulate DMA interrupt */
static rt_err_t mic_device_start(struct rt_audio_device *audio, int stream)
{
thread_simulate_intr_create();
return RT_EOK;
}
static rt_err_t mic_device_stop(struct rt_audio_device *audio, int stream)
{
if (thread_simulate_intr_handle != RT_NULL)
{
rt_thread_delete(thread_simulate_intr_handle);
thread_simulate_intr_handle = RT_NULL;
}
return RT_EOK;
}
static rt_err_t mic_device_getcaps(struct rt_audio_device *audio, struct rt_audio_caps *caps)
{
return RT_EOK;
}
static rt_err_t mic_device_configure(struct rt_audio_device *audio, struct rt_audio_caps *caps)
{
return RT_EOK;
}
static struct rt_audio_ops _mic_audio_ops =
{
.getcaps = mic_device_getcaps,
.configure = mic_device_configure,
.init = mic_device_init,
.start = mic_device_start,
.stop = mic_device_stop,
.transmit = RT_NULL,
.buffer_info = RT_NULL,
};
static int rt_hw_mic_init(void)
{
struct rt_audio_device *audio = &mic_dev.audio;
/* mic default */
mic_dev.rx_fifo = rt_malloc(RX_DMA_FIFO_SIZE);
if (mic_dev.rx_fifo == RT_NULL)
{
return -RT_ENOMEM;
}
mic_dev.config.channels = MIC_CHANNEL;
mic_dev.config.samplerate = MIC_SAMPLERATE;
mic_dev.config.samplebits = MIC_SAMPLEBITS;
/* register mic device */
audio->ops = &_mic_audio_ops;
rt_audio_register(audio, SOUND_MIC_DEVICE_NAME, RT_DEVICE_FLAG_RDONLY, (void *)&mic_dev);
return RT_EOK;
}
INIT_DEVICE_EXPORT(rt_hw_mic_init);

Some files were not shown because too many files have changed in this diff Show More