Build own driver with kernel compilation

  • In this section, you are going to learn

  • How to build own driver with kernel compilation

#

Version

Freebsd

14.1.0

  • To compile the kernel source code user should change the user access to root previlege mode

  • Execute below command to redirect to root access

test:~$ su
  • Run the below command to change the directory to kernel source code location

test:~$ cd /usr/src/sys
  • Execute the below commands to add the driver source code

test:~$ cd /dev

test:~$ mkdir mychar

test:~$ cd mychar
  • Create a .c file, add your char driver source code and save it

test:~$ vi mychar.c
  • Run the below commands to add the Makefile for compilation

test:~$ cd /usr/src/sys/modules

test:~$ cd mychar
  • Create a Makefile, add the below content to the Makefile for compilation and save it

test:~$ vi Makefile
  • Open the Makefile and add the module name in SUBDIR list.

test:~$ vi /usr/src/sys/modules/Makefile

SUBDIR= \
        mychar \
        .
        .
  • Run the below command to include the module into conf file for compilation

  • Add the below lines and save it

test:~$ vi /usr/src/sys/conf/files

dev/mychar/mychar.c       optional mychar
  • Add the device details in configuration file to include the device changes on kernel image

  • Add the below lines and save it

test:~$ vi /usr/src/sys/amd64/conf/MYKERNEL

device      mychar
  • Execute the below command to build the kernel compilation

test:~$ cd /usr/src

test:~$ make -j8 -DNO_CLEAN buildkernel KERNCONF=MYKERNEL
  • Check the module generated in below path

test:~$ ls /usr/obj/usr/src/amd64.amd64/sys/MYKERNEL/modules/usr/src/sys/modules/mychar/
mychar.ko
  • Move to the directory and load the module by running below command

test:~$ cd /usr/obj/usr/src/amd64.amd64/sys/MYKERNEL/modules/usr/src/sys/modules/mychar/

test:~$ kldload mychar.ko

test:~$ dmesg
Echo device loaded
  • Unload the module from the system by running below command

test:~$ cd /usr/obj/usr/src/amd64.amd64/sys/MYKERNEL/modules/usr/src/sys/modules/mychar/

test:~$ kldunload mychar.ko

test:~$ dmesg
Echo device unloaded
  • Execute the below command to install the kernel module on system.

  • Check the given directory /boot/kernel

test:~$ make -j8 installkernel KERNCONF=MYKERNEL
test:~$ ls /boot/kernel