File kernel-cachyos-bore.spec of Package kernel-cachyos-source

#
# spec file for package kernel-cachyos-bore
#
# Copyright (c) 2025 SUSE LLC
#
# All modifications and additions to the file contributed by third parties
# remain the property of their copyright owners, unless otherwise agreed
# upon. The license for this file, and modifications and additions to the
# file, is the same license as for the pristine package itself (unless the
# license for the pristine package is not an Open Source License, in which
# case the license is the MIT License). An "Open Source License" is a
# license that conforms to the Open Source Definition (Version 1.9)
# published by the Open Source Initiative.

# Please submit bugfixes or comments via https://bugs.opensuse.org/
#
# needssslcertforbuild

%define srcversion 7.0-rc6
%define patchversion 7.0.0-rc6
%define cachyos_tag cachyos-7.0-rc6-1
%define git_commit 5f7e4b61c73f9d3698515ab8c374dc43283ba60b
%define compress_modules zstd
%define compress_vmlinux xz
%if 0%{?build_nvidia}
# NVIDIA open kernel modules
%define nv_ver 595.58.03
%define nv_open_pkg NVIDIA-kernel-module-source-%{nv_ver}
%endif
%if 0%{?build_rtl8125}
%define rtl8125_ver 9.016.01
%define rtl8125_dir rtl8125-%{rtl8125_ver}
%endif
%define sb_efi_only 0
%define split_base 0
%define split_optional 0
%define supported_modules_check 0
%define build_flavor cachyos-bore
%define variant %{nil}

%include %_sourcedir/kernel-spec-macros

%(chmod +x %_sourcedir/{guards,apply-patches,check-for-config-changes,group-source-files.pl,split-modules,modversions,kabi.pl,arch-symbols,check-module-license,splitflist,mergedep,moddep,modflist,kernel-subpackage-build})

Name:           kernel-cachyos-bore
Version:        7.0~rc6
Release:        1.0
Summary:        CachyOS Kernel with BORE scheduler (Clang/ThinLTO, general-purpose)
License:        GPL-2.0-only
Group:          System/Kernel
URL:            https://github.com/CachyOS/linux
%if 0%{?suse_version} > 1500 || 0%{?sle_version} > 150300
BuildRequires:  bash-sh
%endif
BuildRequires:  lzop
BuildRequires:  bc
BuildRequires:  bison
BuildRequires:  coreutils
BuildRequires:  fdupes
BuildRequires:  flex

BuildRequires:  hmaccalc
BuildRequires:  libopenssl-devel
BuildRequires:  modutils
BuildRequires:  python3-base
# Used to sign the kernel in the buildservice
BuildRequires:  openssl
BuildRequires:  pesign-obs-integration
%if 0%{?suse_version} > 1500 || 0%{?sle_version} >= 150300
# pahole for CONFIG_DEBUG_INFO_BTF
BuildRequires:  dwarves >= 1.22
%endif
# Clang/LLVM toolchain for build
BuildRequires:  clang
BuildRequires:  lld
BuildRequires:  llvm
# for objtool
BuildRequires:  libelf-devel
# part of elfutils not shipped on SLE 12
%if 0%{?suse_version} >= 1500
# for gendwarfksyms
BuildRequires:  libdw-devel
%endif
# required for 50-check-kernel-build-id rpm check
BuildRequires:  elfutils
# for perf tool
BuildRequires:  audit-devel
BuildRequires:  binutils-devel
BuildRequires:  libcap-devel
BuildRequires:  libnuma-devel
BuildRequires:  libunwind-devel
BuildRequires:  python3-devel
BuildRequires:  python3-setuptools
BuildRequires:  slang-devel
BuildRequires:  libtraceevent-devel
BuildRequires:  asciidoc
BuildRequires:  xmlto
BuildRequires:  zlib-devel
BuildRequires:  libdebuginfod-devel
BuildRequires:  systemtap-sdt-devel
BuildRequires:  libpfm-devel

# Do not install p-b and dracut for the install check, the %post script is
# able to handle this
#!BuildIgnore: perl-Bootloader dracut distribution-release suse-kernel-rpm-scriptlets
# Remove some packages that are installed automatically by the build system,
# but are not needed to build the kernel
#!BuildIgnore: autoconf automake gettext-runtime libtool cvs gettext-tools udev insserv

%define image vmlinuz
%define install_vdso 1
%if 0%{?suse_version} > 1500 || 0%{?sle_version} >= 150500
%define separate_vdso 1
%endif

%define src_install_dir /usr/src/linux-%kernelrelease%variant
%define obj_install_dir /usr/src/linux-%kernelrelease%variant-obj
%define rpm_install_dir %buildroot%obj_install_dir
%define kernel_build_dir %my_builddir/%{cachyos_tag}/linux-obj
%define modules_dir %kernel_module_directory/%kernelrelease-%build_flavor

%global cpu_arch %(%_sourcedir/arch-symbols %_target_cpu)
%define cpu_arch_flavor %cpu_arch/%build_flavor

# Define some CONFIG variables as rpm macros as well. (rpm cannot handle
# defining them all at once.)
%define config_vars CONFIG_MODULES CONFIG_MODULE_SIG CONFIG_MODULE_SIG_HASH CONFIG_KMSG_IDS CONFIG_SUSE_KERNEL_SUPPORTED CONFIG_EFI_STUB CONFIG_DEBUG_INFO_BTF_MODULES CONFIG_PREEMPT_DYNAMIC
%{expand:%(eval "$(test -n "%cpu_arch_flavor" && tar -xjf %_sourcedir/config.tar.bz2 --to-stdout config/%cpu_arch_flavor)"; for config in %config_vars; do echo "%%global $config ${!config:-n}"; done)}
%define split_extra ("%CONFIG_MODULES" == "y" && "%CONFIG_SUSE_KERNEL_SUPPORTED" == "y")

%global certs %( space="" ; for f in %_sourcedir/*.crt; do                                              \
    if ! test -e "$f"; then                                                                             \
        continue                                                                                        \
    fi                                                                                                  \
    h=$(openssl x509 -inform PEM -fingerprint -noout -in "$f")                                          \
    if [ -z "$h" ] ; then                                                                               \
        echo Cannot parse "$f" >&2                                                                      \
        continue                                                                                        \
    fi                                                                                                  \
    cert=$(echo "$h" | sed -rn 's/^SHA1 Fingerprint=//; T; s/://g; s/(.{8}).*/\\1/p')                   \
    echo Found signing certificate "$f" "($cert)" >&2                                                   \
    cat "$f" >>%_sourcedir/.kernel_signing_key.pem                                                      \
    mkdir -p %_sourcedir/.kernel_signing_certs                                                          \
    openssl x509 -inform PEM -in "$f" -outform DER -out %_sourcedir/.kernel_signing_certs/"$cert".crt   \
    echo -n "$space$cert" ; space=" "                                                                   \
done )

Source0:        https://github.com/CachyOS/linux/releases/download/%{cachyos_tag}/%{cachyos_tag}.tar.gz
Source3:        kernel-cachyos-source.rpmlintrc
Source14:       series.conf
Source16:       guards
Source17:       apply-patches
Source19:       kernel-binary-conflicts
Source20:       obsolete-kmps
Source21:       config.conf
Source23:       supported.conf
Source33:       check-for-config-changes
Source35:       group-source-files.pl
Source36:       README.PATCH-POLICY.SUSE
Source37:       README.SUSE
Source38:       README.KSYMS
Source40:       source-timestamp
Source46:       split-modules
Source47:       modversions
Source48:       macros.kernel-source
Source49:       kernel-module-subpackage
Source50:       kabi.pl
Source52:       kernel-cachyos-source%variant.changes
Source57:       kernel-cert-subpackage
Source60:       config.sh
Source63:       arch-symbols
Source65:       kernel-spec-macros
Source75:       release-projects
Source76:       check-module-license
Source78:       modules.fips
Source79:       splitflist
Source80:       mergedep
Source81:       moddep
Source82:       modflist
Source83:       kernel-subpackage-build
Source84:       kernel-subpackage-spec
Source85:       kernel-default-base.spec.txt
Source86:       old_changelog.txt
Source100:      config.tar.bz2
Source101:      config.addon.tar.bz2
Source102:      patches.arch.tar.bz2
Source103:      patches.drivers.tar.bz2
Source104:      patches.fixes.tar.bz2
Source105:      patches.rpmify.tar.bz2
Source106:      patches.suse.tar.bz2
# https://github.com/CachyOS/kernel-patches/blob/master/6.17/all/0001-cachyos-base-all.patch
# https://github.com/CachyOS/kernel-patches/blob/master/6.17/sched/0001-bore-cachy.patch
Source109:      patches.kernel.org.tar.bz2
Source110:      patches.apparmor.tar.bz2
Source111:      patches.rt.tar.bz2
Source113:      patches.kabi.tar.bz2
Source114:      patches.drm.tar.bz2
Source120:      kabi.tar.bz2
Source121:      sysctl.tar.bz2
%if 0%{?build_nvidia}
# NVIDIA open kernel module source
Source200:      https://download.nvidia.com/XFree86/NVIDIA-kernel-module-source/%{nv_open_pkg}.tar.xz
%endif
%if 0%{?build_rtl8125}
# Realtek RTL8125 2.5GbE out-of-tree driver
Source201:      https://github.com/openwrt/rtl8125/archive/refs/tags/%{rtl8125_ver}.tar.gz#/rtl8125-%{rtl8125_ver}.tar.gz
Source202:      r8125-blacklist.conf
Source203:      r8125-load.conf
%endif

# CachyOS patches
Patch0:         0001-bore-cachy.patch
Patch1:         0001-acpi-call.patch
Patch2:         0001-cgroup-vram.patch
Patch3:         0001-rt-i915.patch
Patch4:         dkms-clang.patch

# These files are found in the kernel-source package:
NoSource:       0
NoSource:       3
NoSource:       14
NoSource:       16
NoSource:       17
NoSource:       19
NoSource:       20
NoSource:       21
NoSource:       23
NoSource:       33
NoSource:       35
NoSource:       36
NoSource:       37
NoSource:       38
NoSource:       40
NoSource:       46
NoSource:       47
NoSource:       48
NoSource:       49
NoSource:       50
NoSource:       52
NoSource:       57
NoSource:       60
NoSource:       63
NoSource:       65
NoSource:       75
NoSource:       76
NoSource:       78
NoSource:       79
NoSource:       80
NoSource:       81
NoSource:       82
NoSource:       83
NoSource:       84
NoSource:       85
NoSource:       86
NoSource:       100
NoSource:       101
NoSource:       102
NoSource:       103
NoSource:       104
NoSource:       105
NoSource:       106
NoSource:       109
NoSource:       110
NoSource:       111
NoSource:       113
NoSource:       114
NoSource:       120
NoSource:       121

ExclusiveArch:  x86_64
# Do not recompute the build-id of vmlinux in find-debuginfo.sh (bsc#964063)
%undefine _unique_build_ids
%define _no_recompute_build_ids 1
# prevent usr/lib/debug/boot/vmlinux-4.12.14-11.10-default-4.12.14-11.10.ppc64le.debug
%undefine _unique_debug_names

%if "%{compress_modules}" == "zstd"
BuildRequires:  zstd
# Make sure kmod supports zstd compressed modules
Requires(post): kmod-zstd
%endif
Provides:       %name = %version-%source_rel
# bnc#901925
Provides:       %name-%version-%source_rel
Provides:       %{name}_%_target_cpu = %version-%source_rel
Provides:       kernel-base = %version-%source_rel
Provides:       multiversion(kernel)
# In SLE11, kernel-$flavor complemented kernel-$flavor-base. With SLE12,
# kernel-$flavor itself contains all the needed files and kernel-$flavor-base
# is a subset that can replace kernel-$flavor in some scenarios. We need to
# obsolete the -base subpackage from SLE11, so that the base files are not
# owned by multiple packages now. The dependency is not correct wrt openSUSE
# 11.2 - 11.4, but we primarily care about the supported upgrade path.
Obsoletes:      %name-base < 3.1
Recommends: kernel-firmware
# The following is copied to the -base subpackage as well
# BEGIN COMMON DEPS
Requires(pre):  suse-kernel-rpm-scriptlets
Requires(post): suse-kernel-rpm-scriptlets
Requires:       suse-kernel-rpm-scriptlets
Requires(preun): suse-kernel-rpm-scriptlets
Requires(postun): suse-kernel-rpm-scriptlets
Requires(pre):  coreutils awk
# For /usr/lib/module-init-tools/weak-modules2 and /usr/lib/modprobe.d/*.conf
Requires(post): suse-module-tools
Requires:       suse-module-tools
# For depmod (modutils is a dependency provided by both module-init-tools and
# kmod-compat)
Requires(post): modutils
# Use OrderWithRequires to instruct the package manager to schedule the
# installation of bootloader and dracut related tools as if they were
# required. This will ensure they're there for post scripts without hard
# requiring them. (boo#1228659, boo#1240785)
# But OrderWithRequires is not correctly implemented (bsc#1241513, bsc#1241353)
# Workaround: Add extra suggests for the ordered package
OrderWithRequires(post): udev
Suggests: udev
OrderWithRequires(post): systemd-boot
Suggests: systemd-boot
OrderWithRequires(post): perl-Bootloader
Suggests: perl-Bootloader
OrderWithRequires(post): update-bootloader
Suggests: update-bootloader
OrderWithRequires(post): dracut
Suggests: dracut
# Install the package providing /etc/SuSE-release early enough, so that
# the grub entry has correct title (bnc#757565)
Requires(post): distribution-release

%if %{usrmerged}
# make sure we have a post-usrmerge system
Conflicts:      filesystem < 16
%endif

Obsoletes:      microcode_ctl < 1.18

%{lua:	fd, err = io.open(rpm.expand('%_sourcedir') .. '/kernel-binary-conflicts')
	if not fd then io.stderr:write(err) end
	unpack = table.unpack or unpack
	for l in fd:lines() do
		if #l > 0 and l:sub(1,1) ~= '#' then
			words = {} ; for w in l:gmatch("([^%s]+)%s*") do table.insert(words, w) end
			package, version = unpack(words)
			print('Conflicts: ' .. package .. ' < '.. version .. '\n')
		end
	end
	fd:close()
}

Provides:       kernel = %version-%source_rel
Provides:       kernel-%build_flavor-base-srchash-%git_commit
Provides:       kernel-srchash-%git_commit
# END COMMON DEPS
Provides:       %name-srchash-%git_commit
Provides:       kernel-trace = 3.13
Obsoletes:      kernel-trace < 3.13
Provides:       kernel-bigsmp = 3.1
Obsoletes:      kernel-bigsmp < 3.1
Provides:       kernel-desktop = 4.3
Obsoletes:      kernel-desktop < 4.3
Provides:       kernel-xen = 4.4
Obsoletes:      kernel-xen < 4.4
Provides:       kernel-ec2 = 4.4
Obsoletes:      kernel-ec2 < 4.4
Provides:       kernel-trace-base = 3.13
Obsoletes:      kernel-trace-base < 3.13
Provides:       kernel-bigsmp-base = 3.1
Obsoletes:      kernel-bigsmp-base < 3.1
Provides:       kernel-desktop-base = 4.3
Obsoletes:      kernel-desktop-base < 4.3
Provides:       kernel-xen-base = 4.4
Obsoletes:      kernel-xen-base < 4.4
Provides:       kernel-ec2-base = 4.4
Obsoletes:      kernel-ec2-base < 4.4
%obsolete_rebuilds %name

%define kmp_target_cpu %_target_cpu

%if "%CONFIG_PREEMPT_DYNAMIC" == "y"
Provides:       kernel-preempt = %version-%release
Provides:       kernel-preempt_%_target_cpu = %version-%source_rel
%endif

%{lua:	fd, err = io.open(rpm.expand('%_sourcedir') .. '/obsolete-kmps')
	if not fd then io.stderr:write(err) end
	unpack = table.unpack or unpack
	for l in fd:lines() do
		if #l > 0 and l:sub(1,1) ~= '#' then
			words = {} ; for w in l:gmatch("([^%s]+)%s*") do table.insert(words, w) end
			package, version = unpack(words)
			print('Obsoletes: ' .. package .. '-kmp-' .. rpm.expand('%build_flavor') .. ' <= '.. version .. '\n')
			print('Provides: ' .. package .. '-kmp = ' .. version .. '.1\n')
			print('Provides: ' .. package .. '-kmp-' .. rpm.expand('%build_flavor') .. ' = '.. version .. '.1\n')
		end
	end
	fd:close()
}

%description
The CachyOS kernel with the BORE (Burst-Oriented Response Enhancer) CPU
scheduler and CachyOS performance patches. Built with Clang/LLVM and
ThinLTO for improved code generation. A general-purpose flavor suitable
for both AMD and Intel systems. NVIDIA open kernel modules and the
Realtek RTL8125 2.5GbE driver can optionally be enabled by defining
build_nvidia and build_rtl8125.


%source_timestamp

%pre
%run_if_exists /usr/lib/module-init-tools/kernel-scriptlets/rpm-pre --name "%name" \
  --version "%version" --release "%release" --kernelrelease "%kernelrelease" \
  --image "%image" --flavor "%build_flavor" --variant "%variant" \
  --usrmerged "%{usrmerged}" --certs "%certs" "$@"
%post
%run_if_exists /usr/lib/module-init-tools/kernel-scriptlets/rpm-post --name "%name" \
  --version "%version" --release "%release" --kernelrelease "%kernelrelease" \
  --image "%image" --flavor "%build_flavor" --variant "%variant" \
  --usrmerged "%{usrmerged}" --certs "%certs" "$@"
%preun
%run_if_exists /usr/lib/module-init-tools/kernel-scriptlets/rpm-preun --name "%name" \
  --version "%version" --release "%release" --kernelrelease "%kernelrelease" \
  --image "%image" --flavor "%build_flavor" --variant "%variant" \
  --usrmerged "%{usrmerged}" --certs "%certs" "$@"
%postun
%run_if_exists /usr/lib/module-init-tools/kernel-scriptlets/rpm-postun --name "%name" \
  --version "%version" --release "%release" --kernelrelease "%kernelrelease" \
  --image "%image" --flavor "%build_flavor" --variant "%variant" \
  --usrmerged "%{usrmerged}" --certs "%certs" "$@"
%posttrans
%run_if_exists /usr/lib/module-init-tools/kernel-scriptlets/rpm-posttrans --name "%name" \
  --version "%version" --release "%release" --kernelrelease "%kernelrelease" \
  --image "%image" --flavor "%build_flavor" --variant "%variant" \
  --usrmerged "%{usrmerged}" --certs "%certs" "$@"
%files -f kernel-main.files
%if "%CONFIG_KMSG_IDS" == "y"

%package man
Summary:        The collection of man pages generated by the kmsg script
Group:          System/Kernel

%description man
This package includes the man pages that have been generated from the
kmsg message documentation comments.


%source_timestamp
%files man
/usr/share/man/man9/*
%endif

%if 0%{?separate_vdso}
%package vdso
Summary:        VDSO binaries for debugging purposes
Group:          System/Kernel

%description vdso
This package includes the vdso binaries. They can be used for debugging. The
actual binary linked to the programs is loaded from the in-memory image, not
from this package.


%source_timestamp
%files vdso
%dir %modules_dir
%modules_dir/vdso/
%endif

%package devel
Summary:        Development files necessary for building kernel modules
Group:          Development/Sources
Provides:       %name-devel = %version-%source_rel
Provides:       multiversion(kernel)
Requires:       kernel-cachyos-devel%variant = %version-%source_rel
Requires:       pesign-obs-integration
Recommends:     make
Recommends:     gcc
Recommends:     perl
# for objtool
Requires:	libelf-devel
Supplements:    (%name and kernel-cachyos-devel%variant)
%if "%{compress_modules}" == "zstd"
Requires:       zstd
%endif
%if "%CONFIG_DEBUG_INFO_BTF_MODULES" == "y"
Requires:       dwarves >= 1.22
%endif
%if "%CONFIG_PREEMPT_DYNAMIC" == "y"
Provides:       kernel-preempt-devel = %version-%release
%endif
Requires:       clang
Requires:       lld
Provides:       kernel-trace-devel = 3.13
Obsoletes:      kernel-trace-devel < 3.13
Provides:       kernel-bigsmp-devel = 3.1
Obsoletes:      kernel-bigsmp-devel < 3.1
Provides:       kernel-desktop-devel = 4.3
Obsoletes:      kernel-desktop-devel < 4.3
Provides:       kernel-xen-devel = 4.4
Obsoletes:      kernel-xen-devel < 4.4
Provides:       kernel-ec2-devel = 4.4
Obsoletes:      kernel-ec2-devel < 4.4
%obsolete_rebuilds %name-devel
PreReq:         coreutils

%description devel
This package contains files necessary for building kernel modules (and
kernel module packages) against the %build_flavor flavor of the kernel.


%source_timestamp

%if "%CONFIG_MODULES" == "y"

%pre devel

# handle update from an older kernel-source with linux-obj as symlink
if [ -h /usr/src/linux-obj ]; then
    rm -vf /usr/src/linux-obj
fi

%post devel
%relink_function

relink ../../linux-%{kernelrelease}%{variant}-obj/"%cpu_arch_flavor" /usr/src/linux-obj/"%cpu_arch_flavor"

%files devel -f kernel-devel.files
%dir /usr/src/linux-obj
%dir /usr/src/linux-obj/%cpu_arch
%ghost %attr(0755,root,root) /usr/src/linux-obj/%cpu_arch_flavor
%dir /usr/include/bpf
/usr/include/bpf/vmlinux.h
%if "%kmp_target_cpu" != "%cpu_arch"
%obj_install_dir/%kmp_target_cpu
/usr/src/linux-obj/%kmp_target_cpu
%endif

%endif # %CONFIG_MODULES

%package perf
Summary:        Performance analysis tools for Linux
Group:          Development/Tools/Debuggers
Requires:       %{name} = %{version}-%{release}
License:        GPL-2.0-only

%description perf
Performance counters for Linux are a framework that abstracts away CPU
hardware differences and provides a common interface for performance
analysis. This package contains the perf tool built against the
kernel-cachyos-bore kernel.

%files perf
%{_bindir}/perf
%{_bindir}/trace
%dir %{_prefix}/libexec/perf-core
%{_prefix}/libexec/perf-core/*
%{_mandir}/man1/perf*
%dir /etc/bash_completion.d
/etc/bash_completion.d/perf
%{_includedir}/perf/perf_dlfilter.h
%dir /usr/share/doc/perf-tip
/usr/share/doc/perf-tip/tips.txt

%if 0%{?build_nvidia}
%package -n %{name}-nvidia-open
Summary:        NVIDIA open kernel modules for kernel-cachyos-bore
Group:          System/Kernel
Requires:       %{name} = %{version}-%{release}
Provides:       nvidia-open-driver-kmp = %{nv_ver}
Conflicts:      nvidia-gfxG06-kmp
Recommends:     nvidia-drivers-G06 >= %{nv_ver}
License:        MIT AND GPL-2.0-only

%description -n %{name}-nvidia-open
NVIDIA open kernel modules (version %{nv_ver}) built for the
kernel-cachyos-bore kernel. This replaces the need for nvidia-open-dkms.
Requires a Turing (RTX 20xx) or newer NVIDIA GPU.

%post -n %{name}-nvidia-open
/sbin/depmod -a %kernelrelease-%build_flavor

%postun -n %{name}-nvidia-open
/sbin/depmod -a %kernelrelease-%build_flavor

%files -n %{name}-nvidia-open
%dir %modules_dir/extramodules
%modules_dir/extramodules/nvidia*.ko*
%dir %_defaultlicensedir/%{name}-nvidia-open
%license %_defaultlicensedir/%{name}-nvidia-open/%{nv_open_pkg}-COPYING
%endif

%if 0%{?build_rtl8125}
%package -n %{name}-rtl8125
Summary:        Realtek RTL8125 2.5GbE driver for kernel-cachyos-bore
Group:          System/Kernel
Requires:       %{name} = %{version}-%{release}
Provides:       r8125-kmp = %{rtl8125_ver}
License:        GPL-2.0-only

%description -n %{name}-rtl8125
Realtek RTL8125 2.5GbE PCI Express out-of-tree driver (version %{rtl8125_ver})
built for the kernel-cachyos-bore kernel.

%post -n %{name}-rtl8125
/sbin/depmod -a %kernelrelease-%build_flavor

%postun -n %{name}-rtl8125
/sbin/depmod -a %kernelrelease-%build_flavor

%files -n %{name}-rtl8125
%dir %modules_dir/extramodules
%modules_dir/extramodules/r8125.ko*
%dir /etc/modprobe.d
%config(noreplace) /etc/modprobe.d/r8125-blacklist.conf
%dir /etc/modules-load.d
%config(noreplace) /etc/modules-load.d/r8125-load.conf
%endif

%prep
if ! [ -e %{S:0} ]; then
    echo "The %name-%version.nosrc.rpm package does not contain the" \
	 "complete sources. Please install kernel-source-%version.src.rpm."
    exit 1
fi

SYMBOLS=
if test -e %_sourcedir/extra-symbols; then
	SYMBOLS=$(cat %_sourcedir/extra-symbols)
	echo "extra symbol(s):" $SYMBOLS
fi

# Unpack all sources and patches
%setup -q -c -T -a 0 -a 100 -a 101 -a 102 -a 103 -a 104 -a 105 -a 106 -a 109 -a 110 -a 111 -a 113 -a 114 -a 120 -a 121 %{?build_nvidia:-a 200} %{?build_rtl8125:-a 201}

mkdir -p %kernel_build_dir

# Generate a list of modules with their support status marking
# The first marker is supposed to be either "+external", "-" or "-!optional",
# where "+external" is for an externally supported module, "-" is for an
# unsuppored module, "-!optional" is for Leap-only unsupported module.
# There can be an optional arch-specific second marker with "+arch" (e.g.
# +arm64), which enforces the module to be supported on the specific arch.
%_sourcedir/guards --list --with-guards <%_sourcedir/supported.conf | \
awk '{
    t = "";
    for (i = 1; i < NF; i++) {
	if ($i == "+external") {
		t = " external";
	} else if ($i == "+'%cpu_arch'") {
		t = "";
	} else if ($i ~ "^-") {
		t = " no";
	}
    }
    print $(NF) t;
}' >%kernel_build_dir/Module.supported
subpackages=(
	base
)
for package in "${subpackages[@]}"; do
	%_sourcedir/guards --default=0 "$package" \
		<%_sourcedir/supported.conf | sed 's,.*/,,; s,\.ko$,,' | \
		sort -u >%kernel_build_dir/Module."$package"
done

cd %{cachyos_tag}

%_sourcedir/apply-patches \
	%_sourcedir/series.conf .. $SYMBOLS

# Apply CachyOS patches
%patch -P0 -p1
%patch -P1 -p1
%patch -P2 -p1
%patch -P3 -p1 -F2
%patch -P4 -p1

cd %kernel_build_dir

# Override the timestamp 'uname -v' reports with the source timestamp and
# the commit hash.
date=$(head -n 1 %_sourcedir/source-timestamp)
commit=$(sed -n 's/GIT Revision: //p' %_sourcedir/source-timestamp)
cat > .kernel-binary.spec.buildenv <<EOF
export KBUILD_BUILD_TIMESTAMP="$(LANG=C date -d "$date") (${commit:0:7})"
export KBUILD_VERBOSE=0
export KBUILD_SYMTYPES=1
export KBUILD_BUILD_USER=geeko
export KBUILD_BUILD_HOST=buildhost
EOF
source .kernel-binary.spec.buildenv

if [ -f %_sourcedir/localversion ] ; then
    cat %_sourcedir/localversion > localversion
fi

config_base="cachyos-bore"
if ! [ -f %my_builddir/config/%cpu_arch/$config_base ] ; then
    config_base=%variant
    config_base=${config_base#-}
fi
if ! grep -q CONFIG_MMU= "%my_builddir/config/%cpu_arch_flavor"; then
cp "%my_builddir/config/%cpu_arch/$config_base" .config
../scripts/kconfig/merge_config.sh -m .config \
                                   %my_builddir/config/%cpu_arch_flavor
else
cp %my_builddir/config/%cpu_arch_flavor .config
fi
if test -e %my_builddir/config.addon/%cpu_arch_flavor; then
	# FIXME: config.addon doesn't affect the %CONFIG_ macros defined at
	# the top of the specfile
	../scripts/kconfig/merge_config.sh -m .config %my_builddir/config.addon/%cpu_arch_flavor
fi

CONFIG_SUSE_KERNEL_RELEASED="--disable CONFIG_SUSE_KERNEL_RELEASED"
%if 0%{?_project:1}
if echo %_project | grep -Eqx -f %_sourcedir/release-projects; then
	CONFIG_SUSE_KERNEL_RELEASED="--enable CONFIG_SUSE_KERNEL_RELEASED"
fi
%endif


CONFIG_SUSE_HAVE_STABLE_KABI=""
SHSK_VAL="$(../scripts/config --state SUSE_HAVE_STABLE_KABI)"
if test -e %my_builddir/kabi/%cpu_arch/symvers-%build_flavor -a $SHSK_VAL = "n" ; then
	echo "CONFIG_SUSE_HAVE_STABLE_KABI=n is a mistake with KABI reference data." \
	     "Create IGNORE-KABI-BADNESS to disable KABI checking."
	exit 1
elif test ! -e %my_builddir/kabi/%cpu_arch/symvers-%build_flavor \
	-o 0%{?ignore_kabi_badness} -ne 0 \
	-o -e %_sourcedir/IGNORE-KABI-BADNESS ; then
	CONFIG_SUSE_HAVE_STABLE_KABI="--disable CONFIG_SUSE_HAVE_STABLE_KABI"
elif test ! -e %my_builddir/kabi/%cpu_arch/symvers-%build_flavor -a $SHSK_VAL = "y" ; then
	# only message, not an error
	echo "Disable CONFIG_SUSE_HAVE_STABLE_KABI or supply KABI reference data in -%build_flavor."
fi

../scripts/config \
	--set-str CONFIG_LOCALVERSION -%source_rel-%build_flavor \
	--enable  CONFIG_SUSE_KERNEL \
	$CONFIG_SUSE_KERNEL_RELEASED \
	$CONFIG_SUSE_HAVE_STABLE_KABI

# Set SUSE release details for openSUSE Tumbleweed
../scripts/config \
	--disable CONFIG_SUSE_PRODUCT_SLE \
	--disable CONFIG_SUSE_PRODUCT_OPENSUSE_LEAP \
	--enable  CONFIG_SUSE_PRODUCT_OPENSUSE_TUMBLEWEED \
	--disable CONFIG_SUSE_PRODUCT_ALP \
	--set-val CONFIG_SUSE_VERSION 1599 \
	--set-val CONFIG_SUSE_PATCHLEVEL 0

# Enable Clang ThinLTO
../scripts/config \
	--enable  CONFIG_LTO_CLANG_THIN \
	--disable CONFIG_LTO_NONE

# Reduce USB enumeration retries on dead/phantom ports
../scripts/config \
	--enable CONFIG_USB_FEW_INIT_RETRIES

# CPU optimization: Generic x86-64-v3 (AVX2, MOVBE, BMI1/2)
../scripts/config \
	--enable  CONFIG_GENERIC_CPU \
	--disable CONFIG_MZEN4 \
	--disable CONFIG_X86_NATIVE_CPU \
	--set-val CONFIG_X86_64_VERSION 3

if [ %CONFIG_MODULE_SIG = "y" ]; then
	if [ -n "%certs" ] ; then
		ln -s %_sourcedir/.kernel_signing_key.pem .
	else
		if ! [ -f .kernel.genkey ] ; then
			cat > .kernel.genkey <<EOF
[ req ]
default_bits = 4096
distinguished_name = req_distinguished_name
prompt = no
string_mask = utf8only
x509_extensions = myexts

[ req_distinguished_name ]
CN = Build time autogenerated kernel key

[ myexts ]
basicConstraints=critical,CA:FALSE
keyUsage=digitalSignature
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid
extendedKeyUsage=codeSigning
EOF
		fi
		openssl req -new -nodes -utf8 -%CONFIG_MODULE_SIG_HASH -days 36500 \
			-batch -x509 -config .kernel.genkey \
			-outform PEM -out .kernel_signing_key.pem \
			-keyout .kernel_signing_key.pem
	fi
	../scripts/config --set-str CONFIG_MODULE_SIG_KEY ".kernel_signing_key.pem"
fi

MAKE_ARGS="$MAKE_ARGS ARCH=x86 LLVM=1"

makeoutputsync=
if make --output-sync --help >/dev/null 2>&1 ; then
        makeoutputsync=--output-sync
else
        echo make does not support --output-sync flag. Build messages may be mangled. 1>&2
fi
MAKE_ARGS="$MAKE_ARGS $makeoutputsync %{?_smp_mflags}"
echo export MAKE_ARGS=\""$MAKE_ARGS"\" >> .kernel-binary.spec.buildenv

KERN_DIRS="-C .. O=$PWD"
if test -e %_sourcedir/TOLERATE-UNKNOWN-NEW-CONFIG-OPTIONS; then
    yes '' | make oldconfig $MAKE_ARGS $KERN_DIRS
else
    cp .config .config.orig
    if test -f ../scripts/kconfig/Makefile && \
       grep -q syncconfig ../scripts/kconfig/Makefile; then
        syncconfig="syncconfig"
    else
        syncconfig="silentoldconfig"
    fi
    make $syncconfig $MAKE_ARGS $KERN_DIRS < /dev/null
    %_sourcedir/check-for-config-changes .config.orig .config
    rm .config.orig
fi

make prepare $MAKE_ARGS
make scripts $MAKE_ARGS
krel=$(make -s kernelrelease $MAKE_ARGS)

if [ "$krel" != "%kernelrelease-%build_flavor" ]; then
    echo "Kernel release mismatch: $krel != %kernelrelease-%build_flavor" >&2
    exit 1
fi

make clean $MAKE_ARGS

rm -f source
find . ! -type d ! -name 'Module.base' ! -name 'Module.*-kmp' ! -name 'Module.optional' -printf '%%P\n' \
	> %my_builddir/obj-files

%build
cd %kernel_build_dir
source .kernel-binary.spec.buildenv

    # create *.symref files in the tree
    if test -e %my_builddir/kabi/%cpu_arch/symtypes-%build_flavor; then
        %_sourcedir/modversions --unpack . < $_
    fi

%if "%CONFIG_KMSG_IDS" == "y"
    chmod +x ../scripts/kmsg-doc
    MAKE_ARGS="$MAKE_ARGS D=2"
%endif

mkdir -p %_topdir/OTHER
log=%_topdir/OTHER/make-stderr.log
make all $MAKE_ARGS 2> >(tee "$log")
result="${PIPESTATUS[0]}"
if ! test "$result" -eq 0; then
    exit "$result"
fi

%if 0%{?build_nvidia}
# Build NVIDIA open kernel modules
cd %my_builddir/%{nv_open_pkg}
unset KBUILD_BUILD_TIMESTAMP KBUILD_VERBOSE KBUILD_SYMTYPES KBUILD_BUILD_USER KBUILD_BUILD_HOST
CFLAGS= CXXFLAGS= LDFLAGS= make %{?_smp_mflags} \
    CC=clang CXX=clang++ HOSTCC=clang HOSTCXX=clang++ LD=ld.lld \
    IGNORE_PREEMPT_RT_PRESENCE=1 \
    CONFIG_DEBUG_INFO_BTF_MODULES= \
    KERNEL_UNAME=%kernelrelease-%build_flavor \
    SYSSRC=%my_builddir/%{cachyos_tag} \
    SYSOUT=%kernel_build_dir \
    modules
cd %kernel_build_dir
%endif

%if 0%{?build_rtl8125}
# Build Realtek RTL8125 out-of-tree driver
cd %my_builddir/%{rtl8125_dir}
make %{?_smp_mflags} \
    CC=clang CXX=clang++ HOSTCC=clang HOSTCXX=clang++ LD=ld.lld \
    BASEDIR=%my_builddir/%{cachyos_tag} \
    KSRC=%my_builddir/%{cachyos_tag} \
    KERNELDIR=%kernel_build_dir \
    modules
cd %kernel_build_dir
%endif

# Generate vmlinux.h for BPF CO-RE development
mkdir -p tools/bpf/bpftool
make -C ../tools/bpf/bpftool OUTPUT=$PWD/tools/bpf/bpftool/ $MAKE_ARGS
tools/bpf/bpftool/bpftool btf dump file vmlinux format c > tools/bpf/bpftool/vmlinux.h

# Build perf tool
mkdir -p tools/perf
make -C ../tools/perf OUTPUT=$PWD/tools/perf/ WERROR=0 LIBTRACEEVENT_DYNAMIC=1 $MAKE_ARGS

%install

# get rid of /usr/lib/rpm/brp-strip-debug
# strip removes too much from the vmlinux ELF binary
export NO_BRP_STRIP_DEBUG=true
export STRIP_KEEP_SYMTAB='*/vmlinux*'

# %kernel_module_directory/%kernelrelease-%build_flavor/source points to the source
# directory installed by kernel-devel. The kernel-%build_flavor-devel package
# has a correct dependency on kernel-devel, but the brp check does not see
# kernel-devel during build.
export NO_BRP_STALE_LINK_ERROR=yes

cd %kernel_build_dir
source .kernel-binary.spec.buildenv

mkdir -p %buildroot/boot
# (Could strip out non-public symbols.)
cp -p System.map %buildroot/boot/System.map-%kernelrelease-%build_flavor

add_vmlinux()
{
    local vmlinux=boot/vmlinux-%kernelrelease-%build_flavor

    cp vmlinux %buildroot/$vmlinux
    # make sure that find-debuginfo.sh picks it up. In the filelist, we
    # mark the file 0644 again
    chmod +x %buildroot/$vmlinux
    if test $1 == "--compressed"; then
        ts="$(head -n1 %_sourcedir/source-timestamp)"
        touch -d "$ts" %buildroot/$vmlinux
        touch %buildroot/$vmlinux.%{compress_vmlinux}
        ghost_vmlinux=true
    else
        ghost_vmlinux=false
    fi
}

# architecture specifics
    add_vmlinux --compressed
    cp -p arch/x86/boot/bzImage %buildroot/boot/%image-%kernelrelease-%build_flavor

# sign the modules, firmware and possibly the kernel in the buildservice
BRP_PESIGN_FILES=""
%if "%CONFIG_EFI_STUB" == "y"
%if %{usrmerged}
BRP_PESIGN_FILES="%modules_dir/%image"
%else
BRP_PESIGN_FILES="/boot/%image-%kernelrelease-%build_flavor"
%endif
%endif
%if "%CONFIG_MODULE_SIG" == "y"
BRP_PESIGN_FILES="$BRP_PESIGN_FILES *.ko"
%endif
export BRP_PESIGN_FILES
%if "%{compress_modules}" != "none"
export BRP_PESIGN_COMPRESS_MODULE=%{compress_modules}
%endif

if test -x /usr/lib/rpm/pesign/gen-hmac; then
	$_ -r %buildroot /boot/%image-%kernelrelease-%build_flavor
fi

# Package the compiled-in certificates as DER files in /etc/uefi/certs
# and have mokutil enroll them when the kernel is installed
echo Signing certificates "%certs"
if test %CONFIG_MODULE_SIG = "y" -a -d %_sourcedir/.kernel_signing_certs ; then
    for f in %_sourcedir/.kernel_signing_certs/*.crt; do
            mkdir -p %buildroot/etc/uefi/certs
            cp -v $f %buildroot/etc/uefi/certs
    done
fi

cp -p .config %buildroot/boot/config-%kernelrelease-%build_flavor
sysctl_file=%buildroot/boot/sysctl.conf-%kernelrelease-%build_flavor
for file in %my_builddir/sysctl/{defaults,%cpu_arch/arch-defaults,%cpu_arch_flavor}; do
	if [ -f "$file" ]; then
		cat "$file"
	fi
done | sed '1i # Generated file - do not edit.' >$sysctl_file
if [ ! -s $sysctl_file ]; then
	rm $sysctl_file
fi

%if %install_vdso
# Install the unstripped vdso's that are linked in the kernel image
make vdso_install $MAKE_ARGS INSTALL_MOD_PATH=%buildroot
rm -rf %buildroot%kernel_module_directory/%kernelrelease-%build_flavor/vdso/.build-id
%endif

# Create a dummy initrd with roughly the size the real one will have.
# That way, YaST will know that this package requires some additional
# space in /boot.
dd if=/dev/zero of=%buildroot/boot/initrd-%kernelrelease-%build_flavor \
	bs=1024 seek=2047 count=1
# Also reserve some space for the kdump initrd
cp %buildroot/boot/initrd-%kernelrelease-%build_flavor{,-kdump}
%if 0%{?suse_version} >= 1500
# Use same permissions as dracut
chmod 0600 %buildroot/boot/initrd-%kernelrelease-%build_flavor{,-kdump}
%endif

if [ %CONFIG_MODULES = y ]; then
    mkdir -p %rpm_install_dir/%cpu_arch_flavor
    mkdir -p %buildroot/usr/src/linux-obj/%cpu_arch
    install -m 755 -D -t %rpm_install_dir/%cpu_arch_flavor/scripts/mod/ scripts/mod/ksym-provides

    gzip -n -c9 < Module.symvers > %buildroot/boot/symvers-%kernelrelease-%build_flavor.gz

    # Skip inline module signing during install — pesign-obs-integration
    # handles signing via BRP hooks (sign-file cannot use OBS public-only certs)
    make modules_install $MAKE_ARGS INSTALL_MOD_PATH=%buildroot CONFIG_MODULE_SIG_ALL=

    # Also put the resulting file in %rpm_install_dir/%cpu_arch/%build_flavor
    # so that kernel-devel + kernel-%build_flavor is sufficient for building
    # modules that have modversions as well.
    mkdir -p %rpm_install_dir/%cpu_arch/%build_flavor
    cp Module.symvers %rpm_install_dir/%cpu_arch/%build_flavor



    # Table of types used in exported symbols (for modversion debugging).
    %_sourcedir/modversions --pack . > %my_builddir/symtypes-%build_flavor
    if [ -s %my_builddir/symtypes-%build_flavor ]; then
        gzip -n -9 -c %my_builddir/symtypes-%build_flavor \
            > %buildroot/boot/symtypes-%kernelrelease-%build_flavor.gz
    fi

    # Some architecture's $(uname -m) output is different from the ARCH
    # parameter that needs to be passed to kbuild. Create symlinks from
    # $(uname -m) to the ARCH directory.
    if [ ! -e %rpm_install_dir/%kmp_target_cpu ]; then
        ln -sf %cpu_arch %rpm_install_dir/%kmp_target_cpu
        ln -sf %cpu_arch %buildroot/usr/src/linux-obj/%kmp_target_cpu
    fi

    # We were building in %my_builddir/linux-%srcversion, but the sources will
    # later be installed in /usr/src/linux-%srcversion-%source_rel. Fix up the
    # build symlink.
    rm -f %buildroot%kernel_module_directory/%kernelrelease-%build_flavor/{source,build}
    ln -s %src_install_dir \
	%buildroot%kernel_module_directory/%kernelrelease-%build_flavor/source
    ln -s %obj_install_dir/%cpu_arch/%build_flavor \
	%buildroot%kernel_module_directory/%kernelrelease-%build_flavor/build

    # Abort if there are any undefined symbols
    msg="$(/sbin/depmod -F %buildroot/boot/System.map-%kernelrelease-%build_flavor \
			-b %buildroot -ae %kernelrelease-%build_flavor 2>&1)"
    if [ $? -ne 0 ] || echo "$msg" | grep  'needs unknown symbol'; then
	exit 1
    fi

    %_sourcedir/split-modules -d %buildroot \
	-o %my_builddir \
	-b %kernel_build_dir \
%if "%CONFIG_SUSE_KERNEL_SUPPORTED" == "y"
	-e \
%endif
%if ! %supported_modules_check
	-i \
%endif
	%nil
%if ! %split_extra
    cat %my_builddir/unsupported-modules >>%my_builddir/main-modules
%endif

    # The modules.dep file is sorted randomly which produces strange file
    # checksums. As the file is not included in the resulting RPM, it's
    # pointless to rely on its contents. Replacing by zeros to make the
    # checksums always the same for several builds of the same package.
    test -s %buildroot%kernel_module_directory/%kernelrelease-%build_flavor/modules.dep && \
    dd if=/dev/zero of=%buildroot%kernel_module_directory/%kernelrelease-%build_flavor/modules.dep ibs=$(stat -c%s %buildroot%kernel_module_directory/%kernelrelease-%build_flavor/modules.dep) count=1

    res=0
    if test -e %my_builddir/kabi/%cpu_arch/symvers-%build_flavor; then
        # check for kabi changes
            %_sourcedir/kabi.pl --rules %my_builddir/kabi/severities \
                %my_builddir/kabi/%cpu_arch/symvers-%build_flavor \
                Module.symvers || res=$?
    fi
    if [ $res -ne 0 ]; then

	# %ignore_kabi_badness is defined in the Kernel:* projects in the
	# OBS to be able to build the KOTD in spite of kabi errors
	if [ 0%{?ignore_kabi_badness} -eq 0 -a \
	     ! -e %_sourcedir/IGNORE-KABI-BADNESS ]; then
	    echo "Create a file IGNORE-KABI-BADNESS in the kernel-source" \
		 "directory to build this kernel even though its badness is" \
		 "higher than allowed for an official kernel."
	   exit 1
	fi
    fi

    # Check the license in each module
    if ! sh %_sourcedir/check-module-license %buildroot; then
	echo "Please fix the missing licenses!"
%if "%CONFIG_SUSE_KERNEL_SUPPORTED" == "y"
	exit 1
%endif
    fi

    # These files are required for building external modules
    for FILE in arch/powerpc/lib/crtsavres.o arch/arm64/kernel/ftrace-mod.o \
		arch/*/kernel/macros.s scripts/module.lds
    do
	    if [ -f %kernel_build_dir/$FILE ]; then
		echo $FILE >> %my_builddir/obj-files
	    fi
    done

    tar --exclude=\*.ipa-clones --exclude=.config.old --exclude=.kernel-binary.spec.buildenv \
        --exclude=.kernel_signing_key.pem --exclude=.kernel.genkey \
        -cf - -T %my_builddir/obj-files | \
	tar -xf - -C %rpm_install_dir/%cpu_arch_flavor
    # bnc#507084
    find %rpm_install_dir/%cpu_arch_flavor/scripts -type f -perm -111 | \
        while read f; do
            case "$(file -b "$f")" in
            ELF\ *\ executable*)
                strip "$f"
            esac
        done

    # Recreate the generated Makefile with correct path
    #
    # Linux 5.13 no longer has mkmakefile
    if [ -f ../scripts/mkmakefile ] ; then
        sh ../scripts/mkmakefile ../../../%{basename:%src_install_dir} \
            %rpm_install_dir/%cpu_arch_flavor \
            $(echo %srcversion | sed -r 's/^([0-9]+)\.([0-9]+).*/\1 \2/')
    else
       echo 'export KBUILD_OUTPUT = %obj_install_dir/%cpu_arch_flavor' > %rpm_install_dir/%cpu_arch_flavor/Makefile
       echo 'include ../../../%{basename:%src_install_dir}/Makefile' >> %rpm_install_dir/%cpu_arch_flavor/Makefile
    fi
fi

# CONFIG_GDB_SCRIPTS
if [ -e vmlinux-gdb.py ]; then
    DEST=%rpm_install_dir/%cpu_arch_flavor/
    install -m 755 -d "$DEST"
    # set sys.path to our devel.rpm scripts
    sed 's@\(sys\.path\.insert(0, \).*@\1"%obj_install_dir/%cpu_arch_flavor/scripts/gdb/")@' vmlinux-gdb.py > "$DEST/vmlinux-gdb.py"

    DEST=%rpm_install_dir/%cpu_arch_flavor/scripts/gdb/linux
    install -m 755 -d "$DEST"
    pushd scripts/gdb/linux/
    for file in *.py; do
	if test -L "$file"; then
	    # relink against our devel.rpm sources, not of buildroot's
	    ln -s "%src_install_dir/scripts/gdb/linux/$file" "$DEST/$file"
	else
	    cp -p "$file" "$DEST"
	fi
    done
    popd

    DEST=%{buildroot}%{_datadir}/gdb/auto-load%modules_dir
    install -m 755 -d "$DEST"
    ln -s %obj_install_dir/%cpu_arch_flavor/vmlinux-gdb.py "$DEST/vmlinux-gdb.py"
fi

# Install vmlinux.h for BPF CO-RE development
if [ -f tools/bpf/bpftool/vmlinux.h ]; then
    install -m 644 -D tools/bpf/bpftool/vmlinux.h %{buildroot}/usr/include/bpf/vmlinux.h
fi

# Install perf tool
make -C ../tools/perf OUTPUT=$PWD/tools/perf/ WERROR=0 LIBTRACEEVENT_DYNAMIC=1 $MAKE_ARGS \
    DESTDIR=%{buildroot} prefix=%{_prefix} install
# Build and install perf man pages (serial – asciidoc races with --output-sync -jN)
make -C ../tools/perf OUTPUT=$PWD/tools/perf/ WERROR=0 LIBTRACEEVENT_DYNAMIC=1 \
    DESTDIR=%{buildroot} prefix=%{_prefix} install-man
# Create trace symlink (perf trace)
ln -sf perf %{buildroot}%{_bindir}/trace

%if 0%{?build_nvidia}
# Install NVIDIA open kernel modules
nvidia_extramodules=%{buildroot}%modules_dir/extramodules
mkdir -p $nvidia_extramodules
find %my_builddir/%{nv_open_pkg}/kernel-open -name '*.ko' -exec install -m 644 {} $nvidia_extramodules/ \;
ko_count=$(find $nvidia_extramodules -name '*.ko' | wc -l)
if [ "$ko_count" -eq 0 ]; then
    echo "ERROR: No nvidia .ko modules found!" >&2
    find %my_builddir/%{nv_open_pkg} -name '*.ko' -ls >&2
    exit 1
fi
# Leave as .ko -- BRP pesign will sign and compress to .ko.zst
install -m 644 -D %my_builddir/%{nv_open_pkg}/COPYING %{buildroot}%_defaultlicensedir/%{name}-nvidia-open/%{nv_open_pkg}-COPYING
%endif

%if 0%{?build_rtl8125}
# Install Realtek RTL8125 module
mkdir -p %{buildroot}%modules_dir/extramodules
install -m 644 %my_builddir/%{rtl8125_dir}/r8125.ko %{buildroot}%modules_dir/extramodules/
install -Dm 644 %{SOURCE202} %{buildroot}/etc/modprobe.d/r8125-blacklist.conf
install -Dm 644 %{SOURCE203} %{buildroot}/etc/modules-load.d/r8125-load.conf
%endif

# Extramodules are left as .ko -- the BRP pesign hook (BRP_PESIGN_FILES *.ko
# + BRP_PESIGN_COMPRESS_MODULE=zstd) will sign and compress them to .ko.zst

rm -rf %{buildroot}/lib/firmware

add_dirs_to_filelist() {
    sed -rn '
        # print file name
        p
        # remove filelist macros
        s:%%[a-z]+(\([^)]+\))? ?::g
        # add %%dir prefix
        s:^:%%dir :
        # print all parents
        :a
            # skip directories owned by other packages
            s:^%%dir (/boot|/etc|(/usr)?/lib/(modules|firmware)|/usr/share|/usr/src)/[^/]+$::
            s:/[^/]+$::p
        ta
    ' "$@" | sort -u
}

# Collect the file lists.
# does not exist for non-modularized kernels
%if %{usrmerged}
        mkdir -p %{buildroot}%modules_dir
%endif
shopt -s nullglob dotglob
> %my_builddir/kernel-devel.files
{
    echo "%modules_dir/build"
    echo "%modules_dir/source"
    cd %buildroot
    for file in boot/symtypes*; do
%if %{usrmerged}
        l="${file##*/}"
        l="%modules_dir/${l//-%kernelrelease-%build_flavor}"
        mv "$file" "%{buildroot}$l"
        ln -s "..$l" $file
        echo "$l"
        echo "%%ghost /$file"
%else
        echo "/$file"
%endif
    done
    if test -d .%{_datadir}/gdb/; then
	find .%obj_install_dir/%cpu_arch_flavor/scripts/gdb/linux/ -name '*.py' -type l | sed -e 's/^[.]//'
	echo "%{_datadir}/gdb/auto-load%modules_dir/vmlinux-gdb.py"
    fi
} | add_dirs_to_filelist >%my_builddir/kernel-devel.files
( cd %buildroot ; find .%obj_install_dir/%cpu_arch_flavor -type f ; ) | \
sed -e 's/^[.]//' | grep -v -e '[.]ipa-clones$' -e '/ipa-clones[.]list$'| \
add_dirs_to_filelist >> %my_builddir/kernel-devel.files

{   echo "%ghost %attr(0644,root,root) /boot/%image"
    echo "%ghost %attr(0644,root,root) /boot/initrd"
    cd %buildroot
    for f in boot/*; do
        l="${f##*/}"
        l="%modules_dir/${l//-%kernelrelease-%build_flavor}"
        if test -L "$f"; then
            echo "%%ghost /$f"
            continue
        elif test ! -f "$f"; then
            continue
        fi
        case "$f" in
        boot/initrd-*)
            echo "%%ghost /$f"
            continue
            ;;
        boot/vmlinux-*.%{compress_vmlinux})
            echo -n "%%attr(0644, root, root) "
            ;;
        boot/vmlinux-*)
            if $ghost_vmlinux; then
                # fall through to mark next echo as %ghost
                echo -n "%%ghost "
            fi
            ;;
%if %{usrmerged}
        boot/vmlinuz-*)
            echo -n "%%attr(0644, root, root) "
            ;;
%endif
        boot/symtypes*)
%if %{usrmerged}
            echo "%exclude $l"
%endif
            continue
            ;;
        esac
%if %{usrmerged}
        mv "$f" "./$l"
        ln -s "..$l" $f
        # the find in the CONFIG_MODULES condition below also finds the files
        # but there's sort -u later, so this is ok
        echo "$l" # note: must be first after case statement above
        echo "%%ghost /$f"
%else
        echo "%%attr(0644, root, root) /$f"
%endif
    done

    if [ %CONFIG_MODULES = y ]; then
	MODULES=%{lua: print(rpm.expand('%kernel_module_directory'):sub(2))}/%kernelrelease-%build_flavor
	find "$MODULES" \
	    -path "$MODULES/extramodules" -prune -o \
%if 0%{?separate_vdso}
	    -path "$MODULES/vdso" -prune -o \
%endif
	    -type d -o \
	    \( -path '*/modules.*' ! -path '*/modules.order' \
	     ! -path '*/modules.builtin' \
	     ! -path '*/modules.builtin.modinfo' \) -printf '%%%%ghost /%%p\n' \
	       -o -name '*.ko' -prune \
	       -o \( -type f \
%if %{usrmerged}
		! -path '*/symtypes*' ! -path '*/vmlinu*' \
%endif
		\) -printf '/%%p\n'
	cat %my_builddir/base-modules
    fi
    if test %CONFIG_MODULE_SIG = "y" -a -d etc/uefi/certs; then
        find etc/uefi/certs -type f -printf '/%%p\n'
    fi
    if test -d lib/firmware/%kernelrelease-%build_flavor; then
        echo "%%dir /lib/firmware/%kernelrelease-%build_flavor"
        cat %my_builddir/base-firmware
    fi
    if [ -e .%_docdir/%name ]; then
	echo "%%doc %_docdir/%name"
    fi
} | sort -u | add_dirs_to_filelist >%my_builddir/kernel-base.files

{
    add_dirs_to_filelist %my_builddir/kernel-base.files
    if [ %CONFIG_MODULES = y ]; then
        add_dirs_to_filelist %my_builddir/main-modules
    fi
    if test -d %buildroot/lib/firmware/%kernelrelease-%build_flavor; then
	echo "/lib/firmware/%kernelrelease-%build_flavor"
    fi
} | sort -u > %my_builddir/kernel-main.files

%if %split_extra
    add_dirs_to_filelist %my_builddir/unsupported-modules > %my_builddir/kernel-extra.files

%if 0%{?suse_version} > 1500 || 0%{?sle_version} >= 150000
    # By default, loading unsupported modules is disabled on SLE through
    # /etc/modprobe.d/10-unsupported-modules.conf from the suse-module-tools
    # package.
    # modules in kernel-$flavor-extra don't have the supported flag set,
    # yet loading them should be possible if the package is installed.
    # CAUTION PACKAGERS: The file content below must not change between
    # kernel versions, otherwise file conflicts might arise with
    # multiversion(kernel).

    modprobe_d_dir=/etc/modprobe.d
    %if 0%{?suse_version} > 1500 || 0%{?sle_version} > 150300
    modprobe_d_dir=/lib/modprobe.d
    %endif
    %if %{usrmerged}
    modprobe_d_dir=/usr/lib/modprobe.d
    %endif

    mkdir -p %buildroot$modprobe_d_dir
    cat >%buildroot$modprobe_d_dir/20-kernel-%{build_flavor}-extra.conf <<EOF
# This file overrides the default from 10-unsupported-modules.conf.
# This is necessary to load kernel modules from the
# kernel-%{build_flavor}-extra package.
#
# WARNING: loading unsupported modules may compromise SLE support.
# Please read the comments in 10-unsupported-modules.conf.
allow_unsupported_modules 1
EOF
    echo "%%dir $modprobe_d_dir" >> %my_builddir/kernel-extra.files
    echo "%%config(noreplace) $modprobe_d_dir/20-kernel-%{build_flavor}-extra.conf" >> %my_builddir/kernel-extra.files
%endif
%endif
if [ %CONFIG_MODULES = y ]; then
  install -m 644 %_sourcedir/modules.fips %{buildroot}%modules_dir/modules.fips
  echo %modules_dir/modules.fips >> %my_builddir/kernel-base.files
  echo %modules_dir/modules.fips >> %my_builddir/kernel-main.files
fi

# Hardlink duplicate files automatically (from package fdupes): It doesn't save
# much, but it keeps rpmlint from breaking the package build. Note that we skip
# /usr/src/linux-obj intentionally, to not accidentally break timestamps there
%fdupes %buildroot%modules_dir

%changelog
openSUSE Build Service is sponsored by