Thursday, December 18, 2008

Using procfs for debug information

In a kernel module we can dynamically create entries under /proc . Each entry (file or directory) under /proc is represented in kernel by a struct proc_dir_entry. This structure is dynamically allocated by various functions used to create directory entries. Here are some useful examples :-

To create a directory "home" under /proc

struct proc_dir_entry *home = proc_mkdir("home", NULL);

To create directory "kitchen" under /proc/home

struct proc_dir_entry *kitchen = proc_mkdir("kitchen", home);

Ok that was enough fun creating directories. Directories can only help that much. What we really want is some files which can be read to get some information from kernel. To create files, we have to specify name of the file, it's permissions, it's parent directory, and a function which will generate data to be given to user through that file. To create a file "name" under /proc/home.

struct proc_dir_entry *name = create_proc_read_entry("name", 0444, home, proc_read_name, NULL);

proc_read_name is the function which generates data

static int proc_read_name(char *page, char **start, off_t off, int count, int *eof, void *data)
u32 nbytes = 0;

/* Never worry about off or count, or else you will get a headache */
*start = NULL; /* We don't want kernel to use *start */

/* Here we print entire contents of file into page */
nbytes = sprintf(page, "Rama Nivas\n");

/* Signal EOF */
*eof = 1;

/* Size of file */
return nbytes;

These files can only handle PAGE_SIZE amount of data (actually more is possible but the effort is not worth it). If you have more than PAGE_SIZE bytes, it's better to split data across files.

No comments: