1 =========================
2 Building External Modules
3 =========================
4 
5 This document describes how to build an out-of-tree kernel module.
6 
7 Introduction
8 ============
9 
10 "kbuild" is the build system used by the Linux kernel. Modules must use
11 kbuild to stay compatible with changes in the build infrastructure and
12 to pick up the right flags to the compiler. Functionality for building modules
13 both in-tree and out-of-tree is provided. The method for building
14 either is similar, and all modules are initially developed and built
15 out-of-tree.
16 
17 Covered in this document is information aimed at developers interested
18 in building out-of-tree (or "external") modules. The author of an
19 external module should supply a makefile that hides most of the
20 complexity, so one only has to type "make" to build the module. This is
21 easily accomplished, and a complete example will be presented in
22 section `Creating a Kbuild File for an External Module`_.
23 
24 
25 How to Build External Modules
26 =============================
27 
28 To build external modules, you must have a prebuilt kernel available
29 that contains the configuration and header files used in the build.
30 Also, the kernel must have been built with modules enabled. If you are
31 using a distribution kernel, there will be a package for the kernel you
32 are running provided by your distribution.
33 
34 An alternative is to use the "make" target "modules_prepare." This will
35 make sure the kernel contains the information required. The target
36 exists solely as a simple way to prepare a kernel source tree for
37 building external modules.
38 
39 NOTE: "modules_prepare" will not build Module.symvers even if
40 CONFIG_MODVERSIONS is set; therefore, a full kernel build needs to be
41 executed to make module versioning work.
42 
43 Command Syntax
44 --------------
45 
46 	The command to build an external module is::
47 
48 		$ make -C <path_to_kernel_dir> M=$PWD
49 
50 	The kbuild system knows that an external module is being built
51 	due to the "M=<dir>" option given in the command.
52 
53 	To build against the running kernel use::
54 
55 		$ make -C /lib/modules/`uname -r`/build M=$PWD
56 
57 	Then to install the module(s) just built, add the target
58 	"modules_install" to the command::
59 
60 		$ make -C /lib/modules/`uname -r`/build M=$PWD modules_install
61 
62 Options
63 -------
64 
65 	($KDIR refers to the path of the kernel source directory, or the path
66 	of the kernel output directory if the kernel was built in a separate
67 	build directory.)
68 
69 	make -C $KDIR M=$PWD
70 
71 	-C $KDIR
72 		The directory that contains the kernel and relevant build
73 		artifacts used for building an external module.
74 		"make" will actually change to the specified directory
75 		when executing and will change back when finished.
76 
77 	M=$PWD
78 		Informs kbuild that an external module is being built.
79 		The value given to "M" is the absolute path of the
80 		directory where the external module (kbuild file) is
81 		located.
82 
83 Targets
84 -------
85 
86 	When building an external module, only a subset of the "make"
87 	targets are available.
88 
89 	make -C $KDIR M=$PWD [target]
90 
91 	The default will build the module(s) located in the current
92 	directory, so a target does not need to be specified. All
93 	output files will also be generated in this directory. No
94 	attempts are made to update the kernel source, and it is a
95 	precondition that a successful "make" has been executed for the
96 	kernel.
97 
98 	modules
99 		The default target for external modules. It has the
100 		same functionality as if no target was specified. See
101 		description above.
102 
103 	modules_install
104 		Install the external module(s). The default location is
105 		/lib/modules/<kernel_release>/updates/, but a prefix may
106 		be added with INSTALL_MOD_PATH (discussed in section
107 		`Module Installation`_).
108 
109 	clean
110 		Remove all generated files in the module directory only.
111 
112 	help
113 		List the available targets for external modules.
114 
115 Building Separate Files
116 -----------------------
117 
118 	It is possible to build single files that are part of a module.
119 	This works equally well for the kernel, a module, and even for
120 	external modules.
121 
122 	Example (The module foo.ko, consist of bar.o and baz.o)::
123 
124 		make -C $KDIR M=$PWD bar.lst
125 		make -C $KDIR M=$PWD baz.o
126 		make -C $KDIR M=$PWD foo.ko
127 		make -C $KDIR M=$PWD ./
128 
129 
130 Creating a Kbuild File for an External Module
131 =============================================
132 
133 In the last section we saw the command to build a module for the
134 running kernel. The module is not actually built, however, because a
135 build file is required. Contained in this file will be the name of
136 the module(s) being built, along with the list of requisite source
137 files. The file may be as simple as a single line::
138 
139 	obj-m := <module_name>.o
140 
141 The kbuild system will build <module_name>.o from <module_name>.c,
142 and, after linking, will result in the kernel module <module_name>.ko.
143 The above line can be put in either a "Kbuild" file or a "Makefile."
144 When the module is built from multiple sources, an additional line is
145 needed listing the files::
146 
147 	<module_name>-y := <src1>.o <src2>.o ...
148 
149 NOTE: Further documentation describing the syntax used by kbuild is
150 located in Documentation/kbuild/makefiles.rst.
151 
152 The examples below demonstrate how to create a build file for the
153 module 8123.ko, which is built from the following files::
154 
155 	8123_if.c
156 	8123_if.h
157 	8123_pci.c
158 
159 Shared Makefile
160 ---------------
161 
162 	An external module always includes a wrapper makefile that
163 	supports building the module using "make" with no arguments.
164 	This target is not used by kbuild; it is only for convenience.
165 	Additional functionality, such as test targets, can be included
166 	but should be filtered out from kbuild due to possible name
167 	clashes.
168 
169 	Example 1::
170 
171 		--> filename: Makefile
172 		ifneq ($(KERNELRELEASE),)
173 		# kbuild part of makefile
174 		obj-m  := 8123.o
175 		8123-y := 8123_if.o 8123_pci.o
176 
177 		else
178 		# normal makefile
179 		KDIR ?= /lib/modules/`uname -r`/build
180 
181 		default:
182 			$(MAKE) -C $(KDIR) M=$$PWD
183 
184 		endif
185 
186 	The check for KERNELRELEASE is used to separate the two parts
187 	of the makefile. In the example, kbuild will only see the two
188 	assignments, whereas "make" will see everything except these
189 	two assignments. This is due to two passes made on the file:
190 	the first pass is by the "make" instance run on the command
191 	line; the second pass is by the kbuild system, which is
192 	initiated by the parameterized "make" in the default target.
193 
194 Separate Kbuild File and Makefile
195 ---------------------------------
196 
197 	Kbuild will first look for a file named "Kbuild", and if it is not
198 	found, it will then look for "Makefile". Utilizing a "Kbuild" file
199 	allows us to split up the "Makefile" from example 1 into two files:
200 
201 	Example 2::
202 
203 		--> filename: Kbuild
204 		obj-m  := 8123.o
205 		8123-y := 8123_if.o 8123_pci.o
206 
207 		--> filename: Makefile
208 		KDIR ?= /lib/modules/`uname -r`/build
209 
210 		default:
211 			$(MAKE) -C $(KDIR) M=$$PWD
212 
213 	The split in example 2 is questionable due to the simplicity of
214 	each file; however, some external modules use makefiles
215 	consisting of several hundred lines, and here it really pays
216 	off to separate the kbuild part from the rest.
217 
218 Building Multiple Modules
219 -------------------------
220 
221 	kbuild supports building multiple modules with a single build
222 	file. For example, if you wanted to build two modules, foo.ko
223 	and bar.ko, the kbuild lines would be::
224 
225 		obj-m := foo.o bar.o
226 		foo-y := <foo_srcs>
227 		bar-y := <bar_srcs>
228 
229 	It is that simple!
230 
231 
232 Include Files
233 =============
234 
235 Within the kernel, header files are kept in standard locations
236 according to the following rule:
237 
238 	* If the header file only describes the internal interface of a
239 	  module, then the file is placed in the same directory as the
240 	  source files.
241 	* If the header file describes an interface used by other parts
242 	  of the kernel that are located in different directories, then
243 	  the file is placed in include/linux/.
244 
245 	  NOTE:
246 	      There are two notable exceptions to this rule: larger
247 	      subsystems have their own directory under include/, such as
248 	      include/scsi; and architecture specific headers are located
249 	      under arch/$(SRCARCH)/include/.
250 
251 Kernel Includes
252 ---------------
253 
254 	To include a header file located under include/linux/, simply
255 	use::
256 
257 		#include <linux/module.h>
258 
259 	kbuild will add options to the compiler so the relevant directories
260 	are searched.
261 
262 Single Subdirectory
263 -------------------
264 
265 	External modules tend to place header files in a separate
266 	include/ directory where their source is located, although this
267 	is not the usual kernel style. To inform kbuild of the
268 	directory, use either ccflags-y or CFLAGS_<filename>.o.
269 
270 	Using the example from section 3, if we moved 8123_if.h to a
271 	subdirectory named include, the resulting kbuild file would
272 	look like::
273 
274 		--> filename: Kbuild
275 		obj-m := 8123.o
276 
277 		ccflags-y := -I $(src)/include
278 		8123-y := 8123_if.o 8123_pci.o
279 
280 Several Subdirectories
281 ----------------------
282 
283 	kbuild can handle files that are spread over several directories.
284 	Consider the following example::
285 
286 		.
287 		|__ src
288 		|   |__ complex_main.c
289 		|   |__ hal
290 		|	|__ hardwareif.c
291 		|	|__ include
292 		|	    |__ hardwareif.h
293 		|__ include
294 		|__ complex.h
295 
296 	To build the module complex.ko, we then need the following
297 	kbuild file::
298 
299 		--> filename: Kbuild
300 		obj-m := complex.o
301 		complex-y := src/complex_main.o
302 		complex-y += src/hal/hardwareif.o
303 
304 		ccflags-y := -I$(src)/include
305 		ccflags-y += -I$(src)/src/hal/include
306 
307 	As you can see, kbuild knows how to handle object files located
308 	in other directories. The trick is to specify the directory
309 	relative to the kbuild file's location. That being said, this
310 	is NOT recommended practice.
311 
312 	For the header files, kbuild must be explicitly told where to
313 	look. When kbuild executes, the current directory is always the
314 	root of the kernel tree (the argument to "-C") and therefore an
315 	absolute path is needed. $(src) provides the absolute path by
316 	pointing to the directory where the currently executing kbuild
317 	file is located.
318 
319 
320 Module Installation
321 ===================
322 
323 Modules which are included in the kernel are installed in the
324 directory:
325 
326 	/lib/modules/$(KERNELRELEASE)/kernel/
327 
328 And external modules are installed in:
329 
330 	/lib/modules/$(KERNELRELEASE)/updates/
331 
332 INSTALL_MOD_PATH
333 ----------------
334 
335 	Above are the default directories but as always some level of
336 	customization is possible. A prefix can be added to the
337 	installation path using the variable INSTALL_MOD_PATH::
338 
339 		$ make INSTALL_MOD_PATH=/frodo modules_install
340 		=> Install dir: /frodo/lib/modules/$(KERNELRELEASE)/kernel/
341 
342 	INSTALL_MOD_PATH may be set as an ordinary shell variable or,
343 	as shown above, can be specified on the command line when
344 	calling "make." This has effect when installing both in-tree
345 	and out-of-tree modules.
346 
347 INSTALL_MOD_DIR
348 ---------------
349 
350 	External modules are by default installed to a directory under
351 	/lib/modules/$(KERNELRELEASE)/updates/, but you may wish to
352 	locate modules for a specific functionality in a separate
353 	directory. For this purpose, use INSTALL_MOD_DIR to specify an
354 	alternative name to "updates."::
355 
356 		$ make INSTALL_MOD_DIR=gandalf -C $KDIR \
357 		       M=$PWD modules_install
358 		=> Install dir: /lib/modules/$(KERNELRELEASE)/gandalf/
359 
360 
361 Module Versioning
362 =================
363 
364 Module versioning is enabled by the CONFIG_MODVERSIONS tag, and is used
365 as a simple ABI consistency check. A CRC value of the full prototype
366 for an exported symbol is created. When a module is loaded/used, the
367 CRC values contained in the kernel are compared with similar values in
368 the module; if they are not equal, the kernel refuses to load the
369 module.
370 
371 Module.symvers contains a list of all exported symbols from a kernel
372 build.
373 
374 Symbols From the Kernel (vmlinux + modules)
375 -------------------------------------------
376 
377 	During a kernel build, a file named Module.symvers will be
378 	generated. Module.symvers contains all exported symbols from
379 	the kernel and compiled modules. For each symbol, the
380 	corresponding CRC value is also stored.
381 
382 	The syntax of the Module.symvers file is::
383 
384 		<CRC>       <Symbol>         <Module>                         <Export Type>     <Namespace>
385 
386 		0xe1cc2a05  usb_stor_suspend drivers/usb/storage/usb-storage  EXPORT_SYMBOL_GPL USB_STORAGE
387 
388 	The fields are separated by tabs and values may be empty (e.g.
389 	if no namespace is defined for an exported symbol).
390 
391 	For a kernel build without CONFIG_MODVERSIONS enabled, the CRC
392 	would read 0x00000000.
393 
394 	Module.symvers serves two purposes:
395 
396 	1) It lists all exported symbols from vmlinux and all modules.
397 	2) It lists the CRC if CONFIG_MODVERSIONS is enabled.
398 
399 Symbols and External Modules
400 ----------------------------
401 
402 	When building an external module, the build system needs access
403 	to the symbols from the kernel to check if all external symbols
404 	are defined. This is done in the MODPOST step. modpost obtains
405 	the symbols by reading Module.symvers from the kernel source
406 	tree. During the MODPOST step, a new Module.symvers file will be
407 	written containing all exported symbols from that external module.
408 
409 Symbols From Another External Module
410 ------------------------------------
411 
412 	Sometimes, an external module uses exported symbols from
413 	another external module. Kbuild needs to have full knowledge of
414 	all symbols to avoid spitting out warnings about undefined
415 	symbols. Two solutions exist for this situation.
416 
417 	NOTE: The method with a top-level kbuild file is recommended
418 	but may be impractical in certain situations.
419 
420 	Use a top-level kbuild file
421 		If you have two modules, foo.ko and bar.ko, where
422 		foo.ko needs symbols from bar.ko, you can use a
423 		common top-level kbuild file so both modules are
424 		compiled in the same build. Consider the following
425 		directory layout::
426 
427 			./foo/ <= contains foo.ko
428 			./bar/ <= contains bar.ko
429 
430 		The top-level kbuild file would then look like::
431 
432 			#./Kbuild (or ./Makefile):
433 				obj-m := foo/ bar/
434 
435 		And executing::
436 
437 			$ make -C $KDIR M=$PWD
438 
439 		will then do the expected and compile both modules with
440 		full knowledge of symbols from either module.
441 
442 	Use "make" variable KBUILD_EXTRA_SYMBOLS
443 		If it is impractical to add a top-level kbuild file,
444 		you can assign a space separated list
445 		of files to KBUILD_EXTRA_SYMBOLS in your build file.
446 		These files will be loaded by modpost during the
447 		initialization of its symbol tables.
448 
449 
450 Tips & Tricks
451 =============
452 
453 Testing for CONFIG_FOO_BAR
454 --------------------------
455 
456 	Modules often need to check for certain `CONFIG_` options to
457 	decide if a specific feature is included in the module. In
458 	kbuild this is done by referencing the `CONFIG_` variable
459 	directly::
460 
461 		#fs/ext2/Makefile
462 		obj-$(CONFIG_EXT2_FS) += ext2.o
463 
464 		ext2-y := balloc.o bitmap.o dir.o
465 		ext2-$(CONFIG_EXT2_FS_XATTR) += xattr.o
466