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