xref: /OK3568_Linux_fs/yocto/poky/meta/classes/kernel.bbclass (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1inherit linux-kernel-base kernel-module-split
2
3COMPATIBLE_HOST = ".*-linux"
4
5KERNEL_PACKAGE_NAME ??= "kernel"
6KERNEL_DEPLOYSUBDIR ??= "${@ "" if (d.getVar("KERNEL_PACKAGE_NAME") == "kernel") else d.getVar("KERNEL_PACKAGE_NAME") }"
7
8PROVIDES += "virtual/kernel"
9DEPENDS += "virtual/${TARGET_PREFIX}binutils virtual/${TARGET_PREFIX}gcc kmod-native bc-native bison-native"
10DEPENDS += "${@bb.utils.contains("INITRAMFS_FSTYPES", "cpio.lzo", "lzop-native", "", d)}"
11DEPENDS += "${@bb.utils.contains("INITRAMFS_FSTYPES", "cpio.lz4", "lz4-native", "", d)}"
12DEPENDS += "${@bb.utils.contains("INITRAMFS_FSTYPES", "cpio.zst", "zstd-native", "", d)}"
13PACKAGE_WRITE_DEPS += "depmodwrapper-cross"
14
15do_deploy[depends] += "depmodwrapper-cross:do_populate_sysroot gzip-native:do_populate_sysroot"
16do_clean[depends] += "make-mod-scripts:do_clean"
17
18CVE_PRODUCT ?= "linux_kernel"
19
20S = "${STAGING_KERNEL_DIR}"
21B = "${WORKDIR}/build"
22KBUILD_OUTPUT = "${B}"
23OE_TERMINAL_EXPORTS += "KBUILD_OUTPUT"
24
25# we include gcc above, we dont need virtual/libc
26INHIBIT_DEFAULT_DEPS = "1"
27
28KERNEL_IMAGETYPE ?= "zImage"
29INITRAMFS_IMAGE ?= ""
30INITRAMFS_IMAGE_NAME ?= "${@['${INITRAMFS_IMAGE}-${MACHINE}', ''][d.getVar('INITRAMFS_IMAGE') == '']}"
31INITRAMFS_TASK ?= ""
32INITRAMFS_IMAGE_BUNDLE ?= ""
33INITRAMFS_DEPLOY_DIR_IMAGE ?= "${DEPLOY_DIR_IMAGE}"
34INITRAMFS_MULTICONFIG ?= ""
35
36# KERNEL_VERSION is extracted from source code. It is evaluated as
37# None for the first parsing, since the code has not been fetched.
38# After the code is fetched, it will be evaluated as real version
39# number and cause kernel to be rebuilt. To avoid this, make
40# KERNEL_VERSION_NAME and KERNEL_VERSION_PKG_NAME depend on
41# LINUX_VERSION which is a constant.
42KERNEL_VERSION_NAME = "${@d.getVar('KERNEL_VERSION') or ""}"
43KERNEL_VERSION_NAME[vardepvalue] = "${LINUX_VERSION}"
44KERNEL_VERSION_PKG_NAME = "${@legitimize_package_name(d.getVar('KERNEL_VERSION'))}"
45KERNEL_VERSION_PKG_NAME[vardepvalue] = "${LINUX_VERSION}"
46
47python __anonymous () {
48    pn = d.getVar("PN")
49    kpn = d.getVar("KERNEL_PACKAGE_NAME")
50
51    # XXX Remove this after bug 11905 is resolved
52    #  FILES:${KERNEL_PACKAGE_NAME}-dev doesn't expand correctly
53    if kpn == pn:
54        bb.warn("Some packages (E.g. *-dev) might be missing due to "
55                "bug 11905 (variable KERNEL_PACKAGE_NAME == PN)")
56
57    # The default kernel recipe builds in a shared location defined by
58    # bitbake/distro confs: STAGING_KERNEL_DIR and STAGING_KERNEL_BUILDDIR.
59    # Set these variables to directories under ${WORKDIR} in alternate
60    # kernel recipes (I.e. where KERNEL_PACKAGE_NAME != kernel) so that they
61    # may build in parallel with the default kernel without clobbering.
62    if kpn != "kernel":
63        workdir = d.getVar("WORKDIR")
64        sourceDir = os.path.join(workdir, 'kernel-source')
65        artifactsDir = os.path.join(workdir, 'kernel-build-artifacts')
66        d.setVar("STAGING_KERNEL_DIR", sourceDir)
67        d.setVar("STAGING_KERNEL_BUILDDIR", artifactsDir)
68
69    # Merge KERNEL_IMAGETYPE and KERNEL_ALT_IMAGETYPE into KERNEL_IMAGETYPES
70    type = d.getVar('KERNEL_IMAGETYPE') or ""
71    alttype = d.getVar('KERNEL_ALT_IMAGETYPE') or ""
72    types = d.getVar('KERNEL_IMAGETYPES') or ""
73    if type not in types.split():
74        types = (type + ' ' + types).strip()
75    if alttype not in types.split():
76        types = (alttype + ' ' + types).strip()
77    d.setVar('KERNEL_IMAGETYPES', types)
78
79    # KERNEL_IMAGETYPES may contain a mixture of image types supported directly
80    # by the kernel build system and types which are created by post-processing
81    # the output of the kernel build system (e.g. compressing vmlinux ->
82    # vmlinux.gz in kernel_do_transform_kernel()).
83    # KERNEL_IMAGETYPE_FOR_MAKE should contain only image types supported
84    # directly by the kernel build system.
85    if not d.getVar('KERNEL_IMAGETYPE_FOR_MAKE'):
86        typeformake = set()
87        for type in types.split():
88            if type == 'vmlinux.gz':
89                type = 'vmlinux'
90            typeformake.add(type)
91
92        d.setVar('KERNEL_IMAGETYPE_FOR_MAKE', ' '.join(sorted(typeformake)))
93
94    kname = d.getVar('KERNEL_PACKAGE_NAME') or "kernel"
95    imagedest = d.getVar('KERNEL_IMAGEDEST')
96
97    for type in types.split():
98        if bb.data.inherits_class('nopackages', d):
99            continue
100        typelower = type.lower()
101        d.appendVar('PACKAGES', ' %s-image-%s' % (kname, typelower))
102        d.setVar('FILES:' + kname + '-image-' + typelower, '/' + imagedest + '/' + type + '-${KERNEL_VERSION_NAME}' + ' /' + imagedest + '/' + type)
103        d.appendVar('RDEPENDS:%s-image' % kname, ' %s-image-%s (= ${EXTENDPKGV})' % (kname, typelower))
104        splitmods = d.getVar("KERNEL_SPLIT_MODULES")
105        if splitmods != '1':
106            d.appendVar('RDEPENDS:%s-image' % kname, ' %s-modules (= ${EXTENDPKGV})' % kname)
107            d.appendVar('RDEPENDS:%s-image-%s' % (kname, typelower), ' %s-modules-${KERNEL_VERSION_PKG_NAME} (= ${EXTENDPKGV})' % kname)
108            d.setVar('PKG:%s-modules' % kname, '%s-modules-${KERNEL_VERSION_PKG_NAME}' % kname)
109            d.appendVar('RPROVIDES:%s-modules' % kname, '%s-modules-${KERNEL_VERSION_PKG_NAME}' % kname)
110
111        d.setVar('PKG:%s-image-%s' % (kname,typelower), '%s-image-%s-${KERNEL_VERSION_PKG_NAME}' % (kname, typelower))
112        d.setVar('ALLOW_EMPTY:%s-image-%s' % (kname, typelower), '1')
113        d.setVar('pkg_postinst:%s-image-%s' % (kname,typelower), """set +e
114if [ -n "$D" ]; then
115    ln -sf %s-${KERNEL_VERSION} $D/${KERNEL_IMAGEDEST}/%s > /dev/null 2>&1
116else
117    ln -sf %s-${KERNEL_VERSION} ${KERNEL_IMAGEDEST}/%s > /dev/null 2>&1
118    if [ $? -ne 0 ]; then
119        echo "Filesystem on ${KERNEL_IMAGEDEST}/ doesn't support symlinks, falling back to copied image (%s)."
120        install -m 0644 ${KERNEL_IMAGEDEST}/%s-${KERNEL_VERSION} ${KERNEL_IMAGEDEST}/%s
121    fi
122fi
123set -e
124""" % (type, type, type, type, type, type, type))
125        d.setVar('pkg_postrm:%s-image-%s' % (kname,typelower), """set +e
126if [ -f "${KERNEL_IMAGEDEST}/%s" -o -L "${KERNEL_IMAGEDEST}/%s" ]; then
127    rm -f ${KERNEL_IMAGEDEST}/%s  > /dev/null 2>&1
128fi
129set -e
130""" % (type, type, type))
131
132
133    image = d.getVar('INITRAMFS_IMAGE')
134    # If the INTIRAMFS_IMAGE is set but the INITRAMFS_IMAGE_BUNDLE is set to 0,
135    # the do_bundle_initramfs does nothing, but the INITRAMFS_IMAGE is built
136    # standalone for use by wic and other tools.
137    if image:
138        if d.getVar('INITRAMFS_MULTICONFIG'):
139            d.appendVarFlag('do_bundle_initramfs', 'mcdepends', ' mc::${INITRAMFS_MULTICONFIG}:${INITRAMFS_IMAGE}:do_image_complete')
140        else:
141            d.appendVarFlag('do_bundle_initramfs', 'depends', ' ${INITRAMFS_IMAGE}:do_image_complete')
142    if image and bb.utils.to_boolean(d.getVar('INITRAMFS_IMAGE_BUNDLE')):
143        bb.build.addtask('do_transform_bundled_initramfs', 'do_deploy', 'do_bundle_initramfs', d)
144
145    # NOTE: setting INITRAMFS_TASK is for backward compatibility
146    #       The preferred method is to set INITRAMFS_IMAGE, because
147    #       this INITRAMFS_TASK has circular dependency problems
148    #       if the initramfs requires kernel modules
149    image_task = d.getVar('INITRAMFS_TASK')
150    if image_task:
151        d.appendVarFlag('do_configure', 'depends', ' ${INITRAMFS_TASK}')
152}
153
154# Here we pull in all various kernel image types which we support.
155#
156# In case you're wondering why kernel.bbclass inherits the other image
157# types instead of the other way around, the reason for that is to
158# maintain compatibility with various currently existing meta-layers.
159# By pulling in the various kernel image types here, we retain the
160# original behavior of kernel.bbclass, so no meta-layers should get
161# broken.
162#
163# KERNEL_CLASSES by default pulls in kernel-uimage.bbclass, since this
164# used to be the default behavior when only uImage was supported. This
165# variable can be appended by users who implement support for new kernel
166# image types.
167
168KERNEL_CLASSES ?= " kernel-uimage "
169inherit ${KERNEL_CLASSES}
170
171# Old style kernels may set ${S} = ${WORKDIR}/git for example
172# We need to move these over to STAGING_KERNEL_DIR. We can't just
173# create the symlink in advance as the git fetcher can't cope with
174# the symlink.
175do_unpack[cleandirs] += " ${S} ${STAGING_KERNEL_DIR} ${B} ${STAGING_KERNEL_BUILDDIR}"
176do_clean[cleandirs] += " ${S} ${STAGING_KERNEL_DIR} ${B} ${STAGING_KERNEL_BUILDDIR}"
177python do_symlink_kernsrc () {
178    s = d.getVar("S")
179    if s[-1] == '/':
180        # drop trailing slash, so that os.symlink(kernsrc, s) doesn't use s as directory name and fail
181        s=s[:-1]
182    kernsrc = d.getVar("STAGING_KERNEL_DIR")
183    if s != kernsrc:
184        bb.utils.mkdirhier(kernsrc)
185        bb.utils.remove(kernsrc, recurse=True)
186        if d.getVar("EXTERNALSRC"):
187            # With EXTERNALSRC S will not be wiped so we can symlink to it
188            os.symlink(s, kernsrc)
189        else:
190            import shutil
191            shutil.move(s, kernsrc)
192            os.symlink(kernsrc, s)
193}
194# do_patch is normally ordered before do_configure, but
195# externalsrc.bbclass deletes do_patch, breaking the dependency of
196# do_configure on do_symlink_kernsrc.
197addtask symlink_kernsrc before do_patch do_configure after do_unpack
198
199inherit kernel-arch deploy
200
201PACKAGES_DYNAMIC += "^${KERNEL_PACKAGE_NAME}-module-.*"
202PACKAGES_DYNAMIC += "^${KERNEL_PACKAGE_NAME}-image-.*"
203PACKAGES_DYNAMIC += "^${KERNEL_PACKAGE_NAME}-firmware-.*"
204
205export OS = "${TARGET_OS}"
206export CROSS_COMPILE = "${TARGET_PREFIX}"
207
208KERNEL_RELEASE ?= "${KERNEL_VERSION}"
209
210# The directory where built kernel lies in the kernel tree
211KERNEL_OUTPUT_DIR ?= "arch/${ARCH}/boot"
212KERNEL_IMAGEDEST ?= "boot"
213
214#
215# configuration
216#
217export CMDLINE_CONSOLE = "console=${@d.getVar("KERNEL_CONSOLE") or "ttyS0"}"
218
219KERNEL_VERSION = "${@get_kernelversion_headers('${B}')}"
220
221# kernels are generally machine specific
222PACKAGE_ARCH = "${MACHINE_ARCH}"
223
224# U-Boot support
225UBOOT_ENTRYPOINT ?= "20008000"
226UBOOT_LOADADDRESS ?= "${UBOOT_ENTRYPOINT}"
227
228# Some Linux kernel configurations need additional parameters on the command line
229KERNEL_EXTRA_ARGS ?= ""
230
231EXTRA_OEMAKE += ' CC="${KERNEL_CC}" LD="${KERNEL_LD}"'
232EXTRA_OEMAKE += ' HOSTCC="${BUILD_CC}" HOSTCFLAGS="${BUILD_CFLAGS}" HOSTLDFLAGS="${BUILD_LDFLAGS}" HOSTCPP="${BUILD_CPP}"'
233EXTRA_OEMAKE += ' HOSTCXX="${BUILD_CXX}" HOSTCXXFLAGS="${BUILD_CXXFLAGS}" PAHOLE=false'
234
235KERNEL_ALT_IMAGETYPE ??= ""
236
237copy_initramfs() {
238	echo "Copying initramfs into ./usr ..."
239	# In case the directory is not created yet from the first pass compile:
240	mkdir -p ${B}/usr
241	# Find and use the first initramfs image archive type we find
242	rm -f ${B}/usr/${INITRAMFS_IMAGE_NAME}.cpio
243	for img in cpio cpio.gz cpio.lz4 cpio.lzo cpio.lzma cpio.xz cpio.zst; do
244		if [ -e "${INITRAMFS_DEPLOY_DIR_IMAGE}/${INITRAMFS_IMAGE_NAME}.$img" ]; then
245			cp ${INITRAMFS_DEPLOY_DIR_IMAGE}/${INITRAMFS_IMAGE_NAME}.$img ${B}/usr/.
246			case $img in
247			*gz)
248				echo "gzip decompressing image"
249				gunzip -f ${B}/usr/${INITRAMFS_IMAGE_NAME}.$img
250				break
251				;;
252			*lz4)
253				echo "lz4 decompressing image"
254				lz4 -df ${B}/usr/${INITRAMFS_IMAGE_NAME}.$img ${B}/usr/${INITRAMFS_IMAGE_NAME}.cpio
255				break
256				;;
257			*lzo)
258				echo "lzo decompressing image"
259				lzop -df ${B}/usr/${INITRAMFS_IMAGE_NAME}.$img
260				break
261				;;
262			*lzma)
263				echo "lzma decompressing image"
264				lzma -df ${B}/usr/${INITRAMFS_IMAGE_NAME}.$img
265				break
266				;;
267			*xz)
268				echo "xz decompressing image"
269				xz -df ${B}/usr/${INITRAMFS_IMAGE_NAME}.$img
270				break
271				;;
272			*zst)
273				echo "zst decompressing image"
274				zstd -df ${B}/usr/${INITRAMFS_IMAGE_NAME}.$img
275				break
276				;;
277			esac
278			break
279		fi
280	done
281	# Verify that the above loop found a initramfs, fail otherwise
282	[ -f ${B}/usr/${INITRAMFS_IMAGE_NAME}.cpio ] && echo "Finished copy of initramfs into ./usr" || die "Could not find any ${INITRAMFS_DEPLOY_DIR_IMAGE}/${INITRAMFS_IMAGE_NAME}.cpio{.gz|.lz4|.lzo|.lzma|.xz|.zst) for bundling; INITRAMFS_IMAGE_NAME might be wrong."
283}
284
285do_bundle_initramfs () {
286	if [ ! -z "${INITRAMFS_IMAGE}" -a x"${INITRAMFS_IMAGE_BUNDLE}" = x1 ]; then
287		echo "Creating a kernel image with a bundled initramfs..."
288		copy_initramfs
289		# Backing up kernel image relies on its type(regular file or symbolic link)
290		tmp_path=""
291		for imageType in ${KERNEL_IMAGETYPE_FOR_MAKE} ; do
292			if [ -h ${KERNEL_OUTPUT_DIR}/$imageType ] ; then
293				linkpath=`readlink -n ${KERNEL_OUTPUT_DIR}/$imageType`
294				realpath=`readlink -fn ${KERNEL_OUTPUT_DIR}/$imageType`
295				mv -f $realpath $realpath.bak
296				tmp_path=$tmp_path" "$imageType"#"$linkpath"#"$realpath
297			elif [ -f ${KERNEL_OUTPUT_DIR}/$imageType ]; then
298				mv -f ${KERNEL_OUTPUT_DIR}/$imageType ${KERNEL_OUTPUT_DIR}/$imageType.bak
299				tmp_path=$tmp_path" "$imageType"##"
300			fi
301		done
302		use_alternate_initrd=CONFIG_INITRAMFS_SOURCE=${B}/usr/${INITRAMFS_IMAGE_NAME}.cpio
303		kernel_do_compile
304		# Restoring kernel image
305		for tp in $tmp_path ; do
306			imageType=`echo $tp|cut -d "#" -f 1`
307			linkpath=`echo $tp|cut -d "#" -f 2`
308			realpath=`echo $tp|cut -d "#" -f 3`
309			if [ -n "$realpath" ]; then
310				mv -f $realpath $realpath.initramfs
311				mv -f $realpath.bak $realpath
312				ln -sf $linkpath.initramfs ${B}/${KERNEL_OUTPUT_DIR}/$imageType.initramfs
313			else
314				mv -f ${KERNEL_OUTPUT_DIR}/$imageType ${KERNEL_OUTPUT_DIR}/$imageType.initramfs
315				mv -f ${KERNEL_OUTPUT_DIR}/$imageType.bak ${KERNEL_OUTPUT_DIR}/$imageType
316			fi
317		done
318	fi
319}
320do_bundle_initramfs[dirs] = "${B}"
321
322kernel_do_transform_bundled_initramfs() {
323        # vmlinux.gz is not built by kernel
324	if (echo "${KERNEL_IMAGETYPES}" | grep -wq "vmlinux\.gz"); then
325		gzip -9cn < ${KERNEL_OUTPUT_DIR}/vmlinux.initramfs > ${KERNEL_OUTPUT_DIR}/vmlinux.gz.initramfs
326        fi
327}
328do_transform_bundled_initramfs[dirs] = "${B}"
329
330python do_devshell:prepend () {
331    os.environ["LDFLAGS"] = ''
332}
333
334addtask bundle_initramfs after do_install before do_deploy
335
336KERNEL_DEBUG_TIMESTAMPS ??= "0"
337
338kernel_do_compile() {
339	unset CFLAGS CPPFLAGS CXXFLAGS LDFLAGS MACHINE
340
341	# setup native pkg-config variables (kconfig scripts call pkg-config directly, cannot generically be overriden to pkg-config-native)
342	export PKG_CONFIG_DIR="${STAGING_DIR_NATIVE}${libdir_native}/pkgconfig"
343	export PKG_CONFIG_PATH="$PKG_CONFIG_DIR:${STAGING_DATADIR_NATIVE}/pkgconfig"
344	export PKG_CONFIG_LIBDIR="$PKG_CONFIG_DIR"
345	export PKG_CONFIG_SYSROOT_DIR=""
346
347	if [ "${KERNEL_DEBUG_TIMESTAMPS}" != "1" ]; then
348		# kernel sources do not use do_unpack, so SOURCE_DATE_EPOCH may not
349		# be set....
350		if [ "${SOURCE_DATE_EPOCH}" = "" -o "${SOURCE_DATE_EPOCH}" = "0" ]; then
351			# The source directory is not necessarily a git repository, so we
352			# specify the git-dir to ensure that git does not query a
353			# repository in any parent directory.
354			SOURCE_DATE_EPOCH=`git --git-dir="${S}/.git" log -1 --pretty=%ct 2>/dev/null || echo "${REPRODUCIBLE_TIMESTAMP_ROOTFS}"`
355		fi
356
357		ts=`LC_ALL=C date -d @$SOURCE_DATE_EPOCH`
358		export KBUILD_BUILD_TIMESTAMP="$ts"
359		export KCONFIG_NOTIMESTAMP=1
360		bbnote "KBUILD_BUILD_TIMESTAMP: $ts"
361	else
362		ts=`LC_ALL=C date`
363		export KBUILD_BUILD_TIMESTAMP="$ts"
364		bbnote "KBUILD_BUILD_TIMESTAMP: $ts"
365	fi
366	# The $use_alternate_initrd is only set from
367	# do_bundle_initramfs() This variable is specifically for the
368	# case where we are making a second pass at the kernel
369	# compilation and we want to force the kernel build to use a
370	# different initramfs image.  The way to do that in the kernel
371	# is to specify:
372	# make ...args... CONFIG_INITRAMFS_SOURCE=some_other_initramfs.cpio
373	if [ "$use_alternate_initrd" = "" ] && [ "${INITRAMFS_TASK}" != "" ] ; then
374		# The old style way of copying an prebuilt image and building it
375		# is turned on via INTIRAMFS_TASK != ""
376		copy_initramfs
377		use_alternate_initrd=CONFIG_INITRAMFS_SOURCE=${B}/usr/${INITRAMFS_IMAGE_NAME}.cpio
378	fi
379	for typeformake in ${KERNEL_IMAGETYPE_FOR_MAKE} ; do
380		oe_runmake ${typeformake} ${KERNEL_EXTRA_ARGS} $use_alternate_initrd
381	done
382}
383
384kernel_do_transform_kernel() {
385	# vmlinux.gz is not built by kernel
386	if (echo "${KERNEL_IMAGETYPES}" | grep -wq "vmlinux\.gz"); then
387		mkdir -p "${KERNEL_OUTPUT_DIR}"
388		gzip -9cn < ${B}/vmlinux > "${KERNEL_OUTPUT_DIR}/vmlinux.gz"
389	fi
390}
391do_transform_kernel[dirs] = "${B}"
392addtask transform_kernel after do_compile before do_install
393
394do_compile_kernelmodules() {
395	unset CFLAGS CPPFLAGS CXXFLAGS LDFLAGS MACHINE
396	if [ "${KERNEL_DEBUG_TIMESTAMPS}" != "1" ]; then
397		# kernel sources do not use do_unpack, so SOURCE_DATE_EPOCH may not
398		# be set....
399		if [ "${SOURCE_DATE_EPOCH}" = "" -o "${SOURCE_DATE_EPOCH}" = "0" ]; then
400			# The source directory is not necessarily a git repository, so we
401			# specify the git-dir to ensure that git does not query a
402			# repository in any parent directory.
403			SOURCE_DATE_EPOCH=`git --git-dir="${S}/.git" log -1 --pretty=%ct 2>/dev/null || echo "${REPRODUCIBLE_TIMESTAMP_ROOTFS}"`
404		fi
405
406		ts=`LC_ALL=C date -d @$SOURCE_DATE_EPOCH`
407		export KBUILD_BUILD_TIMESTAMP="$ts"
408		export KCONFIG_NOTIMESTAMP=1
409		bbnote "KBUILD_BUILD_TIMESTAMP: $ts"
410	else
411		ts=`LC_ALL=C date`
412		export KBUILD_BUILD_TIMESTAMP="$ts"
413		bbnote "KBUILD_BUILD_TIMESTAMP: $ts"
414	fi
415	if (grep -q -i -e '^CONFIG_MODULES=y$' ${B}/.config); then
416		oe_runmake -C ${B} ${PARALLEL_MAKE} modules ${KERNEL_EXTRA_ARGS}
417
418		# Module.symvers gets updated during the
419		# building of the kernel modules. We need to
420		# update this in the shared workdir since some
421		# external kernel modules has a dependency on
422		# other kernel modules and will look at this
423		# file to do symbol lookups
424		cp ${B}/Module.symvers ${STAGING_KERNEL_BUILDDIR}/
425		# 5.10+ kernels have module.lds that we need to copy for external module builds
426		if [ -e "${B}/scripts/module.lds" ]; then
427			install -Dm 0644 ${B}/scripts/module.lds ${STAGING_KERNEL_BUILDDIR}/scripts/module.lds
428		fi
429	else
430		bbnote "no modules to compile"
431	fi
432}
433addtask compile_kernelmodules after do_compile before do_strip
434
435kernel_do_install() {
436	#
437	# First install the modules
438	#
439	unset CFLAGS CPPFLAGS CXXFLAGS LDFLAGS MACHINE
440	if (grep -q -i -e '^CONFIG_MODULES=y$' .config); then
441		oe_runmake DEPMOD=echo MODLIB=${D}${nonarch_base_libdir}/modules/${KERNEL_VERSION} INSTALL_FW_PATH=${D}${nonarch_base_libdir}/firmware modules_install
442		rm "${D}${nonarch_base_libdir}/modules/${KERNEL_VERSION}/build"
443		rm "${D}${nonarch_base_libdir}/modules/${KERNEL_VERSION}/source"
444		# Remove empty module directories to prevent QA issues
445		find "${D}${nonarch_base_libdir}/modules/${KERNEL_VERSION}/kernel" -type d -empty -delete
446	else
447		bbnote "no modules to install"
448	fi
449
450	#
451	# Install various kernel output (zImage, map file, config, module support files)
452	#
453	install -d ${D}/${KERNEL_IMAGEDEST}
454
455	#
456	# When including an initramfs bundle inside a FIT image, the fitImage is created after the install task
457	# by do_assemble_fitimage_initramfs.
458	# This happens after the generation of the initramfs bundle (done by do_bundle_initramfs).
459	# So, at the level of the install task we should not try to install the fitImage. fitImage is still not
460	# generated yet.
461	# After the generation of the fitImage, the deploy task copies the fitImage from the build directory to
462	# the deploy folder.
463	#
464
465	for imageType in ${KERNEL_IMAGETYPES} ; do
466		if [ $imageType != "fitImage" ] || [ "${INITRAMFS_IMAGE_BUNDLE}" != "1" ] ; then
467			install -m 0644 ${KERNEL_OUTPUT_DIR}/$imageType ${D}/${KERNEL_IMAGEDEST}/$imageType-${KERNEL_VERSION}
468		fi
469	done
470
471	install -m 0644 System.map ${D}/${KERNEL_IMAGEDEST}/System.map-${KERNEL_VERSION}
472	install -m 0644 .config ${D}/${KERNEL_IMAGEDEST}/config-${KERNEL_VERSION}
473	install -m 0644 vmlinux ${D}/${KERNEL_IMAGEDEST}/vmlinux-${KERNEL_VERSION}
474	[ -e Module.symvers ] && install -m 0644 Module.symvers ${D}/${KERNEL_IMAGEDEST}/Module.symvers-${KERNEL_VERSION}
475	install -d ${D}${sysconfdir}/modules-load.d
476	install -d ${D}${sysconfdir}/modprobe.d
477}
478
479# Must be ran no earlier than after do_kernel_checkout or else Makefile won't be in ${S}/Makefile
480do_kernel_version_sanity_check() {
481	if [ "x${KERNEL_VERSION_SANITY_SKIP}" = "x1" ]; then
482		exit 0
483	fi
484
485	# The Makefile determines the kernel version shown at runtime
486	# Don't use KERNEL_VERSION because the headers it grabs the version from aren't generated until do_compile
487	VERSION=$(grep "^VERSION =" ${S}/Makefile | sed s/.*=\ *//)
488	PATCHLEVEL=$(grep "^PATCHLEVEL =" ${S}/Makefile | sed s/.*=\ *//)
489	SUBLEVEL=$(grep "^SUBLEVEL =" ${S}/Makefile | sed s/.*=\ *//)
490	EXTRAVERSION=$(grep "^EXTRAVERSION =" ${S}/Makefile | sed s/.*=\ *//)
491
492	# Build a string for regex and a plain version string
493	reg="^${VERSION}\.${PATCHLEVEL}"
494	vers="${VERSION}.${PATCHLEVEL}"
495	if [ -n "${SUBLEVEL}" ]; then
496		# Ignoring a SUBLEVEL of zero is fine
497		if [ "${SUBLEVEL}" = "0" ]; then
498			reg="${reg}(\.${SUBLEVEL})?"
499		else
500			reg="${reg}\.${SUBLEVEL}"
501			vers="${vers}.${SUBLEVEL}"
502		fi
503	fi
504	vers="${vers}${EXTRAVERSION}"
505	reg="${reg}${EXTRAVERSION}"
506
507	if [ -z `echo ${PV} | grep -E "${reg}"` ]; then
508		bbfatal "Package Version (${PV}) does not match of kernel being built (${vers}). Please update the PV variable to match the kernel source or set KERNEL_VERSION_SANITY_SKIP=\"1\" in your recipe."
509	fi
510	exit 0
511}
512
513addtask shared_workdir after do_compile before do_compile_kernelmodules
514addtask shared_workdir_setscene
515
516do_shared_workdir_setscene () {
517	exit 1
518}
519
520emit_depmod_pkgdata() {
521	# Stash data for depmod
522	install -d ${PKGDESTWORK}/${KERNEL_PACKAGE_NAME}-depmod/
523	echo "${KERNEL_VERSION}" > ${PKGDESTWORK}/${KERNEL_PACKAGE_NAME}-depmod/${KERNEL_PACKAGE_NAME}-abiversion
524	cp ${B}/System.map ${PKGDESTWORK}/${KERNEL_PACKAGE_NAME}-depmod/System.map-${KERNEL_VERSION}
525}
526
527PACKAGEFUNCS += "emit_depmod_pkgdata"
528
529do_shared_workdir[cleandirs] += " ${STAGING_KERNEL_BUILDDIR}"
530do_shared_workdir () {
531	cd ${B}
532
533	kerneldir=${STAGING_KERNEL_BUILDDIR}
534	install -d $kerneldir
535
536	#
537	# Store the kernel version in sysroots for module-base.bbclass
538	#
539
540	echo "${KERNEL_VERSION}" > $kerneldir/${KERNEL_PACKAGE_NAME}-abiversion
541
542	# Copy files required for module builds
543	cp System.map $kerneldir/System.map-${KERNEL_VERSION}
544	[ -e Module.symvers ] && cp Module.symvers $kerneldir/
545	cp .config $kerneldir/
546	mkdir -p $kerneldir/include/config
547	cp include/config/kernel.release $kerneldir/include/config/kernel.release
548	if [ -e certs/signing_key.x509 ]; then
549		# The signing_key.* files are stored in the certs/ dir in
550		# newer Linux kernels
551		mkdir -p $kerneldir/certs
552		cp certs/signing_key.* $kerneldir/certs/
553	elif [ -e signing_key.priv ]; then
554		cp signing_key.* $kerneldir/
555	fi
556
557	# We can also copy over all the generated files and avoid special cases
558	# like version.h, but we've opted to keep this small until file creep starts
559	# to happen
560	if [ -e include/linux/version.h ]; then
561		mkdir -p $kerneldir/include/linux
562		cp include/linux/version.h $kerneldir/include/linux/version.h
563	fi
564
565	# As of Linux kernel version 3.0.1, the clean target removes
566	# arch/powerpc/lib/crtsavres.o which is present in
567	# KBUILD_LDFLAGS_MODULE, making it required to build external modules.
568	if [ ${ARCH} = "powerpc" ]; then
569		if [ -e arch/powerpc/lib/crtsavres.o ]; then
570			mkdir -p $kerneldir/arch/powerpc/lib/
571			cp arch/powerpc/lib/crtsavres.o $kerneldir/arch/powerpc/lib/crtsavres.o
572		fi
573	fi
574
575	if [ -d include/generated ]; then
576		mkdir -p $kerneldir/include/generated/
577		cp -fR include/generated/* $kerneldir/include/generated/
578	fi
579
580	if [ -d arch/${ARCH}/include/generated ]; then
581		mkdir -p $kerneldir/arch/${ARCH}/include/generated/
582		cp -fR arch/${ARCH}/include/generated/* $kerneldir/arch/${ARCH}/include/generated/
583	fi
584
585	if (grep -q -i -e '^CONFIG_UNWINDER_ORC=y$' $kerneldir/.config); then
586		# With CONFIG_UNWINDER_ORC (the default in 4.14), objtool is required for
587		# out-of-tree modules to be able to generate object files.
588		if [ -x tools/objtool/objtool ]; then
589			mkdir -p ${kerneldir}/tools/objtool
590			cp tools/objtool/objtool ${kerneldir}/tools/objtool/
591		fi
592	fi
593
594	# When building with CONFIG_MODVERSIONS=y and CONFIG_RANDSTRUCT=y we need
595	# to copy the build assets generated for the randstruct seed to
596	# STAGING_KERNEL_BUILDDIR, otherwise the out-of-tree modules build will
597	# generate those assets which will result in a different
598	# RANDSTRUCT_HASHED_SEED
599	if [ -d scripts/basic ]; then
600		mkdir -p ${kerneldir}/scripts
601		cp -r scripts/basic ${kerneldir}/scripts
602	fi
603
604	if [ -d scripts/gcc-plugins ]; then
605		mkdir -p ${kerneldir}/scripts
606		cp -r scripts/gcc-plugins ${kerneldir}/scripts
607	fi
608
609}
610
611# We don't need to stage anything, not the modules/firmware since those would clash with linux-firmware
612SYSROOT_DIRS = ""
613
614KERNEL_CONFIG_COMMAND ?= "oe_runmake_call -C ${S} O=${B} olddefconfig || oe_runmake -C ${S} O=${B} oldnoconfig"
615
616python check_oldest_kernel() {
617    oldest_kernel = d.getVar('OLDEST_KERNEL')
618    kernel_version = d.getVar('KERNEL_VERSION')
619    tclibc = d.getVar('TCLIBC')
620    if tclibc == 'glibc':
621        kernel_version = kernel_version.split('-', 1)[0]
622        if oldest_kernel and kernel_version:
623            if bb.utils.vercmp_string(kernel_version, oldest_kernel) < 0:
624                bb.warn('%s: OLDEST_KERNEL is "%s" but the version of the kernel you are building is "%s" - therefore %s as built may not be compatible with this kernel. Either set OLDEST_KERNEL to an older version, or build a newer kernel.' % (d.getVar('PN'), oldest_kernel, kernel_version, tclibc))
625}
626
627check_oldest_kernel[vardepsexclude] += "OLDEST_KERNEL KERNEL_VERSION"
628do_configure[prefuncs] += "check_oldest_kernel"
629
630kernel_do_configure() {
631	# fixes extra + in /lib/modules/2.6.37+
632	# $ scripts/setlocalversion . => +
633	# $ make kernelversion => 2.6.37
634	# $ make kernelrelease => 2.6.37+
635	touch ${B}/.scmversion ${S}/.scmversion
636
637	if [ "${S}" != "${B}" ] && [ -f "${S}/.config" ] && [ ! -f "${B}/.config" ]; then
638		mv "${S}/.config" "${B}/.config"
639	fi
640
641	# Copy defconfig to .config if .config does not exist. This allows
642	# recipes to manage the .config themselves in do_configure:prepend().
643	if [ -f "${WORKDIR}/defconfig" ] && [ ! -f "${B}/.config" ]; then
644		cp "${WORKDIR}/defconfig" "${B}/.config"
645	fi
646
647	${KERNEL_CONFIG_COMMAND}
648}
649
650do_savedefconfig() {
651	bbplain "Saving defconfig to:\n${B}/defconfig"
652	oe_runmake -C ${B} savedefconfig
653}
654do_savedefconfig[nostamp] = "1"
655addtask savedefconfig after do_configure
656
657inherit cml1 pkgconfig
658
659# Need LD, HOSTLDFLAGS and more for config operations
660KCONFIG_CONFIG_COMMAND:append = " ${EXTRA_OEMAKE}"
661
662EXPORT_FUNCTIONS do_compile do_transform_kernel do_transform_bundled_initramfs do_install do_configure
663
664# kernel-base becomes kernel-${KERNEL_VERSION}
665# kernel-image becomes kernel-image-${KERNEL_VERSION}
666PACKAGES = "${KERNEL_PACKAGE_NAME} ${KERNEL_PACKAGE_NAME}-base ${KERNEL_PACKAGE_NAME}-vmlinux ${KERNEL_PACKAGE_NAME}-image ${KERNEL_PACKAGE_NAME}-dev ${KERNEL_PACKAGE_NAME}-modules ${KERNEL_PACKAGE_NAME}-dbg"
667FILES:${PN} = ""
668FILES:${KERNEL_PACKAGE_NAME}-base = "${nonarch_base_libdir}/modules/${KERNEL_VERSION}/modules.order ${nonarch_base_libdir}/modules/${KERNEL_VERSION}/modules.builtin ${nonarch_base_libdir}/modules/${KERNEL_VERSION}/modules.builtin.modinfo"
669FILES:${KERNEL_PACKAGE_NAME}-image = ""
670FILES:${KERNEL_PACKAGE_NAME}-dev = "/${KERNEL_IMAGEDEST}/System.map* /${KERNEL_IMAGEDEST}/Module.symvers* /${KERNEL_IMAGEDEST}/config* ${KERNEL_SRC_PATH} ${nonarch_base_libdir}/modules/${KERNEL_VERSION}/build"
671FILES:${KERNEL_PACKAGE_NAME}-vmlinux = "/${KERNEL_IMAGEDEST}/vmlinux-${KERNEL_VERSION_NAME}"
672FILES:${KERNEL_PACKAGE_NAME}-modules = ""
673RDEPENDS:${KERNEL_PACKAGE_NAME} = "${KERNEL_PACKAGE_NAME}-base (= ${EXTENDPKGV})"
674# Allow machines to override this dependency if kernel image files are
675# not wanted in images as standard
676RRECOMMENDS:${KERNEL_PACKAGE_NAME}-base ?= "${KERNEL_PACKAGE_NAME}-image (= ${EXTENDPKGV})"
677PKG:${KERNEL_PACKAGE_NAME}-image = "${KERNEL_PACKAGE_NAME}-image-${@legitimize_package_name(d.getVar('KERNEL_VERSION'))}"
678RDEPENDS:${KERNEL_PACKAGE_NAME}-image += "${@oe.utils.conditional('KERNEL_IMAGETYPE', 'vmlinux', '${KERNEL_PACKAGE_NAME}-vmlinux (= ${EXTENDPKGV})', '', d)}"
679PKG:${KERNEL_PACKAGE_NAME}-base = "${KERNEL_PACKAGE_NAME}-${@legitimize_package_name(d.getVar('KERNEL_VERSION'))}"
680RPROVIDES:${KERNEL_PACKAGE_NAME}-base += "${KERNEL_PACKAGE_NAME}-${KERNEL_VERSION}"
681ALLOW_EMPTY:${KERNEL_PACKAGE_NAME} = "1"
682ALLOW_EMPTY:${KERNEL_PACKAGE_NAME}-base = "1"
683ALLOW_EMPTY:${KERNEL_PACKAGE_NAME}-image = "1"
684ALLOW_EMPTY:${KERNEL_PACKAGE_NAME}-modules = "1"
685DESCRIPTION:${KERNEL_PACKAGE_NAME}-modules = "Kernel modules meta package"
686
687pkg_postinst:${KERNEL_PACKAGE_NAME}-base () {
688	if [ ! -e "$D/lib/modules/${KERNEL_VERSION}" ]; then
689		mkdir -p $D/lib/modules/${KERNEL_VERSION}
690	fi
691	if [ -n "$D" ]; then
692		depmodwrapper -a -b $D ${KERNEL_VERSION}
693	else
694		depmod -a ${KERNEL_VERSION}
695	fi
696}
697
698PACKAGESPLITFUNCS:prepend = "split_kernel_packages "
699
700python split_kernel_packages () {
701    do_split_packages(d, root='${nonarch_base_libdir}/firmware', file_regex=r'^(.*)\.(bin|fw|cis|csp|dsp)$', output_pattern='${KERNEL_PACKAGE_NAME}-firmware-%s', description='Firmware for %s', recursive=True, extra_depends='')
702}
703
704# Many scripts want to look in arch/$arch/boot for the bootable
705# image. This poses a problem for vmlinux and vmlinuz based
706# booting. This task arranges to have vmlinux and vmlinuz appear
707# in the normalized directory location.
708do_kernel_link_images() {
709	if [ ! -d "${B}/arch/${ARCH}/boot" ]; then
710		mkdir ${B}/arch/${ARCH}/boot
711	fi
712	cd ${B}/arch/${ARCH}/boot
713	ln -sf ../../../vmlinux
714	if [ -f ../../../vmlinuz ]; then
715		ln -sf ../../../vmlinuz
716	fi
717	if [ -f ../../../vmlinuz.bin ]; then
718		ln -sf ../../../vmlinuz.bin
719	fi
720	if [ -f ../../../vmlinux.64 ]; then
721		ln -sf ../../../vmlinux.64
722	fi
723}
724addtask kernel_link_images after do_compile before do_strip
725
726python do_strip() {
727    import shutil
728
729    strip = d.getVar('STRIP')
730    extra_sections = d.getVar('KERNEL_IMAGE_STRIP_EXTRA_SECTIONS')
731    kernel_image = d.getVar('B') + "/" + d.getVar('KERNEL_OUTPUT_DIR') + "/vmlinux"
732
733    if (extra_sections and kernel_image.find(d.getVar('KERNEL_IMAGEDEST') + '/vmlinux') != -1):
734        kernel_image_stripped = kernel_image + ".stripped"
735        shutil.copy2(kernel_image, kernel_image_stripped)
736        oe.package.runstrip((kernel_image_stripped, 8, strip, extra_sections))
737        bb.debug(1, "KERNEL_IMAGE_STRIP_EXTRA_SECTIONS is set, stripping sections: " + \
738            extra_sections)
739}
740do_strip[dirs] = "${B}"
741
742addtask strip before do_sizecheck after do_kernel_link_images
743
744# Support checking the kernel size since some kernels need to reside in partitions
745# with a fixed length or there is a limit in transferring the kernel to memory.
746# If more than one image type is enabled, warn on any that don't fit but only fail
747# if none fit.
748do_sizecheck() {
749	if [ ! -z "${KERNEL_IMAGE_MAXSIZE}" ]; then
750		invalid=`echo ${KERNEL_IMAGE_MAXSIZE} | sed 's/[0-9]//g'`
751		if [ -n "$invalid" ]; then
752			die "Invalid KERNEL_IMAGE_MAXSIZE: ${KERNEL_IMAGE_MAXSIZE}, should be an integer (The unit is Kbytes)"
753		fi
754		at_least_one_fits=
755		for imageType in ${KERNEL_IMAGETYPES} ; do
756			size=`du -ks ${B}/${KERNEL_OUTPUT_DIR}/$imageType | awk '{print $1}'`
757			if [ $size -gt ${KERNEL_IMAGE_MAXSIZE} ]; then
758				bbwarn "This kernel $imageType (size=$size(K) > ${KERNEL_IMAGE_MAXSIZE}(K)) is too big for your device."
759			else
760				at_least_one_fits=y
761			fi
762		done
763		if [ -z "$at_least_one_fits" ]; then
764			die "All kernel images are too big for your device. Please reduce the size of the kernel by making more of it modular."
765		fi
766	fi
767}
768do_sizecheck[dirs] = "${B}"
769
770addtask sizecheck before do_install after do_strip
771
772inherit kernel-artifact-names
773
774kernel_do_deploy() {
775	deployDir="${DEPLOYDIR}"
776	if [ -n "${KERNEL_DEPLOYSUBDIR}" ]; then
777		deployDir="${DEPLOYDIR}/${KERNEL_DEPLOYSUBDIR}"
778		mkdir "$deployDir"
779	fi
780
781	for imageType in ${KERNEL_IMAGETYPES} ; do
782		baseName=$imageType-${KERNEL_IMAGE_NAME}
783
784		if [ -s ${KERNEL_OUTPUT_DIR}/$imageType.stripped ] ; then
785			install -m 0644 ${KERNEL_OUTPUT_DIR}/$imageType.stripped $deployDir/$baseName${KERNEL_IMAGE_BIN_EXT}
786		else
787			install -m 0644 ${KERNEL_OUTPUT_DIR}/$imageType $deployDir/$baseName${KERNEL_IMAGE_BIN_EXT}
788		fi
789		if [ -n "${KERNEL_IMAGE_LINK_NAME}" ] ; then
790			ln -sf $baseName${KERNEL_IMAGE_BIN_EXT} $deployDir/$imageType-${KERNEL_IMAGE_LINK_NAME}${KERNEL_IMAGE_BIN_EXT}
791		fi
792		if [ "${KERNEL_IMAGETYPE_SYMLINK}" = "1" ] ; then
793			ln -sf $baseName${KERNEL_IMAGE_BIN_EXT} $deployDir/$imageType
794		fi
795	done
796
797	if [ ${MODULE_TARBALL_DEPLOY} = "1" ] && (grep -q -i -e '^CONFIG_MODULES=y$' .config); then
798		mkdir -p ${D}${root_prefix}/lib
799		if [ -n "${SOURCE_DATE_EPOCH}" ]; then
800			TAR_ARGS="--sort=name --clamp-mtime --mtime=@${SOURCE_DATE_EPOCH}"
801		else
802			TAR_ARGS=""
803		fi
804		TAR_ARGS="$TAR_ARGS --owner=0 --group=0"
805		tar $TAR_ARGS -cv -C ${D}${root_prefix} lib | gzip -9n > $deployDir/modules-${MODULE_TARBALL_NAME}.tgz
806
807		if [ -n "${MODULE_TARBALL_LINK_NAME}" ] ; then
808			ln -sf modules-${MODULE_TARBALL_NAME}.tgz $deployDir/modules-${MODULE_TARBALL_LINK_NAME}.tgz
809		fi
810	fi
811
812	if [ ! -z "${INITRAMFS_IMAGE}" -a x"${INITRAMFS_IMAGE_BUNDLE}" = x1 ]; then
813		for imageType in ${KERNEL_IMAGETYPES} ; do
814			if [ "$imageType" = "fitImage" ] ; then
815				continue
816			fi
817			initramfsBaseName=$imageType-${INITRAMFS_NAME}
818			install -m 0644 ${KERNEL_OUTPUT_DIR}/$imageType.initramfs $deployDir/$initramfsBaseName${KERNEL_IMAGE_BIN_EXT}
819			if [ -n "${INITRAMFS_LINK_NAME}" ] ; then
820				ln -sf $initramfsBaseName${KERNEL_IMAGE_BIN_EXT} $deployDir/$imageType-${INITRAMFS_LINK_NAME}${KERNEL_IMAGE_BIN_EXT}
821			fi
822		done
823	fi
824}
825
826# We deploy to filenames that include PKGV and PKGR, read the saved data to
827# ensure we get the right values for both
828do_deploy[prefuncs] += "read_subpackage_metadata"
829
830addtask deploy after do_populate_sysroot do_packagedata
831
832EXPORT_FUNCTIONS do_deploy
833
834# Add using Device Tree support
835inherit kernel-devicetree
836