How to get started writing a kernel module

Create a folder: since you are making a kernel module, put in in ~/openwrt/package/kernel and lets call it "hello-world"
Inside that folder create a sub-folder called "src"
Inside the "hello-world" folder create a almost minimal Makefile like:

#
# Copyright (C) 2006-2009 OpenWrt.org
#
# This is free software, licensed under the GNU General Public License v2.
# See /LICENSE for more information.
#

include $(TOPDIR)/rules.mk
include $(INCLUDE_DIR)/kernel.mk

PKG_NAME:=hello-world
PKG_RELEASE:=0.1

include $(INCLUDE_DIR)/package.mk

define KernelPackage/hello-world
  SECTION:=kernel
  CATEGORY:=Kernel modules
  SUBMENU:=Other modules
  TITLE:=Hello World Kernel Module
  FILES:=$(PKG_BUILD_DIR)/hello-world.ko
endef

define Build/Compile
	$(MAKE) -C "$(LINUX_DIR)" \
		$(KERNEL_MAKE_FLAGS) \
		M="$(PKG_BUILD_DIR)" \
		EXTRA_CFLAGS="$(BUILDFLAGS)" \
		modules
endef

$(eval $(call KernelPackage,hello-world))

In your "src" sub-folder you should have a file with the source code from your post above. Lets call that: "hello-world.c"

Now add another Makefile INSIDE the src folder:

obj-m += hello-world.o

Again: those are simple files, add more fancy stuff as you get more comfortable (or need extra).

from ~/openwrt and as normal user:

make package/hello-world/compile V=s

V=s is optional but I would recommend to see any errors.
Change the source and I recommend:

make package/hello-world/{clean,compile} V=s

you will end up the an kmod-hello-world_(kernel version)(version)(target).ipk in ~/openwrt/bin/target/(whatever your target)/packages

in ~/openwrt/build_dir/(target)/(linux)/hello-world you end up the everything the original "src" folder plus anything that was needed to build the .ko file and the .ipkg stuff.

Edit:
DON'T forget to do a "make menuconfig" and select your module (either as * or M, but I would use M for clarity). Inside "kernel modules/Other modules" as defined in the "top" Makefile.

3 Likes