Posts

Showing posts with the label kernel

How to Use container_of in Linux Kernel Development

In this post, I will explain the usage of linux's container_of macro with a sample code. If you know address of a data structure's field, you can get the address of the instance of that data structure by using the container_of macro. This is the simplest explanation of this macro. Let's say you have a function called with a pointer parameter and you know that the pointer is pointing an address of a data structure field. struct my_object { int a; int b; } obj; function(&obj->b); If you want to access the other field "a" in the function, you need to use container_of macro. Let's see the below sample code and it's output to understand it easily. /* * my_object structure. */ struct my_object { int a; int b; int c; }; /* * container_test() * Test function for usage of container_of macro. * * This function is passed a pointer which points a field of * an allocated my_obj...

Linux Dynamic Debugging

Image
In Linux programming, it is very important to debug your code by adding some debug messages to your code. By using the dynamic debug feature of Linux, you can enable these debug messages per file, per function and even per line.  This post will show you how to do this with a simple kernel loadable module implementation. First, you need compile your kernel with the CONFIG_DYNAMIC_DEBUG option. It is under " Kernel hacking " menu and prompt name is " E nable dynamic printk() support " as you see on the below screenshot. Sample Code: TBD Enable/Disable dynamic debug in the sample code: TBD

Linux Debugfs implementation as a userspace interface

debugfs is a Linux file system. It is a user space interface to and from the Linux kernel. It is mounted at /sys/kernel/debug.  The kernel must be compiled with the   CONFIG_DEBUG_FS option to use this file system. It exists in the Linux kernel since version 2.6.10-rc3 [1] In the below example, you will see an example to a debugfs. A 32-bit flag is created under the /sys/kernel/debug/debugfs_ex directory called enable for read and write. debugfs_ex.c #include <linux/version.h> #include <linux/module.h> #include <linux/debugfs.h> static struct dentry * dn; /* Dentry object for debugfs directory */ static int enable; /* Enable flag for debugfs_ex module */ /* * debugfs_ex_init() */ static int __init debugfs_ex_init ( void ) { printk(KERN_INFO "debugfs_ex init \n " ); dn = debugfs_create_dir( "debugfs_ex" , NULL ); if ( ! dn) { printk(KERN_ERR "Failed to create debugfs_ex directory in debugfs \n " ); ...