The kernel reads and writes files in sysfs.
Recently, when implementing a new feature in Android, you need to read data from a file in sysfs in the driver and save it to another file after computation.
Reading and Writing files in kernel and reading files in userspace require calling different interfaces.
Global variables:
#define FILE_PATH "/data/xxxx.cfg"#define BUF_SIZE 128char global_buf[BUF_SIZE];struct file *fp;
Read functions:
static int get_data_from_sysfs(const char *path, char *buf){ mm_segment_t fs; fp = filp_open(path, O_RDONLY, 0644); if (unlikely(IS_ERR(fp))) { pr_info("Fail to open file \"%s\"\n", path); return -1; } fp->f_pos = 0; fs = get_fs(); set_fs(KERNEL_DS); fp->f_op->read(fp, buf, BUF_SIZE, &(fp->f_pos)); set_fs(fs); filp_close(fp, NULL); return 0;}
Write Functions
static int update_data_to_sysfs(void){ mm_segment_t fs; sprintf(global_buf, "%u %u %u\n", aaa, bbb, ccc); fp = filp_open(FILE_PATH, O_RDWR | O_CREAT, 0644); fp->f_pos = 0; fs = get_fs(); set_fs(KERNEL_DS); fp->f_op->write(fp, global_buf, sizeof(global_buf), &fp->f_pos); set_fs(fs); return 0;}
In the function prototype, the second parameter of fp-> f_op-> write and fp-> f_op-> read is the data in userspace. Therefore, it must be converted to the kernel state available, after the call is complete, it is converted back to the user State.