xref: /openbmc/openbmc/poky/meta/classes-recipe/kernel-yocto.bbclass (revision c9537f57ab488bf5d90132917b0184e2527970a5)
1#
2# Copyright OpenEmbedded Contributors
3#
4# SPDX-License-Identifier: MIT
5#
6
7# remove tasks that modify the source tree in case externalsrc is inherited
8SRCTREECOVEREDTASKS += "do_validate_branches do_kernel_configcheck do_kernel_checkout do_fetch do_unpack do_patch"
9PATCH_GIT_USER_EMAIL ?= "kernel-yocto@oe"
10PATCH_GIT_USER_NAME ?= "OpenEmbedded"
11
12# The distro or local.conf should set this, but if nobody cares...
13LINUX_KERNEL_TYPE ??= "standard"
14
15# KMETA ?= ""
16KBRANCH ?= "master"
17KMACHINE ?= "${MACHINE}"
18SRCREV_FORMAT ?= "meta_machine"
19
20# LEVELS:
21#   0: no reporting
22#   1: report options that are specified, but not in the final config
23#   2: report options that are not hardware related, but set by a BSP
24KCONF_AUDIT_LEVEL ?= "1"
25KCONF_BSP_AUDIT_LEVEL ?= "0"
26KMETA_AUDIT ?= "yes"
27KMETA_AUDIT_WERROR ?= ""
28KMETA_CONFIG_FEATURES ?= ""
29
30# returns local (absolute) path names for all valid patches in the
31# src_uri
32def find_patches(d,subdir):
33    patches = src_patches(d)
34    patch_list=[]
35    for p in patches:
36        _, _, local, _, _, parm = bb.fetch.decodeurl(p)
37        # if patchdir has been passed, we won't be able to apply it so skip
38        # the patch for now, and special processing happens later
39        patchdir = ''
40        if "patchdir" in parm:
41            patchdir = parm["patchdir"]
42        if subdir:
43            if subdir == patchdir:
44                patch_list.append(local)
45        else:
46            # skip the patch if a patchdir was supplied, it won't be handled
47            # properly
48            if not patchdir:
49                patch_list.append(local)
50
51    return patch_list
52
53# returns all the elements from the src uri that are .scc files
54def find_sccs(d):
55    sources=src_patches(d, True)
56    sources_list=[]
57    for s in sources:
58        base, ext = os.path.splitext(os.path.basename(s))
59        if ext and ext in [".scc", ".cfg"]:
60            sources_list.append(s)
61        elif base and 'defconfig' in base:
62            sources_list.append(s)
63
64    return sources_list
65
66# check the SRC_URI for "kmeta" type'd git repositories and directories. Return
67# the name of the repository or directory as it will be found in UNPACKDIR
68def find_kernel_feature_dirs(d):
69    feature_dirs=[]
70    fetch = bb.fetch2.Fetch([], d)
71    for url in fetch.urls:
72        urldata = fetch.ud[url]
73        parm = urldata.parm
74        type=""
75        destdir = ""
76        if "type" in parm:
77            type = parm["type"]
78        if "destsuffix" in parm:
79            destdir = parm["destsuffix"]
80        elif urldata.type == "file":
81            destdir = urldata.basepath
82        if type == "kmeta" and destdir:
83            feature_dirs.append(destdir)
84
85    return feature_dirs
86
87# find the master/machine source branch. In the same way that the fetcher proceses
88# git repositories in the SRC_URI we take the first repo found, first branch.
89def get_machine_branch(d, default):
90    fetch = bb.fetch2.Fetch([], d)
91    for url in fetch.urls:
92        urldata = fetch.ud[url]
93        parm = urldata.parm
94        if "branch" in parm:
95            branches = urldata.parm.get("branch").split(',')
96            btype = urldata.parm.get("type")
97            if btype != "kmeta":
98                return branches[0]
99
100    return default
101
102# returns a list of all directories that are on FILESEXTRAPATHS (and
103# hence available to the build) that contain .scc or .cfg files
104def get_dirs_with_fragments(d):
105    extrapaths = []
106    extrafiles = []
107    extrapathsvalue = (d.getVar("FILESEXTRAPATHS") or "")
108    # Remove default flag which was used for checking
109    extrapathsvalue = extrapathsvalue.replace("__default:", "")
110    extrapaths = extrapathsvalue.split(":")
111    for path in extrapaths:
112        if path + ":True" not in extrafiles:
113            extrafiles.append(path + ":" + str(os.path.exists(path)))
114
115    return " ".join(extrafiles)
116
117do_kernel_metadata() {
118	set +e
119
120	if [ -n "$1" ]; then
121		mode="$1"
122	else
123		mode="patch"
124	fi
125
126	cd ${S}
127	export KMETA=${KMETA}
128
129	bbnote "do_kernel_metadata: for summary/debug, set KCONF_AUDIT_LEVEL > 0"
130
131	# if kernel tools are available in-tree, they are preferred
132	# and are placed on the path before any external tools. Unless
133	# the external tools flag is set, in that case we do nothing.
134	if [ -f "${S}/scripts/util/configme" ]; then
135		if [ -z "${EXTERNAL_KERNEL_TOOLS}" ]; then
136			PATH=${S}/scripts/util:${PATH}
137		fi
138	fi
139
140	# In a similar manner to the kernel itself:
141	#
142	#   defconfig: $(obj)/conf
143	#   ifeq ($(KBUILD_DEFCONFIG),)
144	#	$< --defconfig $(Kconfig)
145	#   else
146	#	@echo "*** Default configuration is based on '$(KBUILD_DEFCONFIG)'"
147	#	$(Q)$< --defconfig=arch/$(SRCARCH)/configs/$(KBUILD_DEFCONFIG) $(Kconfig)
148	#   endif
149	#
150	# If a defconfig is specified via the KBUILD_DEFCONFIG variable, we copy it
151	# from the source tree, into a common location and normalized "defconfig" name,
152	# where the rest of the process will include and incoroporate it into the build
153	#
154	if [ -n "${KBUILD_DEFCONFIG}" ]; then
155		if [ -f "${S}/arch/${ARCH}/configs/${KBUILD_DEFCONFIG}" ]; then
156			if [ -f "${UNPACKDIR}/defconfig" ]; then
157				# If the two defconfig's are different, warn that we overwrote the
158				# one already placed in UNPACKDIR
159				cmp "${UNPACKDIR}/defconfig" "${S}/arch/${ARCH}/configs/${KBUILD_DEFCONFIG}"
160				if [ $? -ne 0 ]; then
161					bbdebug 1 "detected SRC_URI or patched defconfig in UNPACKDIR. ${KBUILD_DEFCONFIG} copied over it"
162				fi
163			fi
164			cp -f ${S}/arch/${ARCH}/configs/${KBUILD_DEFCONFIG} ${UNPACKDIR}/defconfig
165			in_tree_defconfig="${UNPACKDIR}/defconfig"
166		else
167			bbfatal "A KBUILD_DEFCONFIG '${KBUILD_DEFCONFIG}' was specified, but not present in the source tree (${S}/arch/${ARCH}/configs/)"
168		fi
169	fi
170
171	if [ "$mode" = "patch" ]; then
172		# was anyone trying to patch the kernel meta data ?, we need to do
173		# this here, since the scc commands migrate the .cfg fragments to the
174		# kernel source tree, where they'll be used later.
175		check_git_config
176		patches="${@" ".join(find_patches(d,'kernel-meta'))}"
177		if [ -n "$patches" ]; then
178		    (
179			    cd ${UNPACKDIR}/kernel-meta
180
181			    # take the SRC_URI patches, and create a series file
182			    # this is required to support some better processing
183			    # of issues with the patches
184			    rm -f series
185			    for p in $patches; do
186				cp $p .
187				echo "$(basename $p)" >> series
188			    done
189
190			    # process the series with kgit-s2q, which is what is
191			    # handling the rest of the kernel. This allows us
192			    # more flexibility for handling failures or advanced
193			    # mergeing functinoality
194			    message=$(kgit-s2q --gen -v --patches ${UNPACKDIR}/kernel-meta 2>&1)
195			    if [ $? -ne 0 ]; then
196				# setup to try the patch again
197				kgit-s2q --prev
198				bberror "Problem applying patches to: ${UNPACKDIR}/kernel-meta"
199				bbfatal_log "\n($message)"
200			    fi
201			)
202		fi
203	fi
204
205	sccs_from_src_uri="${@" ".join(find_sccs(d))}"
206	patches="${@" ".join(find_patches(d,''))}"
207	feat_dirs="${@" ".join(find_kernel_feature_dirs(d))}"
208
209	# a quick check to make sure we don't have duplicate defconfigs If
210	# there's a defconfig in the SRC_URI, did we also have one from the
211	# KBUILD_DEFCONFIG processing above ?
212	src_uri_defconfig=$(echo $sccs_from_src_uri | awk '(match($0, "defconfig") != 0) { print $0 }' RS=' ')
213	# drop and defconfig's from the src_uri variable, we captured it just above here if it existed
214	sccs_from_src_uri=$(echo $sccs_from_src_uri | awk '(match($0, "defconfig") == 0) { print $0 }' RS=' ')
215
216	if [ -n "$in_tree_defconfig" ]; then
217		sccs_defconfig=$in_tree_defconfig
218		if [ -n "$src_uri_defconfig" ]; then
219			bbwarn "[NOTE]: defconfig was supplied both via KBUILD_DEFCONFIG and SRC_URI. Dropping SRC_URI entry $src_uri_defconfig"
220		fi
221	else
222		# if we didn't have an in-tree one, make our defconfig the one
223		# from the src_uri. Note: there may not have been one from the
224		# src_uri, so this can be an empty variable.
225		sccs_defconfig=$src_uri_defconfig
226	fi
227	sccs="$sccs_from_src_uri"
228
229	# check for feature directories/repos/branches that were part of the
230	# SRC_URI. If they were supplied, we convert them into include directives
231	# for the update part of the process
232	for f in ${feat_dirs}; do
233		if [ -d "${UNPACKDIR}/$f/kernel-meta" ]; then
234			includes="$includes -I${UNPACKDIR}/$f/kernel-meta"
235	        elif [ -d "${UNPACKDIR}/$f" ]; then
236			includes="$includes -I${UNPACKDIR}/$f"
237		fi
238	done
239	for s in ${sccs} ${patches}; do
240		sdir=$(dirname $s)
241		includes="$includes -I${sdir}"
242                # if a SRC_URI passed patch or .scc has a subdir of "kernel-meta",
243                # then we add it to the search path
244                if [ -d "${sdir}/kernel-meta" ]; then
245			includes="$includes -I${sdir}/kernel-meta"
246                fi
247	done
248
249	# allow in-tree config fragments to be used in KERNEL_FEATURES
250	includes="$includes -I${S}/arch/${ARCH}/configs -I${S}/kernel/configs"
251
252	# expand kernel features into their full path equivalents
253	bsp_definition=$(spp ${includes} --find -DKMACHINE=${KMACHINE} -DKTYPE=${LINUX_KERNEL_TYPE})
254	if [ -z "$bsp_definition" ]; then
255		if [ -z "$sccs_defconfig" ]; then
256			bbfatal_log "Could not locate BSP definition for ${KMACHINE}/${LINUX_KERNEL_TYPE} and no defconfig was provided"
257		fi
258	else
259		# if the bsp definition has "define KMETA_EXTERNAL_BSP t",
260		# then we need to set a flag that will instruct the next
261		# steps to use the BSP as both configuration and patches.
262		grep -q KMETA_EXTERNAL_BSP $bsp_definition
263		if [ $? -eq 0 ]; then
264		    KMETA_EXTERNAL_BSPS="t"
265		fi
266	fi
267	meta_dir=$(kgit --meta)
268
269	KERNEL_FEATURES_FINAL=""
270	if [ -n "${KERNEL_FEATURES}" ]; then
271		for feature in ${KERNEL_FEATURES}; do
272			feature_as_specified="$feature"
273			feature="$(echo $feature_as_specified | cut -d: -f1)"
274			feature_specifier="$(echo $feature_as_specified | cut -d: -f2)"
275			feature_found=f
276			for d in $includes; do
277				path_to_check=$(echo $d | sed 's/^-I//')
278				if [ "$feature_found" = "f" ] && [ -e "$path_to_check/$feature" ]; then
279				    feature_found=t
280				fi
281			done
282			if [ "$feature_found" = "f" ]; then
283				if [ -n "${KERNEL_DANGLING_FEATURES_WARN_ONLY}" ]; then
284				    bbwarn "Feature '$feature' not found, but KERNEL_DANGLING_FEATURES_WARN_ONLY is set"
285				    bbwarn "This may cause runtime issues, dropping feature and allowing configuration to continue"
286				else
287				    bberror "Feature '$feature' not found, this will cause configuration failures."
288				    bberror "Check the SRC_URI for meta-data repositories or directories that may be missing"
289				    bbfatal_log "Set KERNEL_DANGLING_FEATURES_WARN_ONLY to ignore this issue"
290				fi
291			else
292				KERNEL_FEATURES_FINAL="$KERNEL_FEATURES_FINAL $feature_as_specified"
293			fi
294		done
295        fi
296
297	if [ "$mode" = "config" ]; then
298		# run1: pull all the configuration fragments, no matter where they come from
299		elements="`echo -n ${bsp_definition} $sccs_defconfig ${sccs} ${patches} $KERNEL_FEATURES_FINAL`"
300		if [ -n "${elements}" ]; then
301			echo "${bsp_definition}" > ${S}/${meta_dir}/bsp_definition
302			echo "${KMETA_CONFIG_FEATURES}" | grep -q "prefer-modules"
303			if [ $? -eq 0 ]; then
304				scc_defines="-DMODULE_OR_Y=m"
305			fi
306			scc --force $scc_defines -o ${S}/${meta_dir}:cfg,merge,meta ${includes} $sccs_defconfig $bsp_definition $sccs $patches $KERNEL_FEATURES_FINAL
307			if [ $? -ne 0 ]; then
308				bbfatal_log "Could not generate configuration queue for ${KMACHINE}."
309			fi
310		fi
311	fi
312
313	# if KMETA_EXTERNAL_BSPS has been set, or it has been detected from
314	# the bsp definition, then we inject the bsp_definition into the
315	# patch phase below.  we'll piggy back on the sccs variable.
316	if [ -n "${KMETA_EXTERNAL_BSPS}" ]; then
317		sccs="${bsp_definition} ${sccs}"
318	fi
319
320	if [ "$mode" = "patch" ]; then
321		# run2: only generate patches for elements that have been passed on the SRC_URI
322		elements="`echo -n ${sccs} ${patches} $KERNEL_FEATURES_FINAL`"
323		if [ -n "${elements}" ]; then
324			scc --force -o ${S}/${meta_dir}:patch --cmds patch ${includes} ${sccs} ${patches} $KERNEL_FEATURES_FINAL
325			if [ $? -ne 0 ]; then
326				bbfatal_log "Could not generate configuration queue for ${KMACHINE}."
327			fi
328		fi
329	fi
330
331	if [ ${KCONF_AUDIT_LEVEL} -gt 0 ]; then
332		bbnote "kernel meta data summary for ${KMACHINE} (${LINUX_KERNEL_TYPE}):"
333		bbnote "======================================================================"
334		if [ -n "${KMETA_EXTERNAL_BSPS}" ]; then
335			bbnote "Non kernel-cache (external) bsp"
336		fi
337		bbnote "BSP entry point / definition: $bsp_definition"
338		if [ -n "$in_tree_defconfig" ]; then
339			bbnote "KBUILD_DEFCONFIG: ${KBUILD_DEFCONFIG}"
340		fi
341		bbnote "Fragments from SRC_URI: $sccs_from_src_uri"
342		bbnote "KERNEL_FEATURES: $KERNEL_FEATURES_FINAL"
343		bbnote "Final scc/cfg list: $sccs_defconfig $bsp_definition $sccs $KERNEL_FEATURES_FINAL"
344	fi
345
346	set -e
347}
348
349do_patch() {
350	set +e
351	cd ${S}
352
353	check_git_config
354	if [ "${KERNEL_DEBUG_TIMESTAMPS}" != "1" ]; then
355		reproducible_git_committer_author
356	fi
357	meta_dir=$(kgit --meta)
358	(cd ${meta_dir}; ln -sf patch.queue series)
359	if [ -f "${meta_dir}/series" ]; then
360		kgit_extra_args=""
361		if [ "${KERNEL_DEBUG_TIMESTAMPS}" != "1" ]; then
362		    kgit_extra_args="--commit-sha author"
363		fi
364		kgit-s2q --gen -v $kgit_extra_args --patches .kernel-meta/
365		if [ $? -ne 0 ]; then
366			bberror "Could not apply patches for ${KMACHINE}."
367			bbfatal_log "Patch failures can be resolved in the linux source directory ${S})"
368		fi
369	fi
370
371	if [ -f "${meta_dir}/merge.queue" ]; then
372		# we need to merge all these branches
373		for b in $(cat ${meta_dir}/merge.queue); do
374			git show-ref --verify --quiet refs/heads/${b}
375			if [ $? -eq 0 ]; then
376				bbnote "Merging branch ${b}"
377				git merge -q --no-ff -m "Merge branch ${b}" ${b}
378			else
379				bbfatal "branch ${b} does not exist, cannot merge"
380			fi
381		done
382	fi
383
384	set -e
385}
386
387do_kernel_checkout() {
388	set +e
389
390	source_dir=`echo ${S} | sed 's%/$%%'`
391	source_workdir="${UNPACKDIR}/git"
392	if [ -d "${UNPACKDIR}/git/" ]; then
393		# case: git repository
394		# if S is WORKDIR/git, then we shouldn't be moving or deleting the tree.
395		if [ "${source_dir}" != "${source_workdir}" ]; then
396			if [ -d "${source_workdir}/.git" ]; then
397				# regular git repository with .git
398				rm -rf ${S}
399				mv ${UNPACKDIR}/git ${S}
400			else
401				# create source for bare cloned git repository
402				git clone ${WORKDIR}/git ${S}
403				rm -rf ${UNPACKDIR}/git
404			fi
405		fi
406		cd ${S}
407
408		# convert any remote branches to local tracking ones
409		for i in `git branch -a --no-color | grep remotes | grep -v HEAD`; do
410			b=`echo $i | cut -d' ' -f2 | sed 's%remotes/origin/%%'`;
411			git show-ref --quiet --verify -- "refs/heads/$b"
412			if [ $? -ne 0 ]; then
413				git branch $b $i > /dev/null
414			fi
415		done
416
417		# Create a working tree copy of the kernel by checking out a branch
418		machine_branch="${@ get_machine_branch(d, "${KBRANCH}" )}"
419
420		# checkout and clobber any unimportant files
421		git checkout -f ${machine_branch}
422	else
423		# case: we have no git repository at all.
424		# To support low bandwidth options for building the kernel, we'll just
425		# convert the tree to a git repo and let the rest of the process work unchanged
426
427		# if ${S} hasn't been set to the proper subdirectory a default of "linux" is
428		# used, but we can't initialize that empty directory. So check it and throw a
429		# clear error
430
431	        cd ${S}
432		if [ ! -f "Makefile" ]; then
433			bberror "S is not set to the linux source directory. Check "
434			bbfatal "the recipe and set S to the proper extracted subdirectory"
435		fi
436		rm -f .gitignore
437		git init
438		check_git_config
439		if [ "${KERNEL_DEBUG_TIMESTAMPS}" != "1" ]; then
440			reproducible_git_committer_author
441		fi
442		git add .
443		git commit -q -n -m "baseline commit: creating repo for ${PN}-${PV}"
444		git clean -d -f
445	fi
446
447	set -e
448}
449do_kernel_checkout[dirs] = "${S} ${UNPACKDIR}"
450
451addtask kernel_checkout before do_kernel_metadata after do_symlink_kernsrc
452addtask kernel_metadata after do_validate_branches do_unpack before do_patch
453do_kernel_metadata[depends] = "kern-tools-native:do_populate_sysroot"
454do_kernel_metadata[file-checksums] = " ${@get_dirs_with_fragments(d)}"
455do_validate_branches[depends] = "kern-tools-native:do_populate_sysroot"
456
457# ${S} doesn't exist for us at unpack
458do_qa_unpack() {
459    return
460}
461
462do_kernel_configme[depends] += "virtual/cross-binutils:do_populate_sysroot"
463do_kernel_configme[depends] += "virtual/cross-cc:do_populate_sysroot"
464do_kernel_configme[depends] += "bc-native:do_populate_sysroot bison-native:do_populate_sysroot"
465do_kernel_configme[depends] += "kern-tools-native:do_populate_sysroot"
466do_kernel_configme[dirs] += "${S} ${B}"
467do_kernel_configme() {
468	do_kernel_metadata config
469
470	# translate the kconfig_mode into something that merge_config.sh
471	# understands
472	case ${KCONFIG_MODE} in
473		*allnoconfig)
474			config_flags="-n"
475			;;
476		*alldefconfig)
477			config_flags=""
478			;;
479		*)
480			if [ -f ${UNPACKDIR}/defconfig ]; then
481				config_flags="-n"
482			fi
483			;;
484	esac
485
486	cd ${S}
487
488	meta_dir=$(kgit --meta)
489	configs="$(scc --configs -o ${meta_dir})"
490	if [ $? -ne 0 ]; then
491		bberror "${configs}"
492		bbfatal_log "Could not find configuration queue (${meta_dir}/config.queue)"
493	fi
494
495	CFLAGS="${CFLAGS} ${TOOLCHAIN_OPTIONS}" HOSTCC="${BUILD_CC} ${BUILD_CFLAGS} ${BUILD_LDFLAGS}" HOSTCPP="${BUILD_CPP}" CC="${KERNEL_CC}" LD="${KERNEL_LD}" OBJCOPY="${KERNEL_OBJCOPY}" STRIP="${KERNEL_STRIP}" ARCH=${ARCH} merge_config.sh -O ${B} ${config_flags} ${configs} > ${meta_dir}/cfg/merge_config_build.log 2>&1
496	if [ $? -ne 0 -o ! -f ${B}/.config ]; then
497		bberror "Could not generate a .config for ${KMACHINE}-${LINUX_KERNEL_TYPE}"
498		if [ ${KCONF_AUDIT_LEVEL} -gt 1 ]; then
499			bbfatal_log "`cat ${meta_dir}/cfg/merge_config_build.log`"
500		else
501			bbfatal_log "Details can be found at: ${S}/${meta_dir}/cfg/merge_config_build.log"
502		fi
503	fi
504
505	if [ ! -z "${LINUX_VERSION_EXTENSION}" ]; then
506		echo "# Global settings from linux recipe" >> ${B}/.config
507		echo "CONFIG_LOCALVERSION="\"${LINUX_VERSION_EXTENSION}\" >> ${B}/.config
508	fi
509}
510
511addtask kernel_configme before do_configure after do_patch
512addtask config_analysis
513
514do_config_analysis[depends] = "virtual/kernel:do_configure"
515do_config_analysis[depends] += "kern-tools-native:do_populate_sysroot"
516
517CONFIG_AUDIT_FILE ?= "${WORKDIR}/config-audit.txt"
518CONFIG_ANALYSIS_FILE ?= "${WORKDIR}/config-analysis.txt"
519
520python do_config_analysis() {
521    import re, string, sys, subprocess
522
523    s = d.getVar('S')
524
525    env = os.environ.copy()
526    env['PATH'] = "%s:%s%s" % (d.getVar('PATH'), s, "/scripts/util/")
527    env['LD'] = d.getVar('KERNEL_LD')
528    env['CC'] = d.getVar('KERNEL_CC')
529    env['OBJCOPY'] = d.getVar('KERNEL_OBJCOPY')
530    env['STRIP'] = d.getVar('KERNEL_STRIP')
531    env['ARCH'] = d.getVar('ARCH')
532    env['srctree'] = s
533
534    # read specific symbols from the kernel recipe or from local.conf
535    # i.e.: CONFIG_ANALYSIS:pn-linux-yocto-dev = 'NF_CONNTRACK LOCALVERSION'
536    config = d.getVar( 'CONFIG_ANALYSIS' )
537    if not config:
538       config = [ "" ]
539    else:
540       config = config.split()
541
542    for c in config:
543        for action in ["analysis","audit"]:
544            if action == "analysis":
545                try:
546                    analysis = subprocess.check_output(['symbol_why.py', '--dotconfig',  '{}'.format( d.getVar('B') + '/.config' ), '--blame', c], cwd=s, env=env ).decode('utf-8')
547                except subprocess.CalledProcessError as e:
548                    bb.fatal( "config analysis failed when running '%s': %s" % (" ".join(e.cmd), e.output.decode('utf-8')))
549
550                outfile = d.getVar( 'CONFIG_ANALYSIS_FILE' )
551
552            if action == "audit":
553                try:
554                    analysis = subprocess.check_output(['symbol_why.py', '--dotconfig',  '{}'.format( d.getVar('B') + '/.config' ), '--summary', '--extended', '--sanity', c], cwd=s, env=env ).decode('utf-8')
555                except subprocess.CalledProcessError as e:
556                    bb.fatal( "config analysis failed when running '%s': %s" % (" ".join(e.cmd), e.output.decode('utf-8')))
557
558                outfile = d.getVar( 'CONFIG_AUDIT_FILE' )
559
560            if c:
561                outdir = os.path.dirname( outfile )
562                outname = os.path.basename( outfile )
563                outfile = outdir + '/'+ c + '-' + outname
564
565            if config and os.path.isfile(outfile):
566                os.remove(outfile)
567
568            with open(outfile, 'w+') as f:
569                f.write( analysis )
570
571            bb.warn( "Configuration {} executed, see: {} for details".format(action,outfile ))
572            if c:
573                bb.warn( analysis )
574}
575
576python do_kernel_configcheck() {
577    import re, string, sys, subprocess
578
579    audit_flag = d.getVar( "KMETA_AUDIT" )
580    if not audit_flag:
581       bb.note( "kernel config audit disabled, skipping .." )
582       return
583
584    s = d.getVar('S')
585
586    # if KMETA isn't set globally by a recipe using this routine, use kgit to
587    # locate or create the meta directory. Otherwise, kconf_check is not
588    # passed a valid meta-series for processing
589    kmeta = d.getVar("KMETA")
590    if not kmeta or not os.path.exists('{}/{}'.format(s,kmeta)):
591        kmeta = subprocess.check_output(['kgit', '--meta'], cwd=d.getVar('S')).decode('utf-8').rstrip()
592
593    env = os.environ.copy()
594    env['PATH'] = "%s:%s%s" % (d.getVar('PATH'), s, "/scripts/util/")
595    env['LD'] = d.getVar('KERNEL_LD')
596    env['CC'] = d.getVar('KERNEL_CC')
597    env['OBJCOPY'] = d.getVar('KERNEL_OBJCOPY')
598    env['STRIP'] = d.getVar('KERNEL_STRIP')
599    env['ARCH'] = d.getVar('ARCH')
600    env['srctree'] = s
601
602    try:
603        configs = subprocess.check_output(['scc', '--configs', '-o', s + '/.kernel-meta'], env=env).decode('utf-8')
604    except subprocess.CalledProcessError as e:
605        bb.fatal( "Cannot gather config fragments for audit: %s" % e.output.decode("utf-8") )
606
607    config_check_visibility = int(d.getVar("KCONF_AUDIT_LEVEL") or 0)
608    bsp_check_visibility = int(d.getVar("KCONF_BSP_AUDIT_LEVEL") or 0)
609    kmeta_audit_werror = d.getVar("KMETA_AUDIT_WERROR") or ""
610    warnings_detected = False
611
612    # if config check visibility is "1", that's the lowest level of audit. So
613    # we add the --classify option to the run, since classification will
614    # streamline the output to only report options that could be boot issues,
615    # or are otherwise required for proper operation.
616    extra_params = ""
617    if config_check_visibility == 1:
618       extra_params = "--classify"
619
620    # category #1: mismatches
621    try:
622        analysis = subprocess.check_output(['symbol_why.py', '--dotconfig',  '{}'.format( d.getVar('B') + '/.config' ), '--mismatches', extra_params], cwd=s, env=env ).decode('utf-8')
623    except subprocess.CalledProcessError as e:
624        bb.fatal( "config analysis failed when running '%s': %s" % (" ".join(e.cmd), e.output.decode('utf-8')))
625
626    if analysis:
627        outfile = "{}/{}/cfg/mismatch.txt".format( s, kmeta )
628        if os.path.isfile(outfile):
629           os.remove(outfile)
630        with open(outfile, 'w+') as f:
631            f.write( analysis )
632
633        if config_check_visibility and os.stat(outfile).st_size > 0:
634            with open (outfile, "r") as myfile:
635                results = myfile.read()
636                bb.warn( "[kernel config]: specified values did not make it into the kernel's final configuration:\n\n%s" % results)
637                warnings_detected = True
638
639    # category #2: invalid fragment elements
640    extra_params = ""
641    if bsp_check_visibility > 1:
642        extra_params = "--strict"
643    try:
644        analysis = subprocess.check_output(['symbol_why.py', '--dotconfig',  '{}'.format( d.getVar('B') + '/.config' ), '--invalid', extra_params], cwd=s, env=env ).decode('utf-8')
645    except subprocess.CalledProcessError as e:
646        bb.fatal( "config analysis failed when running '%s': %s" % (" ".join(e.cmd), e.output.decode('utf-8')))
647
648    if analysis:
649        outfile = "{}/{}/cfg/invalid.txt".format(s,kmeta)
650        if os.path.isfile(outfile):
651           os.remove(outfile)
652        with open(outfile, 'w+') as f:
653            f.write( analysis )
654
655        if bsp_check_visibility and os.stat(outfile).st_size > 0:
656            with open (outfile, "r") as myfile:
657                results = myfile.read()
658                bb.warn( "[kernel config]: This BSP contains fragments with warnings:\n\n%s" % results)
659                warnings_detected = True
660
661    # category #3: redefined options (this is pretty verbose and is debug only)
662    try:
663        analysis = subprocess.check_output(['symbol_why.py', '--dotconfig',  '{}'.format( d.getVar('B') + '/.config' ), '--sanity'], cwd=s, env=env ).decode('utf-8')
664    except subprocess.CalledProcessError as e:
665        bb.fatal( "config analysis failed when running '%s': %s" % (" ".join(e.cmd), e.output.decode('utf-8')))
666
667    if analysis:
668        outfile = "{}/{}/cfg/redefinition.txt".format(s,kmeta)
669        if os.path.isfile(outfile):
670           os.remove(outfile)
671        with open(outfile, 'w+') as f:
672            f.write( analysis )
673
674        # if the audit level is greater than two, we report if a fragment has overriden
675        # a value from a base fragment. This is really only used for new kernel introduction
676        if bsp_check_visibility > 2 and os.stat(outfile).st_size > 0:
677            with open (outfile, "r") as myfile:
678                results = myfile.read()
679                bb.warn( "[kernel config]: This BSP has configuration options defined in more than one config, with differing values:\n\n%s" % results)
680                warnings_detected = True
681
682    if warnings_detected and kmeta_audit_werror:
683        bb.fatal( "configuration warnings detected, werror is set, promoting to fatal" )
684}
685
686# Ensure that the branches (BSP and meta) are on the locations specified by
687# their SRCREV values. If they are NOT on the right commits, the branches
688# are corrected to the proper commit.
689do_validate_branches() {
690	set +e
691	cd ${S}
692
693	machine_branch="${@ get_machine_branch(d, "${KBRANCH}" )}"
694	machine_srcrev="${SRCREV_machine}"
695
696	# if SRCREV is AUTOREV it shows up as AUTOINC there's nothing to
697	# check and we can exit early
698	if [ "${machine_srcrev}" = "AUTOINC" ]; then
699	    linux_yocto_dev='${@oe.utils.conditional("PREFERRED_PROVIDER_virtual/kernel", "linux-yocto-dev", "1", "", d)}'
700	    if [ -n "$linux_yocto_dev" ]; then
701		git checkout -q -f ${machine_branch}
702		ver=$(grep "^VERSION =" ${S}/Makefile | sed s/.*=\ *//)
703		patchlevel=$(grep "^PATCHLEVEL =" ${S}/Makefile | sed s/.*=\ *//)
704		sublevel=$(grep "^SUBLEVEL =" ${S}/Makefile | sed s/.*=\ *//)
705		kver="$ver.$patchlevel"
706		bbnote "dev kernel: performing version -> branch -> SRCREV validation"
707		bbnote "dev kernel: recipe version ${LINUX_VERSION}, src version: $kver"
708		echo "${LINUX_VERSION}" | grep -q $kver
709		if [ $? -ne 0 ]; then
710		    version="$(echo ${LINUX_VERSION} | sed 's/\+.*$//g')"
711		    versioned_branch="v$version/$machine_branch"
712
713		    machine_branch=$versioned_branch
714		    force_srcrev="$(git rev-parse $machine_branch 2> /dev/null)"
715		    if [ $? -ne 0 ]; then
716			bbfatal "kernel version mismatch detected, and no valid branch $machine_branch detected"
717		    fi
718
719		    bbnote "dev kernel: adjusting branch to $machine_branch, srcrev to: $force_srcrev"
720		fi
721	    else
722		bbnote "SRCREV validation is not required for AUTOREV"
723	    fi
724	elif [ "${machine_srcrev}" = "" ]; then
725		if [ "${SRCREV}" != "AUTOINC" ] && [ "${SRCREV}" != "INVALID" ]; then
726		       # SRCREV_machine_<MACHINE> was not set. This means that a custom recipe
727		       # that doesn't use the SRCREV_FORMAT "machine_meta" is being built. In
728		       # this case, we need to reset to the give SRCREV before heading to patching
729		       bbnote "custom recipe is being built, forcing SRCREV to ${SRCREV}"
730		       force_srcrev="${SRCREV}"
731		fi
732	else
733		git cat-file -t ${machine_srcrev} > /dev/null
734		if [ $? -ne 0 ]; then
735			bberror "${machine_srcrev} is not a valid commit ID."
736			bbfatal_log "The kernel source tree may be out of sync"
737		fi
738		force_srcrev=${machine_srcrev}
739	fi
740
741	git checkout -q -f ${machine_branch}
742	if [ -n "${force_srcrev}" ]; then
743		# see if the branch we are about to patch has been properly reset to the defined
744		# SRCREV .. if not, we reset it.
745		branch_head=`git rev-parse HEAD`
746		if [ "${force_srcrev}" != "${branch_head}" ]; then
747			current_branch=`git rev-parse --abbrev-ref HEAD`
748			git branch "$current_branch-orig"
749			git reset --hard ${force_srcrev}
750			# We've checked out HEAD, make sure we cleanup kgit-s2q fence post check
751			# so the patches are applied as expected otherwise no patching
752			# would be done in some corner cases.
753			kgit-s2q --clean
754		fi
755	fi
756
757	set -e
758}
759
760OE_TERMINAL_EXPORTS += "KBUILD_OUTPUT"
761KBUILD_OUTPUT = "${B}"
762
763python () {
764    # If diffconfig is available, ensure it runs after kernel_configme
765    if 'do_diffconfig' in d:
766        bb.build.addtask('do_diffconfig', None, 'do_kernel_configme', d)
767
768    externalsrc = d.getVar('EXTERNALSRC')
769    if externalsrc:
770        # If we deltask do_patch, do_kernel_configme is left without
771        # dependencies and runs too early
772        d.setVarFlag('do_kernel_configme', 'deps', (d.getVarFlag('do_kernel_configme', 'deps', False) or []) + ['do_unpack'])
773}
774
775# extra tasks
776addtask kernel_version_sanity_check after do_kernel_metadata do_kernel_checkout before do_compile
777addtask validate_branches before do_patch after do_kernel_checkout
778addtask kernel_configcheck after do_configure before do_compile
779