# Let's play with kernel API

22th dec,2019


Linux kernel programming is much different from the User Space programming. Linux Kernel is a stand-alone entity that can not use the libraries of userspace. As a result, the userspace function such as malloc, calloc, free, open, etc is no longer use. Kernel programming is based on the Portable Operating System Interface (POSIX), which is a family of standards specified by the IEEE Computer Society or ANSI C..


Error Convention

Usually, Like Unix programming the convention used for calling function is the same, 0 for success or TRUE and other value than 0 is indicating failure.



String Operation

There are many functions which are defined at include/linux/string.h header and implemented in the kernel in the lib/string.c file

/* Some examples of the functions are */

strcpy(), strncpy(), strlcpy(), strcat(), strncat(), strlcat(), strcmp(), strncmp(), strnicmp(), strchr(), strnchr(), strrchr(), strstr(), strlen(), memset(), memmove(), memcmp()


Printk()

The equivalent of the printf in the Kernel API is printk defined in include/linux/printk.h. The syntax is very similar to the printf the first parameter of the printk decides the logs . Because kernel logs are important so there are some additional features with the printk for example.

printk(KERN_WARNING "my_module input string %s\n", buff);
printk(KERN_ALERT " There is some issue with the memory ");

here KERN_ALERT is a category of the log msg.



To reduce the size of lines when using printk(), it is recommended to use the following help functions instead of directly using the printk() call:





Memory Allocation

When we call the Kmalloc func, we are going to get only certain predefined, fixed size of memory in the physical memory unit. each byte of the array is smaller than the page size. The smallest allocation that kmalloc() can handle is as big as 32 or 64 bytes and this is Architecture dependent.

$ getconf PAGESIZE or $ getconf PAGE_SIZE you can find the page size using these commands

if you want to know the max size of the page of your kernel you should visit
/usr/src/linux/include/linux/slab.h

The first argument is in kmalloc func is for the @size of the array
The second argument is a @flag defined at /usr/src/linux/include/linux/slab.h.
@flag is the type of memory that we are going to allocate.
Counter function to free the memory is Kfree() that receives the area of allocated memory by Kalloc(). Also, this function does not suspend any process.





SHIVAM CHAUDHARY

cvam0000

#Linux #Embedded divices#RTOS #Embedded Linux #Embedded c#RTOS ANYWHERE #Bash #FreeRTOS


# Popular Posts

1. RTOS VS GPOS