Writing a FreeBSD loadable module

In preparation for writing a device driver, I thought I would firstly write a module.  The resulting source code is here.   Firstly the Makefile:

SRCS+=bus_if.h device_if.h examplemodule.c
.include <bsd.kmod.mk>

The first line defines the sources.   examplemodule.c is my module source.  I needed to include bus_if.h and device_if.h since I'm writing my module for newbus, and those files are generated from bus_if.m and device_if.m, respectively.  Including the .h files as sources tells the FreeBSD make that it needs to generate those from the .m files.

The second line simply defines the name I wish to give my module.  This Makefile will generate "examplemodule.ko".   Finally the last line is the magic the FreeBSD team has defined which contains everything else I need to make my module.

The entry point for my module looks like this:

static int
examplemodule_modevent(module_t mod, int type, void *unused)

	switch (type) {
	case MOD_LOAD:
		uprintf("Loaded examplemodule \n");
		return (0);
		uprintf("Unloaded examplemodule \n");
		return (0);
	return (EINVAL);

When FreeBSD loads my module, or unloads it, this method will be called.  The body of the module is pretty self-explanatory.

There is also this:

static moduledata_t examplemodule_mod = {

This is the definition of my module. It contains the name of my module ("examplemodule") and the entry point "examplemodule_modevent".  If you're curious about "moduledata_t", it's a struct defined in sys/module.h

Finally a macro is used to declare the module.  Of course, this macro refers to the module definition "examplemodule_mod"

DECLARE_MODULE(examplemodule, examplemodule_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);

The macro "DECLARE_MODULE" is also defined in sys/module.h

Loading the module produces this:

root@raspberry-pi:/home/pi/freebsd-module # kldload ./examplemodule.ko 
Loaded examplemodule 
root@raspberry-pi:/home/pi/freebsd-module # kldunload ./examplemodule.ko
Unloaded examplemodule


2 Responses to "Writing a FreeBSD loadable module"

  • The skeleton of a FreeBSD driver | khubla.com
    August 17, 2013 - 7:32 pm Reply

    […] a while to understand how FreeBSD device drivers work.  So, firstly I wrote a simple module; it's here.  The next step is to write the skeleton of a device driver.  That is, a device driver that does […]

  • Jonas
    August 29, 2013 - 12:09 am Reply

    Hi, im looking for a compiled if_gif.ko module, so i can start my box with Sixxs. Is there possible some one here 🙂 ?

Leave a Reply