最近项目中遇到一个问题,需要在驱动ko文件中写文件记录log,网上google了半天,要么不能用,要么直接编译不通过,最后参考内核源码linux-2.6.38/drivers/staging/spectra/lld_emu.c才搞定,主要如下:
1.我内核版本为2.6.38,编译器gcc version 4.4.1 (Sourcery G++ Lite 2009q3-67);
2.使用网上说的sys_open编译没问题,加载时会提示unknown symbol错误,估计是没有EXPORT_SYMBOL,所以不能在ko文件中使用;
3.使用网上一个filp_open例子,里面还调用了ioctl相关,直接编译错误,去除相关错误后,又加载错误;
4.用cscope搜索调用filp_open相关地方,找到drivers/staging/spectra/lld_emu.c里面有一个int emu_write_mem_to_file(void),copy出来,几乎不用修改直接可以使用,源码如下:
- #include <linux/kernel.h>
- #include <linux/init.h>
- #include <linux/module.h>
- #include <linux/syscalls.h>
- #include <linux/file.h>
- #include <linux/fs.h>
- #include <linux/fcntl.h>
- #include <asm/uaccess.h>
- #include <linux/stat.h>
- #include <asm/unistd.h>
- #include <linux/types.h>
- static int write_log_file(char *filename, char *data_w) {
- mm_segment_t fs;
- struct file *nef_filp = NULL;
- struct inode *inode = NULL;
- loff_t nef_size = 0;
- loff_t tmp_file_offset;
- ssize_t nwritten;
- int rc = -EINVAL;
- int str_len;
- fs = get_fs();
- set_fs(get_ds());
- nef_filp = filp_open(filename, O_CREAT | O_RDWR, 0);
- if (IS_ERR(nef_filp)) {
- printk(KERN_ERR "filp_open error: "
- "Unable to open nand emu file!\n");
- return PTR_ERR(nef_filp);
- }
- if (nef_filp->f_path.dentry) {
- inode = nef_filp->f_path.dentry->d_inode;
- } else {
- printk(KERN_ERR "Invalid " "nef_filp->f_path.dentry value!\n");
- goto out;
- }
- nef_size = i_size_read(inode->i_mapping->host);
- if (nef_size < 0) {
- printk(KERN_ERR "Invalid "
- "nand emu file size: 0x%llx\n", nef_size);
- goto out;
- } else {
- printk(KERN_ERR "nand emu file size: ""%lld\n", nef_size);
- }
- str_len = strlen(data_w) + 1;
- tmp_file_offset = nef_size;
- nwritten = vfs_write(nef_filp,
- (char __user *)data_w,
- str_len, &tmp_file_offset);
- if (nwritten < str_len) {
- printk(KERN_ERR "%s, Line %d - "
- "nand emu file partial write: "
- "%d bytes\n", __FILE__, __LINE__, (int)nwritten);
- goto out;
- }
-
- rc = 0;
- out:
- filp_close(nef_filp, current->files);
- set_fs(fs);
- return rc;
- }
在合适处调用如write_log_file("/root/kernel_reboot.txt", "rebooting...\n\n")即可。
阅读(608) | 评论(0) | 转发(0) |