From 4750462646bf5ad49acb894083e3207fd11fdb24 Mon Sep 17 00:00:00 2001 From: movo987 Date: Sun, 22 Nov 2026 14:39:57 +0800 Subject: Keep each release in its own directory Signed-off-by: movo987 --- README | 32 +- patches/7.3.5/0001-zen-7.3.5-zen1.patch | 23684 ------------------- patches/7.3.5/0002-sched-bore-7.0.0.patch | 1409 -- .../v7.3.5-zako1/patches/0001-zen-7.3.5-zen1.patch | 23684 +++++++++++++++++++ .../patches/0002-sched-bore-7.0.0.patch | 1409 ++ releases/v7.3.5-zako1/series | 2 + releases/v7.3.5-zako1/sources | 5 + series/7.3.5 | 2 - sources/7.3.5 | 3 - 9 files changed, 25116 insertions(+), 25114 deletions(-) delete mode 100644 patches/7.3.5/0001-zen-7.3.5-zen1.patch delete mode 100644 patches/7.3.5/0002-sched-bore-7.0.0.patch create mode 100644 releases/v7.3.5-zako1/patches/0001-zen-7.3.5-zen1.patch create mode 100644 releases/v7.3.5-zako1/patches/0002-sched-bore-7.0.0.patch create mode 100644 releases/v7.3.5-zako1/series create mode 100644 releases/v7.3.5-zako1/sources delete mode 100644 series/7.3.5 delete mode 100644 sources/7.3.5 diff --git a/README b/README index 9b06c56..24fe0f2 100644 --- a/README +++ b/README @@ -3,29 +3,29 @@ linux-zako Linux-libre with the Zen patchset and the BORE scheduler on top. Layout - patches// patch set for one kernel version - series/ order to apply them in - sources/ base tarball, its URL and sha256 - COPYING GPL-2 + releases//patches/ patch set of that release + releases//series order to apply them in + releases//sources base tarball, its URL and sha256, plus the Zen tag + and the BORE version it was built against + COPYING GPL-2 - Every version has its own directory and they are all kept. A new version adds - a directory, it never replaces an older one. + One directory per published tag, kept forever. A new release adds a + directory, no existing directory is ever rewritten. Build + cd releases/ tar xf linux-libre--gnu.tar.xz cd linux- - git apply ../patches//0001-*.patch - git apply ../patches//0002-*.patch + git apply ../patches/0001-*.patch + git apply ../patches/0002-*.patch make olddefconfig make LOCALVERSION=-zako - Apply in the order given by series/. Enable CONFIG_SCHED_BORE in - olddefconfig. Keep CONFIG_SCHED_ALT (BMQ, PDS) off, it costs cgroup v2 - cpu.weight and cpu.max, sched_ext and SCHED_CORE. + Apply in the order given by series. Enable CONFIG_SCHED_BORE in olddefconfig. + Keep CONFIG_SCHED_ALT (BMQ, PDS) off, it costs cgroup v2 cpu.weight and + cpu.max, sched_ext and SCHED_CORE. Tags - v-zako: kernel version plus a revision of this queue. Published - tags do not move. - -Next version - Added once Linux-libre, Zen and BORE have all reached it. + v-zako: kernel version plus a revision of this queue. A new kernel + version starts at zako1, a Zen or BORE update within the same kernel version + increments N. Published tags do not move. diff --git a/patches/7.3.5/0001-zen-7.3.5-zen1.patch b/patches/7.3.5/0001-zen-7.3.5-zen1.patch deleted file mode 100644 index 56898e1..0000000 --- a/patches/7.3.5/0001-zen-7.3.5-zen1.patch +++ /dev/null @@ -1,23684 +0,0 @@ -diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt -index 4e64219..79121b0 100644 ---- a/Documentation/admin-guide/kernel-parameters.txt -+++ b/Documentation/admin-guide/kernel-parameters.txt -@@ -2532,6 +2532,9 @@ Kernel parameters - disable - Do not enable intel_pstate as the default - scaling driver for the supported processors -+ enable -+ Enable intel_pstate in-case "disable" was passed -+ previously in the kernel boot parameters - active - Use intel_pstate driver to bypass the scaling - governors layer of cpufreq and provides it own -@@ -4693,6 +4696,10 @@ Kernel parameters - - nosync [HW,M68K] Disables sync negotiation for all devices. - -+ nothreadirqs [KNL,EARLY] -+ Disable forced threading of interrupt handlers that -+ is enabled by default with CONFIG_FORCE_IRQ_THREADING. -+ - no_timer_check [X86,APIC] Disables the code which tests for broken - timer IRQ sources, i.e., the IO-APIC timer. This can - work around problems with incorrect timer -@@ -5312,6 +5319,19 @@ Kernel parameters - to disable PCIe TLP Processing Hints support - system-wide. - -+ pcie_acs_override= -+ [PCIE] Assert ACS isolation for PCIe devices -+ lacking it, splitting their IOMMU groups. Not a -+ security boundary: peer-to-peer DMA between -+ affected devices is unprotected. Taints the -+ kernel. Devices with real ACS, and devices the -+ firmware marked untrusted or external-facing, are -+ never affected. Comma-separated list of: -+ downstream Downstream and root ports -+ multifunction Multifunction endpoints and upstream ports -+ id:nnnn:nnnn Devices with this vendor:device ID, hex, -+ up to 16 -+ - pcie_aspm= [PCIE] Forcibly enable or ignore PCIe Active State Power - Management. - off Don't touch ASPM configuration at all. Leave any -@@ -6805,6 +6825,13 @@ Kernel parameters - cost of significant additional memory use for tables. - - -+ sched_pds_sleep_credit= -+ [KNL] Enable or disable the PDS sleep credit, which -+ moves a task that slept ahead of CPU-bound tasks of -+ the same nice level when it wakes up. -+ Format: -+ Default: CONFIG_SCHED_PDS_SLEEP_CREDIT -+ - sched_proxy_exec= [KNL] - Enables or disables "proxy execution" style - solution to mutex-based priority inversion. -diff --git a/Documentation/admin-guide/mm/multigen_lru.rst b/Documentation/admin-guide/mm/multigen_lru.rst -index 9cb54b4..808d2e9 100644 ---- a/Documentation/admin-guide/mm/multigen_lru.rst -+++ b/Documentation/admin-guide/mm/multigen_lru.rst -@@ -149,8 +149,8 @@ generations less than or equal to ``min_gen_nr``. - ``- memcg_id node_id min_gen_nr [swappiness [nr_to_reclaim]]`` - - ``min_gen_nr`` should be less than ``max_gen_nr-1``, since --``max_gen_nr`` and ``max_gen_nr-1`` are not fully aged (equivalent to --the active list) and therefore cannot be evicted. ``swappiness`` -+``max_gen_nr`` and ``max_gen_nr-1`` are not fully aged and therefore -+cannot be evicted. ``swappiness`` - overrides the default value in ``/proc/sys/vm/swappiness`` and the valid - range is [0-200, max], with max being exclusively used for the reclamation - of anonymous memory. ``nr_to_reclaim`` limits the number of pages to evict. -diff --git a/Documentation/admin-guide/sysctl/kernel.rst b/Documentation/admin-guide/sysctl/kernel.rst -index ffea61d..cdeb639 100644 ---- a/Documentation/admin-guide/sysctl/kernel.rst -+++ b/Documentation/admin-guide/sysctl/kernel.rst -@@ -1751,3 +1751,12 @@ is 10 seconds. - - The softlockup threshold is (``2 * watchdog_thresh``). Setting this - tunable to zero will disable lockup detection altogether. -+ -+yield_type: -+=========== -+ -+BMQ/PDS CPU scheduler only. This determines what type of yield calls -+to sched_yield() will be performed. -+ -+ 0 - No yield. -+ 1 - Requeue task. (default) -diff --git a/Documentation/mm/multigen_lru.rst b/Documentation/mm/multigen_lru.rst -index 52ed509..ec8744c 100644 ---- a/Documentation/mm/multigen_lru.rst -+++ b/Documentation/mm/multigen_lru.rst -@@ -95,16 +95,19 @@ at most ``MAX_NR_GENS`` generations. The gen counter stores a value - within ``[1, MAX_NR_GENS]`` while a page is on one of - ``lrugen->folios[]``; otherwise it stores zero. - --Each generation is divided into multiple tiers. A page accessed ``N`` --times through file descriptors is in tier ``order_base_2(N)``. Unlike --generations, tiers do not have dedicated ``lrugen->folios[]``. In --contrast to moving across generations, which requires the LRU lock, --moving across tiers only involves atomic operations on --``folio->flags`` and therefore has a negligible cost. A feedback loop --modeled after the PID controller monitors refaults over all the tiers --from anon and file types and decides which tiers from which types to --evict or protect. The desired effect is to balance refault percentages --between anon and file types proportional to the swappiness level. -+Each generation is divided into multiple tiers. A page's tier is -+derived from its referenced count, which counts the accesses collected -+from both channels above and is capped at ``LRU_REFS_MAX``: pages -+accessed at most once are in the lowest tier, and the tiers above hold -+pages accessed at least twice. Unlike generations, tiers do not have -+dedicated ``lrugen->folios[]``. In contrast to moving across -+generations, which requires the LRU lock, updating the referenced -+count only involves atomic operations on ``folio->flags`` and -+therefore has a negligible cost. A feedback loop modeled after the PID -+controller monitors refaults over all the tiers from anon and file -+types and decides which tiers from which types to evict or protect. -+The desired effect is to balance refault percentages between anon and -+file types proportional to the swappiness level. - - There are two conceptually independent procedures: the aging and the - eviction. They form a closed-loop system, i.e., the page reclaim. -@@ -122,25 +125,31 @@ and calls ``walk_page_range()`` with each ``mm_struct`` on this list - to scan PTEs, and after each iteration, it increments ``max_seq``. For - the latter, when the eviction walks the rmap and finds a young PTE, - the aging scans the adjacent PTEs. For both, on finding a young PTE, --the aging clears the accessed bit and updates the gen counter of the --page mapped by this PTE to ``(max_seq%MAX_NR_GENS)+1``. -+the aging clears the accessed bit and bumps the referenced count of -+the page mapped by this PTE. A second access promotes the page by -+updating its gen counter to ``(max_seq%MAX_NR_GENS)+1``; the first -+access only moves a page one generation forward if it is at the tail -+of its LRU, i.e., in one of the two oldest generations of its type, -+so that the next time it becomes the oldest one, its accessed bit -+reflects whether it has been used again. Executable file pages are -+promoted on their first access, since reclaiming them causes typical -+I/O thrashing. - - Eviction - -------- - The eviction consumes old generations. Given an ``lruvec``, it - increments ``min_seq`` when ``lrugen->folios[]`` indexed by --``min_seq%MAX_NR_GENS`` becomes empty. To select a type and a tier to --evict from, it first compares ``min_seq[]`` to select the older type. --If both types are equally old, it selects the one whose first tier has --a lower refault percentage. The first tier contains single-use --unmapped clean pages, which are the best bet. The eviction sorts a --page according to its gen counter if the aging has found this page --accessed through page tables and updated its gen counter. It also --moves a page to the next generation, i.e., ``min_seq+1``, if this page --was accessed multiple times through file descriptors and the feedback --loop has detected outlying refaults from the tier this page is in. To --this end, the feedback loop uses the first tier as the baseline, for --the reason stated earlier. -+``min_seq%MAX_NR_GENS`` becomes empty. To select a type to evict from, -+it first compares ``min_seq[]`` to select the older type. If both -+types are equally old, it compares the refault percentages of all the -+tiers of each type proportional to the swappiness level. To select a -+tier to protect, it compares the refault percentage of each tier -+against that of the tiers below it. The lowest tier contains pages -+accessed at most once, which are the best bet. The eviction sorts a -+page according to its gen counter if the aging or an access has -+updated its gen counter. It also moves a page to the next generation, -+i.e., ``min_seq+1``, if the feedback loop has detected outlying -+refaults from the tier this page is in. - - Working set protection - ---------------------- -diff --git a/Documentation/scheduler/sched-BMQ.txt b/Documentation/scheduler/sched-BMQ.txt -new file mode 100644 -index 0000000..05c84ee ---- /dev/null -+++ b/Documentation/scheduler/sched-BMQ.txt -@@ -0,0 +1,110 @@ -+ BitMap queue CPU Scheduler -+ -------------------------- -+ -+CONTENT -+======== -+ -+ Background -+ Design -+ Overview -+ Task policy -+ Priority management -+ BitMap Queue -+ CPU Assignment and Migration -+ -+ -+Background -+========== -+ -+BitMap Queue CPU scheduler, referred to as BMQ from here on, is an evolution -+of previous Priority and Deadline based Skiplist multiple queue scheduler(PDS), -+and inspired by Zircon scheduler. The goal of it is to keep the scheduler code -+simple, while efficiency and scalable for interactive tasks, such as desktop, -+movie playback and gaming etc. -+ -+Design -+====== -+ -+Overview -+-------- -+ -+BMQ use per CPU run queue design, each CPU(logical) has it's own run queue, -+each CPU is responsible for scheduling the tasks that are putting into it's -+run queue. -+ -+The run queue is a set of priority queues. Note that these queues are fifo -+queue for non-rt tasks or priority queue for rt tasks in data structure. See -+BitMap Queue below for details. BMQ is optimized for non-rt tasks in the fact -+that most applications are non-rt tasks. No matter the queue is fifo or -+priority, In each queue is an ordered list of runnable tasks awaiting execution -+and the data structures are the same. When it is time for a new task to run, -+the scheduler simply looks the lowest numbered queueue that contains a task, -+and runs the first task from the head of that queue. And per CPU idle task is -+also in the run queue, so the scheduler can always find a task to run on from -+its run queue. -+ -+Each task will assigned the same timeslice(default 4ms) when it is picked to -+start running. Task will be reinserted at the end of the appropriate priority -+queue when it uses its whole timeslice. When the scheduler selects a new task -+from the priority queue it sets the CPU's preemption timer for the remainder of -+the previous timeslice. When that timer fires the scheduler will stop execution -+on that task, select another task and start over again. -+ -+If a task blocks waiting for a shared resource then it's taken out of its -+priority queue and is placed in a wait queue for the shared resource. When it -+is unblocked it will be reinserted in the appropriate priority queue of an -+eligible CPU. -+ -+Task policy -+----------- -+ -+BMQ supports DEADLINE, FIFO, RR, NORMAL, BATCH and IDLE task policy like the -+mainline CFS scheduler. But BMQ is heavy optimized for non-rt task, that's -+NORMAL/BATCH/IDLE policy tasks. Below is the implementation detail of each -+policy. -+ -+DEADLINE -+ It is squashed as priority 0 FIFO task. -+ -+FIFO/RR -+ All RT tasks share one single priority queue in BMQ run queue designed. The -+complexity of insert operation is O(n). BMQ is not designed for system runs -+with major rt policy tasks. -+ -+NORMAL/BATCH/IDLE -+ BATCH and IDLE tasks are treated as the same policy. They compete CPU with -+NORMAL policy tasks, but they just don't boost. To control the priority of -+NORMAL/BATCH/IDLE tasks, simply use nice level. -+ -+ISO -+ ISO policy is not supported in BMQ. Please use nice level -20 NORMAL policy -+task instead. -+ -+Priority management -+------------------- -+ -+RT tasks have priority from 0-99. For non-rt tasks, there are three different -+factors used to determine the effective priority of a task. The effective -+priority being what is used to determine which queue it will be in. -+ -+The first factor is simply the task’s static priority. Which is assigned from -+task's nice level, within [-20, 19] in userland's point of view and [0, 39] -+internally. -+ -+The second factor is the priority boost. This is a value bounded between -+[-MAX_PRIORITY_ADJ, MAX_PRIORITY_ADJ] used to offset the base priority, it is -+modified by the following cases: -+ -+*When a thread has used up its entire timeslice, always deboost its boost by -+increasing by one. -+*When a thread gives up cpu control(voluntary or non-voluntary) to reschedule, -+and its switch-in time(time after last switch and run) below the thredhold -+based on its priority boost, will boost its boost by decreasing by one buti is -+capped at 0 (won’t go negative). -+ -+The intent in this system is to ensure that interactive threads are serviced -+quickly. These are usually the threads that interact directly with the user -+and cause user-perceivable latency. These threads usually do little work and -+spend most of their time blocked awaiting another user event. So they get the -+priority boost from unblocking while background threads that do most of the -+processing receive the priority penalty for using their entire timeslice. -diff --git a/Makefile b/Makefile -index 5e0123c..6c8a280 100644 ---- a/Makefile -+++ b/Makefile -@@ -3,7 +3,7 @@ VERSION = 7 - PATCHLEVEL = 3 - SUBLEVEL = 5 - EXTRAVERSION = -gnu --NAME = Baby Opossum Posse -+NAME = Channeling Inner Peace for Peak Performance - - # *DOCUMENTATION* - # To see a list of typical targets execute "make help" -@@ -932,6 +932,9 @@ KBUILD_CFLAGS += -fno-delete-null-pointer-checks - ifdef CONFIG_CC_OPTIMIZE_FOR_PERFORMANCE - KBUILD_CFLAGS += -O2 - KBUILD_RUSTFLAGS += -Copt-level=2 -+else ifdef CONFIG_CC_OPTIMIZE_FOR_PERFORMANCE_O3 -+KBUILD_CFLAGS += -O3 -+KBUILD_RUSTFLAGS += -Copt-level=3 - else ifdef CONFIG_CC_OPTIMIZE_FOR_SIZE - KBUILD_CFLAGS += -Os - KBUILD_RUSTFLAGS += -Copt-level=s -diff --git a/arch/arm/include/asm/mmu_context.h b/arch/arm/include/asm/mmu_context.h -index db2cb06..bebde46 100644 ---- a/arch/arm/include/asm/mmu_context.h -+++ b/arch/arm/include/asm/mmu_context.h -@@ -80,7 +80,7 @@ static inline void check_and_switch_context(struct mm_struct *mm, - #ifndef MODULE - #define finish_arch_post_lock_switch \ - finish_arch_post_lock_switch --static inline void finish_arch_post_lock_switch(void) -+static __always_inline void finish_arch_post_lock_switch(void) - { - struct mm_struct *mm = current->mm; - -diff --git a/arch/riscv/include/asm/sync_core.h b/arch/riscv/include/asm/sync_core.h -index 9153016..2fe6b7f 100644 ---- a/arch/riscv/include/asm/sync_core.h -+++ b/arch/riscv/include/asm/sync_core.h -@@ -6,7 +6,7 @@ - * RISC-V implements return to user-space through an xRET instruction, - * which is not core serializing. - */ --static inline void sync_core_before_usermode(void) -+static __always_inline void sync_core_before_usermode(void) - { - asm volatile ("fence.i" ::: "memory"); - } -diff --git a/arch/s390/include/asm/mmu_context.h b/arch/s390/include/asm/mmu_context.h -index bd1ef5e..95d03be 100644 ---- a/arch/s390/include/asm/mmu_context.h -+++ b/arch/s390/include/asm/mmu_context.h -@@ -93,7 +93,7 @@ static inline void switch_mm(struct mm_struct *prev, struct mm_struct *next, - } - - #define finish_arch_post_lock_switch finish_arch_post_lock_switch --static inline void finish_arch_post_lock_switch(void) -+static __always_inline void finish_arch_post_lock_switch(void) - { - struct task_struct *tsk = current; - struct mm_struct *mm = tsk->mm; -diff --git a/arch/sparc/include/asm/mmu_context_64.h b/arch/sparc/include/asm/mmu_context_64.h -index 78bbacc..d196721 100644 ---- a/arch/sparc/include/asm/mmu_context_64.h -+++ b/arch/sparc/include/asm/mmu_context_64.h -@@ -160,7 +160,7 @@ static inline void arch_start_context_switch(struct task_struct *prev) - } - - #define finish_arch_post_lock_switch finish_arch_post_lock_switch --static inline void finish_arch_post_lock_switch(void) -+static __always_inline void finish_arch_post_lock_switch(void) - { - /* Restore the state of MCDPER register for the new process - * just switched to. -diff --git a/arch/x86/Kconfig.cpu b/arch/x86/Kconfig.cpu -index 6e7a366..e72e2c2 100644 ---- a/arch/x86/Kconfig.cpu -+++ b/arch/x86/Kconfig.cpu -@@ -229,6 +229,25 @@ config X86_NATIVE_CPU - - If unsure, say N. - -+config X86_64_VERSION -+ int "x86-64 ISA level" -+ range 1 3 -+ default 1 -+ depends on X86_64 && !X86_NATIVE_CPU -+ depends on CC_IS_CLANG || GCC_VERSION >= 110000 -+ help -+ Build the kernel for an x86-64 psABI micro-architecture level. -+ The kernel does not boot on a CPU below the selected level. -+ -+ 1: x86-64 (baseline) -+ 2: x86-64-v2 -+ 3: x86-64-v3 -+ -+ Run "/lib64/ld-linux-x86-64.so.2 --help" to see the levels -+ that this CPU supports. -+ -+ If unsure, say 1. -+ - config X86_GENERIC - bool "Generic x86 support" - depends on X86_32 -diff --git a/arch/x86/Makefile b/arch/x86/Makefile -index 8af6b80..9c25454 100644 ---- a/arch/x86/Makefile -+++ b/arch/x86/Makefile -@@ -73,7 +73,7 @@ export BITS - # - # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53383 - # --KBUILD_CFLAGS += -mno-sse -mno-mmx -mno-sse2 -mno-3dnow -mno-avx -mno-sse4a -+KBUILD_CFLAGS += -mno-sse -mno-mmx -mno-sse2 -mno-3dnow -mno-avx -mno-sse4a -mno-avx2 -fno-tree-vectorize - KBUILD_RUSTFLAGS += --target=$(objtree)/scripts/target.json - KBUILD_RUSTFLAGS += -Ctarget-feature=-sse,-sse2,-sse3,-ssse3,-sse4.1,-sse4.2,-avx,-avx2 - -@@ -167,6 +167,9 @@ ifdef CONFIG_X86_NATIVE_CPU - - # generate_rust_target.rs handles Rust APX gating. - KBUILD_RUSTFLAGS += -Ctarget-cpu=native -+else ifneq ($(filter-out 1,$(CONFIG_X86_64_VERSION)),) -+ KBUILD_CFLAGS += -march=x86-64-v$(CONFIG_X86_64_VERSION) -mtune=generic -+ KBUILD_RUSTFLAGS += -Ctarget-cpu=x86-64-v$(CONFIG_X86_64_VERSION) -Ztune-cpu=generic - else - KBUILD_CFLAGS += -march=x86-64 -mtune=generic - KBUILD_RUSTFLAGS += -Ctarget-cpu=x86-64 -Ztune-cpu=generic -diff --git a/arch/x86/include/asm/sync_core.h b/arch/x86/include/asm/sync_core.h -index df22113..3b0ed46 100644 ---- a/arch/x86/include/asm/sync_core.h -+++ b/arch/x86/include/asm/sync_core.h -@@ -93,7 +93,7 @@ static __always_inline void sync_core(void) - * to user-mode. x86 implements return to user-space through sysexit, - * sysrel, and sysretq, which are not core serializing. - */ --static inline void sync_core_before_usermode(void) -+static __always_inline void sync_core_before_usermode(void) - { - /* With PTI, we unconditionally serialize before running user code. */ - if (cpu_feature_enabled(X86_FEATURE_PTI)) -diff --git a/arch/x86/kernel/cpu/bus_lock.c b/arch/x86/kernel/cpu/bus_lock.c -index 177f964..a5c1338 100644 ---- a/arch/x86/kernel/cpu/bus_lock.c -+++ b/arch/x86/kernel/cpu/bus_lock.c -@@ -47,7 +47,11 @@ static const struct { - - static struct ratelimit_state bld_ratelimit; - -+#ifdef CONFIG_ZEN_INTERACTIVE -+static unsigned int sysctl_sld_mitigate; -+#else - static unsigned int sysctl_sld_mitigate = 1; -+#endif - static DEFINE_SEMAPHORE(buslock_sem, 1); - - #ifdef CONFIG_SYSCTL -diff --git a/block/elevator.c b/block/elevator.c -index 66edf1a..8fd2341 100644 ---- a/block/elevator.c -+++ b/block/elevator.c -@@ -729,7 +729,11 @@ void elv_update_nr_hw_queues(struct request_queue *q, - void elevator_set_default(struct request_queue *q) - { - struct elv_change_ctx ctx = { -+#if defined(CONFIG_ZEN_INTERACTIVE) && defined(CONFIG_IOSCHED_BFQ) -+ .name = "bfq", -+#else - .name = "mq-deadline", -+#endif - .no_uevent = true, - }; - int err; -@@ -745,17 +749,22 @@ void elevator_set_default(struct request_queue *q) - * have multiple queues or mq-deadline is not available, default - * to "none". - */ -+ if (q->nr_hw_queues != 1 && !blk_mq_is_shared_tags(q->tag_set->flags)) -+#if defined(CONFIG_ZEN_INTERACTIVE) && defined(CONFIG_MQ_IOSCHED_KYBER) -+ ctx.name = "kyber"; -+#else -+ return; -+#endif -+ - ctx.type = elevator_find_get(ctx.name); - if (!ctx.type) - return; - -- if ((q->nr_hw_queues == 1 || -- blk_mq_is_shared_tags(q->tag_set->flags))) { -- err = elevator_change(q, &ctx); -- if (err < 0) -- pr_warn("\"%s\" elevator initialization, failed %d, falling back to \"none\"\n", -- ctx.name, err); -- } -+ err = elevator_change(q, &ctx); -+ if (err < 0) -+ pr_warn("\"%s\" elevator initialization, failed %d, falling back to \"none\"\n", -+ ctx.name, err); -+ - elevator_put(ctx.type); - } - -diff --git a/crypto/acompress.c b/crypto/acompress.c -index 4de1a2a..c8b4b85 100644 ---- a/crypto/acompress.c -+++ b/crypto/acompress.c -@@ -92,10 +92,6 @@ static int crypto_acomp_init_tfm(struct crypto_tfm *tfm) - if (IS_ERR(fb)) - return PTR_ERR(fb); - -- err = -EINVAL; -- if (crypto_acomp_reqsize(fb) > MAX_SYNC_COMP_REQSIZE) -- goto out_free_fb; -- - tfm->fb = crypto_acomp_tfm(fb); - } - -@@ -105,15 +101,19 @@ static int crypto_acomp_init_tfm(struct crypto_tfm *tfm) - - acomp->base.exit = crypto_acomp_exit_tfm; - -- if (!alg->init) -- return 0; -- -- err = alg->init(acomp); -- if (err) -+ if (alg->init && ((err = alg->init(acomp)))) - goto out_free_fb; - -+ err = -EINVAL; -+ if (!acomp_is_async(acomp) && -+ crypto_acomp_reqsize(acomp) > MAX_SYNC_COMP_REQSIZE) -+ goto out_exit_tfm; -+ - return 0; - -+out_exit_tfm: -+ if (alg->exit) -+ alg->exit(acomp); - out_free_fb: - crypto_free_acomp(fb); - return err; -diff --git a/drivers/block/zram/backend_842.c b/drivers/block/zram/backend_842.c -index 3846a04..f911cd1 100644 ---- a/drivers/block/zram/backend_842.c -+++ b/drivers/block/zram/backend_842.c -@@ -1,6 +1,6 @@ - // SPDX-License-Identifier: GPL-2.0-or-later - --#define pr_fmt(fmt) "842: " fmt -+#define pr_fmt(fmt) "zram: 842: " fmt - - #include - #include -@@ -63,8 +63,8 @@ static int decompress_842(struct zcomp_params *params, struct zcomp_ctx *ctx, - const struct zcomp_ops backend_842 = { - .compress = compress_842, - .decompress = decompress_842, -- .create_ctx = create_842, -- .destroy_ctx = destroy_842, -+ .create_cctx = create_842, -+ .destroy_cctx = destroy_842, - .setup_params = setup_params_842, - .release_params = release_params_842, - .name = "842", -diff --git a/drivers/block/zram/backend_deflate.c b/drivers/block/zram/backend_deflate.c -index f71b11b..5ffdaf8 100644 ---- a/drivers/block/zram/backend_deflate.c -+++ b/drivers/block/zram/backend_deflate.c -@@ -1,6 +1,6 @@ - // SPDX-License-Identifier: GPL-2.0-or-later - --#define pr_fmt(fmt) "deflate: " fmt -+#define pr_fmt(fmt) "zram: deflate: " fmt - - #include - #include -@@ -13,11 +13,6 @@ - #define DEFLATE_DEF_WINBITS (-11) - #define DEFLATE_DEF_MEMLEVEL MAX_MEM_LEVEL - --struct deflate_ctx { -- struct z_stream_s cctx; -- struct z_stream_s dctx; --}; -- - static void deflate_release_params(struct zcomp_params *params) - { - } -@@ -51,70 +46,98 @@ static int deflate_setup_params(struct zcomp_params *params) - return 0; - } - --static void deflate_destroy(struct zcomp_ctx *ctx) -+static void deflate_destroy_cctx(struct zcomp_ctx *ctx) - { -- struct deflate_ctx *zctx = ctx->context; -+ struct z_stream_s *cctx = ctx->context; - -- if (!zctx) -+ if (!cctx) - return; - -- if (zctx->cctx.workspace) { -- zlib_deflateEnd(&zctx->cctx); -- vfree(zctx->cctx.workspace); -- } -- if (zctx->dctx.workspace) { -- zlib_inflateEnd(&zctx->dctx); -- vfree(zctx->dctx.workspace); -+ if (cctx->workspace) { -+ zlib_deflateEnd(cctx); -+ vfree(cctx->workspace); - } -- kfree(zctx); -+ kfree(cctx); - } - --static int deflate_create(struct zcomp_params *params, struct zcomp_ctx *ctx) -+static int deflate_create_cctx(struct zcomp_params *params, -+ struct zcomp_ctx *ctx) - { -- struct deflate_ctx *zctx; -+ struct z_stream_s *cctx; - size_t sz; - int ret; - -- zctx = kzalloc_obj(*zctx); -- if (!zctx) -+ cctx = kzalloc_obj(*cctx); -+ if (!cctx) - return -ENOMEM; - -- ctx->context = zctx; -+ ctx->context = cctx; - sz = zlib_deflate_workspacesize(params->deflate.winbits, MAX_MEM_LEVEL); -- zctx->cctx.workspace = vzalloc(sz); -- if (!zctx->cctx.workspace) -+ cctx->workspace = vzalloc(sz); -+ if (!cctx->workspace) - goto error; - -- ret = zlib_deflateInit2(&zctx->cctx, params->level, Z_DEFLATED, -+ ret = zlib_deflateInit2(cctx, params->level, Z_DEFLATED, - params->deflate.winbits, DEFLATE_DEF_MEMLEVEL, - Z_DEFAULT_STRATEGY); - if (ret != Z_OK) - goto error; - -+ return 0; -+ -+error: -+ deflate_destroy_cctx(ctx); -+ return -EINVAL; -+} -+ -+static void deflate_destroy_dctx(struct zcomp_ctx *ctx) -+{ -+ struct z_stream_s *dctx = ctx->context; -+ -+ if (!dctx) -+ return; -+ -+ if (dctx->workspace) { -+ zlib_inflateEnd(dctx); -+ vfree(dctx->workspace); -+ } -+ kfree(dctx); -+} -+ -+static int deflate_create_dctx(struct zcomp_params *params, -+ struct zcomp_ctx *ctx) -+{ -+ struct z_stream_s *dctx; -+ size_t sz; -+ int ret; -+ -+ dctx = kzalloc_obj(*dctx); -+ if (!dctx) -+ return -ENOMEM; -+ -+ ctx->context = dctx; - sz = zlib_inflate_workspacesize(); -- zctx->dctx.workspace = vzalloc(sz); -- if (!zctx->dctx.workspace) -+ dctx->workspace = vzalloc(sz); -+ if (!dctx->workspace) - goto error; - -- ret = zlib_inflateInit2(&zctx->dctx, params->deflate.winbits); -+ ret = zlib_inflateInit2(dctx, params->deflate.winbits); - if (ret != Z_OK) - goto error; - - return 0; - - error: -- deflate_destroy(ctx); -+ deflate_destroy_dctx(ctx); - return -EINVAL; - } - - static int deflate_compress(struct zcomp_params *params, struct zcomp_ctx *ctx, - struct zcomp_req *req) - { -- struct deflate_ctx *zctx = ctx->context; -- struct z_stream_s *deflate; -+ struct z_stream_s *deflate = ctx->context; - int ret; - -- deflate = &zctx->cctx; - ret = zlib_deflateReset(deflate); - if (ret != Z_OK) - return -EINVAL; -@@ -136,12 +159,9 @@ static int deflate_decompress(struct zcomp_params *params, - struct zcomp_ctx *ctx, - struct zcomp_req *req) - { -- struct deflate_ctx *zctx = ctx->context; -- struct z_stream_s *inflate; -+ struct z_stream_s *inflate = ctx->context; - int ret; - -- inflate = &zctx->dctx; -- - ret = zlib_inflateReset(inflate); - if (ret != Z_OK) - return -EINVAL; -@@ -161,8 +181,10 @@ static int deflate_decompress(struct zcomp_params *params, - const struct zcomp_ops backend_deflate = { - .compress = deflate_compress, - .decompress = deflate_decompress, -- .create_ctx = deflate_create, -- .destroy_ctx = deflate_destroy, -+ .create_cctx = deflate_create_cctx, -+ .destroy_cctx = deflate_destroy_cctx, -+ .create_dctx = deflate_create_dctx, -+ .destroy_dctx = deflate_destroy_dctx, - .setup_params = deflate_setup_params, - .release_params = deflate_release_params, - .name = "deflate", -diff --git a/drivers/block/zram/backend_lz4.c b/drivers/block/zram/backend_lz4.c -index 1e4ad31..9767482 100644 ---- a/drivers/block/zram/backend_lz4.c -+++ b/drivers/block/zram/backend_lz4.c -@@ -1,21 +1,13 @@ - // SPDX-License-Identifier: GPL-2.0-or-later - --#define pr_fmt(fmt) "lz4: " fmt -+#define pr_fmt(fmt) "zram: lz4: " fmt - - #include - #include --#include - #include - - #include "backend_lz4.h" - --struct lz4_ctx { -- void *mem; -- -- LZ4_streamDecode_t *dstrm; -- LZ4_stream_t *cstrm; --}; -- - static void lz4_release_params(struct zcomp_params *params) - { - LZ4_stream_t *dict_stream = params->drv_data; -@@ -24,7 +16,7 @@ static void lz4_release_params(struct zcomp_params *params) - if (!dict_stream) - return; - -- kfree(dict_stream); -+ vfree(dict_stream); - } - - static int lz4_setup_params(struct zcomp_params *params) -@@ -42,14 +34,13 @@ static int lz4_setup_params(struct zcomp_params *params) - if (!params->dict || !params->dict_sz) - return 0; - -- dict_stream = kzalloc_obj(*dict_stream); -+ dict_stream = vzalloc(sizeof(*dict_stream)); - if (!dict_stream) - return -ENOMEM; - -- ret = LZ4_loadDict(dict_stream, -- params->dict, params->dict_sz); -+ ret = LZ4_loadDict(dict_stream, params->dict, params->dict_sz); - if (ret != params->dict_sz) { -- kfree(dict_stream); -+ vfree(dict_stream); - return -EINVAL; - } - params->drv_data = dict_stream; -@@ -59,61 +50,32 @@ static int lz4_setup_params(struct zcomp_params *params) - - static void lz4_destroy(struct zcomp_ctx *ctx) - { -- struct lz4_ctx *zctx = ctx->context; -- -- if (!zctx) -- return; -- -- vfree(zctx->mem); -- kfree(zctx->dstrm); -- kfree(zctx->cstrm); -- kfree(zctx); -+ vfree(ctx->context); - } - - static int lz4_create(struct zcomp_params *params, struct zcomp_ctx *ctx) - { -- struct lz4_ctx *zctx; -+ BUILD_BUG_ON(sizeof(LZ4_stream_t) != LZ4_MEM_COMPRESS); - -- zctx = kzalloc_obj(*zctx); -- if (!zctx) -+ ctx->context = vmalloc(LZ4_MEM_COMPRESS); -+ if (!ctx->context) - return -ENOMEM; -- -- ctx->context = zctx; -- if (params->dict_sz == 0) { -- zctx->mem = vmalloc(LZ4_MEM_COMPRESS); -- if (!zctx->mem) -- goto error; -- } else { -- zctx->dstrm = kzalloc_obj(*zctx->dstrm); -- if (!zctx->dstrm) -- goto error; -- -- zctx->cstrm = kzalloc_obj(*zctx->cstrm); -- if (!zctx->cstrm) -- goto error; -- } -- - return 0; -- --error: -- lz4_destroy(ctx); -- return -ENOMEM; - } - - static int lz4_compress(struct zcomp_params *params, struct zcomp_ctx *ctx, - struct zcomp_req *req) - { -- struct lz4_ctx *zctx = ctx->context; - int ret; - -- if (!zctx->cstrm) { -+ if (!params->drv_data) { - ret = LZ4_compress_fast(req->src, req->dst, req->src_len, - req->dst_len, params->level, -- zctx->mem); -+ ctx->context); - } else { - /* Cstrm needs to be reset */ -- memcpy(zctx->cstrm, params->drv_data, sizeof(*zctx->cstrm)); -- ret = LZ4_compress_fast_continue(zctx->cstrm, req->src, -+ memcpy(ctx->context, params->drv_data, sizeof(LZ4_stream_t)); -+ ret = LZ4_compress_fast_continue(ctx->context, req->src, - req->dst, req->src_len, - req->dst_len, params->level); - } -@@ -126,22 +88,11 @@ static int lz4_compress(struct zcomp_params *params, struct zcomp_ctx *ctx, - static int lz4_decompress(struct zcomp_params *params, struct zcomp_ctx *ctx, - struct zcomp_req *req) - { -- struct lz4_ctx *zctx = ctx->context; - int ret; - -- if (!zctx->dstrm) { -- ret = LZ4_decompress_safe(req->src, req->dst, req->src_len, -- req->dst_len); -- } else { -- /* Dstrm needs to be reset */ -- ret = LZ4_setStreamDecode(zctx->dstrm, params->dict, -- params->dict_sz); -- if (!ret) -- return -EINVAL; -- ret = LZ4_decompress_safe_continue(zctx->dstrm, req->src, -- req->dst, req->src_len, -- req->dst_len); -- } -+ ret = LZ4_decompress_safe_usingDict(req->src, req->dst, req->src_len, -+ req->dst_len, params->dict, -+ params->dict_sz); - if (ret < 0) - return -EINVAL; - return 0; -@@ -150,8 +101,8 @@ static int lz4_decompress(struct zcomp_params *params, struct zcomp_ctx *ctx, - const struct zcomp_ops backend_lz4 = { - .compress = lz4_compress, - .decompress = lz4_decompress, -- .create_ctx = lz4_create, -- .destroy_ctx = lz4_destroy, -+ .create_cctx = lz4_create, -+ .destroy_cctx = lz4_destroy, - .setup_params = lz4_setup_params, - .release_params = lz4_release_params, - .name = "lz4", -diff --git a/drivers/block/zram/backend_lz4hc.c b/drivers/block/zram/backend_lz4hc.c -index d8aa01b..2d1364a 100644 ---- a/drivers/block/zram/backend_lz4hc.c -+++ b/drivers/block/zram/backend_lz4hc.c -@@ -1,27 +1,29 @@ - // SPDX-License-Identifier: GPL-2.0-or-later - --#define pr_fmt(fmt) "lz4hc: " fmt -+#define pr_fmt(fmt) "zram: lz4hc: " fmt - - #include - #include --#include - #include - - #include "backend_lz4hc.h" - --struct lz4hc_ctx { -- void *mem; -- -- LZ4_streamDecode_t *dstrm; -- LZ4_streamHC_t *cstrm; --}; -- - static void lz4hc_release_params(struct zcomp_params *params) - { -+ LZ4_streamHC_t *dict_stream = params->drv_data; -+ -+ params->drv_data = NULL; -+ if (!dict_stream) -+ return; -+ -+ vfree(dict_stream); - } - - static int lz4hc_setup_params(struct zcomp_params *params) - { -+ LZ4_streamHC_t *dict_stream; -+ int ret; -+ - if (params->level == ZCOMP_PARAM_NOT_SET) { - params->level = LZ4HC_DEFAULT_CLEVEL; - } else if (params->level < 1 || params->level > LZ4HC_MAX_CLEVEL) { -@@ -35,70 +37,52 @@ static int lz4hc_setup_params(struct zcomp_params *params) - return -EINVAL; - } - -+ if (!params->dict || !params->dict_sz) -+ return 0; -+ -+ dict_stream = vzalloc(sizeof(*dict_stream)); -+ if (!dict_stream) -+ return -ENOMEM; -+ -+ LZ4_resetStreamHC(dict_stream, params->level); -+ ret = LZ4_loadDictHC(dict_stream, params->dict, params->dict_sz); -+ if (ret != params->dict_sz) { -+ vfree(dict_stream); -+ return -EINVAL; -+ } -+ params->drv_data = dict_stream; -+ - return 0; - } - - static void lz4hc_destroy(struct zcomp_ctx *ctx) - { -- struct lz4hc_ctx *zctx = ctx->context; -- -- if (!zctx) -- return; -- -- kfree(zctx->dstrm); -- kfree(zctx->cstrm); -- vfree(zctx->mem); -- kfree(zctx); -+ vfree(ctx->context); - } - - static int lz4hc_create(struct zcomp_params *params, struct zcomp_ctx *ctx) - { -- struct lz4hc_ctx *zctx; -+ BUILD_BUG_ON(sizeof(LZ4_streamHC_t) != LZ4HC_MEM_COMPRESS); - -- zctx = kzalloc_obj(*zctx); -- if (!zctx) -+ ctx->context = vmalloc(LZ4HC_MEM_COMPRESS); -+ if (!ctx->context) - return -ENOMEM; -- -- ctx->context = zctx; -- if (params->dict_sz == 0) { -- zctx->mem = vmalloc(LZ4HC_MEM_COMPRESS); -- if (!zctx->mem) -- goto error; -- } else { -- zctx->dstrm = kzalloc_obj(*zctx->dstrm); -- if (!zctx->dstrm) -- goto error; -- -- zctx->cstrm = kzalloc_obj(*zctx->cstrm); -- if (!zctx->cstrm) -- goto error; -- } -- - return 0; -- --error: -- lz4hc_destroy(ctx); -- return -EINVAL; - } - - static int lz4hc_compress(struct zcomp_params *params, struct zcomp_ctx *ctx, - struct zcomp_req *req) - { -- struct lz4hc_ctx *zctx = ctx->context; - int ret; - -- if (!zctx->cstrm) { -+ if (!params->drv_data) { - ret = LZ4_compress_HC(req->src, req->dst, req->src_len, - req->dst_len, params->level, -- zctx->mem); -+ ctx->context); - } else { - /* Cstrm needs to be reset */ -- LZ4_resetStreamHC(zctx->cstrm, params->level); -- ret = LZ4_loadDictHC(zctx->cstrm, params->dict, -- params->dict_sz); -- if (ret != params->dict_sz) -- return -EINVAL; -- ret = LZ4_compress_HC_continue(zctx->cstrm, req->src, req->dst, -+ memcpy(ctx->context, params->drv_data, sizeof(LZ4_streamHC_t)); -+ ret = LZ4_compress_HC_continue(ctx->context, req->src, req->dst, - req->src_len, req->dst_len); - } - if (!ret) -@@ -110,22 +94,11 @@ static int lz4hc_compress(struct zcomp_params *params, struct zcomp_ctx *ctx, - static int lz4hc_decompress(struct zcomp_params *params, struct zcomp_ctx *ctx, - struct zcomp_req *req) - { -- struct lz4hc_ctx *zctx = ctx->context; - int ret; - -- if (!zctx->dstrm) { -- ret = LZ4_decompress_safe(req->src, req->dst, req->src_len, -- req->dst_len); -- } else { -- /* Dstrm needs to be reset */ -- ret = LZ4_setStreamDecode(zctx->dstrm, params->dict, -- params->dict_sz); -- if (!ret) -- return -EINVAL; -- ret = LZ4_decompress_safe_continue(zctx->dstrm, req->src, -- req->dst, req->src_len, -- req->dst_len); -- } -+ ret = LZ4_decompress_safe_usingDict(req->src, req->dst, req->src_len, -+ req->dst_len, params->dict, -+ params->dict_sz); - if (ret < 0) - return -EINVAL; - return 0; -@@ -134,8 +107,8 @@ static int lz4hc_decompress(struct zcomp_params *params, struct zcomp_ctx *ctx, - const struct zcomp_ops backend_lz4hc = { - .compress = lz4hc_compress, - .decompress = lz4hc_decompress, -- .create_ctx = lz4hc_create, -- .destroy_ctx = lz4hc_destroy, -+ .create_cctx = lz4hc_create, -+ .destroy_cctx = lz4hc_destroy, - .setup_params = lz4hc_setup_params, - .release_params = lz4hc_release_params, - .name = "lz4hc", -diff --git a/drivers/block/zram/backend_lzo.c b/drivers/block/zram/backend_lzo.c -index d83f92c..e703560 100644 ---- a/drivers/block/zram/backend_lzo.c -+++ b/drivers/block/zram/backend_lzo.c -@@ -1,6 +1,6 @@ - // SPDX-License-Identifier: GPL-2.0-or-later - --#define pr_fmt(fmt) "lzo: " fmt -+#define pr_fmt(fmt) "zram: lzo: " fmt - - #include - #include -@@ -61,8 +61,8 @@ static int lzo_decompress(struct zcomp_params *params, struct zcomp_ctx *ctx, - const struct zcomp_ops backend_lzo = { - .compress = lzo_compress, - .decompress = lzo_decompress, -- .create_ctx = lzo_create, -- .destroy_ctx = lzo_destroy, -+ .create_cctx = lzo_create, -+ .destroy_cctx = lzo_destroy, - .setup_params = lzo_setup_params, - .release_params = lzo_release_params, - .name = "lzo", -diff --git a/drivers/block/zram/backend_lzorle.c b/drivers/block/zram/backend_lzorle.c -index 1b120d0..e95026e 100644 ---- a/drivers/block/zram/backend_lzorle.c -+++ b/drivers/block/zram/backend_lzorle.c -@@ -1,6 +1,6 @@ - // SPDX-License-Identifier: GPL-2.0-or-later - --#define pr_fmt(fmt) "lzo-rle: " fmt -+#define pr_fmt(fmt) "zram: lzo-rle: " fmt - - #include - #include -@@ -61,8 +61,8 @@ static int lzorle_decompress(struct zcomp_params *params, struct zcomp_ctx *ctx, - const struct zcomp_ops backend_lzorle = { - .compress = lzorle_compress, - .decompress = lzorle_decompress, -- .create_ctx = lzorle_create, -- .destroy_ctx = lzorle_destroy, -+ .create_cctx = lzorle_create, -+ .destroy_cctx = lzorle_destroy, - .setup_params = lzorle_setup_params, - .release_params = lzorle_release_params, - .name = "lzo-rle", -diff --git a/drivers/block/zram/backend_zstd.c b/drivers/block/zram/backend_zstd.c -index 08da381..d55615f 100644 ---- a/drivers/block/zram/backend_zstd.c -+++ b/drivers/block/zram/backend_zstd.c -@@ -1,6 +1,6 @@ - // SPDX-License-Identifier: GPL-2.0-or-later - --#define pr_fmt(fmt) "zstd: " fmt -+#define pr_fmt(fmt) "zram: zstd: " fmt - - #include - #include -@@ -10,10 +10,8 @@ - #include "backend_zstd.h" - - struct zstd_ctx { -- zstd_cctx *cctx; -- zstd_dctx *dctx; -- void *cctx_mem; -- void *dctx_mem; -+ void *ctx; -+ void *mem; - }; - - struct zstd_params { -@@ -26,10 +24,17 @@ struct zstd_params { - /* - * For C/D dictionaries we need to provide zstd with zstd_custom_mem, - * which zstd uses internally to allocate/free memory when needed. -+ * -+ * zstd allocations (C/D dictionaries and contexts) are large and -+ * long-lived. Don't use kvzalloc() for them: when enough physically -+ * contiguous memory is available it serves them from kmalloc(), which -+ * rounds them up to a power-of-two number of pages. - */ - static void *zstd_custom_alloc(void *opaque, size_t size) - { -- return kvzalloc(size, GFP_NOIO | __GFP_NOWARN); -+ if (size <= PAGE_SIZE) -+ return kzalloc(size, GFP_NOIO | __GFP_NOWARN); -+ return __vmalloc(size, GFP_NOIO | __GFP_NOWARN | __GFP_ZERO); - } - - static void zstd_custom_free(void *opaque, void *address) -@@ -76,6 +81,9 @@ static int zstd_setup_params(struct zcomp_params *params) - prm = zstd_get_cparams(params->level, PAGE_SIZE, - params->dict_sz); - -+ if (!params->dict || !params->dict_sz) -+ return 0; -+ - zp->cdict = zstd_create_cdict_byreference(params->dict, - params->dict_sz, - prm, -@@ -95,7 +103,7 @@ static int zstd_setup_params(struct zcomp_params *params) - return -EINVAL; - } - --static void zstd_destroy(struct zcomp_ctx *ctx) -+static void zstd_destroy_cctx(struct zcomp_ctx *ctx) - { - struct zstd_ctx *zctx = ctx->context; - -@@ -103,30 +111,23 @@ static void zstd_destroy(struct zcomp_ctx *ctx) - return; - - /* -- * If ->cctx_mem and ->dctx_mem were allocated then we didn't use -- * C/D dictionary and ->cctx / ->dctx were "embedded" into these -- * buffers. -+ * If ->mem was allocated then we didn't use C/D dictionary and -+ * ->ctx was "embedded" into this buffer. - * -- * If otherwise then we need to explicitly release ->cctx / ->dctx. -+ * If otherwise then we need to explicitly release ->ctx. - */ -- if (zctx->cctx_mem) -- vfree(zctx->cctx_mem); -- else -- zstd_free_cctx(zctx->cctx); -- -- if (zctx->dctx_mem) -- vfree(zctx->dctx_mem); -+ if (zctx->mem) -+ vfree(zctx->mem); - else -- zstd_free_dctx(zctx->dctx); -+ zstd_free_cctx(zctx->ctx); - - kfree(zctx); - } - --static int zstd_create(struct zcomp_params *params, struct zcomp_ctx *ctx) -+static int zstd_create_cctx(struct zcomp_params *params, struct zcomp_ctx *ctx) - { -+ struct zstd_params *zp = params->drv_data; - struct zstd_ctx *zctx; -- zstd_parameters prm; -- size_t sz; - - zctx = kzalloc_obj(*zctx); - if (!zctx) -@@ -134,40 +135,74 @@ static int zstd_create(struct zcomp_params *params, struct zcomp_ctx *ctx) - - ctx->context = zctx; - if (params->dict_sz == 0) { -- prm = zstd_get_params(params->level, PAGE_SIZE); -- sz = zstd_cctx_workspace_bound(&prm.cParams); -- zctx->cctx_mem = vzalloc(sz); -- if (!zctx->cctx_mem) -- goto error; -+ zstd_parameters prm = zp->cprm; -+ size_t sz = zstd_cctx_workspace_bound(&prm.cParams); - -- zctx->cctx = zstd_init_cctx(zctx->cctx_mem, sz); -- if (!zctx->cctx) -+ zctx->mem = vzalloc(sz); -+ if (!zctx->mem) - goto error; - -- sz = zstd_dctx_workspace_bound(); -- zctx->dctx_mem = vzalloc(sz); -- if (!zctx->dctx_mem) -- goto error; -- -- zctx->dctx = zstd_init_dctx(zctx->dctx_mem, sz); -- if (!zctx->dctx) -+ zctx->ctx = zstd_init_cctx(zctx->mem, sz); -+ if (!zctx->ctx) - goto error; - } else { -- struct zstd_params *zp = params->drv_data; -+ zctx->ctx = zstd_create_cctx_advanced(zp->custom_mem); -+ if (!zctx->ctx) -+ goto error; -+ } -+ -+ return 0; -+ -+error: -+ zstd_destroy_cctx(ctx); -+ return -EINVAL; -+} - -- zctx->cctx = zstd_create_cctx_advanced(zp->custom_mem); -- if (!zctx->cctx) -+static void zstd_destroy_dctx(struct zcomp_ctx *ctx) -+{ -+ struct zstd_ctx *zctx = ctx->context; -+ -+ if (!zctx) -+ return; -+ -+ if (zctx->mem) -+ vfree(zctx->mem); -+ else -+ zstd_free_dctx(zctx->ctx); -+ -+ kfree(zctx); -+} -+ -+static int zstd_create_dctx(struct zcomp_params *params, struct zcomp_ctx *ctx) -+{ -+ struct zstd_params *zp = params->drv_data; -+ struct zstd_ctx *zctx; -+ -+ zctx = kzalloc_obj(*zctx); -+ if (!zctx) -+ return -ENOMEM; -+ -+ ctx->context = zctx; -+ if (params->dict_sz == 0) { -+ size_t sz = zstd_dctx_workspace_bound(); -+ -+ zctx->mem = vzalloc(sz); -+ if (!zctx->mem) - goto error; - -- zctx->dctx = zstd_create_dctx_advanced(zp->custom_mem); -- if (!zctx->dctx) -+ zctx->ctx = zstd_init_dctx(zctx->mem, sz); -+ if (!zctx->ctx) -+ goto error; -+ } else { -+ zctx->ctx = zstd_create_dctx_advanced(zp->custom_mem); -+ if (!zctx->ctx) - goto error; - } - - return 0; - - error: -- zstd_destroy(ctx); -+ zstd_destroy_dctx(ctx); - return -EINVAL; - } - -@@ -179,10 +214,10 @@ static int zstd_compress(struct zcomp_params *params, struct zcomp_ctx *ctx, - size_t ret; - - if (params->dict_sz == 0) -- ret = zstd_compress_cctx(zctx->cctx, req->dst, req->dst_len, -+ ret = zstd_compress_cctx(zctx->ctx, req->dst, req->dst_len, - req->src, req->src_len, &zp->cprm); - else -- ret = zstd_compress_using_cdict(zctx->cctx, req->dst, -+ ret = zstd_compress_using_cdict(zctx->ctx, req->dst, - req->dst_len, req->src, - req->src_len, - zp->cdict); -@@ -200,10 +235,10 @@ static int zstd_decompress(struct zcomp_params *params, struct zcomp_ctx *ctx, - size_t ret; - - if (params->dict_sz == 0) -- ret = zstd_decompress_dctx(zctx->dctx, req->dst, req->dst_len, -+ ret = zstd_decompress_dctx(zctx->ctx, req->dst, req->dst_len, - req->src, req->src_len); - else -- ret = zstd_decompress_using_ddict(zctx->dctx, req->dst, -+ ret = zstd_decompress_using_ddict(zctx->ctx, req->dst, - req->dst_len, req->src, - req->src_len, zp->ddict); - if (zstd_is_error(ret)) -@@ -214,8 +249,10 @@ static int zstd_decompress(struct zcomp_params *params, struct zcomp_ctx *ctx, - const struct zcomp_ops backend_zstd = { - .compress = zstd_compress, - .decompress = zstd_decompress, -- .create_ctx = zstd_create, -- .destroy_ctx = zstd_destroy, -+ .create_cctx = zstd_create_cctx, -+ .destroy_cctx = zstd_destroy_cctx, -+ .create_dctx = zstd_create_dctx, -+ .destroy_dctx = zstd_destroy_dctx, - .setup_params = zstd_setup_params, - .release_params = zstd_release_params, - .name = "zstd", -diff --git a/drivers/block/zram/zcomp.c b/drivers/block/zram/zcomp.c -index 974c469..ad8c7dc 100644 ---- a/drivers/block/zram/zcomp.c -+++ b/drivers/block/zram/zcomp.c -@@ -7,6 +7,8 @@ - #include - #include - #include -+#include -+#include - #include - #include - -@@ -43,30 +45,65 @@ static const struct zcomp_ops *backends[] = { - NULL - }; - --static void zcomp_strm_free(struct zcomp *comp, struct zcomp_strm *zstrm) -+static void zcomp_cstrm_free(struct zcomp *comp, struct zcomp_cstrm *zstrm) - { -- comp->ops->destroy_ctx(&zstrm->ctx); -- vfree(zstrm->local_copy); -+ if (comp->ops->destroy_cctx) -+ comp->ops->destroy_cctx(&zstrm->ctx); - vfree(zstrm->buffer); - zstrm->buffer = NULL; -+ zstrm->ctx.context = NULL; - } - --static int zcomp_strm_init(struct zcomp *comp, struct zcomp_strm *zstrm) -+static int zcomp_cstrm_init(struct zcomp *comp, struct zcomp_cstrm *zstrm) - { - int ret; - -- ret = comp->ops->create_ctx(comp->params, &zstrm->ctx); -- if (ret) -- return ret; -+ if (comp->ops->create_cctx) { -+ ret = comp->ops->create_cctx(comp->params, &zstrm->ctx); -+ if (ret) { -+ /* backend has released partially created context */ -+ zstrm->ctx.context = NULL; -+ return ret; -+ } -+ } - -- zstrm->local_copy = vzalloc(PAGE_SIZE); - /* - * allocate 2 pages. 1 for compressed data, plus 1 extra for the - * case when compressed size is larger than the original one - */ - zstrm->buffer = vzalloc(2 * PAGE_SIZE); -- if (!zstrm->buffer || !zstrm->local_copy) { -- zcomp_strm_free(comp, zstrm); -+ if (!zstrm->buffer) { -+ zcomp_cstrm_free(comp, zstrm); -+ return -ENOMEM; -+ } -+ return 0; -+} -+ -+static void zcomp_dstrm_free(struct zcomp *comp, struct zcomp_dstrm *zstrm) -+{ -+ if (comp->ops->destroy_dctx) -+ comp->ops->destroy_dctx(&zstrm->ctx); -+ vfree(zstrm->local_copy); -+ zstrm->local_copy = NULL; -+ zstrm->ctx.context = NULL; -+} -+ -+static int zcomp_dstrm_init(struct zcomp *comp, struct zcomp_dstrm *zstrm) -+{ -+ int ret; -+ -+ if (comp->ops->create_dctx) { -+ ret = comp->ops->create_dctx(comp->params, &zstrm->ctx); -+ if (ret) { -+ /* backend has released partially created context */ -+ zstrm->ctx.context = NULL; -+ return ret; -+ } -+ } -+ -+ zstrm->local_copy = vzalloc(PAGE_SIZE); -+ if (!zstrm->local_copy) { -+ zcomp_dstrm_free(comp, zstrm); - return -ENOMEM; - } - return 0; -@@ -112,10 +149,15 @@ ssize_t zcomp_available_show(const char *comp, char *buf, ssize_t at) - return at; - } - --struct zcomp_strm *zcomp_stream_get(struct zcomp *comp) -+struct zcomp_cstrm *zcomp_cstrm_get(struct zcomp *comp) - { -+ if (comp->recomp_cstream) { -+ mutex_lock(&comp->recomp_cstream->lock); -+ return comp->recomp_cstream; -+ } -+ - for (;;) { -- struct zcomp_strm *zstrm = raw_cpu_ptr(comp->stream); -+ struct zcomp_cstrm *zstrm = raw_cpu_ptr(comp->cstream); - - /* - * Inspired by zswap -@@ -128,18 +170,91 @@ struct zcomp_strm *zcomp_stream_get(struct zcomp *comp) - * so then unlock and re-try on the current CPU. - */ - mutex_lock(&zstrm->lock); -- if (likely(zstrm->buffer)) -+ if (zstrm->buffer) - return zstrm; - mutex_unlock(&zstrm->lock); - } - } - --void zcomp_stream_put(struct zcomp_strm *zstrm) -+void zcomp_cstrm_put(struct zcomp_cstrm *zstrm) - { - mutex_unlock(&zstrm->lock); - } - --int zcomp_compress(struct zcomp *comp, struct zcomp_strm *zstrm, -+bool zcomp_shared_decomp(struct zcomp *comp) -+{ -+ /* -+ * Shared decompression is only safe when the backend has no -+ * mutable per-stream decompression context. -+ */ -+ return !comp->ops->create_dctx; -+} -+ -+static bool zcomp_dstrm_excl_trylock(struct zcomp_dstrm *zstrm) -+{ -+ /* Cheap pre-check: don't touch a busy stream's cachelines */ -+ if (mutex_is_locked(&zstrm->excl_lock)) -+ return false; -+ /* -+ * Pin the stream. The write side of ->lock is only taken by -+ * zcomp_cpu_dead(), which also sets ->local_copy to NULL. -+ */ -+ if (!down_read_trylock(&zstrm->lock)) -+ return false; -+ if (zstrm->local_copy && mutex_trylock(&zstrm->excl_lock)) -+ return true; -+ up_read(&zstrm->lock); -+ return false; -+} -+ -+static struct zcomp_dstrm *zcomp_dstrm_excl_tryget(struct zcomp *comp) -+{ -+ unsigned int cpu, start = raw_smp_processor_id(); -+ struct zcomp_dstrm *zstrm; -+ -+ /* Best-effort start CPU hint; migration during the scan is fine */ -+ for_each_online_cpu_wrap(cpu, start) { -+ zstrm = per_cpu_ptr(comp->dstream, cpu); -+ if (zcomp_dstrm_excl_trylock(zstrm)) -+ return zstrm; -+ } -+ return NULL; -+} -+ -+struct zcomp_dstrm *zcomp_dstrm_get(struct zcomp *comp, -+ enum zcomp_dstrm_mode mode) -+{ -+ struct zcomp_dstrm *zstrm; -+ -+ if (mode == ZCOMP_DSTRM_SHARED) { -+ for (;;) { -+ zstrm = raw_cpu_ptr(comp->dstream); -+ down_read(&zstrm->lock); -+ if (zstrm->local_copy) -+ return zstrm; -+ up_read(&zstrm->lock); -+ } -+ } -+ -+ /* Checks zcomp_dstrm_excl_tryget() before touching the waitq */ -+ wait_event(comp->dstrm_waitq, (zstrm = zcomp_dstrm_excl_tryget(comp))); -+ return zstrm; -+} -+ -+void zcomp_dstrm_put(struct zcomp *comp, struct zcomp_dstrm *zstrm, -+ enum zcomp_dstrm_mode mode) -+{ -+ if (mode == ZCOMP_DSTRM_EXCLUSIVE) { -+ mutex_unlock(&zstrm->excl_lock); -+ up_read(&zstrm->lock); -+ if (wq_has_sleeper(&comp->dstrm_waitq)) -+ wake_up(&comp->dstrm_waitq); -+ return; -+ } -+ up_read(&zstrm->lock); -+} -+ -+int zcomp_compress(struct zcomp *comp, struct zcomp_cstrm *zstrm, - const void *src, unsigned int *dst_len) - { - struct zcomp_req req = { -@@ -157,58 +272,159 @@ int zcomp_compress(struct zcomp *comp, struct zcomp_strm *zstrm, - return ret; - } - --int zcomp_decompress(struct zcomp *comp, struct zcomp_strm *zstrm, -- const void *src, unsigned int src_len, void *dst) -+static int zcomp_decompress_buf(struct zcomp *comp, struct zcomp_dstrm *zstrm, -+ struct scatterlist *sg, void *buf, -+ struct zcomp_req *req) -+{ -+ sg_copy_to_buffer(sg, 2, buf, req->src_len); -+ req->src = buf; -+ return comp->ops->decompress(comp->params, &zstrm->ctx, req); -+} -+ -+int zcomp_decompress(struct zcomp *comp, struct zcomp_dstrm *zstrm, -+ struct scatterlist *sg, unsigned int src_len, void *dst) - { - struct zcomp_req req = { -- .src = src, - .dst = dst, - .src_len = src_len, - .dst_len = PAGE_SIZE, - }; -+ void *src; -+ int ret; - - might_sleep(); -- return comp->ops->decompress(comp->params, &zstrm->ctx, &req); -+ lockdep_assert_held(&zstrm->lock); -+ if (!zcomp_shared_decomp(comp)) -+ lockdep_assert_held(&zstrm->excl_lock); -+ -+ if (sg_is_last(sg)) { -+ /* the object is contained within one page, read it in-place */ -+ src = kmap_local_page(sg_page(sg)); -+ req.src = src + sg->offset; -+ ret = comp->ops->decompress(comp->params, &zstrm->ctx, &req); -+ kunmap_local(src); -+ return ret; -+ } -+ -+ /* exclusive mode already holds ->excl_lock */ -+ if (!zcomp_shared_decomp(comp)) -+ return zcomp_decompress_buf(comp, zstrm, sg, zstrm->local_copy, -+ &req); -+ -+ /* shared mode: try a per-request bounce buffer first */ -+ src = kmalloc(src_len, GFP_NOWAIT | __GFP_NOWARN); -+ if (src) { -+ ret = zcomp_decompress_buf(comp, zstrm, sg, src, &req); -+ kfree(src); -+ return ret; -+ } -+ -+ /* fall back to ->local_copy serialized by ->excl_lock */ -+ mutex_lock(&zstrm->excl_lock); -+ ret = zcomp_decompress_buf(comp, zstrm, sg, zstrm->local_copy, &req); -+ mutex_unlock(&zstrm->excl_lock); -+ if (wq_has_sleeper(&comp->dstrm_waitq)) -+ wake_up(&comp->dstrm_waitq); -+ return ret; - } - - int zcomp_cpu_up_prepare(unsigned int cpu, struct hlist_node *node) - { - struct zcomp *comp = hlist_entry(node, struct zcomp, node); -- struct zcomp_strm *zstrm = per_cpu_ptr(comp->stream, cpu); -+ struct zcomp_cstrm *cstrm = NULL; -+ struct zcomp_dstrm *dstrm; - int ret; - -- ret = zcomp_strm_init(comp, zstrm); -- if (ret) -- pr_err("Can't allocate a compression stream\n"); -- return ret; -+ if (comp->cstream) { -+ cstrm = per_cpu_ptr(comp->cstream, cpu); -+ ret = zcomp_cstrm_init(comp, cstrm); -+ if (ret) { -+ pr_err("Can't allocate a compression stream\n"); -+ return ret; -+ } -+ } -+ -+ dstrm = per_cpu_ptr(comp->dstream, cpu); -+ ret = zcomp_dstrm_init(comp, dstrm); -+ if (ret) { -+ pr_err("Can't allocate a decompression stream\n"); -+ if (cstrm) -+ zcomp_cstrm_free(comp, cstrm); -+ return ret; -+ } -+ -+ return 0; - } - - int zcomp_cpu_dead(unsigned int cpu, struct hlist_node *node) - { - struct zcomp *comp = hlist_entry(node, struct zcomp, node); -- struct zcomp_strm *zstrm = per_cpu_ptr(comp->stream, cpu); -+ struct zcomp_cstrm *cstrm; -+ struct zcomp_dstrm *dstrm; -+ -+ if (comp->cstream) { -+ cstrm = per_cpu_ptr(comp->cstream, cpu); -+ mutex_lock(&cstrm->lock); -+ zcomp_cstrm_free(comp, cstrm); -+ mutex_unlock(&cstrm->lock); -+ } -+ -+ dstrm = per_cpu_ptr(comp->dstream, cpu); -+ down_write(&dstrm->lock); -+ zcomp_dstrm_free(comp, dstrm); -+ up_write(&dstrm->lock); - -- mutex_lock(&zstrm->lock); -- zcomp_strm_free(comp, zstrm); -- mutex_unlock(&zstrm->lock); - return 0; - } - --static int zcomp_init(struct zcomp *comp, struct zcomp_params *params) -+static int zcomp_init(struct zcomp *comp, struct zcomp_params *params, -+ bool recomp) - { - int ret, cpu; - -- comp->stream = alloc_percpu(struct zcomp_strm); -- if (!comp->stream) -- return -ENOMEM; -- - comp->params = params; - ret = comp->ops->setup_params(comp->params); - if (ret) - goto cleanup; - -- for_each_possible_cpu(cpu) -- mutex_init(&per_cpu_ptr(comp->stream, cpu)->lock); -+ if (recomp) { -+ comp->recomp_cstream = kzalloc_obj(*comp->recomp_cstream); -+ if (!comp->recomp_cstream) { -+ ret = -ENOMEM; -+ goto cleanup; -+ } -+ mutex_init(&comp->recomp_cstream->lock); -+ ret = zcomp_cstrm_init(comp, comp->recomp_cstream); -+ if (ret) { -+ /* zcomp_cstrm_init() cleans up after itself */ -+ kfree(comp->recomp_cstream); -+ comp->recomp_cstream = NULL; -+ goto cleanup; -+ } -+ } else { -+ comp->cstream = alloc_percpu(struct zcomp_cstrm); -+ if (!comp->cstream) { -+ ret = -ENOMEM; -+ goto cleanup; -+ } -+ for_each_possible_cpu(cpu) -+ mutex_init(&per_cpu_ptr(comp->cstream, cpu)->lock); -+ } -+ -+ comp->dstream = alloc_percpu(struct zcomp_dstrm); -+ if (!comp->dstream) { -+ ret = -ENOMEM; -+ goto cleanup; -+ } -+ -+ init_waitqueue_head(&comp->dstrm_waitq); -+ -+ for_each_possible_cpu(cpu) { -+ struct zcomp_dstrm *zstrm = per_cpu_ptr(comp->dstream, cpu); -+ -+ init_rwsem(&zstrm->lock); -+ mutex_init(&zstrm->excl_lock); -+ } - - ret = cpuhp_state_add_instance(CPUHP_ZCOMP_PREPARE, &comp->node); - if (ret < 0) -@@ -217,20 +433,31 @@ static int zcomp_init(struct zcomp *comp, struct zcomp_params *params) - return 0; - - cleanup: -+ if (comp->recomp_cstream) { -+ zcomp_cstrm_free(comp, comp->recomp_cstream); -+ kfree(comp->recomp_cstream); -+ } - comp->ops->release_params(comp->params); -- free_percpu(comp->stream); -+ free_percpu(comp->dstream); -+ free_percpu(comp->cstream); - return ret; - } - - void zcomp_destroy(struct zcomp *comp) - { - cpuhp_state_remove_instance(CPUHP_ZCOMP_PREPARE, &comp->node); -+ if (comp->recomp_cstream) { -+ zcomp_cstrm_free(comp, comp->recomp_cstream); -+ kfree(comp->recomp_cstream); -+ } - comp->ops->release_params(comp->params); -- free_percpu(comp->stream); -+ free_percpu(comp->dstream); -+ free_percpu(comp->cstream); - kfree(comp); - } - --struct zcomp *zcomp_create(const char *alg, struct zcomp_params *params) -+struct zcomp *zcomp_create(const char *alg, struct zcomp_params *params, -+ bool recomp) - { - struct zcomp *comp; - int error; -@@ -253,7 +480,7 @@ struct zcomp *zcomp_create(const char *alg, struct zcomp_params *params) - return ERR_PTR(-EINVAL); - } - -- error = zcomp_init(comp, params); -+ error = zcomp_init(comp, params, recomp); - if (error) { - kfree(comp); - return ERR_PTR(error); -diff --git a/drivers/block/zram/zcomp.h b/drivers/block/zram/zcomp.h -index 81a0f3f..39efefc 100644 ---- a/drivers/block/zram/zcomp.h -+++ b/drivers/block/zram/zcomp.h -@@ -4,9 +4,18 @@ - #define _ZCOMP_H_ - - #include -+#include -+#include -+ -+struct scatterlist; - - #define ZCOMP_PARAM_NOT_SET INT_MIN - -+enum zcomp_dstrm_mode { -+ ZCOMP_DSTRM_SHARED, -+ ZCOMP_DSTRM_EXCLUSIVE, -+}; -+ - struct deflate_params { - s32 winbits; - }; -@@ -31,16 +40,29 @@ struct zcomp_params { - /* - * Run-time driver context - scratch buffers, etc. It is modified during - * request execution (compression/decompression), cannot be shared, so -- * it's in per-CPU area. -+ * it's in per-CPU area (except for recompression, which uses a single -+ * per-device compression stream). - */ - struct zcomp_ctx { - void *context; - }; - --struct zcomp_strm { -+struct zcomp_cstrm { - struct mutex lock; - /* compression buffer */ - void *buffer; -+ struct zcomp_ctx ctx; -+}; -+ -+struct zcomp_dstrm { -+ /* -+ * Pins the stream: held in read mode by every user, regardless -+ * of the decompression mode, and in write mode only by -+ * zcomp_cpu_dead(). -+ */ -+ struct rw_semaphore lock; -+ /* Serializes users of the mutable stream state: ->local_copy, ->ctx */ -+ struct mutex excl_lock; - /* local copy of handle memory */ - void *local_copy; - struct zcomp_ctx ctx; -@@ -60,8 +82,11 @@ struct zcomp_ops { - int (*decompress)(struct zcomp_params *params, struct zcomp_ctx *ctx, - struct zcomp_req *req); - -- int (*create_ctx)(struct zcomp_params *params, struct zcomp_ctx *ctx); -- void (*destroy_ctx)(struct zcomp_ctx *ctx); -+ int (*create_cctx)(struct zcomp_params *params, struct zcomp_ctx *ctx); -+ void (*destroy_cctx)(struct zcomp_ctx *ctx); -+ -+ int (*create_dctx)(struct zcomp_params *params, struct zcomp_ctx *ctx); -+ void (*destroy_dctx)(struct zcomp_ctx *ctx); - - int (*setup_params)(struct zcomp_params *params); - void (*release_params)(struct zcomp_params *params); -@@ -71,7 +96,10 @@ struct zcomp_ops { - - /* dynamic per-device compression frontend */ - struct zcomp { -- struct zcomp_strm __percpu *stream; -+ struct zcomp_dstrm __percpu *dstream; -+ wait_queue_head_t dstrm_waitq; -+ struct zcomp_cstrm __percpu *cstream; -+ struct zcomp_cstrm *recomp_cstream; - const struct zcomp_ops *ops; - struct zcomp_params *params; - struct hlist_node node; -@@ -82,15 +110,22 @@ int zcomp_cpu_dead(unsigned int cpu, struct hlist_node *node); - ssize_t zcomp_available_show(const char *comp, char *buf, ssize_t at); - const char *zcomp_lookup_backend_name(const char *comp); - --struct zcomp *zcomp_create(const char *alg, struct zcomp_params *params); -+struct zcomp *zcomp_create(const char *alg, struct zcomp_params *params, -+ bool recomp); - void zcomp_destroy(struct zcomp *comp); - --struct zcomp_strm *zcomp_stream_get(struct zcomp *comp); --void zcomp_stream_put(struct zcomp_strm *zstrm); -+struct zcomp_cstrm *zcomp_cstrm_get(struct zcomp *comp); -+void zcomp_cstrm_put(struct zcomp_cstrm *zstrm); -+ -+bool zcomp_shared_decomp(struct zcomp *comp); -+struct zcomp_dstrm *zcomp_dstrm_get(struct zcomp *comp, -+ enum zcomp_dstrm_mode mode); -+void zcomp_dstrm_put(struct zcomp *comp, struct zcomp_dstrm *zstrm, -+ enum zcomp_dstrm_mode mode); - --int zcomp_compress(struct zcomp *comp, struct zcomp_strm *zstrm, -+int zcomp_compress(struct zcomp *comp, struct zcomp_cstrm *zstrm, - const void *src, unsigned int *dst_len); --int zcomp_decompress(struct zcomp *comp, struct zcomp_strm *zstrm, -- const void *src, unsigned int src_len, void *dst); -+int zcomp_decompress(struct zcomp *comp, struct zcomp_dstrm *zstrm, -+ struct scatterlist *sg, unsigned int src_len, void *dst); - - #endif /* _ZCOMP_H_ */ -diff --git a/drivers/block/zram/zram_drv.c b/drivers/block/zram/zram_drv.c -index 4ba0f77..5e5ad2e 100644 ---- a/drivers/block/zram/zram_drv.c -+++ b/drivers/block/zram/zram_drv.c -@@ -32,6 +32,7 @@ - #include - #include - #include -+#include - #include - #include - -@@ -693,6 +694,7 @@ static void reset_bdev(struct zram *zram) - zram->disk->fops = &zram_devops; - kvfree(zram->bitmap); - zram->bitmap = NULL; -+ zram->nr_pages = 0; - } - - static ssize_t backing_dev_show(struct device *dev, -@@ -1346,10 +1348,10 @@ static ssize_t writeback_store(struct device *dev, - static int decompress_bdev_page(struct zram *zram, struct page *page, - unsigned long index) - { -- struct zcomp_strm *zstrm; -+ struct zcomp_dstrm *zstrm; -+ struct scatterlist sg[1]; - unsigned int size; - int ret, prio; -- void *src; - - slot_lock(zram, index); - /* Since slot was unlocked we need to make sure it's still ZRAM_WB */ -@@ -1368,14 +1370,19 @@ static int decompress_bdev_page(struct zram *zram, struct page *page, - size = get_slot_size(zram, index); - prio = get_slot_comp_priority(zram, index); - -- zstrm = zcomp_stream_get(zram->comps[prio]); -- src = kmap_local_page(page); -- ret = zcomp_decompress(zram->comps[prio], zstrm, src, size, -+ sg_init_table(sg, 1); -+ sg_set_page(sg, page, size, 0); -+ -+ zstrm = zcomp_dstrm_get(zram->comps[prio], ZCOMP_DSTRM_EXCLUSIVE); -+ ret = zcomp_decompress(zram->comps[prio], zstrm, sg, size, - zstrm->local_copy); -- if (!ret) -- copy_page(src, zstrm->local_copy); -- kunmap_local(src); -- zcomp_stream_put(zstrm); -+ if (!ret) { -+ void *dst = kmap_local_page(page); -+ -+ copy_page(dst, zstrm->local_copy); -+ kunmap_local(dst); -+ } -+ zcomp_dstrm_put(zram->comps[prio], zstrm, ZCOMP_DSTRM_EXCLUSIVE); - slot_unlock(zram, index); - - return ret; -@@ -1547,68 +1554,70 @@ static void zram_debugfs_destroy(void) - debugfs_remove_recursive(zram_debugfs_root); - } - --static ssize_t read_block_state(struct file *file, char __user *buf, -- size_t count, loff_t *ppos) -+static void *zram_block_state_start(struct seq_file *seq, loff_t *pos) - { -- char *kbuf; -- unsigned long index; -- ssize_t written = 0; -- struct zram *zram = file->private_data; -+ struct zram *zram = seq->private; - unsigned long nr_pages; - -- kbuf = kvmalloc(count, GFP_KERNEL); -- if (!kbuf) -- return -ENOMEM; -- -- guard(rwsem_read)(&zram->dev_lock); -- if (!init_done(zram)) { -- kvfree(kbuf); -- return -EINVAL; -- } -+ down_read(&zram->dev_lock); -+ if (!init_done(zram)) -+ return ERR_PTR(-EINVAL); - - nr_pages = zram->disksize >> PAGE_SHIFT; -+ if (*pos >= nr_pages) -+ return NULL; - -- for (index = *ppos; index < nr_pages; index++) { -- int copied; -+ return pos; -+} - -- slot_lock(zram, index); -- if (!slot_allocated(zram, index)) -- goto next; -+static void *zram_block_state_next(struct seq_file *seq, void *v, loff_t *pos) -+{ -+ struct zram *zram = seq->private; -+ unsigned long nr_pages = zram->disksize >> PAGE_SHIFT; - -- copied = snprintf(kbuf + written, count, -- "%12lu %12u.%06d %c%c%c%c%c%c\n", -- index, zram->table[index].attr.ac_time, 0, -- test_slot_flag(zram, index, ZRAM_SAME) ? 's' : '.', -- test_slot_flag(zram, index, ZRAM_WB) ? 'w' : '.', -- test_slot_flag(zram, index, ZRAM_HUGE) ? 'h' : '.', -- test_slot_flag(zram, index, ZRAM_IDLE) ? 'i' : '.', -- get_slot_comp_priority(zram, index) ? 'r' : '.', -- test_slot_flag(zram, index, -- ZRAM_INCOMPRESSIBLE) ? 'n' : '.'); -- -- if (count <= copied) { -- slot_unlock(zram, index); -- break; -- } -- written += copied; -- count -= copied; --next: -- slot_unlock(zram, index); -- *ppos += 1; -- } -+ ++*pos; -+ if (*pos >= nr_pages) -+ return NULL; - -- if (copy_to_user(buf, kbuf, written)) -- written = -EFAULT; -- kvfree(kbuf); -+ return pos; -+} - -- return written; -+static void zram_block_state_stop(struct seq_file *seq, void *v) -+{ -+ struct zram *zram = seq->private; -+ -+ up_read(&zram->dev_lock); -+} -+ -+static int zram_block_state_show(struct seq_file *seq, void *v) -+{ -+ struct zram *zram = seq->private; -+ unsigned long index = *(loff_t *)v; -+ -+ slot_lock(zram, index); -+ if (slot_allocated(zram, index)) { -+ seq_printf(seq, "%12lu %12u.%06d %c%c%c%c%c%c\n", -+ index, zram->table[index].attr.ac_time, 0, -+ test_slot_flag(zram, index, ZRAM_SAME) ? 's' : '.', -+ test_slot_flag(zram, index, ZRAM_WB) ? 'w' : '.', -+ test_slot_flag(zram, index, ZRAM_HUGE) ? 'h' : '.', -+ test_slot_flag(zram, index, ZRAM_IDLE) ? 'i' : '.', -+ get_slot_comp_priority(zram, index) ? 'r' : '.', -+ test_slot_flag(zram, index, -+ ZRAM_INCOMPRESSIBLE) ? 'n' : '.'); -+ } -+ slot_unlock(zram, index); -+ -+ return 0; - } - --static const struct file_operations proc_zram_block_state_op = { -- .open = simple_open, -- .read = read_block_state, -- .llseek = default_llseek, -+static const struct seq_operations zram_block_state_sops = { -+ .start = zram_block_state_start, -+ .next = zram_block_state_next, -+ .stop = zram_block_state_stop, -+ .show = zram_block_state_show, - }; -+DEFINE_SEQ_ATTRIBUTE(zram_block_state); - - static void zram_debugfs_register(struct zram *zram) - { -@@ -1618,7 +1627,7 @@ static void zram_debugfs_register(struct zram *zram) - zram->debugfs_dir = debugfs_create_dir(zram->disk->disk_name, - zram_debugfs_root); - debugfs_create_file("block_state", 0400, zram->debugfs_dir, -- zram, &proc_zram_block_state_op); -+ zram, &zram_block_state_fops); - } - - static void zram_debugfs_unregister(struct zram *zram) -@@ -2091,15 +2100,19 @@ static int read_same_filled_page(struct zram *zram, struct page *page, - static int read_incompressible_page(struct zram *zram, struct page *page, - unsigned long index) - { -+ struct scatterlist sg[2]; - unsigned long handle; - void *src, *dst; - - handle = get_slot_handle(zram, index); -- src = zs_obj_read_begin(zram->mem_pool, handle, PAGE_SIZE, NULL); -+ zs_obj_read_sg_begin(zram->mem_pool, handle, sg, PAGE_SIZE); -+ /* an incompressible object never spans two pages */ -+ src = kmap_local_page(sg_page(sg)); - dst = kmap_local_page(page); - copy_page(dst, src); - kunmap_local(dst); -- zs_obj_read_end(zram->mem_pool, handle, PAGE_SIZE, src); -+ kunmap_local(src); -+ zs_obj_read_sg_end(zram->mem_pool, handle); - - return 0; - } -@@ -2107,24 +2120,28 @@ static int read_incompressible_page(struct zram *zram, struct page *page, - static int read_compressed_page(struct zram *zram, struct page *page, - unsigned long index) - { -- struct zcomp_strm *zstrm; -+ enum zcomp_dstrm_mode mode = ZCOMP_DSTRM_EXCLUSIVE; -+ struct zcomp_dstrm *zstrm; -+ struct scatterlist sg[2]; - unsigned long handle; - unsigned int size; -- void *src, *dst; -+ void *dst; - int ret, prio; - - handle = get_slot_handle(zram, index); - size = get_slot_size(zram, index); - prio = get_slot_comp_priority(zram, index); - -- zstrm = zcomp_stream_get(zram->comps[prio]); -- src = zs_obj_read_begin(zram->mem_pool, handle, size, -- zstrm->local_copy); -+ zs_obj_read_sg_begin(zram->mem_pool, handle, sg, size); -+ if (zcomp_shared_decomp(zram->comps[prio])) -+ mode = ZCOMP_DSTRM_SHARED; -+ -+ zstrm = zcomp_dstrm_get(zram->comps[prio], mode); - dst = kmap_local_page(page); -- ret = zcomp_decompress(zram->comps[prio], zstrm, src, size, dst); -+ ret = zcomp_decompress(zram->comps[prio], zstrm, sg, size, dst); - kunmap_local(dst); -- zs_obj_read_end(zram->mem_pool, handle, size, src); -- zcomp_stream_put(zstrm); -+ zcomp_dstrm_put(zram->comps[prio], zstrm, mode); -+ zs_obj_read_sg_end(zram->mem_pool, handle); - - return ret; - } -@@ -2133,25 +2150,23 @@ static int read_compressed_page(struct zram *zram, struct page *page, - static int read_from_zspool_raw(struct zram *zram, struct page *page, - unsigned long index) - { -- struct zcomp_strm *zstrm; -+ struct scatterlist sg[2]; - unsigned long handle; - unsigned int size; -- void *src; -+ void *dst; - - handle = get_slot_handle(zram, index); - size = get_slot_size(zram, index); - - /* -- * We need to get stream just for ->local_copy buffer, in -- * case if object spans two physical pages. No decompression -- * takes place here, as we read raw compressed data. -+ * No decompression takes place here, we copy out raw compressed -+ * data directly into the destination page. - */ -- zstrm = zcomp_stream_get(zram->comps[ZRAM_PRIMARY_COMP]); -- src = zs_obj_read_begin(zram->mem_pool, handle, size, -- zstrm->local_copy); -- memcpy_to_page(page, 0, src, size); -- zs_obj_read_end(zram->mem_pool, handle, size, src); -- zcomp_stream_put(zstrm); -+ zs_obj_read_sg_begin(zram->mem_pool, handle, sg, size); -+ dst = kmap_local_page(page); -+ sg_copy_to_buffer(sg, sg_nents(sg), dst, size); -+ kunmap_local(dst); -+ zs_obj_read_sg_end(zram->mem_pool, handle); - - memzero_page(page, size, PAGE_SIZE - size); - -@@ -2182,6 +2197,7 @@ static int zram_read_page(struct zram *zram, struct page *page, - int ret; - - slot_lock(zram, index); -+ mark_slot_accessed(zram, index); - if (!test_slot_flag(zram, index, ZRAM_WB)) { - /* Slot should be locked through out the function call */ - ret = read_from_zspool(zram, page, index); -@@ -2197,10 +2213,6 @@ static int zram_read_page(struct zram *zram, struct page *page, - ret = read_from_bdev(zram, page, index, blk_idx, parent); - } - -- /* Should NEVER happen. Return bio error if it does. */ -- if (WARN_ON(ret < 0)) -- pr_err("Decompression failed! err=%d, page=%lu\n", ret, index); -- - return ret; - } - -@@ -2238,6 +2250,7 @@ static int write_same_filled_page(struct zram *zram, unsigned long fill, - slot_free(zram, index); - set_slot_flag(zram, index, ZRAM_SAME); - set_slot_handle(zram, index, fill); -+ mark_slot_accessed(zram, index); - slot_unlock(zram, index); - - atomic64_inc(&zram->stats.same_pages); -@@ -2277,6 +2290,7 @@ static int write_incompressible_page(struct zram *zram, struct page *page, - set_slot_flag(zram, index, ZRAM_HUGE); - set_slot_handle(zram, index, handle); - set_slot_size(zram, index, PAGE_SIZE); -+ mark_slot_accessed(zram, index); - slot_unlock(zram, index); - - atomic64_add(PAGE_SIZE, &zram->stats.compr_data_size); -@@ -2294,7 +2308,7 @@ static int zram_write_page(struct zram *zram, struct page *page, - unsigned long handle; - unsigned int comp_len; - void *mem; -- struct zcomp_strm *zstrm; -+ struct zcomp_cstrm *zstrm; - unsigned long element; - bool same_filled; - -@@ -2304,20 +2318,20 @@ static int zram_write_page(struct zram *zram, struct page *page, - if (same_filled) - return write_same_filled_page(zram, element, index); - -- zstrm = zcomp_stream_get(zram->comps[ZRAM_PRIMARY_COMP]); -+ zstrm = zcomp_cstrm_get(zram->comps[ZRAM_PRIMARY_COMP]); - mem = kmap_local_page(page); - ret = zcomp_compress(zram->comps[ZRAM_PRIMARY_COMP], zstrm, - mem, &comp_len); - kunmap_local(mem); - - if (unlikely(ret)) { -- zcomp_stream_put(zstrm); -+ zcomp_cstrm_put(zstrm); - pr_err("Compression failed! err=%d\n", ret); - return ret; - } - - if (comp_len >= huge_class_size) { -- zcomp_stream_put(zstrm); -+ zcomp_cstrm_put(zstrm); - return write_incompressible_page(zram, page, index); - } - -@@ -2325,23 +2339,24 @@ static int zram_write_page(struct zram *zram, struct page *page, - GFP_NOIO | __GFP_NOWARN | - __GFP_HIGHMEM | __GFP_MOVABLE, page_to_nid(page)); - if (IS_ERR_VALUE(handle)) { -- zcomp_stream_put(zstrm); -+ zcomp_cstrm_put(zstrm); - return PTR_ERR((void *)handle); - } - - if (!zram_can_store_page(zram)) { -- zcomp_stream_put(zstrm); -+ zcomp_cstrm_put(zstrm); - zs_free(zram->mem_pool, handle); - return -ENOMEM; - } - - zs_obj_write(zram->mem_pool, handle, zstrm->buffer, comp_len); -- zcomp_stream_put(zstrm); -+ zcomp_cstrm_put(zstrm); - - slot_lock(zram, index); - slot_free(zram, index); - set_slot_handle(zram, index, handle); - set_slot_size(zram, index, comp_len); -+ mark_slot_accessed(zram, index); - slot_unlock(zram, index); - - /* Update stats */ -@@ -2445,7 +2460,7 @@ static int recompress_slot(struct zram *zram, unsigned long index, - struct page *page, u64 *num_recomp_pages, - u32 threshold, u32 prio) - { -- struct zcomp_strm *zstrm = NULL; -+ struct zcomp_cstrm *zstrm = NULL; - unsigned long handle_old; - unsigned long handle_new; - unsigned int comp_len_old; -@@ -2477,7 +2492,7 @@ static int recompress_slot(struct zram *zram, unsigned long index, - */ - clear_slot_flag(zram, index, ZRAM_IDLE); - -- zstrm = zcomp_stream_get(zram->comps[prio]); -+ zstrm = zcomp_cstrm_get(zram->comps[prio]); - src = kmap_local_page(page); - ret = zcomp_compress(zram->comps[prio], zstrm, src, &comp_len_new); - kunmap_local(src); -@@ -2492,7 +2507,7 @@ static int recompress_slot(struct zram *zram, unsigned long index, - *num_recomp_pages -= 1; - - if (ret) { -- zcomp_stream_put(zstrm); -+ zcomp_cstrm_put(zstrm); - return ret; - } - -@@ -2501,7 +2516,7 @@ static int recompress_slot(struct zram *zram, unsigned long index, - - if (class_index_new >= class_index_old || - (threshold && comp_len_new >= threshold)) { -- zcomp_stream_put(zstrm); -+ zcomp_cstrm_put(zstrm); - - /* - * Secondary algorithms failed to re-compress the page -@@ -2516,7 +2531,7 @@ static int recompress_slot(struct zram *zram, unsigned long index, - } - - /* -- * We are holding per-CPU stream mutex and entry lock so better -+ * We are holding compression stream mutex and entry lock so better - * avoid direct reclaim. Allocation error is not fatal since - * we still have the old object in the mem_pool. - * -@@ -2530,12 +2545,12 @@ static int recompress_slot(struct zram *zram, unsigned long index, - __GFP_HIGHMEM | __GFP_MOVABLE, - page_to_nid(page)); - if (IS_ERR_VALUE(handle_new)) { -- zcomp_stream_put(zstrm); -+ zcomp_cstrm_put(zstrm); - return PTR_ERR((void *)handle_new); - } - - zs_obj_write(zram->mem_pool, handle_new, zstrm->buffer, comp_len_new); -- zcomp_stream_put(zstrm); -+ zcomp_cstrm_put(zstrm); - - slot_free(zram, index); - set_slot_handle(zram, index, handle_new); -@@ -2750,10 +2765,6 @@ static void zram_bio_read(struct zram *zram, struct bio *bio) - } - flush_dcache_page(bv.bv_page); - -- slot_lock(zram, index); -- mark_slot_accessed(zram, index); -- slot_unlock(zram, index); -- - bio_advance_iter_single(bio, &iter, bv.bv_len); - } while (iter.bi_size); - -@@ -2780,10 +2791,6 @@ static void zram_bio_write(struct zram *zram, struct bio *bio) - break; - } - -- slot_lock(zram, index); -- mark_slot_accessed(zram, index); -- slot_unlock(zram, index); -- - bio_advance_iter_single(bio, &iter, bv.bv_len); - } while (iter.bi_size); - -@@ -2876,6 +2883,12 @@ static void zram_reset_device(struct zram *zram) - zram_destroy_comps(zram); - memset(&zram->stats, 0, sizeof(zram->stats)); - reset_bdev(zram); -+#ifdef CONFIG_ZRAM_WRITEBACK -+ zram->wb_limit_enable = false; -+ zram->bd_wb_limit = 0; -+ zram->wb_batch_size = 32; -+ zram->compressed_wb = false; -+#endif - } - - static ssize_t disksize_store(struct device *dev, struct device_attribute *attr, -@@ -2912,7 +2925,8 @@ static ssize_t disksize_store(struct device *dev, struct device_attribute *attr, - continue; - - comp = zcomp_create(zram->comp_algs[prio], -- &zram->params[prio]); -+ &zram->params[prio], -+ prio != ZRAM_PRIMARY_COMP); - if (IS_ERR(comp)) { - pr_err("Cannot initialise %s compressing backend\n", - zram->comp_algs[prio]); -@@ -3292,6 +3306,7 @@ static int __init zram_init(void) - if (zram_major <= 0) { - pr_err("Unable to get major number\n"); - class_unregister(&zram_control_class); -+ zram_debugfs_destroy(); - cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE); - return -EBUSY; - } -diff --git a/drivers/cpufreq/Kconfig.x86 b/drivers/cpufreq/Kconfig.x86 -index d6190b8..9d10fde 100644 ---- a/drivers/cpufreq/Kconfig.x86 -+++ b/drivers/cpufreq/Kconfig.x86 -@@ -8,7 +8,6 @@ config X86_INTEL_PSTATE - select ACPI_PROCESSOR if ACPI - select ACPI_CPPC_LIB if X86_64 && ACPI && SCHED_MC_PRIO - select CPU_FREQ_GOV_PERFORMANCE -- select CPU_FREQ_GOV_SCHEDUTIL if SMP - help - This driver provides a P state for Intel core processors. - The driver implements an internal governor and will become -@@ -38,7 +37,6 @@ config X86_AMD_PSTATE - depends on ACPI - select ACPI_PROCESSOR - select ACPI_CPPC_LIB if X86_64 -- select CPU_FREQ_GOV_SCHEDUTIL if SMP - select ACPI_PLATFORM_PROFILE - select POWER_SUPPLY - help -diff --git a/drivers/cpufreq/cpufreq_ondemand.c b/drivers/cpufreq/cpufreq_ondemand.c -index 9942dbb..7f8f399 100644 ---- a/drivers/cpufreq/cpufreq_ondemand.c -+++ b/drivers/cpufreq/cpufreq_ondemand.c -@@ -18,10 +18,16 @@ - #include "cpufreq_ondemand.h" - - /* On-demand governor macros */ -+#if defined(CONFIG_ZEN_INTERACTIVE) -+#define DEF_FREQUENCY_UP_THRESHOLD (55) -+#define MICRO_FREQUENCY_UP_THRESHOLD (60) -+#define DEF_SAMPLING_DOWN_FACTOR (5) -+#else - #define DEF_FREQUENCY_UP_THRESHOLD (80) -+#define MICRO_FREQUENCY_UP_THRESHOLD (95) - #define DEF_SAMPLING_DOWN_FACTOR (1) -+#endif - #define MAX_SAMPLING_DOWN_FACTOR (100000) --#define MICRO_FREQUENCY_UP_THRESHOLD (95) - #define MIN_FREQUENCY_UP_THRESHOLD (1) - #define MAX_FREQUENCY_UP_THRESHOLD (100) - -diff --git a/drivers/cpufreq/intel_pstate.c b/drivers/cpufreq/intel_pstate.c -index 0e6ae4c..90887b3 100644 ---- a/drivers/cpufreq/intel_pstate.c -+++ b/drivers/cpufreq/intel_pstate.c -@@ -3946,6 +3946,8 @@ static int __init intel_pstate_setup(char *str) - - if (!strcmp(str, "disable")) - no_load = 1; -+ else if (!strcmp(str, "enable")) -+ no_load = 0; - else if (!strcmp(str, "active")) - default_driver = &intel_pstate; - else if (!strcmp(str, "passive")) -diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu.h b/drivers/gpu/drm/amd/amdgpu/amdgpu.h -index a63404a..1fd4ca2 100644 ---- a/drivers/gpu/drm/amd/amdgpu/amdgpu.h -+++ b/drivers/gpu/drm/amd/amdgpu/amdgpu.h -@@ -157,6 +157,7 @@ struct amdgpu_watchdog_timer { - */ - extern int amdgpu_modeset; - extern unsigned int amdgpu_vram_limit; -+extern int amdgpu_ignore_min_pcap; - extern int amdgpu_vis_vram_limit; - extern int amdgpu_gart_size; - extern int amdgpu_gtt_size; -diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c -index 6927802..942283c 100644 ---- a/drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c -+++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c -@@ -150,6 +150,7 @@ enum AMDGPU_DEBUG_MASK { - }; - - unsigned int amdgpu_vram_limit = UINT_MAX; -+int amdgpu_ignore_min_pcap = 0; /* do not ignore by default */ - int amdgpu_vis_vram_limit; - int amdgpu_gart_size = -1; /* auto */ - int amdgpu_gtt_size = -1; /* auto */ -@@ -271,6 +272,15 @@ struct amdgpu_watchdog_timer amdgpu_watchdog_timer = { - .period = 0x0, /* default to 0x0 (timeout disable) */ - }; - -+/** -+ * DOC: ignore_min_pcap (int) -+ * Ignore the minimum power cap. -+ * Useful on graphics cards where the minimum power cap is very high. -+ * The default is 0 (Do not ignore). -+ */ -+MODULE_PARM_DESC(ignore_min_pcap, "Ignore the minimum power cap"); -+module_param_named(ignore_min_pcap, amdgpu_ignore_min_pcap, int, 0600); -+ - /** - * DOC: vramlimit (int) - * Restrict the total amount of VRAM in MiB for testing. The default is 0 (Use full VRAM). -diff --git a/drivers/gpu/drm/amd/pm/amdgpu_pm.c b/drivers/gpu/drm/amd/pm/amdgpu_pm.c -index c0e6773..2fa7a42 100644 ---- a/drivers/gpu/drm/amd/pm/amdgpu_pm.c -+++ b/drivers/gpu/drm/amd/pm/amdgpu_pm.c -@@ -3422,6 +3422,9 @@ static ssize_t amdgpu_hwmon_show_power_cap_min(struct device *dev, - struct device_attribute *attr, - char *buf) - { -+ if (amdgpu_ignore_min_pcap) -+ return sysfs_emit(buf, "%i\n", 0); -+ - return amdgpu_hwmon_show_power_cap_generic(dev, attr, buf, PP_PWR_LIMIT_MIN); - } - -diff --git a/drivers/gpu/drm/amd/pm/swsmu/amdgpu_smu.c b/drivers/gpu/drm/amd/pm/swsmu/amdgpu_smu.c -index 9e70a0f..1c4dce1 100644 ---- a/drivers/gpu/drm/amd/pm/swsmu/amdgpu_smu.c -+++ b/drivers/gpu/drm/amd/pm/swsmu/amdgpu_smu.c -@@ -3071,9 +3071,12 @@ int smu_get_ppt_limit(void *handle, - smu->ppt_limits.range[power_source][limit_type].max; - break; - case SMU_PPT_LIMIT_MIN: -- *limit = smu->od_enabled ? -- smu->ppt_limits.range[power_source][limit_type].od_min : -- smu->ppt_limits.range[power_source][limit_type].min; -+ if (amdgpu_ignore_min_pcap && limit_type == SMU_DEFAULT_PPT_LIMIT) -+ *limit = 0; -+ else -+ *limit = smu->od_enabled ? -+ smu->ppt_limits.range[power_source][limit_type].od_min : -+ smu->ppt_limits.range[power_source][limit_type].min; - break; - default: - return -EINVAL; -@@ -3110,7 +3113,9 @@ static int smu_set_ppt_limit(void *handle, uint32_t limit_type, uint32_t limit) - return ret; - } - -- if (limit > max_limit || limit < min_limit) { -+ if (limit > max_limit || -+ (!(amdgpu_ignore_min_pcap && limit_type == SMU_DEFAULT_PPT_LIMIT) && -+ limit < min_limit)) { - dev_err(smu->adev->dev, - "New PPT limit (%d) is out of range [%d,%d]\n", - limit, min_limit, max_limit); -diff --git a/drivers/gpu/drm/i915/display/intel_dp.c b/drivers/gpu/drm/i915/display/intel_dp.c -index d79b636..28cc65f 100644 ---- a/drivers/gpu/drm/i915/display/intel_dp.c -+++ b/drivers/gpu/drm/i915/display/intel_dp.c -@@ -4785,6 +4785,38 @@ intel_edp_set_sink_rates(struct intel_dp *intel_dp) - intel_edp_set_data_override_rates(intel_dp); - } - -+static void intel_edp_wake_sink(struct intel_dp *intel_dp) -+{ -+ u8 value = 0; -+ int ret; -+ -+ /* -+ * Read the current sink power state. drm_dp_dpcd_read_byte() already -+ * retries the AUX transaction internally, so a single read suffices. -+ * First commercial eDP panels are Ver1.0 or 1.1, on which DPCD -+ * DP_SET_POWER is supported. -+ */ -+ ret = drm_dp_dpcd_read_byte(&intel_dp->aux, DP_SET_POWER, &value); -+ -+ /* -+ * If the AUX read failed the sink may be asleep and not responding, -+ * or it read back D3; in either case wake it up to D0. -+ * In case of AUX read failure which is usually a POR case, the -+ * remaining bits of register 0x600 is set to '0' on POR. So a bare -+ * write should be fine. -+ */ -+ if (ret < 0 || value == DP_SET_POWER_D3) { -+ value &= ~DP_SET_POWER_MASK; -+ value |= DP_SET_POWER_D0; -+ drm_dp_dpcd_write_byte(&intel_dp->aux, DP_SET_POWER, -+ value); -+ /* After setting to D0 need a min of 1ms to wake (Spec DP2.1 sec 2.3.1.2) */ -+ fsleep(1000); -+ drm_dp_dpcd_write_byte(&intel_dp->aux, DP_SET_POWER, -+ value); -+ } -+} -+ - static bool - intel_edp_init_dpcd(struct intel_dp *intel_dp, struct intel_connector *connector) - { -@@ -4795,6 +4827,12 @@ intel_edp_init_dpcd(struct intel_dp *intel_dp, struct intel_connector *connector - /* this function is meant to be called only once */ - drm_WARN_ON(display->drm, intel_dp->dpcd[DP_DPCD_REV] != 0); - -+ /* -+ * Spec DP2.1 Section 3.5.2.16 page 966. -+ * Also if sink is asleep, this will wake the sink. -+ */ -+ intel_edp_wake_sink(intel_dp); -+ - if (drm_dp_read_dpcd_caps(&intel_dp->aux, intel_dp->dpcd) != 0) - return false; - -diff --git a/drivers/input/evdev.c b/drivers/input/evdev.c -index 8bfaaa4..cc37779 100644 ---- a/drivers/input/evdev.c -+++ b/drivers/input/evdev.c -@@ -47,6 +47,7 @@ struct evdev_client { - struct fasync_struct *fasync; - struct evdev *evdev; - struct list_head node; -+ struct rcu_head rcu; - enum input_clock_type clk_type; - bool revoked; - unsigned long *evmasks[EV_CNT]; -@@ -373,13 +374,22 @@ static void evdev_attach_client(struct evdev *evdev, - spin_unlock(&evdev->client_lock); - } - -+static void evdev_reclaim_client(struct rcu_head *rp) -+{ -+ struct evdev_client *client = container_of(rp, struct evdev_client, rcu); -+ unsigned int i; -+ for (i = 0; i < EV_CNT; ++i) -+ bitmap_free(client->evmasks[i]); -+ kvfree(client); -+} -+ - static void evdev_detach_client(struct evdev *evdev, - struct evdev_client *client) - { - spin_lock(&evdev->client_lock); - list_del_rcu(&client->node); - spin_unlock(&evdev->client_lock); -- synchronize_rcu(); -+ call_rcu(&client->rcu, evdev_reclaim_client); - } - - static int evdev_open_device(struct evdev *evdev) -@@ -432,7 +442,6 @@ static int evdev_release(struct inode *inode, struct file *file) - { - struct evdev_client *client = file->private_data; - struct evdev *evdev = client->evdev; -- unsigned int i; - - mutex_lock(&evdev->mutex); - -@@ -444,11 +453,6 @@ static int evdev_release(struct inode *inode, struct file *file) - - evdev_detach_client(evdev, client); - -- for (i = 0; i < EV_CNT; ++i) -- bitmap_free(client->evmasks[i]); -- -- kvfree(client); -- - evdev_close_device(evdev); - - return 0; -@@ -491,7 +495,6 @@ static int evdev_open(struct inode *inode, struct file *file) - - err_free_client: - evdev_detach_client(evdev, client); -- kvfree(client); - return error; - } - -diff --git a/drivers/pci/quirks.c b/drivers/pci/quirks.c -index d4fcc33..1f48544 100644 ---- a/drivers/pci/quirks.c -+++ b/drivers/pci/quirks.c -@@ -15,6 +15,7 @@ - #include - #include - #include -+#include - #include - #include - #include -@@ -5112,6 +5113,128 @@ static int pci_quirk_wangxun_nic_acs(struct pci_dev *dev, u16 acs_flags) - return false; - } - -+static bool acs_on_downstream; -+static bool acs_on_multifunction; -+ -+#define NUM_ACS_IDS 16 -+struct acs_on_id { -+ unsigned short vendor; -+ unsigned short device; -+}; -+static struct acs_on_id acs_on_ids[NUM_ACS_IDS]; -+static u8 max_acs_id; -+ -+static int __init pcie_acs_parse_id(const char *p, struct acs_on_id *id) -+{ -+ unsigned int val = 0; -+ int i, d; -+ -+ if (p[7] != ':') -+ return -EINVAL; -+ -+ for (i = 3; i < 12; i++) { -+ if (i == 7) -+ continue; -+ d = hex_to_bin(p[i]); -+ if (d < 0) -+ return -EINVAL; -+ val = (val << 4) | d; -+ } -+ -+ id->vendor = val >> 16; -+ id->device = val & 0xffff; -+ return 0; -+} -+ -+static int __init pcie_acs_override_setup(char *p) -+{ -+ if (!p) -+ return -EINVAL; -+ -+ while (*p) { -+ size_t len = strcspn(p, ","); -+ -+ if (len == strlen("downstream") && -+ !strncmp(p, "downstream", len)) { -+ acs_on_downstream = true; -+ } else if (len == strlen("multifunction") && -+ !strncmp(p, "multifunction", len)) { -+ acs_on_multifunction = true; -+ } else if (len == strlen("id:nnnn:nnnn") && -+ !strncmp(p, "id:", 3)) { -+ struct acs_on_id id; -+ -+ if (pcie_acs_parse_id(p, &id)) { -+ pr_warn("Invalid PCIe ACS override '%.*s'\n", -+ (int)len, p); -+ } else if (max_acs_id >= ARRAY_SIZE(acs_on_ids)) { -+ pr_warn("Out of PCIe ACS override slots (%d)\n", -+ NUM_ACS_IDS); -+ } else { -+ acs_on_ids[max_acs_id++] = id; -+ } -+ } else if (len) { -+ pr_warn("Invalid PCIe ACS override '%.*s'\n", -+ (int)len, p); -+ } -+ -+ p += len; -+ if (*p == ',') -+ p++; -+ } -+ -+ if (acs_on_downstream || acs_on_multifunction || max_acs_id) { -+ pr_warn("Warning: PCIe ACS overrides enabled; This may allow non-IOMMU protected peer-to-peer DMA\n"); -+ add_taint(TAINT_USER, LOCKDEP_STILL_OK); -+ } -+ -+ return 0; -+} -+early_param("pcie_acs_override", pcie_acs_override_setup); -+ -+static int pcie_acs_overrides(struct pci_dev *dev, u16 acs_flags) -+{ -+ int i; -+ -+ if (!acs_on_downstream && !acs_on_multifunction && !max_acs_id) -+ return -ENOTTY; -+ -+ /* Only answer the IOMMU group isolation query (REQ_ACS_FLAGS) */ -+ if (acs_flags != (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)) -+ return -ENOTTY; -+ -+ /* Never override ACS for legacy devices or devices with ACS caps */ -+ if (!pci_is_pcie(dev) || dev->acs_cap) -+ return -ENOTTY; -+ -+ if (dev->untrusted || dev->external_facing) -+ return -ENOTTY; -+ -+ switch (pci_pcie_type(dev)) { -+ case PCI_EXP_TYPE_DOWNSTREAM: -+ case PCI_EXP_TYPE_ROOT_PORT: -+ if (acs_on_downstream) -+ return 1; -+ break; -+ case PCI_EXP_TYPE_ENDPOINT: -+ case PCI_EXP_TYPE_UPSTREAM: -+ case PCI_EXP_TYPE_LEG_END: -+ case PCI_EXP_TYPE_RC_END: -+ if (acs_on_multifunction && dev->multifunction) -+ return 1; -+ break; -+ default: -+ return -ENOTTY; -+ } -+ -+ for (i = 0; i < max_acs_id; i++) -+ if (acs_on_ids[i].vendor == dev->vendor && -+ acs_on_ids[i].device == dev->device) -+ return 1; -+ -+ return -ENOTTY; -+} -+ - static const struct pci_dev_acs_enabled { - u16 vendor; - u16 device; -@@ -5280,6 +5403,7 @@ static const struct pci_dev_acs_enabled { - { PCI_VENDOR_ID_ZHAOXIN, PCI_ANY_ID, pci_quirk_zhaoxin_pcie_ports_acs }, - /* Wangxun nics */ - { PCI_VENDOR_ID_WANGXUN, PCI_ANY_ID, pci_quirk_wangxun_nic_acs }, -+ { PCI_ANY_ID, PCI_ANY_ID, pcie_acs_overrides }, - { 0 } - }; - -diff --git a/drivers/scsi/Kconfig b/drivers/scsi/Kconfig -index 1eec661..7552093 100644 ---- a/drivers/scsi/Kconfig -+++ b/drivers/scsi/Kconfig -@@ -1524,4 +1524,6 @@ endif # SCSI_LOWLEVEL - - source "drivers/scsi/device_handler/Kconfig" - -+source "drivers/scsi/vhba/Kconfig" -+ - endmenu -diff --git a/drivers/scsi/Makefile b/drivers/scsi/Makefile -index 5336233..7f61fa0 100644 ---- a/drivers/scsi/Makefile -+++ b/drivers/scsi/Makefile -@@ -176,6 +176,7 @@ obj-$(CONFIG_CHR_DEV_SCH) += ch.o - obj-$(CONFIG_SCSI_ENCLOSURE) += ses.o - - obj-$(CONFIG_SCSI_HISI_SAS) += hisi_sas/ -+obj-$(CONFIG_VHBA) += vhba/ - - # This goes last, so that "real" scsi devices probe earlier - obj-$(CONFIG_SCSI_DEBUG) += scsi_debug.o -diff --git a/drivers/scsi/vhba/Kconfig b/drivers/scsi/vhba/Kconfig -new file mode 100644 -index 0000000..e70a381 ---- /dev/null -+++ b/drivers/scsi/vhba/Kconfig -@@ -0,0 +1,9 @@ -+config VHBA -+ tristate "Virtual (SCSI) Host Bus Adapter" -+ depends on SCSI -+ help -+ This is the in-kernel part of CDEmu, a CD/DVD-ROM device -+ emulator. -+ -+ This driver can also be built as a module. If so, the module -+ will be called vhba. -diff --git a/drivers/scsi/vhba/Makefile b/drivers/scsi/vhba/Makefile -new file mode 100644 -index 0000000..c55e5c3 ---- /dev/null -+++ b/drivers/scsi/vhba/Makefile -@@ -0,0 +1,4 @@ -+VHBA_VERSION := 20260313 -+ -+obj-$(CONFIG_VHBA) += vhba.o -+ccflags-y := -DVHBA_VERSION=\"$(VHBA_VERSION)\" -Werror -diff --git a/drivers/scsi/vhba/vhba.c b/drivers/scsi/vhba/vhba.c -new file mode 100644 -index 0000000..e24e600 ---- /dev/null -+++ b/drivers/scsi/vhba/vhba.c -@@ -0,0 +1,1136 @@ -+/* -+ * vhba.c -+ * -+ * Copyright (C) 2007-2026 Chia-I Wu -+ * -+ * This program is free software; you can redistribute it and/or modify -+ * it under the terms of the GNU General Public License as published by -+ * the Free Software Foundation; either version 2 of the License, or -+ * (at your option) any later version. -+ * -+ * This program is distributed in the hope that it will be useful, -+ * but WITHOUT ANY WARRANTY; without even the implied warranty of -+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -+ * GNU General Public License for more details. -+ * -+ * You should have received a copy of the GNU General Public License along -+ * with this program; if not, write to the Free Software Foundation, Inc., -+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -+ */ -+ -+#define pr_fmt(fmt) "vhba: " fmt -+ -+#include -+ -+#include -+#include -+#include -+#include -+#if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 11, 0) -+#include -+#else -+#include -+#endif -+#include -+#include -+#include -+#include -+#include -+#ifdef CONFIG_COMPAT -+#include -+#endif -+#include -+#include -+#include -+#include -+#include -+#include -+ -+ -+MODULE_AUTHOR("Chia-I Wu"); -+MODULE_VERSION(VHBA_VERSION); -+MODULE_DESCRIPTION("Virtual SCSI HBA"); -+MODULE_LICENSE("GPL"); -+ -+ -+#if LINUX_VERSION_CODE < KERNEL_VERSION(3, 15, 0) -+#define sdev_dbg(sdev, fmt, a...) \ -+ dev_dbg(&(sdev)->sdev_gendev, fmt, ##a) -+#define scmd_dbg(scmd, fmt, a...) \ -+ dev_dbg(&(scmd)->device->sdev_gendev, fmt, ##a) -+#endif -+ -+#define VHBA_MAX_SECTORS_PER_IO 256 -+#define VHBA_MAX_BUS 16 -+#define VHBA_MAX_ID 16 -+#define VHBA_MAX_DEVICES (VHBA_MAX_BUS * (VHBA_MAX_ID-1)) -+#define VHBA_KBUF_SIZE PAGE_SIZE -+ -+#define DATA_TO_DEVICE(dir) ((dir) == DMA_TO_DEVICE || (dir) == DMA_BIDIRECTIONAL) -+#define DATA_FROM_DEVICE(dir) ((dir) == DMA_FROM_DEVICE || (dir) == DMA_BIDIRECTIONAL) -+ -+ -+static int vhba_can_queue = 32; -+module_param_named(can_queue, vhba_can_queue, int, 0); -+ -+ -+enum vhba_req_state { -+ VHBA_REQ_FREE, -+ VHBA_REQ_PENDING, -+ VHBA_REQ_READING, -+ VHBA_REQ_SENT, -+ VHBA_REQ_WRITING, -+}; -+ -+struct vhba_command { -+ struct scsi_cmnd *cmd; -+ /* metatags are per-host. not to be confused with -+ queue tags that are usually per-lun */ -+ unsigned long metatag; -+ int status; -+ struct list_head entry; -+}; -+ -+struct vhba_device { -+ unsigned int num; -+ spinlock_t cmd_lock; -+ struct list_head cmd_list; -+ wait_queue_head_t cmd_wq; -+ atomic_t refcnt; -+ -+ unsigned char *kbuf; -+ size_t kbuf_size; -+}; -+ -+struct vhba_host { -+ struct Scsi_Host *shost; -+ spinlock_t cmd_lock; -+ int cmd_next; -+ struct vhba_command *commands; -+ spinlock_t dev_lock; -+ struct vhba_device *devices[VHBA_MAX_DEVICES]; -+ int num_devices; -+ DECLARE_BITMAP(chgmap, VHBA_MAX_DEVICES); -+ int chgtype[VHBA_MAX_DEVICES]; -+ struct work_struct scan_devices; -+}; -+ -+#define MAX_COMMAND_SIZE 16 -+ -+struct vhba_request { -+ __u32 metatag; -+ __u32 lun; -+ __u8 cdb[MAX_COMMAND_SIZE]; -+ __u8 cdb_len; -+ __u32 data_len; -+}; -+ -+struct vhba_response { -+ __u32 metatag; -+ __u32 status; -+ __u32 data_len; -+}; -+ -+ -+ -+static struct vhba_command *vhba_alloc_command (void); -+static void vhba_free_command (struct vhba_command *vcmd); -+ -+static struct platform_device vhba_platform_device; -+ -+ -+ -+/* These functions define a symmetric 1:1 mapping between device numbers and -+ the bus and id. We have reserved the last id per bus for the host itself. */ -+static void devnum_to_bus_and_id(unsigned int devnum, unsigned int *bus, unsigned int *id) -+{ -+ *bus = devnum / (VHBA_MAX_ID-1); -+ *id = devnum % (VHBA_MAX_ID-1); -+} -+ -+static unsigned int bus_and_id_to_devnum(unsigned int bus, unsigned int id) -+{ -+ return (bus * (VHBA_MAX_ID-1)) + id; -+} -+ -+static struct vhba_device *vhba_device_alloc (void) -+{ -+ struct vhba_device *vdev; -+ -+ vdev = kzalloc(sizeof(struct vhba_device), GFP_KERNEL); -+ if (!vdev) { -+ return NULL; -+ } -+ -+ spin_lock_init(&vdev->cmd_lock); -+ INIT_LIST_HEAD(&vdev->cmd_list); -+ init_waitqueue_head(&vdev->cmd_wq); -+ atomic_set(&vdev->refcnt, 1); -+ -+ vdev->kbuf = NULL; -+ vdev->kbuf_size = 0; -+ -+ return vdev; -+} -+ -+static void vhba_device_put (struct vhba_device *vdev) -+{ -+ if (atomic_dec_and_test(&vdev->refcnt)) { -+ kfree(vdev); -+ } -+} -+ -+static struct vhba_device *vhba_device_get (struct vhba_device *vdev) -+{ -+ atomic_inc(&vdev->refcnt); -+ -+ return vdev; -+} -+ -+static int vhba_device_queue (struct vhba_device *vdev, struct scsi_cmnd *cmd) -+{ -+ struct vhba_host *vhost; -+ struct vhba_command *vcmd; -+ unsigned long flags; -+ -+ vhost = platform_get_drvdata(&vhba_platform_device); -+ -+ vcmd = vhba_alloc_command(); -+ if (!vcmd) { -+ return SCSI_MLQUEUE_HOST_BUSY; -+ } -+ -+ vcmd->cmd = cmd; -+ -+ spin_lock_irqsave(&vdev->cmd_lock, flags); -+#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 15, 0) -+ vcmd->metatag = scsi_cmd_to_rq(vcmd->cmd)->tag; -+#else -+ vcmd->metatag = vcmd->cmd->request->tag; -+#endif -+ list_add_tail(&vcmd->entry, &vdev->cmd_list); -+ spin_unlock_irqrestore(&vdev->cmd_lock, flags); -+ -+ wake_up_interruptible(&vdev->cmd_wq); -+ -+ return 0; -+} -+ -+static int vhba_device_dequeue (struct vhba_device *vdev, struct scsi_cmnd *cmd) -+{ -+ struct vhba_command *vcmd; -+ int retval; -+ unsigned long flags; -+ -+ spin_lock_irqsave(&vdev->cmd_lock, flags); -+ list_for_each_entry(vcmd, &vdev->cmd_list, entry) { -+ if (vcmd->cmd == cmd) { -+ list_del_init(&vcmd->entry); -+ break; -+ } -+ } -+ -+ /* command not found */ -+ if (&vcmd->entry == &vdev->cmd_list) { -+ spin_unlock_irqrestore(&vdev->cmd_lock, flags); -+ return SUCCESS; -+ } -+ -+ while (vcmd->status == VHBA_REQ_READING || vcmd->status == VHBA_REQ_WRITING) { -+ spin_unlock_irqrestore(&vdev->cmd_lock, flags); -+ scmd_dbg(cmd, "wait for I/O before aborting\n"); -+ schedule_timeout(1); -+ spin_lock_irqsave(&vdev->cmd_lock, flags); -+ } -+ -+ retval = (vcmd->status == VHBA_REQ_SENT) ? FAILED : SUCCESS; -+ -+ vhba_free_command(vcmd); -+ -+ spin_unlock_irqrestore(&vdev->cmd_lock, flags); -+ -+ return retval; -+} -+ -+#if LINUX_VERSION_CODE < KERNEL_VERSION(3, 19, 0) -+static int vhba_slave_alloc(struct scsi_device *sdev) -+{ -+ struct Scsi_Host *shost = sdev->host; -+ -+ sdev_dbg(sdev, "enabling tagging (queue depth: %i).\n", sdev->queue_depth); -+#if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 17, 0) -+ if (!shost_use_blk_mq(shost) && shost->bqt) { -+#else -+ if (shost->bqt) { -+#endif -+ blk_queue_init_tags(sdev->request_queue, sdev->queue_depth, shost->bqt); -+ } -+ scsi_adjust_queue_depth(sdev, 0, sdev->queue_depth); -+ -+ return 0; -+} -+#endif -+ -+static void vhba_scan_devices_add (struct vhba_host *vhost, int bus, int id) -+{ -+ struct scsi_device *sdev; -+ -+ sdev = scsi_device_lookup(vhost->shost, bus, id, 0); -+ if (!sdev) { -+ scsi_add_device(vhost->shost, bus, id, 0); -+ } else { -+ dev_warn(&vhost->shost->shost_gendev, "tried to add an already-existing device %d:%d:0!\n", bus, id); -+ scsi_device_put(sdev); -+ } -+} -+ -+static void vhba_scan_devices_remove (struct vhba_host *vhost, int bus, int id) -+{ -+ struct scsi_device *sdev; -+ -+ sdev = scsi_device_lookup(vhost->shost, bus, id, 0); -+ if (sdev) { -+ scsi_remove_device(sdev); -+ scsi_device_put(sdev); -+ } else { -+ dev_warn(&vhost->shost->shost_gendev, "tried to remove non-existing device %d:%d:0!\n", bus, id); -+ } -+} -+ -+static void vhba_scan_devices (struct work_struct *work) -+{ -+ struct vhba_host *vhost = container_of(work, struct vhba_host, scan_devices); -+ unsigned long flags; -+ int change, exists; -+ unsigned int devnum; -+ unsigned int bus, id; -+ -+ for (;;) { -+ spin_lock_irqsave(&vhost->dev_lock, flags); -+ -+ devnum = find_first_bit(vhost->chgmap, VHBA_MAX_DEVICES); -+ if (devnum >= VHBA_MAX_DEVICES) { -+ spin_unlock_irqrestore(&vhost->dev_lock, flags); -+ break; -+ } -+ change = vhost->chgtype[devnum]; -+ exists = vhost->devices[devnum] != NULL; -+ -+ vhost->chgtype[devnum] = 0; -+ clear_bit(devnum, vhost->chgmap); -+ -+ spin_unlock_irqrestore(&vhost->dev_lock, flags); -+ -+ devnum_to_bus_and_id(devnum, &bus, &id); -+ -+ if (change < 0) { -+ dev_dbg(&vhost->shost->shost_gendev, "trying to remove target %d:%d:0\n", bus, id); -+ vhba_scan_devices_remove(vhost, bus, id); -+ } else if (change > 0) { -+ dev_dbg(&vhost->shost->shost_gendev, "trying to add target %d:%d:0\n", bus, id); -+ vhba_scan_devices_add(vhost, bus, id); -+ } else { -+ /* quick sequence of add/remove or remove/add; we determine -+ which one it was by checking if device structure exists */ -+ if (exists) { -+ /* remove followed by add: remove and (re)add */ -+ dev_dbg(&vhost->shost->shost_gendev, "trying to (re)add target %d:%d:0\n", bus, id); -+ vhba_scan_devices_remove(vhost, bus, id); -+ vhba_scan_devices_add(vhost, bus, id); -+ } else { -+ /* add followed by remove: no-op */ -+ dev_dbg(&vhost->shost->shost_gendev, "no-op for target %d:%d:0\n", bus, id); -+ } -+ } -+ } -+} -+ -+static int vhba_add_device (struct vhba_device *vdev) -+{ -+ struct vhba_host *vhost; -+ unsigned int devnum; -+ unsigned long flags; -+ -+ vhost = platform_get_drvdata(&vhba_platform_device); -+ -+ vhba_device_get(vdev); -+ -+ spin_lock_irqsave(&vhost->dev_lock, flags); -+ if (vhost->num_devices >= VHBA_MAX_DEVICES) { -+ spin_unlock_irqrestore(&vhost->dev_lock, flags); -+ vhba_device_put(vdev); -+ return -EBUSY; -+ } -+ -+ for (devnum = 0; devnum < VHBA_MAX_DEVICES; devnum++) { -+ if (vhost->devices[devnum] == NULL) { -+ vdev->num = devnum; -+ vhost->devices[devnum] = vdev; -+ vhost->num_devices++; -+ set_bit(devnum, vhost->chgmap); -+ vhost->chgtype[devnum]++; -+ break; -+ } -+ } -+ spin_unlock_irqrestore(&vhost->dev_lock, flags); -+ -+ schedule_work(&vhost->scan_devices); -+ -+ return 0; -+} -+ -+static int vhba_remove_device (struct vhba_device *vdev) -+{ -+ struct vhba_host *vhost; -+ unsigned long flags; -+ -+ vhost = platform_get_drvdata(&vhba_platform_device); -+ -+ spin_lock_irqsave(&vhost->dev_lock, flags); -+ set_bit(vdev->num, vhost->chgmap); -+ vhost->chgtype[vdev->num]--; -+ vhost->devices[vdev->num] = NULL; -+ vhost->num_devices--; -+ spin_unlock_irqrestore(&vhost->dev_lock, flags); -+ -+ vhba_device_put(vdev); -+ -+ schedule_work(&vhost->scan_devices); -+ -+ return 0; -+} -+ -+static struct vhba_device *vhba_lookup_device (int devnum) -+{ -+ struct vhba_host *vhost; -+ struct vhba_device *vdev = NULL; -+ unsigned long flags; -+ -+ vhost = platform_get_drvdata(&vhba_platform_device); -+ -+ if (likely(devnum < VHBA_MAX_DEVICES)) { -+ spin_lock_irqsave(&vhost->dev_lock, flags); -+ vdev = vhost->devices[devnum]; -+ if (vdev) { -+ vdev = vhba_device_get(vdev); -+ } -+ -+ spin_unlock_irqrestore(&vhost->dev_lock, flags); -+ } -+ -+ return vdev; -+} -+ -+static struct vhba_command *vhba_alloc_command (void) -+{ -+ struct vhba_host *vhost; -+ struct vhba_command *vcmd; -+ unsigned long flags; -+ int i; -+ -+ vhost = platform_get_drvdata(&vhba_platform_device); -+ -+ spin_lock_irqsave(&vhost->cmd_lock, flags); -+ -+ vcmd = vhost->commands + vhost->cmd_next++; -+ if (vcmd->status != VHBA_REQ_FREE) { -+ for (i = 0; i < vhba_can_queue; i++) { -+ vcmd = vhost->commands + i; -+ -+ if (vcmd->status == VHBA_REQ_FREE) { -+ vhost->cmd_next = i + 1; -+ break; -+ } -+ } -+ -+ if (i == vhba_can_queue) { -+ vcmd = NULL; -+ } -+ } -+ -+ if (vcmd) { -+ vcmd->status = VHBA_REQ_PENDING; -+ } -+ -+ vhost->cmd_next %= vhba_can_queue; -+ -+ spin_unlock_irqrestore(&vhost->cmd_lock, flags); -+ -+ return vcmd; -+} -+ -+static void vhba_free_command (struct vhba_command *vcmd) -+{ -+ struct vhba_host *vhost; -+ unsigned long flags; -+ -+ vhost = platform_get_drvdata(&vhba_platform_device); -+ -+ spin_lock_irqsave(&vhost->cmd_lock, flags); -+ vcmd->status = VHBA_REQ_FREE; -+ spin_unlock_irqrestore(&vhost->cmd_lock, flags); -+} -+ -+#if LINUX_VERSION_CODE >= KERNEL_VERSION(7, 0, 0) -+static enum scsi_qc_status vhba_queuecommand (struct Scsi_Host *shost, struct scsi_cmnd *cmd) -+#else -+static int vhba_queuecommand (struct Scsi_Host *shost, struct scsi_cmnd *cmd) -+#endif -+{ -+ struct vhba_device *vdev; -+ int retval; -+ unsigned int devnum; -+ -+#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 15, 0) -+ scmd_dbg(cmd, "queue %p tag %i\n", cmd, scsi_cmd_to_rq(cmd)->tag); -+#else -+ scmd_dbg(cmd, "queue %p tag %i\n", cmd, cmd->request->tag); -+#endif -+ -+ devnum = bus_and_id_to_devnum(cmd->device->channel, cmd->device->id); -+ vdev = vhba_lookup_device(devnum); -+ if (!vdev) { -+ scmd_dbg(cmd, "no such device\n"); -+ -+ cmd->result = DID_NO_CONNECT << 16; -+#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 16, 0) -+ scsi_done(cmd); -+#else -+ cmd->scsi_done(cmd); -+#endif -+ -+ return 0; -+ } -+ -+ retval = vhba_device_queue(vdev, cmd); -+ -+ vhba_device_put(vdev); -+ -+ return retval; -+} -+ -+static int vhba_abort (struct scsi_cmnd *cmd) -+{ -+ struct vhba_device *vdev; -+ int retval = SUCCESS; -+ unsigned int devnum; -+ -+ scmd_dbg(cmd, "abort %p\n", cmd); -+ -+ devnum = bus_and_id_to_devnum(cmd->device->channel, cmd->device->id); -+ vdev = vhba_lookup_device(devnum); -+ if (vdev) { -+ retval = vhba_device_dequeue(vdev, cmd); -+ vhba_device_put(vdev); -+ } else { -+ cmd->result = DID_NO_CONNECT << 16; -+ } -+ -+ return retval; -+} -+ -+static struct scsi_host_template vhba_template = { -+ .module = THIS_MODULE, -+ .name = "vhba", -+ .proc_name = "vhba", -+ .queuecommand = vhba_queuecommand, -+ .eh_abort_handler = vhba_abort, -+ .this_id = -1, -+ .max_sectors = VHBA_MAX_SECTORS_PER_IO, -+ .sg_tablesize = 256, -+#if LINUX_VERSION_CODE < KERNEL_VERSION(3, 19, 0) -+ .slave_alloc = vhba_slave_alloc, -+#endif -+#if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 14, 0) -+ .tag_alloc_policy_rr = true, -+#elif LINUX_VERSION_CODE >= KERNEL_VERSION(4, 0, 0) -+ .tag_alloc_policy = BLK_TAG_ALLOC_RR, -+#endif -+#if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 19, 0) && LINUX_VERSION_CODE < KERNEL_VERSION(4, 4, 0) -+ .use_blk_tags = 1, -+#endif -+#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 0, 0) -+ .max_segment_size = VHBA_KBUF_SIZE, -+#endif -+}; -+ -+static ssize_t do_request (struct vhba_device *vdev, unsigned long metatag, struct scsi_cmnd *cmd, char __user *buf, size_t buf_len) -+{ -+ struct vhba_request vreq; -+ ssize_t ret; -+ -+ scmd_dbg(cmd, "request %lu (%p), cdb 0x%x, bufflen %d, sg count %d\n", -+ metatag, cmd, cmd->cmnd[0], scsi_bufflen(cmd), scsi_sg_count(cmd)); -+ -+ ret = sizeof(vreq); -+ if (DATA_TO_DEVICE(cmd->sc_data_direction)) { -+ ret += scsi_bufflen(cmd); -+ } -+ -+ if (ret > buf_len) { -+ scmd_dbg(cmd, "buffer too small (%zd < %zd) for a request\n", buf_len, ret); -+ return -EIO; -+ } -+ -+ vreq.metatag = metatag; -+ vreq.lun = cmd->device->lun; -+ memcpy(vreq.cdb, cmd->cmnd, MAX_COMMAND_SIZE); -+ vreq.cdb_len = cmd->cmd_len; -+ vreq.data_len = scsi_bufflen(cmd); -+ -+ if (copy_to_user(buf, &vreq, sizeof(vreq))) { -+ return -EFAULT; -+ } -+ -+ if (DATA_TO_DEVICE(cmd->sc_data_direction) && vreq.data_len) { -+ buf += sizeof(vreq); -+ -+ if (scsi_sg_count(cmd)) { -+ unsigned char *kaddr, *uaddr; -+ struct scatterlist *sglist = scsi_sglist(cmd); -+ struct scatterlist *sg; -+ int i; -+ -+ uaddr = (unsigned char *) buf; -+ -+ for_each_sg(sglist, sg, scsi_sg_count(cmd), i) { -+ size_t len = sg->length; -+ -+ if (len > vdev->kbuf_size) { -+ scmd_dbg(cmd, "segment size (%zu) exceeds kbuf size (%zu)!", len, vdev->kbuf_size); -+ len = vdev->kbuf_size; -+ } -+ -+ kaddr = kmap_atomic(sg_page(sg)); -+ memcpy(vdev->kbuf, kaddr + sg->offset, len); -+ kunmap_atomic(kaddr); -+ -+ if (copy_to_user(uaddr, vdev->kbuf, len)) { -+ return -EFAULT; -+ } -+ uaddr += len; -+ } -+ } else { -+ if (copy_to_user(buf, scsi_sglist(cmd), vreq.data_len)) { -+ return -EFAULT; -+ } -+ } -+ } -+ -+ return ret; -+} -+ -+static ssize_t do_response (struct vhba_device *vdev, unsigned long metatag, struct scsi_cmnd *cmd, const char __user *buf, size_t buf_len, struct vhba_response *res) -+{ -+ ssize_t ret = 0; -+ -+ scmd_dbg(cmd, "response %lu (%p), status %x, data len %d, sg count %d\n", -+ metatag, cmd, res->status, res->data_len, scsi_sg_count(cmd)); -+ -+ if (res->status) { -+ if (res->data_len > SCSI_SENSE_BUFFERSIZE) { -+ scmd_dbg(cmd, "truncate sense (%d < %d)", SCSI_SENSE_BUFFERSIZE, res->data_len); -+ res->data_len = SCSI_SENSE_BUFFERSIZE; -+ } -+ -+ if (copy_from_user(cmd->sense_buffer, buf, res->data_len)) { -+ return -EFAULT; -+ } -+ -+ cmd->result = res->status; -+ -+ ret += res->data_len; -+ } else if (DATA_FROM_DEVICE(cmd->sc_data_direction) && scsi_bufflen(cmd)) { -+ size_t to_read; -+ -+ if (res->data_len > scsi_bufflen(cmd)) { -+ scmd_dbg(cmd, "truncate data (%d < %d)\n", scsi_bufflen(cmd), res->data_len); -+ res->data_len = scsi_bufflen(cmd); -+ } -+ -+ to_read = res->data_len; -+ -+ if (scsi_sg_count(cmd)) { -+ unsigned char *kaddr, *uaddr; -+ struct scatterlist *sglist = scsi_sglist(cmd); -+ struct scatterlist *sg; -+ int i; -+ -+ uaddr = (unsigned char *)buf; -+ -+ for_each_sg(sglist, sg, scsi_sg_count(cmd), i) { -+ size_t len = (sg->length < to_read) ? sg->length : to_read; -+ -+ if (len > vdev->kbuf_size) { -+ scmd_dbg(cmd, "segment size (%zu) exceeds kbuf size (%zu)!", len, vdev->kbuf_size); -+ len = vdev->kbuf_size; -+ } -+ -+ if (copy_from_user(vdev->kbuf, uaddr, len)) { -+ return -EFAULT; -+ } -+ uaddr += len; -+ -+ kaddr = kmap_atomic(sg_page(sg)); -+ memcpy(kaddr + sg->offset, vdev->kbuf, len); -+ kunmap_atomic(kaddr); -+ -+ to_read -= len; -+ if (to_read == 0) { -+ break; -+ } -+ } -+ } else { -+ if (copy_from_user(scsi_sglist(cmd), buf, res->data_len)) { -+ return -EFAULT; -+ } -+ -+ to_read -= res->data_len; -+ } -+ -+ scsi_set_resid(cmd, to_read); -+ -+ ret += res->data_len - to_read; -+ } -+ -+ return ret; -+} -+ -+static struct vhba_command *next_command (struct vhba_device *vdev) -+{ -+ struct vhba_command *vcmd; -+ -+ list_for_each_entry(vcmd, &vdev->cmd_list, entry) { -+ if (vcmd->status == VHBA_REQ_PENDING) { -+ break; -+ } -+ } -+ -+ if (&vcmd->entry == &vdev->cmd_list) { -+ vcmd = NULL; -+ } -+ -+ return vcmd; -+} -+ -+static struct vhba_command *match_command (struct vhba_device *vdev, __u32 metatag) -+{ -+ struct vhba_command *vcmd; -+ -+ list_for_each_entry(vcmd, &vdev->cmd_list, entry) { -+ if (vcmd->metatag == metatag) { -+ break; -+ } -+ } -+ -+ if (&vcmd->entry == &vdev->cmd_list) { -+ vcmd = NULL; -+ } -+ -+ return vcmd; -+} -+ -+static struct vhba_command *wait_command (struct vhba_device *vdev, unsigned long flags) -+{ -+ struct vhba_command *vcmd; -+ DEFINE_WAIT(wait); -+ -+ while (!(vcmd = next_command(vdev))) { -+ if (signal_pending(current)) { -+ break; -+ } -+ -+ prepare_to_wait(&vdev->cmd_wq, &wait, TASK_INTERRUPTIBLE); -+ -+ spin_unlock_irqrestore(&vdev->cmd_lock, flags); -+ -+ schedule(); -+ -+ spin_lock_irqsave(&vdev->cmd_lock, flags); -+ } -+ -+ finish_wait(&vdev->cmd_wq, &wait); -+ if (vcmd) { -+ vcmd->status = VHBA_REQ_READING; -+ } -+ -+ return vcmd; -+} -+ -+static ssize_t vhba_ctl_read (struct file *file, char __user *buf, size_t buf_len, loff_t *offset) -+{ -+ struct vhba_device *vdev; -+ struct vhba_command *vcmd; -+ ssize_t ret; -+ unsigned long flags; -+ -+ vdev = file->private_data; -+ -+ /* Get next command */ -+ if (file->f_flags & O_NONBLOCK) { -+ /* Non-blocking variant */ -+ spin_lock_irqsave(&vdev->cmd_lock, flags); -+ vcmd = next_command(vdev); -+ spin_unlock_irqrestore(&vdev->cmd_lock, flags); -+ -+ if (!vcmd) { -+ return -EWOULDBLOCK; -+ } -+ } else { -+ /* Blocking variant */ -+ spin_lock_irqsave(&vdev->cmd_lock, flags); -+ vcmd = wait_command(vdev, flags); -+ spin_unlock_irqrestore(&vdev->cmd_lock, flags); -+ -+ if (!vcmd) { -+ return -ERESTARTSYS; -+ } -+ } -+ -+ ret = do_request(vdev, vcmd->metatag, vcmd->cmd, buf, buf_len); -+ -+ spin_lock_irqsave(&vdev->cmd_lock, flags); -+ if (ret >= 0) { -+ vcmd->status = VHBA_REQ_SENT; -+ *offset += ret; -+ } else { -+ vcmd->status = VHBA_REQ_PENDING; -+ } -+ -+ spin_unlock_irqrestore(&vdev->cmd_lock, flags); -+ -+ return ret; -+} -+ -+static ssize_t vhba_ctl_write (struct file *file, const char __user *buf, size_t buf_len, loff_t *offset) -+{ -+ struct vhba_device *vdev; -+ struct vhba_command *vcmd; -+ struct vhba_response res; -+ ssize_t ret; -+ unsigned long flags; -+ -+ if (buf_len < sizeof(res)) { -+ return -EIO; -+ } -+ -+ if (copy_from_user(&res, buf, sizeof(res))) { -+ return -EFAULT; -+ } -+ -+ vdev = file->private_data; -+ -+ spin_lock_irqsave(&vdev->cmd_lock, flags); -+ vcmd = match_command(vdev, res.metatag); -+ if (!vcmd || vcmd->status != VHBA_REQ_SENT) { -+ spin_unlock_irqrestore(&vdev->cmd_lock, flags); -+ pr_debug("ctl dev #%u not expecting response\n", vdev->num); -+ return -EIO; -+ } -+ vcmd->status = VHBA_REQ_WRITING; -+ spin_unlock_irqrestore(&vdev->cmd_lock, flags); -+ -+ ret = do_response(vdev, vcmd->metatag, vcmd->cmd, buf + sizeof(res), buf_len - sizeof(res), &res); -+ -+ spin_lock_irqsave(&vdev->cmd_lock, flags); -+ if (ret >= 0) { -+#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 16, 0) -+ scsi_done(vcmd->cmd); -+#else -+ vcmd->cmd->scsi_done(vcmd->cmd); -+#endif -+ ret += sizeof(res); -+ -+ /* don't compete with vhba_device_dequeue */ -+ if (!list_empty(&vcmd->entry)) { -+ list_del_init(&vcmd->entry); -+ vhba_free_command(vcmd); -+ } -+ } else { -+ vcmd->status = VHBA_REQ_SENT; -+ } -+ -+ spin_unlock_irqrestore(&vdev->cmd_lock, flags); -+ -+ return ret; -+} -+ -+static long vhba_ctl_ioctl (struct file *file, unsigned int cmd, unsigned long arg) -+{ -+ struct vhba_device *vdev = file->private_data; -+ struct vhba_host *vhost = platform_get_drvdata(&vhba_platform_device); -+ -+ switch (cmd) { -+ case 0xBEEF001: { -+ unsigned int ident[4]; /* host, channel, id, lun */ -+ -+ ident[0] = vhost->shost->host_no; -+ devnum_to_bus_and_id(vdev->num, &ident[1], &ident[2]); -+ ident[3] = 0; /* lun */ -+ -+ if (copy_to_user((void *) arg, ident, sizeof(ident))) { -+ return -EFAULT; -+ } -+ -+ return 0; -+ } -+ case 0xBEEF002: { -+ unsigned int devnum = vdev->num; -+ -+ if (copy_to_user((void *) arg, &devnum, sizeof(devnum))) { -+ return -EFAULT; -+ } -+ -+ return 0; -+ } -+ } -+ -+ return -ENOTTY; -+} -+ -+#ifdef CONFIG_COMPAT -+static long vhba_ctl_compat_ioctl (struct file *file, unsigned int cmd, unsigned long arg) -+{ -+ unsigned long compat_arg = (unsigned long)compat_ptr(arg); -+ return vhba_ctl_ioctl(file, cmd, compat_arg); -+} -+#endif -+ -+static unsigned int vhba_ctl_poll (struct file *file, poll_table *wait) -+{ -+ struct vhba_device *vdev = file->private_data; -+ unsigned int mask = 0; -+ unsigned long flags; -+ -+ poll_wait(file, &vdev->cmd_wq, wait); -+ -+ spin_lock_irqsave(&vdev->cmd_lock, flags); -+ if (next_command(vdev)) { -+ mask |= POLLIN | POLLRDNORM; -+ } -+ spin_unlock_irqrestore(&vdev->cmd_lock, flags); -+ -+ return mask; -+} -+ -+static int vhba_ctl_open (struct inode *inode, struct file *file) -+{ -+ struct vhba_device *vdev; -+ int retval; -+ -+ pr_debug("ctl dev open\n"); -+ -+ /* check if vhba is probed */ -+ if (!platform_get_drvdata(&vhba_platform_device)) { -+ return -ENODEV; -+ } -+ -+ vdev = vhba_device_alloc(); -+ if (!vdev) { -+ return -ENOMEM; -+ } -+ -+ vdev->kbuf_size = VHBA_KBUF_SIZE; -+ vdev->kbuf = kzalloc(vdev->kbuf_size, GFP_KERNEL); -+ if (!vdev->kbuf) { -+ return -ENOMEM; -+ } -+ -+ if (!(retval = vhba_add_device(vdev))) { -+ file->private_data = vdev; -+ } -+ -+ vhba_device_put(vdev); -+ -+ return retval; -+} -+ -+static int vhba_ctl_release (struct inode *inode, struct file *file) -+{ -+ struct vhba_device *vdev; -+ struct vhba_command *vcmd; -+ unsigned long flags; -+ -+ vdev = file->private_data; -+ -+ pr_debug("ctl dev release\n"); -+ -+ vhba_device_get(vdev); -+ vhba_remove_device(vdev); -+ -+ spin_lock_irqsave(&vdev->cmd_lock, flags); -+ list_for_each_entry(vcmd, &vdev->cmd_list, entry) { -+ WARN_ON(vcmd->status == VHBA_REQ_READING || vcmd->status == VHBA_REQ_WRITING); -+ -+ scmd_dbg(vcmd->cmd, "device released with command %lu (%p)\n", vcmd->metatag, vcmd->cmd); -+ vcmd->cmd->result = DID_NO_CONNECT << 16; -+#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 16, 0) -+ scsi_done(vcmd->cmd); -+#else -+ vcmd->cmd->scsi_done(vcmd->cmd); -+#endif -+ vhba_free_command(vcmd); -+ } -+ INIT_LIST_HEAD(&vdev->cmd_list); -+ spin_unlock_irqrestore(&vdev->cmd_lock, flags); -+ -+ kfree(vdev->kbuf); -+ vdev->kbuf = NULL; -+ -+ vhba_device_put(vdev); -+ -+ return 0; -+} -+ -+static struct file_operations vhba_ctl_fops = { -+ .owner = THIS_MODULE, -+ .open = vhba_ctl_open, -+ .release = vhba_ctl_release, -+ .read = vhba_ctl_read, -+ .write = vhba_ctl_write, -+ .poll = vhba_ctl_poll, -+ .unlocked_ioctl = vhba_ctl_ioctl, -+#ifdef CONFIG_COMPAT -+ .compat_ioctl = vhba_ctl_compat_ioctl, -+#endif -+}; -+ -+static struct miscdevice vhba_miscdev = { -+ .minor = MISC_DYNAMIC_MINOR, -+ .name = "vhba_ctl", -+ .fops = &vhba_ctl_fops, -+}; -+ -+static int vhba_probe (struct platform_device *pdev) -+{ -+ struct Scsi_Host *shost; -+ struct vhba_host *vhost; -+ int i; -+ -+ vhba_can_queue = clamp(vhba_can_queue, 1, 256); -+ -+ shost = scsi_host_alloc(&vhba_template, sizeof(struct vhba_host)); -+ if (!shost) { -+ return -ENOMEM; -+ } -+ -+ shost->max_channel = VHBA_MAX_BUS-1; -+ shost->max_id = VHBA_MAX_ID; -+ /* we don't support lun > 0 */ -+ shost->max_lun = 1; -+ shost->max_cmd_len = MAX_COMMAND_SIZE; -+ shost->can_queue = vhba_can_queue; -+ shost->cmd_per_lun = vhba_can_queue; -+ -+ vhost = (struct vhba_host *)shost->hostdata; -+ memset(vhost, 0, sizeof(struct vhba_host)); -+ -+ vhost->shost = shost; -+ vhost->num_devices = 0; -+ spin_lock_init(&vhost->dev_lock); -+ spin_lock_init(&vhost->cmd_lock); -+ INIT_WORK(&vhost->scan_devices, vhba_scan_devices); -+ vhost->cmd_next = 0; -+ vhost->commands = kzalloc(vhba_can_queue * sizeof(struct vhba_command), GFP_KERNEL); -+ if (!vhost->commands) { -+ return -ENOMEM; -+ } -+ -+ for (i = 0; i < vhba_can_queue; i++) { -+ vhost->commands[i].status = VHBA_REQ_FREE; -+ } -+ -+ platform_set_drvdata(pdev, vhost); -+ -+#if LINUX_VERSION_CODE < KERNEL_VERSION(4, 4, 0) -+ i = scsi_init_shared_tag_map(shost, vhba_can_queue); -+ if (i) return i; -+#endif -+ -+ if (scsi_add_host(shost, &pdev->dev)) { -+ scsi_host_put(shost); -+ return -ENOMEM; -+ } -+ -+ return 0; -+} -+ -+#if LINUX_VERSION_CODE < KERNEL_VERSION(6, 11, 0) -+static int vhba_remove (struct platform_device *pdev) -+#else -+static void vhba_remove (struct platform_device *pdev) -+#endif -+{ -+ struct vhba_host *vhost; -+ struct Scsi_Host *shost; -+ -+ vhost = platform_get_drvdata(pdev); -+ shost = vhost->shost; -+ -+ scsi_remove_host(shost); -+ scsi_host_put(shost); -+ -+ kfree(vhost->commands); -+ -+#if LINUX_VERSION_CODE < KERNEL_VERSION(6, 11, 0) -+ return 0; -+#endif -+} -+ -+static void vhba_release (struct device * dev) -+{ -+ return; -+} -+ -+static struct platform_device vhba_platform_device = { -+ .name = "vhba", -+ .id = -1, -+ .dev = { -+ .release = vhba_release, -+ }, -+}; -+ -+static struct platform_driver vhba_platform_driver = { -+ .driver = { -+ .owner = THIS_MODULE, -+ .name = "vhba", -+ }, -+ .probe = vhba_probe, -+ .remove = vhba_remove, -+}; -+ -+static int __init vhba_init (void) -+{ -+ int ret; -+ -+ ret = platform_device_register(&vhba_platform_device); -+ if (ret < 0) { -+ return ret; -+ } -+ -+ ret = platform_driver_register(&vhba_platform_driver); -+ if (ret < 0) { -+ platform_device_unregister(&vhba_platform_device); -+ return ret; -+ } -+ -+ ret = misc_register(&vhba_miscdev); -+ if (ret < 0) { -+ platform_driver_unregister(&vhba_platform_driver); -+ platform_device_unregister(&vhba_platform_device); -+ return ret; -+ } -+ -+ return 0; -+} -+ -+static void __exit vhba_exit(void) -+{ -+ misc_deregister(&vhba_miscdev); -+ platform_driver_unregister(&vhba_platform_driver); -+ platform_device_unregister(&vhba_platform_device); -+} -+ -+module_init(vhba_init); -+module_exit(vhba_exit); -+ -diff --git a/fs/btrfs/compression.c b/fs/btrfs/compression.c -index c62b514..57d2441 100644 ---- a/fs/btrfs/compression.c -+++ b/fs/btrfs/compression.c -@@ -8,6 +8,7 @@ - #include - #include - #include -+#include - #include - #include - #include -diff --git a/fs/erofs/zdata.c b/fs/erofs/zdata.c -index 6b07e73..c618bbf 100644 ---- a/fs/erofs/zdata.c -+++ b/fs/erofs/zdata.c -@@ -6,6 +6,7 @@ - */ - #include "compress.h" - #include -+#include - #include - #include - -@@ -1713,7 +1714,7 @@ static void z_erofs_submit_queue(struct z_erofs_frontend *f, - DBG_BUGON(bvec.bv_len < sb->s_blocksize); - } - -- if (unlikely(PageWorkingset(bvec.bv_page)) && -+ if (unlikely(folio_test_workingset(page_folio(bvec.bv_page))) && - !memstall) { - psi_memstall_enter(&pflags); - memstall = 1; -diff --git a/fs/f2fs/checkpoint.c b/fs/f2fs/checkpoint.c -index a845170..08130b0 100644 ---- a/fs/f2fs/checkpoint.c -+++ b/fs/f2fs/checkpoint.c -@@ -28,7 +28,7 @@ static inline void get_lock_elapsed_time(struct f2fs_time_stat *ts) - { - ts->total_time = ktime_get(); - #ifdef CONFIG_64BIT -- ts->running_time = current->se.sum_exec_runtime; -+ ts->running_time = tsk_seruntime(current); - #endif - #if defined(CONFIG_SCHED_INFO) && defined(CONFIG_SCHEDSTATS) - ts->runnable_time = current->sched_info.run_delay; -diff --git a/fs/proc/base.c b/fs/proc/base.c -index 6a39de4..1acfa9f 100644 ---- a/fs/proc/base.c -+++ b/fs/proc/base.c -@@ -513,7 +513,7 @@ static int proc_pid_schedstat(struct seq_file *m, struct pid_namespace *ns, - seq_puts(m, "0 0 0\n"); - else - seq_printf(m, "%llu %llu %lu\n", -- (unsigned long long)task->se.sum_exec_runtime, -+ (unsigned long long)tsk_seruntime(task), - (unsigned long long)task->sched_info.run_delay, - task->sched_info.pcount); - -diff --git a/fs/proc/task_mmu.c b/fs/proc/task_mmu.c -index 2eaa79a..3cd136a 100644 ---- a/fs/proc/task_mmu.c -+++ b/fs/proc/task_mmu.c -@@ -970,7 +970,7 @@ static void smaps_account(struct mem_size_stats *mss, struct page *page, - - mss->resident += size; - /* Accumulate the size in pages that have been accessed. */ -- if (young || folio_test_young(folio) || folio_test_referenced(folio)) -+ if (young || folio_test_young(folio) || folio_check_lru_refs(folio)) - mss->referenced += size; - - /* -@@ -1793,7 +1793,7 @@ static int clear_refs_pte_range(pmd_t *pmd, unsigned long addr, - /* Clear accessed and referenced bits. */ - pmdp_test_and_clear_young(vma, addr, pmd); - folio_test_clear_young(folio); -- folio_clear_referenced(folio); -+ folio_clear_lru_refs(folio); - out: - spin_unlock(ptl); - return 0; -@@ -1822,7 +1822,7 @@ static int clear_refs_pte_range(pmd_t *pmd, unsigned long addr, - /* Clear accessed and referenced bits. */ - ptep_test_and_clear_young(vma, addr, pte); - folio_test_clear_young(folio); -- folio_clear_referenced(folio); -+ folio_clear_lru_refs(folio); - } - pte_unmap_unlock(pte - 1, ptl); - cond_resched(); -diff --git a/include/linux/interrupt.h b/include/linux/interrupt.h -index 5074560..da79173 100644 ---- a/include/linux/interrupt.h -+++ b/include/linux/interrupt.h -@@ -513,6 +513,9 @@ extern int irq_set_irqchip_state(unsigned int irq, enum irqchip_irq_state which, - #ifdef CONFIG_IRQ_FORCED_THREADING - # ifdef CONFIG_PREEMPT_RT - # define force_irqthreads() (true) -+# elif defined(CONFIG_FORCE_IRQ_THREADING) -+DECLARE_STATIC_KEY_TRUE(force_irqthreads_key); -+# define force_irqthreads() (static_branch_likely(&force_irqthreads_key)) - # else - DECLARE_STATIC_KEY_FALSE(force_irqthreads_key); - # define force_irqthreads() (static_branch_unlikely(&force_irqthreads_key)) -diff --git a/include/linux/memcontrol.h b/include/linux/memcontrol.h -index 6d1c9e9..961f433 100644 ---- a/include/linux/memcontrol.h -+++ b/include/linux/memcontrol.h -@@ -113,7 +113,7 @@ struct mem_cgroup_per_node { - /* Fields which get updated often at the end. */ - struct lruvec lruvec; - CACHELINE_PADDING(_pad2_); -- unsigned long lru_zone_size[MAX_NR_ZONES][NR_LRU_LISTS]; -+ long lru_zone_size[MAX_NR_ZONES][NR_LRU_LISTS]; - struct mem_cgroup_reclaim_iter iter; - - /* -@@ -903,10 +903,15 @@ static inline - unsigned long mem_cgroup_get_zone_lru_size(struct lruvec *lruvec, - enum lru_list lru, int zone_idx) - { -+ long val; - struct mem_cgroup_per_node *mz; - - mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec); -- return READ_ONCE(mz->lru_zone_size[zone_idx][lru]); -+ val = READ_ONCE(mz->lru_zone_size[zone_idx][lru]); -+ if (WARN_ON_ONCE(val < 0)) -+ return 0; -+ -+ return val; - } - - void __mem_cgroup_handle_over_high(gfp_t gfp_mask); -@@ -1503,6 +1508,45 @@ static inline void lruvec_lock_irq(struct lruvec *lruvec) - spin_lock_irq(&lruvec->lru_lock); - } - -+/** -+ * folio_lruvec_live_get - get a live lruvec for a folio under RCU -+ * @folio: the folio -+ * -+ * Computes @folio's lruvec and walks up to the nearest live ancestor -+ * if the folio's memcg is dying. Paired with folio_lruvec_live_put(). -+ * The result may be stale: RCU keeps it alive but does not pin @folio -+ * to it. That is fine as the counters are fixed up on reparenting. -+ * -+ * Return: the live lruvec, with rcu_read_lock held. -+ */ -+static inline struct lruvec *folio_lruvec_live_get(struct folio *folio) -+{ -+#ifdef CONFIG_MEMCG -+ struct lruvec *lruvec; -+ struct pglist_data *pgdat; -+ struct mem_cgroup *memcg; -+ -+ rcu_read_lock(); -+ lruvec = folio_lruvec(folio); -+ pgdat = lruvec_pgdat(lruvec); -+ memcg = lruvec_memcg(lruvec); -+ while (unlikely(memcg && css_is_dying(&memcg->css))) { -+ memcg = parent_mem_cgroup(memcg); -+ lruvec = mem_cgroup_lruvec(memcg, pgdat); -+ } -+ return lruvec; -+#else -+ return folio_lruvec(folio); -+#endif -+} -+ -+static inline void folio_lruvec_live_put(struct lruvec *lruvec) -+{ -+#ifdef CONFIG_MEMCG -+ rcu_read_unlock(); -+#endif -+} -+ - static inline struct lruvec *lruvec_live_lock_irq(struct lruvec *lruvec) - { - #ifdef CONFIG_MEMCG -diff --git a/include/linux/mm.h b/include/linux/mm.h -index dd09c43..31f606a 100644 ---- a/include/linux/mm.h -+++ b/include/linux/mm.h -@@ -206,7 +206,7 @@ static inline void __mm_zero_struct_page(struct page *page) - * that. - */ - #define MAPCOUNT_ELF_CORE_MARGIN (5) --#define DEFAULT_MAX_MAP_COUNT (USHRT_MAX - MAPCOUNT_ELF_CORE_MARGIN) -+#define DEFAULT_MAX_MAP_COUNT (INT_MAX - MAPCOUNT_ELF_CORE_MARGIN) - - extern unsigned long sysctl_user_reserve_kbytes; - extern unsigned long sysctl_admin_reserve_kbytes; -diff --git a/include/linux/mm_inline.h b/include/linux/mm_inline.h -index 621c865..ae50f98 100644 ---- a/include/linux/mm_inline.h -+++ b/include/linux/mm_inline.h -@@ -30,17 +30,27 @@ static inline int folio_is_file_lru(const struct folio *folio) - return !folio_test_swapbacked(folio); - } - -+/** -+ * folio_flags_is_file_lru - Should the folio be on a file LRU or anon LRU? -+ * @flags: The folio's flags. -+ * -+ * Just like folio_is_file_lru but take the folio flags directly instead. -+ */ -+static inline int folio_flags_is_file_lru(const unsigned long *flags) -+{ -+ return !test_bit(PG_swapbacked, flags); -+} -+ - static __always_inline void __update_lru_size(struct lruvec *lruvec, - enum lru_list lru, enum zone_type zid, - long nr_pages) - { - struct pglist_data *pgdat = lruvec_pgdat(lruvec); - -- lockdep_assert_held(&lruvec->lru_lock); - WARN_ON_ONCE(nr_pages != (int)nr_pages); - - mod_lruvec_state(lruvec, NR_LRU_BASE + lru, nr_pages); -- __mod_zone_page_state(&pgdat->node_zones[zid], -+ mod_zone_page_state(&pgdat->node_zones[zid], - NR_ZONE_LRU_BASE + lru, nr_pages); - } - -@@ -95,6 +105,22 @@ static __always_inline enum lru_list folio_lru_list(const struct folio *folio) - return lru; - } - -+/** -+ * lru_get_gen_flags - Return the LRU generation number from folio flags. -+ * @flags: folio flags -+ * -+ * Returns: A number between 0 and (MAX_NR_GENS - 1), inclusive. Returns -+ * -1 if the flags indicate the folio is off the list (e.g., isolated). -+ */ -+static inline int lru_get_gen_flags(unsigned long flags) -+{ -+ int gen = ((flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1; -+ -+ /* Exclude the legal -1 from the unsigned MAX_NR_GENS comparison */ -+ VM_WARN_ON_ONCE(gen != -1 && gen >= MAX_NR_GENS); -+ return gen; -+} -+ - #ifdef CONFIG_LRU_GEN - - static inline bool lru_gen_switching(void) -@@ -134,51 +160,176 @@ static inline int lru_hist_from_seq(unsigned long seq) - return seq % NR_HIST_GENS; - } - --static inline int lru_tier_from_refs(int refs, bool workingset) -+static inline int lru_tier_from_refs(unsigned int refs) - { -- VM_WARN_ON_ONCE(refs > BIT(LRU_REFS_WIDTH)); -+ BUILD_BUG_ON(fls(LRU_REFS_MAX - 1) > MAX_NR_TIERS - 1); -+ VM_WARN_ON_ONCE(refs > LRU_REFS_MAX); -+ if (refs < LRU_REFS_WORKINGSET) -+ return 0; -+ return fls(refs - 1); -+} - -- /* see the comment on MAX_NR_TIERS */ -- return workingset ? MAX_NR_TIERS - 1 : order_base_2(refs); -+/** -+ * lru_set_gen_flags - Set the LRU generation number to specified folio flags. -+ * @flags: pointer to the folio flags -+ * @gen: generation number, between 0 and (MAX_NR_GENS - 1), inclusive. -+ */ -+static inline void lru_set_gen_flags(unsigned long *flags, int gen) -+{ -+ BUILD_BUG_ON(LRU_GEN_MASK & LRU_REFS_MASK); -+ VM_WARN_ON_ONCE(gen >= MAX_NR_GENS || gen < 0); -+ /* Store gen offset by 1, zero means the folio is off-list. */ -+ *flags &= ~LRU_GEN_MASK; -+ *flags |= (gen + 1UL) << LRU_GEN_PGOFF; -+} -+ -+static inline int folio_lru_gen(const struct folio *folio) -+{ -+ return lru_get_gen_flags(READ_ONCE(*const_folio_flags(folio, 0))); -+} -+#endif -+ -+/** -+ * lru_set_refs_flags - Set the LRU referenced count to folio flags. -+ * @flags: pointer to the folio flags -+ * @refs: referenced / access count number, between 0 and LRU_REFS_MAX, inclusive. -+ * -+ * For MGLRU, PG_referenced, PG_workingset are used as the lower two bits of -+ * refs counter, and extra bits hold the remaining higher bits. For classical -+ * LRU the extra bits are not used, and the two flags has no direct -+ * relationship with each other, but this helper can still be used to sync -+ * them. For both cases, refs == 0 means these two flags and the extra bits -+ * are all unset. And refs == 1 / 2 / 3 means PG_referenced and PG_workingset -+ * are set in an bit order way, which is more meaningful for MGLRU though. -+ */ -+static inline void lru_set_refs_flags(unsigned long *flags, unsigned int refs) -+{ -+ VM_WARN_ON_ONCE(refs > LRU_REFS_MAX); -+ BUILD_BUG_ON(LRU_REFS_MASK & (BIT(PG_referenced) | BIT(PG_workingset))); -+ *flags &= ~LRU_REFS_FLAGS; -+ if (refs & BIT(0)) -+ *flags |= BIT(PG_referenced); -+ if (refs & BIT(1)) -+ *flags |= BIT(PG_workingset); -+ if (LRU_REFS_WIDTH) -+ *flags |= ((unsigned long)refs >> 2) << LRU_REFS_PGOFF; -+} -+ -+/** -+ * lru_get_refs_flags - Return LRU referenced / access count from folio flags. -+ * @flags: folio flags -+ * -+ * Reads the LRU referenced count set by lru_set_refs_flags(). -+ */ -+static inline int lru_get_refs_flags(unsigned long flags) -+{ -+ int refs; -+ -+ /* Return the total number of accesses. See the comment above MAX_NR_TIERS. */ -+ refs = (flags & BIT(PG_referenced)) ? BIT(0) : 0; -+ refs += (flags & BIT(PG_workingset)) ? BIT(1) : 0; -+ refs += ((flags & LRU_REFS_MASK) >> LRU_REFS_PGOFF) << 2; -+ return refs; - } - - static inline int folio_lru_refs(const struct folio *folio) - { -- unsigned long flags = READ_ONCE(folio->flags.f); -+ return lru_get_refs_flags(READ_ONCE(*const_folio_flags(folio, 0))); -+} - -- if (!(flags & BIT(PG_referenced))) -- return 0; -- /* -- * Return the total number of accesses including PG_referenced. Also see -- * the comment on LRU_REFS_FLAGS. -- */ -- return ((flags & LRU_REFS_MASK) >> LRU_REFS_PGOFF) + 1; -+/** -+ * __folio_set_lru_refs - Set a folio's LRU refs. -+ * @folio: the folio -+ * @refs: the new referenced count (0 .. LRU_REFS_MAX) -+ * -+ * Set the folio's LRU refs. The folio must be off the LRU list (e.g., -+ * isolated), or use folio_inc_lru_refs or folio_reset_lru_refs instead. -+ */ -+static inline void __folio_set_lru_refs(struct folio *folio, unsigned int refs) -+{ -+ unsigned long new_flags, old_flags = READ_ONCE(*folio_flags(folio, 0)); -+ -+ do { -+ new_flags = old_flags; -+ VM_WARN_ON_ONCE(lru_get_gen_flags(old_flags) != -1); -+ lru_set_refs_flags(&new_flags, refs); -+ } while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags)); - } - --static inline int folio_lru_gen(const struct folio *folio) -+#ifdef CONFIG_LRU_GEN -+void folio_inc_lru_refs(struct folio *folio, unsigned int flags); -+bool folio_reset_lru_refs(struct folio *folio); -+#else -+static inline void folio_inc_lru_refs(struct folio *folio, unsigned int flags) -+{ -+ /* Should not be called with !CONFIG_LRU_GEN */ -+ WARN_ON_ONCE(1); -+} -+ -+static inline bool folio_reset_lru_refs(struct folio *folio) - { -- unsigned long flags = READ_ONCE(folio->flags.f); -+ return false; -+} -+#endif - -- return ((flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1; -+/** -+ * folio_migrate_lru_refs - copy the reference state to a new folio -+ * @new: the destination folio -+ * @old: the source folio -+ * -+ * Transfer the reference state to @new during migration: the MGLRU -+ * refs count, or PG_referenced and PG_workingset (bits 0-1 of the -+ * encoding) for the active/inactive LRU. -+ */ -+static inline void folio_migrate_lru_refs(struct folio *new, const struct folio *old) -+{ -+ VM_WARN_ON_ONCE_FOLIO(folio_test_lru(old), old); -+ VM_WARN_ON_ONCE_FOLIO(folio_test_lru(new), new); -+ __folio_set_lru_refs(new, folio_lru_refs(old)); -+} -+ -+/** -+ * folio_test_workingset - Test if a folio is in the workingset. -+ * @folio: the folio -+ * -+ * A folio is workingset when its LRU refs count reaches -+ * LRU_REFS_WORKINGSET. Under the classical LRU the extra refs counter -+ * are always zero so this is just testing the PG_workingset bit. -+ * NOTE: folio_set_workingset() must not be used under MGLRU, as the -+ * folio refs are tracked by folio_inc_lru_refs() with rules. -+ * -+ * Return: true if the folio is workingset. -+ */ -+static __always_inline bool folio_test_workingset(const struct folio *folio) -+{ -+ return folio_lru_refs(folio) >= LRU_REFS_WORKINGSET; - } - --static inline bool lru_gen_is_active(const struct lruvec *lruvec, int gen) -+#ifdef CONFIG_LRU_GEN -+static inline bool lru_refs_is_active(unsigned int refs) - { -- unsigned long max_seq = lruvec->lrugen.max_seq; -+ VM_WARN_ON_ONCE(refs > LRU_REFS_MAX); -+ return refs >= LRU_REFS_ACTIVATED; -+} - -- VM_WARN_ON_ONCE(gen >= MAX_NR_GENS); -+static inline bool lru_gen_at_tail(struct lruvec *lruvec, int type, int gen) -+{ -+ unsigned long min_seq = READ_ONCE(lruvec->lrugen.min_seq[type]); - -- /* see the comment on MIN_NR_GENS */ -- return gen == lru_gen_from_seq(max_seq) || gen == lru_gen_from_seq(max_seq - 1); -+ /* -+ * Consider a folio is at the tail of its LRU when it is within -+ * MIN_NR_GENS of the oldest generation of its own type -+ */ -+ BUILD_BUG_ON(MIN_NR_GENS != 2); -+ return gen == lru_gen_from_seq(min_seq) || -+ gen == lru_gen_from_seq(min_seq + 1); - } - --static inline void lru_gen_update_size(struct lruvec *lruvec, struct folio *folio, -- int old_gen, int new_gen) -+static inline void lru_gen_update_size(struct lruvec *lruvec, int type, -+ struct folio *folio, int old_gen, int new_gen) - { -- int type = folio_is_file_lru(folio); - int zone = folio_zonenum(folio); - int delta = folio_nr_pages(folio); -- enum lru_list lru = type * LRU_INACTIVE_FILE; - struct lru_gen_folio *lrugen = &lruvec->lrugen; - - VM_WARN_ON_ONCE(old_gen != -1 && old_gen >= MAX_NR_GENS); -@@ -186,36 +337,9 @@ static inline void lru_gen_update_size(struct lruvec *lruvec, struct folio *foli - VM_WARN_ON_ONCE(old_gen == -1 && new_gen == -1); - - if (old_gen >= 0) -- WRITE_ONCE(lrugen->nr_pages[old_gen][type][zone], -- lrugen->nr_pages[old_gen][type][zone] - delta); -+ atomic_long_sub(delta, &lrugen->nr_pages[old_gen][type][zone]); - if (new_gen >= 0) -- WRITE_ONCE(lrugen->nr_pages[new_gen][type][zone], -- lrugen->nr_pages[new_gen][type][zone] + delta); -- -- /* addition */ -- if (old_gen < 0) { -- if (lru_gen_is_active(lruvec, new_gen)) -- lru += LRU_ACTIVE; -- __update_lru_size(lruvec, lru, zone, delta); -- return; -- } -- -- /* deletion */ -- if (new_gen < 0) { -- if (lru_gen_is_active(lruvec, old_gen)) -- lru += LRU_ACTIVE; -- __update_lru_size(lruvec, lru, zone, -delta); -- return; -- } -- -- /* promotion */ -- if (!lru_gen_is_active(lruvec, old_gen) && lru_gen_is_active(lruvec, new_gen)) { -- __update_lru_size(lruvec, lru, zone, -delta); -- __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, delta); -- } -- -- /* demotion requires isolation, e.g., lru_deactivate_fn() */ -- VM_WARN_ON_ONCE(lru_gen_is_active(lruvec, old_gen) && !lru_gen_is_active(lruvec, new_gen)); -+ atomic_long_add(delta, &lrugen->nr_pages[new_gen][type][zone]); - } - - static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec, -@@ -223,23 +347,24 @@ static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec, - bool reclaiming) - { - int gen; -+ int refs = folio_lru_refs(folio); - int type = folio_is_file_lru(folio); - const struct lru_gen_folio *lrugen = &lruvec->lrugen; - - /* -- * +-----------------------------------+-----------------------------------+ -- * | Accessed through page tables and | Accessed through file descriptors | -- * | promoted by folio_update_gen() | and protected by folio_inc_gen() | -- * +-----------------------------------+-----------------------------------+ -- * | PG_active (set while isolated) | | -- * +-----------------+-----------------+-----------------+-----------------+ -- * | PG_workingset | PG_referenced | PG_workingset | LRU_REFS_FLAGS | -- * +-----------------------------------+-----------------------------------+ -- * |<---------- MIN_NR_GENS ---------->| | -- * |<---------------------------- MAX_NR_GENS ---------------------------->| -+ * +------------------------------------------+------------------------------------------+ -+ * | Accessed through page tables and | Accessed through file descriptors | -+ * | promoted by folio_inc_lru_refs_walk() | protected by folio_inc_lru_refs/inc_gen | -+ * +------------------------------------------+------------------------------------------+ -+ * | PG_active (set at isolation or refault) | | -+ * +--------------------+---------------------+--------------------+---------------------+ -+ * | LRU_REFS_MAX | LRU_REFS_WORKINGSET | LRU_REFS_MAX | LRU_REFS_WORKINGSET | -+ * +------------------------------------------+------------------------------------------+ -+ * |<-------------- MIN_NR_GENS ------------->| | -+ * |<----------------------------------- MAX_NR_GENS ----------------------------------->| - */ - if (folio_test_active(folio)) -- gen = MIN_NR_GENS - folio_test_workingset(folio); -+ gen = MIN_NR_GENS - (refs >= LRU_REFS_WORKINGSET); - else if (reclaiming) - gen = MAX_NR_GENS; - else if ((!folio_is_file_lru(folio) && !folio_test_swapcache(folio)) || -@@ -247,7 +372,7 @@ static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec, - (folio_test_dirty(folio) || folio_test_writeback(folio)))) - gen = MIN_NR_GENS; - else -- gen = MAX_NR_GENS - (folio_test_workingset(folio) || folio_test_referenced(folio)); -+ gen = MAX_NR_GENS - (refs >= LRU_REFS_WORKINGSET); - - return max(READ_ONCE(lrugen->max_seq) - gen + 1, READ_ONCE(lrugen->min_seq[type])); - } -@@ -256,12 +381,15 @@ static inline bool lru_gen_add_folio(struct lruvec *lruvec, struct folio *folio, - { - unsigned long seq; - unsigned long flags; -- int gen = folio_lru_gen(folio); -+ int gen, refs; - int type = folio_is_file_lru(folio); - int zone = folio_zonenum(folio); -+ int delta = folio_nr_pages(folio); -+ enum lru_list lru = type * LRU_INACTIVE_FILE; - struct lru_gen_folio *lrugen = &lruvec->lrugen; - -- VM_WARN_ON_ONCE_FOLIO(gen != -1, folio); -+ BUILD_BUG_ON(BIT(LRU_GEN_WIDTH - 1) != MAX_NR_GENS); -+ VM_WARN_ON_ONCE_FOLIO(folio_lru_gen(folio) != -1, folio); - - if (folio_test_unevictable(folio) || !lrugen->enabled) - return false; -@@ -270,9 +398,15 @@ static inline bool lru_gen_add_folio(struct lruvec *lruvec, struct folio *folio, - gen = lru_gen_from_seq(seq); - flags = (gen + 1UL) << LRU_GEN_PGOFF; - /* see the comment on MIN_NR_GENS about PG_active */ -- set_mask_bits(&folio->flags.f, LRU_GEN_MASK | BIT(PG_active), flags); -+ flags = set_mask_bits(folio_flags(folio, 0), LRU_GEN_MASK | BIT(PG_active), flags); -+ /* use the refs from the atomic snapshot to avoid raced update */ -+ refs = lru_get_refs_flags(flags); -+ -+ lru_gen_update_size(lruvec, type, folio, -1, gen); -+ if (lru_refs_is_active(refs)) -+ lru += LRU_ACTIVE; -+ __update_lru_size(lruvec, lru, zone, delta); - -- lru_gen_update_size(lruvec, folio, -1, gen); - /* for folio_rotate_reclaimable() */ - if (reclaiming) - list_add_tail(&folio->lru, &lrugen->folios[gen][type][zone]); -@@ -285,31 +419,38 @@ static inline bool lru_gen_add_folio(struct lruvec *lruvec, struct folio *folio, - static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio, bool reclaiming) - { - unsigned long flags; -- int gen = folio_lru_gen(folio); -+ int gen, refs; -+ int type = folio_is_file_lru(folio); -+ int zone = folio_zonenum(folio); -+ int delta = folio_nr_pages(folio); -+ enum lru_list lru = folio_is_file_lru(folio) * LRU_INACTIVE_FILE; -+ unsigned long max_seq = READ_ONCE(lruvec->lrugen.max_seq); - -+ flags = set_mask_bits(folio_flags(folio, 0), LRU_GEN_MASK, 0); -+ gen = lru_get_gen_flags(flags); -+ refs = lru_get_refs_flags(flags); - if (gen < 0) - return false; - - VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio); - VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio); - -- /* for folio_migrate_flags() */ -- flags = !reclaiming && lru_gen_is_active(lruvec, gen) ? BIT(PG_active) : 0; -- flags = set_mask_bits(&folio->flags.f, LRU_GEN_MASK, flags); -- gen = ((flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1; -+ /* -+ * See the comment in lru_gen_folio_seq. For migration, compaction, -+ * or any other isolation of a hot folio, try best to retain its gen -+ * info. Ideally we would keep the full gen info. -+ */ -+ if (!reclaiming && ((max_seq - gen) % MAX_NR_GENS) < MIN_NR_GENS) -+ folio_set_active(folio); - -- lru_gen_update_size(lruvec, folio, gen, -1); -+ lru_gen_update_size(lruvec, type, folio, gen, -1); -+ if (lru_refs_is_active(refs)) -+ lru += LRU_ACTIVE; -+ __update_lru_size(lruvec, lru, zone, -delta); - list_del(&folio->lru); - - return true; - } -- --static inline void folio_migrate_refs(struct folio *new, const struct folio *old) --{ -- unsigned long refs = READ_ONCE(old->flags.f) & LRU_REFS_MASK; -- -- set_mask_bits(&new->flags.f, LRU_REFS_MASK, refs); --} - #else /* !CONFIG_LRU_GEN */ - - static inline bool lru_gen_enabled(void) -@@ -336,12 +477,76 @@ static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio, - { - return false; - } -+#endif /* CONFIG_LRU_GEN */ - --static inline void folio_migrate_refs(struct folio *new, const struct folio *old) -+/** -+ * folio_inc_lru_refs_fast - Bump folio refs count without promotion. -+ * @folio: the folio -+ * -+ * Raise refs from 0 to LRU_REFS_REFERENCED and leave hotter folios -+ * untouched. For the classical LRU, a plain PG_referenced set. -+ */ -+static __always_inline void folio_inc_lru_refs_fast(struct folio *folio) - { -+ unsigned long new_flags, old_flags; - -+ if (!lru_gen_enabled()) { -+ folio_set_referenced(folio); -+ return; -+ } -+ -+ BUILD_BUG_ON(LRU_REFS_REFERENCED >= LRU_REFS_ACTIVATED); -+ old_flags = READ_ONCE(*folio_flags(folio, 0)); -+ do { -+ if (lru_get_refs_flags(old_flags)) -+ break; -+ new_flags = old_flags; -+ lru_set_refs_flags(&new_flags, LRU_REFS_REFERENCED); -+ } while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags)); -+} -+ -+/** -+ * folio_check_lru_refs - Test if an LRU managed folio has been referenced. -+ * @folio: The folio to test. -+ * -+ * Returns true if the MGLRU refs count is nonzero, or PG_referenced is set, -+ * which is also correct for the non-MGLRU case. Kept as a separate helper, -+ * to avoid splattering the lru_gen_enabled() static key. -+ */ -+static inline bool folio_check_lru_refs(const struct folio *folio) -+{ -+ if (lru_gen_enabled()) -+ return folio_lru_refs(folio) > 0; -+ return folio_test_referenced(folio); -+} -+ -+/** -+ * folio_clear_lru_refs - Clear the referenced state of an LRU managed folio. -+ * @folio: The folio to clear. -+ * -+ * Reset the MGLRU refs count to zero, or clear PG_referenced, leaving -+ * PG_workingset alone for the non-MGLRU case. Kept as a separate helper -+ * just like folio_check_lru_refs(). -+ */ -+static inline void folio_clear_lru_refs(struct folio *folio) -+{ -+ if (lru_gen_enabled()) -+ folio_reset_lru_refs(folio); -+ else -+ folio_clear_referenced(folio); -+} -+ -+/* -+ * For the classical LRU only: with MGLRU the PG_workingset bit is -+ * part of the folio refs count maintained by folio_inc_lru_refs(), -+ * and a raw set would corrupt it. The switching window is exempt -+ * because the classical paths legitimately run alongside MGLRU then. -+ */ -+static __always_inline void folio_set_workingset(struct folio *folio) -+{ -+ VM_WARN_ON_ONCE(lru_gen_enabled() && !lru_gen_switching()); -+ set_bit(PG_workingset, folio_flags(folio, FOLIO_HEAD_PAGE)); - } --#endif /* CONFIG_LRU_GEN */ - - static __always_inline - void lruvec_add_folio(struct lruvec *lruvec, struct folio *folio) -diff --git a/include/linux/mmzone.h b/include/linux/mmzone.h -index da8dd04..6bdbcc6 100644 ---- a/include/linux/mmzone.h -+++ b/include/linux/mmzone.h -@@ -453,15 +453,15 @@ enum lruvec_flags { - * least twice before handing this folio over to the eviction. The first check - * clears the accessed bit from the initial fault; the second check makes sure - * this folio hasn't been used since then. This process, AKA second chance, -- * requires a minimum of two generations, hence MIN_NR_GENS. And to maintain ABI -- * compatibility with the active/inactive LRU, e.g., /proc/vmstat, these two -- * generations are considered active; the rest of generations, if they exist, -- * are considered inactive. See lru_gen_is_active(). -+ * requires a minimum of two generations, hence MIN_NR_GENS. -+ * -+ * Active/inactive is per-folio based on the referenced count; -+ * see the comment above MAX_NR_TIERS. - * - * PG_active is always cleared while a folio is on one of lrugen->folios[] so -- * that the sliding window needs not to worry about it. And it's set again when -- * a folio considered active is isolated for non-reclaiming purposes, e.g., -- * migration. See lru_gen_add_folio() and lru_gen_del_folio(). -+ * that the sliding window needs not to worry about it. It is set on a -+ * fault-driven refault (see lru_gen_refault), or isolation (see -+ * lru_gen_del_folio). - * - * MAX_NR_GENS is set to 4 so that the multi-gen LRU can support twice the - * number of categories of the active/inactive LRU when keeping track of -@@ -472,56 +472,128 @@ enum lruvec_flags { - #define MAX_NR_GENS 4U - - /* -- * Each generation is divided into multiple tiers. A folio accessed N times -- * through file descriptors is in tier order_base_2(N). A folio in the first -- * tier (N=0,1) is marked by PG_referenced unless it was faulted in through page -- * tables or read ahead. A folio in the last tier (MAX_NR_TIERS-1) is marked by -- * PG_workingset. A folio in any other tier (1flags. -+ * Each generation is divided into multiple tiers. A folio's referenced -+ * count maps to a tier as shown below: - * -- * In contrast to moving across generations which requires the LRU lock, moving -- * across tiers only involves atomic operations on folio->flags and therefore -- * has a negligible cost in the buffered access path. In the eviction path, -- * comparisons of refaulted/(evicted+protected) from the first tier and the rest -- * infer whether folios accessed multiple times through file descriptors are -- * statistically hot and thus worth protecting. -+ * MGLRU (frequency guidance) -+ * Refs Tier |- Refs: how many times (at least) a folio has been referenced. -+ * 0 0 |- Mostly cold pages, readahead, etc. [1] -+ * 1 0 |= LRU_REFS_REFERENCED: Used at least once. [2] -+ * -WORKINGSET-+|- Pages beyond are workingset and never fall below this floor. [3] -+ * 2 1<-+|= LRU_REFS_WORKINGSET: Classical workingset, accessed twice, protected. [4] -+ * 3 2 |- LRU_REFS_PROTECTED: Protected workingset, promoted pages capped at here. [5] -+ * 4 2 | -+ * 5 3 |- The tier here is MAX_NR_TIERS - 1 -+ * 6 3 | -+ * 7 3 |= LRU_REFS_MAX: Promotion candidate. [6] -+ * -PROMOTION->-/ - * -- * MAX_NR_TIERS is set to 4 so that the multi-gen LRU can support twice the -- * number of categories of the active/inactive LRU when keeping track of -- * accesses through file descriptors. This uses MAX_NR_TIERS-2 spare bits in -- * folio->flags, masked by LRU_REFS_MASK. -+ * Ideally each tier holds folios of similar access patterns: lower tiers -+ * are less important and evicted faster. A page's reference count and -+ * tier are capped when it changes generation, preventing it from -+ * dominating the new generation based on old-generation access history. -+ * Generation ordering already ensures a newer-gen page is hotter than an -+ * older-gen one regardless of tier. -+ * -+ * Refs tracks accesses from two sources: page table (lazily collected by -+ * the page table aging walk or rmap eviction lookup) and file descriptors -+ * (by folio_mark_accessed). Page table accesses are weighted heavier -+ * because the accessed bit is sticky (undercounts repeated accesses), -+ * passively collected, and page faults are generally more important as -+ * userspace does not expect a memory access to block on reclaim. Both -+ * access types increment refs by one; the result is capped at -+ * LRU_REFS_PROTECTED on promotion or deferral, or LRU_REFS_MAX otherwise. -+ * -+ * 1. Tier is fls(N-1) for N > 1, 0 otherwise. Folios with zero -+ * accesses (refs == 0) are generally cold, e.g. readahead folios. -+ * -+ * Freshly allocated folios start with refs == 0; faulted and mapped -+ * folios have their page table access bit set, so the first page table -+ * access check always sets LRU_REFS_REFERENCED. That is the second -+ * chance described above MIN_NR_GENS: it moves the folio one -+ * generation forward if it is at the tail of its LRU, i.e., in one -+ * of the two oldest generations of its type. -+ * -+ * 2. Folios accessed once stay on tier 0: one-time usage does not -+ * qualify for protection. A second access advances the folio, -+ * aligning with classical LRU's use-twice threshold. A second page -+ * table access promotes to the latest gen; file access only defers -+ * eviction from the tail gens of its type. -+ * -+ * 3. Folios accessed at least twice are considered workingset. This -+ * mostly aligns with classical LRU: at least one I/O is saved by -+ * keeping them in memory. Folios at or above this level never fall -+ * below tier 1 (the workingset floor), so tier 0 stays a clean tier -+ * for cold cache while tier 1 serves as the fallback line for -+ * actually reused or historically hot folios. -+ * -+ * Folios refaulted through a page fault at refs 1 will enter the second -+ * newest gen, so faulting will be protected better. -+ * -+ * 4. Starting from tier 1, PID protection sacrifices lower tiers to -+ * protect higher tiers by comparing refault rates for long-term -+ * accuracy, and caps higher refs to this value. Since PID protection -+ * bypasses page table lookup and clearing, when a further eviction -+ * attempt occurs after PID loosens, the folio's page table access is -+ * rechecked and a referenced folio is put back with refs capped to -+ * this value as well. This also gives folios a fair opportunity to be -+ * promoted by file access again. -+ * -+ * Folios refaulted through a page fault at tier 1 or above are activated -+ * and enter the newest gen. Non fault page will enter second oldest gen, -+ * driving aging and workingset shifting. -+ * -+ * 5. Pages beyond the ordinary workingset tier form new tiers for the -+ * PID controller to protect differently. Folios at or above this -+ * level are capped at LRU_REFS_PROTECTED on promotion or deferral, -+ * and at LRU_REFS_WORKINGSET under PID protection in the oldest -+ * generation, where they represent a historical workingset. -+ * -+ * 6. Folios that reach LRU_REFS_MAX are advanced to the next generation -+ * on further access, with refs capped to LRU_REFS_PROTECTED. This -+ * gives them a fair start for advancement to an even newer generation -+ * while keeping hot folios distinguishable. -+ * -+ * Tiering uses PG_referenced and PG_workingset as the lower two bits, -+ * and the bits masked by LRU_REFS_MASK as the higher bits, so the refs -+ * count ranges from 0 to LRU_REFS_MAX. A folio is on the workingset -+ * tier once accessed at least twice, which is more consistent with the -+ * classical LRU. -+ * -+ * A folio's referenced count never goes backwards except upon gen -+ * increase as described above, or when explicitly reset by -+ * folio_reset_lru_refs(). Refault of a reclaimed folio restores -+ * its referenced count, capped at LRU_REFS_PROTECTED, which aligns with -+ * promotion. Page table refaults of previous workingset folios send -+ * them to the latest gen, driving aging faster. -+ * -+ * For the active/inactive LRU ABI (/proc/vmstat), a folio is active -+ * if its referenced count reaches LRU_REFS_ACTIVATED. The threshold -+ * currently set to LRU_REFS_PROTECTED, which is tier 2. -+ * -+ * MAX_NR_TIERS is set to 4 so that the multi-gen LRU can support twice -+ * the number of categories of the active/inactive LRU. - */ - #define MAX_NR_TIERS 4U - #define LRU_TIER_MIN 0U - #define LRU_TIER_MAX (MAX_NR_TIERS - 1) - -+/* Flags for folio_inc_lru_refs() */ -+#define LRU_REF_MAPPED 0x1U -+#define LRU_REF_EXEC 0x2U -+#define LRU_REF_FORCE 0x4U -+ -+#define LRU_REFS_REFERENCED 0x1 -+#define LRU_REFS_WORKINGSET 0x2 -+#define LRU_REFS_PROTECTED 0x3 -+#define LRU_REFS_ACTIVATED LRU_REFS_PROTECTED -+ - #ifndef __GENERATING_BOUNDS_H - - #define LRU_GEN_MASK ((BIT(LRU_GEN_WIDTH) - 1) << LRU_GEN_PGOFF) - #define LRU_REFS_MASK ((BIT(LRU_REFS_WIDTH) - 1) << LRU_REFS_PGOFF) -- --/* -- * For folios accessed multiple times through file descriptors, -- * lru_gen_inc_refs() sets additional bits of LRU_REFS_WIDTH in folio->flags -- * after PG_referenced, then PG_workingset after LRU_REFS_WIDTH. After all its -- * bits are set, i.e., LRU_REFS_FLAGS|BIT(PG_workingset), a folio is lazily -- * promoted into the second oldest generation in the eviction path. And when -- * folio_inc_gen() does that, it clears LRU_REFS_FLAGS so that -- * lru_gen_inc_refs() can start over. Note that for this case, LRU_REFS_MASK is -- * only valid when PG_referenced is set. -- * -- * For folios accessed multiple times through page tables, folio_update_gen() -- * from a page table walk or lru_gen_set_refs() from a rmap walk sets -- * PG_referenced after the accessed bit is cleared for the first time. -- * Thereafter, those two paths set PG_workingset and promote folios to the -- * youngest generation. Like folio_inc_gen(), folio_update_gen() also clears -- * PG_referenced. Note that for this case, LRU_REFS_MASK is not used. -- * -- * For both cases above, after PG_workingset is set on a folio, it remains until -- * this folio is either reclaimed, or "deactivated" by lru_gen_clear_refs(). It -- * can be set again if lru_gen_test_recent() returns true upon a refault. -- */ --#define LRU_REFS_FLAGS (LRU_REFS_MASK | BIT(PG_referenced)) -+#define LRU_REFS_FLAGS (LRU_REFS_MASK | BIT(PG_referenced) | BIT(PG_workingset)) -+#define LRU_REFS_MAX (BIT(LRU_REFS_WIDTH + 2) - 1) - - struct lruvec; - struct page_vma_mapped_walk; -@@ -572,7 +644,7 @@ struct lru_gen_folio { - /* the multi-gen LRU lists, lazily sorted on eviction */ - struct list_head folios[MAX_NR_GENS][ANON_AND_FILE][MAX_NR_ZONES]; - /* the multi-gen LRU sizes, eventually consistent */ -- long nr_pages[MAX_NR_GENS][ANON_AND_FILE][MAX_NR_ZONES]; -+ atomic_long_t nr_pages[MAX_NR_GENS][ANON_AND_FILE][MAX_NR_ZONES]; - /* the exponential moving average of refaulted */ - unsigned long avg_refaulted[ANON_AND_FILE][MAX_NR_TIERS]; - /* the exponential moving average of evicted+protected */ -@@ -623,6 +695,8 @@ struct lru_gen_mm_walk { - unsigned long seq; - /* the next address within an mm to scan */ - unsigned long next_addr; -+ /* to batch activated pages */ -+ int nr_activated[ANON_AND_FILE][MAX_NR_ZONES]; - /* to batch promoted pages */ - int nr_pages[MAX_NR_GENS][ANON_AND_FILE][MAX_NR_ZONES]; - /* to batch the mm stats */ -diff --git a/include/linux/page-flags.h b/include/linux/page-flags.h -index 7a86357..13f1b4a 100644 ---- a/include/linux/page-flags.h -+++ b/include/linux/page-flags.h -@@ -554,8 +554,6 @@ PAGEFLAG(LRU, lru, PF_HEAD) __CLEARPAGEFLAG(LRU, lru, PF_HEAD) - FOLIO_FLAG(active, FOLIO_HEAD_PAGE) - __FOLIO_CLEAR_FLAG(active, FOLIO_HEAD_PAGE) - FOLIO_TEST_CLEAR_FLAG(active, FOLIO_HEAD_PAGE) --PAGEFLAG(Workingset, workingset, PF_HEAD) -- TESTCLEARFLAG(Workingset, workingset, PF_HEAD) - PAGEFLAG(Checked, checked, PF_NO_COMPOUND) /* Used by some filesystems */ - - /* Xen */ -diff --git a/include/linux/perf_event.h b/include/linux/perf_event.h -index 2d5e768..b422c06 100644 ---- a/include/linux/perf_event.h -+++ b/include/linux/perf_event.h -@@ -1616,7 +1616,7 @@ static inline void perf_event_task_migrate(struct task_struct *task) - task->sched_migrated = 1; - } - --static inline void perf_event_task_sched_in(struct task_struct *prev, -+static __always_inline void perf_event_task_sched_in(struct task_struct *prev, - struct task_struct *task) - { - if (static_branch_unlikely(&perf_sched_events)) -diff --git a/include/linux/rseq_entry.h b/include/linux/rseq_entry.h -index 31ce349..23db2b3 100644 ---- a/include/linux/rseq_entry.h -+++ b/include/linux/rseq_entry.h -@@ -730,7 +730,10 @@ static __always_inline void rseq_syscall_exit_to_user_mode(void) - - /* Needed to remove the store for the !lockdep case */ - if (IS_ENABLED(CONFIG_LOCKDEP)) { -+#ifndef CONFIG_SCHED_ALT -+/* WA for sched/alt: [Sync] 9a723ed7facf sched/mmcid: Provide new scheduler CID mechanism */ - WARN_ON_ONCE(ev->sched_switch); -+#endif /* !CONFIG_SCHED_ALT */ - ev->events = 0; - } - } -diff --git a/include/linux/sched.h b/include/linux/sched.h -index 78bfc0e..2d1fa54 100644 ---- a/include/linux/sched.h -+++ b/include/linux/sched.h -@@ -871,6 +871,7 @@ struct task_struct { - unsigned long wakee_flip_decay_ts; - struct task_struct *last_wakee; - -+#ifndef CONFIG_SCHED_ALT - /* - * recent_used_cpu is initially set as the last CPU used by a task - * that wakes affine another task. Waker/wakee relationships can -@@ -880,12 +881,33 @@ struct task_struct { - */ - int recent_used_cpu; - int wake_cpu; -+#endif /* !CONFIG_SCHED_ALT */ - - int prio; - int static_prio; - int normal_prio; - unsigned int rt_priority; - -+#ifdef CONFIG_SCHED_ALT -+ u64 last_ran; -+ s64 time_slice; -+ u64 wake_start; -+ struct list_head sq_node; -+#ifdef CONFIG_SCHED_BMQ -+ int boost_prio; -+#endif /* CONFIG_SCHED_BMQ */ -+#ifdef CONFIG_SCHED_PDS -+ u64 deadline; -+ u64 sleep_start; -+ u64 sleep_credit; -+ u64 wake_sched_time; -+ u64 wake_period; -+ u64 credit_wake; -+ u64 credit_sched_time; -+#endif /* CONFIG_SCHED_PDS */ -+ /* sched_clock time spent running */ -+ u64 sched_time; -+#else /* !CONFIG_SCHED_ALT */ - struct sched_entity se; - struct sched_rt_entity rt; - struct sched_dl_entity dl; -@@ -900,6 +922,7 @@ struct task_struct { - unsigned long core_cookie; - unsigned int core_occupation; - #endif -+#endif /* !CONFIG_SCHED_ALT */ - - #ifdef CONFIG_CGROUP_SCHED - struct task_group *sched_task_group; -@@ -941,9 +964,13 @@ struct task_struct { - const cpumask_t *cpus_ptr; - cpumask_t *user_cpus_ptr; - cpumask_t cpus_mask; -+#ifndef CONFIG_SCHED_ALT - void *migration_pending; -+#endif - unsigned short migration_disabled; -+#ifndef CONFIG_SCHED_ALT - unsigned short migration_flags; -+#endif - - #ifdef CONFIG_PREEMPT_RCU - int rcu_read_lock_nesting; -@@ -974,8 +1001,10 @@ struct task_struct { - struct sched_info sched_info; - - struct list_head tasks; -+#ifndef CONFIG_SCHED_ALT - struct plist_node pushable_tasks; - struct rb_node pushable_dl_tasks; -+#endif - - struct mm_struct *mm; - struct mm_struct *active_mm; -@@ -1703,6 +1732,15 @@ static inline bool sched_proxy_exec(void) - } - #endif - -+#ifdef CONFIG_SCHED_ALT -+#define tsk_seruntime(t) ((t)->sched_time) -+/* replace the uncertian rt_timeout with 0UL */ -+#define tsk_rttimeout(t) (0UL) -+#else /* !CONFIG_SCHED_ALT: */ -+#define tsk_seruntime(t) ((t)->se.sum_exec_runtime) -+#define tsk_rttimeout(t) ((t)->rt.timeout) -+#endif /* !CONFIG_SCHED_ALT */ -+ - #define TASK_REPORT_IDLE (TASK_REPORT + 1) - #define TASK_REPORT_MAX (TASK_REPORT_IDLE << 1) - -@@ -2301,7 +2339,11 @@ static inline void set_task_cpu(struct task_struct *p, unsigned int cpu) - - static inline bool task_is_runnable(struct task_struct *p) - { -+#ifdef CONFIG_SCHED_ALT -+ return p->on_rq; -+#else - return p->on_rq && !p->se.sched_delayed; -+#endif /* !CONFIG_SCHED_ALT */ - } - - extern bool sched_task_on_rq(struct task_struct *p); -@@ -2460,10 +2502,33 @@ DECLARE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues); - #endif - #define this_rq_pinned() (*(unsigned int *)((void *)this_rq_raw() + RQ_nr_pinned)) - -+static inline void -+__do_set_cpus_ptr(struct task_struct *p, const struct cpumask *new_mask) -+{ -+ /* -+ * This here violates the locking rules for affinity, since we're only -+ * supposed to change these variables while holding both rq->lock and -+ * p->pi_lock. -+ * -+ * HOWEVER, it magically works, because ttwu() is the only code that -+ * accesses these variables under p->pi_lock and only does so after -+ * smp_cond_load_acquire(&p->on_cpu, !VAL), and we're in __schedule() -+ * before finish_task(). -+ * -+ * XXX do further audits, this smells like something putrid. -+ */ -+ WARN_ON_ONCE(!p->on_cpu); -+ p->cpus_ptr = new_mask; -+} -+ - static inline void __migrate_enable(void) - { - struct task_struct *p = current; - -+#ifdef CONFIG_SCHED_ALT -+ if (!p->migration_disabled) -+ return; -+#endif - #ifdef CONFIG_DEBUG_PREEMPT - /* - * Check both overflow from migrate_disable() and superfluous -@@ -2483,8 +2548,17 @@ static inline void __migrate_enable(void) - * __set_cpus_allowed_ptr(SCA_MIGRATE_ENABLE) doesn't schedule(). - */ - guard(preempt)(); -+#ifdef CONFIG_SCHED_ALT -+ /* -+ * Assumption: current should be running on allowed cpu -+ */ -+ WARN_ON_ONCE(!cpumask_test_cpu(smp_processor_id(), &p->cpus_mask)); -+ if (p->cpus_ptr != &p->cpus_mask) -+ __do_set_cpus_ptr(p, &p->cpus_mask); -+#else - if (unlikely(p->cpus_ptr != &p->cpus_mask)) - ___migrate_enable(); -+#endif - /* - * Mustn't clear migration_disabled() until cpus_ptr points back at the - * regular cpus_mask, otherwise things that race (eg. -@@ -2511,8 +2585,20 @@ static inline void __migrate_disable(void) - } - - guard(preempt)(); -+#ifdef CONFIG_SCHED_ALT -+ int cpu = smp_processor_id(); -+ if (cpumask_test_cpu(cpu, &p->cpus_mask)) { -+#endif - this_rq_pinned()++; - p->migration_disabled = 1; -+#ifdef CONFIG_SCHED_ALT -+ /* -+ * Violates locking rules! see comment in __do_set_cpus_ptr(). -+ */ -+ if (p->cpus_ptr == &p->cpus_mask) -+ __do_set_cpus_ptr(p, cpumask_of(cpu)); -+ } -+#endif - } - #else /* !COMPILE_OFFSETS */ - static inline void __migrate_disable(void) { } -diff --git a/include/linux/sched/deadline.h b/include/linux/sched/deadline.h -index 2735382..12b4150 100644 ---- a/include/linux/sched/deadline.h -+++ b/include/linux/sched/deadline.h -@@ -2,6 +2,25 @@ - #ifndef _LINUX_SCHED_DEADLINE_H - #define _LINUX_SCHED_DEADLINE_H - -+#ifdef CONFIG_SCHED_ALT -+ -+static inline int dl_task(struct task_struct *p) -+{ -+ return 0; -+} -+ -+#ifdef CONFIG_SCHED_BMQ -+#define __tsk_deadline(p) (0UL) -+#endif -+ -+#ifdef CONFIG_SCHED_PDS -+#define __tsk_deadline(p) ((((u64) ((p)->prio))<<56) | (p)->deadline) -+#endif -+ -+#else -+ -+#define __tsk_deadline(p) ((p)->dl.deadline) -+ - /* - * SCHED_DEADLINE tasks has negative priorities, reflecting - * the fact that any of them has higher prio than RT and -@@ -72,5 +91,6 @@ static inline bool dl_is_implicit(struct sched_dl_entity *dl_se) - { - return dl_se->dl_deadline == dl_se->dl_period; - } -+#endif /* !CONFIG_SCHED_ALT */ - - #endif /* _LINUX_SCHED_DEADLINE_H */ -diff --git a/include/linux/sched/mm.h b/include/linux/sched/mm.h -index d7c6a94..d1b4bdd 100644 ---- a/include/linux/sched/mm.h -+++ b/include/linux/sched/mm.h -@@ -44,7 +44,7 @@ static inline void smp_mb__after_mmgrab(void) - - extern void __mmdrop(struct mm_struct *mm); - --static inline void mmdrop(struct mm_struct *mm) -+static __always_inline void mmdrop(struct mm_struct *mm) - { - /* - * The implicit full barrier implied by atomic_dec_and_test() is -@@ -71,14 +71,14 @@ static inline void __mmdrop_delayed(struct rcu_head *rhp) - * Invoked from finish_task_switch(). Delegates the heavy lifting on RT - * kernels via RCU. - */ --static inline void mmdrop_sched(struct mm_struct *mm) -+static __always_inline void mmdrop_sched(struct mm_struct *mm) - { - /* Provides a full memory barrier. See mmdrop() */ - if (atomic_dec_and_test(&mm->mm_count)) - call_rcu(&mm->delayed_drop, __mmdrop_delayed); - } - #else --static inline void mmdrop_sched(struct mm_struct *mm) -+static __always_inline void mmdrop_sched(struct mm_struct *mm) - { - mmdrop(mm); - } -@@ -104,7 +104,7 @@ static inline void mmdrop_lazy_tlb(struct mm_struct *mm) - } - } - --static inline void mmdrop_lazy_tlb_sched(struct mm_struct *mm) -+static __always_inline void mmdrop_lazy_tlb_sched(struct mm_struct *mm) - { - if (IS_ENABLED(CONFIG_MMU_LAZY_TLB_REFCOUNT)) - mmdrop_sched(mm); -@@ -531,7 +531,7 @@ enum { - #include - #endif - --static inline void membarrier_mm_sync_core_before_usermode(struct mm_struct *mm) -+static __always_inline void membarrier_mm_sync_core_before_usermode(struct mm_struct *mm) - { - /* - * The atomic_read() below prevents CSE. The following should -diff --git a/include/linux/sched/prio.h b/include/linux/sched/prio.h -index 6ab43b4..ef1cff5 100644 ---- a/include/linux/sched/prio.h -+++ b/include/linux/sched/prio.h -@@ -19,6 +19,28 @@ - #define MAX_PRIO (MAX_RT_PRIO + NICE_WIDTH) - #define DEFAULT_PRIO (MAX_RT_PRIO + NICE_WIDTH / 2) - -+#ifdef CONFIG_SCHED_ALT -+ -+/* Undefine MAX_PRIO and DEFAULT_PRIO */ -+#undef MAX_PRIO -+#undef DEFAULT_PRIO -+ -+/* +/- priority levels from the base priority */ -+#ifdef CONFIG_SCHED_BMQ -+#define MAX_PRIORITY_ADJ (12) -+#endif -+ -+#ifdef CONFIG_SCHED_PDS -+#define MAX_PRIORITY_ADJ (0) -+#endif -+ -+#define MIN_NORMAL_PRIO (128) -+#define NORMAL_PRIO_NUM (64) -+#define MAX_PRIO (MIN_NORMAL_PRIO + NORMAL_PRIO_NUM) -+#define DEFAULT_PRIO (MAX_PRIO - MAX_PRIORITY_ADJ - NICE_WIDTH / 2) -+ -+#endif /* CONFIG_SCHED_ALT */ -+ - /* - * Convert user-nice values [ -20 ... 0 ... 19 ] - * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ], -diff --git a/include/linux/sched/rt.h b/include/linux/sched/rt.h -index 922935c..9cb5c02 100644 ---- a/include/linux/sched/rt.h -+++ b/include/linux/sched/rt.h -@@ -45,8 +45,10 @@ static inline bool rt_or_dl_task_policy(struct task_struct *tsk) - - if (policy == SCHED_FIFO || policy == SCHED_RR) - return true; -+#ifndef CONFIG_SCHED_ALT - if (policy == SCHED_DEADLINE) - return true; -+#endif - return false; - } - -diff --git a/include/linux/sched/topology.h b/include/linux/sched/topology.h -index f96812d..8984fce 100644 ---- a/include/linux/sched/topology.h -+++ b/include/linux/sched/topology.h -@@ -226,7 +226,8 @@ extern void sched_update_asym_prefer_cpu(int cpu, int old_prio, int new_prio); - #define SDTL_INIT(maskfn, flagsfn, dname) ((struct sched_domain_topology_level) \ - { .mask = maskfn, .sd_flags = flagsfn, .name = #dname }) - --#if defined(CONFIG_ENERGY_MODEL) && defined(CONFIG_CPU_FREQ_GOV_SCHEDUTIL) -+#if defined(CONFIG_ENERGY_MODEL) && defined(CONFIG_CPU_FREQ_GOV_SCHEDUTIL) && \ -+ !defined(CONFIG_SCHED_ALT) - extern void rebuild_sched_domains_energy(void); - #else - static inline void rebuild_sched_domains_energy(void) -diff --git a/include/linux/tcp.h b/include/linux/tcp.h -index 6a8c777..38498e2 100644 ---- a/include/linux/tcp.h -+++ b/include/linux/tcp.h -@@ -232,7 +232,8 @@ struct tcp_sock { - tcp_usec_ts : 1, /* TSval values in usec */ - is_sack_reneg:1, /* in recovery from loss with SACK reneg? */ - is_cwnd_limited:1,/* forward progress limited by snd_cwnd? */ -- recvmsg_inq : 1;/* Indicate # of bytes in queue upon recvmsg */ -+ recvmsg_inq : 1,/* Indicate # of bytes in queue upon recvmsg */ -+ fast_ack_mode:1;/* ack ASAP if >1 rcv_mss received? */ - __cacheline_group_end(tcp_sock_read_txrx); - - /* RX read-mostly hotpath cache lines */ -@@ -298,7 +299,8 @@ struct tcp_sock { - * 0x5?10 << 16 + snd_wnd in net byte order - */ - u8 nonagle : 4,/* Disable Nagle algorithm? */ -- rate_app_limited:1; /* rate_{delivered,interval_us} limited? */ -+ rate_app_limited:1, /* rate_{delivered,interval_us} limited? */ -+ tlp_orig_data_app_limited:1; /* app-limited before TLP rtx? */ - u8 received_ce_pending:4, /* Not yet transmit cnt of received_ce */ - accecn_opt_sent_w_dsack:1,/* Sent ACCECN opt in previous ACK w/ D-SACK */ - unused2:3; -diff --git a/include/linux/tick.h b/include/linux/tick.h -index b121c5d..ea7002a 100644 ---- a/include/linux/tick.h -+++ b/include/linux/tick.h -@@ -172,7 +172,7 @@ extern cpumask_var_t tick_nohz_full_mask; - #ifdef CONFIG_NO_HZ_FULL - extern bool tick_nohz_full_running; - --static inline bool tick_nohz_full_enabled(void) -+static __always_inline bool tick_nohz_full_enabled(void) - { - if (!context_tracking_enabled()) - return false; -@@ -296,7 +296,7 @@ static inline void __tick_nohz_task_switch(void) { } - static inline void tick_nohz_full_setup(cpumask_var_t cpumask) { } - #endif - --static inline void tick_nohz_task_switch(void) -+static __always_inline void tick_nohz_task_switch(void) - { - if (tick_nohz_full_enabled()) - __tick_nohz_task_switch(); -diff --git a/include/linux/vtime.h b/include/linux/vtime.h -index 82825e7..ce83fc7 100644 ---- a/include/linux/vtime.h -+++ b/include/linux/vtime.h -@@ -89,24 +89,24 @@ static __always_inline void vtime_account_guest_exit(void) - * For now vtime state is tied to context tracking. We might want to decouple - * those later if necessary. - */ --static inline bool vtime_accounting_enabled(void) -+static __always_inline bool vtime_accounting_enabled(void) - { - return context_tracking_enabled(); - } - --static inline bool vtime_accounting_enabled_cpu(int cpu) -+static __always_inline bool vtime_accounting_enabled_cpu(int cpu) - { - return vtime_generic_enabled_cpu(cpu); - } - --static inline bool vtime_accounting_enabled_this_cpu(void) -+static __always_inline bool vtime_accounting_enabled_this_cpu(void) - { - return vtime_generic_enabled_this_cpu(); - } - - extern void vtime_task_switch_generic(struct task_struct *prev); - --static inline void vtime_task_switch(struct task_struct *prev) -+static __always_inline void vtime_task_switch(struct task_struct *prev) - { - if (vtime_accounting_enabled_this_cpu()) - vtime_task_switch_generic(prev); -diff --git a/include/net/inet_connection_sock.h b/include/net/inet_connection_sock.h -index 433c2df..ce51146 100644 ---- a/include/net/inet_connection_sock.h -+++ b/include/net/inet_connection_sock.h -@@ -138,8 +138,8 @@ struct inet_connection_sock { - u32 icsk_probes_tstamp; - u32 icsk_user_timeout; - -- u64 icsk_ca_priv[104 / sizeof(u64)]; --#define ICSK_CA_PRIV_SIZE sizeof_field(struct inet_connection_sock, icsk_ca_priv) -+#define ICSK_CA_PRIV_SIZE (144) -+ u64 icsk_ca_priv[ICSK_CA_PRIV_SIZE / sizeof(u64)]; - }; - - #define ICSK_TIME_RETRANS 1 /* Retransmit timer */ -diff --git a/include/net/tcp.h b/include/net/tcp.h -index 4416cdf..6828726 100644 ---- a/include/net/tcp.h -+++ b/include/net/tcp.h -@@ -428,6 +428,8 @@ static inline void tcp_dec_quickack_mode(struct sock *sk) - #define TCP_ECN_DEMAND_CWR BIT(2) - #define TCP_ECN_SEEN BIT(3) - #define TCP_ECN_MODE_ACCECN BIT(4) -+#define TCP_ECN_LOW BIT(5) -+#define TCP_ECN_ECT_PERMANENT BIT(6) - - #define TCP_ECN_DISABLED 0 - #define TCP_ECN_MODE_PENDING (TCP_ECN_MODE_RFC3168 | TCP_ECN_MODE_ACCECN) -@@ -891,6 +893,15 @@ static inline unsigned long tcp_reqsk_timeout(struct request_sock *req) - - u32 tcp_delack_max(const struct sock *sk); - -+static inline void tcp_set_ecn_low_from_dst(struct sock *sk, -+ const struct dst_entry *dst) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ -+ if (dst_feature(dst, RTAX_FEATURE_ECN_LOW)) -+ tp->ecn_flags |= TCP_ECN_LOW; -+} -+ - /* Compute the actual rto_min value */ - static inline u32 tcp_rto_min(const struct sock *sk) - { -@@ -1028,6 +1039,11 @@ static inline u32 tcp_stamp_us_delta(u64 t1, u64 t0) - return max_t(s64, t1 - t0, 0); - } - -+static inline u32 tcp_stamp32_us_delta(u32 t1, u32 t0) -+{ -+ return max_t(s32, t1 - t0, 0); -+} -+ - /* provide the departure time in us unit */ - static inline u64 tcp_skb_timestamp_us(const struct sk_buff *skb) - { -@@ -1141,9 +1157,14 @@ struct tcp_skb_cb { - /* pkts S/ACKed so far upon tx of skb, incl retrans: */ - __u32 delivered; - /* start of send pipeline phase */ -- u64 first_tx_mstamp; -+ u32 first_tx_mstamp; - /* when we reached the "delivered" count */ -- u64 delivered_mstamp; -+ u32 delivered_mstamp; -+#define TCPCB_IN_FLIGHT_BITS 20 -+#define TCPCB_IN_FLIGHT_MAX ((1U << TCPCB_IN_FLIGHT_BITS) - 1) -+ u32 in_flight:20, /* packets in flight at transmit */ -+ unused2:12; -+ u32 lost; /* packets lost so far upon tx of skb */ - } tx; /* only used for outgoing skbs */ - union { - struct inet_skb_parm h4; -@@ -1254,6 +1275,7 @@ enum tcp_ca_event { - CA_EVENT_LOSS, /* loss timeout */ - CA_EVENT_ECN_NO_CE, /* ECT set, but not CE marked */ - CA_EVENT_ECN_IS_CE, /* received CE marked IP packet */ -+ CA_EVENT_TLP_RECOVERY, /* a lost segment was repaired by TLP probe */ - }; - - /* Information about inbound ACK, passed to cong_ops->in_ack_event() */ -@@ -1282,9 +1304,11 @@ enum tcp_ca_ack_event_flags { - #define TCP_CONG_ECT_1_NEGOTIATION BIT(3) - /* Cannot fallback to RFC3168 during AccECN negotiation */ - #define TCP_CONG_NO_FALLBACK_RFC3168 BIT(4) -+/* Wants notification of CE events (CA_EVENT_ECN_IS_CE, CA_EVENT_ECN_NO_CE). */ -+#define TCP_CONG_WANTS_CE_EVENTS BIT(5) - #define TCP_CONG_MASK (TCP_CONG_NON_RESTRICTED | TCP_CONG_NEEDS_ECN | \ - TCP_CONG_NEEDS_ACCECN | TCP_CONG_ECT_1_NEGOTIATION | \ -- TCP_CONG_NO_FALLBACK_RFC3168) -+ TCP_CONG_NO_FALLBACK_RFC3168 | TCP_CONG_WANTS_CE_EVENTS) - - union tcp_cc_info; - -@@ -1304,10 +1328,13 @@ struct ack_sample { - */ - struct rate_sample { - u64 prior_mstamp; /* starting timestamp for interval */ -+ u32 prior_lost; /* tp->lost at "prior_mstamp" */ - u32 prior_delivered; /* tp->delivered at "prior_mstamp" */ - u32 prior_delivered_ce;/* tp->delivered_ce at "prior_mstamp" */ -+ u32 tx_in_flight; /* packets in flight at starting timestamp */ -+ s32 lost; /* number of packets lost over interval */ - s32 delivered; /* number of packets delivered over interval */ -- s32 delivered_ce; /* number of packets delivered w/ CE marks*/ -+ s32 delivered_ce; /* packets delivered w/ CE mark over interval */ - long interval_us; /* time for tp->delivered to incr "delivered" */ - u32 snd_interval_us; /* snd interval for delivered packets */ - u32 rcv_interval_us; /* rcv interval for delivered packets */ -@@ -1318,7 +1345,9 @@ struct rate_sample { - u32 last_end_seq; /* end_seq of most recently ACKed packet */ - bool is_app_limited; /* is sample from packet with bubble in pipe? */ - bool is_retrans; /* is sample from retransmission? */ -+ bool is_acking_tlp_retrans_seq; /* ACKed a TLP retransmit sequence? */ - bool is_ack_delayed; /* is this (likely) a delayed ACK? */ -+ bool is_ece; /* did this ACK have ECN marked? */ - }; - - struct tcp_congestion_ops { -@@ -1360,8 +1389,11 @@ struct tcp_congestion_ops { - /* hook for packet ack accounting (optional) */ - void (*pkts_acked)(struct sock *sk, const struct ack_sample *sample); - -- /* override sysctl_tcp_min_tso_segs (optional) */ -- u32 (*min_tso_segs)(struct sock *sk); -+ /* pick target number of segments per TSO/GSO skb (optional): */ -+ u32 (*tso_segs)(struct sock *sk, unsigned int mss_now); -+ -+ /* react to a specific lost skb (optional) */ -+ void (*skb_marked_lost)(struct sock *sk, const struct sk_buff *skb); - - /* new value of cwnd after loss (required) */ - u32 (*undo_cwnd)(struct sock *sk); -@@ -1421,6 +1453,14 @@ static inline char *tcp_ca_get_name_by_key(u32 key, char *buffer) - } - #endif - -+static inline bool tcp_ca_wants_ce_events(const struct sock *sk) -+{ -+ const struct inet_connection_sock *icsk = inet_csk(sk); -+ -+ return icsk->icsk_ca_ops->flags & (TCP_CONG_NEEDS_ECN | -+ TCP_CONG_WANTS_CE_EVENTS); -+} -+ - static inline bool tcp_ca_needs_ecn(const struct sock *sk) - { - const struct inet_connection_sock *icsk = inet_csk(sk); -@@ -1471,6 +1511,21 @@ static inline bool tcp_skb_sent_after(u64 t1, u64 t2, u32 seq1, u32 seq2) - return t1 > t2 || (t1 == t2 && after(seq1, seq2)); - } - -+/* If a retransmit failed due to local qdisc congestion or other local issues, -+ * then we may have called tcp_set_skb_tso_segs() to increase the number of -+ * segments in the skb without increasing the tx.in_flight. In all other cases, -+ * the tx.in_flight should be at least as big as the pcount of the sk_buff. We -+ * do not have the state to know whether a retransmit failed due to local qdisc -+ * congestion or other local issues, so to avoid spurious warnings we consider -+ * that any skb marked lost may have suffered that fate. -+ */ -+static inline bool tcp_skb_tx_in_flight_is_suspicious(u32 skb_pcount, -+ u32 skb_sacked_flags, -+ u32 tx_in_flight) -+{ -+ return (skb_pcount > tx_in_flight) && !(skb_sacked_flags & TCPCB_LOST); -+} -+ - /* These functions determine how the current flow behaves in respect of SACK - * handling. SACK is negotiated with the peer, and therefore it can vary - * between different flows. -@@ -2662,7 +2717,7 @@ struct tcp_plb_state { - u8 consec_cong_rounds:5, /* consecutive congested rounds */ - unused:3; - u32 pause_until; /* jiffies32 when PLB can resume rerouting */ --}; -+} __attribute__ ((__packed__)); - - static inline void tcp_plb_init(const struct sock *sk, - struct tcp_plb_state *plb) -diff --git a/include/net/tcp_ecn.h b/include/net/tcp_ecn.h -index 865d5c5..b5cd7e5 100644 ---- a/include/net/tcp_ecn.h -+++ b/include/net/tcp_ecn.h -@@ -606,10 +606,9 @@ static inline void tcp_ecn_send_syn(struct sock *sk, struct sk_buff *skb) - use_ecn = tcp_ecn == TCP_ECN_IN_ECN_OUT_ECN || - tcp_ecn == TCP_ECN_IN_ACCECN_OUT_ECN || - tcp_ca_needs_ecn(sk) || bpf_needs_ecn || use_accecn; -+ const struct dst_entry *dst = __sk_dst_get(sk); - - if (!use_ecn) { -- const struct dst_entry *dst = __sk_dst_get(sk); -- - if (dst && dst_feature(dst, RTAX_FEATURE_ECN)) - use_ecn = true; - } -@@ -627,6 +626,9 @@ static inline void tcp_ecn_send_syn(struct sock *sk, struct sk_buff *skb) - tp->syn_ect_snt = inet_sk(sk)->tos & INET_ECN_MASK; - } else { - tcp_ecn_mode_set(tp, TCP_ECN_MODE_RFC3168); -+ -+ if (dst) -+ tcp_set_ecn_low_from_dst(sk, dst); - } - } - } -diff --git a/include/uapi/linux/inet_diag.h b/include/uapi/linux/inet_diag.h -index 21f0d73..80794f6 100644 ---- a/include/uapi/linux/inet_diag.h -+++ b/include/uapi/linux/inet_diag.h -@@ -238,6 +238,29 @@ struct tcp_bbr_info { - __u32 bbr_min_rtt; /* min-filtered RTT in uSec */ - __u32 bbr_pacing_gain; /* pacing gain shifted left 8 bits */ - __u32 bbr_cwnd_gain; /* cwnd gain shifted left 8 bits */ -+ __u32 bbr_bw_hi_lsb; /* lower 32 bits of bw_hi */ -+ __u32 bbr_bw_hi_msb; /* upper 32 bits of bw_hi */ -+ __u32 bbr_bw_lo_lsb; /* lower 32 bits of bw_lo */ -+ __u32 bbr_bw_lo_msb; /* upper 32 bits of bw_lo */ -+ __u8 bbr_mode; /* current bbr_mode in state machine */ -+ __u8 bbr_phase; /* current state machine phase */ -+ __u8 unused1; /* alignment padding; not used yet */ -+ __u8 bbr_version; /* BBR algorithm version */ -+ __u32 bbr_inflight_lo; /* lower short-term data volume bound */ -+ __u32 bbr_inflight_hi; /* higher long-term data volume bound */ -+ __u32 bbr_extra_acked; /* max excess packets ACKed in epoch */ -+}; -+ -+/* TCP BBR congestion control bbr_phase as reported in netlink/ss stats. */ -+enum tcp_bbr_phase { -+ BBR_PHASE_INVALID = 0, -+ BBR_PHASE_STARTUP = 1, -+ BBR_PHASE_DRAIN = 2, -+ BBR_PHASE_PROBE_RTT = 3, -+ BBR_PHASE_PROBE_BW_UP = 4, -+ BBR_PHASE_PROBE_BW_DOWN = 5, -+ BBR_PHASE_PROBE_BW_CRUISE = 6, -+ BBR_PHASE_PROBE_BW_REFILL = 7, - }; - - union tcp_cc_info { -diff --git a/include/uapi/linux/rtnetlink.h b/include/uapi/linux/rtnetlink.h -index 3988b51..f76b0f1 100644 ---- a/include/uapi/linux/rtnetlink.h -+++ b/include/uapi/linux/rtnetlink.h -@@ -542,12 +542,14 @@ enum { - #define RTAX_FEATURE_TIMESTAMP (1 << 2) /* unused */ - #define RTAX_FEATURE_ALLFRAG (1 << 3) /* unused */ - #define RTAX_FEATURE_TCP_USEC_TS (1 << 4) -+#define RTAX_FEATURE_ECN_LOW (1 << 5) - - #define RTAX_FEATURE_MASK (RTAX_FEATURE_ECN | \ - RTAX_FEATURE_SACK | \ - RTAX_FEATURE_TIMESTAMP | \ - RTAX_FEATURE_ALLFRAG | \ -- RTAX_FEATURE_TCP_USEC_TS) -+ RTAX_FEATURE_TCP_USEC_TS | \ -+ RTAX_FEATURE_ECN_LOW) - - struct rta_session { - __u8 proto; -diff --git a/include/uapi/linux/tcp.h b/include/uapi/linux/tcp.h -index 03772dd..83eaf13 100644 ---- a/include/uapi/linux/tcp.h -+++ b/include/uapi/linux/tcp.h -@@ -185,6 +185,7 @@ enum tcp_fastopen_client_fail { - #define TCPI_OPT_SYN_DATA 32 /* SYN-ACK acked data in SYN sent or rcvd */ - #define TCPI_OPT_USEC_TS 64 /* usec timestamps */ - #define TCPI_OPT_TFO_CHILD 128 /* child from a Fast Open option on SYN */ -+#define TCPI_OPT_ECN_LOW 256 /* Low-latency ECN enabled at conn init */ - - /* - * Sender's congestion state indicating normal or abnormal situations -diff --git a/init/Kconfig b/init/Kconfig -index ad592fd..0f0ca94 100644 ---- a/init/Kconfig -+++ b/init/Kconfig -@@ -223,6 +223,45 @@ config THREAD_INFO_IN_TASK - - menu "General setup" - -+config ZEN_INTERACTIVE -+ bool "Tune kernel for interactivity" -+ default y -+ help -+ Tunes the kernel for responsiveness at the cost of throughput and power usage. -+ -+ --- Block Layer ---------------------------------------- -+ -+ Default scheduler for SQ..: mq-deadline -> bfq -+ Default scheduler for MQ..: none -> kyber -+ -+ --- Virtual Memory Subsystem --------------------------- -+ -+ Background-reclaim hugepages...: no -> yes -+ Compact unevictable............: yes -> no -+ Swap-in readahead..............: 3 -> 0 -+ -+ --- EEVDF CPU Scheduler -------------------------------- -+ -+ Minimal granularity............: 0.7 -> 0.4 ms -+ Migration cost.................: 0.5 -> 0.3 ms -+ Bandwidth slice size...........: 5 -> 3 ms -+ Task rebalancing threshold.....: 32 -> 8 -+ -+ --- PDS/BMQ CPU Scheduler ------------------------------ -+ -+ Scheduling timeslice...........: 4 -> 2 ms -+ PDS sleep credit...............: 0 -> 1 -+ -+ --- CPUFreq Settings ----------------------------------- -+ -+ Ondemand sampling down factor..: 1 -> 5 -+ Ondemand default up threshold..: 80 -> 55 -+ Ondemand micro up threshold....: 95 -> 60 -+ -+ --- Split/Bus lock detection -------------------------- -+ -+ Split lock mitigation..........: 1 -> 0 -+ - config BROKEN - bool - help -@@ -947,10 +986,59 @@ config SCHED_PROXY_EXEC - depends on !SCHED_CLASS_EXT - # Not particularly useful until we get to multi-rq proxying - depends on EXPERT -+ depends on !SCHED_ALT - help - This option enables proxy execution, a mechanism for mutex-owning - tasks to inherit the scheduling context of higher priority waiters. - -+menuconfig SCHED_ALT -+ bool "Alternative CPU Schedulers" -+ default n -+ help -+ This feature enables the ProjectC alternative CPU schedulers. -+ -+if SCHED_ALT -+ -+choice -+ prompt "Alternative CPU schedulers" -+ default SCHED_PDS -+ -+config SCHED_BMQ -+ bool "BMQ CPU scheduler" -+ help -+ The BitMap Queue CPU scheduler for excellent interactivity and -+ responsiveness on the desktop and solid scalability on normal -+ hardware and commodity servers. -+ -+config SCHED_PDS -+ bool "PDS CPU scheduler" -+ help -+ The Priority and Deadline based Skip list multiple queue CPU -+ Scheduler. -+ -+endchoice -+ -+config SCHED_PDS_SLEEP_CREDIT -+ bool "PDS sleep credit on by default" -+ depends on SCHED_PDS -+ default y if ZEN_INTERACTIVE -+ help -+ Move a task that slept ahead of CPU-bound tasks of the same nice -+ level when it wakes up. This favours interactivity over fairness. -+ sched_pds_sleep_credit= on the command line overrides it. -+ -+config SCHED_ALT_TOPOLOGY_KUNIT_TEST -+ bool "KUnit tests for alternative scheduler CPU topology" if !KUNIT_ALL_TESTS -+ depends on KUNIT=y && SCHED_SMT -+ default KUNIT_ALL_TESTS -+ help -+ Test the policy which selects generic, homogeneous SMT, or -+ heterogeneous P/E scheduling from detected CPU topology. -+ The tests cover incomplete classification and the rule that -+ detected E-core SMT disables P/E-aware scheduling. -+ -+endif -+ - endmenu - - # -@@ -1029,6 +1117,7 @@ config NUMA_BALANCING - depends on ARCH_HAS_PTE_PROTNONE - depends on !ARCH_WANT_NUMA_VARIABLE_LOCALITY - depends on SMP && NUMA_MIGRATION && !PREEMPT_RT -+ depends on !SCHED_ALT - help - This option adds support for automatic NUMA aware memory/task placement. - The mechanism is quite primitive and is based on migrating memory when -@@ -1040,6 +1129,7 @@ config SCHED_CACHE - bool "Cache aware load balance" - default y - depends on SMP -+ depends on !SCHED_ALT - help - When enabled, the scheduler will attempt to aggregate tasks from - the same process onto a single Last Level Cache (LLC) domain when -@@ -1326,7 +1416,7 @@ config CPUSETS - - config CPUSETS_V1 - bool "Legacy cgroup v1 cpusets controller" -- depends on CPUSETS -+ depends on (CPUSETS && !SCHED_ALT) - default n - help - Legacy cgroup v1 cpusets controller which has been deprecated by -@@ -1462,6 +1552,22 @@ config USER_NS - - If unsure, say N. - -+config USER_NS_UNPRIVILEGED -+ bool "Allow unprivileged users to create namespaces" -+ default y -+ depends on USER_NS -+ help -+ When disabled, unprivileged users will not be able to create -+ new namespaces. Allowing users to create their own namespaces -+ has been part of several recent local privilege escalation -+ exploits, so if you need user namespaces but are -+ paranoid^Wsecurity-conscious you want to disable this. -+ -+ This setting can be overridden at runtime via the -+ kernel.unprivileged_userns_clone sysctl. -+ -+ If unsure, say Y. -+ - config PID_NS - bool "PID Namespaces" - default y -@@ -1496,6 +1602,7 @@ config CHECKPOINT_RESTORE - - config SCHED_AUTOGROUP - bool "Automatic process group scheduling" -+ depends on !SCHED_ALT - select CGROUPS - select CGROUP_SCHED - select FAIR_GROUP_SCHED -@@ -1666,6 +1773,12 @@ config CC_OPTIMIZE_FOR_PERFORMANCE - with the "-O2" compiler flag for best performance and most - helpful compile-time warnings. - -+config CC_OPTIMIZE_FOR_PERFORMANCE_O3 -+ bool "Optimize more for performance (-O3)" -+ help -+ Choosing this option will pass "-O3" to your compiler to optimize -+ the kernel yet more for performance. -+ - config CC_OPTIMIZE_FOR_SIZE - bool "Optimize for size (-Os)" - help -diff --git a/init/Makefile b/init/Makefile -index d6f75d8..b3d6a2b 100644 ---- a/init/Makefile -+++ b/init/Makefile -@@ -34,7 +34,7 @@ build-timestamp = $(or $(KBUILD_BUILD_TIMESTAMP), $(build-timestamp-auto)) - - # Maximum length of UTS_VERSION is 64 chars - filechk_uts_version = \ -- utsver=$$(echo '$(pound)'"$(build-version)" $(smp-flag-y) $(preempt-flag-y) "$(build-timestamp)" | cut -b -64); \ -+ utsver=$$(echo '$(pound)'"$(build-version)" ZEN $(smp-flag-y) $(preempt-flag-y) "$(build-timestamp)" | cut -b -64); \ - echo '$(pound)'define UTS_VERSION \""$${utsver}"\" - - # -diff --git a/init/init_task.c b/init/init_task.c -index adb207c..b136c5d 100644 ---- a/init/init_task.c -+++ b/init/init_task.c -@@ -111,9 +111,16 @@ struct task_struct init_task __aligned(L1_CACHE_BYTES) = { - .stack = init_stack, - .usage = REFCOUNT_INIT(2), - .flags = PF_KTHREAD, -+#ifdef CONFIG_SCHED_ALT -+ .on_cpu = 1, -+ .prio = DEFAULT_PRIO, -+ .static_prio = DEFAULT_PRIO, -+ .normal_prio = DEFAULT_PRIO, -+#else - .prio = MAX_PRIO - 20, - .static_prio = MAX_PRIO - 20, - .normal_prio = MAX_PRIO - 20, -+#endif - .policy = SCHED_NORMAL, - .cpus_ptr = &init_task.cpus_mask, - .user_cpus_ptr = NULL, -@@ -126,6 +133,16 @@ struct task_struct init_task __aligned(L1_CACHE_BYTES) = { - .restart_block = { - .fn = do_no_restart_syscall, - }, -+#ifdef CONFIG_SCHED_ALT -+ .sq_node = LIST_HEAD_INIT(init_task.sq_node), -+#ifdef CONFIG_SCHED_BMQ -+ .boost_prio = 0, -+#endif -+#ifdef CONFIG_SCHED_PDS -+ .deadline = 0, -+#endif -+ .time_slice = HZ, -+#else - .se = { - .group_node = LIST_HEAD_INIT(init_task.se.group_node), - }, -@@ -133,10 +150,13 @@ struct task_struct init_task __aligned(L1_CACHE_BYTES) = { - .run_list = LIST_HEAD_INIT(init_task.rt.run_list), - .time_slice = RR_TIMESLICE, - }, -+#endif - .tasks = LIST_HEAD_INIT(init_task.tasks), -+#ifndef CONFIG_SCHED_ALT - #ifdef CONFIG_SMP - .pushable_tasks = PLIST_NODE_INIT(init_task.pushable_tasks, MAX_PRIO), - #endif -+#endif - #ifdef CONFIG_CGROUP_SCHED - .sched_task_group = &root_task_group, - #endif -diff --git a/kernel/Kconfig.preempt b/kernel/Kconfig.preempt -index f294dad..1707b33 100644 ---- a/kernel/Kconfig.preempt -+++ b/kernel/Kconfig.preempt -@@ -91,7 +91,7 @@ endchoice - - config PREEMPT_RT - bool "Fully Preemptible Kernel (Real-Time)" -- depends on EXPERT && ARCH_SUPPORTS_RT && !COMPILE_TEST -+ depends on ARCH_SUPPORTS_RT && !COMPILE_TEST - select PREEMPTION - help - This option turns the kernel into a real-time kernel by replacing -@@ -154,7 +154,7 @@ config PREEMPT_DYNAMIC - - config SCHED_CORE - bool "Core Scheduling for SMT" -- depends on SCHED_SMT -+ depends on SCHED_SMT && !SCHED_ALT - help - This option permits Core Scheduling, a means of coordinated task - selection across SMT siblings. When enabled -- see -@@ -172,7 +172,7 @@ config SCHED_CORE - - config SCHED_CLASS_EXT - bool "Extensible Scheduling Class" -- depends on BPF_SYSCALL && BPF_JIT && DEBUG_INFO_BTF -+ depends on BPF_SYSCALL && BPF_JIT && DEBUG_INFO_BTF && !SCHED_ALT - select GENERIC_ALLOCATOR - select STACKTRACE if STACKTRACE_SUPPORT - help -diff --git a/kernel/bounds.c b/kernel/bounds.c -index 02b619e..06a0347 100644 ---- a/kernel/bounds.c -+++ b/kernel/bounds.c -@@ -25,7 +25,7 @@ int main(void) - DEFINE(SPINLOCK_SIZE, sizeof(spinlock_t)); - #ifdef CONFIG_LRU_GEN - DEFINE(LRU_GEN_WIDTH, order_base_2(MAX_NR_GENS + 1)); -- DEFINE(__LRU_REFS_WIDTH, MAX_NR_TIERS - 2); -+ DEFINE(__LRU_REFS_WIDTH, MAX_NR_TIERS - 3); - #else - DEFINE(LRU_GEN_WIDTH, 0); - DEFINE(__LRU_REFS_WIDTH, 0); -diff --git a/kernel/cgroup/cpuset.c b/kernel/cgroup/cpuset.c -index 86b5921..6f52bec 100644 ---- a/kernel/cgroup/cpuset.c -+++ b/kernel/cgroup/cpuset.c -@@ -827,7 +827,7 @@ static int validate_change(struct cpuset *cur, struct cpuset *trial) - return ret; - } - --#ifdef CONFIG_SMP -+#if defined(CONFIG_SMP) && !defined(CONFIG_SCHED_ALT) - - /* - * generate_sched_domains() -@@ -1074,7 +1074,7 @@ void rebuild_sched_domains_locked(void) - /* Have scheduler rebuild the domains */ - partition_sched_domains(ndoms, doms, attr); - } --#else /* !CONFIG_SMP */ -+#else /* !CONFIG_SMP || CONFIG_SCHED_ALT */ - void rebuild_sched_domains_locked(void) - { - } -@@ -3127,6 +3127,7 @@ static int cpuset_can_attach_check(struct cpuset *cs, struct cpuset *oldcs, - return 0; - } - -+#ifndef CONFIG_SCHED_ALT - static int cpuset_reserve_dl_bw(void) - { - struct cpuset *cs; -@@ -3148,6 +3149,7 @@ static int cpuset_reserve_dl_bw(void) - } - return 0; - } -+#endif /* !CONFIG_SCHED_ALT */ - - /* - * Clear and optionally apply (@cancel is false) the attach related data in the -@@ -3160,6 +3162,7 @@ static void clear_attach_data(struct llist_head *head, bool cancel) - - llist_for_each_entry_safe(cs, next, lnode, attach_node) { - init_llist_node(&cs->attach_node); -+#ifndef CONFIG_SCHED_ALT - if (cs->nr_migrate_dl_tasks) { - if (!cancel) - atomic_add(cs->nr_migrate_dl_tasks, &cs->nr_deadline_tasks); -@@ -3169,6 +3172,7 @@ static void clear_attach_data(struct llist_head *head, bool cancel) - cs->sum_migrate_dl_bw = 0; - cs->dl_bw_cpu = -1; - } -+#endif /* !CONFIG_SCHED_ALT */ - } - } - -@@ -3245,6 +3249,7 @@ static int cpuset_can_attach(struct cgroup_taskset *tset) - goto out_unlock; - } - -+#ifndef CONFIG_SCHED_ALT - if (dl_task(task)) { - /* - * Count all migrating DL tasks for cpuset task accounting. -@@ -3256,6 +3261,7 @@ static int cpuset_can_attach(struct cgroup_taskset *tset) - if (dl_task_needs_bw_move(task, cs->effective_cpus)) - cs->sum_migrate_dl_bw += task->dl.dl_bw; - } -+#endif /* !CONFIG_SCHED_ALT */ - } - - /* -@@ -3274,7 +3280,11 @@ static int cpuset_can_attach(struct cgroup_taskset *tset) - goto out_unlock; - } - -+#ifndef CONFIG_SCHED_ALT - ret = cpuset_reserve_dl_bw(); -+#else /* !CONFIG_SCHED_ALT */ -+ ret = 0; -+#endif /* CONFIG_SCHED_ALT */ - - out_unlock: - if (ret) { -@@ -3294,7 +3304,6 @@ static void cpuset_cancel_attach(struct cgroup_taskset *tset) - dec_attach_in_progress_locked(); - clear_attach_data(&src_cs_head, true); - clear_attach_data(&dst_cs_head, true); -- mutex_unlock(&cpuset_mutex); - } - - /* -diff --git a/kernel/delayacct.c b/kernel/delayacct.c -index 479e860..61440f7 100644 ---- a/kernel/delayacct.c -+++ b/kernel/delayacct.c -@@ -170,7 +170,7 @@ int delayacct_add_tsk(struct taskstats *d, struct task_struct *tsk) - */ - t1 = tsk->sched_info.pcount; - t2 = tsk->sched_info.run_delay; -- t3 = tsk->se.sum_exec_runtime; -+ t3 = tsk_seruntime(tsk); - - d->cpu_count += t1; - -diff --git a/kernel/exit.c b/kernel/exit.c -index 25a68e1..263b422 100644 ---- a/kernel/exit.c -+++ b/kernel/exit.c -@@ -206,7 +206,7 @@ static void __exit_signal(struct release_task_post *post, struct task_struct *ts - sig->inblock += task_io_get_inblock(tsk); - sig->oublock += task_io_get_oublock(tsk); - task_io_accounting_add(&sig->ioac, &tsk->ioac); -- sig->sum_sched_runtime += tsk->se.sum_exec_runtime; -+ sig->sum_sched_runtime += tsk_seruntime(tsk); - sig->nr_threads--; - __unhash_process(post, tsk, group_dead); - write_sequnlock(&sig->stats_lock); -@@ -297,8 +297,8 @@ void release_task(struct task_struct *p) - proc_flush_pid(thread_pid); - put_pid(thread_pid); - exit_cred_namespaces(p); -- add_device_randomness(&p->se.sum_exec_runtime, -- sizeof(p->se.sum_exec_runtime)); -+ add_device_randomness((const void*) &tsk_seruntime(p), -+ sizeof(unsigned long long)); - free_pids(post.pids); - release_thread(p); - /* -diff --git a/kernel/fork.c b/kernel/fork.c -index 48d7ca0..9566b99 100644 ---- a/kernel/fork.c -+++ b/kernel/fork.c -@@ -127,6 +127,16 @@ - - #include - -+#ifdef CONFIG_USER_NS -+# ifdef CONFIG_USER_NS_UNPRIVILEGED -+static int unprivileged_userns_clone = 1; -+# else -+static int unprivileged_userns_clone = 0; -+# endif -+#else -+#define unprivileged_userns_clone 1 -+#endif -+ - /* - * Minimum number of threads to boot the kernel - */ -@@ -2130,6 +2140,11 @@ __latent_entropy struct task_struct *copy_process( - return ERR_PTR(-EPERM); - } - -+ if ((clone_flags & CLONE_NEWUSER) && !unprivileged_userns_clone) { -+ if (!capable(CAP_SYS_ADMIN)) -+ return ERR_PTR(-EPERM); -+ } -+ - /* - * Force any signals received before this point to be delivered - * before the fork happens. Collect up signals sent to multiple -@@ -3213,6 +3228,10 @@ static int check_unshare_flags(unsigned long unshare_flags) - if (!current_is_single_threaded()) - return -EINVAL; - } -+ if ((unshare_flags & CLONE_NEWUSER) && !unprivileged_userns_clone) { -+ if (!capable(CAP_SYS_ADMIN)) -+ return -EPERM; -+ } - - return 0; - } -@@ -3446,6 +3465,15 @@ static const struct ctl_table fork_sysctl_table[] = { - .mode = 0644, - .proc_handler = sysctl_max_threads, - }, -+#ifdef CONFIG_USER_NS -+ { -+ .procname = "unprivileged_userns_clone", -+ .data = &unprivileged_userns_clone, -+ .maxlen = sizeof(int), -+ .mode = 0644, -+ .proc_handler = proc_dointvec, -+ }, -+#endif - }; - - static int __init init_fork_sysctl(void) -diff --git a/kernel/irq/Kconfig b/kernel/irq/Kconfig -index 6923f37..d15390a 100644 ---- a/kernel/irq/Kconfig -+++ b/kernel/irq/Kconfig -@@ -106,6 +106,23 @@ config GENERIC_IRQ_STAT_SNAPSHOT - config IRQ_FORCED_THREADING - bool - -+config FORCE_IRQ_THREADING -+ bool "Make IRQ threading compulsory" -+ depends on IRQ_FORCED_THREADING -+ default n -+ help -+ -+ Make IRQ threading mandatory for any IRQ handlers that support it -+ instead of being optional and requiring the threadirqs kernel -+ parameter. Instead they can be optionally disabled with the -+ nothreadirqs kernel parameter. -+ -+ Enabling this may expose bugs in some drivers and prevent some -+ systems from booting. -+ -+ Enable if you are building for a desktop or low latency system, -+ otherwise say N. -+ - config SPARSE_IRQ - bool "Support sparse irq numbering" if MAY_HAVE_SPARSE_IRQ - help -diff --git a/kernel/irq/manage.c b/kernel/irq/manage.c -index ec3ecb0..f6df1e8 100644 ---- a/kernel/irq/manage.c -+++ b/kernel/irq/manage.c -@@ -26,7 +26,18 @@ - #include "internals.h" - - #if defined(CONFIG_IRQ_FORCED_THREADING) && !defined(CONFIG_PREEMPT_RT) -+#ifdef CONFIG_FORCE_IRQ_THREADING -+DEFINE_STATIC_KEY_TRUE(force_irqthreads_key); -+#else - DEFINE_STATIC_KEY_FALSE(force_irqthreads_key); -+#endif -+ -+static int __init setup_noforced_irqthreads(char *arg) -+{ -+ static_branch_disable(&force_irqthreads_key); -+ return 0; -+} -+early_param("nothreadirqs", setup_noforced_irqthreads); - - static int __init setup_forced_irqthreads(char *arg) - { -diff --git a/kernel/locking/rtmutex.c b/kernel/locking/rtmutex.c -index 4728631..15772f6 100644 ---- a/kernel/locking/rtmutex.c -+++ b/kernel/locking/rtmutex.c -@@ -372,7 +372,7 @@ waiter_update_prio(struct rt_mutex_waiter *waiter, struct task_struct *task) - lockdep_assert(RB_EMPTY_NODE(&waiter->tree.entry)); - - waiter->tree.prio = __waiter_prio(task); -- waiter->tree.deadline = task->dl.deadline; -+ waiter->tree.deadline = __tsk_deadline(task); - } - - /* -@@ -393,16 +393,20 @@ waiter_clone_prio(struct rt_mutex_waiter *waiter, struct task_struct *task) - * Only use with rt_waiter_node_{less,equal}() - */ - #define task_to_waiter_node(p) \ -- &(struct rt_waiter_node){ .prio = __waiter_prio(p), .deadline = (p)->dl.deadline } -+ &(struct rt_waiter_node){ .prio = __waiter_prio(p), .deadline = __tsk_deadline(p) } - #define task_to_waiter(p) \ - &(struct rt_mutex_waiter){ .tree = *task_to_waiter_node(p) } - - static __always_inline int rt_waiter_node_less(struct rt_waiter_node *left, - struct rt_waiter_node *right) - { -+#ifdef CONFIG_SCHED_PDS -+ return (left->deadline < right->deadline); -+#else - if (left->prio < right->prio) - return 1; - -+#ifndef CONFIG_SCHED_BMQ - /* - * If both waiters have dl_prio(), we check the deadlines of the - * associated tasks. -@@ -411,16 +415,22 @@ static __always_inline int rt_waiter_node_less(struct rt_waiter_node *left, - */ - if (dl_prio(left->prio)) - return dl_time_before(left->deadline, right->deadline); -+#endif - - return 0; -+#endif - } - - static __always_inline int rt_waiter_node_equal(struct rt_waiter_node *left, - struct rt_waiter_node *right) - { -+#ifdef CONFIG_SCHED_PDS -+ return (left->deadline == right->deadline); -+#else - if (left->prio != right->prio) - return 0; - -+#ifndef CONFIG_SCHED_BMQ - /* - * If both waiters have dl_prio(), we check the deadlines of the - * associated tasks. -@@ -429,8 +439,10 @@ static __always_inline int rt_waiter_node_equal(struct rt_waiter_node *left, - */ - if (dl_prio(left->prio)) - return left->deadline == right->deadline; -+#endif - - return 1; -+#endif - } - - static inline bool rt_mutex_steal(struct rt_mutex_waiter *waiter, -diff --git a/kernel/locking/ww_mutex.h b/kernel/locking/ww_mutex.h -index d62b49b..a487885 100644 ---- a/kernel/locking/ww_mutex.h -+++ b/kernel/locking/ww_mutex.h -@@ -282,6 +282,7 @@ __ww_ctx_less(struct ww_acquire_ctx *a, struct ww_acquire_ctx *b) - - /* equal static prio */ - -+#ifndef CONFIG_SCHED_ALT - if (dl_prio(a_prio)) { - if (dl_time_before(b->task->dl.deadline, - a->task->dl.deadline)) -@@ -291,6 +292,7 @@ __ww_ctx_less(struct ww_acquire_ctx *a, struct ww_acquire_ctx *b) - b->task->dl.deadline)) - return false; - } -+#endif - - /* equal prio */ - } -diff --git a/kernel/sched/Makefile b/kernel/sched/Makefile -index b1f1a36..0c1f4f0 100644 ---- a/kernel/sched/Makefile -+++ b/kernel/sched/Makefile -@@ -2,6 +2,7 @@ - - CONTEXT_ANALYSIS_core.o := y - CONTEXT_ANALYSIS_fair.o := y -+CONTEXT_ANALYSIS_alt_core.o := y - - # The compilers are complaining about unused variables inside an if(0) scope - # block. This is daft, shut them up. -@@ -36,7 +37,12 @@ endif - # These compilation units have roughly the same size and complexity - so their - # build parallelizes well and finishes roughly at once: - # -+ifdef CONFIG_SCHED_ALT -+obj-y += alt_core.o -+obj-$(CONFIG_SCHED_DEBUG) += alt_debug.o -+else - obj-y += core.o - obj-y += fair.o -+endif - obj-y += build_policy.o - obj-y += build_utility.o -diff --git a/kernel/sched/alt_core.c b/kernel/sched/alt_core.c -new file mode 100644 -index 0000000..97e4246 ---- /dev/null -+++ b/kernel/sched/alt_core.c -@@ -0,0 +1,8280 @@ -+/* -+ * kernel/sched/alt_core.c -+ * -+ * Core alternative kernel scheduler code and related syscalls -+ * -+ * Copyright (C) 1991-2002 Linus Torvalds -+ * -+ * 2009-08-13 Brainfuck deadline scheduling policy by Con Kolivas deletes -+ * a whole lot of those previous things. -+ * 2017-09-06 Priority and Deadline based Skip list multiple queue kernel -+ * scheduler by Alfred Chen. -+ * 2019-02-20 BMQ(BitMap Queue) kernel scheduler by Alfred Chen. -+ */ -+#define INSTANTIATE_EXPORTED_MIGRATE_DISABLE -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+ -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+ -+#ifdef CONFIG_PREEMPT_DYNAMIC -+# ifdef CONFIG_GENERIC_IRQ_ENTRY -+# include -+# endif -+#endif -+ -+#include -+ -+#include -+#include -+ -+#define CREATE_TRACE_POINTS -+#include -+#include -+#undef CREATE_TRACE_POINTS -+ -+#include "sched.h" -+#include "smp.h" -+ -+#include "pelt.h" -+ -+#include "../../io_uring/io-wq.h" -+#include "../smpboot.h" -+ -+/* Use CONFIG_PARAVIRT as this will avoid more #ifdef in arch code. */ -+#ifdef CONFIG_PARAVIRT -+struct static_key paravirt_steal_rq_enabled; -+#endif -+ -+EXPORT_TRACEPOINT_SYMBOL_GPL(ipi_send_cpu); -+EXPORT_TRACEPOINT_SYMBOL_GPL(ipi_send_cpumask); -+ -+/* -+ * Export tracepoints that act as a bare tracehook (ie: have no trace event -+ * associated with them) to allow external modules to probe them. -+ */ -+EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_irq_tp); -+EXPORT_TRACEPOINT_SYMBOL_GPL(sched_entry_tp); -+EXPORT_TRACEPOINT_SYMBOL_GPL(sched_exit_tp); -+EXPORT_TRACEPOINT_SYMBOL_GPL(sched_set_need_resched_tp); -+ -+#define sched_feat(x) (0) -+/* -+ * Print a warning if need_resched is set for the given duration (if -+ * LATENCY_WARN is enabled). -+ * -+ * If sysctl_resched_latency_warn_once is set, only one warning will be shown -+ * per boot. -+ */ -+__read_mostly int sysctl_resched_latency_warn_ms = 100; -+__read_mostly int sysctl_resched_latency_warn_once = 1; -+ -+#define ALT_SCHED_VERSION "v7.3-r0" -+ -+#define STOP_PRIO (MAX_RT_PRIO - 1) -+ -+/* -+ * Time slice -+ * (default: 4 msec, units: nanoseconds) -+ */ -+#ifdef CONFIG_ZEN_INTERACTIVE -+unsigned int sysctl_sched_base_slice __read_mostly = (2 << 20); -+#else -+unsigned int sysctl_sched_base_slice __read_mostly = (4 << 20); -+#endif -+ -+#include "alt_core.h" -+#include "alt_topology.h" -+ -+/** -+ * sched_yield_type - Type of sched_yield() will be performed. -+ * 0: No yield. -+ * 1: Requeue task. (default) -+ */ -+int sched_yield_type __read_mostly = 1; -+ -+DEFINE_STATIC_KEY_MAYBE_RO(CONFIG_SCHED_PDS_SLEEP_CREDIT, sched_pds_sleep_credit); -+ -+static int __init setup_sched_pds_sleep_credit(char *str) -+{ -+ bool on; -+ -+ if (kstrtobool(str, &on)) -+ pr_warn("Unable to parse sched_pds_sleep_credit=\n"); -+ else if (on) -+ static_branch_enable(&sched_pds_sleep_credit); -+ else -+ static_branch_disable(&sched_pds_sleep_credit); -+ -+ return 1; -+} -+__setup("sched_pds_sleep_credit=", setup_sched_pds_sleep_credit); -+ -+cpumask_t sched_rq_pending_mask ____cacheline_aligned_in_smp; -+ -+DEFINE_PER_CPU_ALIGNED(cpumask_t [NR_CPU_AFFINITY_LEVELS], sched_cpu_topo_masks); -+DEFINE_PER_CPU_ALIGNED(cpumask_t *, sched_cpu_llc_mask); -+DEFINE_PER_CPU_ALIGNED(cpumask_t *, sched_cpu_topo_end_mask); -+ -+DEFINE_STATIC_KEY_FALSE(sched_smt_present); -+EXPORT_SYMBOL_GPL(sched_smt_present); -+ -+DEFINE_PER_CPU_ALIGNED(raw_spinlock_t, sched_smt_idle_lock); -+ -+cpumask_t sched_smt_mask ____cacheline_aligned_in_smp; -+ -+/* -+ * Keep a unique ID per domain (we use the first CPUs number in the cpumask of -+ * the domain), this allows us to quickly tell if two cpus are in the same cache -+ * domain, see cpus_share_cache(). -+ */ -+static DEFINE_PER_CPU_READ_MOSTLY(int, sd_llc_id); -+static DEFINE_PER_CPU_READ_MOSTLY(int, sd_llc_size); -+static DEFINE_PER_CPU_READ_MOSTLY(bool, sched_cpu_topology_valid); -+static cpumask_t sched_llc_id_merge_mask; -+ -+DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues); -+ -+#ifndef prepare_arch_switch -+# define prepare_arch_switch(next) do { } while (0) -+#endif -+#ifndef finish_arch_post_lock_switch -+# define finish_arch_post_lock_switch() do { } while (0) -+#endif -+ -+static struct { -+ cpumask_t pad; -+ cpumask_t mask[SCHED_QUEUE_BITS + 3]; -+} sched_preempt_masks ____cacheline_aligned_in_smp; -+ -+#define sched_preempt_mask sched_preempt_masks.mask -+ -+static_assert(offsetof(typeof(sched_preempt_masks), -+ mask[SCHED_QUEUE_BITS - 1]) % SMP_CACHE_BYTES == 0); -+ -+cpumask_t *const sched_idle_mask = &sched_preempt_mask[SCHED_QUEUE_BITS - 1]; -+cpumask_t *const sched_sg_idle_mask = &sched_preempt_mask[SCHED_QUEUE_BITS]; -+cpumask_t *const sched_pcore_idle_mask = &sched_preempt_mask[SCHED_QUEUE_BITS + 1]; -+cpumask_t *const sched_ecore_idle_mask = &sched_preempt_mask[SCHED_QUEUE_BITS + 2]; -+ -+/* task function */ -+static inline const struct cpumask *task_user_cpus(struct task_struct *p) -+{ -+ if (!p->user_cpus_ptr) -+ return cpu_possible_mask; /* &init_task.cpus_mask */ -+ return p->user_cpus_ptr; -+} -+ -+/* sched_queue related functions */ -+static inline void sched_queue_init(struct sched_queue *q) -+{ -+ int i; -+ -+ bitmap_zero(q->bitmap, SCHED_QUEUE_BITS); -+ for(i = 0; i < SCHED_LEVELS; i++) -+ INIT_LIST_HEAD(&q->heads[i]); -+} -+ -+/* -+ * Init idle task and put into queue structure of rq -+ * IMPORTANT: may be called multiple times for a single cpu -+ */ -+static inline void sched_queue_init_idle(struct sched_queue *q, -+ struct task_struct *idle) -+{ -+ INIT_LIST_HEAD(&q->heads[IDLE_TASK_SCHED_PRIO]); -+ list_add_tail(&idle->sq_node, &q->heads[IDLE_TASK_SCHED_PRIO]); -+ idle->on_rq = TASK_ON_RQ_QUEUED; -+} -+ -+static atomic_t sched_prio_record = ATOMIC_INIT(0); -+ -+/* water mark related functions */ -+static inline void update_sched_preempt_mask(struct rq *rq) -+{ -+ int prio = find_first_bit(rq->queue.bitmap, SCHED_QUEUE_BITS); -+ int last_prio = rq->prio; -+ -+ if (prio == last_prio) -+ return; -+ -+ sched_rq_set_prio(rq, prio); -+ -+ int cpu = cpu_of(rq); -+ bool set = prio > last_prio; -+ int low = set ? last_prio : prio; -+ int high = set ? prio : last_prio; -+ -+ if (IDLE_TASK_SCHED_PRIO == high) { -+ high -= 1; -+ if (set) -+ sched_set_idle_mask(cpu); -+ else -+ sched_clear_idle_mask(cpu); -+ } -+ int pr = atomic_read(&sched_prio_record); -+ if (low <= pr && pr < high) { -+ if (set) -+ cpumask_set_cpu(cpu, sched_preempt_mask + pr); -+ else -+ cpumask_clear_cpu(cpu, sched_preempt_mask + pr); -+ } -+} -+ -+/* need a wrapper since we may need to trace from modules */ -+EXPORT_TRACEPOINT_SYMBOL(sched_set_state_tp); -+ -+/* -+ * Call via the helper macro trace_set_current_state. -+ * Calls to this function MUST be guarded by a -+ * tracepoint_enabled(sched_set_state_tp) -+ */ -+void __trace_set_current_state(int state_value) -+{ -+ trace_call__sched_set_state_tp(current, state_value); -+} -+EXPORT_SYMBOL(__trace_set_current_state); -+ -+/* -+ * Serialization rules: -+ * -+ * Lock order: -+ * -+ * p->pi_lock -+ * rq->lock -+ * hrtimer_cpu_base->lock (hrtimer_start() for bandwidth controls) -+ * -+ * rq1->lock -+ * rq2->lock where: rq1 < rq2 -+ * -+ * Regular state: -+ * -+ * Normal scheduling state is serialized by rq->lock. __schedule() takes the -+ * local CPU's rq->lock, it optionally removes the task from the runqueue and -+ * always looks at the local rq data structures to find the most eligible task -+ * to run next. -+ * -+ * Task enqueue is also under rq->lock, possibly taken from another CPU. -+ * Wakeups from another LLC domain might use an IPI to transfer the enqueue to -+ * the local CPU to avoid bouncing the runqueue state around [ see -+ * ttwu_queue_wakelist() ] -+ * -+ * Task wakeup, specifically wakeups that involve migration, are horribly -+ * complicated to avoid having to take two rq->locks. -+ * -+ * Special state: -+ * -+ * System-calls and anything external will use task_rq_lock() which acquires -+ * both p->pi_lock and rq->lock. As a consequence the state they change is -+ * stable while holding either lock: -+ * -+ * - sched_setaffinity()/ -+ * set_cpus_allowed_ptr(): p->cpus_ptr, p->nr_cpus_allowed -+ * - set_user_nice(): p->se.load, p->*prio -+ * - __sched_setscheduler(): p->sched_class, p->policy, p->*prio, -+ * p->se.load, p->rt_priority, -+ * p->dl.dl_{runtime, deadline, period, flags, bw, density} -+ * - sched_setnuma(): p->numa_preferred_nid -+ * - sched_move_task(): p->sched_task_group -+ * - uclamp_update_active() p->uclamp* -+ * -+ * p->state <- TASK_*: -+ * -+ * is changed locklessly using set_current_state(), __set_current_state() or -+ * set_special_state(), see their respective comments, or by -+ * try_to_wake_up(). This latter uses p->pi_lock to serialize against -+ * concurrent self. -+ * -+ * p->on_rq <- { 0, 1 = TASK_ON_RQ_QUEUED, 2 = TASK_ON_RQ_MIGRATING }: -+ * -+ * is set by activate_task() and cleared by deactivate_task()/block_task(), -+ * under rq->lock. Non-zero indicates the task is runnable, the special -+ * ON_RQ_MIGRATING state is used for migration without holding both -+ * rq->locks. It indicates task_cpu() is not stable, see task_rq_lock(). -+ * -+ * Additionally it is possible to be ->on_rq but still be considered not -+ * runnable when p->se.sched_delayed is true. These tasks are on the runqueue -+ * but will be dequeued as soon as they get picked again. See the -+ * task_is_runnable() helper. -+ * -+ * p->on_cpu <- { 0, 1 }: -+ * -+ * is set by prepare_task() and cleared by finish_task() such that it will be -+ * set before p is scheduled-in and cleared after p is scheduled-out, both -+ * under rq->lock. Non-zero indicates the task is running on its CPU. -+ * -+ * [ The astute reader will observe that it is possible for two tasks on one -+ * CPU to have ->on_cpu = 1 at the same time. ] -+ * -+ * p->is_blocked <- { 0, 1 }: -+ * -+ * is set by try_to_block_task() and cleared by ttwu_do_wakeup() and tracks -+ * if the task is blocked. Traditionally this would mirror p->on_rq, however -+ * due things like DELAY_DEQUEUE and PROXY_EXEC, this can diverge. -+ * -+ * task_cpu(p): is changed by set_task_cpu(), the rules are: -+ * -+ * - Don't call set_task_cpu() on a blocked task: -+ * -+ * We don't care what CPU we're not running on, this simplifies hotplug, -+ * the CPU assignment of blocked tasks isn't required to be valid. -+ * -+ * - for try_to_wake_up(), called under p->pi_lock: -+ * -+ * This allows try_to_wake_up() to only take one rq->lock, see its comment. -+ * -+ * - for migration called under rq->lock: -+ * [ see task_on_rq_migrating() in task_rq_lock() ] -+ * -+ * o move_queued_task() -+ * o detach_task() -+ * -+ * - for migration called under double_rq_lock(): -+ * -+ * o __migrate_swap_task() -+ * o push_rt_task() / pull_rt_task() -+ * o push_dl_task() / pull_dl_task() -+ * o dl_task_offline_migration() -+ * -+ */ -+ -+/* -+ * __task_rq_lock - lock the rq @p resides on. -+ */ -+struct rq *___task_rq_lock(struct task_struct *p, struct rq_flags *rf) -+{ -+ struct rq *rq; -+ -+ lockdep_assert_held(&p->pi_lock); -+ -+ for (;;) { -+ rq = task_rq(p); -+ raw_spin_rq_lock(rq); -+ if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) { -+ rq_pin_lock(rq, rf); -+ return rq; -+ } -+ raw_spin_rq_unlock(rq); -+ -+ while (unlikely(task_on_rq_migrating(p))) -+ cpu_relax(); -+ } -+} -+ -+/* -+ * task_rq_lock - lock p->pi_lock and lock the rq @p resides on. -+ */ -+struct rq *_task_rq_lock(struct task_struct *p, struct rq_flags *rf) -+{ -+ struct rq *rq; -+ -+ for (;;) { -+ raw_spin_lock_irqsave(&p->pi_lock, rf->flags); -+ rq = task_rq(p); -+ raw_spin_rq_lock(rq); -+ /* -+ * move_queued_task() task_rq_lock() -+ * -+ * ACQUIRE (rq->lock) -+ * [S] ->on_rq = MIGRATING [L] rq = task_rq() -+ * WMB (__set_task_cpu()) ACQUIRE (rq->lock); -+ * [S] ->cpu = new_cpu [L] task_rq() -+ * [L] ->on_rq -+ * RELEASE (rq->lock) -+ * -+ * If we observe the old CPU in task_rq_lock(), the acquire of -+ * the old rq->lock will fully serialize against the stores. -+ * -+ * If we observe the new CPU in task_rq_lock(), the address -+ * dependency headed by '[L] rq = task_rq()' and the acquire -+ * will pair with the WMB to ensure we then also see migrating. -+ */ -+ if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) { -+ rq_pin_lock(rq, rf); -+ return rq; -+ } -+ raw_spin_rq_unlock(rq); -+ raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags); -+ -+ while (unlikely(task_on_rq_migrating(p))) -+ cpu_relax(); -+ } -+} -+ -+void raw_spin_rq_lock_nested(struct rq *rq, int subclass) -+{ -+ /* Matches synchronize_rcu() in __sched_core_enable() */ -+ preempt_disable(); -+ raw_spin_lock_nested(rq_lockp(rq), subclass); -+ /* preempt_count *MUST* be > 1 */ -+ preempt_enable_no_resched(); -+} -+ -+bool raw_spin_rq_trylock(struct rq *rq) -+{ -+ return raw_spin_trylock(rq_lockp(rq)); -+} -+ -+/* -+ * RQ-clock updating methods: -+ */ -+ -+static void update_rq_clock_task(struct rq *rq, s64 delta) -+{ -+/* -+ * In theory, the compile should just see 0 here, and optimize out the call -+ * to sched_rt_avg_update. But I don't trust it... -+ */ -+ s64 __maybe_unused steal = 0, irq_delta = 0; -+ -+#ifdef CONFIG_IRQ_TIME_ACCOUNTING -+ if (irqtime_enabled()) { -+ irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time; -+ -+ /* -+ * Since irq_time is only updated on {soft,}irq_exit, we might run into -+ * this case when a previous update_rq_clock() happened inside a -+ * {soft,}IRQ region. -+ * -+ * When this happens, we stop ->clock_task and only update the -+ * prev_irq_time stamp to account for the part that fit, so that a next -+ * update will consume the rest. This ensures ->clock_task is -+ * monotonic. -+ * -+ * It does however cause some slight miss-attribution of {soft,}IRQ -+ * time, a more accurate solution would be to update the irq_time using -+ * the current rq->clock timestamp, except that would require using -+ * atomic ops. -+ */ -+ if (irq_delta > delta) -+ irq_delta = delta; -+ -+ rq->prev_irq_time += irq_delta; -+ delta -= irq_delta; -+ delayacct_irq(rq->curr, irq_delta); -+ } -+#endif -+#ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING -+ if (static_key_false((¶virt_steal_rq_enabled))) { -+ u64 prev_steal; -+ -+ steal = prev_steal = paravirt_steal_clock(cpu_of(rq)); -+ steal -= rq->prev_steal_time_rq; -+ -+ if (unlikely(steal > delta)) -+ steal = delta; -+ -+ rq->prev_steal_time_rq = prev_steal; -+ delta -= steal; -+ } -+#endif -+ -+ rq->clock_task += delta; -+ -+#ifdef CONFIG_HAVE_SCHED_AVG_IRQ -+ if ((irq_delta + steal)) -+ update_irq_load_avg(rq, irq_delta + steal); -+#endif -+} -+ -+__always_inline void update_rq_clock(struct rq *rq) -+{ -+ s64 delta; -+ -+ lockdep_assert_rq_held(rq); -+ -+ delta = sched_clock_cpu(cpu_of(rq)) - rq->clock; -+ if (unlikely(delta <= 0)) -+ return; -+ rq->clock += delta; -+ sched_update_rq_clock(rq); -+ update_rq_clock_task(rq, delta); -+} -+ -+/* -+ * RQ Load update routine -+ */ -+#define RQ_LOAD_HISTORY_BITS (sizeof(s32) * 8ULL) -+#define RQ_UTIL_SHIFT (8) -+#define RQ_LOAD_HISTORY_TO_UTIL(l) (((l) >> (RQ_LOAD_HISTORY_BITS - 1 - RQ_UTIL_SHIFT)) & 0xff) -+ -+#define LOAD_BLOCK(t) ((t) >> 17) -+#define LOAD_HALF_BLOCK(t) ((t) >> 16) -+#define BLOCK_MASK(t) ((t) & ((0x01 << 18) - 1)) -+#define LOAD_BLOCK_BIT(b) (1UL << (RQ_LOAD_HISTORY_BITS - 1 - (b))) -+#define CURRENT_LOAD_BIT LOAD_BLOCK_BIT(0) -+ -+static inline void rq_load_update(struct rq *rq) -+{ -+ u64 time = rq->clock; -+ u64 delta = min(LOAD_BLOCK(time) - LOAD_BLOCK(rq->load_stamp), RQ_LOAD_HISTORY_BITS - 1); -+ u64 prev = !!(rq->load_history & CURRENT_LOAD_BIT); -+ u64 curr = !!rq->nr_running; -+ -+ if (delta) { -+ rq->load_history = rq->load_history >> delta; -+ -+ if (delta < RQ_UTIL_SHIFT) { -+ rq->load_block += (~BLOCK_MASK(rq->load_stamp)) * prev; -+ if (!!LOAD_HALF_BLOCK(rq->load_block) ^ curr) -+ rq->load_history ^= LOAD_BLOCK_BIT(delta); -+ } -+ -+ rq->load_block = BLOCK_MASK(time) * prev; -+ } else { -+ rq->load_block += (time - rq->load_stamp) * prev; -+ } -+ if (prev ^ curr) -+ rq->load_history ^= CURRENT_LOAD_BIT; -+ rq->load_stamp = time; -+} -+ -+unsigned long rq_load_util(struct rq *rq, unsigned long max) -+{ -+ return RQ_LOAD_HISTORY_TO_UTIL(rq->load_history) * (max >> RQ_UTIL_SHIFT); -+} -+ -+unsigned long sched_cpu_util(int cpu) -+{ -+ return rq_load_util(cpu_rq(cpu), arch_scale_cpu_capacity(cpu)); -+} -+ -+#ifdef CONFIG_CPU_FREQ -+/** -+ * cpufreq_update_util - Take a note about CPU utilization changes. -+ * @rq: Runqueue to carry out the update for. -+ * @flags: Update reason flags. -+ * -+ * This function is called by the scheduler on the CPU whose utilization is -+ * being updated. -+ * -+ * It can only be called from RCU-sched read-side critical sections. -+ * -+ * The way cpufreq is currently arranged requires it to evaluate the CPU -+ * performance state (frequency/voltage) on a regular basis to prevent it from -+ * being stuck in a completely inadequate performance level for too long. -+ * That is not guaranteed to happen if the updates are only triggered from CFS -+ * and DL, though, because they may not be coming in if only RT tasks are -+ * active all the time (or there are RT tasks only). -+ * -+ * As a workaround for that issue, this function is called periodically by the -+ * RT sched class to trigger extra cpufreq updates to prevent it from stalling, -+ * but that really is a band-aid. Going forward it should be replaced with -+ * solutions targeted more specifically at RT tasks. -+ */ -+static inline void cpufreq_update_util(struct rq *rq, unsigned int flags) -+{ -+ struct update_util_data *data; -+ -+ rq_load_update(rq); -+ data = rcu_dereference_sched(*per_cpu_ptr(&cpufreq_update_util_data, cpu_of(rq))); -+ if (data) -+ data->func(data, rq_clock(rq), flags); -+} -+#else /* !CONFIG_CPU_FREQ: */ -+static inline void cpufreq_update_util(struct rq *rq, unsigned int flags) -+{ -+ rq_load_update(rq); -+} -+#endif /* !CONFIG_CPU_FREQ */ -+ -+#ifdef CONFIG_NO_HZ_FULL -+/* -+ * Tick may be needed by tasks in the runqueue depending on their policy and -+ * requirements. If tick is needed, lets send the target an IPI to kick it out -+ * of nohz mode if necessary. -+ */ -+static inline void sched_update_tick_dependency(struct rq *rq) -+{ -+ int cpu = cpu_of(rq); -+ -+ if (!tick_nohz_full_cpu(cpu)) -+ return; -+ -+ if (rq->nr_running < 2) -+ tick_nohz_dep_clear_cpu(cpu, TICK_DEP_BIT_SCHED); -+ else -+ tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED); -+} -+#else /* !CONFIG_NO_HZ_FULL: */ -+static inline void sched_update_tick_dependency(struct rq *rq) { } -+#endif /* !CONFIG_NO_HZ_FULL */ -+ -+static inline void add_nr_running(struct rq *rq, unsigned count) -+{ -+ unsigned prev_nr = rq->nr_running; -+ -+ rq->nr_running = prev_nr + count; -+ trace_sched_update_nr_running_tp(rq, count); -+ if (rq->nr_running > 1) { -+ if (prev_nr < 2) -+ cpumask_set_cpu(cpu_of(rq), &sched_rq_pending_mask); -+ rq->prio_balance_time = rq->clock; -+ } -+ -+ sched_update_tick_dependency(rq); -+} -+ -+static inline void sub_nr_running(struct rq *rq, unsigned count) -+{ -+ unsigned prev_nr = rq->nr_running; -+ -+ rq->nr_running = prev_nr - count; -+ trace_sched_update_nr_running_tp(rq, -count); -+ if (rq->nr_running < 2) { -+ if (prev_nr > 1) -+ cpumask_clear_cpu(cpu_of(rq), &sched_rq_pending_mask); -+ rq->prio_balance_time = 0; -+ } -+ -+ sched_update_tick_dependency(rq); -+} -+ -+bool sched_task_on_rq(struct task_struct *p) -+{ -+ return task_on_rq_queued(p); -+} -+ -+unsigned long get_wchan(struct task_struct *p) -+{ -+ unsigned long ip = 0; -+ unsigned int state; -+ -+ if (!p || p == current) -+ return 0; -+ -+ /* Only get wchan if task is blocked and we can keep it that way. */ -+ raw_spin_lock_irq(&p->pi_lock); -+ state = READ_ONCE(p->__state); -+ smp_rmb(); /* see try_to_wake_up() */ -+ if (state != TASK_RUNNING && state != TASK_WAKING && !p->on_rq) -+ ip = __get_wchan(p); -+ raw_spin_unlock_irq(&p->pi_lock); -+ -+ return ip; -+} -+ -+/* -+ * Add/Remove/Requeue task to/from the runqueue routines -+ * Context: rq->lock -+ */ -+#define __SCHED_DEQUEUE_TASK(p, rq, func) \ -+ sched_info_dequeue(rq, p); \ -+ \ -+ __list_del_entry(&p->sq_node); \ -+ if (p->sq_node.prev == p->sq_node.next) { \ -+ __clear_bit(sched_idx2prio(p->sq_node.next - &rq->queue.heads[0], rq), \ -+ rq->queue.bitmap); \ -+ func; \ -+ } -+ -+#define __SCHED_ENQUEUE_TASK(p, rq, func) \ -+ sched_info_enqueue(rq, p); \ -+ { \ -+ int idx, prio; \ -+ TASK_SCHED_PRIO_IDX(p, rq, idx, prio); \ -+ list_add_tail(&p->sq_node, &rq->queue.heads[idx]); \ -+ if (list_is_first(&p->sq_node, &rq->queue.heads[idx])) { \ -+ __set_bit(prio, rq->queue.bitmap); \ -+ func; \ -+ } \ -+ } -+ -+static inline void __dequeue_task(struct task_struct *p, struct rq *rq) -+{ -+#ifdef ALT_SCHED_DEBUG -+ lockdep_assert_rq_held(rq); -+ -+ /*printk(KERN_INFO "sched: dequeue(%d) %px %016llx\n", cpu_of(rq), p, p->deadline);*/ -+ WARN_ONCE(task_rq(p) != rq, "sched: dequeue task reside on cpu%d from cpu%d\n", -+ task_cpu(p), cpu_of(rq)); -+#endif -+ -+ __SCHED_DEQUEUE_TASK(p, rq, update_sched_preempt_mask(rq)); -+} -+ -+static inline void dequeue_task(struct task_struct *p, struct rq *rq, int flags) -+{ -+ __dequeue_task(p, rq); -+ psi_dequeue(p, flags); -+ sub_nr_running(rq, 1); -+} -+ -+static inline void __enqueue_task(struct task_struct *p, struct rq *rq) -+{ -+#ifdef ALT_SCHED_DEBUG -+ lockdep_assert_rq_held(rq); -+ -+ /*printk(KERN_INFO "sched: enqueue(%d) %px %d\n", cpu_of(rq), p, p->prio);*/ -+ WARN_ONCE(task_rq(p) != rq, "sched: enqueue task reside on cpu%d to cpu%d\n", -+ task_cpu(p), cpu_of(rq)); -+#endif -+ -+ __SCHED_ENQUEUE_TASK(p, rq, update_sched_preempt_mask(rq)); -+} -+ -+static inline void enqueue_task(struct task_struct *p, struct rq *rq, int flags) -+{ -+ __enqueue_task(p, rq); -+ psi_enqueue(p, flags); -+ add_nr_running(rq, 1); -+} -+ -+void requeue_task(struct task_struct *p, struct rq *rq, int flags) -+{ -+ struct list_head *node = &p->sq_node; -+ int deq_idx, idx, prio; -+ -+ if (!rt_task(p)) -+ flags &= ~ENQUEUE_HEAD; -+ -+ TASK_SCHED_PRIO_IDX(p, rq, idx, prio); -+#ifdef ALT_SCHED_DEBUG -+ lockdep_assert_rq_held(rq); -+ /*printk(KERN_INFO "sched: requeue(%d) %px %016llx\n", cpu_of(rq), p, p->deadline);*/ -+ WARN_ONCE(task_rq(p) != rq, "sched: cpu[%d] requeue task reside on cpu%d\n", -+ cpu_of(rq), task_cpu(p)); -+#endif -+ if (flags & ENQUEUE_HEAD) { -+ if (list_is_first(node, &rq->queue.heads[idx])) -+ return; -+ } else if (list_is_last(node, &rq->queue.heads[idx])) -+ return; -+ -+ __list_del_entry(node); -+ if (node->prev == node->next && (deq_idx = node->next - &rq->queue.heads[0]) != idx) -+ __clear_bit(sched_idx2prio(deq_idx, rq), rq->queue.bitmap); -+ -+ if (flags & ENQUEUE_HEAD) -+ list_add(node, &rq->queue.heads[idx]); -+ else -+ list_add_tail(node, &rq->queue.heads[idx]); -+ if (list_is_first(node, &rq->queue.heads[idx])) -+ __set_bit(prio, rq->queue.bitmap); -+ update_sched_preempt_mask(rq); -+} -+ -+/* -+ * try_cmpxchg based fetch_or() macro so it works for different integer types: -+ */ -+#define fetch_or(ptr, mask) \ -+ ({ \ -+ typeof(ptr) _ptr = (ptr); \ -+ typeof(mask) _mask = (mask); \ -+ typeof(*_ptr) _val = *_ptr; \ -+ \ -+ do { \ -+ } while (!try_cmpxchg(_ptr, &_val, _val | _mask)); \ -+ _val; \ -+}) -+ -+#ifdef TIF_POLLING_NRFLAG -+/* -+ * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG, -+ * this avoids any races wrt polling state changes and thereby avoids -+ * spurious IPIs. -+ */ -+static inline bool set_nr_and_not_polling(struct thread_info *ti, int tif) -+{ -+ return !(fetch_or(&ti->flags, 1 << tif) & _TIF_POLLING_NRFLAG); -+} -+ -+/* -+ * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set. -+ * -+ * If this returns true, then the idle task promises to call -+ * sched_ttwu_pending() and reschedule soon. -+ */ -+static bool set_nr_if_polling(struct task_struct *p) -+{ -+ struct thread_info *ti = task_thread_info(p); -+ typeof(ti->flags) val = READ_ONCE(ti->flags); -+ -+ do { -+ if (!(val & _TIF_POLLING_NRFLAG)) -+ return false; -+ if (val & _TIF_NEED_RESCHED) -+ return true; -+ } while (!try_cmpxchg(&ti->flags, &val, val | _TIF_NEED_RESCHED)); -+ -+ return true; -+} -+ -+#else /* !TIF_POLLING_NRFLAG: */ -+static inline bool set_nr_and_not_polling(struct thread_info *ti, int tif) -+{ -+ set_ti_thread_flag(ti, tif); -+ return true; -+} -+ -+static inline bool set_nr_if_polling(struct task_struct *p) -+{ -+ return false; -+} -+#endif /* !TIF_POLLING_NRFLAG */ -+ -+static bool __wake_q_add(struct wake_q_head *head, struct task_struct *task) -+{ -+ struct wake_q_node *node = &task->wake_q; -+ -+ /* -+ * Atomically grab the task, if ->wake_q is !nil already it means -+ * it's already queued (either by us or someone else) and will get the -+ * wakeup due to that. -+ * -+ * In order to ensure that a pending wakeup will observe our pending -+ * state, even in the failed case, an explicit smp_mb() must be used. -+ */ -+ smp_mb__before_atomic(); -+ if (unlikely(cmpxchg_relaxed(&node->next, NULL, WAKE_Q_TAIL))) -+ return false; -+ -+ /* -+ * The head is context local, there can be no concurrency. -+ */ -+ *head->lastp = node; -+ head->lastp = &node->next; -+ return true; -+} -+ -+/** -+ * wake_q_add() - queue a wakeup for 'later' waking. -+ * @head: the wake_q_head to add @task to -+ * @task: the task to queue for 'later' wakeup -+ * -+ * Queue a task for later wakeup, most likely by the wake_up_q() call in the -+ * same context, _HOWEVER_ this is not guaranteed, the wakeup can come -+ * instantly. -+ * -+ * This function must be used as-if it were wake_up_process(); IOW the task -+ * must be ready to be woken at this location. -+ */ -+void wake_q_add(struct wake_q_head *head, struct task_struct *task) -+{ -+ if (__wake_q_add(head, task)) -+ get_task_struct(task); -+} -+ -+/** -+ * wake_q_add_safe() - safely queue a wakeup for 'later' waking. -+ * @head: the wake_q_head to add @task to -+ * @task: the task to queue for 'later' wakeup -+ * -+ * Queue a task for later wakeup, most likely by the wake_up_q() call in the -+ * same context, _HOWEVER_ this is not guaranteed, the wakeup can come -+ * instantly. -+ * -+ * This function must be used as-if it were wake_up_process(); IOW the task -+ * must be ready to be woken at this location. -+ * -+ * This function is essentially a task-safe equivalent to wake_q_add(). Callers -+ * that already hold reference to @task can call the 'safe' version and trust -+ * wake_q to do the right thing depending whether or not the @task is already -+ * queued for wakeup. -+ */ -+void wake_q_add_safe(struct wake_q_head *head, struct task_struct *task) -+{ -+ if (!__wake_q_add(head, task)) -+ put_task_struct(task); -+} -+ -+void wake_up_q(struct wake_q_head *head) -+{ -+ struct wake_q_node *node = head->first; -+ -+ while (node != WAKE_Q_TAIL) { -+ struct task_struct *task; -+ -+ task = container_of(node, struct task_struct, wake_q); -+ node = node->next; -+ /* pairs with cmpxchg_relaxed() in __wake_q_add() */ -+ WRITE_ONCE(task->wake_q.next, NULL); -+ /* Task can safely be re-inserted now. */ -+ -+ /* -+ * wake_up_process() executes a full barrier, which pairs with -+ * the queueing in wake_q_add() so as not to miss wakeups. -+ */ -+ wake_up_process(task); -+ put_task_struct(task); -+ } -+} -+ -+/* -+ * resched_curr - mark rq's current task 'to be rescheduled now'. -+ * -+ * On UP this means the setting of the need_resched flag, on SMP it -+ * might also involve a cross-CPU call to trigger the scheduler on -+ * the target CPU. -+ */ -+static inline void __resched_curr(struct rq *rq, int tif) -+{ -+ struct task_struct *curr = rq->curr; -+ struct thread_info *cti = task_thread_info(curr); -+ int cpu; -+ -+ lockdep_assert_rq_held(rq); -+ -+ /* -+ * Always immediately preempt the idle task; no point in delaying doing -+ * actual work. -+ */ -+ if (is_idle_task(curr) && tif == TIF_NEED_RESCHED_LAZY) -+ tif = TIF_NEED_RESCHED; -+ -+ if (cti->flags & ((1 << tif) | _TIF_NEED_RESCHED)) -+ return; -+ -+ cpu = cpu_of(rq); -+ -+ trace_sched_set_need_resched_tp(curr, cpu, tif); -+ if (cpu == smp_processor_id()) { -+ set_ti_thread_flag(cti, tif); -+ if (tif == TIF_NEED_RESCHED) -+ set_preempt_need_resched(); -+ return; -+ } -+ -+ if (set_nr_and_not_polling(cti, tif)) { -+ if (tif == TIF_NEED_RESCHED) -+ smp_send_reschedule(cpu); -+ } else { -+ trace_sched_wake_idle_without_ipi(cpu); -+ } -+} -+ -+/* -+ * Calls to this function MUST be guarded by a -+ * tracepoint_enabled(sched_set_need_resched_tp) -+ */ -+void __trace_set_need_resched(struct task_struct *curr, int tif) -+{ -+ trace_call__sched_set_need_resched_tp(curr, smp_processor_id(), tif); -+} -+EXPORT_SYMBOL_GPL(__trace_set_need_resched); -+ -+static inline void resched_curr(struct rq *rq) -+{ -+ __resched_curr(rq, TIF_NEED_RESCHED); -+} -+ -+#ifdef CONFIG_PREEMPT_DYNAMIC -+static DEFINE_STATIC_KEY_FALSE(sk_dynamic_preempt_lazy); -+static __always_inline bool dynamic_preempt_lazy(void) -+{ -+ return static_branch_unlikely(&sk_dynamic_preempt_lazy); -+} -+#else /* !CONFIG_PREEMPT_DYNAMIC: */ -+static __always_inline bool dynamic_preempt_lazy(void) -+{ -+ return IS_ENABLED(CONFIG_PREEMPT_LAZY); -+} -+#endif /* !CONFIG_PREEMPT_DYNAMIC */ -+ -+static __always_inline int get_lazy_tif_bit(void) -+{ -+ if (dynamic_preempt_lazy()) -+ return TIF_NEED_RESCHED_LAZY; -+ -+ return TIF_NEED_RESCHED; -+} -+ -+static inline void resched_curr_lazy(struct rq *rq) -+{ -+ __resched_curr(rq, get_lazy_tif_bit()); -+} -+ -+void resched_cpu(int cpu) -+{ -+ struct rq *rq = cpu_rq(cpu); -+ unsigned long flags; -+ -+ raw_spin_rq_lock_irqsave(rq, flags); -+ if (cpu_online(cpu) || cpu == smp_processor_id()) -+ resched_curr(rq); -+ raw_spin_rq_unlock_irqrestore(rq, flags); -+} -+ -+#ifdef CONFIG_NO_HZ_COMMON -+/* -+ * This routine will record that the CPU is going idle with tick stopped. -+ * This info will be used in performing idle load balancing in the future. -+ */ -+void nohz_balance_enter_idle(int cpu) {} -+ -+/* -+ * In the semi idle case, use the nearest busy CPU for migrating timers -+ * from an idle CPU. This is good for power-savings. -+ * -+ * We don't do similar optimization for completely idle system, as -+ * selecting an idle CPU will add more delays to the timers than intended -+ * (as that CPU's timer base may not be up to date wrt jiffies etc). -+ */ -+int get_nohz_timer_target(void) -+{ -+ int i, cpu = smp_processor_id(), default_cpu = -1; -+ struct cpumask *topo_masks, *mask; -+ const struct cpumask *hk_mask; -+ -+ if (housekeeping_cpu(cpu, HK_TYPE_KERNEL_NOISE)) { -+ if (!idle_cpu(cpu)) -+ return cpu; -+ default_cpu = cpu; -+ } -+ -+ hk_mask = housekeeping_cpumask(HK_TYPE_KERNEL_NOISE); -+ -+ topo_masks = per_cpu(sched_cpu_topo_masks, cpu); -+ for (mask = topo_masks; -+ mask < per_cpu(sched_cpu_topo_end_mask, cpu); mask++) { -+ if (sched_cpu_topo_level_repeats(topo_masks, mask)) -+ continue; -+ -+ for_each_cpu_and(i, mask, hk_mask) -+ if (!idle_cpu(i)) -+ return i; -+ } -+ -+ if (default_cpu == -1) -+ default_cpu = housekeeping_any_cpu(HK_TYPE_KERNEL_NOISE); -+ cpu = default_cpu; -+ -+ return cpu; -+} -+ -+/* -+ * When add_timer_on() enqueues a timer into the timer wheel of an -+ * idle CPU then this timer might expire before the next timer event -+ * which is scheduled to wake up that CPU. In case of a completely -+ * idle system the next event might even be infinite time into the -+ * future. wake_up_idle_cpu() ensures that the CPU is woken up and -+ * leaves the inner idle loop so the newly added timer is taken into -+ * account when the CPU goes back to idle and evaluates the timer -+ * wheel for the next timer event. -+ */ -+static inline void wake_up_idle_cpu(int cpu) -+{ -+ struct rq *rq = cpu_rq(cpu); -+ -+ if (cpu == smp_processor_id()) -+ return; -+ -+ /* -+ * Set TIF_NEED_RESCHED and send an IPI if in the non-polling -+ * part of the idle loop. This forces an exit from the idle loop -+ * and a round trip to schedule(). Now this could be optimized -+ * because a simple new idle loop iteration is enough to -+ * re-evaluate the next tick. Provided some re-ordering of tick -+ * nohz functions that would need to follow TIF_NR_POLLING -+ * clearing: -+ * -+ * - On most architectures, a simple fetch_or on ti::flags with a -+ * "0" value would be enough to know if an IPI needs to be sent. -+ * -+ * - x86 needs to perform a last need_resched() check between -+ * monitor and mwait which doesn't take timers into account. -+ * There a dedicated TIF_TIMER flag would be required to -+ * fetch_or here and be checked along with TIF_NEED_RESCHED -+ * before mwait(). -+ * -+ * However, remote timer enqueue is not such a frequent event -+ * and testing of the above solutions didn't appear to report -+ * much benefits. -+ */ -+ if (set_nr_and_not_polling(task_thread_info(rq->idle), TIF_NEED_RESCHED)) -+ smp_send_reschedule(cpu); -+ else -+ trace_sched_wake_idle_without_ipi(cpu); -+} -+ -+static inline bool wake_up_full_nohz_cpu(int cpu) -+{ -+ /* -+ * We just need the target to call irq_exit() and re-evaluate -+ * the next tick. The nohz full kick at least implies that. -+ * If needed we can still optimize that later with an -+ * empty IRQ. -+ */ -+ if (cpu_is_offline(cpu)) -+ return true; /* Don't try to wake offline CPUs. */ -+ if (tick_nohz_full_cpu(cpu)) { -+ if (cpu != smp_processor_id() || -+ tick_nohz_tick_stopped()) -+ tick_nohz_full_kick_cpu(cpu); -+ return true; -+ } -+ -+ return false; -+} -+ -+void wake_up_nohz_cpu(int cpu) -+{ -+ if (!wake_up_full_nohz_cpu(cpu)) -+ wake_up_idle_cpu(cpu); -+} -+ -+static void nohz_csd_func(void *info) -+{ -+ struct rq *rq = info; -+ int cpu = cpu_of(rq); -+ unsigned int flags; -+ -+ /* -+ * Release the rq::nohz_csd. -+ */ -+ flags = atomic_fetch_andnot(NOHZ_KICK_MASK, nohz_flags(cpu)); -+ WARN_ON(!(flags & NOHZ_KICK_MASK)); -+ -+ rq->idle_balance = idle_cpu(cpu); -+ if (rq->idle_balance) { -+ rq->nohz_idle_balance = flags; -+ __raise_softirq_irqoff(SCHED_SOFTIRQ); -+ } -+} -+ -+#endif /* CONFIG_NO_HZ_COMMON */ -+ -+static __always_inline void wakeup_preempt(struct rq *rq) -+{ -+ if (sched_rq_first_task(rq) != rq->curr) -+ resched_curr(rq); -+} -+ -+static __always_inline -+int __task_state_match(struct task_struct *p, unsigned int state) -+{ -+ if (READ_ONCE(p->__state) & state) -+ return 1; -+ -+ if (READ_ONCE(p->saved_state) & state) -+ return -1; -+ -+ return 0; -+} -+ -+static __always_inline -+int task_state_match(struct task_struct *p, unsigned int state) -+{ -+ /* -+ * Serialize against current_save_and_set_rtlock_wait_state(), -+ * current_restore_rtlock_saved_state(), and __refrigerator(). -+ */ -+ guard(raw_spinlock_irq)(&p->pi_lock); -+ -+ return __task_state_match(p, state); -+} -+ -+/* -+ * wait_task_inactive - wait for a thread to unschedule. -+ * -+ * Wait for the thread to block in any of the states set in @match_state. -+ * If it changes, i.e. @p might have woken up, then return zero. When we -+ * succeed in waiting for @p to be off its CPU, we return a positive number -+ * (its total switch count). If a second call a short while later returns the -+ * same number, the caller can be sure that @p has remained unscheduled the -+ * whole time. -+ * -+ * The caller must ensure that the task *will* unschedule sometime soon, -+ * else this function might spin for a *long* time. This function can't -+ * be called with interrupts off, or it may introduce deadlock with -+ * smp_call_function() if an IPI is sent by the same process we are -+ * waiting to become inactive. -+ */ -+unsigned long wait_task_inactive(struct task_struct *p, unsigned int match_state) -+{ -+ int running, queued, match; -+ struct rq_flags rf; -+ unsigned long ncsw; -+ struct rq *rq; -+ -+ for (;;) { -+ rq = task_rq(p); -+ -+ /* -+ * If the task is actively running on another CPU -+ * still, just relax and busy-wait without holding -+ * any locks. -+ * -+ * NOTE! Since we don't hold any locks, it's not -+ * even sure that "rq" stays as the right runqueue! -+ * But we don't care, since this will return false -+ * if the runqueue has changed and p is actually now -+ * running somewhere else! -+ */ -+ while (task_on_cpu(rq, p)) { -+ if (!task_state_match(p, match_state)) -+ return 0; -+ cpu_relax(); -+ } -+ -+ /* -+ * Ok, time to look more closely! We need the rq -+ * lock now, to be *sure*. If we're wrong, we'll -+ * just go back and repeat. -+ */ -+ rq = task_rq_lock(p, &rf); -+ trace_sched_wait_task(p); -+ running = task_on_cpu(rq, p); -+ queued = task_on_rq_queued(p); -+ ncsw = 0; -+ if ((match = __task_state_match(p, match_state))) { -+ /* -+ * When matching on p->saved_state, consider this task -+ * still queued so it will wait. -+ */ -+ if (match < 0) -+ queued = 1; -+ ncsw = p->nvcsw | LONG_MIN; /* sets MSB */ -+ } -+ task_rq_unlock(rq, p, &rf); -+ -+ /* -+ * If it changed from the expected state, bail out now. -+ */ -+ if (unlikely(!ncsw)) -+ break; -+ -+ /* -+ * Was it really running after all now that we -+ * checked with the proper locks actually held? -+ * -+ * Oops. Go back and try again.. -+ */ -+ if (unlikely(running)) { -+ cpu_relax(); -+ continue; -+ } -+ -+ /* -+ * It's not enough that it's not actively running, -+ * it must be off the runqueue _entirely_, and not -+ * preempted! -+ * -+ * So if it was still runnable (but just not actively -+ * running right now), it's preempted, and we should -+ * yield - it could be a while. -+ */ -+ if (unlikely(queued)) { -+ ktime_t to = NSEC_PER_SEC / HZ; -+ -+ set_current_state(TASK_UNINTERRUPTIBLE); -+ schedule_hrtimeout(&to, HRTIMER_MODE_REL_HARD); -+ continue; -+ } -+ -+ /* -+ * Ahh, all good. It wasn't running, and it wasn't -+ * runnable, which means that it will never become -+ * running in the future either. We're all done! -+ */ -+ break; -+ } -+ -+ return ncsw; -+} -+ -+#ifdef CONFIG_SCHED_HRTICK -+/* -+ * Use HR-timers to deliver accurate preemption points. -+ */ -+ -+enum { -+ HRTICK_SCHED_NONE = 0, -+ HRTICK_SCHED_DEFER = BIT(1), -+ HRTICK_SCHED_START = BIT(2), -+ HRTICK_SCHED_REARM_HRTIMER = BIT(3) -+}; -+ -+static void __used hrtick_clear(struct rq *rq) -+{ -+ if (hrtimer_active(&rq->hrtick_timer)) -+ hrtimer_cancel(&rq->hrtick_timer); -+} -+ -+/* -+ * High-resolution timer tick. -+ * Runs from hardirq context with interrupts disabled. -+ */ -+static enum hrtimer_restart hrtick(struct hrtimer *timer) -+{ -+ struct rq *rq = container_of(timer, struct rq, hrtick_timer); -+ -+ WARN_ON_ONCE(cpu_of(rq) != smp_processor_id()); -+ -+ raw_spin_rq_lock(rq); -+ resched_curr(rq); -+ raw_spin_rq_unlock(rq); -+ -+ return HRTIMER_NORESTART; -+} -+ -+/* -+ * Use hrtick when: -+ * - enabled by features -+ * - hrtimer is actually high res -+ */ -+static inline bool hrtick_enabled(struct rq *rq) -+{ -+ return cpu_active(cpu_of(rq)) && hrtimer_highres_enabled(); -+} -+ -+static inline bool hrtick_needs_rearm(struct hrtimer *timer, ktime_t expires) -+{ -+ /* -+ * Queued is false when the timer is not started or currently -+ * running the callback. In both cases, restart. If queued check -+ * whether the expiry time actually changes substantially. -+ */ -+ return !hrtimer_is_queued(timer) || -+ abs(expires - hrtimer_get_expires(timer)) > 5000; -+} -+ -+static void hrtick_cond_restart(struct rq *rq) -+{ -+ struct hrtimer *timer = &rq->hrtick_timer; -+ ktime_t time = rq->hrtick_time; -+ -+ if (hrtick_needs_rearm(timer, time)) -+ hrtimer_start(timer, time, HRTIMER_MODE_ABS_PINNED_HARD); -+} -+ -+/* -+ * called from hardirq (IPI) context -+ */ -+static void __hrtick_start(void *arg) -+{ -+ struct rq *rq = arg; -+ -+ raw_spin_rq_lock(rq); -+ hrtick_cond_restart(rq); -+ raw_spin_rq_unlock(rq); -+} -+ -+/* -+ * Called to set the hrtick timer state. -+ * -+ * called with rq->lock held and IRQs disabled -+ */ -+static inline void hrtick_start(struct rq *rq, u64 delay) -+{ -+ s64 delta; -+ -+ /* -+ * Don't schedule slices shorter than 10000ns, that just -+ * doesn't make sense and can cause timer DoS. -+ */ -+ delta = max_t(s64, delay, 10000LL); -+ -+ /* -+ * If this is in the middle of schedule() only note the delay -+ * and let hrtick_schedule_exit() deal with it. -+ */ -+ if (rq->hrtick_sched) { -+ rq->hrtick_sched |= HRTICK_SCHED_START; -+ rq->hrtick_delay = delta; -+ return; -+ } -+ -+ rq->hrtick_time = ktime_add_ns(ktime_get(), delta); -+ if (!hrtick_needs_rearm(&rq->hrtick_timer, rq->hrtick_time)) -+ return; -+ -+ if (rq == this_rq()) -+ hrtimer_start(&rq->hrtick_timer, rq->hrtick_time, HRTIMER_MODE_ABS_PINNED_HARD); -+ else -+ smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd); -+} -+ -+static inline void hrtick_schedule_enter(struct rq *rq) -+{ -+ rq->hrtick_sched = HRTICK_SCHED_DEFER; -+ if (hrtimer_test_and_clear_rearm_deferred()) -+ rq->hrtick_sched |= HRTICK_SCHED_REARM_HRTIMER; -+} -+ -+static inline void hrtick_schedule_exit(struct rq *rq) -+{ -+ if (rq->hrtick_sched & HRTICK_SCHED_START) { -+ rq->hrtick_time = ktime_add_ns(ktime_get(), rq->hrtick_delay); -+ hrtick_cond_restart(rq); -+ } else { -+ /* -+ * No need for using hrtimer_is_active(). The timer is CPU local -+ * and interrupts are disabled, so the callback cannot be -+ * running and the queued state is valid. -+ */ -+ if (hrtimer_is_queued(&rq->hrtick_timer)) -+ hrtimer_cancel(&rq->hrtick_timer); -+ } -+ -+ if (rq->hrtick_sched & HRTICK_SCHED_REARM_HRTIMER) -+ __hrtimer_rearm_deferred(); -+ -+ rq->hrtick_sched = HRTICK_SCHED_NONE; -+} -+ -+static void hrtick_rq_init(struct rq *rq) -+{ -+ INIT_CSD(&rq->hrtick_csd, __hrtick_start, rq); -+ rq->hrtick_sched = HRTICK_SCHED_NONE; -+ hrtimer_setup(&rq->hrtick_timer, hrtick, CLOCK_MONOTONIC, -+ HRTIMER_MODE_REL_HARD | HRTIMER_MODE_LAZY_REARM); -+} -+#else /* !CONFIG_SCHED_HRTICK: */ -+static inline void hrtick_clear(struct rq *rq) { } -+static inline void hrtick_start(struct rq *rq, u64 delay) { } -+static inline void hrtick_rq_init(struct rq *rq) { } -+static inline void hrtick_schedule_enter(struct rq *rq) { } -+static inline void hrtick_schedule_exit(struct rq *rq) { } -+#endif /* !CONFIG_SCHED_HRTICK */ -+ -+/* -+ * activate_task - move a task to the runqueue. -+ * -+ * Context: rq->lock -+ */ -+static void activate_task(struct task_struct *p, struct rq *rq, int flags) -+{ -+ enqueue_task(p, rq, flags); -+ -+ WRITE_ONCE(p->on_rq, TASK_ON_RQ_QUEUED); -+ ASSERT_EXCLUSIVE_WRITER(p->on_rq); -+ -+ /* -+ * If in_iowait is set, the code below may not trigger any cpufreq -+ * utilization updates, so do it here explicitly with the IOWAIT flag -+ * passed. -+ */ -+ cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT * p->in_iowait); -+} -+ -+static void block_task(struct rq *rq, struct task_struct *p, unsigned long task_state) -+{ -+ p->sched_contributes_to_load = -+ (task_state & TASK_UNINTERRUPTIBLE) && -+ !(task_state & TASK_NOLOAD) && -+ !(task_state & TASK_FROZEN); -+ -+ /* -+ * __schedule() ttwu() -+ * prev_state = prev->state; if (p->on_rq && ...) -+ * if (prev_state) goto out; -+ * p->on_rq = 0; smp_acquire__after_ctrl_dep(); -+ * p->state = TASK_WAKING -+ * -+ * Where __schedule() and ttwu() have matching control dependencies. -+ * -+ * After this, schedule() must not care about p->state any more. -+ */ -+ dequeue_task(p, rq, DEQUEUE_SLEEP); -+ __block_task(rq, p); -+} -+ -+static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu) -+{ -+ /* -+ * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be -+ * successfully executed on another CPU. We must ensure that updates of -+ * per-task data have been completed by this moment. -+ */ -+ smp_wmb(); -+ -+ WRITE_ONCE(task_thread_info(p)->cpu, cpu); -+ rseq_sched_set_ids_changed(p); -+} -+ -+void set_task_cpu(struct task_struct *p, unsigned int new_cpu) -+{ -+ unsigned int state = READ_ONCE(p->__state); -+ -+ /* -+ * We should never call set_task_cpu() on a blocked task, -+ * ttwu() will sort out the placement. -+ */ -+ WARN_ON_ONCE(state != TASK_RUNNING && state != TASK_WAKING && !p->on_rq); -+ -+#ifdef CONFIG_LOCKDEP -+ /* -+ * The caller should hold either p->pi_lock or rq->lock, when changing -+ * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks. -+ * -+ * sched_move_task() holds both and thus holding either pins the cgroup, -+ * see task_group(). -+ * -+ * Furthermore, all task_rq users should acquire both locks, see -+ * task_rq_lock(). -+ */ -+ WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) || -+ lockdep_is_held(__rq_lockp(task_rq(p))))); -+#endif -+ /* -+ * Clearly, migrating tasks to offline CPUs is a fairly daft thing. -+ */ -+ WARN_ON_ONCE(!cpu_online(new_cpu)); -+ -+ WARN_ON_ONCE(is_migration_disabled(p)); -+ trace_sched_migrate_task(p, new_cpu); -+ -+ if (task_cpu(p) != new_cpu) -+ perf_event_task_migrate(p); -+ -+ __set_task_cpu(p, new_cpu); -+} -+ -+void ___migrate_enable(void) -+{ -+ struct task_struct *p = current; -+ __do_set_cpus_ptr(p, &p->cpus_mask); -+} -+EXPORT_SYMBOL_GPL(___migrate_enable); -+ -+void migrate_disable(void) -+{ -+ __migrate_disable(); -+} -+EXPORT_SYMBOL_GPL(migrate_disable); -+ -+void migrate_enable(void) -+{ -+ __migrate_enable(); -+} -+EXPORT_SYMBOL_GPL(migrate_enable); -+ -+static void __migrate_force_enable(struct task_struct *p, struct rq *rq) -+{ -+ if (likely(p->cpus_ptr != &p->cpus_mask)) -+ __do_set_cpus_ptr(p, &p->cpus_mask); -+ p->migration_disabled = 0; -+ /* When p is migrate_disabled, rq->lock should be held */ -+ rq->nr_pinned--; -+} -+ -+static inline bool rq_has_pinned_tasks(struct rq *rq) -+{ -+ return rq->nr_pinned; -+} -+ -+/* -+ * Per-CPU kthreads are allowed to run on !active && online CPUs, see -+ * __set_cpus_allowed_ptr() and select_fallback_rq(). -+ */ -+static inline bool is_cpu_allowed(struct task_struct *p, int cpu) -+{ -+ /* When not in the task's cpumask, no point in looking further. */ -+ if (!task_allowed_on_cpu(p, cpu)) -+ return false; -+ -+ /* migrate_disabled() must be allowed to finish. */ -+ if (is_migration_disabled(p)) -+ return cpu_online(cpu); -+ -+ /* Non kernel threads are not allowed during either online or offline. */ -+ if (!(p->flags & PF_KTHREAD)) -+ return cpu_active(cpu); -+ -+ /* KTHREAD_IS_PER_CPU is always allowed. */ -+ if (kthread_is_per_cpu(p)) -+ return cpu_online(cpu); -+ -+ /* Regular kernel threads don't get to stay during offline. */ -+ if (cpu_dying(cpu)) -+ return false; -+ -+ /* But are allowed during online. */ -+ return cpu_online(cpu); -+} -+ -+/* -+ * This is how migration works: -+ * -+ * 1) we invoke migration_cpu_stop() on the target CPU using -+ * stop_one_cpu(). -+ * 2) stopper starts to run (implicitly forcing the migrated thread -+ * off the CPU) -+ * 3) it checks whether the migrated task is still in the wrong runqueue. -+ * 4) if it's in the wrong runqueue then the migration thread removes -+ * it and puts it into the right queue. -+ * 5) stopper completes and stop_one_cpu() returns and the migration -+ * is done. -+ */ -+ -+/* -+ * move_queued_task - move a queued task to new rq. -+ * -+ * Returns (locked) new rq. Old rq's lock is released. -+ */ -+struct rq *move_queued_task(struct rq *rq, struct rq_flags *rf, -+ struct task_struct *p, int new_cpu) -+ __must_hold(__rq_lockp(rq)) -+{ -+ lockdep_assert_rq_held(rq); -+ -+ WRITE_ONCE(p->on_rq, TASK_ON_RQ_MIGRATING); -+ dequeue_task(p, rq, 0); -+ set_task_cpu(p, new_cpu); -+ rq_unlock(rq, rf); -+ -+ rq = cpu_rq(new_cpu); -+ -+ rq_lock(rq, rf); -+ WARN_ON_ONCE(task_cpu(p) != new_cpu); -+ -+ sched_task_sanity_check(p, rq); -+ enqueue_task(p, rq, ENQUEUE_MIGRATED); -+ WRITE_ONCE(p->on_rq, TASK_ON_RQ_QUEUED); -+ wakeup_preempt(rq); -+ -+ return rq; -+} -+ -+struct migration_arg { -+ struct task_struct *task; -+ int dest_cpu; -+}; -+ -+/* -+ * Move (not current) task off this CPU, onto the destination CPU. We're doing -+ * this because either it can't run here any more (set_cpus_allowed() -+ * away from this CPU, or CPU going down), or because we're -+ * attempting to rebalance this task on exec (sched_exec). -+ * -+ * So we race with normal scheduler movements, but that's OK, as long -+ * as the task is no longer on this CPU. -+ */ -+static struct rq *__migrate_task(struct rq *rq, struct rq_flags *rf, -+ struct task_struct *p, int dest_cpu) -+ __must_hold(__rq_lockp(rq)) -+{ -+ /* Affinity changed (again). */ -+ if (!is_cpu_allowed(p, dest_cpu)) -+ return rq; -+ -+ return move_queued_task(rq, rf, p, dest_cpu); -+} -+ -+/* -+ * migration_cpu_stop - this will be executed by a high-prio stopper thread -+ * and performs thread migration by bumping thread off CPU then -+ * 'pushing' onto another runqueue. -+ */ -+static int migration_cpu_stop(void *data) -+{ -+ struct migration_arg *arg = data; -+ struct task_struct *p = arg->task; -+ struct rq *rq = this_rq(); -+ struct rq_flags rf; -+ -+ /* -+ * The original target CPU might have gone down and we might -+ * be on another CPU but it doesn't matter. -+ */ -+ local_irq_save(rf.flags); -+ /* -+ * We need to explicitly wake pending tasks before running -+ * __migrate_task() such that we will not miss enforcing cpus_ptr -+ * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test. -+ */ -+ flush_smp_call_function_queue(); -+ -+ /* -+ * We may change the underlying rq, but the locks held will -+ * appropriately be "transferred" when switching. -+ */ -+ context_unsafe_alias(rq); -+ -+ raw_spin_lock(&p->pi_lock); -+ rq_lock(rq, &rf); -+ /* -+ * If task_rq(p) != rq, it cannot be migrated here, because we're -+ * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because -+ * we're holding p->pi_lock. -+ */ -+ if (task_rq(p) == rq && task_on_rq_queued(p)) { -+ update_rq_clock(rq); -+ rq = __migrate_task(rq, &rf, p, arg->dest_cpu); -+ } -+ rq_unlock(rq, &rf); -+ raw_spin_unlock_irqrestore(&p->pi_lock, rf.flags); -+ -+ return 0; -+} -+ -+static inline void mm_update_cpus_allowed(struct mm_struct *mm, const cpumask_t *affmask); -+ -+static inline void -+set_cpus_allowed_common(struct task_struct *p, struct affinity_context *ctx) -+{ -+ cpumask_copy(&p->cpus_mask, ctx->new_mask); -+ p->nr_cpus_allowed = cpumask_weight(ctx->new_mask); -+ mm_update_cpus_allowed(p->mm, ctx->new_mask); -+ -+ /* -+ * Swap in a new user_cpus_ptr if SCA_USER flag set -+ */ -+ if (ctx->flags & SCA_USER) -+ swap(p->user_cpus_ptr, ctx->user_mask); -+} -+ -+static void -+do_set_cpus_allowed(struct task_struct *p, struct affinity_context *ctx) -+{ -+ lockdep_assert_held(&p->pi_lock); -+ set_cpus_allowed_common(p, ctx); -+} -+ -+/* -+ * Used for kthread_bind() and select_fallback_rq(), in both cases the user -+ * affinity (if any) should be destroyed too. -+ */ -+void set_cpus_allowed_force(struct task_struct *p, const struct cpumask *new_mask) -+{ -+ struct affinity_context ac = { -+ .new_mask = new_mask, -+ .user_mask = NULL, -+ .flags = SCA_USER, /* clear the user requested mask */ -+ }; -+ union cpumask_rcuhead { -+ cpumask_t cpumask; -+ struct rcu_head rcu; -+ }; -+ -+ do_set_cpus_allowed(p, &ac); -+ -+ if (is_migration_disabled(p) && !cpumask_test_cpu(task_cpu(p), &p->cpus_mask)) -+ __migrate_force_enable(p, task_rq(p)); -+ -+ /* -+ * Because this is called with p->pi_lock held, it is not possible -+ * to use kfree() here (when PREEMPT_RT=y), therefore punt to using -+ * kfree_rcu(). -+ */ -+ kfree_rcu((union cpumask_rcuhead *)ac.user_mask, rcu); -+} -+ -+int dup_user_cpus_ptr(struct task_struct *dst, struct task_struct *src, -+ int node) -+{ -+ cpumask_t *user_mask; -+ unsigned long flags; -+ -+ /* -+ * Always clear dst->user_cpus_ptr first as their user_cpus_ptr's -+ * may differ by now due to racing. -+ */ -+ dst->user_cpus_ptr = NULL; -+ -+ /* -+ * This check is racy and losing the race is a valid situation. -+ * It is not worth the extra overhead of taking the pi_lock on -+ * every fork/clone. -+ */ -+ if (data_race(!src->user_cpus_ptr)) -+ return 0; -+ -+ user_mask = alloc_user_cpus_ptr(node); -+ if (!user_mask) -+ return -ENOMEM; -+ -+ /* -+ * Use pi_lock to protect content of user_cpus_ptr -+ * -+ * Though unlikely, user_cpus_ptr can be reset to NULL by a concurrent -+ * set_cpus_allowed_force(). -+ */ -+ raw_spin_lock_irqsave(&src->pi_lock, flags); -+ if (src->user_cpus_ptr) { -+ swap(dst->user_cpus_ptr, user_mask); -+ cpumask_copy(dst->user_cpus_ptr, src->user_cpus_ptr); -+ } -+ raw_spin_unlock_irqrestore(&src->pi_lock, flags); -+ -+ if (unlikely(user_mask)) -+ kfree(user_mask); -+ -+ return 0; -+} -+ -+static inline struct cpumask *clear_user_cpus_ptr(struct task_struct *p) -+{ -+ struct cpumask *user_mask = NULL; -+ -+ swap(p->user_cpus_ptr, user_mask); -+ -+ return user_mask; -+} -+ -+void release_user_cpus_ptr(struct task_struct *p) -+{ -+ kfree(clear_user_cpus_ptr(p)); -+} -+ -+/** -+ * task_curr - is this task currently executing on a CPU? -+ * @p: the task in question. -+ * -+ * Return: 1 if the task is currently executing. 0 otherwise. -+ */ -+inline int task_curr(const struct task_struct *p) -+{ -+ return cpu_curr(task_cpu(p)) == p; -+} -+ -+/*** -+ * kick_process - kick a running thread to enter/exit the kernel -+ * @p: the to-be-kicked thread -+ * -+ * Cause a process which is running on another CPU to enter -+ * kernel-mode, without any delay. (to get signals handled.) -+ * -+ * NOTE: this function doesn't have to take the runqueue lock, -+ * because all it wants to ensure is that the remote task enters -+ * the kernel. If the IPI races and the task has been migrated -+ * to another CPU then no harm is done and the purpose has been -+ * achieved as well. -+ */ -+void kick_process(struct task_struct *p) -+{ -+ guard(preempt)(); -+ int cpu = task_cpu(p); -+ -+ if ((cpu != smp_processor_id()) && task_curr(p)) -+ smp_send_reschedule(cpu); -+} -+EXPORT_SYMBOL_GPL(kick_process); -+ -+/* -+ * ->cpus_ptr is protected by both rq->lock and p->pi_lock -+ * -+ * A few notes on cpu_active vs cpu_online: -+ * -+ * - cpu_active must be a subset of cpu_online -+ * -+ * - on CPU-up we allow per-CPU kthreads on the online && !active CPU, -+ * see __set_cpus_allowed_ptr(). At this point the newly online -+ * CPU isn't yet part of the sched domains, and balancing will not -+ * see it. -+ * -+ * - on cpu-down we clear cpu_active() to mask the sched domains and -+ * avoid the load balancer to place new tasks on the to be removed -+ * CPU. Existing tasks will remain running there and will be taken -+ * off. -+ * -+ * This means that fallback selection must not select !active CPUs. -+ * And can assume that any active CPU must be online. Conversely -+ * select_task_rq() below may allow selection of !active CPUs in order -+ * to satisfy the above rules. -+ */ -+static int select_fallback_rq(int cpu, struct task_struct *p) -+{ -+ int nid = cpu_to_node(cpu); -+ const struct cpumask *nodemask = NULL; -+ enum { cpuset, possible, fail } state = cpuset; -+ int dest_cpu; -+ -+ /* -+ * If the node that the CPU is on has been offlined, cpu_to_node() -+ * will return -1. There is no CPU on the node, and we should -+ * select the CPU on the other node. -+ */ -+ if (nid != -1) { -+ nodemask = cpumask_of_node(nid); -+ -+ /* Look for allowed, online CPU in same node. */ -+ for_each_cpu(dest_cpu, nodemask) { -+ if (is_cpu_allowed(p, dest_cpu)) -+ return dest_cpu; -+ } -+ } -+ -+ for (;;) { -+ /* Any allowed, online CPU? */ -+ for_each_cpu(dest_cpu, p->cpus_ptr) { -+ if (!is_cpu_allowed(p, dest_cpu)) -+ continue; -+ goto out; -+ } -+ -+ /* No more Mr. Nice Guy. */ -+ switch (state) { -+ case cpuset: -+ if (cpuset_cpus_allowed_fallback(p)) { -+ state = possible; -+ break; -+ } -+ fallthrough; -+ case possible: -+ set_cpus_allowed_force(p, task_cpu_fallback_mask(p)); -+ state = fail; -+ break; -+ -+ case fail: -+ BUG(); -+ break; -+ } -+ } -+ -+out: -+ if (state != cpuset) { -+ /* -+ * Don't tell them about moving exiting tasks or -+ * kernel threads (both mm NULL), since they never -+ * leave kernel. -+ */ -+ if (p->mm && printk_ratelimit()) { -+ printk_deferred("process %d (%s) no longer affine to cpu%d\n", -+ task_pid_nr(p), p->comm, cpu); -+ } -+ } -+ -+ return dest_cpu; -+} -+ -+static inline void -+sched_preempt_mask_flush(cpumask_t *mask, int prio, int ref) -+{ -+ int cpu; -+ -+ cpumask_copy(mask, sched_preempt_mask + ref); -+ if (prio < ref) { -+ for_each_clear_bit(cpu, cpumask_bits(mask), nr_cpumask_bits) { -+ if (prio < cpu_rq(cpu)->prio) -+ cpumask_set_cpu(cpu, mask); -+ } -+ } else { -+ for_each_cpu_andnot(cpu, mask, sched_idle_mask) { -+ if (prio >= cpu_rq(cpu)->prio) -+ cpumask_clear_cpu(cpu, mask); -+ } -+ } -+} -+ -+static inline int -+preempt_mask_check(cpumask_t *preempt_mask, const cpumask_t *allow_mask, int prio) -+{ -+ cpumask_t *mask = sched_preempt_mask + prio; -+ int pr = atomic_read(&sched_prio_record); -+ -+ if (pr != prio && SCHED_QUEUE_BITS - 1 != prio) { -+ sched_preempt_mask_flush(mask, prio, pr); -+ atomic_set(&sched_prio_record, prio); -+ } -+ -+ return cpumask_and(preempt_mask, allow_mask, mask); -+} -+ -+DEFINE_STATIC_CALL(sched_idle_select_func, cpumask_and); -+ -+static void record_wakee(struct task_struct *p) -+{ -+ /* -+ * Only decay a single time; tasks that have less then 1 wakeup per -+ * jiffy will not have built up many flips. -+ */ -+ if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) { -+ current->wakee_flips >>= 1; -+ WRITE_ONCE(current->wakee_flip_decay_ts, jiffies); -+ } -+ -+ if (current->last_wakee != p) { -+ WRITE_ONCE(current->last_wakee, p); -+ current->wakee_flips++; -+ } -+} -+ -+/* -+ * Detect M:N waker/wakee relationships via a switching-frequency heuristic. -+ * -+ * A waker of many should wake a different task than the one last awakened -+ * at a frequency roughly N times higher than one of its wakees. -+ * -+ * In order to determine whether we should let the load spread vs consolidating -+ * to shared cache, we look for a minimum 'flip' frequency of llc_size in one -+ * partner, and a factor of lls_size higher frequency in the other. -+ * -+ * With both conditions met, we can be relatively sure that the relationship is -+ * non-monogamous, with partner count exceeding socket size. -+ * -+ * Waker/wakee being client/server, worker/dispatcher, interrupt source or -+ * whatever is irrelevant, spread criteria is apparent partner count exceeds -+ * socket size. -+ */ -+static int wake_wide(struct task_struct *p) -+{ -+ unsigned int master = current->wakee_flips; -+ unsigned int slave = p->wakee_flips; -+ int factor = __this_cpu_read(sd_llc_size); -+ -+ if (master < slave) -+ swap(master, slave); -+ if (slave < factor || master < slave * factor) -+ return 0; -+ return 1; -+} -+ -+static int -+wake_affine_idle(int this_cpu, int prev_cpu, int sync) -+{ -+ /* -+ * If this_cpu is idle, it implies the wakeup is from interrupt -+ * context. Only allow the move if cache is shared. Otherwise an -+ * interrupt intensive workload could force all tasks onto one -+ * node depending on the IO topology or IRQ affinity settings. -+ * -+ * If the prev_cpu is idle and cache affine then avoid a migration. -+ * There is no guarantee that the cache hot data from an interrupt -+ * is more important than cache hot data on the prev_cpu and from -+ * a cpufreq perspective, it's better to have higher utilisation -+ * on one CPU. -+ */ -+ if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu)) -+ return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu; -+ -+ /* -+ * If the previous CPU is cache affine and idle, don't be stupid. -+ */ -+ if (prev_cpu != this_cpu && cpus_share_cache(this_cpu, prev_cpu) && -+ available_idle_cpu(prev_cpu)) -+ return prev_cpu; -+ -+ if (sync) { -+ struct rq *rq = cpu_rq(this_cpu); -+ -+ if (rq->nr_running == 1) -+ return this_cpu; -+ } -+ -+ if (available_idle_cpu(prev_cpu)) -+ return prev_cpu; -+ -+ return nr_cpu_ids; -+} -+ -+static inline int select_task_rq(struct task_struct *p, int wake_flags) -+{ -+ int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING); -+ cpumask_t allow_mask, mask; -+ int cpu = smp_processor_id(); -+ int prev_cpu = task_cpu(p); -+ int new_cpu = prev_cpu; -+ int want_affine = 0; -+ bool wakee_migratable = p->nr_cpus_allowed > 1 && !is_migration_disabled(p); -+ -+ /* -+ * required for stable ->cpus_allowed -+ */ -+ lockdep_assert_held(&p->pi_lock); -+ -+ if (!wakee_migratable) { -+ new_cpu = cpumask_any(p->cpus_ptr); -+ goto out; -+ } -+ -+ if (wake_flags & WF_TTWU) { -+ record_wakee(p); -+ -+ if ((wake_flags & WF_CURRENT_CPU) && -+ cpumask_test_cpu(cpu, p->cpus_ptr)) { -+ new_cpu = cpu; -+ goto out; -+ } -+ -+ want_affine = sync && cpumask_test_cpu(cpu, p->cpus_ptr) && -+ !wake_wide(p); -+ } -+ -+ if (unlikely(!cpumask_and(&allow_mask, p->cpus_ptr, cpu_active_mask))) { -+ new_cpu = select_fallback_rq(prev_cpu, p); -+ goto out; -+ } -+ -+ if (want_affine) { -+ int affine_cpu = nr_cpu_ids; -+ s64 waker_ran = READ_ONCE(this_rq()->clock) - -+ READ_ONCE(current->wake_start); -+ -+ if (!is_idle_task(current) && waker_ran < TICK_NSEC) { -+ cpumask_and(&mask, cpu_smt_mask(cpu), &allow_mask); -+ affine_cpu = cpumask_any_but(&mask, cpu); -+ if (affine_cpu >= nr_cpu_ids) -+ affine_cpu = cpu; -+ } -+ if (affine_cpu >= nr_cpu_ids) -+ affine_cpu = wake_affine_idle(cpu, prev_cpu, sync); -+ else if (!available_idle_cpu(affine_cpu) && -+ ((affine_cpu != cpu && -+ (rt_task(p) || sched_task_has_credit(p)) && -+ task_sched_prio(p) >= cpu_rq(affine_cpu)->prio) || -+ (cpu_rq(cpu)->nr_running + cpu_rq(affine_cpu)->nr_running > 3 && -+ cpumask_intersects(&allow_mask, sched_idle_mask)))) -+ affine_cpu = nr_cpu_ids; -+ if (affine_cpu < nr_cpu_ids && -+ cpumask_test_cpu(affine_cpu, &allow_mask)) { -+ new_cpu = affine_cpu; -+ goto out; -+ } -+ } -+ -+ if (static_call(sched_idle_select_func)(&mask, &allow_mask, sched_idle_mask)) { -+ do { -+ new_cpu = cpumask_test_cpu(prev_cpu, &mask) ? -+ prev_cpu : best_mask_cpu(prev_cpu, &mask); -+ if (!__is_defined(ALT_SCHED_TTWU_QUEUE) || -+ !cpu_rq(new_cpu)->ttwu_pending) -+ goto out; -+ __cpumask_clear_cpu(new_cpu, &mask); -+ } while (!cpumask_empty(&mask)); -+ } -+ -+ int prio = task_sched_prio(p); -+ -+ if (preempt_mask_check(&mask, &allow_mask, prio)) { -+ int preempt_cpu = nr_cpu_ids; -+ -+ guard(rcu)(); -+ do { -+ new_cpu = best_mask_cpu(prev_cpu, &mask); -+ if (prio < cpu_rq(new_cpu)->prio) { -+ struct task_struct *curr = rcu_dereference(cpu_rq(new_cpu)->curr); -+ -+ if (!rt_task(curr) && !sched_task_has_credit(curr) && -+ !test_tsk_need_resched(curr)) -+ goto out; -+ if (preempt_cpu >= nr_cpu_ids) -+ preempt_cpu = new_cpu; -+ } -+ __cpumask_clear_cpu(new_cpu, &mask); -+ } while (!cpumask_empty(&mask)); -+ -+ if (preempt_cpu < nr_cpu_ids) { -+ new_cpu = preempt_cpu; -+ goto out; -+ } -+ } -+ new_cpu = best_mask_cpu(prev_cpu, &allow_mask); -+ -+out: -+ if (unlikely(!is_cpu_allowed(p, new_cpu))) -+ new_cpu = select_fallback_rq(prev_cpu, p); -+ -+ return new_cpu; -+} -+ -+void sched_set_stop_task(int cpu, struct task_struct *stop) -+{ -+ static struct lock_class_key stop_pi_lock; -+ struct sched_param stop_param = { .sched_priority = STOP_PRIO }; -+ struct sched_param start_param = { .sched_priority = 0 }; -+ struct task_struct *old_stop = cpu_rq(cpu)->stop; -+ -+ if (stop) { -+ /* -+ * Make it appear like a SCHED_FIFO task, its something -+ * userspace knows about and won't get confused about. -+ * -+ * Also, it will make PI more or less work without too -+ * much confusion -- but then, stop work should not -+ * rely on PI working anyway. -+ */ -+ sched_setscheduler_nocheck(stop, SCHED_FIFO, &stop_param); -+ -+ /* -+ * The PI code calls rt_mutex_setprio() with ->pi_lock held to -+ * adjust the effective priority of a task. As a result, -+ * rt_mutex_setprio() can trigger (RT) balancing operations, -+ * which can then trigger wakeups of the stop thread to push -+ * around the current task. -+ * -+ * The stop task itself will never be part of the PI-chain, it -+ * never blocks, therefore that ->pi_lock recursion is safe. -+ * Tell lockdep about this by placing the stop->pi_lock in its -+ * own class. -+ */ -+ lockdep_set_class(&stop->pi_lock, &stop_pi_lock); -+ } -+ -+ cpu_rq(cpu)->stop = stop; -+ -+ if (old_stop) { -+ /* -+ * Reset it back to a normal scheduling policy so that -+ * it can die in pieces. -+ */ -+ sched_setscheduler_nocheck(old_stop, SCHED_NORMAL, &start_param); -+ } -+} -+ -+static int affine_move_task(struct rq *rq, struct task_struct *p, -+ struct rq_flags *rf, int dest_cpu) -+ __releases(__rq_lockp(rq), &p->pi_lock) -+{ -+ /* Can the task run on the task's current CPU? If so, we're done */ -+ if (!cpumask_test_cpu(task_cpu(p), &p->cpus_mask)) { -+ if (is_migration_disabled(p)) -+ __migrate_force_enable(p, rq); -+ -+ if (task_on_cpu(task_rq(p), p) || READ_ONCE(p->__state) == TASK_WAKING) { -+ struct migration_arg arg = { p, dest_cpu }; -+ -+ /* Need help from migration thread: drop lock and wait. */ -+ task_rq_unlock(rq, p, rf); -+ stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg); -+ return 0; -+ } -+ if (task_on_rq_queued(p)) { -+ /* -+ * OK, since we're going to drop the lock immediately -+ * afterwards anyway. -+ */ -+ update_rq_clock(rq); -+ rq = move_queued_task(rq, rf, p, dest_cpu); -+ } -+ } -+ task_rq_unlock(rq, p, rf); -+ return 0; -+} -+ -+static int __set_cpus_allowed_ptr_locked(struct task_struct *p, -+ struct affinity_context *ctx, -+ struct rq *rq, -+ struct rq_flags *rf) -+ __releases(__rq_lockp(rq), &p->pi_lock) -+{ -+ const struct cpumask *cpu_allowed_mask = task_cpu_possible_mask(p); -+ const struct cpumask *cpu_valid_mask = cpu_active_mask; -+ bool kthread = p->flags & PF_KTHREAD; -+ int dest_cpu; -+ int ret = 0; -+ -+ if (kthread || is_migration_disabled(p)) { -+ /* -+ * Kernel threads are allowed on online && !active CPUs, -+ * however, during cpu-hot-unplug, even these might get pushed -+ * away if not KTHREAD_IS_PER_CPU. -+ * -+ * Specifically, migration_disabled() tasks must not fail the -+ * cpumask_any_and_distribute() pick below, esp. so on -+ * SCA_MIGRATE_ENABLE, otherwise we'll not call -+ * set_cpus_allowed_common() and actually reset p->cpus_ptr. -+ */ -+ cpu_valid_mask = cpu_online_mask; -+ } -+ -+ if (!kthread && !cpumask_subset(ctx->new_mask, cpu_allowed_mask)) { -+ ret = -EINVAL; -+ goto out; -+ } -+ -+ /* -+ * Must re-check here, to close a race against __kthread_bind(), -+ * sched_setaffinity() is not guaranteed to observe the flag. -+ */ -+ if ((ctx->flags & SCA_CHECK) && (p->flags & PF_NO_SETAFFINITY)) { -+ ret = -EINVAL; -+ goto out; -+ } -+ -+ if (cpumask_equal(&p->cpus_mask, ctx->new_mask)) { -+ if (ctx->flags & SCA_USER) -+ swap(p->user_cpus_ptr, ctx->user_mask); -+ goto out; -+ } -+ -+ dest_cpu = cpumask_any_and_distribute(cpu_valid_mask, ctx->new_mask); -+ if (dest_cpu >= nr_cpu_ids) { -+ ret = -EINVAL; -+ goto out; -+ } -+ -+ do_set_cpus_allowed(p, ctx); -+ -+ return affine_move_task(rq, p, rf, dest_cpu); -+ -+out: -+ task_rq_unlock(rq, p, rf); -+ -+ return ret; -+} -+ -+/* -+ * Change a given task's CPU affinity. Migrate the thread to a -+ * is removed from the allowed bitmask. -+ * -+ * NOTE: the caller must have a valid reference to the task, the -+ * task must not exit() & deallocate itself prematurely. The -+ * call is not atomic; no spinlocks may be held. -+ */ -+int __set_cpus_allowed_ptr(struct task_struct *p, -+ struct affinity_context *ctx) -+{ -+ struct rq_flags rf; -+ struct rq *rq; -+ -+ rq = task_rq_lock(p, &rf); -+ /* -+ * Masking should be skipped if SCA_USER or any of the SCA_MIGRATE_* -+ * flags are set. -+ */ -+ if (p->user_cpus_ptr && -+ !(ctx->flags & (SCA_USER | SCA_MIGRATE_ENABLE | SCA_MIGRATE_DISABLE)) && -+ cpumask_and(rq->scratch_mask, ctx->new_mask, p->user_cpus_ptr)) -+ ctx->new_mask = rq->scratch_mask; -+ -+ -+ return __set_cpus_allowed_ptr_locked(p, ctx, rq, &rf); -+} -+ -+int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask) -+{ -+ struct affinity_context ac = { -+ .new_mask = new_mask, -+ .flags = 0, -+ }; -+ -+ return __set_cpus_allowed_ptr(p, &ac); -+} -+EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr); -+ -+/* -+ * Change a given task's CPU affinity to the intersection of its current -+ * affinity mask and @subset_mask, writing the resulting mask to @new_mask. -+ * If user_cpus_ptr is defined, use it as the basis for restricting CPU -+ * affinity or use cpu_online_mask instead. -+ * -+ * If the resulting mask is empty, leave the affinity unchanged and return -+ * -EINVAL. -+ */ -+static int restrict_cpus_allowed_ptr(struct task_struct *p, -+ struct cpumask *new_mask, -+ const struct cpumask *subset_mask) -+{ -+ struct affinity_context ac = { -+ .new_mask = new_mask, -+ .flags = 0, -+ }; -+ struct rq_flags rf; -+ struct rq *rq; -+ int err; -+ -+ rq = task_rq_lock(p, &rf); -+ -+ if (!cpumask_and(new_mask, task_user_cpus(p), subset_mask)) { -+ err = -EINVAL; -+ goto err_unlock; -+ } -+ -+ return __set_cpus_allowed_ptr_locked(p, &ac, rq, &rf); -+ -+err_unlock: -+ task_rq_unlock(rq, p, &rf); -+ return err; -+} -+ -+/* -+ * Restrict the CPU affinity of task @p so that it is a subset of -+ * task_cpu_possible_mask() and point @p->user_cpus_ptr to a copy of the -+ * old affinity mask. If the resulting mask is empty, we warn and walk -+ * up the cpuset hierarchy until we find a suitable mask. -+ */ -+void force_compatible_cpus_allowed_ptr(struct task_struct *p) -+{ -+ cpumask_var_t new_mask; -+ const struct cpumask *override_mask = task_cpu_possible_mask(p); -+ -+ alloc_cpumask_var(&new_mask, GFP_KERNEL); -+ -+ /* -+ * __migrate_task() can fail silently in the face of concurrent -+ * offlining of the chosen destination CPU, so take the hotplug -+ * lock to ensure that the migration succeeds. -+ */ -+ cpus_read_lock(); -+ if (!cpumask_available(new_mask)) -+ goto out_set_mask; -+ -+ if (!restrict_cpus_allowed_ptr(p, new_mask, override_mask)) -+ goto out_free_mask; -+ -+ /* -+ * We failed to find a valid subset of the affinity mask for the -+ * task, so override it based on its cpuset hierarchy. -+ */ -+ cpuset_cpus_allowed(p, new_mask); -+ override_mask = new_mask; -+ -+out_set_mask: -+ if (printk_ratelimit()) { -+ printk_deferred("Overriding affinity for process %d (%s) to CPUs %*pbl\n", -+ task_pid_nr(p), p->comm, -+ cpumask_pr_args(override_mask)); -+ } -+ -+ WARN_ON(set_cpus_allowed_ptr(p, override_mask)); -+out_free_mask: -+ cpus_read_unlock(); -+ free_cpumask_var(new_mask); -+} -+ -+/* -+ * Restore the affinity of a task @p which was previously restricted by a -+ * call to force_compatible_cpus_allowed_ptr(). -+ * -+ * It is the caller's responsibility to serialise this with any calls to -+ * force_compatible_cpus_allowed_ptr(@p). -+ */ -+void relax_compatible_cpus_allowed_ptr(struct task_struct *p) -+{ -+ struct affinity_context ac = { -+ .new_mask = task_user_cpus(p), -+ .flags = 0, -+ }; -+ int ret; -+ -+ /* -+ * Try to restore the old affinity mask with __sched_setaffinity(). -+ * Cpuset masking will be done there too. -+ */ -+ ret = __sched_setaffinity(p, &ac); -+ WARN_ON_ONCE(ret); -+} -+ -+static void -+ttwu_stat(struct task_struct *p, int cpu, int wake_flags) -+{ -+ struct rq *rq; -+ -+ if (!schedstat_enabled()) -+ return; -+ -+ rq = this_rq(); -+ -+ if (cpu == rq->cpu) { -+ __schedstat_inc(rq->ttwu_local); -+ __schedstat_inc(p->stats.nr_wakeups_local); -+ } else { -+ /** Alt schedule FW ToDo: -+ * How to do ttwu_wake_remote -+ */ -+ } -+ -+ __schedstat_inc(rq->ttwu_count); -+ __schedstat_inc(p->stats.nr_wakeups); -+} -+ -+/* -+ * Mark the task runnable. -+ */ -+static inline void ttwu_do_wakeup(struct task_struct *p) -+{ -+ p->is_blocked = 0; -+ WRITE_ONCE(p->__state, TASK_RUNNING); -+ trace_sched_wakeup(p); -+} -+ -+static inline void -+ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags) -+{ -+ int en_flags = ENQUEUE_WAKEUP; -+ -+ lockdep_assert_rq_held(rq); -+ -+ if (p->sched_contributes_to_load) -+ rq->nr_uninterruptible--; -+ -+ if (wake_flags & WF_MIGRATED) -+ en_flags |= ENQUEUE_MIGRATED; -+ else -+ if (p->in_iowait) { -+ delayacct_blkio_end(p); -+ atomic_dec(&task_rq(p)->nr_iowait); -+ } -+ -+ WRITE_ONCE(p->wake_start, rq->clock); -+ -+ activate_task(p, rq, en_flags); -+ wakeup_preempt(rq); -+ -+ ttwu_do_wakeup(p); -+} -+ -+/* -+ * Consider @p being inside a wait loop: -+ * -+ * for (;;) { -+ * set_current_state(TASK_UNINTERRUPTIBLE); -+ * -+ * if (CONDITION) -+ * break; -+ * -+ * schedule(); -+ * } -+ * __set_current_state(TASK_RUNNING); -+ * -+ * between set_current_state() and schedule(). In this case @p is still -+ * runnable, so all that needs doing is change p->state back to TASK_RUNNING in -+ * an atomic manner. -+ * -+ * By taking task_rq(p)->lock we serialize against schedule(), if @p->on_rq -+ * then schedule() must still happen and p->state can be changed to -+ * TASK_RUNNING. Otherwise we lost the race, schedule() has happened, and we -+ * need to do a full wakeup with enqueue. -+ * -+ * Returns: %true when the wakeup is done, -+ * %false otherwise. -+ */ -+static int ttwu_runnable(struct task_struct *p, int wake_flags) -+{ -+ struct rq *rq; -+ raw_spinlock_t *lock; -+ int ret = 0; -+ -+ rq = __task_access_lock(p, &lock); -+ if (task_on_rq_queued(p)) { -+ if (!task_on_cpu(task_rq(p), p)) { -+ /* -+ * When on_rq && !on_cpu the task is preempted, see if -+ * it should preempt the task that is current now. -+ */ -+ update_rq_clock(rq); -+ wakeup_preempt(rq); -+ } -+ ttwu_do_wakeup(p); -+ ret = 1; -+ } -+ __task_access_unlock(p, lock); -+ -+ return ret; -+} -+ -+void sched_ttwu_pending(void *arg) -+{ -+ struct llist_node *llist = arg; -+ struct rq *rq = this_rq(); -+ struct task_struct *p, *t; -+ struct rq_flags rf; -+ -+ if (!llist) -+ return; -+ -+ rq_lock_irqsave(rq, &rf); -+ update_rq_clock(rq); -+ -+ llist_for_each_entry_safe(p, t, llist, wake_entry.llist) { -+ if (WARN_ON_ONCE(p->on_cpu)) -+ smp_cond_load_acquire(&p->on_cpu, !VAL); -+ -+ if (WARN_ON_ONCE(task_cpu(p) != cpu_of(rq))) -+ set_task_cpu(p, cpu_of(rq)); -+ -+ ttwu_do_activate(rq, p, p->sched_remote_wakeup ? WF_MIGRATED : 0); -+ } -+ -+ /* -+ * Must be after enqueueing at least once task such that -+ * idle_cpu() does not observe a false-negative -- if it does, -+ * it is possible for select_idle_siblings() to stack a number -+ * of tasks on this CPU during that window. -+ * -+ * It is OK to clear ttwu_pending when another task pending. -+ * We will receive IPI after local IRQ enabled and then enqueue it. -+ * Since now nr_running > 0, idle_cpu() will always get correct result. -+ */ -+ WRITE_ONCE(rq->ttwu_pending, 0); -+ rq_unlock_irqrestore(rq, &rf); -+} -+ -+/* -+ * Prepare the scene for sending an IPI for a remote smp_call -+ * -+ * Returns true if the caller can proceed with sending the IPI. -+ * Returns false otherwise. -+ */ -+bool call_function_single_prep_ipi(int cpu) -+{ -+ if (set_nr_if_polling(cpu_rq(cpu)->idle)) { -+ trace_sched_wake_idle_without_ipi(cpu); -+ return false; -+ } -+ -+ return true; -+} -+ -+/* -+ * Queue a task on the target CPUs wake_list and wake the CPU via IPI if -+ * necessary. The wakee CPU on receipt of the IPI will queue the task -+ * via sched_ttwu_wakeup() for activation so the wakee incurs the cost -+ * of the wakeup instead of the waker. -+ */ -+static void __ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags) -+{ -+ struct rq *rq = cpu_rq(cpu); -+ -+ p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED); -+ -+ WRITE_ONCE(rq->ttwu_pending, 1); -+#ifdef CONFIG_SMP -+ __smp_call_single_queue(cpu, &p->wake_entry.llist); -+#endif -+} -+ -+static inline bool ttwu_queue_cond(struct task_struct *p, int cpu) -+{ -+ int this_cpu = smp_processor_id(); -+ -+ if (p == cpu_rq(cpu)->stop) -+ return false; -+ -+ /* -+ * Do not complicate things with the async wake_list while the CPU is -+ * in hotplug state. -+ */ -+ if (!cpu_active(cpu)) -+ return false; -+ -+ /* Ensure the task will still be allowed to run on the CPU. */ -+ if (!cpumask_test_cpu(cpu, p->cpus_ptr)) -+ return false; -+ -+ /* -+ * If the CPU does not share cache, then queue the task on the -+ * remote rqs wakelist to avoid accessing remote data. -+ */ -+ if (!cpus_share_cache(this_cpu, cpu)) -+ return true; -+ -+ if (cpu == this_cpu) -+ return false; -+ -+ /* -+ * If the wakee cpu is idle, or the task is descheduling and the -+ * only running task on the CPU, then use the wakelist to offload -+ * the task activation to the idle (or soon-to-be-idle) CPU as -+ * the current CPU is likely busy. nr_running is checked to -+ * avoid unnecessary task stacking. -+ * -+ * Note that we can only get here with (wakee) p->on_rq=0, -+ * p->on_cpu can be whatever, we've done the dequeue, so -+ * the wakee has been accounted out of ->nr_running. -+ */ -+ if (!cpu_rq(cpu)->nr_running) -+ return true; -+ -+ return false; -+} -+ -+static bool ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags) -+{ -+ if (__is_defined(ALT_SCHED_TTWU_QUEUE) && ttwu_queue_cond(p, cpu)) { -+ sched_clock_cpu(cpu); /* Sync clocks across CPUs */ -+ __ttwu_queue_wakelist(p, cpu, wake_flags); -+ return true; -+ } -+ -+ return false; -+} -+ -+void wake_up_if_idle(int cpu) -+{ -+ struct rq *rq = cpu_rq(cpu); -+ -+ guard(rcu)(); -+ if (is_idle_task(rcu_dereference(rq->curr))) { -+ guard(rq_lock_irqsave)(rq); -+ if (is_idle_task(rq->curr)) -+ resched_curr(rq); -+ } -+} -+ -+extern struct static_key_false sched_asym_cpucapacity; -+ -+static __always_inline bool sched_asym_cpucap_active(void) -+{ -+ return static_branch_unlikely(&sched_asym_cpucapacity); -+} -+ -+bool cpus_equal_capacity(int this_cpu, int that_cpu) -+{ -+ if (!sched_asym_cpucap_active()) -+ return true; -+ -+ if (this_cpu == that_cpu) -+ return true; -+ -+ return arch_scale_cpu_capacity(this_cpu) == arch_scale_cpu_capacity(that_cpu); -+} -+ -+bool cpus_share_cache(int this_cpu, int that_cpu) -+{ -+ if (this_cpu == that_cpu) -+ return true; -+ -+ return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu); -+} -+ -+static inline void ttwu_queue(struct task_struct *p, int cpu, int wake_flags) -+{ -+ struct rq *rq = cpu_rq(cpu); -+ -+ if (ttwu_queue_wakelist(p, cpu, wake_flags)) -+ return; -+ -+ raw_spin_rq_lock(rq); -+ update_rq_clock(rq); -+ ttwu_do_activate(rq, p, wake_flags); -+ raw_spin_rq_unlock(rq); -+} -+ -+/* -+ * Invoked from try_to_wake_up() to check whether the task can be woken up. -+ * -+ * The caller holds p::pi_lock if p != current or has preemption -+ * disabled when p == current. -+ * -+ * The rules of saved_state: -+ * -+ * The related locking code always holds p::pi_lock when updating -+ * p::saved_state, which means the code is fully serialized in both cases. -+ * -+ * For PREEMPT_RT, the lock wait and lock wakeups happen via TASK_RTLOCK_WAIT. -+ * No other bits set. This allows to distinguish all wakeup scenarios. -+ * -+ * For FREEZER, the wakeup happens via TASK_FROZEN. No other bits set. This -+ * allows us to prevent early wakeup of tasks before they can be run on -+ * asymmetric ISA architectures (eg ARMv9). -+ */ -+static __always_inline -+bool ttwu_state_match(struct task_struct *p, unsigned int state, int *success) -+{ -+ int match; -+ -+ if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)) { -+ WARN_ON_ONCE((state & TASK_RTLOCK_WAIT) && -+ state != TASK_RTLOCK_WAIT); -+ } -+ -+ *success = !!(match = __task_state_match(p, state)); -+ -+ /* -+ * Saved state preserves the task state across blocking on -+ * an RT lock or TASK_FREEZABLE tasks. If the state matches, -+ * set p::saved_state to TASK_RUNNING, but do not wake the task -+ * because it waits for a lock wakeup or __thaw_task(). Also -+ * indicate success because from the regular waker's point of -+ * view this has succeeded. -+ * -+ * After acquiring the lock the task will restore p::__state -+ * from p::saved_state which ensures that the regular -+ * wakeup is not lost. The restore will also set -+ * p::saved_state to TASK_RUNNING so any further tests will -+ * not result in false positives vs. @success -+ */ -+ if (match < 0) -+ p->saved_state = TASK_RUNNING; -+ -+ return match > 0; -+} -+ -+/* -+ * Notes on Program-Order guarantees on SMP systems. -+ * -+ * MIGRATION -+ * -+ * The basic program-order guarantee on SMP systems is that when a task [t] -+ * migrates, all its activity on its old CPU [c0] happens-before any subsequent -+ * execution on its new CPU [c1]. -+ * -+ * For migration (of runnable tasks) this is provided by the following means: -+ * -+ * A) UNLOCK of the rq(c0)->lock scheduling out task t -+ * B) migration for t is required to synchronize *both* rq(c0)->lock and -+ * rq(c1)->lock (if not at the same time, then in that order). -+ * C) LOCK of the rq(c1)->lock scheduling in task -+ * -+ * Transitivity guarantees that B happens after A and C after B. -+ * Note: we only require RCpc transitivity. -+ * Note: the CPU doing B need not be c0 or c1 -+ * -+ * Example: -+ * -+ * CPU0 CPU1 CPU2 -+ * -+ * LOCK rq(0)->lock -+ * sched-out X -+ * sched-in Y -+ * UNLOCK rq(0)->lock -+ * -+ * LOCK rq(0)->lock // orders against CPU0 -+ * dequeue X -+ * UNLOCK rq(0)->lock -+ * -+ * LOCK rq(1)->lock -+ * enqueue X -+ * UNLOCK rq(1)->lock -+ * -+ * LOCK rq(1)->lock // orders against CPU2 -+ * sched-out Z -+ * sched-in X -+ * UNLOCK rq(1)->lock -+ * -+ * -+ * BLOCKING -- aka. SLEEP + WAKEUP -+ * -+ * For blocking we (obviously) need to provide the same guarantee as for -+ * migration. However the means are completely different as there is no lock -+ * chain to provide order. Instead we do: -+ * -+ * 1) smp_store_release(X->on_cpu, 0) -- finish_task() -+ * 2) smp_cond_load_acquire(!X->on_cpu) -- try_to_wake_up() -+ * -+ * Example: -+ * -+ * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule) -+ * -+ * LOCK rq(0)->lock LOCK X->pi_lock -+ * dequeue X -+ * sched-out X -+ * smp_store_release(X->on_cpu, 0); -+ * -+ * smp_cond_load_acquire(&X->on_cpu, !VAL); -+ * X->state = WAKING -+ * set_task_cpu(X,2) -+ * -+ * LOCK rq(2)->lock -+ * enqueue X -+ * X->state = RUNNING -+ * UNLOCK rq(2)->lock -+ * -+ * LOCK rq(2)->lock // orders against CPU1 -+ * sched-out Z -+ * sched-in X -+ * UNLOCK rq(2)->lock -+ * -+ * UNLOCK X->pi_lock -+ * UNLOCK rq(0)->lock -+ * -+ * -+ * However; for wakeups there is a second guarantee we must provide, namely we -+ * must observe the state that lead to our wakeup. That is, not only must our -+ * task observe its own prior state, it must also observe the stores prior to -+ * its wakeup. -+ * -+ * This means that any means of doing remote wakeups must order the CPU doing -+ * the wakeup against the CPU the task is going to end up running on. This, -+ * however, is already required for the regular Program-Order guarantee above, -+ * since the waking CPU is the one issueing the ACQUIRE (smp_cond_load_acquire). -+ * -+ */ -+ -+/** -+ * try_to_wake_up - wake up a thread -+ * @p: the thread to be awakened -+ * @state: the mask of task states that can be woken -+ * @wake_flags: wake modifier flags (WF_*) -+ * -+ * Conceptually does: -+ * -+ * If (@state & @p->state) @p->state = TASK_RUNNING. -+ * -+ * If the task was not queued/runnable, also place it back on a runqueue. -+ * -+ * This function is atomic against schedule() which would dequeue the task. -+ * -+ * It issues a full memory barrier before accessing @p->state, see the comment -+ * with set_current_state(). -+ * -+ * Uses p->pi_lock to serialize against concurrent wake-ups. -+ * -+ * Relies on p->pi_lock stabilizing: -+ * - p->sched_class -+ * - p->cpus_ptr -+ * - p->sched_task_group -+ * in order to do migration, see its use of select_task_rq()/set_task_cpu(). -+ * -+ * Tries really hard to only take one task_rq(p)->lock for performance. -+ * Takes rq->lock in: -+ * - ttwu_runnable() -- old rq, unavoidable, see comment there; -+ * - ttwu_queue() -- new rq, for enqueue of the task; -+ * - psi_ttwu_dequeue() -- much sadness :-( accounting will kill us. -+ * -+ * As a consequence we race really badly with just about everything. See the -+ * many memory barriers and their comments for details. -+ * -+ * Return: %true if @p->state changes (an actual wakeup was done), -+ * %false otherwise. -+ */ -+int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags) -+{ -+ guard(preempt)(); -+ int cpu, success = 0; -+ -+ wake_flags |= WF_TTWU; -+ -+ if (p == current) { -+ /* -+ * We're waking current, this means 'p->on_rq' and 'task_cpu(p) -+ * == smp_processor_id()'. Together this means we can special -+ * case the whole 'p->on_rq && ttwu_runnable()' case below -+ * without taking any locks. -+ * -+ * In particular: -+ * - we rely on Program-Order guarantees for all the ordering, -+ * - we're serialized against set_special_state() by virtue of -+ * it disabling IRQs (this allows not taking ->pi_lock). -+ */ -+ WARN_ON_ONCE(p->is_blocked); -+ if (!ttwu_state_match(p, state, &success)) -+ goto out; -+ -+ trace_sched_waking(p); -+ ttwu_do_wakeup(p); -+ goto out; -+ } -+ -+ /* -+ * If we are going to wake up a thread waiting for CONDITION we -+ * need to ensure that CONDITION=1 done by the caller can not be -+ * reordered with p->state check below. This pairs with smp_store_mb() -+ * in set_current_state() that the waiting thread does. -+ */ -+ scoped_guard (raw_spinlock_irqsave, &p->pi_lock) { -+ smp_mb__after_spinlock(); -+ if (!ttwu_state_match(p, state, &success)) -+ break; -+ -+ trace_sched_waking(p); -+ -+ /* -+ * Ensure we load p->on_rq _after_ p->state, otherwise it would -+ * be possible to, falsely, observe p->on_rq == 0 and get stuck -+ * in smp_cond_load_acquire() below. -+ * -+ * sched_ttwu_pending() try_to_wake_up() -+ * STORE p->on_rq = 1 LOAD p->state -+ * UNLOCK rq->lock -+ * -+ * __schedule() (switch to task 'p') -+ * LOCK rq->lock smp_rmb(); -+ * smp_mb__after_spinlock(); -+ * UNLOCK rq->lock -+ * -+ * [task p] -+ * STORE p->state = UNINTERRUPTIBLE LOAD p->on_rq -+ * -+ * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in -+ * __schedule(). See the comment for smp_mb__after_spinlock(). -+ * -+ * A similar smp_rmb() lives in __task_needs_rq_lock(). -+ */ -+ smp_rmb(); -+ if (READ_ONCE(p->on_rq) && ttwu_runnable(p, wake_flags)) -+ break; -+ -+ /* -+ * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be -+ * possible to, falsely, observe p->on_cpu == 0. -+ * -+ * One must be running (->on_cpu == 1) in order to remove oneself -+ * from the runqueue. -+ * -+ * __schedule() (switch to task 'p') try_to_wake_up() -+ * STORE p->on_cpu = 1 LOAD p->on_rq -+ * UNLOCK rq->lock -+ * -+ * __schedule() (put 'p' to sleep) -+ * LOCK rq->lock smp_rmb(); -+ * smp_mb__after_spinlock(); -+ * STORE p->on_rq = 0 LOAD p->on_cpu -+ * -+ * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in -+ * __schedule(). See the comment for smp_mb__after_spinlock(). -+ * -+ * Form a control-dep-acquire with p->on_rq == 0 above, to ensure -+ * schedule()'s block_task() has 'happened' and p will no longer -+ * care about it's own p->state. See the comment in __schedule(). -+ */ -+ smp_acquire__after_ctrl_dep(); -+ -+ /* -+ * We're doing the wakeup (@success == 1), they did a dequeue (p->on_rq -+ * == 0), which means we need to do an enqueue, change p->state to -+ * TASK_WAKING such that we can unlock p->pi_lock before doing the -+ * enqueue, such as ttwu_queue_wakelist(). -+ */ -+ WRITE_ONCE(p->__state, TASK_WAKING); -+ -+ /* -+ * If the owning (remote) CPU is still in the middle of schedule() with -+ * this task as prev, considering queueing p on the remote CPUs wake_list -+ * which potentially sends an IPI instead of spinning on p->on_cpu to -+ * let the waker make forward progress. This is safe because IRQs are -+ * disabled and the IPI will deliver after on_cpu is cleared. -+ * -+ * Ensure we load task_cpu(p) after p->on_cpu: -+ * -+ * set_task_cpu(p, cpu); -+ * STORE p->cpu = @cpu -+ * __schedule() (switch to task 'p') -+ * LOCK rq->lock -+ * smp_mb__after_spin_lock() smp_cond_load_acquire(&p->on_cpu) -+ * STORE p->on_cpu = 1 LOAD p->cpu -+ * -+ * to ensure we observe the correct CPU on which the task is currently -+ * scheduling. -+ */ -+ if (smp_load_acquire(&p->on_cpu) && -+ ttwu_queue_wakelist(p, task_cpu(p), wake_flags)) -+ break; -+ -+ /* -+ * If the owning (remote) CPU is still in the middle of schedule() with -+ * this task as prev, wait until it's done referencing the task. -+ * -+ * Pairs with the smp_store_release() in finish_task(). -+ * -+ * This ensures that tasks getting woken will be fully ordered against -+ * their previous state and preserve Program Order. -+ */ -+ smp_cond_load_acquire(&p->on_cpu, !VAL); -+ -+ sched_task_ttwu(p); -+ -+ cpu = select_task_rq(p, wake_flags); -+ -+ if (cpu != task_cpu(p)) { -+ if (p->in_iowait) { -+ delayacct_blkio_end(p); -+ atomic_dec(&task_rq(p)->nr_iowait); -+ } -+ -+ wake_flags |= WF_MIGRATED; -+ psi_ttwu_dequeue(p); -+ set_task_cpu(p, cpu); -+ } -+ -+ ttwu_queue(p, cpu, wake_flags); -+ } -+out: -+ if (success) -+ ttwu_stat(p, task_cpu(p), wake_flags); -+ -+ return success; -+} -+ -+static bool __task_needs_rq_lock(struct task_struct *p) -+{ -+ unsigned int state = READ_ONCE(p->__state); -+ -+ /* -+ * Since pi->lock blocks try_to_wake_up(), we don't need rq->lock when -+ * the task is blocked. Make sure to check @state since ttwu() can drop -+ * locks at the end, see ttwu_queue_wakelist(). -+ */ -+ if (state == TASK_RUNNING || state == TASK_WAKING) -+ return true; -+ -+ /* -+ * Ensure we load p->on_rq after p->__state, otherwise it would be -+ * possible to, falsely, observe p->on_rq == 0. -+ * -+ * See try_to_wake_up() for a longer comment. -+ */ -+ smp_rmb(); -+ if (p->on_rq) -+ return true; -+ -+ /* -+ * Ensure the task has finished __schedule() and will not be referenced -+ * anymore. Again, see try_to_wake_up() for a longer comment. -+ */ -+ smp_rmb(); -+ smp_cond_load_acquire(&p->on_cpu, !VAL); -+ -+ return false; -+} -+ -+/** -+ * task_call_func - Invoke a function on task in fixed state -+ * @p: Process for which the function is to be invoked, can be @current. -+ * @func: Function to invoke. -+ * @arg: Argument to function. -+ * -+ * Fix the task in it's current state by avoiding wakeups and or rq operations -+ * and call @func(@arg) on it. This function can use task_is_runnable() and -+ * task_curr() to work out what the state is, if required. Given that @func -+ * can be invoked with a runqueue lock held, it had better be quite -+ * lightweight. -+ * -+ * Returns: -+ * Whatever @func returns -+ */ -+int task_call_func(struct task_struct *p, task_call_f func, void *arg) -+{ -+ struct rq_flags rf; -+ int ret; -+ -+ raw_spin_lock_irqsave(&p->pi_lock, rf.flags); -+ -+ if (__task_needs_rq_lock(p)) { -+ struct rq *rq = __task_rq_lock(p, &rf); -+ -+ /* -+ * At this point the task is pinned; either: -+ * - blocked and we're holding off wakeups (pi->lock) -+ * - woken, and we're holding off enqueue (rq->lock) -+ * - queued, and we're holding off schedule (rq->lock) -+ * - running, and we're holding off de-schedule (rq->lock) -+ * -+ * The called function (@func) can use: task_curr(), p->on_rq and -+ * p->__state to differentiate between these states. -+ */ -+ ret = func(p, arg); -+ -+ __task_rq_unlock(rq, p, &rf); -+ } else { -+ ret = func(p, arg); -+ } -+ -+ raw_spin_unlock_irqrestore(&p->pi_lock, rf.flags); -+ return ret; -+} -+ -+/** -+ * cpu_curr_snapshot - Return a snapshot of the currently running task -+ * @cpu: The CPU on which to snapshot the task. -+ * -+ * Returns the task_struct pointer of the task "currently" running on -+ * the specified CPU. -+ * -+ * If the specified CPU was offline, the return value is whatever it -+ * is, perhaps a pointer to the task_struct structure of that CPU's idle -+ * task, but there is no guarantee. Callers wishing a useful return -+ * value must take some action to ensure that the specified CPU remains -+ * online throughout. -+ * -+ * This function executes full memory barriers before and after fetching -+ * the pointer, which permits the caller to confine this function's fetch -+ * with respect to the caller's accesses to other shared variables. -+ */ -+struct task_struct *cpu_curr_snapshot(int cpu) -+{ -+ struct rq *rq = cpu_rq(cpu); -+ struct task_struct *t; -+ struct rq_flags rf; -+ -+ rq_lock_irqsave(rq, &rf); -+ smp_mb__after_spinlock(); /* Pairing determined by caller's synchronization design. */ -+ t = rcu_dereference(cpu_curr(cpu)); -+ rq_unlock_irqrestore(rq, &rf); -+ smp_mb(); /* Pairing determined by caller's synchronization design. */ -+ -+ return t; -+} -+ -+/** -+ * wake_up_process - Wake up a specific process -+ * @p: The process to be woken up. -+ * -+ * Attempt to wake up the nominated process and move it to the set of runnable -+ * processes. -+ * -+ * Return: 1 if the process was woken up, 0 if it was already running. -+ * -+ * This function executes a full memory barrier before accessing the task state. -+ */ -+int wake_up_process(struct task_struct *p) -+{ -+ return try_to_wake_up(p, TASK_NORMAL, 0); -+} -+EXPORT_SYMBOL(wake_up_process); -+ -+int wake_up_state(struct task_struct *p, unsigned int state) -+{ -+ return try_to_wake_up(p, state, 0); -+} -+ -+/* -+ * Perform scheduler related setup for a newly forked process p. -+ * p is forked by current. -+ * -+ * __sched_fork() is basic setup which is also used by sched_init() to -+ * initialize the boot CPU's idle task. -+ */ -+static inline void __sched_fork(u64 clone_flags, struct task_struct *p) -+{ -+ p->on_rq = 0; -+ p->on_cpu = 0; -+ p->utime = 0; -+ p->stime = 0; -+ p->sched_time = 0; -+ -+ WARN_ON_ONCE(p->is_blocked); -+ -+#ifdef CONFIG_SCHEDSTATS -+ /* Even if schedstat is disabled, there should not be garbage */ -+ memset(&p->stats, 0, sizeof(p->stats)); -+#endif -+ -+#ifdef CONFIG_PREEMPT_NOTIFIERS -+ INIT_HLIST_HEAD(&p->preempt_notifiers); -+#endif -+ -+#ifdef CONFIG_COMPACTION -+ p->capture_control = NULL; -+#endif -+ p->wake_entry.u_flags = CSD_TYPE_TTWU; -+} -+ -+/* -+ * fork()/clone()-time setup: -+ */ -+int sched_fork(u64 clone_flags, struct task_struct *p) -+{ -+ __sched_fork(clone_flags, p); -+ /* -+ * We mark the process as NEW here. This guarantees that -+ * nobody will actually run it, and a signal or other external -+ * event cannot wake it up and insert it on the runqueue either. -+ */ -+ p->__state = TASK_NEW; -+ -+ /* -+ * Make sure we do not leak PI boosting priority to the child. -+ */ -+ p->prio = current->normal_prio; -+ -+ /* -+ * Revert to default priority/policy on fork if requested. -+ */ -+ if (unlikely(p->sched_reset_on_fork)) { -+ if (task_has_rt_policy(p)) { -+ p->policy = SCHED_NORMAL; -+ p->static_prio = NICE_TO_PRIO(0); -+ p->rt_priority = 0; -+ p->timer_slack_ns = p->default_timer_slack_ns; -+ } else if (PRIO_TO_NICE(p->static_prio) < 0) -+ p->static_prio = NICE_TO_PRIO(0); -+ -+ p->prio = p->normal_prio = p->static_prio; -+ -+ /* -+ * We don't need the reset flag anymore after the fork. It has -+ * fulfilled its duty: -+ */ -+ p->sched_reset_on_fork = 0; -+ } -+ -+#ifdef CONFIG_SCHED_INFO -+ if (likely(sched_info_on())) -+ memset(&p->sched_info, 0, sizeof(p->sched_info)); -+#endif -+ init_task_preempt_count(p); -+ -+ return 0; -+} -+ -+static __always_inline void update_curr(struct rq *rq, struct task_struct *p); -+ -+int sched_cgroup_fork(struct task_struct *p, struct kernel_clone_args *kargs) -+{ -+ unsigned long flags; -+ struct rq *rq; -+ -+ /* -+ * Because we're not yet on the pid-hash, p->pi_lock isn't strictly -+ * required yet, but lockdep gets upset if rules are violated. -+ */ -+ raw_spin_lock_irqsave(&p->pi_lock, flags); -+ /* -+ * Share the timeslice between parent and child, thus the -+ * total amount of pending timeslices in the system doesn't change, -+ * resulting in more scheduling fairness. -+ */ -+ rq = this_rq(); -+ raw_spin_rq_lock(rq); -+ -+ update_rq_clock(rq); -+ update_curr(rq, rq->curr); -+ -+ rq->curr->time_slice /= 2; -+ p->time_slice = rq->curr->time_slice; -+ -+ if (p->time_slice < RESCHED_NS) { -+ p->time_slice = sysctl_sched_base_slice; -+ resched_curr(rq); -+ } else { -+ hrtick_start(rq, rq->curr->time_slice); -+ } -+ sched_task_fork(p, rq); -+ raw_spin_rq_unlock(rq); -+ -+ /* -+ * We're setting the CPU for the first time, we don't migrate, -+ * so use __set_task_cpu(). -+ */ -+ __set_task_cpu(p, smp_processor_id()); -+ raw_spin_unlock_irqrestore(&p->pi_lock, flags); -+ -+ return 0; -+} -+ -+void sched_cancel_fork(struct task_struct *p) -+{ -+} -+ -+static void sched_mm_cid_fork(struct task_struct *t); -+ -+void sched_post_fork(struct task_struct *p) -+{ -+ sched_mm_cid_fork(p); -+} -+ -+#ifdef CONFIG_SCHEDSTATS -+ -+DEFINE_STATIC_KEY_FALSE(sched_schedstats); -+ -+static void set_schedstats(bool enabled) -+{ -+ if (enabled) -+ static_branch_enable(&sched_schedstats); -+ else -+ static_branch_disable(&sched_schedstats); -+} -+ -+void force_schedstat_enabled(void) -+{ -+ if (!schedstat_enabled()) { -+ pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n"); -+ static_branch_enable(&sched_schedstats); -+ } -+} -+ -+static int __init setup_schedstats(char *str) -+{ -+ int ret = 0; -+ if (!str) -+ goto out; -+ -+ if (!strcmp(str, "enable")) { -+ set_schedstats(true); -+ ret = 1; -+ } else if (!strcmp(str, "disable")) { -+ set_schedstats(false); -+ ret = 1; -+ } -+out: -+ if (!ret) -+ pr_warn("Unable to parse schedstats=\n"); -+ -+ return ret; -+} -+__setup("schedstats=", setup_schedstats); -+ -+#ifdef CONFIG_SYSCTL -+static int sysctl_schedstats(const struct ctl_table *table, int write, void *buffer, -+ size_t *lenp, loff_t *ppos) -+{ -+ struct ctl_table t; -+ int err; -+ int state = static_branch_likely(&sched_schedstats); -+ -+ if (write && !capable(CAP_SYS_ADMIN)) -+ return -EPERM; -+ -+ t = *table; -+ t.data = &state; -+ err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos); -+ if (err < 0) -+ return err; -+ if (write) -+ set_schedstats(state); -+ return err; -+} -+#endif /* CONFIG_SYSCTL */ -+#endif /* CONFIG_SCHEDSTATS */ -+ -+#ifdef CONFIG_SYSCTL -+static const struct ctl_table sched_core_sysctls[] = { -+#ifdef CONFIG_SCHEDSTATS -+ { -+ .procname = "sched_schedstats", -+ .data = NULL, -+ .maxlen = sizeof(unsigned int), -+ .mode = 0644, -+ .proc_handler = sysctl_schedstats, -+ .extra1 = SYSCTL_ZERO, -+ .extra2 = SYSCTL_ONE, -+ }, -+#endif /* CONFIG_SCHEDSTATS */ -+}; -+static int __init sched_core_sysctl_init(void) -+{ -+ register_sysctl_init("kernel", sched_core_sysctls); -+ return 0; -+} -+late_initcall(sched_core_sysctl_init); -+#endif /* CONFIG_SYSCTL */ -+ -+/* -+ * wake_up_new_task - wake up a newly created task for the first time. -+ * -+ * This function will do some initial scheduler statistics housekeeping -+ * that must be done for every newly created context, then puts the task -+ * on the runqueue and wakes it. -+ */ -+void wake_up_new_task(struct task_struct *p) -+{ -+ unsigned long flags; -+ struct rq *rq; -+ -+ raw_spin_lock_irqsave(&p->pi_lock, flags); -+ WRITE_ONCE(p->__state, TASK_RUNNING); -+ rq = cpu_rq(select_task_rq(p, 0)); -+ /* -+ * Fork balancing, do it here and not earlier because: -+ * - cpus_ptr can change in the fork path -+ * - any previously selected CPU might disappear through hotplug -+ * -+ * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq, -+ * as we're not fully set-up yet. -+ */ -+ __set_task_cpu(p, cpu_of(rq)); -+ -+ raw_spin_rq_lock(rq); -+ update_rq_clock(rq); -+ -+ activate_task(p, rq, ENQUEUE_INITIAL); -+ trace_sched_wakeup_new(p); -+ wakeup_preempt(rq); -+ -+ raw_spin_rq_unlock(rq); -+ raw_spin_unlock_irqrestore(&p->pi_lock, flags); -+} -+ -+#ifdef CONFIG_PREEMPT_NOTIFIERS -+ -+static DEFINE_STATIC_KEY_FALSE(preempt_notifier_key); -+ -+void preempt_notifier_inc(void) -+{ -+ static_branch_inc(&preempt_notifier_key); -+} -+EXPORT_SYMBOL_GPL(preempt_notifier_inc); -+ -+void preempt_notifier_dec(void) -+{ -+ static_branch_dec(&preempt_notifier_key); -+} -+EXPORT_SYMBOL_GPL(preempt_notifier_dec); -+ -+/** -+ * preempt_notifier_register - tell me when current is being preempted & rescheduled -+ * @notifier: notifier struct to register -+ */ -+void preempt_notifier_register(struct preempt_notifier *notifier) -+{ -+ if (!static_branch_unlikely(&preempt_notifier_key)) -+ WARN(1, "registering preempt_notifier while notifiers disabled\n"); -+ -+ hlist_add_head(¬ifier->link, ¤t->preempt_notifiers); -+} -+EXPORT_SYMBOL_GPL(preempt_notifier_register); -+ -+/** -+ * preempt_notifier_unregister - no longer interested in preemption notifications -+ * @notifier: notifier struct to unregister -+ * -+ * This is *not* safe to call from within a preemption notifier. -+ */ -+void preempt_notifier_unregister(struct preempt_notifier *notifier) -+{ -+ hlist_del(¬ifier->link); -+} -+EXPORT_SYMBOL_GPL(preempt_notifier_unregister); -+ -+static void __fire_sched_in_preempt_notifiers(struct task_struct *curr) -+{ -+ struct preempt_notifier *notifier; -+ -+ hlist_for_each_entry(notifier, &curr->preempt_notifiers, link) -+ notifier->ops->sched_in(notifier, raw_smp_processor_id()); -+} -+ -+static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr) -+{ -+ if (static_branch_unlikely(&preempt_notifier_key)) -+ __fire_sched_in_preempt_notifiers(curr); -+} -+ -+static void -+__fire_sched_out_preempt_notifiers(struct task_struct *curr, -+ struct task_struct *next) -+{ -+ struct preempt_notifier *notifier; -+ -+ hlist_for_each_entry(notifier, &curr->preempt_notifiers, link) -+ notifier->ops->sched_out(notifier, next); -+} -+ -+static __always_inline void -+fire_sched_out_preempt_notifiers(struct task_struct *curr, -+ struct task_struct *next) -+{ -+ if (static_branch_unlikely(&preempt_notifier_key)) -+ __fire_sched_out_preempt_notifiers(curr, next); -+} -+ -+#else /* !CONFIG_PREEMPT_NOTIFIERS: */ -+ -+static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr) -+{ -+} -+ -+static inline void -+fire_sched_out_preempt_notifiers(struct task_struct *curr, -+ struct task_struct *next) -+{ -+} -+ -+#endif /* !CONFIG_PREEMPT_NOTIFIERS */ -+ -+static inline void prepare_task(struct task_struct *next) -+{ -+ /* -+ * Claim the task as running, we do this before switching to it -+ * such that any running task will have this set. -+ * -+ * See the smp_load_acquire(&p->on_cpu) case in ttwu() and -+ * its ordering comment. -+ */ -+ WRITE_ONCE(next->on_cpu, 1); -+} -+ -+static __always_inline void finish_task(struct task_struct *prev) -+{ -+ /* -+ * This must be the very last reference to @prev from this CPU. After -+ * p->on_cpu is cleared, the task can be moved to a different CPU. We -+ * must ensure this doesn't happen until the switch is completely -+ * finished. -+ * -+ * In particular, the load of prev->state in finish_task_switch() must -+ * happen before this. -+ * -+ * Pairs with the smp_cond_load_acquire() in try_to_wake_up(). -+ */ -+ smp_store_release(&prev->on_cpu, 0); -+} -+ -+static __always_inline void do_balance_callbacks(struct rq *rq, struct balance_callback *head) -+{ -+ void (*func)(struct rq *rq); -+ struct balance_callback *next; -+ -+ lockdep_assert_rq_held(rq); -+ -+ while (head) { -+ func = (void (*)(struct rq *))head->func; -+ next = head->next; -+ head->next = NULL; -+ head = next; -+ -+ func(rq); -+ } -+} -+ -+static void balance_push(struct rq *rq); -+ -+/* -+ * balance_push_callback is a right abuse of the callback interface and plays -+ * by significantly different rules. -+ * -+ * Where the normal balance_callback's purpose is to be ran in the same context -+ * that queued it (only later, when it's safe to drop rq->lock again), -+ * balance_push_callback is specifically targeted at __schedule(). -+ * -+ * This abuse is tolerated because it places all the unlikely/odd cases behind -+ * a single test, namely: rq->balance_callback == NULL. -+ */ -+struct balance_callback balance_push_callback = { -+ .next = NULL, -+ .func = balance_push, -+}; -+ -+static __always_inline struct balance_callback * -+__splice_balance_callbacks(struct rq *rq, bool split) -+{ -+ struct balance_callback *head = rq->balance_callback; -+ -+ if (likely(!head)) -+ return NULL; -+ -+ lockdep_assert_rq_held(rq); -+ /* -+ * Must not take balance_push_callback off the list when -+ * splice_balance_callbacks() and balance_callbacks() are not -+ * in the same rq->lock section. -+ * -+ * In that case it would be possible for __schedule() to interleave -+ * and observe the list empty. -+ */ -+ if (split && head == &balance_push_callback) -+ head = NULL; -+ else -+ rq->balance_callback = NULL; -+ -+ return head; -+} -+ -+struct balance_callback *splice_balance_callbacks(struct rq *rq) -+{ -+ return __splice_balance_callbacks(rq, true); -+} -+ -+__always_inline void __balance_callbacks(struct rq *rq, struct rq_flags *rf) -+{ -+ if (rf) -+ rq_unpin_lock(rq, rf); -+ do_balance_callbacks(rq, __splice_balance_callbacks(rq, false)); -+ if (rf) -+ rq_repin_lock(rq, rf); -+} -+ -+void balance_callbacks(struct rq *rq, struct balance_callback *head) -+{ -+ unsigned long flags; -+ -+ if (unlikely(head)) { -+ raw_spin_rq_lock_irqsave(rq, flags); -+ do_balance_callbacks(rq, head); -+ raw_spin_rq_unlock_irqrestore(rq, flags); -+ } -+} -+ -+static inline void -+prepare_lock_switch(struct rq *rq, struct task_struct *next, -+ struct rq_flags *rf) -+ __releases(__rq_lockp(rq)) -+ __acquires(__rq_lockp(this_rq())) -+{ -+ /* -+ * Since the runqueue lock will be released by the next -+ * task (which is an invalid locking op but in the case -+ * of the scheduler it's an obvious special-case), so we -+ * do an early lockdep release here: -+ */ -+ rq_unpin_lock(rq, rf); -+ spin_release(&__rq_lockp(rq)->dep_map, _THIS_IP_); -+#ifdef CONFIG_DEBUG_SPINLOCK -+ /* this is a valid case when another task releases the spinlock */ -+ rq_lockp(rq)->owner = next; -+#endif -+ /* -+ * Model the rq reference switcheroo. -+ */ -+ __release(__rq_lockp(rq)); -+ __acquire(__rq_lockp(this_rq())); -+} -+ -+static __always_inline void finish_lock_switch(struct rq *rq) -+ __releases(__rq_lockp(rq)) -+{ -+ /* -+ * If we are tracking spinlock dependencies then we have to -+ * fix up the runqueue lock - which gets 'carried over' from -+ * prev into current: -+ */ -+ spin_acquire(&__rq_lockp(rq)->dep_map, 0, 0, _THIS_IP_); -+ __balance_callbacks(rq, NULL); -+ hrtick_schedule_exit(rq); -+ raw_spin_rq_unlock_irq(rq); -+} -+ -+/* -+ * NOP if the arch has not defined these: -+ */ -+ -+#ifndef prepare_arch_switch -+# define prepare_arch_switch(next) do { } while (0) -+#endif -+ -+#ifndef finish_arch_post_lock_switch -+# define finish_arch_post_lock_switch() do { } while (0) -+#endif -+ -+static inline void kmap_local_sched_out(void) -+{ -+#ifdef CONFIG_KMAP_LOCAL -+ if (unlikely(current->kmap_ctrl.idx)) -+ __kmap_local_sched_out(); -+#endif -+} -+ -+static __always_inline void kmap_local_sched_in(void) -+{ -+#ifdef CONFIG_KMAP_LOCAL -+ if (unlikely(current->kmap_ctrl.idx)) -+ __kmap_local_sched_in(); -+#endif -+} -+ -+/** -+ * prepare_task_switch - prepare to switch tasks -+ * @rq: the runqueue preparing to switch -+ * @next: the task we are going to switch to. -+ * -+ * This is called with the rq lock held and interrupts off. It must -+ * be paired with a subsequent finish_task_switch after the context -+ * switch. -+ * -+ * prepare_task_switch sets up locking and calls architecture specific -+ * hooks. -+ */ -+static inline void -+prepare_task_switch(struct rq *rq, struct task_struct *prev, -+ struct task_struct *next) -+ __must_hold(__rq_lockp(rq)) -+{ -+ kcov_prepare_switch(prev); -+ sched_info_switch(rq, prev, next); -+ perf_event_task_sched_out(prev, next); -+ fire_sched_out_preempt_notifiers(prev, next); -+ kmap_local_sched_out(); -+ prepare_task(next); -+ prepare_arch_switch(next); -+} -+ -+/** -+ * finish_task_switch - clean up after a task-switch -+ * @rq: runqueue associated with task-switch -+ * @prev: the thread we just switched away from. -+ * -+ * finish_task_switch must be called after the context switch, paired -+ * with a prepare_task_switch call before the context switch. -+ * finish_task_switch will reconcile locking set up by prepare_task_switch, -+ * and do any other architecture-specific cleanup actions. -+ * -+ * Note that we may have delayed dropping an mm in context_switch(). If -+ * so, we finish that here outside of the runqueue lock. (Doing it -+ * with the lock held can cause deadlocks; see schedule() for -+ * details.) -+ * -+ * The context switch have flipped the stack from under us and restored the -+ * local variables which were saved when this task called schedule() in the -+ * past. 'prev == current' is still correct but we need to recalculate this_rq -+ * because prev may have moved to another CPU. -+ */ -+static __always_inline struct rq *finish_task_switch(struct task_struct *prev) -+ __releases(__rq_lockp(this_rq())) -+{ -+ struct rq *rq = this_rq(); -+ struct mm_struct *mm = rq->prev_mm; -+ unsigned int prev_state; -+ -+ /* -+ * The previous task will have left us with a preempt_count of 2 -+ * because it left us after: -+ * -+ * schedule() -+ * preempt_disable(); // 1 -+ * __schedule() -+ * raw_spin_lock_irq(&rq->lock) // 2 -+ * -+ * Also, see FORK_PREEMPT_COUNT. -+ */ -+ if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET, -+ "corrupted preempt_count: %s/%d/0x%x\n", -+ current->comm, current->pid, preempt_count())) -+ preempt_count_set(FORK_PREEMPT_COUNT); -+ -+ rq->prev_mm = NULL; -+ -+ /* -+ * A task struct has one reference for the use as "current". -+ * If a task dies, then it sets TASK_DEAD in tsk->state and calls -+ * schedule one last time. The schedule call will never return, and -+ * the scheduled task must drop that reference. -+ * -+ * We must observe prev->state before clearing prev->on_cpu (in -+ * finish_task), otherwise a concurrent wakeup can get prev -+ * running on another CPU and we could rave with its RUNNING -> DEAD -+ * transition, resulting in a double drop. -+ */ -+ prev_state = READ_ONCE(prev->__state); -+ vtime_task_switch(prev); -+ perf_event_task_sched_in(prev, current); -+ finish_task(prev); -+ tick_nohz_task_switch(); -+ finish_lock_switch(rq); -+ finish_arch_post_lock_switch(); -+ kcov_finish_switch(current); -+ /* -+ * kmap_local_sched_out() is invoked with rq::lock held and -+ * interrupts disabled. There is no requirement for that, but the -+ * sched out code does not have an interrupt enabled section. -+ * Restoring the maps on sched in does not require interrupts being -+ * disabled either. -+ */ -+ kmap_local_sched_in(); -+ -+ /* -+ * Any cached block-layer timestamp (plug->cur_ktime) is stale now, -+ * invalidate it. -+ */ -+ blk_plug_invalidate_ts(); -+ -+ fire_sched_in_preempt_notifiers(current); -+ /* -+ * When switching through a kernel thread, the loop in -+ * membarrier_{private,global}_expedited() may have observed that -+ * kernel thread and not issued an IPI. It is therefore possible to -+ * schedule between user->kernel->user threads without passing though -+ * switch_mm(). Membarrier requires a barrier after storing to -+ * rq->curr, before returning to userspace, so provide them here: -+ * -+ * - a full memory barrier for {PRIVATE,GLOBAL}_EXPEDITED, implicitly -+ * provided by mmdrop_lazy_tlb(), -+ * - a sync_core for SYNC_CORE. -+ */ -+ if (mm) { -+ membarrier_mm_sync_core_before_usermode(mm); -+ mmdrop_lazy_tlb_sched(mm); -+ } -+ if (unlikely(prev_state == TASK_DEAD)) { -+ cgroup_task_dead(prev); -+ -+ /* Task is done with its stack. */ -+ put_task_stack(prev); -+ -+ put_task_struct_rcu_user(prev); -+ } -+ -+ return rq; -+} -+ -+/** -+ * schedule_tail - first thing a freshly forked thread must call. -+ * @prev: the thread we just switched away from. -+ */ -+asmlinkage __visible void schedule_tail(struct task_struct *prev) -+ __releases(__rq_lockp(this_rq())) -+{ -+ /* -+ * New tasks start with FORK_PREEMPT_COUNT, see there and -+ * finish_task_switch() for details. -+ * -+ * finish_task_switch() will drop rq->lock() and lower preempt_count -+ * and the preempt_enable() will end up enabling preemption (on -+ * PREEMPT_COUNT kernels). -+ */ -+ -+ finish_task_switch(prev); -+ /* -+ * This is a special case: the newly created task has just -+ * switched the context for the first time. It is returning from -+ * schedule for the first time in this path. -+ */ -+ trace_sched_exit_tp(true); -+ preempt_enable(); -+ -+ if (current->set_child_tid) -+ put_user(task_pid_vnr(current), current->set_child_tid); -+ -+ calculate_sigpending(); -+} -+ -+/* -+ * context_switch - switch to the new MM and the new thread's register state. -+ */ -+static __always_inline struct rq * -+context_switch(struct rq *rq, struct task_struct *prev, -+ struct task_struct *next, struct rq_flags *rf) -+ __releases(__rq_lockp(rq)) -+{ -+ prepare_task_switch(rq, prev, next); -+ -+ /* -+ * For paravirt, this is coupled with an exit in switch_to to -+ * combine the page table reload and the switch backend into -+ * one hypercall. -+ */ -+ arch_start_context_switch(prev); -+ -+ /* -+ * kernel -> kernel lazy + transfer active -+ * user -> kernel lazy + mmgrab_lazy_tlb() active -+ * -+ * kernel -> user switch + mmdrop_lazy_tlb() active -+ * user -> user switch -+ */ -+ if (!next->mm) { // to kernel -+ enter_lazy_tlb(prev->active_mm, next); -+ -+ next->active_mm = prev->active_mm; -+ if (prev->mm) // from user -+ mmgrab_lazy_tlb(prev->active_mm); -+ else -+ prev->active_mm = NULL; -+ } else { // to user -+ membarrier_switch_mm(rq, prev->active_mm, next->mm); -+ /* -+ * sys_membarrier() requires an smp_mb() between setting -+ * rq->curr / membarrier_switch_mm() and returning to userspace. -+ * -+ * The below provides this either through switch_mm(), or in -+ * case 'prev->active_mm == next->mm' through -+ * finish_task_switch()'s mmdrop(). -+ */ -+ switch_mm_irqs_off(prev->active_mm, next->mm, next); -+ lru_gen_use_mm(next->mm); -+ -+ if (!prev->mm) { // from kernel -+ /* will mmdrop_lazy_tlb() in finish_task_switch(). */ -+ rq->prev_mm = prev->active_mm; -+ prev->active_mm = NULL; -+ } -+ } -+ -+ mm_cid_switch_to(prev, next); -+ -+ /* -+ * Tell rseq that the task was scheduled in. Must be after -+ * switch_mm_cid() to get the TIF flag set. -+ */ -+ rseq_sched_switch_event(next); -+ -+ prepare_lock_switch(rq, next, rf); -+ -+ /* Here we just switch the register state and the stack. */ -+ switch_to(prev, next, prev); -+ barrier(); -+ -+ return finish_task_switch(prev); -+} -+ -+/* -+ * nr_running, nr_uninterruptible and nr_context_switches: -+ * -+ * externally visible scheduler statistics: current number of runnable -+ * threads, total number of context switches performed since bootup. -+ */ -+unsigned int nr_running(void) -+{ -+ unsigned int i, sum = 0; -+ -+ for_each_online_cpu(i) -+ sum += cpu_rq(i)->nr_running; -+ -+ return sum; -+} -+ -+/* -+ * Check if only the current task is running on the CPU. -+ * -+ * Caution: this function does not check that the caller has disabled -+ * preemption, thus the result might have a time-of-check-to-time-of-use -+ * race. The caller is responsible to use it correctly, for example: -+ * -+ * - from a non-preemptible section (of course) -+ * -+ * - from a thread that is bound to a single CPU -+ * -+ * - in a loop with very short iterations (e.g. a polling loop) -+ */ -+bool single_task_running(void) -+{ -+ return raw_rq()->nr_running == 1; -+} -+EXPORT_SYMBOL(single_task_running); -+ -+unsigned long long nr_context_switches_cpu(int cpu) -+{ -+ return cpu_rq(cpu)->nr_switches; -+} -+ -+unsigned long long nr_context_switches(void) -+{ -+ int i; -+ unsigned long long sum = 0; -+ -+ for_each_possible_cpu(i) -+ sum += cpu_rq(i)->nr_switches; -+ -+ return sum; -+} -+ -+/* -+ * Consumers of these two interfaces, like for example the cpuidle menu -+ * governor, are using nonsensical data. Preferring shallow idle state selection -+ * for a CPU that has IO-wait which might not even end up running the task when -+ * it does become runnable. -+ */ -+ -+unsigned int nr_iowait_cpu(int cpu) -+{ -+ return atomic_read(&cpu_rq(cpu)->nr_iowait); -+} -+ -+/* -+ * IO-wait accounting, and how it's mostly bollocks (on SMP). -+ * -+ * The idea behind IO-wait account is to account the idle time that we could -+ * have spend running if it were not for IO. That is, if we were to improve the -+ * storage performance, we'd have a proportional reduction in IO-wait time. -+ * -+ * This all works nicely on UP, where, when a task blocks on IO, we account -+ * idle time as IO-wait, because if the storage were faster, it could've been -+ * running and we'd not be idle. -+ * -+ * This has been extended to SMP, by doing the same for each CPU. This however -+ * is broken. -+ * -+ * Imagine for instance the case where two tasks block on one CPU, only the one -+ * CPU will have IO-wait accounted, while the other has regular idle. Even -+ * though, if the storage were faster, both could've ran at the same time, -+ * utilising both CPUs. -+ * -+ * This means, that when looking globally, the current IO-wait accounting on -+ * SMP is a lower bound, by reason of under accounting. -+ * -+ * Worse, since the numbers are provided per CPU, they are sometimes -+ * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly -+ * associated with any one particular CPU, it can wake to another CPU than it -+ * blocked on. This means the per CPU IO-wait number is meaningless. -+ * -+ * Task CPU affinities can make all that even more 'interesting'. -+ */ -+ -+unsigned int nr_iowait(void) -+{ -+ unsigned int i, sum = 0; -+ -+ for_each_possible_cpu(i) -+ sum += nr_iowait_cpu(i); -+ -+ return sum; -+} -+ -+/* -+ * sched_exec - execve() is a valuable balancing opportunity, because at -+ * this point the task has the smallest effective memory and cache -+ * footprint. -+ */ -+void sched_exec(void) -+{ -+} -+ -+DEFINE_PER_CPU(struct kernel_stat, kstat); -+DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat) = { -+#ifdef CONFIG_NO_HZ_COMMON -+ .idle_sleeptime_seq = SEQCNT_ZERO(kernel_cpustat.idle_sleeptime_seq) -+#endif -+}; -+ -+EXPORT_PER_CPU_SYMBOL(kstat); -+EXPORT_PER_CPU_SYMBOL(kernel_cpustat); -+ -+static __always_inline void update_curr(struct rq *rq, struct task_struct *p) -+{ -+ s64 ns = rq->clock_task - p->last_ran; -+ -+ if (unlikely(ns <= 0)) -+ return; -+ -+ p->sched_time += ns; -+ cgroup_account_cputime(p, ns); -+ account_group_exec_runtime(p, ns); -+ -+ if (SCHED_FIFO != p->policy) -+ p->time_slice -= ns; -+ p->last_ran = rq->clock_task; -+} -+ -+/* -+ * Return accounted runtime for the task. -+ * Return separately the current's pending runtime that have not been -+ * accounted yet. -+ */ -+unsigned long long task_sched_runtime(struct task_struct *p) -+{ -+ struct rq_flags rf; -+ struct rq *rq; -+ u64 ns; -+ -+#ifdef CONFIG_64BIT -+ /* -+ * 64-bit doesn't need locks to atomically read a 64-bit value. -+ * So we have a optimization chance when the task's delta_exec is 0. -+ * Reading ->on_cpu is racy, but this is OK. -+ * -+ * If we race with it leaving CPU, we'll take a lock. So we're correct. -+ * If we race with it entering CPU, unaccounted time is 0. This is -+ * indistinguishable from the read occurring a few cycles earlier. -+ * If we see ->on_cpu without ->on_rq, the task is leaving, and has -+ * been accounted, so we're correct here as well. -+ */ -+ if (!p->on_cpu || !task_on_rq_queued(p)) -+ return tsk_seruntime(p); -+#endif -+ -+ rq = task_rq_lock(p, &rf); -+ /* -+ * Must be ->curr _and_ ->on_rq. If dequeued, we would -+ * project cycles that may never be accounted to this -+ * thread, breaking clock_gettime(). -+ */ -+ if (p == rq->curr && task_on_rq_queued(p)) { -+ update_rq_clock(rq); -+ update_curr(rq, p); -+ } -+ ns = tsk_seruntime(p); -+ task_rq_unlock(rq, p, &rf); -+ -+ return ns; -+} -+ -+/* This manages tasks that have run out of timeslice during a scheduler_tick */ -+static inline void scheduler_task_tick(struct rq *rq) -+{ -+ struct task_struct *p = rq->curr; -+ -+ if (is_idle_task(p)) -+ return; -+ -+ update_curr(rq, p); -+ cpufreq_update_util(rq, 0); -+ -+ /* -+ * Tasks have less than RESCHED_NS of time slice left they will be -+ * rescheduled. -+ */ -+ if (p->time_slice >= RESCHED_NS) -+ return; -+ set_tsk_need_resched(p); -+ set_preempt_need_resched(); -+} -+ -+static u64 cpu_resched_latency(struct rq *rq) -+{ -+ int latency_warn_ms = READ_ONCE(sysctl_resched_latency_warn_ms); -+ u64 resched_latency, now = rq_clock(rq); -+ static bool warned_once; -+ -+ if (sysctl_resched_latency_warn_once && warned_once) -+ return 0; -+ -+ if (!need_resched() || !latency_warn_ms) -+ return 0; -+ -+ if (system_state == SYSTEM_BOOTING) -+ return 0; -+ -+ if (!rq->last_seen_need_resched_ns) { -+ rq->last_seen_need_resched_ns = now; -+ rq->ticks_without_resched = 0; -+ return 0; -+ } -+ -+ rq->ticks_without_resched++; -+ resched_latency = now - rq->last_seen_need_resched_ns; -+ if (resched_latency <= latency_warn_ms * NSEC_PER_MSEC) -+ return 0; -+ -+ warned_once = true; -+ -+ return resched_latency; -+} -+ -+static int __init setup_resched_latency_warn_ms(char *str) -+{ -+ long val; -+ -+ if ((kstrtol(str, 0, &val))) { -+ pr_warn("Unable to set resched_latency_warn_ms\n"); -+ return 1; -+ } -+ -+ sysctl_resched_latency_warn_ms = val; -+ return 1; -+} -+__setup("resched_latency_warn_ms=", setup_resched_latency_warn_ms); -+ -+#ifdef CONFIG_SCHED_SMT -+static void smt_balance_kick(struct rq *rq) -+{ -+ int cpu = cpu_of(rq), sibling, target; -+ struct rq *target_rq; -+ cpumask_t mask; -+ -+ if (rq->nr_running != 1 || cpumask_empty(sched_idle_mask) || -+ !cpumask_test_cpu(cpu, &sched_smt_mask)) -+ return; -+ -+ for_each_cpu_and(sibling, cpu_smt_mask(cpu), &sched_smt_mask) -+ if (sibling != cpu && -+ (cpumask_test_cpu(sibling, sched_idle_mask) || -+ cpumask_test_cpu(sibling, &sched_rq_pending_mask))) -+ return; -+ -+ cpumask_copy(&mask, sched_sg_idle_mask); -+ if (per_cpu(sched_cpu_topo, cpu) == CPU_TOPOLOGY_PCORE && -+ cpumask_empty(sched_pcore_idle_mask)) -+ cpumask_or(&mask, &mask, sched_ecore_idle_mask); -+ -+ /* -+ * Other CPUs can clear the last idle core while we hold only this -+ * rq's lock. Select from a nonempty snapshot, restricted to CPUs the -+ * task can use, rather than looking up a CPU in the live idle mask. -+ */ -+ if (!cpumask_and(&mask, &mask, rq->curr->cpus_ptr) || -+ !cpumask_and(&mask, &mask, cpu_active_mask)) -+ return; -+ -+ if (sched_smt_group_paired(rq, cpu)) -+ return; -+ -+ target = best_mask_cpu(cpu, &mask); -+ if (target >= nr_cpu_ids) -+ return; -+ -+ target_rq = cpu_rq(target); -+ if (raw_spin_rq_trylock(target_rq)) { -+ if (target_rq->online && idle_rq(target_rq) && -+ (cpumask_test_cpu(target, sched_sg_idle_mask) || -+ cpumask_test_cpu(target, sched_ecore_idle_mask))) { -+ /* -+ * The target queues its own callback in __schedule(), -+ * including the SM_IDLE fast path. Callbacks must not -+ * remain queued across an rq unlock/relock boundary. -+ */ -+ resched_curr(target_rq); -+ } -+ raw_spin_rq_unlock(target_rq); -+ } -+} -+#else -+static inline void smt_balance_kick(struct rq *rq) { } -+#endif -+ -+/* -+ * This function gets called by the timer code, with HZ frequency. -+ * We call it with interrupts disabled. -+ */ -+void sched_tick(void) -+{ -+ int cpu __maybe_unused = smp_processor_id(); -+ struct rq *rq = cpu_rq(cpu); -+ /* scheduler accounting goes to the donor task */ -+ struct task_struct *curr; -+ struct rq_flags rf; -+ u64 resched_latency; -+ -+ if (housekeeping_cpu(cpu, HK_TYPE_KERNEL_NOISE)) -+ arch_scale_freq_tick(); -+ -+ sched_clock_tick(); -+ -+ rq_lock(rq, &rf); -+ curr = rq->curr; -+ -+ psi_account_irqtime(rq, curr, NULL); -+ update_rq_clock(rq); -+ -+ if (dynamic_preempt_lazy() && tif_test_bit(TIF_NEED_RESCHED_LAZY)) -+ resched_curr(rq); -+ -+ scheduler_task_tick(rq); -+ smt_balance_kick(rq); -+ if (sched_feat(LATENCY_WARN)) -+ resched_latency = cpu_resched_latency(rq); -+ calc_global_load_tick(rq); -+ -+ rq_unlock(rq, &rf); -+ -+ if (sched_feat(LATENCY_WARN) && resched_latency) -+ resched_latency_warn(cpu, resched_latency); -+ -+ perf_event_task_tick(); -+ -+ if (curr->flags & PF_WQ_WORKER) -+ wq_worker_tick(curr); -+} -+ -+#ifdef CONFIG_NO_HZ_FULL -+ -+struct tick_work { -+ int cpu; -+ atomic_t state; -+ struct delayed_work work; -+}; -+/* Values for ->state, see diagram below. */ -+#define TICK_SCHED_REMOTE_OFFLINE 0 -+#define TICK_SCHED_REMOTE_OFFLINING 1 -+#define TICK_SCHED_REMOTE_RUNNING 2 -+ -+/* -+ * State diagram for ->state: -+ * -+ * -+ * TICK_SCHED_REMOTE_OFFLINE -+ * | ^ -+ * | | -+ * | | sched_tick_remote() -+ * | | -+ * | | -+ * +--TICK_SCHED_REMOTE_OFFLINING -+ * | ^ -+ * | | -+ * sched_tick_start() | | sched_tick_stop() -+ * | | -+ * V | -+ * TICK_SCHED_REMOTE_RUNNING -+ * -+ * -+ * Other transitions get WARN_ON_ONCE(), except that sched_tick_remote() -+ * and sched_tick_start() are happy to leave the state in RUNNING. -+ */ -+ -+static struct tick_work __percpu *tick_work_cpu; -+ -+static void sched_tick_remote(struct work_struct *work) -+{ -+ struct delayed_work *dwork = to_delayed_work(work); -+ struct tick_work *twork = container_of(dwork, struct tick_work, work); -+ int cpu = twork->cpu; -+ struct rq *rq = cpu_rq(cpu); -+ int os; -+ -+ /* -+ * Handle the tick only if it appears the remote CPU is running in full -+ * dynticks mode. The check is racy by nature, but missing a tick or -+ * having one too much is no big deal because the scheduler tick updates -+ * statistics and checks timeslices in a time-independent way, regardless -+ * of when exactly it is running. -+ */ -+ if (tick_nohz_tick_stopped_cpu(cpu)) { -+ guard(rq_lock_irq)(rq); -+ struct task_struct *curr = rq->curr; -+ -+ if (cpu_online(cpu)) { -+ update_rq_clock(rq); -+ -+ if (!is_idle_task(curr)) { -+ /* -+ * Make sure the next tick runs within a -+ * reasonable amount of time. -+ */ -+ u64 delta = rq_clock_task(rq) - curr->last_ran; -+ WARN_ON_ONCE(delta > (u64)NSEC_PER_SEC * 30); -+ } -+ scheduler_task_tick(rq); -+ smt_balance_kick(rq); -+ -+ calc_load_nohz_remote(rq); -+ } -+ } -+ -+ /* -+ * Run the remote tick once per second (1Hz). This arbitrary -+ * frequency is large enough to avoid overload but short enough -+ * to keep scheduler internal stats reasonably up to date. But -+ * first update state to reflect hotplug activity if required. -+ */ -+ os = atomic_fetch_add_unless(&twork->state, -1, TICK_SCHED_REMOTE_RUNNING); -+ WARN_ON_ONCE(os == TICK_SCHED_REMOTE_OFFLINE); -+ if (os == TICK_SCHED_REMOTE_RUNNING) -+ queue_delayed_work(system_dfl_wq, dwork, HZ); -+} -+ -+static void sched_tick_start(int cpu) -+{ -+ int os; -+ struct tick_work *twork; -+ -+ if (housekeeping_cpu(cpu, HK_TYPE_KERNEL_NOISE)) -+ return; -+ -+ WARN_ON_ONCE(!tick_work_cpu); -+ -+ twork = per_cpu_ptr(tick_work_cpu, cpu); -+ os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_RUNNING); -+ WARN_ON_ONCE(os == TICK_SCHED_REMOTE_RUNNING); -+ if (os == TICK_SCHED_REMOTE_OFFLINE) { -+ twork->cpu = cpu; -+ INIT_DELAYED_WORK(&twork->work, sched_tick_remote); -+ queue_delayed_work(system_dfl_wq, &twork->work, HZ); -+ } -+} -+ -+#ifdef CONFIG_HOTPLUG_CPU -+static void sched_tick_stop(int cpu) -+{ -+ struct tick_work *twork; -+ int os; -+ -+ if (housekeeping_cpu(cpu, HK_TYPE_KERNEL_NOISE)) -+ return; -+ -+ WARN_ON_ONCE(!tick_work_cpu); -+ -+ twork = per_cpu_ptr(tick_work_cpu, cpu); -+ /* There cannot be competing actions, but don't rely on stop-machine. */ -+ os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_OFFLINING); -+ WARN_ON_ONCE(os != TICK_SCHED_REMOTE_RUNNING); -+ /* Don't cancel, as this would mess up the state machine. */ -+} -+#endif /* CONFIG_HOTPLUG_CPU */ -+ -+int __init sched_tick_offload_init(void) -+{ -+ tick_work_cpu = alloc_percpu(struct tick_work); -+ BUG_ON(!tick_work_cpu); -+ return 0; -+} -+ -+#else /* !CONFIG_NO_HZ_FULL: */ -+static inline void sched_tick_start(int cpu) { } -+static inline void sched_tick_stop(int cpu) { } -+#endif /* !CONFIG_NO_HZ_FULL */ -+ -+#if defined(CONFIG_PREEMPTION) && (defined(CONFIG_DEBUG_PREEMPT) || \ -+ defined(CONFIG_PREEMPT_TRACER)) -+/* -+ * If the value passed in is equal to the current preempt count -+ * then we just disabled preemption. Start timing the latency. -+ */ -+static inline void preempt_latency_start(int val) -+{ -+ if (preempt_count() == val) { -+ unsigned long ip = get_lock_parent_ip(); -+#ifdef CONFIG_DEBUG_PREEMPT -+ current->preempt_disable_ip = ip; -+#endif -+ trace_preempt_off(CALLER_ADDR0, ip); -+ } -+} -+ -+void preempt_count_add(int val) -+{ -+#ifdef CONFIG_DEBUG_PREEMPT -+ /* -+ * Underflow? -+ * Cannot detect underflow based on the current preempt_count() value -+ * if using HAS_SEPARATE_PREEMPT_RESCHED_BITS because preempt count takes all 32 -+ * bits. -+ */ -+ if (!IS_ENABLED(CONFIG_HAS_SEPARATE_PREEMPT_RESCHED_BITS) && -+ DEBUG_LOCKS_WARN_ON((preempt_count() < 0))) -+ return; -+#endif -+ __preempt_count_add(val); -+#ifdef CONFIG_DEBUG_PREEMPT -+ /* -+ * Spinlock count overflowing soon? -+ */ -+ DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >= -+ PREEMPT_MASK - 10); -+#endif -+ preempt_latency_start(val); -+} -+EXPORT_SYMBOL(preempt_count_add); -+NOKPROBE_SYMBOL(preempt_count_add); -+ -+/* -+ * If the value passed in equals to the current preempt count -+ * then we just enabled preemption. Stop timing the latency. -+ */ -+static inline void preempt_latency_stop(int val) -+{ -+ if (preempt_count() == val) -+ trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip()); -+} -+ -+void preempt_count_sub(int val) -+{ -+#ifdef CONFIG_DEBUG_PREEMPT -+ /* -+ * Underflow? -+ */ -+ unsigned int uval = val; -+ unsigned int pc = preempt_count(); -+ -+ if (DEBUG_LOCKS_WARN_ON(pc - uval > pc)) -+ return; -+ /* -+ * Is the spinlock portion underflowing? -+ */ -+ if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) && -+ !(preempt_count() & PREEMPT_MASK))) -+ return; -+#endif -+ -+ preempt_latency_stop(val); -+ __preempt_count_sub(val); -+} -+EXPORT_SYMBOL(preempt_count_sub); -+NOKPROBE_SYMBOL(preempt_count_sub); -+ -+#else -+static inline void preempt_latency_start(int val) { } -+static inline void preempt_latency_stop(int val) { } -+#endif -+ -+static inline unsigned long get_preempt_disable_ip(struct task_struct *p) -+{ -+#ifdef CONFIG_DEBUG_PREEMPT -+ return p->preempt_disable_ip; -+#else -+ return 0; -+#endif -+} -+ -+/* -+ * Print scheduling while atomic bug: -+ */ -+static noinline void __schedule_bug(struct task_struct *prev) -+{ -+ /* Save this before calling printk(), since that will clobber it */ -+ unsigned long preempt_disable_ip = get_preempt_disable_ip(current); -+ -+ if (oops_in_progress) -+ return; -+ -+ printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n", -+ prev->comm, prev->pid, preempt_count()); -+ -+ debug_show_held_locks(prev); -+ print_modules(); -+ if (irqs_disabled()) -+ print_irqtrace_events(prev); -+ if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)) { -+ pr_err("Preemption disabled at:"); -+ print_ip_sym(KERN_ERR, preempt_disable_ip); -+ } -+ check_panic_on_warn("scheduling while atomic"); -+ -+ dump_stack(); -+ add_taint(TAINT_WARN, LOCKDEP_STILL_OK); -+} -+ -+/* -+ * Various schedule()-time debugging checks and statistics: -+ */ -+static inline void schedule_debug(struct task_struct *prev, bool preempt) -+{ -+#ifdef CONFIG_SCHED_STACK_END_CHECK -+ if (task_stack_end_corrupted(prev)) -+ panic("corrupted stack end detected inside scheduler\n"); -+ -+ if (task_scs_end_corrupted(prev)) -+ panic("corrupted shadow stack detected inside scheduler\n"); -+#endif -+ -+#ifdef CONFIG_DEBUG_ATOMIC_SLEEP -+ if (!preempt && READ_ONCE(prev->__state) && prev->non_block_count) { -+ printk(KERN_ERR "BUG: scheduling in a non-blocking section: %s/%d/%i\n", -+ prev->comm, prev->pid, prev->non_block_count); -+ dump_stack(); -+ add_taint(TAINT_WARN, LOCKDEP_STILL_OK); -+ } -+#endif -+ -+ if (unlikely(in_atomic_preempt_off())) { -+ __schedule_bug(prev); -+ preempt_count_set(PREEMPT_DISABLED); -+ } -+ rcu_sleep_check(); -+ WARN_ON_ONCE(ct_state() == CT_STATE_USER); -+ -+ profile_hit(SCHED_PROFILING, __builtin_return_address(0)); -+ -+ schedstat_inc(this_rq()->sched_count); -+} -+ -+#ifdef ALT_SCHED_DEBUG -+void alt_sched_debug(void) -+{ -+ pr_info("sched: pending: 0x%04lx, idle: 0x%04lx, sg_idle: 0x%04lx\n", -+ sched_rq_pending_mask.bits[0], -+ sched_idle_mask->bits[0], -+ sched_sg_idle_mask->bits[0]); -+ pr_info("sched: pcore_idle: 0x%04lx, ecore_idle: 0x%04lx\n", -+ sched_pcore_idle_mask->bits[0], -+ sched_ecore_idle_mask->bits[0]); -+} -+#endif -+ -+ -+#if defined(CONFIG_PREEMPT_RT) || defined(CONFIG_ZEN_INTERACTIVE) -+#define SCHED_NR_MIGRATE_BREAK 8 -+#else -+#define SCHED_NR_MIGRATE_BREAK 32 -+#endif -+ -+__read_mostly unsigned int sysctl_sched_nr_migrate = SCHED_NR_MIGRATE_BREAK; -+ -+/* -+ * Migrate pending tasks in @rq to @dest_cpu -+ */ -+static inline int -+migrate_pending_tasks(struct rq *rq, struct rq *dest_rq, const int dest_cpu) -+{ -+ struct task_struct *p, *skip = rq->curr; -+ int nr_migrated = 0; -+ int nr_tries = min(rq->nr_running / 2, sysctl_sched_nr_migrate); -+ -+ /* WA to check rq->curr is still on rq */ -+ if (!task_on_rq_queued(skip)) -+ return 0; -+ -+ while (skip != rq->idle && nr_tries && -+ (p = sched_rq_next_task(skip, rq)) != rq->idle) { -+ skip = sched_rq_next_task(p, rq); -+ if (cpumask_test_cpu(dest_cpu, p->cpus_ptr)) { -+ psi_dequeue(p, 0); -+ __SCHED_DEQUEUE_TASK(p, rq, ); -+ set_task_cpu(p, dest_cpu); -+ sched_task_sanity_check(p, dest_rq); -+ __SCHED_ENQUEUE_TASK(p, dest_rq, ); -+ psi_enqueue(p, ENQUEUE_MIGRATED); -+ nr_migrated++; -+ } -+ nr_tries--; -+ } -+ -+ return nr_migrated; -+} -+ -+static inline int take_other_rq_tasks(struct rq *rq, int cpu) -+{ -+ cpumask_t *topo_masks, *topo_mask, *end_mask, chk; -+ -+ if (unlikely(!rq->online)) -+ return 0; -+ -+ if (cpumask_empty(&sched_rq_pending_mask)) -+ return 0; -+ -+ topo_masks = per_cpu(sched_cpu_topo_masks, cpu); -+ topo_mask = topo_masks; -+ end_mask = per_cpu(sched_cpu_topo_end_mask, cpu); -+ do { -+ int i; -+ -+ if (sched_cpu_topo_level_repeats(topo_masks, topo_mask)) -+ continue; -+ -+ if (!cpumask_and(&chk, &sched_rq_pending_mask, topo_mask)) -+ continue; -+ -+ for_each_cpu_wrap(i, &chk, cpu) { -+ int nr_migrated; -+ struct rq *src_rq; -+ -+ src_rq = cpu_rq(i); -+ if (!do_raw_spin_trylock(rq_lockp(src_rq))) -+ continue; -+ spin_acquire(&rq_lockp(src_rq)->dep_map, -+ SINGLE_DEPTH_NESTING, 1, _RET_IP_); -+ -+ if ((nr_migrated = migrate_pending_tasks(src_rq, rq, cpu))) { -+ sub_nr_running(src_rq, nr_migrated); -+ update_sched_preempt_mask(src_rq); -+ -+ spin_release(&rq_lockp(src_rq)->dep_map, _RET_IP_); -+ do_raw_spin_unlock(rq_lockp(src_rq)); -+ -+ add_nr_running(rq, nr_migrated); -+ -+ update_sched_preempt_mask(rq); -+ cpufreq_update_util(rq, 0); -+ -+ return 1; -+ } -+ -+ spin_release(&rq_lockp(src_rq)->dep_map, _RET_IP_); -+ do_raw_spin_unlock(rq_lockp(src_rq)); -+ } -+ } while (++topo_mask < end_mask); -+ -+ return 0; -+} -+ -+static inline void time_slice_expired(struct task_struct *p, struct rq *rq) -+{ -+ p->time_slice = sysctl_sched_base_slice; -+ -+ sched_task_renew(p, rq); -+ -+ if (SCHED_FIFO != p->policy && task_on_rq_queued(p)) -+ requeue_task(p, rq, 0); -+} -+ -+static inline int balance_select_task_rq(struct task_struct *p, cpumask_t *avail_mask) -+{ -+ cpumask_t mask; -+ -+ if (!preempt_mask_check(&mask, avail_mask, task_sched_prio(p))) -+ return -1; -+ -+ if (cpumask_and(&mask, &mask, p->cpus_ptr)) -+ return best_mask_cpu(task_cpu(p), &mask); -+ -+ return task_cpu(p); -+} -+ -+static inline void -+__move_queued_task(struct rq *rq, struct task_struct *p, struct rq *dest_rq, int dest_cpu) -+{ -+ WRITE_ONCE(p->on_rq, TASK_ON_RQ_MIGRATING); -+ dequeue_task(p, rq, 0); -+ set_task_cpu(p, dest_cpu); -+ -+ sched_task_sanity_check(p, dest_rq); -+ enqueue_task(p, dest_rq, ENQUEUE_MIGRATED); -+ WRITE_ONCE(p->on_rq, TASK_ON_RQ_QUEUED); -+ wakeup_preempt(dest_rq); -+} -+ -+static inline void prio_balance(struct rq *rq, const int cpu) -+{ -+ struct task_struct *p, *next; -+ cpumask_t mask; -+ int nr_tries = min(rq->nr_running / 2, sysctl_sched_nr_migrate); -+ -+ if (!rq->online) -+ return; -+ -+ if (0 == rq->prio_balance_time) -+ return; -+ -+ if (rq->clock - rq->prio_balance_time < sysctl_sched_base_slice << 1) -+ return; -+ -+ if (!cpumask_empty(sched_idle_mask)) -+ return; -+ -+ rq->prio_balance_time = rq->clock; -+ -+ cpumask_copy(&mask, cpu_active_mask); -+ __cpumask_clear_cpu(cpu, &mask); -+ -+ p = sched_rq_next_task(rq->curr, rq); -+ while (p != rq->idle && nr_tries--) { -+ next = sched_rq_next_task(p, rq); -+ if (!is_migration_disabled(p)) { -+ int dest_cpu; -+ -+ dest_cpu = balance_select_task_rq(p, &mask); -+ if (dest_cpu < 0) -+ return; -+ -+ if (cpu != dest_cpu) { -+ struct rq *dest_rq = cpu_rq(dest_cpu); -+ -+ if (do_raw_spin_trylock(rq_lockp(dest_rq))) { -+ __cpumask_clear_cpu(dest_cpu, &mask); -+ -+ spin_acquire(&rq_lockp(dest_rq)->dep_map, -+ SINGLE_DEPTH_NESTING, 1, _RET_IP_); -+ -+ __move_queued_task(rq, p, dest_rq, dest_cpu); -+ -+ spin_release(&rq_lockp(dest_rq)->dep_map, _RET_IP_); -+ do_raw_spin_unlock(rq_lockp(dest_rq)); -+ } -+ } -+ } -+ p = next; -+ } -+} -+ -+/* -+ * Timeslices below RESCHED_NS are considered as good as expired as there's no -+ * point rescheduling when there's so little time left. -+ */ -+static inline void check_curr(struct task_struct *p, struct rq *rq) -+{ -+ if (unlikely(rq->idle == p)) -+ return; -+ -+ update_curr(rq, p); -+ -+ if (p->time_slice < RESCHED_NS) -+ time_slice_expired(p, rq); -+} -+ -+static inline struct task_struct * -+choose_next_task(struct rq *rq, int cpu) -+ __must_hold(__rq_lockp(rq)) -+{ -+ struct task_struct *next = sched_rq_first_task(rq); -+ -+ if (next == rq->idle) { -+ if (!take_other_rq_tasks(rq, cpu)) { -+ sched_cpu_topology_balance(cpu, rq); -+ -+ schedstat_inc(rq->sched_goidle); -+ /*printk(KERN_INFO "sched: choose_next_task(%d) idle %px\n", cpu, next);*/ -+ return next; -+ } -+ next = sched_rq_first_task(rq); -+ } -+ if (SCHED_FIFO != next->policy) -+ hrtick_start(rq, next->time_slice); -+ /*printk(KERN_INFO "sched: choose_next_task(%d) next %px\n", cpu, next);*/ -+ return next; -+} -+ -+/* -+ * Constants for the sched_mode argument of __schedule(). -+ * -+ * The mode argument allows RT enabled kernels to differentiate a -+ * preemption from blocking on an 'sleeping' spin/rwlock. -+ */ -+ #define SM_IDLE (-1) -+ #define SM_NONE 0 -+ #define SM_PREEMPT 1 -+ #define SM_RTLOCK_WAIT 2 -+ -+/* -+ * Helper function for __schedule() -+ * -+ * If a task does not have signals pending, deactivate it -+ * Otherwise marks the task's __state as RUNNING -+ */ -+static bool try_to_block_task(struct rq *rq, struct task_struct *p, -+ unsigned long *task_state_p) -+{ -+ unsigned long task_state = *task_state_p; -+ -+ WARN_ON_ONCE(p->is_blocked); -+ -+ if (signal_pending_state(task_state, p)) { -+ WRITE_ONCE(p->__state, TASK_RUNNING); -+ *task_state_p = TASK_RUNNING; -+ return false; -+ } -+ -+ p->is_blocked = 1; -+ -+ sched_task_deactivate(p, rq); -+ -+ block_task(rq, p, task_state); -+ -+ return true; -+} -+ -+/* -+ * schedule() is the main scheduler function. -+ * -+ * The main means of driving the scheduler and thus entering this function are: -+ * -+ * 1. Explicit blocking: mutex, semaphore, waitqueue, etc. -+ * -+ * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return -+ * paths. For example, see arch/x86/entry_64.S. -+ * -+ * To drive preemption between tasks, the scheduler sets the flag in timer -+ * interrupt handler sched_tick(). -+ * -+ * 3. Wakeups don't really cause entry into schedule(). They add a -+ * task to the run-queue and that's it. -+ * -+ * Now, if the new task added to the run-queue preempts the current -+ * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets -+ * called on the nearest possible occasion: -+ * -+ * - If the kernel is preemptible (CONFIG_PREEMPTION=y): -+ * -+ * - in syscall or exception context, at the next outmost -+ * preempt_enable(). (this might be as soon as the wake_up()'s -+ * spin_unlock()!) -+ * -+ * - in IRQ context, return from interrupt-handler to -+ * preemptible context -+ * -+ * - If the kernel is not preemptible (CONFIG_PREEMPTION is not set) -+ * then at the next: -+ * -+ * - cond_resched() call -+ * - explicit schedule() call -+ * - return from syscall or exception to user-space -+ * - return from interrupt-handler to user-space -+ * -+ * WARNING: must be called with preemption disabled! -+ */ -+static void __sched notrace __schedule(int sched_mode) -+{ -+ struct task_struct *prev, *next; -+ /* -+ * On PREEMPT_RT kernel, SM_RTLOCK_WAIT is noted -+ * as a preemption by schedule_debug() and RCU. -+ */ -+ bool preempt = sched_mode > SM_NONE; -+ bool is_switch = false; -+ unsigned long *switch_count; -+ unsigned long prev_state; -+ struct rq_flags rf; -+ struct rq *rq; -+ int cpu; -+ -+ /* Trace preemptions consistently with task switches */ -+ trace_sched_entry_tp(sched_mode == SM_PREEMPT); -+ -+ cpu = smp_processor_id(); -+ rq = cpu_rq(cpu); -+ prev = rq->curr; -+ -+ schedule_debug(prev, preempt); -+ -+ klp_sched_try_switch(prev); -+ -+ local_irq_disable(); -+ rcu_note_context_switch(preempt); -+ -+ /* -+ * Make sure that signal_pending_state()->signal_pending() below -+ * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE) -+ * done by the caller to avoid the race with signal_wake_up(): -+ * -+ * __set_current_state(@state) signal_wake_up() -+ * schedule() set_tsk_thread_flag(p, TIF_SIGPENDING) -+ * wake_up_state(p, state) -+ * LOCK rq->lock LOCK p->pi_state -+ * smp_mb__after_spinlock() smp_mb__after_spinlock() -+ * if (signal_pending_state()) if (p->state & @state) -+ * -+ * Also, the membarrier system call requires a full memory barrier -+ * after coming from user-space, before storing to rq->curr; this -+ * barrier matches a full barrier in the proximity of the membarrier -+ * system call exit. -+ */ -+ rq_lock(rq, &rf); -+ smp_mb__after_spinlock(); -+ -+ hrtick_schedule_enter(rq); -+ -+ update_rq_clock(rq); -+ -+ switch_count = &prev->nivcsw; -+ -+ /* Task state changes only considers SM_PREEMPT as preemption */ -+ preempt = sched_mode == SM_PREEMPT; -+ -+ /* -+ * We must load prev->state once (task_struct::state is volatile), such -+ * that we form a control dependency vs deactivate_task() below. -+ */ -+ prev_state = READ_ONCE(prev->__state); -+ if (sched_mode == SM_IDLE) { -+ if (!rq->nr_running) { -+ sched_cpu_topology_balance(cpu, rq); -+ next = prev; -+ goto picked; -+ } -+ } else if (!preempt && prev_state) { -+ try_to_block_task(rq, prev, &prev_state); -+ switch_count = &prev->nvcsw; -+ } -+ -+ check_curr(prev, rq); -+ -+ next = choose_next_task(rq, cpu); -+picked: -+ clear_tsk_need_resched(prev); -+ clear_preempt_need_resched(); -+ rq->last_seen_need_resched_ns = 0; -+ -+ is_switch = prev != next; -+ if (likely(is_switch)) { -+ next->last_ran = rq->clock_task; -+ -+ /*printk(KERN_INFO "sched: %px -> %px\n", prev, next);*/ -+ rq->nr_switches++; -+ /* -+ * RCU users of rcu_dereference(rq->curr) may not see -+ * changes to task_struct made by pick_next_task(). -+ */ -+ RCU_INIT_POINTER(rq->curr, next); -+ /* -+ * The membarrier system call requires each architecture -+ * to have a full memory barrier after updating -+ * rq->curr, before returning to user-space. -+ * -+ * Here are the schemes providing that barrier on the -+ * various architectures: -+ * - mm ? switch_mm() : mmdrop() for x86, s390, sparc, PowerPC, -+ * RISC-V. switch_mm() relies on membarrier_arch_switch_mm() -+ * on PowerPC and on RISC-V. -+ * - finish_lock_switch() for weakly-ordered -+ * architectures where spin_unlock is a full barrier, -+ * - switch_to() for arm64 (weakly-ordered, spin_unlock -+ * is a RELEASE barrier), -+ * -+ * The barrier matches a full barrier in the proximity of -+ * the membarrier system call entry. -+ * -+ * On RISC-V, this barrier pairing is also needed for the -+ * SYNC_CORE command when switching between processes, cf. -+ * the inline comments in membarrier_arch_switch_mm(). -+ */ -+ ++*switch_count; -+ -+ psi_account_irqtime(rq, prev, next); -+ psi_sched_switch(prev, next, !task_on_rq_queued(prev)); -+ -+ trace_sched_switch(preempt, prev, next, prev_state); -+ -+ /* Also unlocks the rq: */ -+ rq = context_switch(rq, prev, next, &rf); -+ -+ cpu = cpu_of(rq); -+ } else { -+ rq_unpin_lock(rq, &rf); -+ __balance_callbacks(rq, NULL); -+ prio_balance(rq, cpu); -+ hrtick_schedule_exit(rq); -+ raw_spin_rq_unlock_irq(rq); -+ } -+ trace_sched_exit_tp(is_switch); -+} -+ -+void __noreturn do_task_dead(void) -+{ -+ /* Causes final put_task_struct in finish_task_switch(): */ -+ set_special_state(TASK_DEAD); -+ -+ /* Tell freezer to ignore us: */ -+ current->flags |= PF_NOFREEZE; -+ -+ __schedule(SM_NONE); -+ BUG(); -+ -+ /* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */ -+ for (;;) -+ cpu_relax(); -+} -+ -+static inline void sched_submit_work(struct task_struct *tsk) -+{ -+ static DEFINE_WAIT_OVERRIDE_MAP(sched_map, LD_WAIT_CONFIG); -+ unsigned int task_flags; -+ -+ /* -+ * Establish LD_WAIT_CONFIG context to ensure none of the code called -+ * will use a blocking primitive -- which would lead to recursion. -+ */ -+ lock_map_acquire_try(&sched_map); -+ -+ task_flags = tsk->flags; -+ /* -+ * If a worker goes to sleep, notify and ask workqueue whether it -+ * wants to wake up a task to maintain concurrency. -+ */ -+ if (task_flags & PF_WQ_WORKER) -+ wq_worker_sleeping(tsk); -+ else if (task_flags & PF_IO_WORKER) -+ io_wq_worker_sleeping(tsk); -+ -+ /* -+ * spinlock and rwlock must not flush block requests. This will -+ * deadlock if the callback attempts to acquire a lock which is -+ * already acquired. -+ */ -+ WARN_ON_ONCE(current->__state & TASK_RTLOCK_WAIT); -+ -+ /* -+ * If we are going to sleep and we have plugged IO queued, -+ * make sure to submit it to avoid deadlocks. -+ */ -+ blk_flush_plug(tsk->plug, true); -+ -+ lock_map_release(&sched_map); -+} -+ -+static void sched_update_worker(struct task_struct *tsk) -+{ -+ if (tsk->flags & (PF_WQ_WORKER | PF_IO_WORKER)) { -+ if (tsk->flags & PF_WQ_WORKER) -+ wq_worker_running(tsk); -+ else -+ io_wq_worker_running(tsk); -+ } -+} -+ -+static __always_inline void __schedule_loop(int sched_mode) -+{ -+ do { -+ preempt_disable(); -+ __schedule(sched_mode); -+ sched_preempt_enable_no_resched(); -+ } while (need_resched()); -+} -+ -+asmlinkage __visible void __sched schedule(void) -+{ -+ struct task_struct *tsk = current; -+ -+#ifdef CONFIG_RT_MUTEXES -+ lockdep_assert(!tsk->sched_rt_mutex); -+#endif -+ -+ if (!task_is_running(tsk)) -+ sched_submit_work(tsk); -+ __schedule_loop(SM_NONE); -+ sched_update_worker(tsk); -+} -+EXPORT_SYMBOL(schedule); -+ -+/* -+ * synchronize_rcu_tasks() makes sure that no task is stuck in preempted -+ * state (have scheduled out non-voluntarily) by making sure that all -+ * tasks have either left the run queue or have gone into user space. -+ * As idle tasks do not do either, they must not ever be preempted -+ * (schedule out non-voluntarily). -+ * -+ * schedule_idle() is similar to schedule_preempt_disable() except that it -+ * never enables preemption because it does not call sched_submit_work(). -+ */ -+void __sched schedule_idle(void) -+{ -+ /* -+ * As this skips calling sched_submit_work(), which the idle task does -+ * regardless because that function is a NOP when the task is in a -+ * TASK_RUNNING state, make sure this isn't used someplace that the -+ * current task can be in any other state. Note, idle is always in the -+ * TASK_RUNNING state. -+ */ -+ WARN_ON_ONCE(current->__state); -+ do { -+ __schedule(SM_IDLE); -+ } while (need_resched()); -+} -+ -+#if defined(CONFIG_CONTEXT_TRACKING_USER) && !defined(CONFIG_HAVE_CONTEXT_TRACKING_USER_OFFSTACK) -+asmlinkage __visible void __sched schedule_user(void) -+{ -+ /* -+ * If we come here after a random call to set_need_resched(), -+ * or we have been woken up remotely but the IPI has not yet arrived, -+ * we haven't yet exited the RCU idle mode. Do it here manually until -+ * we find a better solution. -+ * -+ * NB: There are buggy callers of this function. Ideally we -+ * should warn if prev_state != CT_STATE_USER, but that will trigger -+ * too frequently to make sense yet. -+ */ -+ enum ctx_state prev_state = exception_enter(); -+ schedule(); -+ exception_exit(prev_state); -+} -+#endif -+ -+/** -+ * schedule_preempt_disabled - called with preemption disabled -+ * -+ * Returns with preemption disabled. Note: preempt_count must be 1 -+ */ -+void __sched schedule_preempt_disabled(void) -+{ -+ sched_preempt_enable_no_resched(); -+ schedule(); -+ preempt_disable(); -+} -+ -+#ifdef CONFIG_PREEMPT_RT -+void __sched notrace schedule_rtlock(void) -+{ -+ __schedule_loop(SM_RTLOCK_WAIT); -+} -+NOKPROBE_SYMBOL(schedule_rtlock); -+#endif -+ -+static void __sched notrace preempt_schedule_common(void) -+{ -+ do { -+ /* -+ * Because the function tracer can trace preempt_count_sub() -+ * and it also uses preempt_enable/disable_notrace(), if -+ * NEED_RESCHED is set, the preempt_enable_notrace() called -+ * by the function tracer will call this function again and -+ * cause infinite recursion. -+ * -+ * Preemption must be disabled here before the function -+ * tracer can trace. Break up preempt_disable() into two -+ * calls. One to disable preemption without fear of being -+ * traced. The other to still record the preemption latency, -+ * which can also be traced by the function tracer. -+ */ -+ preempt_disable_notrace(); -+ preempt_latency_start(1); -+ __schedule(SM_PREEMPT); -+ preempt_latency_stop(1); -+ preempt_enable_no_resched_notrace(); -+ -+ /* -+ * Check again in case we missed a preemption opportunity -+ * between schedule and now. -+ */ -+ } while (need_resched()); -+} -+ -+#ifdef CONFIG_PREEMPTION -+/* -+ * This is the entry point to schedule() from in-kernel preemption -+ * off of preempt_enable. -+ */ -+asmlinkage __visible void __sched notrace preempt_schedule(void) -+{ -+ /* -+ * If there is a non-zero preempt_count or interrupts are disabled, -+ * we do not want to preempt the current task. Just return.. -+ */ -+ if (likely(!preemptible())) -+ return; -+ -+ preempt_schedule_common(); -+} -+NOKPROBE_SYMBOL(preempt_schedule); -+EXPORT_SYMBOL(preempt_schedule); -+ -+#ifdef CONFIG_PREEMPT_DYNAMIC -+# ifdef CONFIG_HAVE_PREEMPT_DYNAMIC_CALL -+# ifndef preempt_schedule_dynamic_enabled -+# define preempt_schedule_dynamic_enabled preempt_schedule -+# define preempt_schedule_dynamic_disabled NULL -+# endif -+DEFINE_STATIC_CALL(preempt_schedule, preempt_schedule_dynamic_enabled); -+EXPORT_STATIC_CALL_TRAMP(preempt_schedule); -+# elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY) -+static DEFINE_STATIC_KEY_TRUE(sk_dynamic_preempt_schedule); -+void __sched notrace dynamic_preempt_schedule(void) -+{ -+ if (!static_branch_unlikely(&sk_dynamic_preempt_schedule)) -+ return; -+ preempt_schedule(); -+} -+NOKPROBE_SYMBOL(dynamic_preempt_schedule); -+EXPORT_SYMBOL(dynamic_preempt_schedule); -+# endif -+#endif /* CONFIG_PREEMPT_DYNAMIC */ -+ -+/** -+ * preempt_schedule_notrace - preempt_schedule called by tracing -+ * -+ * The tracing infrastructure uses preempt_enable_notrace to prevent -+ * recursion and tracing preempt enabling caused by the tracing -+ * infrastructure itself. But as tracing can happen in areas coming -+ * from userspace or just about to enter userspace, a preempt enable -+ * can occur before user_exit() is called. This will cause the scheduler -+ * to be called when the system is still in usermode. -+ * -+ * To prevent this, the preempt_enable_notrace will use this function -+ * instead of preempt_schedule() to exit user context if needed before -+ * calling the scheduler. -+ */ -+asmlinkage __visible void __sched notrace preempt_schedule_notrace(void) -+{ -+ enum ctx_state prev_ctx; -+ -+ if (likely(!preemptible())) -+ return; -+ -+ do { -+ /* -+ * Because the function tracer can trace preempt_count_sub() -+ * and it also uses preempt_enable/disable_notrace(), if -+ * NEED_RESCHED is set, the preempt_enable_notrace() called -+ * by the function tracer will call this function again and -+ * cause infinite recursion. -+ * -+ * Preemption must be disabled here before the function -+ * tracer can trace. Break up preempt_disable() into two -+ * calls. One to disable preemption without fear of being -+ * traced. The other to still record the preemption latency, -+ * which can also be traced by the function tracer. -+ */ -+ preempt_disable_notrace(); -+ preempt_latency_start(1); -+ /* -+ * Needs preempt disabled in case user_exit() is traced -+ * and the tracer calls preempt_enable_notrace() causing -+ * an infinite recursion. -+ */ -+ prev_ctx = exception_enter(); -+ __schedule(SM_PREEMPT); -+ exception_exit(prev_ctx); -+ -+ preempt_latency_stop(1); -+ preempt_enable_no_resched_notrace(); -+ } while (need_resched()); -+} -+EXPORT_SYMBOL_GPL(preempt_schedule_notrace); -+ -+#ifdef CONFIG_PREEMPT_DYNAMIC -+# ifdef CONFIG_HAVE_PREEMPT_DYNAMIC_CALL -+# ifndef preempt_schedule_notrace_dynamic_enabled -+# define preempt_schedule_notrace_dynamic_enabled preempt_schedule_notrace -+# define preempt_schedule_notrace_dynamic_disabled NULL -+# endif -+DEFINE_STATIC_CALL(preempt_schedule_notrace, preempt_schedule_notrace_dynamic_enabled); -+EXPORT_STATIC_CALL_TRAMP(preempt_schedule_notrace); -+# elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY) -+static DEFINE_STATIC_KEY_TRUE(sk_dynamic_preempt_schedule_notrace); -+void __sched notrace dynamic_preempt_schedule_notrace(void) -+{ -+ if (!static_branch_unlikely(&sk_dynamic_preempt_schedule_notrace)) -+ return; -+ preempt_schedule_notrace(); -+} -+NOKPROBE_SYMBOL(dynamic_preempt_schedule_notrace); -+EXPORT_SYMBOL(dynamic_preempt_schedule_notrace); -+# endif -+#endif /* CONFIG_PREEMPT_DYNAMIC */ -+ -+#endif /* CONFIG_PREEMPTION */ -+ -+/* -+ * This is the entry point to schedule() from kernel preemption -+ * off of IRQ context. -+ * Note, that this is called and return with IRQs disabled. This will -+ * protect us against recursive calling from IRQ contexts. -+ */ -+asmlinkage __visible void __sched preempt_schedule_irq(void) -+{ -+ enum ctx_state prev_state; -+ -+ /* Catch callers which need to be fixed */ -+ BUG_ON(preempt_count() || !irqs_disabled()); -+ -+ prev_state = exception_enter(); -+ -+ do { -+ preempt_disable(); -+ local_irq_enable(); -+ __schedule(SM_PREEMPT); -+ local_irq_disable(); -+ sched_preempt_enable_no_resched(); -+ } while (need_resched()); -+ -+ exception_exit(prev_state); -+} -+ -+int default_wake_function(wait_queue_entry_t *curr, unsigned mode, int wake_flags, -+ void *key) -+{ -+ WARN_ON_ONCE(wake_flags & ~(WF_SYNC|WF_CURRENT_CPU)); -+ return try_to_wake_up(curr->private, mode, wake_flags); -+} -+EXPORT_SYMBOL(default_wake_function); -+ -+#ifdef CONFIG_RT_MUTEXES -+ -+/* -+ * Would be more useful with typeof()/auto_type but they don't mix with -+ * bit-fields. Since it's a local thing, use int. Keep the generic sounding -+ * name such that if someone were to implement this function we get to compare -+ * notes. -+ */ -+#define fetch_and_set(x, v) ({ int _x = (x); (x) = (v); _x; }) -+ -+void rt_mutex_pre_schedule(void) -+{ -+ lockdep_assert(!fetch_and_set(current->sched_rt_mutex, 1)); -+ sched_submit_work(current); -+} -+ -+/* -+ * Used within the futex syscall context, skips sched_submit_work() because none -+ * its work will be done. Asserts ensure that it is indeed the case. -+ */ -+void rt_mutex_futex_pre_schedule(void) -+{ -+ lockdep_assert(!(current->flags & (PF_WQ_WORKER | PF_IO_WORKER))); -+ lockdep_assert(!current->plug); -+ lockdep_assert(!fetch_and_set(current->sched_rt_mutex, 1)); -+} -+ -+void rt_mutex_schedule(void) -+{ -+ lockdep_assert(current->sched_rt_mutex); -+ __schedule_loop(SM_NONE); -+} -+ -+void rt_mutex_futex_post_schedule(void) -+{ -+ lockdep_assert(fetch_and_set(current->sched_rt_mutex, 0)); -+} -+ -+void rt_mutex_post_schedule(void) -+{ -+ sched_update_worker(current); -+ lockdep_assert(fetch_and_set(current->sched_rt_mutex, 0)); -+} -+ -+/* -+ * rt_mutex_setprio - set the current priority of a task -+ * @p: task to boost -+ * @pi_task: donor task -+ * -+ * This function changes the 'effective' priority of a task. It does -+ * not touch ->normal_prio like __setscheduler(). -+ * -+ * Used by the rt_mutex code to implement priority inheritance -+ * logic. Call site only calls if the priority of the task changed. -+ */ -+void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task) -+{ -+ int prio, queue_flag = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK; -+ struct rq_flags rf; -+ struct rq *rq; -+ -+ /* XXX used to be waiter->prio, not waiter->task->prio */ -+ prio = __rt_effective_prio(pi_task, p->normal_prio); -+ -+ /* -+ * If nothing changed; bail early. -+ */ -+ if (p->pi_top_task == pi_task && prio == p->prio) -+ return; -+ -+ rq = __task_rq_lock(p, &rf); -+ update_rq_clock(rq); -+ /* -+ * Set under pi_lock && rq->lock, such that the value can be used under -+ * either lock. -+ * -+ * Note that there is loads of tricky to make this pointer cache work -+ * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to -+ * ensure a task is de-boosted (pi_task is set to NULL) before the -+ * task is allowed to run again (and can exit). This ensures the pointer -+ * points to a blocked task -- which guarantees the task is present. -+ */ -+ p->pi_top_task = pi_task; -+ -+ /* -+ * For FIFO/RR we only need to set prio, if that matches we're done. -+ */ -+ if (prio == p->prio) -+ goto out_unlock; -+ -+ /* -+ * Idle task boosting is a no-no in general. There is one -+ * exception, when PREEMPT_RT and NOHZ is active: -+ * -+ * The idle task calls get_next_timer_interrupt() and holds -+ * the timer wheel base->lock on the CPU and another CPU wants -+ * to access the timer (probably to cancel it). We can safely -+ * ignore the boosting request, as the idle CPU runs this code -+ * with interrupts disabled and will complete the lock -+ * protected section without being interrupted. So there is no -+ * real need to boost. -+ */ -+ if (unlikely(p == rq->idle)) { -+ WARN_ON(p != rq->curr); -+ WARN_ON(p->pi_blocked_on); -+ goto out_unlock; -+ } -+ -+ trace_sched_pi_setprio(p, pi_task); -+ -+ scoped_guard (sched_change, p, queue_flag) { -+ if (rt_prio(prio) && p->prio < prio) -+ scope->flags |= ENQUEUE_HEAD; -+ p->prio = prio; -+ } -+ -+out_unlock: -+ /* Caller holds task_struct::pi_lock, IRQs are still disabled */ -+ -+ __balance_callbacks(rq, &rf); -+ __task_rq_unlock(rq, p, &rf); -+} -+#endif /* CONFIG_RT_MUTEXES */ -+ -+#if !defined(CONFIG_PREEMPTION) || defined(CONFIG_PREEMPT_DYNAMIC) -+int __sched __cond_resched(void) -+{ -+ if (should_resched(0) && !irqs_disabled()) { -+ preempt_schedule_common(); -+ return 1; -+ } -+ /* -+ * In PREEMPT_RCU kernels, ->rcu_read_lock_nesting tells the tick -+ * whether the current CPU is in an RCU read-side critical section, -+ * so the tick can report quiescent states even for CPUs looping -+ * in kernel context. In contrast, in non-preemptible kernels, -+ * RCU readers leave no in-memory hints, which means that CPU-bound -+ * processes executing in kernel context might never report an -+ * RCU quiescent state. Therefore, the following code causes -+ * cond_resched() to report a quiescent state, but only when RCU -+ * is in urgent need of one. -+ * A third case, preemptible, but non-PREEMPT_RCU provides for -+ * urgently needed quiescent states via rcu_flavor_sched_clock_irq(). -+ */ -+#ifndef CONFIG_PREEMPT_RCU -+ rcu_all_qs(); -+#endif -+ return 0; -+} -+EXPORT_SYMBOL(__cond_resched); -+#endif -+ -+#ifdef CONFIG_PREEMPT_DYNAMIC -+# ifdef CONFIG_HAVE_PREEMPT_DYNAMIC_CALL -+# define cond_resched_dynamic_enabled __cond_resched -+# define cond_resched_dynamic_disabled ((void *)&__static_call_return0) -+DEFINE_STATIC_CALL_RET0(cond_resched, __cond_resched); -+EXPORT_STATIC_CALL_TRAMP(cond_resched); -+ -+# define might_resched_dynamic_enabled __cond_resched -+# define might_resched_dynamic_disabled ((void *)&__static_call_return0) -+DEFINE_STATIC_CALL_RET0(might_resched, __cond_resched); -+EXPORT_STATIC_CALL_TRAMP(might_resched); -+# elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY) -+static DEFINE_STATIC_KEY_FALSE(sk_dynamic_cond_resched); -+int __sched dynamic_cond_resched(void) -+{ -+ if (!static_branch_unlikely(&sk_dynamic_cond_resched)) -+ return 0; -+ return __cond_resched(); -+} -+EXPORT_SYMBOL(dynamic_cond_resched); -+ -+static DEFINE_STATIC_KEY_FALSE(sk_dynamic_might_resched); -+int __sched dynamic_might_resched(void) -+{ -+ if (!static_branch_unlikely(&sk_dynamic_might_resched)) -+ return 0; -+ return __cond_resched(); -+} -+EXPORT_SYMBOL(dynamic_might_resched); -+# endif -+#endif /* CONFIG_PREEMPT_DYNAMIC */ -+ -+/* -+ * __cond_resched_lock() - if a reschedule is pending, drop the given lock, -+ * call schedule, and on return reacquire the lock. -+ * -+ * This works OK both with and without CONFIG_PREEMPTION. We do strange low-level -+ * operations here to prevent schedule() from being called twice (once via -+ * spin_unlock(), once by hand). -+ */ -+int __cond_resched_lock(spinlock_t *lock) -+{ -+ int resched = should_resched(PREEMPT_LOCK_OFFSET); -+ int ret = 0; -+ -+ lockdep_assert_held(lock); -+ -+ if (spin_needbreak(lock) || resched) { -+ spin_unlock(lock); -+ if (!_cond_resched()) -+ cpu_relax(); -+ ret = 1; -+ spin_lock(lock); -+ } -+ return ret; -+} -+EXPORT_SYMBOL(__cond_resched_lock); -+ -+int __cond_resched_rwlock_read(rwlock_t *lock) -+{ -+ int resched = should_resched(PREEMPT_LOCK_OFFSET); -+ int ret = 0; -+ -+ lockdep_assert_held_read(lock); -+ -+ if (rwlock_needbreak(lock) || resched) { -+ read_unlock(lock); -+ if (!_cond_resched()) -+ cpu_relax(); -+ ret = 1; -+ read_lock(lock); -+ } -+ return ret; -+} -+EXPORT_SYMBOL(__cond_resched_rwlock_read); -+ -+int __cond_resched_rwlock_write(rwlock_t *lock) -+{ -+ int resched = should_resched(PREEMPT_LOCK_OFFSET); -+ int ret = 0; -+ -+ lockdep_assert_held_write(lock); -+ -+ if (rwlock_needbreak(lock) || resched) { -+ write_unlock(lock); -+ if (!_cond_resched()) -+ cpu_relax(); -+ ret = 1; -+ write_lock(lock); -+ } -+ return ret; -+} -+EXPORT_SYMBOL(__cond_resched_rwlock_write); -+ -+#ifdef CONFIG_PREEMPT_DYNAMIC -+ -+# ifdef CONFIG_GENERIC_IRQ_ENTRY -+# include -+# endif -+ -+/* -+ * SC:cond_resched -+ * SC:might_resched -+ * SC:preempt_schedule -+ * SC:preempt_schedule_notrace -+ * SC:irqentry_exit_cond_resched -+ * -+ * -+ * NONE: -+ * cond_resched <- __cond_resched -+ * might_resched <- RET0 -+ * preempt_schedule <- NOP -+ * preempt_schedule_notrace <- NOP -+ * irqentry_exit_cond_resched <- NOP -+ * dynamic_preempt_lazy <- false -+ * -+ * VOLUNTARY: -+ * cond_resched <- __cond_resched -+ * might_resched <- __cond_resched -+ * preempt_schedule <- NOP -+ * preempt_schedule_notrace <- NOP -+ * irqentry_exit_cond_resched <- NOP -+ * dynamic_preempt_lazy <- false -+ * -+ * FULL: -+ * cond_resched <- RET0 -+ * might_resched <- RET0 -+ * preempt_schedule <- preempt_schedule -+ * preempt_schedule_notrace <- preempt_schedule_notrace -+ * irqentry_exit_cond_resched <- irqentry_exit_cond_resched -+ * dynamic_preempt_lazy <- false -+ * -+ * LAZY: -+ * cond_resched <- RET0 -+ * might_resched <- RET0 -+ * preempt_schedule <- preempt_schedule -+ * preempt_schedule_notrace <- preempt_schedule_notrace -+ * irqentry_exit_cond_resched <- irqentry_exit_cond_resched -+ * dynamic_preempt_lazy <- true -+ */ -+ -+enum { -+ preempt_dynamic_undefined = -1, -+ preempt_dynamic_none, -+ preempt_dynamic_voluntary, -+ preempt_dynamic_full, -+ preempt_dynamic_lazy, -+}; -+ -+int preempt_dynamic_mode = preempt_dynamic_undefined; -+ -+int sched_dynamic_mode(const char *str) -+{ -+# if !(defined(CONFIG_PREEMPT_RT) || defined(CONFIG_ARCH_HAS_PREEMPT_LAZY)) -+ if (!strcmp(str, "none")) -+ return preempt_dynamic_none; -+ -+ if (!strcmp(str, "voluntary")) -+ return preempt_dynamic_voluntary; -+# endif -+ -+ if (!strcmp(str, "full")) -+ return preempt_dynamic_full; -+ -+# ifdef CONFIG_ARCH_HAS_PREEMPT_LAZY -+ if (!strcmp(str, "lazy")) -+ return preempt_dynamic_lazy; -+# endif -+ -+ return -EINVAL; -+} -+ -+# define preempt_dynamic_key_enable(f) static_key_enable(&sk_dynamic_##f.key) -+# define preempt_dynamic_key_disable(f) static_key_disable(&sk_dynamic_##f.key) -+ -+# if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL) -+# define preempt_dynamic_enable(f) static_call_update(f, f##_dynamic_enabled) -+# define preempt_dynamic_disable(f) static_call_update(f, f##_dynamic_disabled) -+# elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY) -+# define preempt_dynamic_enable(f) preempt_dynamic_key_enable(f) -+# define preempt_dynamic_disable(f) preempt_dynamic_key_disable(f) -+# else -+# error "Unsupported PREEMPT_DYNAMIC mechanism" -+# endif -+ -+static DEFINE_MUTEX(sched_dynamic_mutex); -+ -+static void __sched_dynamic_update(int mode) -+{ -+ /* -+ * Avoid {NONE,VOLUNTARY} -> FULL transitions from ever ending up in -+ * the ZERO state, which is invalid. -+ */ -+ preempt_dynamic_enable(cond_resched); -+ preempt_dynamic_enable(might_resched); -+ preempt_dynamic_enable(preempt_schedule); -+ preempt_dynamic_enable(preempt_schedule_notrace); -+ preempt_dynamic_enable(irqentry_exit_cond_resched); -+ preempt_dynamic_key_disable(preempt_lazy); -+ -+ switch (mode) { -+ case preempt_dynamic_none: -+ preempt_dynamic_enable(cond_resched); -+ preempt_dynamic_disable(might_resched); -+ preempt_dynamic_disable(preempt_schedule); -+ preempt_dynamic_disable(preempt_schedule_notrace); -+ preempt_dynamic_disable(irqentry_exit_cond_resched); -+ preempt_dynamic_key_disable(preempt_lazy); -+ if (mode != preempt_dynamic_mode) -+ pr_info("Dynamic Preempt: none\n"); -+ break; -+ -+ case preempt_dynamic_voluntary: -+ preempt_dynamic_enable(cond_resched); -+ preempt_dynamic_enable(might_resched); -+ preempt_dynamic_disable(preempt_schedule); -+ preempt_dynamic_disable(preempt_schedule_notrace); -+ preempt_dynamic_disable(irqentry_exit_cond_resched); -+ preempt_dynamic_key_disable(preempt_lazy); -+ if (mode != preempt_dynamic_mode) -+ pr_info("Dynamic Preempt: voluntary\n"); -+ break; -+ -+ case preempt_dynamic_full: -+ preempt_dynamic_disable(cond_resched); -+ preempt_dynamic_disable(might_resched); -+ preempt_dynamic_enable(preempt_schedule); -+ preempt_dynamic_enable(preempt_schedule_notrace); -+ preempt_dynamic_enable(irqentry_exit_cond_resched); -+ preempt_dynamic_key_disable(preempt_lazy); -+ if (mode != preempt_dynamic_mode) -+ pr_info("Dynamic Preempt: full\n"); -+ break; -+ -+ case preempt_dynamic_lazy: -+ preempt_dynamic_disable(cond_resched); -+ preempt_dynamic_disable(might_resched); -+ preempt_dynamic_enable(preempt_schedule); -+ preempt_dynamic_enable(preempt_schedule_notrace); -+ preempt_dynamic_enable(irqentry_exit_cond_resched); -+ preempt_dynamic_key_enable(preempt_lazy); -+ if (mode != preempt_dynamic_mode) -+ pr_info("Dynamic Preempt: lazy\n"); -+ break; -+ } -+ -+ WRITE_ONCE(preempt_dynamic_mode, mode); -+} -+ -+void sched_dynamic_update(int mode) -+{ -+ mutex_lock(&sched_dynamic_mutex); -+ __sched_dynamic_update(mode); -+ mutex_unlock(&sched_dynamic_mutex); -+} -+ -+static int __init setup_preempt_mode(char *str) -+{ -+ int mode = sched_dynamic_mode(str); -+ if (mode < 0) { -+ pr_warn("Dynamic Preempt: unsupported mode: %s\n", str); -+ return 0; -+ } -+ -+ sched_dynamic_update(mode); -+ return 1; -+} -+__setup("preempt=", setup_preempt_mode); -+ -+static void __init preempt_dynamic_init(void) -+{ -+ if (preempt_dynamic_mode == preempt_dynamic_undefined) { -+ if (IS_ENABLED(CONFIG_PREEMPT_NONE)) { -+ sched_dynamic_update(preempt_dynamic_none); -+ } else if (IS_ENABLED(CONFIG_PREEMPT_VOLUNTARY)) { -+ sched_dynamic_update(preempt_dynamic_voluntary); -+ } else if (IS_ENABLED(CONFIG_PREEMPT_LAZY)) { -+ sched_dynamic_update(preempt_dynamic_lazy); -+ } else { -+ /* Default static call setting, nothing to do */ -+ WARN_ON_ONCE(!IS_ENABLED(CONFIG_PREEMPT)); -+ preempt_dynamic_mode = preempt_dynamic_full; -+ pr_info("Dynamic Preempt: full\n"); -+ } -+ } -+} -+ -+# define PREEMPT_MODEL_ACCESSOR(mode) \ -+ bool preempt_model_##mode(void) \ -+ { \ -+ int mode = READ_ONCE(preempt_dynamic_mode); \ -+ WARN_ON_ONCE(mode == preempt_dynamic_undefined); \ -+ return mode == preempt_dynamic_##mode; \ -+ } \ -+ EXPORT_SYMBOL_GPL(preempt_model_##mode) -+ -+PREEMPT_MODEL_ACCESSOR(none); -+PREEMPT_MODEL_ACCESSOR(voluntary); -+PREEMPT_MODEL_ACCESSOR(full); -+PREEMPT_MODEL_ACCESSOR(lazy); -+ -+#else /* !CONFIG_PREEMPT_DYNAMIC: */ -+ -+#define preempt_dynamic_mode -1 -+ -+static inline void preempt_dynamic_init(void) { } -+ -+#endif /* CONFIG_PREEMPT_DYNAMIC */ -+ -+const char *preempt_modes[] = { -+ "none", "voluntary", "full", "lazy", NULL, -+}; -+ -+const char *preempt_model_str(void) -+{ -+ bool brace = IS_ENABLED(CONFIG_PREEMPT_RT) && -+ (IS_ENABLED(CONFIG_PREEMPT_DYNAMIC) || -+ IS_ENABLED(CONFIG_PREEMPT_LAZY)); -+ static char buf[128]; -+ -+ if (IS_ENABLED(CONFIG_PREEMPT_BUILD)) { -+ struct seq_buf s; -+ -+ seq_buf_init(&s, buf, sizeof(buf)); -+ seq_buf_puts(&s, "PREEMPT"); -+ -+ if (IS_ENABLED(CONFIG_PREEMPT_RT)) -+ seq_buf_printf(&s, "%sRT%s", -+ brace ? "_{" : "_", -+ brace ? "," : ""); -+ -+ if (IS_ENABLED(CONFIG_PREEMPT_DYNAMIC)) { -+ seq_buf_printf(&s, "(%s)%s", -+ preempt_dynamic_mode >= 0 ? -+ preempt_modes[preempt_dynamic_mode] : "undef", -+ brace ? "}" : ""); -+ return seq_buf_str(&s); -+ } -+ -+ if (IS_ENABLED(CONFIG_PREEMPT_LAZY)) { -+ seq_buf_printf(&s, "LAZY%s", -+ brace ? "}" : ""); -+ return seq_buf_str(&s); -+ } -+ -+ return seq_buf_str(&s); -+ } -+ -+ if (IS_ENABLED(CONFIG_PREEMPT_VOLUNTARY_BUILD)) -+ return "VOLUNTARY"; -+ -+ return "NONE"; -+} -+ -+int io_schedule_prepare(void) -+{ -+ int old_iowait = current->in_iowait; -+ -+ current->in_iowait = 1; -+ blk_flush_plug(current->plug, true); -+ return old_iowait; -+} -+ -+void io_schedule_finish(int token) -+{ -+ current->in_iowait = token; -+} -+ -+/* -+ * This task is about to go to sleep on IO. Increment rq->nr_iowait so -+ * that process accounting knows that this is a task in IO wait state. -+ */ -+ -+long __sched io_schedule_timeout(long timeout) -+{ -+ int token; -+ long ret; -+ -+ token = io_schedule_prepare(); -+ ret = schedule_timeout(timeout); -+ io_schedule_finish(token); -+ -+ return ret; -+} -+EXPORT_SYMBOL(io_schedule_timeout); -+ -+void __sched io_schedule(void) -+{ -+ int token; -+ -+ token = io_schedule_prepare(); -+ schedule(); -+ io_schedule_finish(token); -+} -+EXPORT_SYMBOL(io_schedule); -+ -+void sched_show_task(struct task_struct *p) -+{ -+ unsigned long free; -+ int ppid; -+ -+ if (!try_get_task_stack(p)) -+ return; -+ -+ pr_info("task:%-15.15s state:%c", p->comm, task_state_to_char(p)); -+ -+ if (task_is_running(p)) -+ pr_cont(" running task "); -+ free = stack_not_used(p); -+ ppid = 0; -+ rcu_read_lock(); -+ if (pid_alive(p)) -+ ppid = task_pid_nr(rcu_dereference(p->real_parent)); -+ rcu_read_unlock(); -+ pr_cont(" stack:%-5lu pid:%-5d tgid:%-5d ppid:%-6d task_flags:0x%04x flags:0x%08lx\n", -+ free, task_pid_nr(p), task_tgid_nr(p), -+ ppid, p->flags, read_task_thread_flags(p)); -+ -+ print_worker_info(KERN_INFO, p); -+ print_stop_info(KERN_INFO, p); -+ show_stack(p, NULL, KERN_INFO); -+ put_task_stack(p); -+} -+EXPORT_SYMBOL_GPL(sched_show_task); -+ -+static inline bool -+state_filter_match(unsigned long state_filter, struct task_struct *p) -+{ -+ unsigned int state = READ_ONCE(p->__state); -+ -+ /* no filter, everything matches */ -+ if (!state_filter) -+ return true; -+ -+ /* filter, but doesn't match */ -+ if (!(state & state_filter)) -+ return false; -+ -+ /* -+ * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows -+ * TASK_KILLABLE). -+ */ -+ if (state_filter == TASK_UNINTERRUPTIBLE && (state & TASK_NOLOAD)) -+ return false; -+ -+ return true; -+} -+ -+ -+void show_state_filter(unsigned int state_filter) -+{ -+ struct task_struct *g, *p; -+ -+ rcu_read_lock(); -+ for_each_process_thread(g, p) { -+ /* -+ * reset the NMI-timeout, listing all files on a slow -+ * console might take a lot of time: -+ * Also, reset softlockup watchdogs on all CPUs, because -+ * another CPU might be blocked waiting for us to process -+ * an IPI. -+ */ -+ touch_nmi_watchdog(); -+ touch_all_softlockup_watchdogs(); -+ if (state_filter_match(state_filter, p)) -+ sched_show_task(p); -+ } -+ -+ /* TODO: Alt schedule FW should support this -+ if (!state_filter) -+ sysrq_sched_debug_show(); -+ */ -+ rcu_read_unlock(); -+ /* -+ * Only show locks if all tasks are dumped: -+ */ -+ if (!state_filter) -+ debug_show_all_locks(); -+} -+ -+void dump_cpu_task(int cpu) -+{ -+ if (in_hardirq() && cpu == smp_processor_id()) { -+ struct pt_regs *regs; -+ -+ regs = get_irq_regs(); -+ if (regs) { -+ show_regs(regs); -+ return; -+ } -+ } -+ -+ if (trigger_single_cpu_backtrace(cpu)) -+ return; -+ -+ pr_info("Task dump for CPU %d:\n", cpu); -+ sched_show_task(cpu_curr(cpu)); -+} -+ -+/** -+ * init_idle - set up an idle thread for a given CPU -+ * @idle: task in question -+ * @cpu: CPU the idle task belongs to -+ * -+ * NOTE: this function does not set the idle thread's NEED_RESCHED -+ * flag, to make booting more robust. -+ */ -+void __init init_idle(struct task_struct *idle, int cpu) -+{ -+ struct affinity_context ac = (struct affinity_context) { -+ .new_mask = cpumask_of(cpu), -+ .flags = 0, -+ }; -+ struct rq *rq = cpu_rq(cpu); -+ unsigned long flags; -+ -+ raw_spin_lock_irqsave(&idle->pi_lock, flags); -+ raw_spin_rq_lock(rq); -+ -+ idle->last_ran = rq->clock_task; -+ idle->__state = TASK_RUNNING; -+ /* -+ * PF_KTHREAD should already be set at this point; regardless, make it -+ * look like a proper per-CPU kthread. -+ */ -+ idle->flags |= PF_KTHREAD | PF_NO_SETAFFINITY; -+ kthread_set_per_cpu(idle, cpu); -+ -+ sched_queue_init_idle(&rq->queue, idle); -+ -+ /* -+ * No validation and serialization required at boot time and for -+ * setting up the idle tasks of not yet online CPUs. -+ */ -+ set_cpus_allowed_common(idle, &ac); -+ -+ /* Silence PROVE_RCU */ -+ rcu_read_lock(); -+ __set_task_cpu(idle, cpu); -+ rcu_read_unlock(); -+ -+ rq->idle = idle; -+ rcu_assign_pointer(rq->curr, idle); -+ idle->on_cpu = 1; -+ -+ raw_spin_rq_unlock(rq); -+ raw_spin_unlock_irqrestore(&idle->pi_lock, flags); -+ -+ /* Set the preempt count _outside_ the spinlocks! */ -+ init_idle_preempt_count(idle, cpu); -+ -+ ftrace_graph_init_idle_task(idle, cpu); -+ vtime_init_idle(idle, cpu); -+ sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu); -+} -+ -+int cpuset_cpumask_can_shrink(const struct cpumask __maybe_unused *cur, -+ const struct cpumask __maybe_unused *trial) -+{ -+ return 1; -+} -+ -+int task_can_attach(struct task_struct *p) -+{ -+ int ret = 0; -+ -+ /* -+ * Kthreads which disallow setaffinity shouldn't be moved -+ * to a new cpuset; we don't want to change their CPU -+ * affinity and isolating such threads by their set of -+ * allowed nodes is unnecessary. Thus, cpusets are not -+ * applicable for such threads. This prevents checking for -+ * success of set_cpus_allowed_ptr() on all attached tasks -+ * before cpus_mask may be changed. -+ */ -+ if (p->flags & PF_NO_SETAFFINITY) -+ ret = -EINVAL; -+ -+ return ret; -+} -+ -+bool sched_smp_initialized __read_mostly; -+ -+#ifdef CONFIG_HOTPLUG_CPU -+/* -+ * Invoked on the outgoing CPU in context of the CPU hotplug thread -+ * after ensuring that there are no user space tasks left on the CPU. -+ * -+ * If there is a lazy mm in use on the hotplug thread, drop it and -+ * switch to init_mm. -+ * -+ * The reference count on init_mm is dropped in finish_cpu(). -+ */ -+static void sched_force_init_mm(void) -+{ -+ struct mm_struct *mm = current->active_mm; -+ -+ if (mm != &init_mm) { -+ mmgrab_lazy_tlb(&init_mm); -+ local_irq_disable(); -+ current->active_mm = &init_mm; -+ switch_mm_irqs_off(mm, &init_mm, current); -+ local_irq_enable(); -+ finish_arch_post_lock_switch(); -+ mmdrop_lazy_tlb(mm); -+ } -+ -+ /* finish_cpu(), as ran on the BP, will clean up the active_mm state */ -+} -+ -+static int __balance_push_cpu_stop(void *arg) -+{ -+ struct task_struct *p = arg; -+ struct rq *rq = this_rq(); -+ struct rq_flags rf; -+ int cpu; -+ -+ scoped_guard (raw_spinlock_irq, &p->pi_lock) { -+ /* -+ * We may change the underlying rq, but the locks held will -+ * appropriately be "transferred" when switching. -+ */ -+ context_unsafe_alias(rq); -+ -+ cpu = select_fallback_rq(rq->cpu, p); -+ rq_lock(rq, &rf); -+ update_rq_clock(rq); -+ if (task_rq(p) == rq && task_on_rq_queued(p)) -+ rq = __migrate_task(rq, &rf, p, cpu); -+ rq_unlock(rq, &rf); -+ } -+ -+ put_task_struct(p); -+ -+ return 0; -+} -+ -+static DEFINE_PER_CPU(struct cpu_stop_work, push_work); -+ -+/* -+ * This is enabled below SCHED_AP_ACTIVE; when !cpu_active(), but only -+ * effective when the hotplug motion is down. -+ */ -+static void balance_push(struct rq *rq) -+ __must_hold(__rq_lockp(rq)) -+{ -+ struct task_struct *push_task = rq->curr; -+ -+ lockdep_assert_rq_held(rq); -+ -+ /* -+ * Ensure the thing is persistent until balance_push_set(.on = false); -+ */ -+ rq->balance_callback = &balance_push_callback; -+ -+ /* -+ * Only active while going offline and when invoked on the outgoing -+ * CPU. -+ */ -+ if (!cpu_dying(rq->cpu) || rq != this_rq()) -+ return; -+ -+ /* -+ * Both the cpu-hotplug and stop task are in this case and are -+ * required to complete the hotplug process. -+ */ -+ if (kthread_is_per_cpu(push_task) || -+ is_migration_disabled(push_task)) { -+ -+ /* -+ * If this is the idle task on the outgoing CPU try to wake -+ * up the hotplug control thread which might wait for the -+ * last task to vanish. The rcuwait_active() check is -+ * accurate here because the waiter is pinned on this CPU -+ * and can't obviously be running in parallel. -+ * -+ * On RT kernels this also has to check whether there are -+ * pinned and scheduled out tasks on the runqueue. They -+ * need to leave the migrate disabled section first. -+ */ -+ if (!rq->nr_running && !rq_has_pinned_tasks(rq) && -+ rcuwait_active(&rq->hotplug_wait)) { -+ raw_spin_rq_unlock(rq); -+ rcuwait_wake_up(&rq->hotplug_wait); -+ raw_spin_rq_lock(rq); -+ } -+ return; -+ } -+ -+ get_task_struct(push_task); -+ /* -+ * Temporarily drop rq->lock such that we can wake-up the stop task. -+ * Both preemption and IRQs are still disabled. -+ */ -+ preempt_disable(); -+ raw_spin_rq_unlock(rq); -+ stop_one_cpu_nowait(rq->cpu, __balance_push_cpu_stop, push_task, -+ this_cpu_ptr(&push_work)); -+ preempt_enable(); -+ /* -+ * At this point need_resched() is true and we'll take the loop in -+ * schedule(). The next pick is obviously going to be the stop task -+ * which kthread_is_per_cpu() and will push this task away. -+ */ -+ raw_spin_rq_lock(rq); -+} -+ -+static void balance_push_set(int cpu, bool on) -+{ -+ struct rq *rq = cpu_rq(cpu); -+ struct rq_flags rf; -+ -+ rq_lock_irqsave(rq, &rf); -+ if (on) { -+ WARN_ON_ONCE(rq->balance_callback); -+ rq->balance_callback = &balance_push_callback; -+ } else if (rq->balance_callback == &balance_push_callback) { -+ rq->balance_callback = NULL; -+ } -+ rq_unlock_irqrestore(rq, &rf); -+} -+ -+/* -+ * Invoked from a CPUs hotplug control thread after the CPU has been marked -+ * inactive. All tasks which are not per CPU kernel threads are either -+ * pushed off this CPU now via balance_push() or placed on a different CPU -+ * during wakeup. Wait until the CPU is quiescent. -+ */ -+static void balance_hotplug_wait(void) -+{ -+ struct rq *rq = this_rq(); -+ -+ rcuwait_wait_event(&rq->hotplug_wait, -+ rq->nr_running == 1 && !rq_has_pinned_tasks(rq), -+ TASK_UNINTERRUPTIBLE); -+} -+ -+#else /* !CONFIG_HOTPLUG_CPU: */ -+ -+static void balance_push(struct rq *rq) -+{ -+} -+ -+static void balance_push_set(int cpu, bool on) -+{ -+} -+ -+static inline void balance_hotplug_wait(void) -+{ -+} -+#endif /* !CONFIG_HOTPLUG_CPU */ -+ -+static void set_rq_offline(struct rq *rq) -+{ -+ if (rq->online) { -+ update_rq_clock(rq); -+ rq->online = false; -+ } -+} -+ -+static void set_rq_online(struct rq *rq) -+{ -+ if (!rq->online) -+ rq->online = true; -+} -+ -+static inline void sched_set_rq_online(struct rq *rq, int cpu) -+{ -+ unsigned long flags; -+ -+ raw_spin_rq_lock_irqsave(rq, flags); -+ set_rq_online(rq); -+ raw_spin_rq_unlock_irqrestore(rq, flags); -+} -+ -+static inline void sched_set_rq_offline(struct rq *rq, int cpu) -+{ -+ unsigned long flags; -+ -+ raw_spin_rq_lock_irqsave(rq, flags); -+ set_rq_offline(rq); -+ raw_spin_rq_unlock_irqrestore(rq, flags); -+} -+ -+/* -+ * used to mark begin/end of suspend/resume: -+ */ -+static int num_cpus_frozen; -+ -+/* -+ * Update cpusets according to cpu_active mask. If cpusets are -+ * disabled, cpuset_update_active_cpus() becomes a simple wrapper -+ * around partition_sched_domains(). -+ * -+ * If we come here as part of a suspend/resume, don't touch cpusets because we -+ * want to restore it back to its original state upon resume anyway. -+ */ -+static void cpuset_cpu_active(void) -+{ -+ if (cpuhp_tasks_frozen) { -+ /* -+ * num_cpus_frozen tracks how many CPUs are involved in suspend -+ * resume sequence. As long as this is not the last online -+ * operation in the resume sequence, just build a single sched -+ * domain, ignoring cpusets. -+ */ -+ cpuset_reset_sched_domains(); -+ if (--num_cpus_frozen) -+ return; -+ /* -+ * This is the last CPU online operation. So fall through and -+ * restore the original sched domains by considering the -+ * cpuset configurations. -+ */ -+ cpuset_force_rebuild(); -+ } -+ -+ cpuset_update_active_cpus(); -+} -+ -+static void cpuset_cpu_inactive(unsigned int cpu) -+{ -+ if (!cpuhp_tasks_frozen) { -+ cpuset_update_active_cpus(); -+ } else { -+ num_cpus_frozen++; -+ cpuset_reset_sched_domains(); -+ } -+} -+ -+static inline void sched_smt_present_inc(int cpu) -+{ -+ if (cpumask_weight(cpu_smt_mask(cpu)) == 2) -+ static_branch_inc_cpuslocked(&sched_smt_present); -+} -+ -+static inline void sched_smt_present_dec(int cpu) -+{ -+ if (cpumask_weight(cpu_smt_mask(cpu)) == 2) -+ static_branch_dec_cpuslocked(&sched_smt_present); -+} -+ -+static void sched_topology_hotplug_rebuild(unsigned int cpu, bool activate); -+ -+int sched_cpu_activate(unsigned int cpu) -+{ -+ struct rq *rq = cpu_rq(cpu); -+ -+ /* -+ * Clear the balance_push callback and prepare to schedule -+ * regular tasks. -+ */ -+ balance_push_set(cpu, false); -+ -+ /* -+ * When going up, increment the number of cores with SMT present. -+ */ -+ sched_smt_present_inc(cpu); -+ if (sched_smp_initialized) -+ sched_topology_hotplug_rebuild(cpu, true); -+ -+ set_cpu_active(cpu, true); -+ -+ if (sched_smp_initialized) -+ cpuset_cpu_active(); -+ -+ /* -+ * Put the rq online, if not already. This happens: -+ * -+ * 1) In the early boot process, because we build the real domains -+ * after all cpus have been brought up. -+ * -+ * 2) At runtime, if cpuset_cpu_active() fails to rebuild the -+ * domains. -+ */ -+ sched_set_rq_online(rq, cpu); -+ -+ return 0; -+} -+ -+int sched_cpu_deactivate(unsigned int cpu) -+{ -+ struct rq *rq = cpu_rq(cpu); -+ -+ set_cpu_active(cpu, false); -+ -+ /* -+ * From this point forward, this CPU will refuse to run any task that -+ * is not: migrate_disable() or KTHREAD_IS_PER_CPU, and will actively -+ * push those tasks away until this gets cleared, see -+ * sched_cpu_dying(). -+ */ -+ balance_push_set(cpu, true); -+ -+ /* -+ * We've cleared cpu_active_mask, wait for all preempt-disabled and RCU -+ * users of this state to go away such that all new such users will -+ * observe it. -+ * -+ * Specifically, we rely on ttwu to no longer target this CPU, see -+ * ttwu_queue_cond() and is_cpu_allowed(). -+ * -+ * Do sync before park smpboot threads to take care the RCU boost case. -+ */ -+ synchronize_rcu(); -+ -+ sched_set_rq_offline(rq, cpu); -+ -+ /* -+ * When going down, decrement the number of cores with SMT present. -+ */ -+ sched_smt_present_dec(cpu); -+ -+ if (!sched_smp_initialized) -+ return 0; -+ -+ sched_topology_hotplug_rebuild(cpu, false); -+ cpuset_cpu_inactive(cpu); -+ -+ return 0; -+} -+ -+static void sched_rq_cpu_starting(unsigned int cpu) -+{ -+ struct rq *rq = cpu_rq(cpu); -+ -+ rq->calc_load_update = calc_load_update; -+} -+ -+int sched_cpu_starting(unsigned int cpu) -+{ -+ sched_rq_cpu_starting(cpu); -+ sched_tick_start(cpu); -+ return 0; -+} -+ -+#ifdef CONFIG_HOTPLUG_CPU -+ -+/* -+ * Invoked immediately before the stopper thread is invoked to bring the -+ * CPU down completely. At this point all per CPU kthreads except the -+ * hotplug thread (current) and the stopper thread (inactive) have been -+ * either parked or have been unbound from the outgoing CPU. Ensure that -+ * any of those which might be on the way out are gone. -+ * -+ * If after this point a bound task is being woken on this CPU then the -+ * responsible hotplug callback has failed to do it's job. -+ * sched_cpu_dying() will catch it with the appropriate fireworks. -+ */ -+int sched_cpu_wait_empty(unsigned int cpu) -+{ -+ balance_hotplug_wait(); -+ sched_force_init_mm(); -+ return 0; -+} -+ -+/* -+ * Since this CPU is going 'away' for a while, fold any nr_active delta we -+ * might have. Called from the CPU stopper task after ensuring that the -+ * stopper is the last running task on the CPU, so nr_active count is -+ * stable. We need to take the tear-down thread which is calling this into -+ * account, so we hand in adjust = 1 to the load calculation. -+ * -+ * Also see the comment "Global load-average calculations". -+ */ -+static void calc_load_migrate(struct rq *rq) -+{ -+ long delta = calc_load_fold_active(rq, 1); -+ -+ if (delta) -+ atomic_long_add(delta, &calc_load_tasks); -+} -+ -+static void dump_rq_tasks(struct rq *rq, const char *loglvl) -+{ -+ struct task_struct *g, *p; -+ int cpu = cpu_of(rq); -+ -+ lockdep_assert_rq_held(rq); -+ -+ printk("%sCPU%d enqueued tasks (%u total):\n", loglvl, cpu, rq->nr_running); -+ for_each_process_thread(g, p) { -+ if (task_cpu(p) != cpu) -+ continue; -+ -+ if (!task_on_rq_queued(p)) -+ continue; -+ -+ printk("%s\tpid: %d, name: %s\n", loglvl, p->pid, p->comm); -+ } -+} -+ -+int sched_cpu_dying(unsigned int cpu) -+{ -+ struct rq *rq = cpu_rq(cpu); -+ unsigned long flags; -+ -+ /* Handle pending wakeups and then migrate everything off */ -+ sched_tick_stop(cpu); -+ -+ raw_spin_rq_lock_irqsave(rq, flags); -+ update_rq_clock(rq); -+ if (rq->nr_running != 1 || rq_has_pinned_tasks(rq)) { -+ WARN(true, "Dying CPU not properly vacated!"); -+ dump_rq_tasks(rq, KERN_WARNING); -+ } -+ raw_spin_rq_unlock_irqrestore(rq, flags); -+ -+ calc_load_migrate(rq); -+ hrtick_clear(rq); -+ return 0; -+} -+#endif /* CONFIG_HOTPLUG_CPU */ -+ -+static void sched_init_topology_cpumask_early(void) -+{ -+ int cpu, level; -+ cpumask_t *topo; -+ -+ for_each_possible_cpu(cpu) { -+ topo = per_cpu(sched_cpu_topo_masks, cpu); -+ for (level = 0; level < NR_CPU_AFFINITY_LEVELS; level++) -+ cpumask_clear(topo + level); -+ -+ cpumask_copy(topo + SCHED_CPU_AFFINITY_OTHER, -+ cpu_possible_mask); -+ per_cpu(sched_cpu_llc_mask, cpu) = -+ topo + SCHED_CPU_AFFINITY_LLC; -+ per_cpu(sched_cpu_topo_end_mask, cpu) = -+ topo + NR_CPU_AFFINITY_LEVELS; -+ per_cpu(sd_llc_id, cpu) = -1; -+ per_cpu(sd_llc_size, cpu) = cpumask_weight(cpu_possible_mask); -+ per_cpu(sched_cpu_topology_valid, cpu) = false; -+ } -+} -+ -+static bool sched_assign_llc_id(int cpu, const struct cpumask *active_mask) -+{ -+ int id, peer; -+ -+ cpumask_clear(&sched_llc_id_merge_mask); -+ if (per_cpu(sched_cpu_topology_valid, cpu) && -+ per_cpu(sd_llc_id, cpu) >= 0) -+ cpumask_set_cpu(per_cpu(sd_llc_id, cpu), -+ &sched_llc_id_merge_mask); -+ -+ for_each_cpu_and(peer, cpu_coregroup_mask(cpu), active_mask) { -+ if (peer == cpu || -+ !per_cpu(sched_cpu_topology_valid, peer)) -+ continue; -+ -+ id = per_cpu(sd_llc_id, peer); -+ if (id >= 0) -+ cpumask_set_cpu(id, &sched_llc_id_merge_mask); -+ } -+ -+ if (cpumask_empty(&sched_llc_id_merge_mask)) { -+ per_cpu(sd_llc_id, cpu) = cpu; -+ return false; -+ } -+ -+ id = cpumask_first(&sched_llc_id_merge_mask); -+ per_cpu(sd_llc_id, cpu) = id; -+ -+ if (cpumask_weight(&sched_llc_id_merge_mask) == 1) -+ return false; -+ -+ /* -+ * Independently discovered offline components can carry different -+ * tokens until they first become co-active. Merge every retained -+ * member so future hotplug cannot split the cache domain again. -+ */ -+ for_each_possible_cpu(peer) { -+ if (per_cpu(sched_cpu_topology_valid, peer) && -+ cpumask_test_cpu(per_cpu(sd_llc_id, peer), -+ &sched_llc_id_merge_mask)) -+ per_cpu(sd_llc_id, peer) = id; -+ } -+ -+ return true; -+} -+ -+static bool sched_build_topology_cpumask(int cpu, -+ const struct cpumask *active_mask) -+{ -+ cpumask_t *topo = per_cpu(sched_cpu_topo_masks, cpu); -+ bool llc_id_merged; -+ int level; -+ -+ for (level = 0; level < NR_CPU_AFFINITY_LEVELS; level++) -+ cpumask_clear(topo + level); -+ -+#ifdef CONFIG_SCHED_SMT -+ cpumask_and(topo + SCHED_CPU_AFFINITY_SMT, active_mask, -+ topology_sibling_cpumask(cpu)); -+#endif /* CONFIG_SCHED_SMT */ -+ cpumask_and(topo + SCHED_CPU_AFFINITY_CLUSTER, active_mask, -+ topology_cluster_cpumask(cpu)); -+ cpumask_and(topo + SCHED_CPU_AFFINITY_LLC, active_mask, -+ cpu_coregroup_mask(cpu)); -+ cpumask_and(topo + SCHED_CPU_AFFINITY_CORE, active_mask, -+ topology_core_cpumask(cpu)); -+ cpumask_copy(topo + SCHED_CPU_AFFINITY_OTHER, active_mask); -+ -+ per_cpu(sched_cpu_llc_mask, cpu) = -+ topo + SCHED_CPU_AFFINITY_LLC; -+ per_cpu(sched_cpu_topo_end_mask, cpu) = -+ topo + NR_CPU_AFFINITY_LEVELS; -+ -+ llc_id_merged = sched_assign_llc_id(cpu, active_mask); -+ per_cpu(sd_llc_size, cpu) = -+ max_t(int, 1, cpumask_weight_and(active_mask, -+ cpu_coregroup_mask(cpu))); -+ per_cpu(sched_cpu_topology_valid, cpu) = true; -+ -+ return llc_id_merged; -+} -+ -+static void sched_topology_add_cpu(int cpu, int added_cpu) -+{ -+ cpumask_t *topo = per_cpu(sched_cpu_topo_masks, cpu); -+ -+#ifdef CONFIG_SCHED_SMT -+ if (cpumask_test_cpu(added_cpu, topology_sibling_cpumask(cpu))) -+ cpumask_set_cpu(added_cpu, -+ topo + SCHED_CPU_AFFINITY_SMT); -+#endif -+ if (cpumask_test_cpu(added_cpu, topology_cluster_cpumask(cpu))) -+ cpumask_set_cpu(added_cpu, -+ topo + SCHED_CPU_AFFINITY_CLUSTER); -+ if (cpumask_test_cpu(added_cpu, cpu_coregroup_mask(cpu))) -+ cpumask_set_cpu(added_cpu, -+ topo + SCHED_CPU_AFFINITY_LLC); -+ if (cpumask_test_cpu(added_cpu, topology_core_cpumask(cpu))) -+ cpumask_set_cpu(added_cpu, -+ topo + SCHED_CPU_AFFINITY_CORE); -+ cpumask_set_cpu(added_cpu, topo + SCHED_CPU_AFFINITY_OTHER); -+} -+ -+static void sched_topology_remove_cpu(int cpu, int removed_cpu) -+{ -+ cpumask_t *topo = per_cpu(sched_cpu_topo_masks, cpu); -+ int level; -+ -+ for (level = 0; level < NR_CPU_AFFINITY_LEVELS; level++) -+ cpumask_clear_cpu(removed_cpu, topo + level); -+} -+ -+static void sched_topology_update_llc_size(const struct cpumask *active_mask, -+ int changed_cpu) -+{ -+ int cpu; -+ -+ for_each_cpu_and(cpu, cpu_coregroup_mask(changed_cpu), active_mask) -+ per_cpu(sd_llc_size, cpu) = -+ max_t(int, 1, cpumask_weight_and(active_mask, -+ cpu_coregroup_mask(cpu))); -+} -+ -+enum sched_topology_update { -+ SCHED_TOPOLOGY_BOOT, -+ SCHED_TOPOLOGY_ACTIVATE, -+ SCHED_TOPOLOGY_DEACTIVATE, -+}; -+ -+struct sched_topology_rebuild_context { -+ cpumask_t active_mask; -+ enum sched_topology_update update; -+ unsigned int cpu; -+ bool llc_id_merged; -+}; -+ -+/* Boot and CPU hotplug are serialized, so one context is sufficient. */ -+static struct sched_topology_rebuild_context sched_topology_context; -+ -+static void -+sched_topology_boot_update(const struct sched_topology_rebuild_context *ctx) -+{ -+ int cpu; -+ -+ for_each_cpu(cpu, &ctx->active_mask) { -+ cpu_rq(cpu)->idle->time_slice = sysctl_sched_base_slice; -+ sched_build_topology_cpumask(cpu, &ctx->active_mask); -+ } -+} -+ -+static void -+sched_topology_activate_update(struct sched_topology_rebuild_context *ctx) -+{ -+ int cpu, incoming = ctx->cpu; -+ -+ ctx->llc_id_merged = -+ sched_build_topology_cpumask(incoming, &ctx->active_mask); -+ -+ for_each_cpu(cpu, cpu_active_mask) { -+ sched_topology_add_cpu(cpu, incoming); -+ if (cpumask_test_cpu(incoming, cpu_coregroup_mask(cpu))) -+ per_cpu(sd_llc_size, cpu) = -+ max_t(int, 1, -+ cpumask_weight_and(&ctx->active_mask, -+ cpu_coregroup_mask(cpu))); -+ } -+} -+ -+static void -+sched_topology_deactivate_update(const struct sched_topology_rebuild_context *ctx) -+{ -+ int cpu, outgoing = ctx->cpu; -+ -+ for_each_cpu(cpu, &ctx->active_mask) -+ sched_topology_remove_cpu(cpu, outgoing); -+ -+ sched_topology_update_llc_size(&ctx->active_mask, outgoing); -+} -+ -+static void -+sched_topology_extend_inactive_snapshots(int incoming, -+ const struct cpumask *active_mask, -+ bool llc_id_merged) -+{ -+ int cpu, peer; -+ -+ /* -+ * A sleeping task may retain an offline previous CPU. Keep that CPU's -+ * locality row useful without extending the stop-machine section. -+ * Individual cpumask bit operations are atomic against lockless readers, -+ * and every placement candidate is independently restricted to active -+ * CPUs. -+ * -+ * Do not remove relationships when another CPU is deactivated. Some -+ * architectures clear their sibling masks later in CPU teardown, so -+ * that learned locality might be impossible to reconstruct. -+ */ -+ for_each_possible_cpu(cpu) { -+ cpumask_t *topo; -+ -+ if (cpu == incoming || cpu_active(cpu) || -+ !per_cpu(sched_cpu_topology_valid, cpu)) -+ continue; -+ -+ sched_topology_add_cpu(cpu, incoming); -+ -+ /* -+ * Retained architectural masks may already be cleared. A stable -+ * LLC token can still recover the cache and enclosing domains. -+ */ -+ if (per_cpu(sd_llc_id, cpu) != per_cpu(sd_llc_id, incoming)) -+ continue; -+ -+ topo = per_cpu(sched_cpu_topo_masks, cpu); -+ cpumask_set_cpu(incoming, topo + SCHED_CPU_AFFINITY_LLC); -+ cpumask_set_cpu(incoming, topo + SCHED_CPU_AFFINITY_CORE); -+ -+ if (!llc_id_merged) -+ continue; -+ -+ /* -+ * Token convergence joins independently retained components. -+ * Promote every active member of the joined LLC into every -+ * inactive row; otherwise those components stay topologically -+ * split even though cpus_share_cache() now agrees. -+ */ -+ for_each_cpu(peer, active_mask) { -+ if (!per_cpu(sched_cpu_topology_valid, peer) || -+ per_cpu(sd_llc_id, peer) != -+ per_cpu(sd_llc_id, incoming)) -+ continue; -+ -+ sched_topology_add_cpu(cpu, peer); -+ cpumask_set_cpu(peer, -+ topo + SCHED_CPU_AFFINITY_LLC); -+ cpumask_set_cpu(peer, -+ topo + SCHED_CPU_AFFINITY_CORE); -+ } -+ } -+} -+ -+static int sched_rebuild_topology_stop(void *data) -+{ -+ struct sched_topology_rebuild_context *ctx = data; -+ -+ sched_topology_apply(&ctx->active_mask); -+ -+ switch (ctx->update) { -+ case SCHED_TOPOLOGY_BOOT: -+ sched_topology_boot_update(ctx); -+ break; -+ case SCHED_TOPOLOGY_ACTIVATE: -+ sched_topology_activate_update(ctx); -+ break; -+ case SCHED_TOPOLOGY_DEACTIVATE: -+ sched_topology_deactivate_update(ctx); -+ break; -+ } -+ -+ return 0; -+} -+ -+static void sched_topology_hotplug_rebuild(unsigned int cpu, bool activate) -+{ -+ unsigned long flags; -+ int ret; -+ -+ cpumask_copy(&sched_topology_context.active_mask, cpu_active_mask); -+ if (activate) -+ cpumask_set_cpu(cpu, &sched_topology_context.active_mask); -+ -+ sched_topology_context.cpu = cpu; -+ sched_topology_context.update = activate ? -+ SCHED_TOPOLOGY_ACTIVATE : SCHED_TOPOLOGY_DEACTIVATE; -+ sched_topology_context.llc_id_merged = false; -+ -+ sched_topology_prepare(&sched_topology_context.active_mask); -+ -+ /* A preemption here would leave the other CPUs spinning with IRQs off. */ -+ local_irq_save(flags); -+ ret = stop_machine_from_inactive_cpu(sched_rebuild_topology_stop, -+ &sched_topology_context, -+ cpumask_of(cpu)); -+ local_irq_restore(flags); -+ -+ if (WARN_ON_ONCE(ret)) -+ return; -+ -+ if (activate) { -+ const struct cpumask *active_mask = -+ &sched_topology_context.active_mask; -+ bool llc_id_merged = sched_topology_context.llc_id_merged; -+ -+ sched_topology_extend_inactive_snapshots(cpu, active_mask, llc_id_merged); -+ } -+ sched_topology_report(); -+ sched_topology_queue_idle_select(); -+} -+ -+void __init sched_init_smp(void) -+{ -+ int ret; -+ -+ /* Move init over to a non-isolated CPU */ -+ if (set_cpus_allowed_ptr(current, housekeeping_cpumask(HK_TYPE_DOMAIN)) < 0) -+ BUG(); -+ current->flags &= ~PF_NO_SETAFFINITY; -+ -+ cpumask_copy(&sched_topology_context.active_mask, cpu_active_mask); -+ sched_topology_context.update = SCHED_TOPOLOGY_BOOT; -+ sched_topology_context.cpu = nr_cpu_ids; -+ sched_topology_context.llc_id_merged = false; -+ -+ sched_topology_prepare(&sched_topology_context.active_mask); -+ ret = stop_machine(sched_rebuild_topology_stop, -+ &sched_topology_context, NULL); -+ if (!WARN_ON_ONCE(ret)) { -+ sched_topology_report(); -+ sched_topology_init_idle_select(); -+ } -+ -+ sched_smp_initialized = true; -+} -+ -+static int __init migration_init(void) -+{ -+ sched_cpu_starting(smp_processor_id()); -+ return 0; -+} -+early_initcall(migration_init); -+ -+int in_sched_functions(unsigned long addr) -+{ -+ return in_lock_functions(addr) || -+ (addr >= (unsigned long)__sched_text_start -+ && addr < (unsigned long)__sched_text_end); -+} -+ -+#ifdef CONFIG_CGROUP_SCHED -+/* -+ * Default task group. -+ * Every task in system belongs to this group at bootup. -+ */ -+struct task_group root_task_group; -+LIST_HEAD(task_groups); -+ -+/* Cacheline aligned slab cache for task_group */ -+static struct kmem_cache *task_group_cache __ro_after_init; -+#endif /* CONFIG_CGROUP_SCHED */ -+ -+void __init sched_init(void) -+{ -+ int i; -+ struct rq *rq; -+ -+ printk(KERN_INFO "sched/alt: "ALT_SCHED_NAME" CPU Scheduler "ALT_SCHED_VERSION\ -+ " by Alfred Chen.\n"); -+ -+ wait_bit_init(); -+ -+ for (i = 0; i < SCHED_QUEUE_BITS; i++) -+ cpumask_copy(sched_preempt_mask + i, cpu_present_mask); -+ -+#ifdef CONFIG_CGROUP_SCHED -+ task_group_cache = KMEM_CACHE(task_group, 0); -+ -+ list_add(&root_task_group.list, &task_groups); -+ INIT_LIST_HEAD(&root_task_group.children); -+ INIT_LIST_HEAD(&root_task_group.siblings); -+#endif /* CONFIG_CGROUP_SCHED */ -+ for_each_possible_cpu(i) { -+ rq = cpu_rq(i); -+ -+#ifdef CONFIG_SCHED_SMT -+ raw_spin_lock_init(&per_cpu(sched_smt_idle_lock, i)); -+#endif -+ sched_queue_init(&rq->queue); -+ sched_rq_set_prio(rq, IDLE_TASK_SCHED_PRIO); -+ rq->prio_balance_time = 0; -+ -+ raw_spin_lock_init(rq_lockp(rq)); -+ rq->nr_running = rq->nr_uninterruptible = 0; -+ rq->calc_load_active = 0; -+ rq->calc_load_update = jiffies + LOAD_FREQ; -+ rq->online = false; -+ rq->cpu = i; -+ -+ rq->active_balance_arg.active = 0; -+ -+#ifdef CONFIG_NO_HZ_COMMON -+ INIT_CSD(&rq->nohz_csd, nohz_csd_func, rq); -+#endif -+ rq->balance_callback = &balance_push_callback; -+#ifdef CONFIG_HOTPLUG_CPU -+ rcuwait_init(&rq->hotplug_wait); -+#endif -+ rq->nr_switches = 0; -+ -+ hrtick_rq_init(rq); -+ atomic_set(&rq->nr_iowait, 0); -+ -+ zalloc_cpumask_var_node(&rq->scratch_mask, GFP_KERNEL, cpu_to_node(i)); -+ } -+ /* Set rq->online for cpu 0 */ -+ cpu_rq(0)->online = true; -+ /* -+ * The boot idle thread does lazy MMU switching as well: -+ */ -+ mmgrab_lazy_tlb(&init_mm); -+ enter_lazy_tlb(&init_mm, current); -+ -+ /* -+ * The idle task doesn't need the kthread struct to function, but it -+ * is dressed up as a per-CPU kthread and thus needs to play the part -+ * if we want to avoid special-casing it in code that deals with per-CPU -+ * kthreads. -+ */ -+ WARN_ON(!set_kthread_struct(current)); -+ -+ /* -+ * Make us the idle thread. Technically, schedule() should not be -+ * called from this thread, however somewhere below it might be, -+ * but because we are the idle thread, we just pick up running again -+ * when this runqueue becomes "idle". -+ */ -+ __sched_fork(0, current); -+ init_idle(current, smp_processor_id()); -+ -+ calc_load_update = jiffies + LOAD_FREQ; -+ -+ idle_thread_set_boot_cpu(); -+ balance_push_set(smp_processor_id(), false); -+ -+ sched_init_topology_cpumask_early(); -+ -+ psi_init(); -+ -+ preempt_dynamic_init(); -+} -+ -+#ifdef CONFIG_DEBUG_ATOMIC_SLEEP -+ -+void __might_sleep(const char *file, int line) -+{ -+ unsigned int state = get_current_state(); -+ /* -+ * Blocking primitives will set (and therefore destroy) current->state, -+ * since we will exit with TASK_RUNNING make sure we enter with it, -+ * otherwise we will destroy state. -+ */ -+ WARN_ONCE(state != TASK_RUNNING && current->task_state_change, -+ "do not call blocking ops when !TASK_RUNNING; " -+ "state=%x set at [<%p>] %pS\n", state, -+ (void *)current->task_state_change, -+ (void *)current->task_state_change); -+ -+ __might_resched(file, line, 0); -+} -+EXPORT_SYMBOL(__might_sleep); -+ -+static void print_preempt_disable_ip(int preempt_offset, unsigned long ip) -+{ -+ if (!IS_ENABLED(CONFIG_DEBUG_PREEMPT)) -+ return; -+ -+ if (preempt_count() == preempt_offset) -+ return; -+ -+ pr_err("Preemption disabled at:"); -+ print_ip_sym(KERN_ERR, ip); -+} -+ -+static inline bool resched_offsets_ok(unsigned int offsets) -+{ -+ unsigned int nested = preempt_count(); -+ -+ nested += rcu_preempt_depth() << MIGHT_RESCHED_RCU_SHIFT; -+ -+ return nested == offsets; -+} -+ -+void __might_resched(const char *file, int line, unsigned int offsets) -+{ -+ /* Ratelimiting timestamp: */ -+ static unsigned long prev_jiffy; -+ -+ unsigned long preempt_disable_ip; -+ -+ /* WARN_ON_ONCE() by default, no rate limit required: */ -+ rcu_sleep_check(); -+ -+ if ((resched_offsets_ok(offsets) && !irqs_disabled() && -+ !is_idle_task(current) && !current->non_block_count) || -+ system_state == SYSTEM_BOOTING || system_state > SYSTEM_RUNNING || -+ oops_in_progress) -+ return; -+ if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy) -+ return; -+ prev_jiffy = jiffies; -+ -+ /* Save this before calling printk(), since that will clobber it: */ -+ preempt_disable_ip = get_preempt_disable_ip(current); -+ -+ pr_err("BUG: sleeping function called from invalid context at %s:%d\n", -+ file, line); -+ pr_err("in_atomic(): %d, irqs_disabled(): %d, non_block: %d, pid: %d, name: %s\n", -+ in_atomic(), irqs_disabled(), current->non_block_count, -+ current->pid, current->comm); -+ pr_err("preempt_count: %x, expected: %x\n", preempt_count(), -+ offsets & MIGHT_RESCHED_PREEMPT_MASK); -+ -+ if (IS_ENABLED(CONFIG_PREEMPT_RCU)) { -+ pr_err("RCU nest depth: %d, expected: %u\n", -+ rcu_preempt_depth(), offsets >> MIGHT_RESCHED_RCU_SHIFT); -+ } -+ -+ if (task_stack_end_corrupted(current)) -+ pr_emerg("Thread overran stack, or stack corrupted\n"); -+ -+ debug_show_held_locks(current); -+ if (irqs_disabled()) -+ print_irqtrace_events(current); -+ -+ print_preempt_disable_ip(offsets & MIGHT_RESCHED_PREEMPT_MASK, -+ preempt_disable_ip); -+ -+ dump_stack(); -+ add_taint(TAINT_WARN, LOCKDEP_STILL_OK); -+} -+EXPORT_SYMBOL(__might_resched); -+ -+void __cant_sleep(const char *file, int line) -+{ -+ static unsigned long prev_jiffy; -+ -+ if (irqs_disabled()) -+ return; -+ -+ if (!IS_ENABLED(CONFIG_PREEMPT_COUNT)) -+ return; -+ -+ if (preempt_count()) -+ return; -+ -+ if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy) -+ return; -+ prev_jiffy = jiffies; -+ -+ printk(KERN_ERR "BUG: assuming atomic context at %s:%d\n", file, line); -+ printk(KERN_ERR "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n", -+ in_atomic(), irqs_disabled(), -+ current->pid, current->comm); -+ -+ debug_show_held_locks(current); -+ dump_stack(); -+ add_taint(TAINT_WARN, LOCKDEP_STILL_OK); -+} -+EXPORT_SYMBOL_GPL(__cant_sleep); -+ -+void __cant_migrate(const char *file, int line) -+{ -+ static unsigned long prev_jiffy; -+ -+ if (irqs_disabled()) -+ return; -+ -+ if (is_migration_disabled(current)) -+ return; -+ -+ if (!IS_ENABLED(CONFIG_PREEMPT_COUNT)) -+ return; -+ -+ if (preempt_count()) -+ return; -+ -+ if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy) -+ return; -+ prev_jiffy = jiffies; -+ -+ pr_err("BUG: assuming non migratable context at %s:%d\n", file, line); -+ pr_err("in_atomic(): %d, irqs_disabled(): %d, migration_disabled() %u pid: %d, name: %s\n", -+ in_atomic(), irqs_disabled(), is_migration_disabled(current), -+ current->pid, current->comm); -+ -+ debug_show_held_locks(current); -+ dump_stack(); -+ add_taint(TAINT_WARN, LOCKDEP_STILL_OK); -+} -+EXPORT_SYMBOL_GPL(__cant_migrate); -+#endif /* CONFIG_DEBUG_ATOMIC_SLEEP */ -+ -+#ifdef CONFIG_MAGIC_SYSRQ -+void normalize_rt_tasks(void) -+{ -+ struct task_struct *g, *p; -+ struct sched_attr attr = { -+ .sched_policy = SCHED_NORMAL, -+ }; -+ -+ read_lock(&tasklist_lock); -+ for_each_process_thread(g, p) { -+ /* -+ * Only normalize user tasks: -+ */ -+ if (p->flags & PF_KTHREAD) -+ continue; -+ -+ schedstat_set(p->stats.wait_start, 0); -+ schedstat_set(p->stats.sleep_start, 0); -+ schedstat_set(p->stats.block_start, 0); -+ -+ if (!rt_or_dl_task(p)) { -+ /* -+ * Renice negative nice level userspace -+ * tasks back to 0: -+ */ -+ if (task_nice(p) < 0) -+ set_user_nice(p, 0); -+ continue; -+ } -+ -+ __sched_setscheduler(p, &attr, false, false); -+ } -+ read_unlock(&tasklist_lock); -+} -+#endif /* CONFIG_MAGIC_SYSRQ */ -+ -+#ifdef CONFIG_KGDB_KDB -+/* -+ * These functions are only useful for KDB. -+ * -+ * They can only be called when the whole system has been -+ * stopped - every CPU needs to be quiescent, and no scheduling -+ * activity can take place. Using them for anything else would -+ * be a serious bug, and as a result, they aren't even visible -+ * under any other configuration. -+ */ -+ -+/** -+ * curr_task - return the current task for a given CPU. -+ * @cpu: the processor in question. -+ * -+ * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED! -+ * -+ * Return: The current task for @cpu. -+ */ -+struct task_struct *curr_task(int cpu) -+{ -+ return cpu_curr(cpu); -+} -+ -+#endif /* CONFIG_KGDB_KDB */ -+ -+#ifdef CONFIG_CGROUP_SCHED -+static void sched_free_group(struct task_group *tg) -+{ -+ kmem_cache_free(task_group_cache, tg); -+} -+ -+static void sched_free_group_rcu(struct rcu_head *rhp) -+{ -+ sched_free_group(container_of(rhp, struct task_group, rcu)); -+} -+ -+static void sched_unregister_group(struct task_group *tg) -+{ -+ /* -+ * We have to wait for yet another RCU grace period to expire, as -+ * print_cfs_stats() might run concurrently. -+ */ -+ call_rcu(&tg->rcu, sched_free_group_rcu); -+} -+ -+/* allocate runqueue etc for a new task group */ -+struct task_group *sched_create_group(struct task_group *parent) -+{ -+ struct task_group *tg; -+ -+ tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO); -+ if (!tg) -+ return ERR_PTR(-ENOMEM); -+ -+ return tg; -+} -+ -+void sched_online_group(struct task_group *tg, struct task_group *parent) -+{ -+} -+ -+/* RCU callback to free various structures associated with a task group */ -+static void sched_unregister_group_rcu(struct rcu_head *rhp) -+{ -+ /* Now it should be safe to free those cfs_rqs: */ -+ sched_unregister_group(container_of(rhp, struct task_group, rcu)); -+} -+ -+void sched_destroy_group(struct task_group *tg) -+{ -+ /* Wait for possible concurrent references to cfs_rqs complete: */ -+ call_rcu(&tg->rcu, sched_unregister_group_rcu); -+} -+ -+void sched_release_group(struct task_group *tg) -+{ -+} -+ -+static inline struct task_group *css_tg(struct cgroup_subsys_state *css) -+{ -+ return css ? container_of(css, struct task_group, css) : NULL; -+} -+ -+static struct cgroup_subsys_state * -+cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css) -+{ -+ struct task_group *parent = css_tg(parent_css); -+ struct task_group *tg; -+ -+ if (!parent) { -+ /* This is early initialization for the top cgroup */ -+ return &root_task_group.css; -+ } -+ -+ tg = sched_create_group(parent); -+ if (IS_ERR(tg)) -+ return ERR_PTR(-ENOMEM); -+ return &tg->css; -+} -+ -+/* Expose task group only after completing cgroup initialization */ -+static int cpu_cgroup_css_online(struct cgroup_subsys_state *css) -+{ -+ struct task_group *tg = css_tg(css); -+ struct task_group *parent = css_tg(css->parent); -+ -+ if (parent) -+ sched_online_group(tg, parent); -+ return 0; -+} -+ -+static void cpu_cgroup_css_released(struct cgroup_subsys_state *css) -+{ -+ struct task_group *tg = css_tg(css); -+ -+ sched_release_group(tg); -+} -+ -+static void cpu_cgroup_css_free(struct cgroup_subsys_state *css) -+{ -+ struct task_group *tg = css_tg(css); -+ -+ /* -+ * Relies on the RCU grace period between css_released() and this. -+ */ -+ sched_unregister_group(tg); -+} -+ -+#ifdef CONFIG_RT_GROUP_SCHED -+static int cpu_cgroup_can_attach(struct cgroup_taskset *tset) -+{ -+ return 0; -+} -+#endif /* CONFIG_RT_GROUP_SCHED */ -+ -+static void cpu_cgroup_attach(struct cgroup_taskset *tset) -+{ -+} -+ -+#ifdef CONFIG_GROUP_SCHED_WEIGHT -+static int sched_group_set_shares(struct task_group *tg, unsigned long shares) -+{ -+ return 0; -+} -+ -+static int sched_group_set_idle(struct task_group *tg, long idle) -+{ -+ return 0; -+} -+ -+static int cpu_shares_write_u64(struct cgroup_subsys_state *css, -+ struct cftype *cftype, u64 shareval) -+{ -+ return sched_group_set_shares(css_tg(css), shareval); -+} -+ -+static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css, -+ struct cftype *cft) -+{ -+ return 1024; -+} -+ -+static s64 cpu_idle_read_s64(struct cgroup_subsys_state *css, -+ struct cftype *cft) -+{ -+ return 0; -+} -+ -+static int cpu_idle_write_s64(struct cgroup_subsys_state *css, -+ struct cftype *cft, s64 idle) -+{ -+ return sched_group_set_idle(css_tg(css), idle); -+} -+#endif /* CONFIG_GROUP_SCHED_WEIGHT */ -+ -+#ifdef CONFIG_CFS_BANDWIDTH -+static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css, -+ struct cftype *cft) -+{ -+ return -1; -+} -+ -+static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css, -+ struct cftype *cftype, s64 cfs_quota_us) -+{ -+ return 0; -+} -+ -+static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css, -+ struct cftype *cft) -+{ -+ return 100000ULL; -+} -+ -+static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css, -+ struct cftype *cftype, u64 cfs_period_us) -+{ -+ return 0; -+} -+ -+static u64 cpu_cfs_burst_read_u64(struct cgroup_subsys_state *css, -+ struct cftype *cft) -+{ -+ return 0; -+} -+ -+static int cpu_cfs_burst_write_u64(struct cgroup_subsys_state *css, -+ struct cftype *cftype, u64 cfs_burst_us) -+{ -+ return 0; -+} -+ -+static int cpu_cfs_stat_show(struct seq_file *sf, void *v) -+{ -+ return 0; -+} -+ -+static int cpu_cfs_local_stat_show(struct seq_file *sf, void *v) -+{ -+ return 0; -+} -+#endif /* CONFIG_CFS_BANDWIDTH */ -+ -+#ifdef CONFIG_RT_GROUP_SCHED -+static int cpu_rt_runtime_write(struct cgroup_subsys_state *css, -+ struct cftype *cft, s64 val) -+{ -+ return 0; -+} -+ -+static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css, -+ struct cftype *cft) -+{ -+ return 0; -+} -+ -+static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css, -+ struct cftype *cftype, u64 rt_period_us) -+{ -+ return 0; -+} -+ -+static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css, -+ struct cftype *cft) -+{ -+ return 0; -+} -+#endif /* CONFIG_RT_GROUP_SCHED */ -+ -+#ifdef CONFIG_UCLAMP_TASK_GROUP -+static int cpu_uclamp_min_show(struct seq_file *sf, void *v) -+{ -+ seq_puts(sf, "0\n"); -+ return 0; -+} -+ -+static int cpu_uclamp_max_show(struct seq_file *sf, void *v) -+{ -+ seq_puts(sf, "max\n"); -+ return 0; -+} -+ -+static ssize_t cpu_uclamp_min_write(struct kernfs_open_file *of, -+ char *buf, size_t nbytes, -+ loff_t off) -+{ -+ return nbytes; -+} -+ -+static ssize_t cpu_uclamp_max_write(struct kernfs_open_file *of, -+ char *buf, size_t nbytes, -+ loff_t off) -+{ -+ return nbytes; -+} -+#endif /* CONFIG_UCLAMP_TASK_GROUP */ -+ -+static struct cftype cpu_legacy_files[] = { -+#ifdef CONFIG_GROUP_SCHED_WEIGHT -+ { -+ .name = "shares", -+ .read_u64 = cpu_shares_read_u64, -+ .write_u64 = cpu_shares_write_u64, -+ }, -+ { -+ .name = "idle", -+ .read_s64 = cpu_idle_read_s64, -+ .write_s64 = cpu_idle_write_s64, -+ }, -+#endif /* CONFIG_GROUP_SCHED_WEIGHT */ -+#ifdef CONFIG_CFS_BANDWIDTH -+ { -+ .name = "cfs_quota_us", -+ .read_s64 = cpu_cfs_quota_read_s64, -+ .write_s64 = cpu_cfs_quota_write_s64, -+ }, -+ { -+ .name = "cfs_period_us", -+ .read_u64 = cpu_cfs_period_read_u64, -+ .write_u64 = cpu_cfs_period_write_u64, -+ }, -+ { -+ .name = "cfs_burst_us", -+ .read_u64 = cpu_cfs_burst_read_u64, -+ .write_u64 = cpu_cfs_burst_write_u64, -+ }, -+ { -+ .name = "stat", -+ .seq_show = cpu_cfs_stat_show, -+ }, -+ { -+ .name = "stat.local", -+ .seq_show = cpu_cfs_local_stat_show, -+ }, -+#endif /* CONFIG_CFS_BANDWIDTH */ -+#ifdef CONFIG_RT_GROUP_SCHED -+ { -+ .name = "rt_runtime_us", -+ .read_s64 = cpu_rt_runtime_read, -+ .write_s64 = cpu_rt_runtime_write, -+ }, -+ { -+ .name = "rt_period_us", -+ .read_u64 = cpu_rt_period_read_uint, -+ .write_u64 = cpu_rt_period_write_uint, -+ }, -+#endif /* CONFIG_RT_GROUP_SCHED */ -+#ifdef CONFIG_UCLAMP_TASK_GROUP -+ { -+ .name = "uclamp.min", -+ .flags = CFTYPE_NOT_ON_ROOT, -+ .seq_show = cpu_uclamp_min_show, -+ .write = cpu_uclamp_min_write, -+ }, -+ { -+ .name = "uclamp.max", -+ .flags = CFTYPE_NOT_ON_ROOT, -+ .seq_show = cpu_uclamp_max_show, -+ .write = cpu_uclamp_max_write, -+ }, -+#endif /* CONFIG_UCLAMP_TASK_GROUP */ -+ { } /* Terminate */ -+}; -+ -+#ifdef CONFIG_GROUP_SCHED_WEIGHT -+static u64 cpu_weight_read_u64(struct cgroup_subsys_state *css, -+ struct cftype *cft) -+{ -+ return 100; -+} -+ -+static int cpu_weight_write_u64(struct cgroup_subsys_state *css, -+ struct cftype *cft, u64 weight) -+{ -+ return 0; -+} -+ -+static s64 cpu_weight_nice_read_s64(struct cgroup_subsys_state *css, -+ struct cftype *cft) -+{ -+ return 0; -+} -+ -+static int cpu_weight_nice_write_s64(struct cgroup_subsys_state *css, -+ struct cftype *cft, s64 nice) -+{ -+ return 0; -+} -+#endif /* CONFIG_GROUP_SCHED_WEIGHT */ -+ -+#ifdef CONFIG_CFS_BANDWIDTH -+static int cpu_max_show(struct seq_file *sf, void *v) -+{ -+ seq_puts(sf, "max 100000\n"); -+ return 0; -+} -+ -+static ssize_t cpu_max_write(struct kernfs_open_file *of, -+ char *buf, size_t nbytes, loff_t off) -+{ -+ return nbytes; -+} -+#endif /* CONFIG_CFS_BANDWIDTH */ -+ -+static struct cftype cpu_files[] = { -+#ifdef CONFIG_GROUP_SCHED_WEIGHT -+ { -+ .name = "weight", -+ .flags = CFTYPE_NOT_ON_ROOT, -+ .read_u64 = cpu_weight_read_u64, -+ .write_u64 = cpu_weight_write_u64, -+ }, -+ { -+ .name = "weight.nice", -+ .flags = CFTYPE_NOT_ON_ROOT, -+ .read_s64 = cpu_weight_nice_read_s64, -+ .write_s64 = cpu_weight_nice_write_s64, -+ }, -+ { -+ .name = "idle", -+ .flags = CFTYPE_NOT_ON_ROOT, -+ .read_s64 = cpu_idle_read_s64, -+ .write_s64 = cpu_idle_write_s64, -+ }, -+#endif /* CONFIG_GROUP_SCHED_WEIGHT */ -+#ifdef CONFIG_CFS_BANDWIDTH -+ { -+ .name = "max", -+ .flags = CFTYPE_NOT_ON_ROOT, -+ .seq_show = cpu_max_show, -+ .write = cpu_max_write, -+ }, -+ { -+ .name = "max.burst", -+ .flags = CFTYPE_NOT_ON_ROOT, -+ .read_u64 = cpu_cfs_burst_read_u64, -+ .write_u64 = cpu_cfs_burst_write_u64, -+ }, -+#endif /* CONFIG_CFS_BANDWIDTH */ -+#ifdef CONFIG_UCLAMP_TASK_GROUP -+ { -+ .name = "uclamp.min", -+ .flags = CFTYPE_NOT_ON_ROOT, -+ .seq_show = cpu_uclamp_min_show, -+ .write = cpu_uclamp_min_write, -+ }, -+ { -+ .name = "uclamp.max", -+ .flags = CFTYPE_NOT_ON_ROOT, -+ .seq_show = cpu_uclamp_max_show, -+ .write = cpu_uclamp_max_write, -+ }, -+#endif /* CONFIG_UCLAMP_TASK_GROUP */ -+ { } /* terminate */ -+}; -+ -+static int cpu_extra_stat_show(struct seq_file *sf, -+ struct cgroup_subsys_state *css) -+{ -+ return 0; -+} -+ -+static int cpu_local_stat_show(struct seq_file *sf, -+ struct cgroup_subsys_state *css) -+{ -+ return 0; -+} -+ -+struct cgroup_subsys cpu_cgrp_subsys = { -+ .css_alloc = cpu_cgroup_css_alloc, -+ .css_online = cpu_cgroup_css_online, -+ .css_released = cpu_cgroup_css_released, -+ .css_free = cpu_cgroup_css_free, -+ .css_extra_stat_show = cpu_extra_stat_show, -+ .css_local_stat_show = cpu_local_stat_show, -+#ifdef CONFIG_RT_GROUP_SCHED -+ .can_attach = cpu_cgroup_can_attach, -+#endif /* CONFIG_RT_GROUP_SCHED */ -+ .attach = cpu_cgroup_attach, -+ .legacy_cftypes = cpu_legacy_files, -+ .dfl_cftypes = cpu_files, -+ .early_init = true, -+ .threaded = true, -+}; -+#endif /* CONFIG_CGROUP_SCHED */ -+ -+#undef CREATE_TRACE_POINTS -+ -+#ifdef CONFIG_SCHED_MM_CID -+/* -+ * Concurrency IDentifier management -+ * -+ * Serialization rules: -+ * -+ * mm::mm_cid::mutex: Serializes fork() and exit() and therefore -+ * protects mm::mm_cid::users and mode switch -+ * transitions -+ * -+ * mm::mm_cid::lock: Serializes mm_update_max_cids() and -+ * mm_update_cpus_allowed(). Nests in mm_cid::mutex -+ * and runqueue lock. -+ * -+ * The mm_cidmask bitmap is not protected by any of the mm::mm_cid locks -+ * and can only be modified with atomic operations. -+ * -+ * The mm::mm_cid:pcpu per CPU storage is protected by the CPUs runqueue -+ * lock. -+ * -+ * CID ownership: -+ * -+ * A CID is either owned by a task (stored in task_struct::mm_cid.cid) or -+ * by a CPU (stored in mm::mm_cid.pcpu::cid). CIDs owned by CPUs have the -+ * MM_CID_ONCPU bit set. -+ * -+ * During the transition of ownership mode, the MM_CID_TRANSIT bit is set -+ * on the CIDs. When this bit is set the tasks drop the CID back into the -+ * pool when scheduling out. -+ * -+ * Both bits (ONCPU and TRANSIT) are filtered out by task_cid() when the -+ * CID is actually handed over to user space in the RSEQ memory. -+ * -+ * Mode switching: -+ * -+ * The ownership mode is per process and stored in mm:mm_cid::mode with the -+ * following possible states: -+ * -+ * 0: Per task ownership -+ * 0 | MM_CID_TRANSIT: Transition from per CPU to per task -+ * MM_CID_ONCPU: Per CPU ownership -+ * MM_CID_ONCPU | MM_CID_TRANSIT: Transition from per task to per CPU -+ * -+ * All transitions of ownership mode happen in two phases: -+ * -+ * 1) mm:mm_cid::mode has the MM_CID_TRANSIT bit set. This is OR'ed on the -+ * CIDs and denotes that the CID is only temporarily owned by a -+ * task. When the task schedules out it drops the CID back into the -+ * pool if this bit is set. -+ * -+ * 2) The initiating context walks the per CPU space or the tasks to fixup -+ * or drop the CIDs and after completion it clears MM_CID_TRANSIT in -+ * mm:mm_cid::mode. After that point the CIDs are strictly task or CPU -+ * owned again. -+ * -+ * This two phase transition is required to prevent CID space exhaustion -+ * during the transition as a direct transfer of ownership would fail: -+ * -+ * - On task to CPU mode switch if a task is scheduled in on one CPU and -+ * then migrated to another CPU before the fixup freed enough per task -+ * CIDs. -+ * -+ * - On CPU to task mode switch if two tasks are scheduled in on the same -+ * CPU before the fixup freed per CPU CIDs. -+ * -+ * Both scenarios can result in a live lock because sched_in() is invoked -+ * with runqueue lock held and loops in search of a CID and the fixup -+ * thread can't make progress freeing them up because it is stuck on the -+ * same runqueue lock. -+ * -+ * While MM_CID_TRANSIT is active during the transition phase the MM_CID -+ * bitmap can be contended, but that's a temporary contention bound to the -+ * transition period. After that everything goes back into steady state and -+ * nothing except fork() and exit() will touch the bitmap. This is an -+ * acceptable tradeoff as it completely avoids complex serialization, -+ * memory barriers and atomic operations for the common case. -+ * -+ * Aside of that this mechanism also ensures RT compability: -+ * -+ * - The task which runs the fixup is fully preemptible except for the -+ * short runqueue lock held sections. -+ * -+ * - The transient impact of the bitmap contention is only problematic -+ * when there is a thundering herd scenario of tasks scheduling in and -+ * out concurrently. There is not much which can be done about that -+ * except for avoiding mode switching by a proper overall system -+ * configuration. -+ * -+ * Switching to per CPU mode happens when the user count becomes greater -+ * than the maximum number of CIDs, which is calculated by: -+ * -+ * opt_cids = min(mm_cid::nr_cpus_allowed, mm_cid::users); -+ * max_cids = min(1.25 * opt_cids, num_possible_cpus()); -+ * -+ * The +25% allowance is useful for tight CPU masks in scenarios where only -+ * a few threads are created and destroyed to avoid frequent mode -+ * switches. Though this allowance shrinks, the closer opt_cids becomes to -+ * num_possible_cpus(), which is the (unfortunate) hard ABI limit. -+ * -+ * At the point of switching to per CPU mode the new user is not yet -+ * visible in the system, so the task which initiated the fork() runs the -+ * fixup function. mm_cid_fixup_tasks_to_cpu() walks the thread list and -+ * either marks each task owned CID with MM_CID_TRANSIT if the task is -+ * running on a CPU or drops it into the CID pool if a task is not on a -+ * CPU. Tasks which schedule in before the task walk reaches them do the -+ * handover in mm_cid_schedin(). When mm_cid_fixup_tasks_to_cpus() -+ * completes it is guaranteed that no task related to that MM owns a CID -+ * anymore. -+ * -+ * Switching back to task mode happens when the user count goes below the -+ * threshold which was recorded on the per CPU mode switch: -+ * -+ * pcpu_thrs = min(opt_cids - (opt_cids / 4), num_possible_cpus() / 2); -+ * -+ * This threshold is updated when a affinity change increases the number of -+ * allowed CPUs for the MM, which might cause a switch back to per task -+ * mode. -+ * -+ * If the switch back was initiated by a exiting task, then that task runs -+ * the fixup function. If it was initiated by a affinity change, then it's -+ * run either in the deferred update function in context of a workqueue or -+ * by a task which forks a new one or by a task which exits. Whatever -+ * happens first. mm_cid_fixup_cpus_to_task() walks through the possible -+ * CPUs and either transfers the CPU owned CIDs to a related task which -+ * runs on the CPU or drops it into the pool. Tasks which schedule in on a -+ * CPU which the walk did not cover yet do the handover themself. -+ * -+ * This transition from CPU to per task ownership happens in two phases: -+ * -+ * 1) mm:mm_cid.transit contains MM_CID_TRANSIT This is OR'ed on the task -+ * CID and denotes that the CID is only temporarily owned by the -+ * task. When it schedules out the task drops the CID back into the -+ * pool if this bit is set. -+ * -+ * 2) The initiating context walks the per CPU space and after completion -+ * clears mm:mm_cid.transit. So after that point the CIDs are strictly -+ * task owned again. -+ * -+ * This two phase transition is required to prevent CID space exhaustion -+ * during the transition as a direct transfer of ownership would fail if -+ * two tasks are scheduled in on the same CPU before the fixup freed per -+ * CPU CIDs. -+ * -+ * When mm_cid_fixup_cpus_to_tasks() completes it's guaranteed that no CID -+ * related to that MM is owned by a CPU anymore. -+ */ -+ -+/* -+ * Update the CID range properties when the constraints change. Invoked via -+ * fork(), exit() and affinity changes -+ */ -+static void __mm_update_max_cids(struct mm_mm_cid *mc) -+{ -+ unsigned int opt_cids, max_cids; -+ -+ /* Calculate the new optimal constraint */ -+ opt_cids = min(mc->nr_cpus_allowed, mc->users); -+ -+ /* Adjust the maximum CIDs to +25% limited by the number of possible CPUs */ -+ max_cids = min(opt_cids + (opt_cids / 4), num_possible_cpus()); -+ WRITE_ONCE(mc->max_cids, max_cids); -+} -+ -+static inline unsigned int mm_cid_calc_pcpu_thrs(struct mm_mm_cid *mc) -+{ -+ unsigned int opt_cids; -+ -+ opt_cids = min(mc->nr_cpus_allowed, mc->users); -+ /* Has to be at least 1 because 0 indicates PCPU mode off */ -+ return max(min(opt_cids - opt_cids / 4, num_possible_cpus() / 2), 1); -+} -+ -+static bool mm_update_max_cids(struct mm_struct *mm) -+{ -+ struct mm_mm_cid *mc = &mm->mm_cid; -+ bool percpu = cid_on_cpu(mc->mode); -+ -+ lockdep_assert_held(&mm->mm_cid.lock); -+ -+ /* Clear deferred mode switch flag. A change is handled by the caller */ -+ mc->update_deferred = false; -+ __mm_update_max_cids(mc); -+ -+ /* Check whether owner mode must be changed */ -+ if (!percpu) { -+ /* Enable per CPU mode when the number of users is above max_cids */ -+ if (mc->users > mc->max_cids) -+ mc->pcpu_thrs = mm_cid_calc_pcpu_thrs(mc); -+ } else { -+ /* Switch back to per task if user count under threshold */ -+ if (mc->users < mc->pcpu_thrs) -+ mc->pcpu_thrs = 0; -+ } -+ -+ /* Mode change required? */ -+ if (percpu == !!mc->pcpu_thrs) -+ return false; -+ -+ /* Flip the mode and set the transition flag to bridge the transfer */ -+ WRITE_ONCE(mc->mode, mc->mode ^ (MM_CID_TRANSIT | MM_CID_ONCPU)); -+ /* -+ * Order the store against the subsequent fixups so that -+ * acquire(rq::lock) cannot be reordered by the CPU before the -+ * store. -+ */ -+ smp_mb(); -+ return true; -+} -+ -+static inline void mm_update_cpus_allowed(struct mm_struct *mm, const struct cpumask *affmsk) -+{ -+ struct cpumask *mm_allowed; -+ struct mm_mm_cid *mc; -+ unsigned int weight; -+ -+ if (!mm || !READ_ONCE(mm->mm_cid.users)) -+ return; -+ /* -+ * mm::mm_cid::mm_cpus_allowed is the superset of each threads -+ * allowed CPUs mask which means it can only grow. -+ */ -+ mc = &mm->mm_cid; -+ guard(raw_spinlock)(&mc->lock); -+ mm_allowed = mm_cpus_allowed(mm); -+ weight = cpumask_weighted_or(mm_allowed, mm_allowed, affmsk); -+ if (weight == mc->nr_cpus_allowed) -+ return; -+ -+ WRITE_ONCE(mc->nr_cpus_allowed, weight); -+ __mm_update_max_cids(mc); -+ if (!cid_on_cpu(mc->mode)) -+ return; -+ -+ /* Adjust the threshold to the wider set */ -+ mc->pcpu_thrs = mm_cid_calc_pcpu_thrs(mc); -+ /* Switch back to per task mode? */ -+ if (mc->users >= mc->pcpu_thrs) -+ return; -+ -+ /* Don't queue twice */ -+ if (mc->update_deferred) -+ return; -+ -+ /* Queue the irq work, which schedules the real work */ -+ mc->update_deferred = true; -+ irq_work_queue(&mc->irq_work); -+} -+ -+static inline void mm_cid_complete_transit(struct mm_struct *mm, unsigned int mode) -+{ -+ /* -+ * Ensure that the store removing the TRANSIT bit cannot be -+ * reordered by the CPU before the fixups have been completed. -+ */ -+ smp_mb(); -+ WRITE_ONCE(mm->mm_cid.mode, mode); -+} -+ -+static inline void mm_cid_transit_to_task(struct task_struct *t, struct mm_cid_pcpu *pcp) -+{ -+ if (cid_on_cpu(t->mm_cid.cid)) { -+ unsigned int cid = cpu_cid_to_cid(t->mm_cid.cid); -+ -+ t->mm_cid.cid = cid_to_transit_cid(cid); -+ pcp->cid = t->mm_cid.cid; -+ } -+} -+ -+static void mm_cid_fixup_cpus_to_tasks(struct mm_struct *mm) -+{ -+ unsigned int cpu; -+ -+ /* Walk the CPUs and fixup all stale CIDs */ -+ for_each_possible_cpu(cpu) { -+ struct mm_cid_pcpu *pcp = per_cpu_ptr(mm->mm_cid.pcpu, cpu); -+ struct rq *rq = cpu_rq(cpu); -+ -+ /* Remote access to mm::mm_cid::pcpu requires rq_lock */ -+ guard(rq_lock_irq)(rq); -+ /* Is the CID still owned by the CPU? */ -+ if (cid_on_cpu(pcp->cid)) { -+ /* -+ * If rq->curr has @mm, transfer it with the -+ * transition bit set. Otherwise drop it. -+ */ -+ if (rq->curr->mm == mm && rq->curr->mm_cid.active) -+ mm_cid_transit_to_task(rq->curr, pcp); -+ else -+ mm_drop_cid_on_cpu(mm, pcp); -+ -+ } else if (rq->curr->mm == mm && rq->curr->mm_cid.active) { -+ unsigned int cid = rq->curr->mm_cid.cid; -+ -+ /* -+ * Set the transition bit only on a genuine task-owned -+ * CID. A running active task can legitimately have -+ * MM_CID_UNSET here: in per-CPU mode CIDs are assigned -+ * lazily on schedule-in, so the fork()/execve() window -+ * leaves the task active with no owned CID. Setting the -+ * transition bit on MM_CID_UNSET would later feed -+ * clear_bit() an out-of-bounds bit number via -+ * mm_cid_schedout(), so exclude it. A CPU-owned -+ * (MM_CID_ONCPU) CID is handled by the cid_on_cpu() -+ * branch above and never reaches here. -+ */ -+ if (cid != MM_CID_UNSET && !cid_in_transit(cid)) { -+ cid = cid_to_transit_cid(cid); -+ rq->curr->mm_cid.cid = cid; -+ pcp->cid = cid; -+ } -+ } -+ } -+ mm_cid_complete_transit(mm, 0); -+} -+ -+static inline void mm_cid_transit_to_cpu(struct task_struct *t, struct mm_cid_pcpu *pcp) -+{ -+ if (cid_on_task(t->mm_cid.cid)) { -+ t->mm_cid.cid = cid_to_transit_cid(t->mm_cid.cid); -+ pcp->cid = t->mm_cid.cid; -+ } -+} -+ -+static void mm_cid_fixup_task_to_cpu(struct task_struct *t, struct mm_struct *mm) -+{ -+ /* Remote access to mm::mm_cid::pcpu requires rq_lock */ -+ guard(task_rq_lock)(t); -+ if (cid_on_task(t->mm_cid.cid)) { -+ /* If running on the CPU, put the CID in transit mode, otherwise drop it */ -+ if (task_rq(t)->curr == t) -+ mm_cid_transit_to_cpu(t, per_cpu_ptr(mm->mm_cid.pcpu, task_cpu(t))); -+ else -+ mm_unset_cid_on_task(t); -+ } -+} -+ -+static void mm_cid_fixup_tasks_to_cpus(void) -+{ -+ struct mm_struct *mm = current->mm; -+ struct task_struct *t; -+ -+ lockdep_assert_held(&mm->mm_cid.mutex); -+ -+ hlist_for_each_entry(t, &mm->mm_cid.user_list, mm_cid.node) { -+ /* Current has already transferred before invoking the fixup. */ -+ if (t != current) -+ mm_cid_fixup_task_to_cpu(t, mm); -+ } -+ -+ mm_cid_complete_transit(mm, MM_CID_ONCPU); -+} -+ -+static bool sched_mm_cid_add_user(struct task_struct *t, struct mm_struct *mm) -+{ -+ lockdep_assert_held(&mm->mm_cid.lock); -+ -+ t->mm_cid.active = 1; -+ hlist_add_head(&t->mm_cid.node, &mm->mm_cid.user_list); -+ mm->mm_cid.users++; -+ return mm_update_max_cids(mm); -+} -+ -+static void sched_mm_cid_fork(struct task_struct *t) -+{ -+ struct mm_struct *mm = t->mm; -+ bool percpu; -+ -+ if (!mm) -+ return; -+ -+ WARN_ON_ONCE(t->mm_cid.cid != MM_CID_UNSET); -+ -+ guard(mutex)(&mm->mm_cid.mutex); -+ scoped_guard(raw_spinlock_irq, &mm->mm_cid.lock) { -+ struct mm_cid_pcpu *pcp = this_cpu_ptr(mm->mm_cid.pcpu); -+ -+ /* First user ? */ -+ if (!mm->mm_cid.users) { -+ sched_mm_cid_add_user(t, mm); -+ t->mm_cid.cid = mm_get_cid(mm); -+ /* Required for execve() */ -+ pcp->cid = t->mm_cid.cid; -+ return; -+ } -+ -+ if (!sched_mm_cid_add_user(t, mm)) { -+ if (!cid_on_cpu(mm->mm_cid.mode)) -+ t->mm_cid.cid = mm_get_cid(mm); -+ return; -+ } -+ -+ /* Handle the mode change and transfer current's CID */ -+ percpu = cid_on_cpu(mm->mm_cid.mode); -+ if (!percpu) -+ mm_cid_transit_to_task(current, pcp); -+ else -+ mm_cid_transit_to_cpu(current, pcp); -+ } -+ -+ if (percpu) { -+ mm_cid_fixup_tasks_to_cpus(); -+ } else { -+ mm_cid_fixup_cpus_to_tasks(mm); -+ t->mm_cid.cid = mm_get_cid(mm); -+ } -+} -+ -+static bool sched_mm_cid_remove_user(struct task_struct *t) -+{ -+ lockdep_assert_held(&t->mm->mm_cid.lock); -+ -+ t->mm_cid.active = 0; -+ /* Clear the transition bit */ -+ t->mm_cid.cid = cid_from_transit_cid(t->mm_cid.cid); -+ mm_unset_cid_on_task(t); -+ hlist_del_init(&t->mm_cid.node); -+ t->mm->mm_cid.users--; -+ return mm_update_max_cids(t->mm); -+} -+ -+static bool __sched_mm_cid_exit(struct task_struct *t) -+{ -+ struct mm_struct *mm = t->mm; -+ -+ if (!sched_mm_cid_remove_user(t)) -+ return false; -+ /* -+ * Contrary to fork() this only deals with a switch back to per -+ * task mode either because the above decreased users or an -+ * affinity change increased the number of allowed CPUs and the -+ * deferred fixup did not run yet. -+ */ -+ if (WARN_ON_ONCE(cid_on_cpu(mm->mm_cid.mode))) -+ return false; -+ /* -+ * A failed fork(2) cleanup never gets here, so @current must have -+ * the same MM as @t. That's true for exit() and the failed -+ * pthread_create() cleanup case. -+ */ -+ if (WARN_ON_ONCE(current->mm != mm)) -+ return false; -+ return true; -+} -+ -+/* -+ * When a task exits, the MM CID held by the task is not longer required as -+ * the task cannot return to user space. -+ */ -+void sched_mm_cid_exit(struct task_struct *t) -+{ -+ struct mm_struct *mm = t->mm; -+ -+ if (!mm || !t->mm_cid.active) -+ return; -+ /* -+ * Ensure that only one instance is doing MM CID operations within -+ * a MM. The common case is uncontended. The rare fixup case adds -+ * some overhead. -+ */ -+ scoped_guard(mutex, &mm->mm_cid.mutex) { -+ /* mm_cid::mutex is sufficient to protect mm_cid::users */ -+ if (likely(mm->mm_cid.users > 1)) { -+ scoped_guard(raw_spinlock_irq, &mm->mm_cid.lock) { -+ if (!__sched_mm_cid_exit(t)) -+ return; -+ /* -+ * Mode change. The task has the CID unset -+ * already and dealt with an eventually set -+ * TRANSIT bit. If the CID is owned by the CPU -+ * then drop it. -+ */ -+ mm_drop_cid_on_cpu(mm, this_cpu_ptr(mm->mm_cid.pcpu)); -+ } -+ mm_cid_fixup_cpus_to_tasks(mm); -+ return; -+ } -+ /* Last user */ -+ scoped_guard(raw_spinlock_irq, &mm->mm_cid.lock) { -+ /* Required across execve() */ -+ if (t == current) -+ mm_cid_transit_to_task(t, this_cpu_ptr(mm->mm_cid.pcpu)); -+ /* Ignore mode change. There is nothing to do. */ -+ sched_mm_cid_remove_user(t); -+ } -+ } -+ -+ /* -+ * As this is the last user (execve(), process exit or failed -+ * fork(2)) there is no concurrency anymore. -+ * -+ * Synchronize eventually pending work to ensure that there are no -+ * dangling references left. @t->mm_cid.users is zero so nothing -+ * can queue this work anymore. -+ */ -+ irq_work_sync(&mm->mm_cid.irq_work); -+ cancel_work_sync(&mm->mm_cid.work); -+} -+ -+/* Deactivate MM CID allocation across execve() */ -+void sched_mm_cid_before_execve(struct task_struct *t) -+{ -+ sched_mm_cid_exit(t); -+} -+ -+/* Reactivate MM CID after execve() */ -+void sched_mm_cid_after_execve(struct task_struct *t) -+{ -+ if (t->mm) -+ sched_mm_cid_fork(t); -+} -+ -+static void mm_cid_work_fn(struct work_struct *work) -+{ -+ struct mm_struct *mm = container_of(work, struct mm_struct, mm_cid.work); -+ -+ guard(mutex)(&mm->mm_cid.mutex); -+ /* Did the last user task exit already? */ -+ if (!mm->mm_cid.users) -+ return; -+ -+ scoped_guard(raw_spinlock_irq, &mm->mm_cid.lock) { -+ /* Have fork() or exit() handled it already? */ -+ if (!mm->mm_cid.update_deferred) -+ return; -+ /* This clears mm_cid::update_deferred */ -+ if (!mm_update_max_cids(mm)) -+ return; -+ /* Affinity changes can only switch back to task mode */ -+ if (WARN_ON_ONCE(cid_on_cpu(mm->mm_cid.mode))) -+ return; -+ } -+ mm_cid_fixup_cpus_to_tasks(mm); -+} -+ -+static void mm_cid_irq_work(struct irq_work *work) -+{ -+ struct mm_struct *mm = container_of(work, struct mm_struct, mm_cid.irq_work); -+ -+ /* -+ * Needs to be unconditional because mm_cid::lock cannot be held -+ * when scheduling work as mm_update_cpus_allowed() nests inside -+ * rq::lock and schedule_work() might end up in wakeup... -+ */ -+ schedule_work(&mm->mm_cid.work); -+} -+ -+void mm_init_cid(struct mm_struct *mm, struct task_struct *p) -+{ -+ mm->mm_cid.max_cids = 0; -+ mm->mm_cid.mode = 0; -+ mm->mm_cid.nr_cpus_allowed = p->nr_cpus_allowed; -+ mm->mm_cid.users = 0; -+ mm->mm_cid.pcpu_thrs = 0; -+ mm->mm_cid.update_deferred = 0; -+ raw_spin_lock_init(&mm->mm_cid.lock); -+ mutex_init(&mm->mm_cid.mutex); -+ mm->mm_cid.irq_work = IRQ_WORK_INIT_HARD(mm_cid_irq_work); -+ INIT_WORK(&mm->mm_cid.work, mm_cid_work_fn); -+ INIT_HLIST_HEAD(&mm->mm_cid.user_list); -+ cpumask_copy(mm_cpus_allowed(mm), &p->cpus_mask); -+ bitmap_zero(mm_cidmask(mm), num_possible_cpus()); -+} -+#else /* CONFIG_SCHED_MM_CID */ -+static inline void mm_update_cpus_allowed(struct mm_struct *mm, const struct cpumask *affmsk) { } -+static inline void sched_mm_cid_fork(struct task_struct *t) { } -+#endif /* !CONFIG_SCHED_MM_CID */ -+ -+static DEFINE_PER_CPU(struct sched_change_ctx, sched_change_ctx); -+ -+struct sched_change_ctx *sched_change_begin(struct task_struct *p, unsigned int flags) -+{ -+ struct sched_change_ctx *ctx = this_cpu_ptr(&sched_change_ctx); -+ struct rq *rq = task_rq(p); -+ -+ /* -+ * Must exclusively use matched flags since this is both dequeue and -+ * enqueue. -+ */ -+ WARN_ON_ONCE(flags & 0xFFFF0000); -+ -+ lockdep_assert_rq_held(rq); -+ -+ if (!(flags & DEQUEUE_NOCLOCK)) { -+ update_rq_clock(rq); -+ flags |= DEQUEUE_NOCLOCK; -+ } -+ -+ *ctx = (struct sched_change_ctx){ -+ .p = p, -+ .flags = flags, -+ .queued = task_on_rq_queued(p), -+ }; -+ -+ return ctx; -+} -+ -+void sched_change_end(struct sched_change_ctx *ctx) -+{ -+ struct task_struct *p = ctx->p; -+ struct rq *rq = task_rq(ctx->p); -+ -+ lockdep_assert_rq_held(rq); -+ -+ /* Trigger resched if task sched_prio has been modified. */ -+ if (ctx->queued) { -+ requeue_task(p, rq, ctx->flags); -+ wakeup_preempt(rq); -+ } -+} -diff --git a/kernel/sched/alt_core.h b/kernel/sched/alt_core.h -new file mode 100644 -index 0000000..f1b9d59 ---- /dev/null -+++ b/kernel/sched/alt_core.h -@@ -0,0 +1,109 @@ -+#ifndef _KERNEL_SCHED_ALT_CORE_H -+#define _KERNEL_SCHED_ALT_CORE_H -+ -+/* -+ * Compile time debug macro -+ * #define ALT_SCHED_DEBUG -+ */ -+ -+/* CONFIG_SCHED_CLASS_EXT is not supported */ -+#define scx_switched_all() false -+ -+/* -+ * Context API -+ */ -+static inline struct rq *__task_access_lock(struct task_struct *p, raw_spinlock_t **plock) -+ __context_unsafe(/* conditionally returns with the rq lock held */) -+{ -+ struct rq *rq; -+ for (;;) { -+ rq = task_rq(p); -+ if (p->on_cpu || task_on_rq_queued(p)) { -+ raw_spin_rq_lock(rq); -+ if (likely((p->on_cpu || task_on_rq_queued(p)) && rq == task_rq(p))) { -+ *plock = rq_lockp(rq); -+ return rq; -+ } -+ raw_spin_rq_unlock(rq); -+ } else if (task_on_rq_migrating(p)) { -+ do { -+ cpu_relax(); -+ } while (unlikely(task_on_rq_migrating(p))); -+ } else { -+ *plock = NULL; -+ return rq; -+ } -+ } -+} -+ -+static inline void __task_access_unlock(struct task_struct *p, raw_spinlock_t *lock) -+ __context_unsafe(/* conditionally releases the returned rq lock */) -+{ -+ if (NULL != lock) -+ raw_spin_unlock(lock); -+} -+ -+/* -+ * RQ related inlined functions -+ */ -+ -+/* -+ * This routine assume that the idle task always in queue -+ */ -+static inline struct task_struct *sched_rq_first_task(struct rq *rq) -+{ -+ const struct list_head *head = &rq->queue.heads[sched_rq_prio_idx(rq)]; -+ -+ return list_first_entry(head, struct task_struct, sq_node); -+} -+ -+static __always_inline struct task_struct * sched_rq_next_task(struct task_struct *p, struct rq *rq) -+{ -+ struct list_head *next = p->sq_node.next; -+ -+ if (&rq->queue.heads[0] <= next && next < &rq->queue.heads[SCHED_LEVELS]) { -+ struct list_head *head; -+ unsigned long idx = next - &rq->queue.heads[0]; -+ -+ idx = find_next_bit(rq->queue.bitmap, SCHED_QUEUE_BITS, -+ sched_idx2prio(idx, rq) + 1); -+ head = &rq->queue.heads[sched_prio2idx(idx, rq)]; -+ -+ return list_first_entry(head, struct task_struct, sq_node); -+ } -+ -+ return list_next_entry(p, sq_node); -+} -+ -+extern void requeue_task(struct task_struct *p, struct rq *rq, int flags); -+ -+#ifdef ALT_SCHED_DEBUG -+extern void alt_sched_debug(void); -+#else -+static inline void alt_sched_debug(void) {} -+#endif -+ -+extern int sched_yield_type; -+ -+extern cpumask_t sched_rq_pending_mask ____cacheline_aligned_in_smp; -+ -+DECLARE_STATIC_KEY_FALSE(sched_smt_present); -+DECLARE_PER_CPU_ALIGNED(cpumask_t *, sched_cpu_llc_mask); -+ -+extern cpumask_t sched_smt_mask ____cacheline_aligned_in_smp; -+#ifdef CONFIG_SCHED_SMT -+DECLARE_PER_CPU_ALIGNED(raw_spinlock_t, sched_smt_idle_lock); -+#endif -+ -+extern cpumask_t *const sched_idle_mask; -+extern cpumask_t *const sched_sg_idle_mask; -+extern cpumask_t *const sched_pcore_idle_mask; -+extern cpumask_t *const sched_ecore_idle_mask; -+ -+extern struct rq *move_queued_task(struct rq *rq, struct rq_flags *rf, -+ struct task_struct *p, int new_cpu) -+ __must_hold(__rq_lockp(rq)); -+ -+DECLARE_STATIC_CALL(sched_idle_select_func, cpumask_and); -+ -+#endif /* _KERNEL_SCHED_ALT_CORE_H */ -diff --git a/kernel/sched/alt_debug.c b/kernel/sched/alt_debug.c -new file mode 100644 -index 0000000..1dbd7eb ---- /dev/null -+++ b/kernel/sched/alt_debug.c -@@ -0,0 +1,32 @@ -+/* -+ * kernel/sched/alt_debug.c -+ * -+ * Print the alt scheduler debugging details -+ * -+ * Author: Alfred Chen -+ * Date : 2020 -+ */ -+#include "sched.h" -+#include "linux/sched/debug.h" -+ -+/* -+ * This allows printing both to /proc/sched_debug and -+ * to the console -+ */ -+#define SEQ_printf(m, x...) \ -+ do { \ -+ if (m) \ -+ seq_printf(m, x); \ -+ else \ -+ pr_cont(x); \ -+ } while (0) -+ -+void proc_sched_show_task(struct task_struct *p, struct pid_namespace *ns, -+ struct seq_file *m) -+{ -+ SEQ_printf(m, "%s (%d, #threads: %d)\n", p->comm, task_pid_nr_ns(p, ns), -+ get_nr_threads(p)); -+} -+ -+void proc_sched_set_task(struct task_struct *p) -+{} -diff --git a/kernel/sched/alt_sched.h b/kernel/sched/alt_sched.h -new file mode 100644 -index 0000000..a04751f ---- /dev/null -+++ b/kernel/sched/alt_sched.h -@@ -0,0 +1,1350 @@ -+#ifndef _KERNEL_SCHED_ALT_SCHED_H -+#define _KERNEL_SCHED_ALT_SCHED_H -+ -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+ -+#include -+#include -+ -+#include "../workqueue_internal.h" -+ -+struct rq; -+struct cpuidle_state; -+ -+#include "cpupri.h" -+ -+#ifdef CONFIG_CGROUP_SCHED -+/* task group related information */ -+struct task_group { -+ struct cgroup_subsys_state css; -+ -+ struct rcu_head rcu; -+ struct list_head list; -+ -+ struct task_group *parent; -+ struct list_head siblings; -+ struct list_head children; -+}; -+ -+extern struct task_group *sched_create_group(struct task_group *parent); -+extern void sched_online_group(struct task_group *tg, -+ struct task_group *parent); -+extern void sched_destroy_group(struct task_group *tg); -+extern void sched_release_group(struct task_group *tg); -+static inline void __sched_cgroup_mode_update(int mode) { } -+#endif /* CONFIG_CGROUP_SCHED */ -+ -+#define MIN_SCHED_NORMAL_PRIO (32) -+/* -+ * levels: RT(0-24), reserved(25-31), NORMAL(32-63), cpu idle task(64) -+ * -+ * -- BMQ -- -+ * NORMAL: (lower boost range 12, NICE_WIDTH 40, higher boost range 12) / 2 -+ * -- PDS -- -+ * NORMAL: SCHED_EDGE_DELTA + ((NICE_WIDTH 40) / 2) -+ */ -+#define SCHED_LEVELS (64 + 1) -+ -+#define IDLE_TASK_SCHED_PRIO (SCHED_LEVELS - 1) -+ -+/* task_struct::on_rq states: */ -+#define TASK_ON_RQ_QUEUED 1 -+#define TASK_ON_RQ_MIGRATING 2 -+ -+/* -+ * Increase resolution of nice-level calculations for 64-bit architectures. -+ * The extra resolution improves shares distribution and load balancing of -+ * low-weight task groups (eg. nice +19 on an autogroup), deeper taskgroup -+ * hierarchies, especially on larger systems. This is not a user-visible change -+ * and does not change the user-interface for setting shares/weights. -+ * -+ * We increase resolution only if we have enough bits to allow this increased -+ * resolution (i.e. 64-bit). The costs for increasing resolution when 32-bit -+ * are pretty high and the returns do not justify the increased costs. -+ * -+ * Really only required when CONFIG_FAIR_GROUP_SCHED=y is also set, but to -+ * increase coverage and consistency always enable it on 64-bit platforms. -+ */ -+#ifdef CONFIG_64BIT -+# define NICE_0_LOAD_SHIFT (SCHED_FIXEDPOINT_SHIFT + SCHED_FIXEDPOINT_SHIFT) -+# define scale_load(w) ((w) << SCHED_FIXEDPOINT_SHIFT) -+# define scale_load_down(w) \ -+({ \ -+ unsigned long __w = (w); \ -+ if (__w) \ -+ __w = max(2UL, __w >> SCHED_FIXEDPOINT_SHIFT); \ -+ __w; \ -+}) -+#else -+# define NICE_0_LOAD_SHIFT (SCHED_FIXEDPOINT_SHIFT) -+# define scale_load(w) (w) -+# define scale_load_down(w) (w) -+#endif -+ -+static inline int normal_policy(int policy) -+{ -+ return policy == SCHED_NORMAL; -+} -+ -+static inline int fair_policy(int policy) -+{ -+ return normal_policy(policy) || policy == SCHED_BATCH; -+} -+ -+static inline int rt_policy(int policy) -+{ -+ return policy == SCHED_FIFO || policy == SCHED_RR; -+} -+ -+#define valid_policy(policy) ((policy) <= SCHED_IDLE) -+ -+static inline int task_has_rt_policy(struct task_struct *p) -+{ -+ return rt_policy(p->policy); -+} -+ -+#define task_has_dl_policy(p) (false) -+#define dl_prio(prio) (false) -+ -+#define cap_scale(v, s) ((v)*(s) >> SCHED_CAPACITY_SHIFT) -+ -+/* -+ * !! For sched_setattr_nocheck() (kernel) only !! -+ * -+ * This is actually gross. :( -+ * -+ * It is used to make schedutil kworker(s) higher priority than SCHED_DEADLINE -+ * tasks, but still be able to sleep. We need this on platforms that cannot -+ * atomically change clock frequency. Remove once fast switching will be -+ * available on such platforms. -+ * -+ * SUGOV stands for SchedUtil GOVernor. -+ */ -+#define SCHED_FLAG_SUGOV 0x10000000 -+ -+#define SCHED_QUEUE_BITS (SCHED_LEVELS - 1) -+ -+struct sched_queue { -+ DECLARE_BITMAP(bitmap, SCHED_QUEUE_BITS); -+ struct list_head heads[SCHED_LEVELS]; -+}; -+ -+struct balance_callback { -+ struct balance_callback *next; -+ void (*func)(struct rq *rq); -+}; -+ -+struct balance_arg { -+ struct task_struct *task; -+ int active; -+ cpumask_t *cpumask; -+}; -+ -+/* -+ * This is the main, per-CPU runqueue data structure. -+ * This data should only be modified by the local cpu. -+ */ -+struct rq { -+ /* runqueue lock: */ -+ raw_spinlock_t __lock; -+ -+ struct task_struct __rcu *curr; -+ struct task_struct *idle; -+ struct task_struct *stop; -+ struct mm_struct *prev_mm; -+ -+ /* switch count */ -+ u64 nr_switches; -+ -+ u64 last_seen_need_resched_ns; -+ int ticks_without_resched; -+ -+ struct sched_queue queue ____cacheline_aligned; -+ -+ int prio; -+#ifdef CONFIG_SCHED_PDS -+ int prio_idx; -+ u64 time_edge; -+#endif -+ -+ atomic_t nr_iowait; -+ -+#ifdef CONFIG_MEMBARRIER -+ int membarrier_state; -+#endif -+ -+ int cpu; /* cpu of this runqueue */ -+ bool online; -+ -+ unsigned int ttwu_pending; -+ unsigned char nohz_idle_balance; -+ unsigned char idle_balance; -+ -+#ifdef CONFIG_HAVE_SCHED_AVG_IRQ -+ struct sched_avg avg_irq; -+#endif -+ -+ struct balance_arg active_balance_arg ____cacheline_aligned; -+ struct cpu_stop_work active_balance_work; -+ -+ struct balance_callback *balance_callback; -+ -+#ifdef CONFIG_HOTPLUG_CPU -+ struct rcuwait hotplug_wait; -+#endif -+ unsigned int nr_pinned; -+ -+#ifdef CONFIG_IRQ_TIME_ACCOUNTING -+ u64 psi_irq_time; -+#endif /* CONFIG_IRQ_TIME_ACCOUNTING */ -+#ifdef CONFIG_PARAVIRT -+ u64 prev_steal_time; -+#endif /* CONFIG_PARAVIRT */ -+#ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING -+ u64 prev_steal_time_rq; -+#endif /* CONFIG_PARAVIRT_TIME_ACCOUNTING */ -+ -+ /* calc_load related fields */ -+ unsigned long calc_load_update; -+ long calc_load_active; -+ -+ /* Ensure that all clocks are in the same cache line */ -+ u64 clock ____cacheline_aligned; -+ u64 clock_task; -+ u64 prio_balance_time; -+#ifdef CONFIG_IRQ_TIME_ACCOUNTING -+ u64 prev_irq_time; -+#endif /* CONFIG_IRQ_TIME_ACCOUNTING */ -+ -+ /* For genenal cpu load util */ -+ u64 load_block; -+ u64 load_stamp; -+ s32 load_history; -+ -+ unsigned int nr_running; -+ unsigned long nr_uninterruptible; -+ -+#ifdef CONFIG_SCHED_HRTICK -+ call_single_data_t hrtick_csd; -+ struct hrtimer hrtick_timer; -+ ktime_t hrtick_time; -+ ktime_t hrtick_delay; -+ unsigned int hrtick_sched; -+#endif -+ -+#ifdef CONFIG_SCHEDSTATS -+ -+ /* latency stats */ -+ struct sched_info rq_sched_info; -+ unsigned long long rq_cpu_time; -+ /* could above be rq->cfs_rq.exec_clock + rq->rt_rq.rt_runtime ? */ -+ -+ /* sys_sched_yield() stats */ -+ unsigned int yld_count; -+ -+ /* schedule() stats */ -+ unsigned int sched_count; -+ unsigned int sched_goidle; -+ -+ /* try_to_wake_up() stats */ -+ unsigned int ttwu_count; -+ unsigned int ttwu_local; -+#endif /* CONFIG_SCHEDSTATS */ -+ -+#ifdef CONFIG_CPU_IDLE -+ /* Must be inspected within a rcu lock section */ -+ struct cpuidle_state *idle_state; -+#endif -+ -+#ifdef CONFIG_NO_HZ_COMMON -+ call_single_data_t nohz_csd; -+ atomic_t nohz_flags; -+#endif /* CONFIG_NO_HZ_COMMON */ -+ -+ /* Scratch cpumask to be temporarily used under rq_lock */ -+ cpumask_var_t scratch_mask; -+} __no_randomize_layout; -+ -+static inline int cpu_of(const struct rq *rq) -+{ -+ return rq->cpu; -+} -+ -+static inline bool is_migration_disabled(struct task_struct *p) -+{ -+ return p->migration_disabled; -+} -+ -+extern unsigned int sysctl_sched_base_slice; -+ -+/* Reschedule if less than this many μs left */ -+#define RESCHED_NS (100 << 10) -+ -+extern unsigned long rq_load_util(struct rq *rq, unsigned long max); -+ -+extern unsigned long calc_load_update; -+extern atomic_long_t calc_load_tasks; -+ -+extern void calc_global_load_tick(struct rq *this_rq); -+extern long calc_load_fold_active(struct rq *this_rq, long adjust); -+ -+DECLARE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues); -+#define cpu_rq(cpu) (&per_cpu(runqueues, (cpu))) -+static __always_inline struct rq *__this_rq(void) -+{ -+ return this_cpu_ptr(&runqueues); -+} -+ -+#define this_rq() __this_rq() -+#define task_rq(p) cpu_rq(task_cpu(p)) -+#define cpu_curr(cpu) (cpu_rq(cpu)->curr) -+#define raw_rq() raw_cpu_ptr(&runqueues) -+ -+static inline bool idle_rq(struct rq *rq) -+{ -+ return rq->curr == rq->idle && !rq->nr_running && !rq->ttwu_pending; -+} -+ -+/** -+ * available_idle_cpu - is a given CPU idle for enqueuing work. -+ * @cpu: the CPU in question. -+ * -+ * Return: 1 if the CPU is currently idle. 0 otherwise. -+ */ -+static inline bool available_idle_cpu(int cpu) -+{ -+ if (!idle_rq(cpu_rq(cpu))) -+ return 0; -+ -+ if (vcpu_is_preempted(cpu)) -+ return 0; -+ -+ return 1; -+} -+ -+#ifdef CONFIG_SYSCTL -+void register_sched_domain_sysctl(void); -+void unregister_sched_domain_sysctl(void); -+#else -+static inline void register_sched_domain_sysctl(void) -+{ -+} -+static inline void unregister_sched_domain_sysctl(void) -+{ -+} -+#endif -+ -+extern bool sched_smp_initialized; -+ -+enum { -+#ifdef CONFIG_SCHED_SMT -+ SCHED_CPU_AFFINITY_SMT, -+#endif -+ SCHED_CPU_AFFINITY_CLUSTER, -+ SCHED_CPU_AFFINITY_LLC, -+ SCHED_CPU_AFFINITY_CORE, -+ SCHED_CPU_AFFINITY_OTHER, -+ NR_CPU_AFFINITY_LEVELS -+}; -+ -+DECLARE_PER_CPU_ALIGNED(cpumask_t [NR_CPU_AFFINITY_LEVELS], sched_cpu_topo_masks); -+DECLARE_PER_CPU_ALIGNED(cpumask_t *, sched_cpu_topo_end_mask); -+ -+/* -+ * Affinity levels are nested, so a level which covers the same CPUs as the -+ * level below it repeats a search which has already failed. -+ */ -+static inline bool -+sched_cpu_topo_level_repeats(const cpumask_t *topo_masks, const cpumask_t *mask) -+{ -+ return mask > topo_masks && cpumask_equal(mask, mask - 1); -+} -+ -+static inline int -+__best_mask_cpu(const cpumask_t *cpumask, const cpumask_t *mask, -+ const cpumask_t *end_mask) -+{ -+ int cpu; -+ -+ while (mask < end_mask) { -+ cpu = cpumask_any_and(cpumask, mask); -+ if (cpu < nr_cpu_ids) -+ return cpu; -+ mask++; -+ } -+ -+ return cpumask_any(cpumask); -+} -+ -+static inline int best_mask_cpu(int cpu, const cpumask_t *mask) -+{ -+ return __best_mask_cpu(mask, per_cpu(sched_cpu_topo_masks, cpu), -+ per_cpu(sched_cpu_topo_end_mask, cpu)); -+} -+ -+extern void resched_latency_warn(int cpu, u64 latency); -+ -+static __always_inline raw_spinlock_t *rq_lockp(struct rq *rq) -+{ -+ return &rq->__lock; -+} -+ -+static __always_inline raw_spinlock_t *__rq_lockp(struct rq *rq) -+ __returns_ctx_lock(rq_lockp(rq)) /* alias them */ -+{ -+ return &rq->__lock; -+} -+ -+static inline void lockdep_assert_rq_held(struct rq *rq) -+ __assumes_ctx_lock(__rq_lockp(rq)) -+{ -+ lockdep_assert_held(__rq_lockp(rq)); -+} -+ -+extern void raw_spin_rq_lock_nested(struct rq *rq, int subclass) -+ __acquires(__rq_lockp(rq)); -+ -+extern bool raw_spin_rq_trylock(struct rq *rq) -+ __cond_acquires(true, __rq_lockp(rq)); -+ -+static __always_inline void raw_spin_rq_lock(struct rq *rq) -+ __acquires(__rq_lockp(rq)) -+{ -+ raw_spin_rq_lock_nested(rq, 0); -+} -+ -+static __always_inline void raw_spin_rq_unlock(struct rq *rq) -+ __releases(__rq_lockp(rq)) -+{ -+ raw_spin_unlock(rq_lockp(rq)); -+} -+ -+static __always_inline void raw_spin_rq_lock_irq(struct rq *rq) -+ __acquires(__rq_lockp(rq)) -+{ -+ local_irq_disable(); -+ raw_spin_rq_lock(rq); -+} -+ -+static __always_inline void raw_spin_rq_unlock_irq(struct rq *rq) -+ __releases(__rq_lockp(rq)) -+{ -+ raw_spin_rq_unlock(rq); -+ local_irq_enable(); -+} -+ -+static inline unsigned long _raw_spin_rq_lock_irqsave(struct rq *rq) -+ __acquires(__rq_lockp(rq)) -+{ -+ unsigned long flags; -+ -+ local_irq_save(flags); -+ raw_spin_rq_lock(rq); -+ -+ return flags; -+} -+ -+static inline void raw_spin_rq_unlock_irqrestore(struct rq *rq, -+ unsigned long flags) -+ __releases(__rq_lockp(rq)) -+{ -+ raw_spin_rq_unlock(rq); -+ local_irq_restore(flags); -+} -+ -+#define raw_spin_rq_lock_irqsave(rq, flags) \ -+do { \ -+ flags = _raw_spin_rq_lock_irqsave(rq); \ -+} while (0) -+ -+struct rq_flags { -+ unsigned long flags; -+ struct pin_cookie cookie; -+ raw_spinlock_t *lock; -+}; -+ -+extern struct balance_callback balance_push_callback; -+ -+static inline void assert_balance_callbacks_empty(struct rq *rq) -+{ -+ WARN_ON_ONCE(IS_ENABLED(CONFIG_PROVE_LOCKING) && -+ rq->balance_callback && -+ rq->balance_callback != &balance_push_callback); -+} -+ -+static inline void rq_pin_lock(struct rq *rq, struct rq_flags *rf) -+{ -+ rf->cookie = lockdep_pin_lock(__rq_lockp(rq)); -+ -+ assert_balance_callbacks_empty(rq); -+} -+ -+static inline void rq_unpin_lock(struct rq *rq, struct rq_flags *rf) -+{ -+ lockdep_unpin_lock(__rq_lockp(rq), rf->cookie); -+} -+ -+static inline void rq_repin_lock(struct rq *rq, struct rq_flags *rf) -+{ -+ lockdep_repin_lock(__rq_lockp(rq), rf->cookie); -+} -+ -+extern void update_rq_clock(struct rq *rq); -+ -+static inline u64 rq_clock(struct rq *rq) -+{ -+ lockdep_assert_rq_held(rq); -+ -+ return rq->clock; -+} -+ -+static inline u64 rq_clock_task(struct rq *rq) -+{ -+ lockdep_assert_rq_held(rq); -+ -+ return rq->clock_task; -+} -+ -+#define __task_rq_lock(...) __acquire_ret(___task_rq_lock(__VA_ARGS__), __rq_lockp(__ret)) -+extern struct rq *___task_rq_lock(struct task_struct *p, struct rq_flags *rf) __acquires_ret; -+ -+#define task_rq_lock(...) __acquire_ret(_task_rq_lock(__VA_ARGS__), __rq_lockp(__ret)) -+extern struct rq *_task_rq_lock(struct task_struct *p, struct rq_flags *rf) -+ __acquires(&p->pi_lock) __acquires_ret; -+ -+static inline void -+__task_rq_unlock(struct rq *rq, struct task_struct *p, struct rq_flags *rf) -+ __releases(__rq_lockp(rq)) -+{ -+ rq_unpin_lock(rq, rf); -+ raw_spin_rq_unlock(rq); -+} -+ -+static inline void -+task_rq_unlock(struct rq *rq, struct task_struct *p, struct rq_flags *rf) -+ __releases(__rq_lockp(rq), &p->pi_lock) -+{ -+ __task_rq_unlock(rq, p, rf); -+ raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags); -+} -+ -+DEFINE_LOCK_GUARD_1(task_rq_lock, struct task_struct, -+ _T->rq = task_rq_lock(_T->lock, &_T->rf), -+ task_rq_unlock(_T->rq, _T->lock, &_T->rf), -+ struct rq *rq; struct rq_flags rf) -+DECLARE_LOCK_GUARD_1_ATTRS(task_rq_lock, __acquires(&_T->pi_lock), -+ __releases(&(*(struct task_struct **)_T)->pi_lock)) -+#define class_task_rq_lock_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(task_rq_lock, _T) -+ -+DEFINE_LOCK_GUARD_1(__task_rq_lock, struct task_struct, -+ _T->rq = __task_rq_lock(_T->lock, &_T->rf), -+ __task_rq_unlock(_T->rq, _T->lock, &_T->rf), -+ struct rq *rq; struct rq_flags rf) -+ -+static inline void rq_lock_irqsave(struct rq *rq, struct rq_flags *rf) -+ __acquires(__rq_lockp(rq)) -+{ -+ raw_spin_rq_lock_irqsave(rq, rf->flags); -+ rq_pin_lock(rq, rf); -+} -+ -+static inline void -+rq_lock_irq(struct rq *rq, struct rq_flags *rf) -+ __acquires(__rq_lockp(rq)) -+{ -+ raw_spin_rq_lock_irq(rq); -+ rq_pin_lock(rq, rf); -+} -+ -+static inline void -+rq_lock(struct rq *rq, struct rq_flags *rf) -+ __acquires(__rq_lockp(rq)) -+{ -+ raw_spin_rq_lock(rq); -+ rq_pin_lock(rq, rf); -+} -+ -+static inline void rq_unlock_irqrestore(struct rq *rq, struct rq_flags *rf) -+ __releases(__rq_lockp(rq)) -+{ -+ rq_unpin_lock(rq, rf); -+ raw_spin_rq_unlock_irqrestore(rq, rf->flags); -+} -+ -+static inline void -+rq_unlock_irq(struct rq *rq, struct rq_flags *rf) -+ __releases(__rq_lockp(rq)) -+{ -+ rq_unpin_lock(rq, rf); -+ raw_spin_rq_unlock_irq(rq); -+} -+ -+static inline void -+rq_unlock(struct rq *rq, struct rq_flags *rf) -+ __releases(__rq_lockp(rq)) -+{ -+ rq_unpin_lock(rq, rf); -+ raw_spin_rq_unlock(rq); -+} -+ -+DEFINE_LOCK_GUARD_1(rq_lock, struct rq, -+ rq_lock(_T->lock, &_T->rf), -+ rq_unlock(_T->lock, &_T->rf), -+ struct rq_flags rf) -+DECLARE_LOCK_GUARD_1_ATTRS(rq_lock, __acquires(__rq_lockp(_T)), -+ __releases(__rq_lockp(*(struct rq **)_T))) -+#define class_rq_lock_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(rq_lock, _T) -+ -+DEFINE_LOCK_GUARD_1(rq_lock_irq, struct rq, -+ rq_lock_irq(_T->lock, &_T->rf), -+ rq_unlock_irq(_T->lock, &_T->rf), -+ struct rq_flags rf) -+DECLARE_LOCK_GUARD_1_ATTRS(rq_lock_irq, __acquires(__rq_lockp(_T)), -+ __releases(__rq_lockp(*(struct rq **)_T))) -+#define class_rq_lock_irq_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(rq_lock_irq, _T) -+ -+DEFINE_LOCK_GUARD_1(rq_lock_irqsave, struct rq, -+ rq_lock_irqsave(_T->lock, &_T->rf), -+ rq_unlock_irqrestore(_T->lock, &_T->rf), -+ struct rq_flags rf) -+DECLARE_LOCK_GUARD_1_ATTRS(rq_lock_irqsave, __acquires(__rq_lockp(_T)), -+ __releases(__rq_lockp(*(struct rq **)_T))) -+#define class_rq_lock_irqsave_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(rq_lock_irqsave, _T) -+ -+#define this_rq_lock_irq(...) __acquire_ret(_this_rq_lock_irq(__VA_ARGS__), __rq_lockp(__ret)) -+static inline struct rq *_this_rq_lock_irq(struct rq_flags *rf) __acquires_ret -+{ -+ struct rq *rq; -+ -+ local_irq_disable(); -+ rq = this_rq(); -+ rq_lock(rq, rf); -+ -+ return rq; -+} -+ -+extern struct static_key_false sched_schedstats; -+ -+static inline int task_current(struct rq *rq, struct task_struct *p) -+{ -+ return rq->curr == p; -+} -+ -+static inline bool task_on_cpu(struct rq *rq, struct task_struct *p) -+{ -+ return p->on_cpu; -+} -+ -+static inline int task_on_rq_queued(struct task_struct *p) -+{ -+ return READ_ONCE(p->on_rq) == TASK_ON_RQ_QUEUED; -+} -+ -+static inline int task_on_rq_migrating(struct task_struct *p) -+{ -+ return READ_ONCE(p->on_rq) == TASK_ON_RQ_MIGRATING; -+} -+ -+/* Wake flags. The first three directly map to some SD flag value */ -+#define WF_EXEC 0x02 /* Wakeup after exec; maps to SD_BALANCE_EXEC */ -+#define WF_FORK 0x04 /* Wakeup after fork; maps to SD_BALANCE_FORK */ -+#define WF_TTWU 0x08 /* Wakeup; maps to SD_BALANCE_WAKE */ -+ -+#define WF_SYNC 0x10 /* Waker goes to sleep after wakeup */ -+#define WF_MIGRATED 0x20 /* Internal use, task got migrated */ -+#define WF_CURRENT_CPU 0x40 /* Prefer to move the wakee to the current CPU. */ -+#define WF_RQ_SELECTED 0x80 /* ->select_task_rq() was called */ -+ -+static_assert(WF_EXEC == SD_BALANCE_EXEC); -+static_assert(WF_FORK == SD_BALANCE_FORK); -+static_assert(WF_TTWU == SD_BALANCE_WAKE); -+ -+/* -+ * {de,en}queue flags: -+ * -+ * SLEEP/WAKEUP - task is no-longer/just-became runnable -+ * -+ * SAVE/RESTORE - an otherwise spurious dequeue/enqueue, done to ensure tasks -+ * are in a known state which allows modification. Such pairs -+ * should preserve as much state as possible. -+ * -+ * MOVE - paired with SAVE/RESTORE, explicitly does not preserve the location -+ * in the runqueue. -+ * -+ * NOCLOCK - skip the update_rq_clock() (avoids double updates) -+ * -+ * MIGRATION - p->on_rq == TASK_ON_RQ_MIGRATING (used for DEADLINE) -+ * -+ * DELAYED - de/re-queue a sched_delayed task -+ * -+ * CLASS - going to update p->sched_class; makes sched_change call the -+ * various switch methods. -+ * -+ * ENQUEUE_HEAD - place at front of runqueue (tail if not specified) -+ * ENQUEUE_REPLENISH - CBS (replenish runtime and postpone deadline) -+ * ENQUEUE_MIGRATED - the task was migrated during wakeup -+ * ENQUEUE_RQ_SELECTED - ->select_task_rq() was called -+ * -+ * XXX SAVE/RESTORE in combination with CLASS doesn't really make sense, but -+ * SCHED_DEADLINE seems to rely on this for now. -+ */ -+ -+#define DEQUEUE_SLEEP 0x0001 /* Matches ENQUEUE_WAKEUP */ -+#define DEQUEUE_SAVE 0x0002 /* Matches ENQUEUE_RESTORE */ -+#define DEQUEUE_MOVE 0x0004 /* Matches ENQUEUE_MOVE */ -+#define DEQUEUE_NOCLOCK 0x0008 /* Matches ENQUEUE_NOCLOCK */ -+ -+#define DEQUEUE_MIGRATING 0x0010 /* Matches ENQUEUE_MIGRATING */ -+#define DEQUEUE_DELAYED 0x0020 /* Matches ENQUEUE_DELAYED */ -+#define DEQUEUE_CLASS 0x0040 /* Matches ENQUEUE_CLASS */ -+ -+#define DEQUEUE_SPECIAL 0x00010000 -+#define DEQUEUE_THROTTLE 0x00020000 -+ -+#define ENQUEUE_WAKEUP 0x0001 -+#define ENQUEUE_RESTORE 0x0002 -+#define ENQUEUE_MOVE 0x0004 -+#define ENQUEUE_NOCLOCK 0x0008 -+ -+#define ENQUEUE_MIGRATING 0x0010 -+#define ENQUEUE_DELAYED 0x0020 -+#define ENQUEUE_CLASS 0x0040 -+ -+#define ENQUEUE_HEAD 0x00010000 -+#define ENQUEUE_REPLENISH 0x00020000 -+#define ENQUEUE_MIGRATED 0x00040000 -+#define ENQUEUE_INITIAL 0x00080000 -+#define ENQUEUE_RQ_SELECTED 0x00100000 -+ -+ -+struct affinity_context { -+ const struct cpumask *new_mask; -+ struct cpumask *user_mask; -+ unsigned int flags; -+}; -+ -+#define SCA_CHECK 0x01 -+#define SCA_MIGRATE_DISABLE 0x02 -+#define SCA_MIGRATE_ENABLE 0x04 -+#define SCA_USER 0x08 -+ -+extern int __set_cpus_allowed_ptr(struct task_struct *p, struct affinity_context *ctx); -+ -+static inline bool task_allowed_on_cpu(struct task_struct *p, int cpu) -+{ -+ /* When not in the task's cpumask, no point in looking further. */ -+ if (!cpumask_test_cpu(cpu, p->cpus_ptr)) -+ return false; -+ -+ /* Can @cpu run a user thread? */ -+ if (!(p->flags & PF_KTHREAD) && !task_cpu_possible(cpu, p)) -+ return false; -+ -+ return true; -+} -+ -+static inline cpumask_t *alloc_user_cpus_ptr(int node) -+{ -+ /* -+ * See set_cpus_allowed_force() above for the rcu_head usage. -+ */ -+ int size = max_t(int, cpumask_size(), sizeof(struct rcu_head)); -+ -+ return kmalloc_node(size, GFP_KERNEL, node); -+} -+ -+#ifdef CONFIG_CPU_IDLE -+static inline void idle_set_state(struct rq *rq, -+ struct cpuidle_state *idle_state) -+{ -+ rq->idle_state = idle_state; -+} -+#else -+static inline void idle_set_state(struct rq *rq, -+ struct cpuidle_state *idle_state) -+{ -+} -+#endif -+ -+extern void resched_cpu(int cpu); -+ -+#ifdef CONFIG_NO_HZ_FULL -+extern int __init sched_tick_offload_init(void); -+#else -+static inline int sched_tick_offload_init(void) { return 0; } -+#endif -+ -+static inline void __block_task(struct rq *rq, struct task_struct *p) -+{ -+ if (p->sched_contributes_to_load) -+ rq->nr_uninterruptible++; -+ -+ if (p->in_iowait) { -+ atomic_inc(&rq->nr_iowait); -+ delayacct_blkio_start(); -+ } -+ -+ ASSERT_EXCLUSIVE_WRITER(p->on_rq); -+ -+ /* -+ * The moment this write goes through, ttwu() can swoop in and migrate -+ * this task, rendering our rq->__lock ineffective. -+ * -+ * __schedule() try_to_wake_up() -+ * LOCK rq->__lock LOCK p->pi_lock -+ * pick_next_task() -+ * pick_next_task_fair() -+ * pick_next_entity() -+ * dequeue_entities() -+ * __block_task() -+ * RELEASE p->on_rq = 0 if (p->on_rq && ...) -+ * break; -+ * -+ * ACQUIRE (after ctrl-dep) -+ * -+ * cpu = select_task_rq(); -+ * set_task_cpu(p, cpu); -+ * ttwu_queue() -+ * ttwu_do_activate() -+ * LOCK rq->__lock -+ * activate_task() -+ * STORE p->on_rq = 1 -+ * UNLOCK rq->__lock -+ * -+ * Callers must ensure to not reference @p after this -- we no longer -+ * own it. -+ */ -+ smp_store_release(&p->on_rq, 0); -+} -+ -+#ifndef arch_scale_freq_tick -+static __always_inline -+void arch_scale_freq_tick(void) -+{ -+} -+#endif -+ -+#ifndef arch_scale_freq_capacity -+static __always_inline -+unsigned long arch_scale_freq_capacity(int cpu) -+{ -+ return SCHED_CAPACITY_SCALE; -+} -+#endif -+ -+#ifdef CONFIG_NO_HZ_COMMON -+#define NOHZ_BALANCE_KICK_BIT 0 -+#define NOHZ_STATS_KICK_BIT 1 -+ -+#define NOHZ_BALANCE_KICK BIT(NOHZ_BALANCE_KICK_BIT) -+#define NOHZ_STATS_KICK BIT(NOHZ_STATS_KICK_BIT) -+ -+#define NOHZ_KICK_MASK (NOHZ_BALANCE_KICK | NOHZ_STATS_KICK) -+ -+#define nohz_flags(cpu) (&cpu_rq(cpu)->nohz_flags) -+ -+/* TODO: needed? -+extern void nohz_balance_exit_idle(struct rq *rq); -+#else -+static inline void nohz_balance_exit_idle(struct rq *rq) { } -+*/ -+#endif -+ -+static inline void nohz_run_idle_balance(int cpu) { } -+ -+#include "stats.h" -+ -+#ifdef CONFIG_IRQ_TIME_ACCOUNTING -+struct irqtime { -+ u64 total; -+ u64 tick_delta; -+ u64 irq_start_time; -+ struct u64_stats_sync sync; -+}; -+ -+DECLARE_PER_CPU(struct irqtime, cpu_irqtime); -+DECLARE_STATIC_KEY_FALSE(sched_clock_irqtime); -+ -+static inline int irqtime_enabled(void) -+{ -+ return static_branch_likely(&sched_clock_irqtime); -+} -+ -+/* -+ * Returns the irqtime minus the softirq time computed by ksoftirqd. -+ * Otherwise ksoftirqd's sum_exec_runtime is substracted its own runtime -+ * and never move forward. -+ */ -+static inline u64 irq_time_read(int cpu) -+{ -+ struct irqtime *irqtime = &per_cpu(cpu_irqtime, cpu); -+ unsigned int seq; -+ u64 total; -+ -+ do { -+ seq = __u64_stats_fetch_begin(&irqtime->sync); -+ total = irqtime->total; -+ } while (__u64_stats_fetch_retry(&irqtime->sync, seq)); -+ -+ return total; -+} -+#else -+ -+static inline int irqtime_enabled(void) -+{ -+ return 0; -+} -+ -+#endif /* CONFIG_IRQ_TIME_ACCOUNTING */ -+ -+#ifdef CONFIG_CPU_FREQ -+DECLARE_PER_CPU(struct update_util_data __rcu *, cpufreq_update_util_data); -+#endif /* CONFIG_CPU_FREQ */ -+ -+#ifdef arch_scale_freq_capacity -+#ifndef arch_scale_freq_invariant -+#define arch_scale_freq_invariant() (true) -+#endif -+#else /* arch_scale_freq_capacity */ -+#define arch_scale_freq_invariant() (false) -+#endif -+ -+unsigned long sugov_effective_cpu_perf(int cpu, unsigned long actual, -+ unsigned long min, -+ unsigned long max); -+ -+extern void schedule_idle(void); -+ -+asmlinkage void schedule_user(void); -+ -+#ifdef CONFIG_MEMBARRIER -+/* -+ * The scheduler provides memory barriers required by membarrier between: -+ * - prior user-space memory accesses and store to rq->membarrier_state, -+ * - store to rq->membarrier_state and following user-space memory accesses. -+ * In the same way it provides those guarantees around store to rq->curr. -+ */ -+static inline void membarrier_switch_mm(struct rq *rq, -+ struct mm_struct *prev_mm, -+ struct mm_struct *next_mm) -+{ -+ int membarrier_state; -+ -+ if (prev_mm == next_mm) -+ return; -+ -+ membarrier_state = atomic_read(&next_mm->membarrier_state); -+ if (READ_ONCE(rq->membarrier_state) == membarrier_state) -+ return; -+ -+ WRITE_ONCE(rq->membarrier_state, membarrier_state); -+} -+#else -+static inline void membarrier_switch_mm(struct rq *rq, -+ struct mm_struct *prev_mm, -+ struct mm_struct *next_mm) -+{ -+} -+#endif -+ -+#ifdef CONFIG_NUMA -+extern int sched_numa_find_closest(const struct cpumask *cpus, int cpu); -+#else -+static inline int sched_numa_find_closest(const struct cpumask *cpus, int cpu) -+{ -+ return nr_cpu_ids; -+} -+#endif -+ -+extern void swake_up_all_locked(struct swait_queue_head *q); -+extern void __prepare_to_swait(struct swait_queue_head *q, struct swait_queue *wait); -+ -+extern int try_to_wake_up(struct task_struct *tsk, unsigned int state, int wake_flags); -+ -+#ifdef CONFIG_PREEMPT_DYNAMIC -+extern int preempt_dynamic_mode; -+extern int sched_dynamic_mode(const char *str); -+extern void sched_dynamic_update(int mode); -+#endif -+extern const char *preempt_modes[]; -+ -+static inline unsigned long -+uclamp_eff_value(struct task_struct *p, enum uclamp_id clamp_id) -+{ -+ if (clamp_id == UCLAMP_MIN) -+ return 0; -+ -+ return SCHED_CAPACITY_SCALE; -+} -+ -+static inline bool uclamp_rq_is_capped(struct rq *rq) { return false; } -+ -+static inline bool uclamp_is_used(void) -+{ -+ return false; -+} -+ -+static inline unsigned long -+uclamp_rq_get(struct rq *rq, enum uclamp_id clamp_id) -+{ -+ if (clamp_id == UCLAMP_MIN) -+ return 0; -+ -+ return SCHED_CAPACITY_SCALE; -+} -+ -+static inline void -+uclamp_rq_set(struct rq *rq, enum uclamp_id clamp_id, unsigned int value) -+{ -+} -+ -+static inline bool uclamp_rq_is_idle(struct rq *rq) -+{ -+ return false; -+} -+ -+#ifdef CONFIG_SCHED_MM_CID -+ -+static __always_inline bool cid_on_cpu(unsigned int cid) -+{ -+ return cid & MM_CID_ONCPU; -+} -+ -+static __always_inline bool cid_in_transit(unsigned int cid) -+{ -+ return cid & MM_CID_TRANSIT; -+} -+ -+static __always_inline unsigned int cpu_cid_to_cid(unsigned int cid) -+{ -+ return cid & ~MM_CID_ONCPU; -+} -+ -+static __always_inline unsigned int cid_to_cpu_cid(unsigned int cid) -+{ -+ return cid | MM_CID_ONCPU; -+} -+ -+static __always_inline unsigned int cid_to_transit_cid(unsigned int cid) -+{ -+ return cid | MM_CID_TRANSIT; -+} -+ -+static __always_inline unsigned int cid_from_transit_cid(unsigned int cid) -+{ -+ return cid & ~MM_CID_TRANSIT; -+} -+ -+static __always_inline bool cid_on_task(unsigned int cid) -+{ -+ /* True if none of the MM_CID_ONCPU, MM_CID_TRANSIT, MM_CID_UNSET bits is set */ -+ return cid < MM_CID_TRANSIT; -+} -+ -+static __always_inline void mm_drop_cid(struct mm_struct *mm, unsigned int cid) -+{ -+ clear_bit(cid, mm_cidmask(mm)); -+} -+ -+static __always_inline void mm_unset_cid_on_task(struct task_struct *t) -+{ -+ unsigned int cid = t->mm_cid.cid; -+ -+ t->mm_cid.cid = MM_CID_UNSET; -+ if (cid_on_task(cid)) -+ mm_drop_cid(t->mm, cid); -+} -+ -+static __always_inline void mm_drop_cid_on_cpu(struct mm_struct *mm, struct mm_cid_pcpu *pcp) -+{ -+ /* Clear the ONCPU bit, but do not set UNSET in the per CPU storage */ -+ if (cid_on_cpu(pcp->cid)) { -+ pcp->cid = cpu_cid_to_cid(pcp->cid); -+ mm_drop_cid(mm, pcp->cid); -+ } -+} -+ -+static inline unsigned int __mm_get_cid(struct mm_struct *mm, unsigned int max_cids) -+{ -+ unsigned int cid = find_first_zero_bit(mm_cidmask(mm), max_cids); -+ -+ if (cid >= max_cids) -+ return MM_CID_UNSET; -+ if (test_and_set_bit(cid, mm_cidmask(mm))) -+ return MM_CID_UNSET; -+ return cid; -+} -+ -+static inline unsigned int mm_get_cid(struct mm_struct *mm) -+{ -+ unsigned int cid = __mm_get_cid(mm, READ_ONCE(mm->mm_cid.max_cids)); -+ -+ while (cid == MM_CID_UNSET) { -+ cpu_relax(); -+ cid = __mm_get_cid(mm, num_possible_cpus()); -+ } -+ return cid; -+} -+ -+static inline unsigned int mm_cid_converge(struct mm_struct *mm, unsigned int orig_cid, -+ unsigned int max_cids) -+{ -+ unsigned int new_cid, cid = cpu_cid_to_cid(orig_cid); -+ -+ /* Is it in the optimal CID space? */ -+ if (likely(cid < max_cids)) -+ return orig_cid; -+ -+ /* Try to find one in the optimal space. Otherwise keep the provided. */ -+ new_cid = __mm_get_cid(mm, max_cids); -+ if (new_cid != MM_CID_UNSET) { -+ mm_drop_cid(mm, cid); -+ /* Preserve the ONCPU mode of the original CID */ -+ return new_cid | (orig_cid & MM_CID_ONCPU); -+ } -+ return orig_cid; -+} -+ -+static __always_inline void mm_cid_update_task_cid(struct task_struct *t, unsigned int cid) -+{ -+ if (t->mm_cid.cid != cid) { -+ t->mm_cid.cid = cid; -+ rseq_sched_set_ids_changed(t); -+ } -+} -+ -+static __always_inline void mm_cid_update_pcpu_cid(struct mm_struct *mm, unsigned int cid) -+{ -+ __this_cpu_write(mm->mm_cid.pcpu->cid, cid); -+} -+ -+static __always_inline void mm_cid_from_cpu(struct task_struct *t, unsigned int cpu_cid, -+ unsigned int mode) -+{ -+ unsigned int max_cids, tcid = t->mm_cid.cid; -+ struct mm_struct *mm = t->mm; -+ -+ max_cids = READ_ONCE(mm->mm_cid.max_cids); -+ /* Optimize for the common case where both have the ONCPU bit set */ -+ if (likely(cid_on_cpu(cpu_cid & tcid))) { -+ if (likely(cpu_cid_to_cid(cpu_cid) < max_cids)) { -+ mm_cid_update_task_cid(t, cpu_cid); -+ return; -+ } -+ /* Try to converge into the optimal CID space */ -+ cpu_cid = mm_cid_converge(mm, cpu_cid, max_cids); -+ } else { -+ /* Hand over or drop the task owned CID */ -+ if (cid_on_task(tcid)) { -+ if (cid_on_cpu(cpu_cid)) -+ mm_unset_cid_on_task(t); -+ else -+ cpu_cid = cid_to_cpu_cid(tcid); -+ } -+ /* Still nothing, allocate a new one */ -+ if (!cid_on_cpu(cpu_cid)) -+ cpu_cid = cid_to_cpu_cid(mm_get_cid(mm)); -+ -+ /* Handle the transition mode flag if required */ -+ if (mode & MM_CID_TRANSIT) -+ cpu_cid = cpu_cid_to_cid(cpu_cid) | MM_CID_TRANSIT; -+ } -+ mm_cid_update_pcpu_cid(mm, cpu_cid); -+ mm_cid_update_task_cid(t, cpu_cid); -+} -+ -+static __always_inline void mm_cid_from_task(struct task_struct *t, unsigned int cpu_cid, -+ unsigned int mode) -+{ -+ unsigned int max_cids, tcid = t->mm_cid.cid; -+ struct mm_struct *mm = t->mm; -+ -+ max_cids = READ_ONCE(mm->mm_cid.max_cids); -+ /* Optimize for the common case, where both have the ONCPU bit clear */ -+ if (likely(cid_on_task(tcid | cpu_cid))) { -+ if (likely(tcid < max_cids)) { -+ mm_cid_update_pcpu_cid(mm, tcid); -+ return; -+ } -+ /* Try to converge into the optimal CID space */ -+ tcid = mm_cid_converge(mm, tcid, max_cids); -+ } else { -+ /* Hand over or drop the CPU owned CID */ -+ if (cid_on_cpu(cpu_cid)) { -+ if (cid_on_task(tcid)) -+ mm_drop_cid_on_cpu(mm, this_cpu_ptr(mm->mm_cid.pcpu)); -+ else -+ tcid = cpu_cid_to_cid(cpu_cid); -+ } -+ /* Still nothing, allocate a new one */ -+ if (!cid_on_task(tcid)) -+ tcid = mm_get_cid(mm); -+ /* Set the transition mode flag if required */ -+ tcid |= mode & MM_CID_TRANSIT; -+ } -+ mm_cid_update_pcpu_cid(mm, tcid); -+ mm_cid_update_task_cid(t, tcid); -+} -+ -+static __always_inline void mm_cid_schedin(struct task_struct *next) -+{ -+ struct mm_struct *mm = next->mm; -+ unsigned int cpu_cid, mode; -+ -+ if (!next->mm_cid.active) -+ return; -+ -+ cpu_cid = __this_cpu_read(mm->mm_cid.pcpu->cid); -+ mode = READ_ONCE(mm->mm_cid.mode); -+ if (likely(!cid_on_cpu(mode))) -+ mm_cid_from_task(next, cpu_cid, mode); -+ else -+ mm_cid_from_cpu(next, cpu_cid, mode); -+} -+ -+static __always_inline void mm_cid_schedout(struct task_struct *prev) -+{ -+ struct mm_struct *mm = prev->mm; -+ unsigned int mode, cid; -+ -+ /* During mode transitions CIDs are temporary and need to be dropped */ -+ if (likely(!cid_in_transit(prev->mm_cid.cid))) -+ return; -+ -+ mode = READ_ONCE(mm->mm_cid.mode); -+ cid = cid_from_transit_cid(prev->mm_cid.cid); -+ -+ /* -+ * If transition mode is done, transfer ownership when the CID is -+ * within the convergence range to optimize the next schedule in. -+ */ -+ if (!cid_in_transit(mode) && cid < READ_ONCE(mm->mm_cid.max_cids)) { -+ if (cid_on_cpu(mode)) -+ cid = cid_to_cpu_cid(cid); -+ -+ /* Update both so that the next schedule in goes into the fast path */ -+ mm_cid_update_pcpu_cid(mm, cid); -+ prev->mm_cid.cid = cid; -+ } else { -+ mm_drop_cid(mm, cid); -+ prev->mm_cid.cid = MM_CID_UNSET; -+ } -+} -+ -+static inline void mm_cid_switch_to(struct task_struct *prev, struct task_struct *next) -+{ -+ mm_cid_schedout(prev); -+ mm_cid_schedin(next); -+} -+ -+#else /* !CONFIG_SCHED_MM_CID: */ -+static inline void mm_cid_switch_to(struct task_struct *prev, struct task_struct *next) { } -+#endif /* !CONFIG_SCHED_MM_CID */ -+ -+static inline void -+queue_balance_callback(struct rq *rq, -+ struct balance_callback *head, -+ void (*func)(struct rq *rq)) -+{ -+ lockdep_assert_rq_held(rq); -+ -+ /* -+ * Don't (re)queue an already queued item; nor queue anything when -+ * balance_push() is active, see the comment with -+ * balance_push_callback. -+ */ -+ if (unlikely(head->next || rq->balance_callback == &balance_push_callback)) -+ return; -+ -+ head->func = func; -+ head->next = rq->balance_callback; -+ rq->balance_callback = head; -+} -+ -+#ifdef CONFIG_RT_MUTEXES -+ -+static inline int __rt_effective_prio(struct task_struct *pi_task, int prio) -+{ -+ if (pi_task) -+ prio = min(prio, pi_task->prio); -+ -+ return prio; -+} -+ -+static inline int rt_effective_prio(struct task_struct *p, int prio) -+{ -+ struct task_struct *pi_task = rt_mutex_get_top_task(p); -+ -+ return __rt_effective_prio(pi_task, prio); -+} -+ -+#else /* !CONFIG_RT_MUTEXES: */ -+ -+static inline int rt_effective_prio(struct task_struct *p, int prio) -+{ -+ return prio; -+} -+ -+#endif /* !CONFIG_RT_MUTEXES */ -+ -+extern int __sched_setscheduler(struct task_struct *p, const struct sched_attr *attr, bool user, bool pi); -+extern int __sched_setaffinity(struct task_struct *p, struct affinity_context *ctx); -+ -+/* balance callback */ -+extern void __balance_callbacks(struct rq *rq, struct rq_flags *rf); -+extern struct balance_callback *splice_balance_callbacks(struct rq *rq); -+extern void balance_callbacks(struct rq *rq, struct balance_callback *head); -+ -+/* -+ * The 'sched_change' pattern is the safe, easy and slow way of changing a -+ * task's scheduling properties. It dequeues a task, such that the scheduler -+ * is fully unaware of it; at which point its properties can be modified; -+ * after which it is enqueued again. -+ * -+ * Typically this must be called while holding task_rq_lock, since most/all -+ * properties are serialized under those locks. There is currently one -+ * exception to this rule in sched/ext which only holds rq->lock. -+ */ -+ -+/* -+ * This structure is a temporary, used to preserve/convey the queueing state -+ * of the task between sched_change_begin() and sched_change_end(). Ensuring -+ * the task's queueing state is idempotent across the operation. -+ */ -+struct sched_change_ctx { -+ u64 prio; -+ struct task_struct *p; -+ int flags; -+ bool queued; -+ bool running; -+}; -+ -+struct sched_change_ctx *sched_change_begin(struct task_struct *p, unsigned int flags); -+void sched_change_end(struct sched_change_ctx *ctx); -+ -+DEFINE_CLASS(sched_change, struct sched_change_ctx *, -+ sched_change_end(_T), -+ sched_change_begin(p, flags), -+ struct task_struct *p, unsigned int flags) -+ -+DEFINE_CLASS_IS_UNCONDITIONAL(sched_change) -+ -+#ifdef CONFIG_SCHED_BMQ -+#include "bmq.h" -+#endif -+#ifdef CONFIG_SCHED_PDS -+#include "pds.h" -+#endif -+ -+#endif /* _KERNEL_SCHED_ALT_SCHED_H */ -diff --git a/kernel/sched/alt_topology.c b/kernel/sched/alt_topology.c -new file mode 100644 -index 0000000..8fde696 ---- /dev/null -+++ b/kernel/sched/alt_topology.c -@@ -0,0 +1,731 @@ -+#include "alt_core.h" -+#include "alt_topology.h" -+ -+/* -+ * The override has been removed, but keep an obsolete setup entry so stale -+ * bootloader configurations are not passed to PID 1 as environment variables. -+ */ -+__setup_param("pcore_cpus=", pcore_cpus_obsolete, NULL, 0); -+ -+enum sched_idle_select_mode { -+ SCHED_IDLE_SELECT_GENERIC, -+#ifdef CONFIG_SCHED_SMT -+ SCHED_IDLE_SELECT_SMT, -+#endif -+ SCHED_IDLE_SELECT_HYBRID, -+}; -+ -+static cpumask_t sched_pcore_mask ____cacheline_aligned_in_smp; -+static cpumask_t sched_ecore_mask; -+static cpumask_t sched_unknown_mask; -+static cpumask_t sched_topology_active_mask; -+ -+/* CPU hotplug is serialized, so one set of rebuild masks is sufficient. */ -+static cpumask_t sched_rebuild_pcore_mask; -+static cpumask_t sched_rebuild_ecore_mask; -+static cpumask_t sched_rebuild_unknown_mask; -+static cpumask_t sched_rebuild_smt_mask; -+static cpumask_t sched_rebuild_visited_mask; -+#ifdef CONFIG_SCHED_SMT -+static cpumask_t sched_rebuild_group_mask; -+#endif -+ -+static enum sched_idle_select_mode sched_idle_select_mode __read_mostly; -+static enum sched_idle_select_mode sched_idle_select_applied __read_mostly; -+static bool sched_heterogeneous __read_mostly; -+static bool sched_mixed_cpu_types __read_mostly; -+static bool sched_unsupported_ecore_smt __read_mostly; -+static bool sched_topology_initialized; -+static bool sched_topology_changed; -+static bool sched_topology_active_changed; -+static bool sched_topology_warn_unknown; -+static bool sched_topology_warn_ecore_smt; -+static bool sched_topology_warn_smt_class; -+ -+#ifdef CONFIG_X86 -+static void sched_detect_cpu_types(const struct cpumask *active_mask) -+{ -+ int cpu; -+ -+ for_each_cpu(cpu, active_mask) { -+ switch (cpu_data(cpu).topo.cpu_type) { -+ case TOPO_CPU_TYPE_PERFORMANCE: -+ cpumask_set_cpu(cpu, &sched_rebuild_pcore_mask); -+ break; -+ case TOPO_CPU_TYPE_EFFICIENCY: -+ case TOPO_CPU_TYPE_LOW_POWER: -+ cpumask_set_cpu(cpu, &sched_rebuild_ecore_mask); -+ break; -+ case TOPO_CPU_TYPE_UNKNOWN: -+ default: -+ cpumask_set_cpu(cpu, &sched_rebuild_unknown_mask); -+ break; -+ } -+ } -+} -+#else -+static inline void sched_detect_cpu_types(const struct cpumask *active_mask) -+{ -+ cpumask_copy(&sched_rebuild_unknown_mask, active_mask); -+} -+#endif -+ -+#ifdef CONFIG_SCHED_SMT -+static bool -+sched_group_has_single_class(const struct cpumask *group, -+ const struct cpumask *pcore_mask, -+ const struct cpumask *ecore_mask, -+ const struct cpumask *unknown_mask) -+{ -+ return cpumask_subset(group, pcore_mask) || -+ cpumask_subset(group, ecore_mask) || -+ cpumask_subset(group, unknown_mask); -+} -+ -+static void sched_detect_smt(const struct cpumask *active_mask) -+{ -+ int cpu, sibling; -+ -+ cpumask_clear(&sched_rebuild_visited_mask); -+ -+ for_each_cpu(cpu, active_mask) { -+ int threads = 0; -+ -+ if (cpumask_test_cpu(cpu, &sched_rebuild_visited_mask)) -+ continue; -+ -+ cpumask_clear(&sched_rebuild_group_mask); -+ for_each_cpu(sibling, cpu_smt_mask(cpu)) { -+ if (!cpumask_test_cpu(sibling, active_mask)) -+ continue; -+ -+ cpumask_set_cpu(sibling, &sched_rebuild_group_mask); -+ cpumask_set_cpu(sibling, &sched_rebuild_visited_mask); -+ threads++; -+ } -+ -+ if (!threads) { -+ cpumask_set_cpu(cpu, &sched_rebuild_group_mask); -+ cpumask_set_cpu(cpu, &sched_rebuild_visited_mask); -+ threads = 1; -+ } -+ -+ if (threads < 2) -+ continue; -+ -+ cpumask_or(&sched_rebuild_smt_mask, &sched_rebuild_smt_mask, -+ &sched_rebuild_group_mask); -+ -+ if (sched_group_has_single_class(&sched_rebuild_group_mask, -+ &sched_rebuild_pcore_mask, -+ &sched_rebuild_ecore_mask, -+ &sched_rebuild_unknown_mask)) -+ continue; -+ -+ cpumask_andnot(&sched_rebuild_pcore_mask, -+ &sched_rebuild_pcore_mask, -+ &sched_rebuild_group_mask); -+ cpumask_andnot(&sched_rebuild_ecore_mask, -+ &sched_rebuild_ecore_mask, -+ &sched_rebuild_group_mask); -+ cpumask_or(&sched_rebuild_unknown_mask, -+ &sched_rebuild_unknown_mask, -+ &sched_rebuild_group_mask); -+ } -+} -+#else -+static inline void sched_detect_smt(const struct cpumask *active_mask) { } -+#endif -+ -+struct sched_topology_policy { -+ enum sched_idle_select_mode idle_select_mode; -+ bool heterogeneous; -+ bool mixed_cpu_types; -+ bool unsupported_ecore_smt; -+}; -+ -+static struct sched_topology_policy sched_rebuild_policy; -+ -+static void -+sched_select_topology_policy(const struct cpumask *active_mask, -+ const struct cpumask *pcore_mask, -+ const struct cpumask *ecore_mask, -+ const struct cpumask *unknown_mask, -+ const struct cpumask *smt_mask, -+ struct sched_topology_policy *policy) -+{ -+ bool have_known = !cpumask_empty(pcore_mask) || -+ !cpumask_empty(ecore_mask); -+ bool complete_hybrid = -+ !cpumask_empty(pcore_mask) && -+ !cpumask_empty(ecore_mask) && -+ cpumask_empty(unknown_mask); -+ -+ policy->idle_select_mode = SCHED_IDLE_SELECT_GENERIC; -+ policy->mixed_cpu_types = -+ have_known && !cpumask_empty(unknown_mask); -+#ifdef CONFIG_SCHED_SMT -+ policy->unsupported_ecore_smt = -+ cpumask_intersects(ecore_mask, smt_mask); -+#else -+ policy->unsupported_ecore_smt = false; -+#endif -+ policy->heterogeneous = -+ complete_hybrid && !policy->unsupported_ecore_smt; -+ -+ if (policy->heterogeneous) { -+ policy->idle_select_mode = SCHED_IDLE_SELECT_HYBRID; -+ return; -+ } -+ -+#ifdef CONFIG_SCHED_SMT -+ if (!cpumask_empty(active_mask) && -+ cpumask_equal(smt_mask, active_mask)) -+ policy->idle_select_mode = SCHED_IDLE_SELECT_SMT; -+#endif -+} -+ -+DEFINE_PER_CPU_READ_MOSTLY(enum cpu_topo_type, sched_cpu_topo); -+DEFINE_PER_CPU_READ_MOSTLY(enum cpu_topo_balance_type, sched_cpu_topo_balance); -+DEFINE_PER_CPU(struct balance_callback, active_balance_head); -+ -+/* -+ * Idle cpu/rq selection functions -+ */ -+#ifdef CONFIG_SCHED_SMT -+static bool p1_idle_select_func(struct cpumask *dstp, const struct cpumask *src1p, -+ const struct cpumask *src2p) -+{ -+ return (cpumask_and(dstp, src1p, sched_sg_idle_mask) && -+ cpumask_and(dstp, dstp, src2p)) || -+ cpumask_and(dstp, src1p, src2p); -+} -+#endif -+ -+static bool p1p2_idle_select_func(struct cpumask *dstp, const struct cpumask *src1p, -+ const struct cpumask *src2p) -+{ -+ return (cpumask_and(dstp, src1p, sched_pcore_idle_mask) && -+ cpumask_and(dstp, dstp, src2p)) || -+ (cpumask_and(dstp, src1p, sched_ecore_idle_mask) && -+ cpumask_and(dstp, dstp, src2p)) || -+ cpumask_and(dstp, src1p, src2p); -+} -+ -+/* common balance functions */ -+static int active_balance_cpu_stop(void *data) -+{ -+ struct balance_arg *arg = data; -+ struct task_struct *p = arg->task; -+ struct rq *rq = this_rq(); -+ struct rq_flags rf; -+ cpumask_t tmp; -+ -+ local_irq_save(rf.flags); -+ -+ raw_spin_lock(&p->pi_lock); -+ rq_lock(rq, &rf); -+ -+ arg->active = 0; -+ -+ if (task_on_rq_queued(p) && task_rq(p) == rq && -+ cpumask_and(&tmp, p->cpus_ptr, arg->cpumask) && -+ cpumask_and(&tmp, &tmp, sched_idle_mask) && -+ cpumask_and(&tmp, &tmp, cpu_active_mask) && -+ !is_migration_disabled(p)) { -+ int dcpu = __best_mask_cpu(&tmp, per_cpu(sched_cpu_llc_mask, cpu_of(rq)), -+ per_cpu(sched_cpu_topo_end_mask, cpu_of(rq))); -+ rq = move_queued_task(rq, &rf, p, dcpu); -+ } -+ -+ rq_unlock(rq, &rf); -+ raw_spin_unlock_irqrestore(&p->pi_lock, rf.flags); -+ -+ put_task_struct(p); -+ -+ return 0; -+} -+ -+/* trigger_active_balance - for @rq */ -+static inline int -+trigger_active_balance(struct rq *src_rq, struct rq *rq, cpumask_t *target_mask) -+{ -+ struct balance_arg *arg; -+ unsigned long flags; -+ struct task_struct *p; -+ int res; -+ -+ local_irq_save(flags); -+ if (!raw_spin_rq_trylock(rq)) { -+ local_irq_restore(flags); -+ return 0; -+ } -+ -+ arg = &rq->active_balance_arg; -+ res = (1 == rq->nr_running) && \ -+ !is_migration_disabled((p = sched_rq_first_task(rq))) && \ -+ cpumask_intersects(p->cpus_ptr, target_mask) && \ -+ !arg->active; -+ if (res) { -+ arg->task = p; -+ arg->cpumask = target_mask; -+ get_task_struct(p); -+ -+ arg->active = 1; -+ } -+ -+ raw_spin_rq_unlock_irqrestore(rq, flags); -+ -+ if (res) { -+ preempt_disable(); -+ raw_spin_rq_unlock(src_rq); -+ -+ stop_one_cpu_nowait(cpu_of(rq), active_balance_cpu_stop, arg, -+ &rq->active_balance_work); -+ -+ preempt_enable(); -+ raw_spin_rq_lock(src_rq); -+ } -+ -+ return res; -+} -+ -+static inline int -+ecore_source_balance(struct rq *rq, cpumask_t *single_task_mask, cpumask_t *target_mask) -+{ -+ if (cpumask_and(single_task_mask, single_task_mask, &sched_ecore_mask)) { -+ int i, cpu = cpu_of(rq); -+ -+ for_each_cpu_wrap(i, single_task_mask, cpu) -+ if (trigger_active_balance(rq, cpu_rq(i), target_mask)) -+ return 1; -+ } -+ -+ return 0; -+} -+ -+#ifdef CONFIG_SCHED_SMT -+static bool sched_smt_group_busy(int cpu, const struct cpumask *busy_mask) -+{ -+ int sibling; -+ -+ for_each_cpu_and(sibling, cpu_smt_mask(cpu), &sched_smt_mask) -+ if (!cpumask_test_cpu(sibling, busy_mask)) -+ return false; -+ -+ return true; -+} -+ -+static bool sched_wakee_recent(struct task_struct *p, u64 now) -+{ -+ s64 delta = now - READ_ONCE(p->wake_start); -+ -+ return time_before(jiffies, READ_ONCE(p->wakee_flip_decay_ts) + 2 * HZ) && -+ delta >= 0 && delta < TICK_NSEC; -+} -+ -+bool sched_smt_group_paired(struct rq *rq, int cpu) -+{ -+ struct task_struct *p = rcu_dereference_all(cpu_rq(cpu)->curr); -+ u64 now = rq_clock(rq); -+ int sibling; -+ -+ if (!sched_wakee_recent(p, now)) -+ return false; -+ -+ for_each_cpu_and(sibling, cpu_smt_mask(cpu), &sched_smt_mask) { -+ struct task_struct *q; -+ -+ if (sibling == cpu) -+ continue; -+ -+ q = rcu_dereference_all(cpu_rq(sibling)->curr); -+ if (READ_ONCE(p->last_wakee) == q && -+ READ_ONCE(q->last_wakee) == p && -+ sched_wakee_recent(q, now)) -+ return true; -+ } -+ -+ return false; -+} -+ -+static inline int -+smt_source_balance(struct rq *rq, cpumask_t *single_task_mask, -+ const struct cpumask *source_mask, cpumask_t *target_mask) -+{ -+ cpumask_t smt_single_mask; -+ -+ if (cpumask_and(&smt_single_mask, single_task_mask, &sched_smt_mask)) { -+ int i, cpu = cpu_of(rq); -+ -+ if (source_mask && -+ !cpumask_and(&smt_single_mask, &smt_single_mask, -+ source_mask)) -+ return 0; -+ -+ for_each_cpu_wrap(i, &smt_single_mask, cpu) { -+ if (sched_smt_group_busy(i, &smt_single_mask) && -+ !sched_smt_group_paired(rq, i) && -+ trigger_active_balance(rq, cpu_rq(i), target_mask)) -+ return 1; -+ } -+ } -+ -+ return 0; -+} -+ -+/* smt p core balance functions */ -+void smt_pcore_balance(struct rq *rq) -+{ -+ cpumask_t single_task_mask; -+ -+ if (cpumask_andnot(&single_task_mask, cpu_active_mask, sched_idle_mask) && -+ cpumask_andnot(&single_task_mask, &single_task_mask, &sched_rq_pending_mask) && -+ (/* smt core group balance */ -+ smt_source_balance(rq, &single_task_mask, &sched_pcore_mask, -+ sched_pcore_idle_mask) || -+ /* e core to idle smt core balance */ -+ ecore_source_balance(rq, &single_task_mask, -+ sched_pcore_idle_mask))) -+ return; -+} -+ -+/* smt balance functions */ -+void smt_balance(struct rq *rq) -+{ -+ cpumask_t single_task_mask; -+ -+ if (cpumask_andnot(&single_task_mask, cpu_active_mask, sched_idle_mask) && -+ cpumask_andnot(&single_task_mask, &single_task_mask, &sched_rq_pending_mask) && -+ smt_source_balance(rq, &single_task_mask, NULL, -+ sched_sg_idle_mask)) -+ return; -+} -+ -+/* e core balance functions */ -+void ecore_balance(struct rq *rq) -+{ -+ cpumask_t single_task_mask; -+ -+ if (cpumask_andnot(&single_task_mask, cpu_active_mask, sched_idle_mask) && -+ cpumask_andnot(&single_task_mask, &single_task_mask, &sched_rq_pending_mask) && -+ cpumask_empty(sched_pcore_idle_mask) && -+ /* smt occupied p core to idle e core balance */ -+ smt_source_balance(rq, &single_task_mask, &sched_pcore_mask, -+ sched_ecore_idle_mask)) -+ return; -+} -+#endif /* CONFIG_SCHED_SMT */ -+ -+/* p core balance functions */ -+void pcore_balance(struct rq *rq) -+{ -+ cpumask_t single_task_mask; -+ -+ if (cpumask_andnot(&single_task_mask, cpu_active_mask, sched_idle_mask) && -+ cpumask_andnot(&single_task_mask, &single_task_mask, &sched_rq_pending_mask) && -+ /* idle e core to p core balance */ -+ ecore_source_balance(rq, &single_task_mask, sched_pcore_idle_mask)) -+ return; -+} -+ -+static const char *sched_idle_select_mode_name(enum sched_idle_select_mode mode) -+{ -+ switch (mode) { -+ case SCHED_IDLE_SELECT_GENERIC: -+ return "generic"; -+#ifdef CONFIG_SCHED_SMT -+ case SCHED_IDLE_SELECT_SMT: -+ return "SMT"; -+#endif -+ case SCHED_IDLE_SELECT_HYBRID: -+ return "hybrid"; -+ } -+ -+ return "unknown"; -+} -+ -+static void sched_idle_select_update(enum sched_idle_select_mode mode) -+{ -+ if (mode == READ_ONCE(sched_idle_select_applied)) -+ return; -+ -+ switch (mode) { -+ case SCHED_IDLE_SELECT_GENERIC: -+ static_call_update(sched_idle_select_func, cpumask_and); -+ break; -+#ifdef CONFIG_SCHED_SMT -+ case SCHED_IDLE_SELECT_SMT: -+ static_call_update(sched_idle_select_func, p1_idle_select_func); -+ break; -+#endif -+ case SCHED_IDLE_SELECT_HYBRID: -+ static_call_update(sched_idle_select_func, p1p2_idle_select_func); -+ break; -+ } -+ -+ WRITE_ONCE(sched_idle_select_applied, mode); -+} -+ -+static void sched_idle_select_workfn(struct work_struct *work) -+{ -+ enum sched_idle_select_mode mode; -+ -+ do { -+ /* static_call_update() takes cpus_read_lock() itself. */ -+ mode = READ_ONCE(sched_idle_select_mode); -+ sched_idle_select_update(mode); -+ } while (mode != READ_ONCE(sched_idle_select_mode)); -+} -+ -+static DECLARE_WORK(sched_idle_select_work, sched_idle_select_workfn); -+ -+void sched_topology_queue_idle_select(void) -+{ -+ if (READ_ONCE(sched_idle_select_mode) != -+ READ_ONCE(sched_idle_select_applied)) -+ schedule_work(&sched_idle_select_work); -+} -+ -+void __init sched_topology_init_idle_select(void) -+{ -+ sched_idle_select_update(READ_ONCE(sched_idle_select_mode)); -+} -+ -+/* Reports outside the stopped machine; CPU hotplug serializes against itself. */ -+void sched_topology_report(void) -+{ -+ bool changed = sched_topology_changed; -+ bool active_changed = sched_topology_active_changed; -+ bool warn_ecore_smt = sched_topology_warn_ecore_smt; -+ bool warn_smt_class = sched_topology_warn_smt_class; -+ bool warn_unknown = sched_topology_warn_unknown; -+ -+ sched_topology_changed = false; -+ sched_topology_active_changed = false; -+ sched_topology_warn_ecore_smt = false; -+ sched_topology_warn_smt_class = false; -+ sched_topology_warn_unknown = false; -+ -+ WARN_ONCE(warn_smt_class, -+ "sched/alt: P/E scheduling with a non-performance SMT group in %*pbl\n", -+ cpumask_pr_args(&sched_smt_mask)); -+ -+ if (warn_unknown) -+ pr_warn_once("sched/alt: UNKNOWN CPU types in %*pbl; disabling P/E auto-detection\n", -+ cpumask_pr_args(&sched_unknown_mask)); -+ -+ if (warn_ecore_smt) -+ pr_warn_once("sched/alt: E-core SMT is unsupported; using homogeneous scheduling\n"); -+ -+ if (!changed) { -+ if (active_changed) -+ pr_debug_ratelimited("sched/alt: active CPUs: %*pbl\n", -+ cpumask_pr_args(&sched_topology_active_mask)); -+ return; -+ } -+ -+ pr_info("sched/alt: %s topology, idle select: %s, active: %*pbl, SMT: %*pbl%s%*pbl%s%*pbl%s%*pbl\n", -+ sched_heterogeneous ? "heterogeneous" : "homogeneous", -+ sched_idle_select_mode_name(READ_ONCE(sched_idle_select_mode)), -+ cpumask_pr_args(&sched_topology_active_mask), -+ cpumask_pr_args(&sched_smt_mask), -+ cpumask_empty(&sched_pcore_mask) ? "" : ", P: ", -+ cpumask_pr_args(&sched_pcore_mask), -+ cpumask_empty(&sched_ecore_mask) ? "" : ", E: ", -+ cpumask_pr_args(&sched_ecore_mask), -+ sched_mixed_cpu_types ? ", UNKNOWN: " : "", -+ cpumask_pr_args(sched_mixed_cpu_types ? -+ &sched_unknown_mask : cpu_none_mask)); -+} -+ -+#ifdef CONFIG_SCHED_SMT -+static bool sched_rebuild_smt_group_idle(int cpu) -+{ -+ int sibling; -+ -+ for_each_cpu_and(sibling, cpu_smt_mask(cpu), &sched_smt_mask) -+ if (!cpumask_test_cpu(sibling, sched_idle_mask)) -+ return false; -+ -+ return true; -+} -+#endif -+ -+static void sched_rebuild_idle_masks(const struct cpumask *active_mask) -+{ -+ int cpu; -+ -+ /* -+ * Every active CPU runs a stopper here, so a remaining bit belongs to -+ * a CPU which is not active and cannot be a placement candidate. -+ */ -+ cpumask_and(sched_idle_mask, sched_idle_mask, active_mask); -+ cpumask_clear(sched_sg_idle_mask); -+ cpumask_clear(sched_pcore_idle_mask); -+ cpumask_clear(sched_ecore_idle_mask); -+ cpumask_clear(&sched_rebuild_visited_mask); -+ -+ for_each_cpu(cpu, active_mask) { -+#ifdef CONFIG_SCHED_SMT -+ if (cpumask_test_cpu(cpu, &sched_smt_mask)) { -+ int sibling; -+ -+ if (cpumask_test_cpu(cpu, &sched_rebuild_visited_mask)) -+ continue; -+ -+ cpumask_clear(&sched_rebuild_group_mask); -+ for_each_cpu_and(sibling, cpu_smt_mask(cpu), -+ &sched_smt_mask) { -+ cpumask_set_cpu(sibling, -+ &sched_rebuild_group_mask); -+ cpumask_set_cpu(sibling, -+ &sched_rebuild_visited_mask); -+ } -+ -+ if (!sched_rebuild_smt_group_idle(cpu)) -+ continue; -+ -+ cpumask_or(sched_sg_idle_mask, sched_sg_idle_mask, -+ &sched_rebuild_group_mask); -+ if (per_cpu(sched_cpu_topo, cpu) == -+ CPU_TOPOLOGY_PCORE) -+ cpumask_or(sched_pcore_idle_mask, -+ sched_pcore_idle_mask, -+ &sched_rebuild_group_mask); -+ continue; -+ } -+#endif -+ -+ if (!cpumask_test_cpu(cpu, sched_idle_mask)) -+ continue; -+ -+ switch (per_cpu(sched_cpu_topo, cpu)) { -+ case CPU_TOPOLOGY_DEFAULT: -+ break; -+ case CPU_TOPOLOGY_PCORE: -+ cpumask_set_cpu(cpu, sched_pcore_idle_mask); -+ break; -+ case CPU_TOPOLOGY_ECORE: -+ cpumask_set_cpu(cpu, sched_ecore_idle_mask); -+ break; -+ } -+ } -+} -+ -+void sched_topology_prepare(const struct cpumask *active_mask) -+{ -+ cpumask_clear(&sched_rebuild_pcore_mask); -+ cpumask_clear(&sched_rebuild_ecore_mask); -+ cpumask_clear(&sched_rebuild_unknown_mask); -+ cpumask_clear(&sched_rebuild_smt_mask); -+ -+ sched_detect_cpu_types(active_mask); -+ sched_detect_smt(active_mask); -+ sched_select_topology_policy(active_mask, -+ &sched_rebuild_pcore_mask, -+ &sched_rebuild_ecore_mask, -+ &sched_rebuild_unknown_mask, -+ &sched_rebuild_smt_mask, -+ &sched_rebuild_policy); -+} -+ -+void sched_topology_apply(const struct cpumask *active_mask) -+{ -+ bool active_changed = -+ !cpumask_equal(active_mask, &sched_topology_active_mask); -+ bool semantic_changed = -+ !sched_topology_initialized || -+ sched_rebuild_policy.heterogeneous != sched_heterogeneous || -+ sched_rebuild_policy.mixed_cpu_types != sched_mixed_cpu_types || -+ sched_rebuild_policy.unsupported_ecore_smt != -+ sched_unsupported_ecore_smt || -+ sched_rebuild_policy.idle_select_mode != sched_idle_select_mode; -+#ifdef CONFIG_SCHED_SMT -+ bool pcore_smt = -+ cpumask_intersects(&sched_rebuild_pcore_mask, -+ &sched_rebuild_smt_mask); -+#endif -+ int cpu; -+ -+ cpumask_or(&sched_rebuild_visited_mask, &sched_topology_active_mask, -+ active_mask); -+ -+ if (sched_rebuild_policy.mixed_cpu_types && -+ !sched_mixed_cpu_types) -+ sched_topology_warn_unknown = true; -+ if (sched_rebuild_policy.unsupported_ecore_smt && -+ !sched_unsupported_ecore_smt) -+ sched_topology_warn_ecore_smt = true; -+ -+ cpumask_copy(&sched_topology_active_mask, active_mask); -+ cpumask_copy(&sched_smt_mask, &sched_rebuild_smt_mask); -+ cpumask_copy(&sched_pcore_mask, &sched_rebuild_pcore_mask); -+ cpumask_copy(&sched_ecore_mask, &sched_rebuild_ecore_mask); -+ cpumask_copy(&sched_unknown_mask, &sched_rebuild_unknown_mask); -+ sched_heterogeneous = sched_rebuild_policy.heterogeneous; -+ sched_mixed_cpu_types = sched_rebuild_policy.mixed_cpu_types; -+ sched_unsupported_ecore_smt = -+ sched_rebuild_policy.unsupported_ecore_smt; -+ WRITE_ONCE(sched_idle_select_mode, -+ sched_rebuild_policy.idle_select_mode); -+ -+ for_each_cpu(cpu, &sched_rebuild_visited_mask) { -+ per_cpu(sched_cpu_topo, cpu) = CPU_TOPOLOGY_DEFAULT; -+ per_cpu(sched_cpu_topo_balance, cpu) = CPU_TOPOLOGY_BALANCE_NONE; -+ } -+ -+ for_each_cpu(cpu, active_mask) { -+ if (sched_heterogeneous) { -+ if (cpumask_test_cpu(cpu, &sched_pcore_mask)) -+ per_cpu(sched_cpu_topo, cpu) = -+ CPU_TOPOLOGY_PCORE; -+ else if (cpumask_test_cpu(cpu, &sched_ecore_mask)) -+ per_cpu(sched_cpu_topo, cpu) = -+ CPU_TOPOLOGY_ECORE; -+ } -+ -+#ifdef CONFIG_SCHED_SMT -+ if (cpumask_test_cpu(cpu, &sched_smt_mask)) { -+ if (sched_heterogeneous) { -+ if (per_cpu(sched_cpu_topo, cpu) != -+ CPU_TOPOLOGY_PCORE) -+ sched_topology_warn_smt_class = true; -+ per_cpu(sched_cpu_topo_balance, cpu) = -+ CPU_TOPOLOGY_BALANCE_SMT_PCORE; -+ } else { -+ per_cpu(sched_cpu_topo_balance, cpu) = -+ CPU_TOPOLOGY_BALANCE_SMT; -+ } -+ -+ continue; -+ } -+#endif -+ if (!sched_heterogeneous) -+ continue; -+ -+ if (per_cpu(sched_cpu_topo, cpu) == CPU_TOPOLOGY_PCORE) { -+ per_cpu(sched_cpu_topo_balance, cpu) = -+ CPU_TOPOLOGY_BALANCE_PCORE; -+ continue; -+ } -+ -+ if (per_cpu(sched_cpu_topo, cpu) == CPU_TOPOLOGY_ECORE) { -+#ifdef CONFIG_SCHED_SMT -+ if (pcore_smt) -+ per_cpu(sched_cpu_topo_balance, cpu) = -+ CPU_TOPOLOGY_BALANCE_ECORE; -+#endif -+ } -+ } -+ -+ sched_rebuild_idle_masks(active_mask); -+ -+ sched_topology_initialized = true; -+ sched_topology_changed |= semantic_changed; -+ sched_topology_active_changed |= active_changed; -+} -+ -+#ifdef CONFIG_SCHED_ALT_TOPOLOGY_KUNIT_TEST -+#include "alt_topology_test.c" -+#endif -diff --git a/kernel/sched/alt_topology.h b/kernel/sched/alt_topology.h -new file mode 100644 -index 0000000..9deb40c ---- /dev/null -+++ b/kernel/sched/alt_topology.h -@@ -0,0 +1,178 @@ -+#ifndef _KERNEL_SCHED_ALT_TOPOLOGY_H -+#define _KERNEL_SCHED_ALT_TOPOLOGY_H -+ -+/* -+ * CPU topology type -+ */ -+enum cpu_topo_type { -+ CPU_TOPOLOGY_DEFAULT = 0, -+ CPU_TOPOLOGY_PCORE, -+ CPU_TOPOLOGY_ECORE, -+}; -+ -+DECLARE_PER_CPU_READ_MOSTLY(enum cpu_topo_type, sched_cpu_topo); -+ -+#ifdef CONFIG_SCHED_SMT -+static inline bool sched_smt_active_group_idle(const unsigned int cpu) -+{ -+ unsigned int sibling; -+ -+ for_each_cpu_and(sibling, cpu_smt_mask(cpu), &sched_smt_mask) -+ if (!cpumask_test_cpu(sibling, sched_idle_mask)) -+ return false; -+ -+ return true; -+} -+ -+static inline void sched_set_smt_idle_masks(const unsigned int cpu) -+{ -+ enum cpu_topo_type class = per_cpu(sched_cpu_topo, cpu); -+ unsigned int sibling; -+ -+ for_each_cpu_and(sibling, cpu_smt_mask(cpu), &sched_smt_mask) { -+ cpumask_set_cpu(sibling, sched_sg_idle_mask); -+ if (class == CPU_TOPOLOGY_PCORE) -+ cpumask_set_cpu(sibling, sched_pcore_idle_mask); -+ } -+} -+ -+static inline void sched_clear_smt_idle_masks(const unsigned int cpu) -+{ -+ enum cpu_topo_type class = per_cpu(sched_cpu_topo, cpu); -+ unsigned int sibling; -+ -+ for_each_cpu_and(sibling, cpu_smt_mask(cpu), &sched_smt_mask) { -+ cpumask_clear_cpu(sibling, sched_sg_idle_mask); -+ if (class == CPU_TOPOLOGY_PCORE) -+ cpumask_clear_cpu(sibling, sched_pcore_idle_mask); -+ } -+} -+#endif -+ -+static inline void sched_set_idle_mask(const unsigned int cpu) -+{ -+#ifdef CONFIG_SCHED_SMT -+ if (cpumask_test_cpu(cpu, &sched_smt_mask)) { -+ cpumask_set_cpu(cpu, sched_idle_mask); -+ smp_mb__after_atomic(); -+ -+ if (!sched_smt_active_group_idle(cpu)) -+ return; -+ -+ unsigned int leader = -+ cpumask_first_and(cpu_smt_mask(cpu), &sched_smt_mask); -+ raw_spinlock_t *lock = &per_cpu(sched_smt_idle_lock, leader); -+ -+ raw_spin_lock(lock); -+ if (sched_smt_active_group_idle(cpu)) -+ sched_set_smt_idle_masks(cpu); -+ raw_spin_unlock(lock); -+ return; -+ } -+#endif -+ -+ cpumask_set_cpu(cpu, sched_idle_mask); -+ -+ switch (per_cpu(sched_cpu_topo, cpu)) { -+ case CPU_TOPOLOGY_DEFAULT: -+ break; -+ case CPU_TOPOLOGY_PCORE: -+ cpumask_set_cpu(cpu, sched_pcore_idle_mask); -+ break; -+ case CPU_TOPOLOGY_ECORE: -+ cpumask_set_cpu(cpu, sched_ecore_idle_mask); -+ break; -+ } -+} -+ -+static inline void sched_clear_idle_mask(const unsigned int cpu) -+{ -+#ifdef CONFIG_SCHED_SMT -+ if (cpumask_test_cpu(cpu, &sched_smt_mask)) { -+ unsigned int leader = -+ cpumask_first_and(cpu_smt_mask(cpu), &sched_smt_mask); -+ raw_spinlock_t *lock = &per_cpu(sched_smt_idle_lock, leader); -+ -+ raw_spin_lock(lock); -+ if (cpumask_test_cpu(cpu, sched_sg_idle_mask)) -+ sched_clear_smt_idle_masks(cpu); -+ cpumask_clear_cpu(cpu, sched_idle_mask); -+ raw_spin_unlock(lock); -+ return; -+ } -+#endif -+ -+ cpumask_clear_cpu(cpu, sched_idle_mask); -+ -+ switch (per_cpu(sched_cpu_topo, cpu)) { -+ case CPU_TOPOLOGY_DEFAULT: -+ break; -+ case CPU_TOPOLOGY_PCORE: -+ cpumask_clear_cpu(cpu, sched_pcore_idle_mask); -+ break; -+ case CPU_TOPOLOGY_ECORE: -+ cpumask_clear_cpu(cpu, sched_ecore_idle_mask); -+ break; -+ } -+} -+ -+/* -+ * CPU topology balance type -+ */ -+enum cpu_topo_balance_type { -+ CPU_TOPOLOGY_BALANCE_NONE = 0, -+ CPU_TOPOLOGY_BALANCE_PCORE, -+#ifdef CONFIG_SCHED_SMT -+ CPU_TOPOLOGY_BALANCE_ECORE, -+ CPU_TOPOLOGY_BALANCE_SMT, -+ CPU_TOPOLOGY_BALANCE_SMT_PCORE, -+#endif -+}; -+ -+DECLARE_PER_CPU_READ_MOSTLY(enum cpu_topo_balance_type, sched_cpu_topo_balance); -+DECLARE_PER_CPU(struct balance_callback, active_balance_head); -+ -+extern void pcore_balance(struct rq *rq); -+#ifdef CONFIG_SCHED_SMT -+extern void ecore_balance(struct rq *rq); -+extern void smt_balance(struct rq *rq); -+bool sched_smt_group_paired(struct rq *rq, int cpu); -+extern void smt_pcore_balance(struct rq *rq); -+#endif -+ -+static inline void sched_cpu_topology_balance(const unsigned int cpu, struct rq *rq) -+{ -+ struct balance_callback *head = &per_cpu(active_balance_head, cpu); -+ -+ if (!rq->online) -+ return; -+ -+ switch (per_cpu(sched_cpu_topo_balance, cpu)) { -+ case CPU_TOPOLOGY_BALANCE_NONE: -+ break; -+ case CPU_TOPOLOGY_BALANCE_PCORE: -+ queue_balance_callback(rq, head, pcore_balance); -+ break; -+#ifdef CONFIG_SCHED_SMT -+ case CPU_TOPOLOGY_BALANCE_ECORE: -+ queue_balance_callback(rq, head, ecore_balance); -+ break; -+ case CPU_TOPOLOGY_BALANCE_SMT: -+ if (cpumask_test_cpu(cpu, sched_sg_idle_mask)) -+ queue_balance_callback(rq, head, smt_balance); -+ break; -+ case CPU_TOPOLOGY_BALANCE_SMT_PCORE: -+ if (cpumask_test_cpu(cpu, sched_sg_idle_mask)) -+ queue_balance_callback(rq, head, smt_pcore_balance); -+ break; -+#endif -+ } -+} -+ -+void sched_topology_prepare(const struct cpumask *active_mask); -+void sched_topology_apply(const struct cpumask *active_mask); -+void sched_topology_report(void); -+void sched_topology_init_idle_select(void); -+void sched_topology_queue_idle_select(void); -+ -+#endif /* _KERNEL_SCHED_ALT_TOPOLOGY_H */ -diff --git a/kernel/sched/alt_topology_test.c b/kernel/sched/alt_topology_test.c -new file mode 100644 -index 0000000..6bdf2d4 ---- /dev/null -+++ b/kernel/sched/alt_topology_test.c -@@ -0,0 +1,211 @@ -+// SPDX-License-Identifier: GPL-2.0-only -+ -+#include -+ -+/* This file is included by alt_topology.c so it can exercise static helpers. */ -+ -+struct sched_topology_test_case { -+ const char *name; -+ unsigned long active; -+ unsigned long pcore; -+ unsigned long ecore; -+ unsigned long unknown; -+ unsigned long smt; -+ enum sched_idle_select_mode mode; -+ bool heterogeneous; -+ bool mixed_cpu_types; -+ bool unsupported_ecore_smt; -+}; -+ -+struct sched_topology_test_masks { -+ cpumask_t active; -+ cpumask_t pcore; -+ cpumask_t ecore; -+ cpumask_t unknown; -+ cpumask_t smt; -+}; -+ -+static void sched_topology_test_mask(cpumask_t *mask, unsigned long bits) -+{ -+ unsigned int cpu; -+ -+ cpumask_clear(mask); -+ for_each_set_bit(cpu, &bits, -+ min_t(unsigned int, BITS_PER_LONG, nr_cpu_ids)) -+ cpumask_set_cpu(cpu, mask); -+} -+ -+static void sched_topology_policy_test(struct kunit *test) -+{ -+ static const struct sched_topology_test_case cases[] = { -+ { -+ .name = "uniformly unknown", -+ .active = BIT(0) | BIT(1), -+ .unknown = BIT(0) | BIT(1), -+ .mode = SCHED_IDLE_SELECT_GENERIC, -+ }, -+ { -+ .name = "performance only", -+ .active = BIT(0) | BIT(1), -+ .pcore = BIT(0) | BIT(1), -+ .mode = SCHED_IDLE_SELECT_GENERIC, -+ }, -+ { -+ .name = "efficiency only", -+ .active = BIT(0) | BIT(1), -+ .ecore = BIT(0) | BIT(1), -+ .mode = SCHED_IDLE_SELECT_GENERIC, -+ }, -+ { -+ .name = "hybrid without SMT", -+ .active = BIT(0) | BIT(1), -+ .pcore = BIT(0), -+ .ecore = BIT(1), -+ .mode = SCHED_IDLE_SELECT_HYBRID, -+ .heterogeneous = true, -+ }, -+ { -+ .name = "hybrid with P-core SMT", -+ .active = BIT(0) | BIT(1) | BIT(2), -+ .pcore = BIT(0) | BIT(1), -+ .ecore = BIT(2), -+ .smt = BIT(0) | BIT(1), -+ .mode = SCHED_IDLE_SELECT_HYBRID, -+ .heterogeneous = true, -+ }, -+ { -+ .name = "hybrid with partial E-core SMT", -+ .active = BIT(0) | BIT(1) | BIT(2), -+ .pcore = BIT(0), -+ .ecore = BIT(1) | BIT(2), -+ .smt = BIT(1) | BIT(2), -+ .mode = SCHED_IDLE_SELECT_GENERIC, -+ .unsupported_ecore_smt = true, -+ }, -+ { -+ .name = "hybrid with universal SMT", -+ .active = BIT(0) | BIT(1) | BIT(2) | BIT(3), -+ .pcore = BIT(0) | BIT(1), -+ .ecore = BIT(2) | BIT(3), -+ .smt = BIT(0) | BIT(1) | BIT(2) | BIT(3), -+ .mode = SCHED_IDLE_SELECT_SMT, -+ .unsupported_ecore_smt = true, -+ }, -+ { -+ .name = "homogeneous SMT", -+ .active = BIT(0) | BIT(1), -+ .unknown = BIT(0) | BIT(1), -+ .smt = BIT(0) | BIT(1), -+ .mode = SCHED_IDLE_SELECT_SMT, -+ }, -+ { -+ .name = "mixed known and unknown", -+ .active = BIT(0) | BIT(1) | BIT(2), -+ .pcore = BIT(0), -+ .ecore = BIT(1), -+ .unknown = BIT(2), -+ .mode = SCHED_IDLE_SELECT_GENERIC, -+ .mixed_cpu_types = true, -+ }, -+ { -+ .name = "mixed topology with E-core SMT", -+ .active = BIT(0) | BIT(1) | BIT(2) | BIT(3), -+ .pcore = BIT(0), -+ .ecore = BIT(1) | BIT(2), -+ .unknown = BIT(3), -+ .smt = BIT(1) | BIT(2), -+ .mode = SCHED_IDLE_SELECT_GENERIC, -+ .mixed_cpu_types = true, -+ .unsupported_ecore_smt = true, -+ }, -+ }; -+ struct sched_topology_test_masks *masks; -+ struct sched_topology_policy policy; -+ int i; -+ -+ if (nr_cpu_ids < 4) { -+ kunit_skip(test, "at least four CPU bits are required"); -+ return; -+ } -+ -+ masks = kunit_kzalloc(test, sizeof(*masks), GFP_KERNEL); -+ KUNIT_ASSERT_NOT_NULL(test, masks); -+ -+ for (i = 0; i < ARRAY_SIZE(cases); i++) { -+ const struct sched_topology_test_case *casep = &cases[i]; -+ -+ sched_topology_test_mask(&masks->active, casep->active); -+ sched_topology_test_mask(&masks->pcore, casep->pcore); -+ sched_topology_test_mask(&masks->ecore, casep->ecore); -+ sched_topology_test_mask(&masks->unknown, casep->unknown); -+ sched_topology_test_mask(&masks->smt, casep->smt); -+ -+ sched_select_topology_policy(&masks->active, &masks->pcore, -+ &masks->ecore, &masks->unknown, -+ &masks->smt, &policy); -+ -+ KUNIT_EXPECT_EQ_MSG(test, policy.idle_select_mode, -+ casep->mode, "%s", casep->name); -+ KUNIT_EXPECT_EQ_MSG(test, policy.heterogeneous, -+ casep->heterogeneous, "%s", casep->name); -+ KUNIT_EXPECT_EQ_MSG(test, policy.mixed_cpu_types, -+ casep->mixed_cpu_types, "%s", casep->name); -+ KUNIT_EXPECT_EQ_MSG(test, policy.unsupported_ecore_smt, -+ casep->unsupported_ecore_smt, -+ "%s", casep->name); -+ } -+} -+ -+static void sched_topology_group_class_test(struct kunit *test) -+{ -+ struct sched_topology_test_masks *masks; -+ bool single_class; -+ -+ if (nr_cpu_ids < 2) { -+ kunit_skip(test, "at least two CPU bits are required"); -+ return; -+ } -+ -+ masks = kunit_kzalloc(test, sizeof(*masks), GFP_KERNEL); -+ KUNIT_ASSERT_NOT_NULL(test, masks); -+ -+ sched_topology_test_mask(&masks->active, BIT(0) | BIT(1)); -+ sched_topology_test_mask(&masks->pcore, BIT(0) | BIT(1)); -+ sched_topology_test_mask(&masks->ecore, 0); -+ sched_topology_test_mask(&masks->unknown, 0); -+ single_class = sched_group_has_single_class(&masks->active, -+ &masks->pcore, -+ &masks->ecore, -+ &masks->unknown); -+ KUNIT_EXPECT_TRUE(test, single_class); -+ -+ sched_topology_test_mask(&masks->pcore, BIT(0)); -+ sched_topology_test_mask(&masks->ecore, BIT(1)); -+ single_class = sched_group_has_single_class(&masks->active, -+ &masks->pcore, -+ &masks->ecore, -+ &masks->unknown); -+ KUNIT_EXPECT_FALSE(test, single_class); -+ -+ sched_topology_test_mask(&masks->pcore, 0); -+ sched_topology_test_mask(&masks->ecore, 0); -+ sched_topology_test_mask(&masks->unknown, BIT(0) | BIT(1)); -+ single_class = sched_group_has_single_class(&masks->active, -+ &masks->pcore, -+ &masks->ecore, -+ &masks->unknown); -+ KUNIT_EXPECT_TRUE(test, single_class); -+} -+ -+static struct kunit_case sched_topology_test_cases[] = { -+ KUNIT_CASE(sched_topology_policy_test), -+ KUNIT_CASE(sched_topology_group_class_test), -+ {} -+}; -+ -+static struct kunit_suite sched_topology_test_suite = { -+ .name = "sched-alt-topology", -+ .test_cases = sched_topology_test_cases, -+}; -+ -+kunit_test_suite(sched_topology_test_suite); -diff --git a/kernel/sched/bmq.h b/kernel/sched/bmq.h -new file mode 100644 -index 0000000..bb46790 ---- /dev/null -+++ b/kernel/sched/bmq.h -@@ -0,0 +1,112 @@ -+#ifndef _KERNEL_SCHED_BMQ_H -+#define _KERNEL_SCHED_BMQ_H -+ -+#define ALT_SCHED_NAME "BMQ" -+ -+/* -+ * BMQ only routines -+ */ -+static inline void boost_task(struct task_struct *p, int n) -+{ -+ int limit; -+ -+ switch (p->policy) { -+ case SCHED_NORMAL: -+ limit = -MAX_PRIORITY_ADJ; -+ break; -+ case SCHED_BATCH: -+ limit = 0; -+ break; -+ default: -+ return; -+ } -+ -+ p->boost_prio = max(limit, p->boost_prio - n); -+} -+ -+static inline void deboost_task(struct task_struct *p) -+{ -+ if ((SCHED_NORMAL == p->policy || SCHED_BATCH == p->policy) && -+ p->boost_prio < MAX_PRIORITY_ADJ) -+ p->boost_prio++; -+} -+ -+/* -+ * Common interfaces -+ */ -+/* This API is used in task_prio(), return value readed by human users */ -+static inline int -+task_sched_prio_normal(const struct task_struct *p, const struct rq *rq) -+{ -+ return p->prio + p->boost_prio - MIN_NORMAL_PRIO; -+} -+ -+static inline int task_sched_prio(const struct task_struct *p) -+{ -+ return (p->prio < MIN_NORMAL_PRIO)? (p->prio >> 2) : -+ MIN_SCHED_NORMAL_PRIO + (p->prio + p->boost_prio - MIN_NORMAL_PRIO) / 2; -+} -+ -+#define TASK_SCHED_PRIO_IDX(p, rq, idx, prio) \ -+ prio = task_sched_prio(p); \ -+ idx = prio; -+ -+static inline int sched_prio2idx(int prio, struct rq *rq) -+{ -+ return prio; -+} -+ -+static inline int sched_idx2prio(int idx, struct rq *rq) -+{ -+ return idx; -+} -+ -+static inline int sched_rq_prio_idx(struct rq *rq) -+{ -+ return rq->prio; -+} -+ -+static inline void sched_rq_set_prio(struct rq *rq, int prio) -+{ -+ rq->prio = prio; -+} -+ -+static inline int task_running_nice(struct task_struct *p) -+{ -+ return (p->prio + p->boost_prio > DEFAULT_PRIO); -+} -+ -+static inline void sched_update_rq_clock(struct rq *rq) {} -+ -+static inline void sched_task_renew(struct task_struct *p, const struct rq *rq) -+{ -+ deboost_task(p); -+} -+ -+static inline void sched_task_sanity_check(struct task_struct *p, struct rq *rq) {} -+static inline void sched_task_fork(struct task_struct *p, struct rq *rq) {} -+ -+static inline void do_sched_yield_type_1(struct task_struct *p, struct rq *rq) -+{ -+ p->boost_prio = MAX_PRIORITY_ADJ; -+} -+ -+static inline void sched_task_ttwu(struct task_struct *p) -+{ -+ s64 delta = this_rq()->clock_task - p->last_ran; -+ -+ if (likely(delta > 0)) -+ boost_task(p, delta >> 22); -+} -+ -+static inline bool sched_task_has_credit(const struct task_struct *p) -+{ -+ return false; -+} -+ -+static inline void sched_task_deactivate(struct task_struct *p, struct rq *rq) -+{ -+ boost_task(p, 1); -+} -+ -+#endif /* _KERNEL_SCHED_BMQ_H */ -diff --git a/kernel/sched/build_policy.c b/kernel/sched/build_policy.c -index 2a82872..89f1fbf 100644 ---- a/kernel/sched/build_policy.c -+++ b/kernel/sched/build_policy.c -@@ -49,13 +49,17 @@ - - #include "idle.c" - --#include "rt.c" --#include "cpudeadline.c" -+#ifndef CONFIG_SCHED_ALT -+# include "rt.c" -+# include "cpudeadline.c" -+#endif - - #include "pelt.c" - - #include "cputime.c" -+#ifndef CONFIG_SCHED_ALT - #include "deadline.c" -+#endif - - #ifdef CONFIG_SCHED_CLASS_EXT - # include -diff --git a/kernel/sched/build_utility.c b/kernel/sched/build_utility.c -index e2cf3b0..a64bf71 100644 ---- a/kernel/sched/build_utility.c -+++ b/kernel/sched/build_utility.c -@@ -56,6 +56,10 @@ - - #include "clock.c" - -+#ifdef CONFIG_SCHED_ALT -+# include "alt_topology.c" -+#endif -+ - #ifdef CONFIG_CGROUP_CPUACCT - # include "cpuacct.c" - #endif -@@ -68,7 +72,7 @@ - # include "cpufreq_schedutil.c" - #endif - --#include "debug.c" -+# include "debug.c" - - #ifdef CONFIG_SCHEDSTATS - # include "stats.c" -@@ -81,7 +85,9 @@ - #include "wait.c" - - #include "cpupri.c" --#include "stop_task.c" -+#ifndef CONFIG_SCHED_ALT -+# include "stop_task.c" -+#endif - - #include "topology.c" - -diff --git a/kernel/sched/core.c b/kernel/sched/core.c -index 1754d9f..4849135 100644 ---- a/kernel/sched/core.c -+++ b/kernel/sched/core.c -@@ -5097,7 +5097,7 @@ static inline void prepare_task(struct task_struct *next) - WRITE_ONCE(next->on_cpu, 1); - } - --static inline void finish_task(struct task_struct *prev) -+static __always_inline void finish_task(struct task_struct *prev) - { - /* - * This must be the very last reference to @prev from this CPU. After -@@ -5141,7 +5141,7 @@ static void zap_balance_callbacks(struct rq *rq) - rq->balance_callback = found ? &balance_push_callback : NULL; - } - --static void do_balance_callbacks(struct rq *rq, struct balance_callback *head) -+static __always_inline void do_balance_callbacks(struct rq *rq, struct balance_callback *head) - { - void (*func)(struct rq *rq); - struct balance_callback *next; -@@ -5176,7 +5176,7 @@ struct balance_callback balance_push_callback = { - .func = balance_push, - }; - --static inline struct balance_callback * -+static __always_inline struct balance_callback * - __splice_balance_callbacks(struct rq *rq, bool split) - { - struct balance_callback *head = rq->balance_callback; -@@ -5206,7 +5206,7 @@ struct balance_callback *splice_balance_callbacks(struct rq *rq) - return __splice_balance_callbacks(rq, true); - } - --void __balance_callbacks(struct rq *rq, struct rq_flags *rf) -+__always_inline void __balance_callbacks(struct rq *rq, struct rq_flags *rf) - { - if (rf) - rq_unpin_lock(rq, rf); -@@ -5250,7 +5250,7 @@ prepare_lock_switch(struct rq *rq, struct task_struct *next, struct rq_flags *rf - __acquire(__rq_lockp(this_rq())); - } - --static inline void finish_lock_switch(struct rq *rq) -+static __always_inline void finish_lock_switch(struct rq *rq) - __releases(__rq_lockp(rq)) - { - /* -@@ -5284,7 +5284,7 @@ static inline void kmap_local_sched_out(void) - #endif - } - --static inline void kmap_local_sched_in(void) -+static __always_inline void kmap_local_sched_in(void) - { - #ifdef CONFIG_KMAP_LOCAL - if (unlikely(current->kmap_ctrl.idx)) -@@ -5338,7 +5338,7 @@ prepare_task_switch(struct rq *rq, struct task_struct *prev, - * past. 'prev == current' is still correct but we need to recalculate this_rq - * because prev may have moved to another CPU. - */ --static struct rq *finish_task_switch(struct task_struct *prev) -+static __always_inline struct rq *finish_task_switch(struct task_struct *prev) - __releases(__rq_lockp(this_rq())) - { - struct rq *rq = this_rq(); -diff --git a/kernel/sched/cpufreq_schedutil.c b/kernel/sched/cpufreq_schedutil.c -index 14405a6..158f1c0 100644 ---- a/kernel/sched/cpufreq_schedutil.c -+++ b/kernel/sched/cpufreq_schedutil.c -@@ -249,6 +249,7 @@ unsigned long sugov_effective_cpu_perf(int cpu, unsigned long actual, - - static void sugov_get_util(struct sugov_cpu *sg_cpu, unsigned long boost) - { -+#ifndef CONFIG_SCHED_ALT - unsigned long min, max, util = scx_cpuperf_target(sg_cpu->cpu); - - if (!scx_switched_all()) -@@ -258,6 +259,10 @@ static void sugov_get_util(struct sugov_cpu *sg_cpu, unsigned long boost) - sg_cpu->bw_min = min; - sg_cpu->bw_max = max; - sg_cpu->util = sugov_effective_cpu_perf(sg_cpu->cpu, util, min, max); -+#else /* CONFIG_SCHED_ALT */ -+ sg_cpu->bw_min = 0; -+ sg_cpu->util = rq_load_util(cpu_rq(sg_cpu->cpu), arch_scale_cpu_capacity(sg_cpu->cpu)); -+#endif /* CONFIG_SCHED_ALT */ - } - - /** -@@ -385,6 +390,7 @@ static bool sugov_hold_freq(struct sugov_cpu *sg_cpu) - unsigned long idle_calls; - bool ret; - -+#ifndef CONFIG_SCHED_ALT - /* - * The heuristics in this function is for the fair class. For SCX, the - * performance target comes directly from the BPF scheduler. Let's just -@@ -392,6 +398,7 @@ static bool sugov_hold_freq(struct sugov_cpu *sg_cpu) - */ - if (scx_switched_all()) - return false; -+#endif /* !CONFIG_SCHED_ALT */ - - /* if capped by uclamp_max, always update to be in compliance */ - if (uclamp_rq_is_capped(cpu_rq(sg_cpu->cpu))) -@@ -417,8 +424,10 @@ static inline bool sugov_hold_freq(struct sugov_cpu *sg_cpu) { return false; } - */ - static inline void ignore_dl_rate_limit(struct sugov_cpu *sg_cpu) - { -+#ifndef CONFIG_SCHED_ALT - if (cpu_bw_dl(cpu_rq(sg_cpu->cpu)) > sg_cpu->bw_min) -- sg_cpu->sg_policy->need_freq_update = true; -+ sg_cpu->sg_policy->limits_changed = true; -+#endif - } - - static inline bool sugov_update_single_common(struct sugov_cpu *sg_cpu, -@@ -714,6 +723,7 @@ static int sugov_kthread_create(struct sugov_policy *sg_policy) - } - - ret = sched_setattr_nocheck(thread, &attr); -+ - if (ret) { - kthread_stop(thread); - pr_warn("%s: failed to set SCHED_DEADLINE\n", __func__); -diff --git a/kernel/sched/cputime.c b/kernel/sched/cputime.c -index 06bddaa..0bc9d14 100644 ---- a/kernel/sched/cputime.c -+++ b/kernel/sched/cputime.c -@@ -130,7 +130,7 @@ void account_user_time(struct task_struct *p, u64 cputime) - p->utime += cputime; - account_group_user_time(p, cputime); - -- index = (task_nice(p) > 0) ? CPUTIME_NICE : CPUTIME_USER; -+ index = task_running_nice(p) ? CPUTIME_NICE : CPUTIME_USER; - - /* Add user time to cpustat. */ - task_group_account_field(p, index, cputime); -@@ -154,7 +154,7 @@ void account_guest_time(struct task_struct *p, u64 cputime) - p->gtime += cputime; - - /* Add guest time to cpustat. */ -- if (task_nice(p) > 0) { -+ if (task_running_nice(p)) { - task_group_account_field(p, CPUTIME_NICE, cputime); - cpustat[CPUTIME_GUEST_NICE] += cputime; - } else { -@@ -305,7 +305,7 @@ static inline u64 account_other_time(u64 max) - #ifdef CONFIG_64BIT - static inline u64 read_sum_exec_runtime(struct task_struct *t) - { -- return t->se.sum_exec_runtime; -+ return tsk_seruntime(t); - } - #else /* !CONFIG_64BIT: */ - static u64 read_sum_exec_runtime(struct task_struct *t) -@@ -315,7 +315,7 @@ static u64 read_sum_exec_runtime(struct task_struct *t) - struct rq *rq; - - rq = task_rq_lock(t, &rf); -- ns = t->se.sum_exec_runtime; -+ ns = tsk_seruntime(t); - task_rq_unlock(rq, t, &rf); - - return ns; -@@ -811,7 +811,7 @@ void cputime_adjust(struct task_cputime *curr, struct prev_cputime *prev, - void task_cputime_adjusted(struct task_struct *p, u64 *ut, u64 *st) - { - struct task_cputime cputime = { -- .sum_exec_runtime = p->se.sum_exec_runtime, -+ .sum_exec_runtime = tsk_seruntime(p), - }; - - if (task_cputime(p, &cputime.utime, &cputime.stime)) -diff --git a/kernel/sched/debug.c b/kernel/sched/debug.c -index 72236db..70b7c34 100644 ---- a/kernel/sched/debug.c -+++ b/kernel/sched/debug.c -@@ -11,6 +11,7 @@ - #include - #include "sched.h" - -+#ifndef CONFIG_SCHED_ALT - /* - * This allows printing both to /sys/kernel/debug/sched/debug and - * to the console -@@ -251,6 +252,7 @@ static const struct file_operations sched_cache_enable_fops = { - .release = single_release, - }; - #endif -+#endif /* !CONFIG_SCHED_ALT */ - - #ifdef CONFIG_PREEMPT_DYNAMIC - -@@ -318,6 +320,7 @@ static const struct file_operations sched_dynamic_fops = { - - #endif /* CONFIG_PREEMPT_DYNAMIC */ - -+#ifndef CONFIG_SCHED_ALT - __read_mostly bool sched_debug_verbose; - - static struct dentry *sd_dentry; -@@ -611,7 +614,11 @@ static const struct file_operations fair_server_period_fops = { - .llseek = seq_lseek, - .release = single_release, - }; -+#endif /* !CONFIG_SCHED_ALT */ - -+static struct dentry *debugfs_sched; -+ -+#ifndef CONFIG_SCHED_ALT - static void debugfs_fair_server_init(void) - { - struct dentry *d_fair; -@@ -632,6 +639,7 @@ static void debugfs_fair_server_init(void) - debugfs_create_file("period", 0644, d_cpu, (void *) cpu, &fair_server_period_fops); - } - } -+#endif /* !CONFIG_SCHED_ALT */ - - #ifdef CONFIG_FAIR_GROUP_SCHED - static int cgroup_mode = 2; -@@ -715,14 +723,17 @@ static __init int sched_init_debug(void) - - debugfs_sched = debugfs_create_dir("sched", NULL); - -+#ifndef CONFIG_SCHED_ALT - debugfs_create_file("features", 0644, debugfs_sched, NULL, &sched_feat_fops); - debugfs_create_file_unsafe("verbose", 0644, debugfs_sched, &sched_debug_verbose, &sched_verbose_fops); -+#endif /* !CONFIG_SCHED_ALT */ - #ifdef CONFIG_PREEMPT_DYNAMIC - debugfs_create_file("preempt", 0644, debugfs_sched, NULL, &sched_dynamic_fops); - #endif - - debugfs_create_u32("base_slice_ns", 0644, debugfs_sched, &sysctl_sched_base_slice); - -+#ifndef CONFIG_SCHED_ALT - debugfs_create_u32("latency_warn_ms", 0644, debugfs_sched, &sysctl_resched_latency_warn_ms); - debugfs_create_u32("latency_warn_once", 0644, debugfs_sched, &sysctl_resched_latency_warn_once); - -@@ -761,20 +772,25 @@ static __init int sched_init_debug(void) - #endif - - debugfs_create_file("debug", 0444, debugfs_sched, NULL, &sched_debug_fops); -+#endif /* !CONFIG_SCHED_ALT */ - - #ifdef CONFIG_FAIR_GROUP_SCHED - debugfs_create_file("cgroup_mode", 0644, debugfs_sched, NULL, &sched_cgroup_fops); - #endif - -+#ifndef CONFIG_SCHED_ALT - debugfs_fair_server_init(); - #ifdef CONFIG_SCHED_CLASS_EXT - debugfs_ext_server_init(); - #endif -+#endif /* !CONFIG_SCHED_ALT */ - - return 0; - } - late_initcall(sched_init_debug); - -+#ifndef CONFIG_SCHED_ALT -+ - static cpumask_var_t sd_sysctl_cpus; - - static int sd_flags_show(struct seq_file *m, void *v) -@@ -1520,6 +1536,11 @@ void proc_sched_show_task(struct task_struct *p, struct pid_namespace *ns, - - sched_show_numa(p, m); - } -+#else -+void proc_sched_show_task(struct task_struct *p, struct pid_namespace *ns, -+ struct seq_file *m) -+{ } -+#endif /* !CONFIG_SCHED_ALT */ - - void proc_sched_set_task(struct task_struct *p) - { -diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c -index 913630c..532c0de 100644 ---- a/kernel/sched/fair.c -+++ b/kernel/sched/fair.c -@@ -82,10 +82,19 @@ unsigned int sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG; - * - * (default: 0.70 msec * (1 + ilog(ncpus)), units: nanoseconds) - */ -+#ifdef CONFIG_ZEN_INTERACTIVE -+unsigned int sysctl_sched_base_slice = 400000ULL; -+static unsigned int normalized_sysctl_sched_base_slice = 400000ULL; -+#else - unsigned int sysctl_sched_base_slice = 700000ULL; - static unsigned int normalized_sysctl_sched_base_slice = 700000ULL; -+#endif - -+#ifdef CONFIG_ZEN_INTERACTIVE -+__read_mostly unsigned int sysctl_sched_migration_cost = 300000UL; -+#else - __read_mostly unsigned int sysctl_sched_migration_cost = 500000UL; -+#endif - - static int __init setup_sched_thermal_decay_shift(char *str) - { -@@ -128,8 +137,12 @@ int __weak arch_asym_cpu_priority(int cpu) - * - * (default: 5 msec, units: microseconds) - */ -+#ifdef CONFIG_ZEN_INTERACTIVE -+static unsigned int sysctl_sched_cfs_bandwidth_slice = 3000UL; -+#else - static unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL; - #endif -+#endif - - #ifdef CONFIG_NUMA_BALANCING - /* Restrict the NUMA promotion throughput (MB/s) for each target node. */ -diff --git a/kernel/sched/idle.c b/kernel/sched/idle.c -index eb73b65..c6a01e7 100644 ---- a/kernel/sched/idle.c -+++ b/kernel/sched/idle.c -@@ -454,6 +454,7 @@ void cpu_startup_entry(enum cpuhp_state state) - do_idle(); - } - -+#ifndef CONFIG_SCHED_ALT - /* - * idle-task scheduling class. - */ -@@ -597,3 +598,4 @@ DEFINE_SCHED_CLASS(idle) = { - .switching_to = switching_to_idle, - .update_curr = update_curr_idle, - }; -+#endif -diff --git a/kernel/sched/pds.h b/kernel/sched/pds.h -new file mode 100644 -index 0000000..1bcfcd2 ---- /dev/null -+++ b/kernel/sched/pds.h -@@ -0,0 +1,230 @@ -+#ifndef _KERNEL_SCHED_PDS_H -+#define _KERNEL_SCHED_PDS_H -+ -+#define ALT_SCHED_NAME "PDS" -+ -+static const u64 RT_MASK = ((1ULL << MIN_SCHED_NORMAL_PRIO) - 1); -+ -+#define SCHED_NORMAL_PRIO_NUM (32) -+#define SCHED_EDGE_DELTA (SCHED_NORMAL_PRIO_NUM - NICE_WIDTH / 2) -+ -+/* PDS assume SCHED_NORMAL_PRIO_NUM is power of 2 */ -+#define SCHED_NORMAL_PRIO_MOD(x) ((x) & (SCHED_NORMAL_PRIO_NUM - 1)) -+ -+/* default time slice 4ms -> shift 22, 2 time slice slots -> shift 23 */ -+static const int sched_timeslice_shift = 23; -+static const int sched_boost_shift = 21; -+DECLARE_STATIC_KEY_MAYBE(CONFIG_SCHED_PDS_SLEEP_CREDIT, sched_pds_sleep_credit); -+ -+#define SCHED_NICE_DELTA(p) (((p)->static_prio - (MAX_PRIO - NICE_WIDTH)) / 2) -+ -+/* -+ * Common interfaces -+ */ -+static inline int -+task_sched_prio_normal(const struct task_struct *p, const struct rq *rq) -+{ -+ u64 sched_dl = max(p->deadline, rq->time_edge); -+ -+#ifdef ALT_SCHED_DEBUG -+ if (WARN_ONCE(sched_dl - rq->time_edge > SCHED_NORMAL_PRIO_NUM - 1, -+ "pds: task_sched_prio_normal() delta %lld\n", sched_dl - rq->time_edge)) -+ return SCHED_NORMAL_PRIO_NUM - 1; -+#endif -+ -+ return sched_dl - rq->time_edge; -+} -+ -+static inline int task_sched_prio(const struct task_struct *p) -+{ -+ return (p->prio < MIN_NORMAL_PRIO) ? (p->prio >> 2) : -+ MIN_SCHED_NORMAL_PRIO + task_sched_prio_normal(p, task_rq(p)); -+} -+ -+#define TASK_SCHED_PRIO_IDX(p, rq, idx, prio) \ -+ if (p->prio < MIN_NORMAL_PRIO) { \ -+ prio = p->prio >> 2; \ -+ idx = prio; \ -+ } else { \ -+ u64 sched_dl = max(p->deadline, rq->time_edge); \ -+ prio = MIN_SCHED_NORMAL_PRIO + sched_dl - rq->time_edge; \ -+ idx = MIN_SCHED_NORMAL_PRIO + SCHED_NORMAL_PRIO_MOD(sched_dl); \ -+ } -+ -+static_assert(MIN_SCHED_NORMAL_PRIO + SCHED_NORMAL_PRIO_NUM == IDLE_TASK_SCHED_PRIO); -+ -+static inline int sched_prio2idx(int sched_prio, struct rq *rq) -+{ -+ return ((unsigned int)(sched_prio - MIN_SCHED_NORMAL_PRIO) < SCHED_NORMAL_PRIO_NUM) ? -+ MIN_SCHED_NORMAL_PRIO + SCHED_NORMAL_PRIO_MOD(sched_prio + rq->time_edge) : -+ sched_prio; -+} -+ -+static inline int sched_idx2prio(int sched_idx, struct rq *rq) -+{ -+ return (sched_idx < MIN_SCHED_NORMAL_PRIO) ? -+ sched_idx : -+ MIN_SCHED_NORMAL_PRIO + SCHED_NORMAL_PRIO_MOD(sched_idx - rq->time_edge); -+} -+ -+static inline int sched_rq_prio_idx(struct rq *rq) -+{ -+ return rq->prio_idx; -+} -+ -+static inline void sched_rq_set_prio(struct rq *rq, int prio) -+{ -+ rq->prio = prio; -+ rq->prio_idx = sched_prio2idx(prio, rq); -+} -+ -+static inline int task_running_nice(struct task_struct *p) -+{ -+ return (p->prio > DEFAULT_PRIO); -+} -+ -+static noinline __maybe_unused void -+sched_rq_time_edge_advance(struct rq *rq, u64 old, u64 now) -+{ -+ struct list_head head; -+ u64 prio, delta; -+ DECLARE_BITMAP(normal, SCHED_QUEUE_BITS); -+ -+ rq->time_edge = now; -+ delta = min_t(u64, SCHED_NORMAL_PRIO_NUM, now - old); -+ INIT_LIST_HEAD(&head); -+ -+ prio = MIN_SCHED_NORMAL_PRIO; -+ for_each_set_bit_from(prio, rq->queue.bitmap, MIN_SCHED_NORMAL_PRIO + delta) -+ list_splice_tail_init(rq->queue.heads + MIN_SCHED_NORMAL_PRIO + -+ SCHED_NORMAL_PRIO_MOD(prio + old), &head); -+ -+ bitmap_shift_right(normal, rq->queue.bitmap, delta, SCHED_QUEUE_BITS); -+ if (!list_empty(&head)) { -+ u64 idx = MIN_SCHED_NORMAL_PRIO + SCHED_NORMAL_PRIO_MOD(now); -+ -+ __list_splice(&head, rq->queue.heads + idx, rq->queue.heads[idx].next); -+ __set_bit(MIN_SCHED_NORMAL_PRIO, normal); -+ } -+ bitmap_replace(rq->queue.bitmap, normal, rq->queue.bitmap, -+ (const unsigned long *)&RT_MASK, SCHED_QUEUE_BITS); -+ -+ if (rq->prio < MIN_SCHED_NORMAL_PRIO || IDLE_TASK_SCHED_PRIO == rq->prio) -+ return; -+ -+ sched_rq_set_prio(rq, max_t(u64, MIN_SCHED_NORMAL_PRIO, rq->prio - delta)); -+} -+ -+static inline void sched_update_rq_clock(struct rq *rq) -+{ -+ u64 old = rq->time_edge; -+ u64 now = rq->clock >> sched_timeslice_shift; -+ -+ if (likely(now == old)) -+ return; -+ -+ sched_rq_time_edge_advance(rq, old, now); -+} -+ -+static inline void sched_task_deadline_reset(struct task_struct *p, const struct rq *rq) -+{ -+ p->sleep_credit = 0; -+ if (p->prio >= MIN_NORMAL_PRIO) -+ p->deadline = rq->time_edge + SCHED_EDGE_DELTA + SCHED_NICE_DELTA(p); -+} -+ -+static inline bool sched_task_used_slice(const struct task_struct *p) -+{ -+ return p->sched_time - p->wake_sched_time >= -+ 2 * (sysctl_sched_base_slice - RESCHED_NS); -+} -+ -+static inline void sched_task_renew(struct task_struct *p, const struct rq *rq) -+{ -+ if (p->prio >= MIN_NORMAL_PRIO) { -+ u64 cap = (normal_policy(p->policy) && !sched_task_used_slice(p)) ? -+ max(SCHED_NICE_DELTA(p) - (NICE_WIDTH / 8 + 1), 0) : 0; -+ -+ if (p->sleep_credit > cap) -+ p->sleep_credit = cap; -+ p->deadline = rq->time_edge + SCHED_EDGE_DELTA + SCHED_NICE_DELTA(p) - -+ p->sleep_credit; -+ } -+} -+ -+static inline void sched_task_sanity_check(struct task_struct *p, struct rq *rq) -+{ -+ u64 max_dl = rq->time_edge + SCHED_EDGE_DELTA + NICE_WIDTH / 2 - 1; -+ if (unlikely(p->deadline > max_dl)) -+ p->deadline = max_dl; -+} -+ -+static inline void sched_task_fork(struct task_struct *p, struct rq *rq) -+{ -+ p->wake_sched_time = 0; -+ p->wake_period = 64 * NSEC_PER_MSEC; -+ p->credit_wake = 0; -+ sched_task_deadline_reset(p, rq); -+} -+ -+static inline void do_sched_yield_type_1(struct task_struct *p, struct rq *rq) -+{ -+ p->time_slice = sysctl_sched_base_slice; -+ sched_task_deadline_reset(p, rq); -+} -+ -+static inline void sched_task_ttwu(struct task_struct *p) -+{ -+ if (!static_branch_maybe(CONFIG_SCHED_PDS_SLEEP_CREDIT, &sched_pds_sleep_credit)) -+ return; -+ -+ u64 now = local_clock(); -+ s64 delta = now - p->sleep_start; -+ s64 credit; -+ u64 boost; -+ bool used_slice = sched_task_used_slice(p); -+ -+ p->wake_sched_time = p->sched_time; -+ if (used_slice) { -+ p->deadline += p->sleep_credit; -+ p->sleep_credit = 0; -+ } -+ -+ if (p->prio < MIN_NORMAL_PRIO || !normal_policy(p->policy) || -+ delta < (1LL << (sched_boost_shift - 2))) -+ return; -+ -+ if (p->credit_wake) { -+ p->wake_period += (s64)(now - p->credit_wake - p->wake_period) >> 3; -+ if (p->sched_time - p->credit_sched_time > (u64)delta) -+ used_slice = true; -+ } -+ p->credit_wake = now; -+ p->credit_sched_time = p->sched_time; -+ -+ boost = min_t(u64, NICE_WIDTH / 4, -+ max_t(u64, 1, (u64)delta >> sched_boost_shift)); -+ if (p->wake_period <= (1ULL << sched_boost_shift)) -+ boost = max_t(u64, boost, 4); -+ else if (p->wake_period <= (1ULL << (sched_boost_shift + 4))) -+ boost = max_t(u64, boost, 3); -+ credit = SCHED_NICE_DELTA(p) - max_t(s64, NICE_WIDTH / 8 + 1, -+ SCHED_NICE_DELTA(p) - (s64)boost); -+ credit = used_slice ? 0 : max_t(s64, credit, 0); -+ -+ p->deadline = min(p->deadline, (now >> sched_timeslice_shift) + SCHED_EDGE_DELTA + -+ SCHED_NICE_DELTA(p) - credit); -+ p->sleep_credit = credit; -+} -+ -+static inline bool sched_task_has_credit(const struct task_struct *p) -+{ -+ return p->sleep_credit; -+} -+ -+static inline void sched_task_deactivate(struct task_struct *p, struct rq *rq) -+{ -+ p->sleep_start = rq->clock; -+} -+ -+#endif /* _KERNEL_SCHED_PDS_H */ -diff --git a/kernel/sched/pelt.c b/kernel/sched/pelt.c -index 779eb58..4657534 100644 ---- a/kernel/sched/pelt.c -+++ b/kernel/sched/pelt.c -@@ -267,6 +267,7 @@ ___update_load_avg(struct sched_avg *sa, unsigned long load) - WRITE_ONCE(sa->util_avg, sa->util_sum / divider); - } - -+#ifndef CONFIG_SCHED_ALT - /* - * sched_entity: - * -@@ -384,8 +385,9 @@ int update_dl_rq_load_avg(u64 now, struct rq *rq, int running) - - return 0; - } -+#endif - --#ifdef CONFIG_SCHED_HW_PRESSURE -+#if defined(CONFIG_SCHED_HW_PRESSURE) && !defined(CONFIG_SCHED_ALT) - /* - * hardware: - * -@@ -469,6 +471,7 @@ int update_irq_load_avg(struct rq *rq, u64 running) - } - #endif /* CONFIG_HAVE_SCHED_AVG_IRQ */ - -+#ifndef CONFIG_SCHED_ALT - /* - * Load avg and utiliztion metrics need to be updated periodically and before - * consumption. This function updates the metrics for all subsystems except for -@@ -488,3 +491,4 @@ bool update_other_load_avgs(struct rq *rq) - update_hw_load_avg(rq_clock_task(rq), rq, hw_pressure) | - update_irq_load_avg(rq, 0); - } -+#endif /* !CONFIG_SCHED_ALT */ -diff --git a/kernel/sched/pelt.h b/kernel/sched/pelt.h -index f921302..2fade7d 100644 ---- a/kernel/sched/pelt.h -+++ b/kernel/sched/pelt.h -@@ -5,14 +5,16 @@ - - #include "sched-pelt.h" - -+#ifndef CONFIG_SCHED_ALT - int __update_load_avg_blocked_se(u64 now, struct sched_entity *se); - int __update_load_avg_se(u64 now, struct cfs_rq *cfs_rq, struct sched_entity *se); - int __update_load_avg_cfs_rq(u64 now, struct cfs_rq *cfs_rq); - int update_rt_rq_load_avg(u64 now, struct rq *rq, int running); - int update_dl_rq_load_avg(u64 now, struct rq *rq, int running); - bool update_other_load_avgs(struct rq *rq); -+#endif - --#ifdef CONFIG_SCHED_HW_PRESSURE -+#if defined(CONFIG_SCHED_HW_PRESSURE) && !defined(CONFIG_SCHED_ALT) - int update_hw_load_avg(u64 now, struct rq *rq, u64 capacity); - - static inline u64 hw_load_avg(struct rq *rq) -@@ -49,6 +51,7 @@ static inline u32 get_pelt_divider(struct sched_avg *avg) - return PELT_MIN_DIVIDER + avg->period_contrib; - } - -+#ifndef CONFIG_SCHED_ALT - static inline void cfs_se_util_change(struct sched_avg *avg) - { - unsigned int enqueued; -@@ -185,5 +188,6 @@ static inline u64 cfs_rq_clock_pelt(struct cfs_rq *cfs_rq) - return rq_clock_pelt(rq_of(cfs_rq)); - } - #endif /* !CONFIG_CFS_BANDWIDTH */ -+#endif /* CONFIG_SCHED_ALT */ - - #endif /* _KERNEL_SCHED_PELT_H */ -diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h -index 4c25fbe..11f5b47 100644 ---- a/kernel/sched/sched.h -+++ b/kernel/sched/sched.h -@@ -5,6 +5,10 @@ - #ifndef _KERNEL_SCHED_SCHED_H - #define _KERNEL_SCHED_SCHED_H - -+#ifdef CONFIG_SCHED_ALT -+#include "alt_sched.h" -+#else -+ - #include - #include - #include -@@ -1481,12 +1485,12 @@ static inline struct cpumask *sched_group_span(struct sched_group *sg); - - DECLARE_STATIC_KEY_FALSE(__sched_core_enabled); - --static inline bool sched_core_enabled(struct rq *rq) -+static __always_inline bool sched_core_enabled(struct rq *rq) - { - return static_branch_unlikely(&__sched_core_enabled) && rq->core_enabled; - } - --static inline bool sched_core_disabled(void) -+static __always_inline bool sched_core_disabled(void) - { - return !static_branch_unlikely(&__sched_core_enabled); - } -@@ -1495,7 +1499,7 @@ static inline bool sched_core_disabled(void) - * Be careful with this function; not for general use. The return value isn't - * stable unless you actually hold a relevant rq->__lock. - */ --static inline raw_spinlock_t *rq_lockp(struct rq *rq) -+static __always_inline raw_spinlock_t *rq_lockp(struct rq *rq) - { - if (sched_core_enabled(rq)) - return &rq->core->__lock; -@@ -1503,7 +1507,7 @@ static inline raw_spinlock_t *rq_lockp(struct rq *rq) - return &rq->__lock; - } - --static inline raw_spinlock_t *__rq_lockp(struct rq *rq) -+static __always_inline raw_spinlock_t *__rq_lockp(struct rq *rq) - __returns_ctx_lock(rq_lockp(rq)) /* alias them */ - { - if (rq->core_enabled) -@@ -1606,12 +1610,12 @@ static inline bool sched_core_disabled(void) - return true; - } - --static inline raw_spinlock_t *rq_lockp(struct rq *rq) -+static __always_inline raw_spinlock_t *rq_lockp(struct rq *rq) - { - return &rq->__lock; - } - --static inline raw_spinlock_t *__rq_lockp(struct rq *rq) -+static __always_inline raw_spinlock_t *__rq_lockp(struct rq *rq) - __returns_ctx_lock(rq_lockp(rq)) /* alias them */ - { - return &rq->__lock; -@@ -1671,26 +1675,26 @@ extern void raw_spin_rq_lock_nested(struct rq *rq, int subclass) - extern bool raw_spin_rq_trylock(struct rq *rq) - __cond_acquires(true, __rq_lockp(rq)); - --static inline void raw_spin_rq_lock(struct rq *rq) -+static __always_inline void raw_spin_rq_lock(struct rq *rq) - __acquires(__rq_lockp(rq)) - { - raw_spin_rq_lock_nested(rq, 0); - } - --static inline void raw_spin_rq_unlock(struct rq *rq) -+static __always_inline void raw_spin_rq_unlock(struct rq *rq) - __releases(__rq_lockp(rq)) - { - raw_spin_unlock(rq_lockp(rq)); - } - --static inline void raw_spin_rq_lock_irq(struct rq *rq) -+static __always_inline void raw_spin_rq_lock_irq(struct rq *rq) - __acquires(__rq_lockp(rq)) - { - local_irq_disable(); - raw_spin_rq_lock(rq); - } - --static inline void raw_spin_rq_unlock_irq(struct rq *rq) -+static __always_inline void raw_spin_rq_unlock_irq(struct rq *rq) - __releases(__rq_lockp(rq)) - { - raw_spin_rq_unlock(rq); -@@ -3138,7 +3142,7 @@ static inline void attach_one_task(struct rq *rq, struct task_struct *p) - attach_task(rq, p); - } - --#ifdef CONFIG_PREEMPT_RT -+#if defined(CONFIG_PREEMPT_RT) || defined(CONFIG_ZEN_INTERACTIVE) - # define SCHED_NR_MIGRATE_BREAK 8 - #else - # define SCHED_NR_MIGRATE_BREAK 32 -@@ -4252,4 +4256,9 @@ DEFINE_CLASS_IS_UNCONDITIONAL(sched_change) - - #include "ext/ext.h" - -+static inline int task_running_nice(struct task_struct *p) -+{ -+ return (task_nice(p) > 0); -+} -+#endif /* !CONFIG_SCHED_ALT */ - #endif /* _KERNEL_SCHED_SCHED_H */ -diff --git a/kernel/sched/stats.c b/kernel/sched/stats.c -index d1c9429..cc37640 100644 ---- a/kernel/sched/stats.c -+++ b/kernel/sched/stats.c -@@ -115,8 +115,10 @@ static int show_schedstat(struct seq_file *seq, void *v) - seq_printf(seq, "timestamp %lu\n", jiffies); - } else { - struct rq *rq; -+#ifndef CONFIG_SCHED_ALT - struct sched_domain *sd; - int dcount = 0; -+#endif - cpu = (unsigned long)(v - 2); - rq = cpu_rq(cpu); - -@@ -131,6 +133,7 @@ static int show_schedstat(struct seq_file *seq, void *v) - - seq_printf(seq, "\n"); - -+#ifndef CONFIG_SCHED_ALT - /* domain-specific stats */ - rcu_read_lock(); - for_each_domain(cpu, sd) { -@@ -161,6 +164,7 @@ static int show_schedstat(struct seq_file *seq, void *v) - sd->ttwu_move_balance); - } - rcu_read_unlock(); -+#endif - } - return 0; - } -diff --git a/kernel/sched/stats.h b/kernel/sched/stats.h -index ebe0a77..7533602 100644 ---- a/kernel/sched/stats.h -+++ b/kernel/sched/stats.h -@@ -89,6 +89,7 @@ static inline void rq_sched_info_depart (struct rq *rq, unsigned long long delt - - #endif /* CONFIG_SCHEDSTATS */ - -+#ifndef CONFIG_SCHED_ALT - static inline struct sched_statistics * - __schedstats_from_se(struct sched_entity *se) - { -@@ -98,6 +99,7 @@ __schedstats_from_se(struct sched_entity *se) - #endif - return &task_of(se)->stats; - } -+#endif /* CONFIG_SCHED_ALT */ - - #ifdef CONFIG_PSI - void psi_task_change(struct task_struct *task, int clear, int set); -@@ -135,6 +137,7 @@ static inline void psi_enqueue(struct task_struct *p, int flags) - if (task_on_cpu(task_rq(p), p)) - return; - -+#ifndef CONFIG_SCHED_ALT - if (p->se.sched_delayed) { - /* CPU migration of "sleeping" task */ - WARN_ON_ONCE(!(flags & ENQUEUE_MIGRATED)); -@@ -142,7 +145,9 @@ static inline void psi_enqueue(struct task_struct *p, int flags) - set |= TSK_MEMSTALL; - if (p->in_iowait) - set |= TSK_IOWAIT; -- } else if (flags & ENQUEUE_MIGRATED) { -+ } else -+#endif -+ if (flags & ENQUEUE_MIGRATED) { - /* CPU migration of runnable task */ - set = TSK_RUNNING; - if (p->in_memstall) -diff --git a/kernel/sched/syscalls.c b/kernel/sched/syscalls.c -index b215b0e..6ce19b8 100644 ---- a/kernel/sched/syscalls.c -+++ b/kernel/sched/syscalls.c -@@ -16,6 +16,14 @@ - #include "sched.h" - #include "autogroup.h" - -+#ifdef CONFIG_SCHED_ALT -+#include "alt_core.h" -+ -+static inline int __normal_prio(int policy, int rt_prio, int static_prio) -+{ -+ return rt_policy(policy) ? (MAX_RT_PRIO - 1 - rt_prio) : static_prio; -+} -+#else /* !CONFIG_SCHED_ALT */ - static inline int __normal_prio(int policy, int rt_prio, int nice) - { - int prio; -@@ -29,6 +37,7 @@ static inline int __normal_prio(int policy, int rt_prio, int nice) - - return prio; - } -+#endif /* !CONFIG_SCHED_ALT */ - - /* - * Calculate the expected normal priority: i.e. priority -@@ -39,7 +48,11 @@ static inline int __normal_prio(int policy, int rt_prio, int nice) - */ - static inline int normal_prio(struct task_struct *p) - { -+#ifdef CONFIG_SCHED_ALT -+ return __normal_prio(p->policy, p->rt_priority, p->static_prio); -+#else /* !CONFIG_SCHED_ALT */ - return __normal_prio(p->policy, p->rt_priority, PRIO_TO_NICE(p->static_prio)); -+#endif /* !CONFIG_SCHED_ALT */ - } - - /* -@@ -64,7 +77,9 @@ static int effective_prio(struct task_struct *p) - - void set_user_nice(struct task_struct *p, long nice) - { -+#ifndef CONFIG_SCHED_ALT - int old_prio; -+#endif - - if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE) - return; -@@ -87,8 +102,10 @@ void set_user_nice(struct task_struct *p, long nice) - - scoped_guard (sched_change, p, DEQUEUE_SAVE) { - p->static_prio = NICE_TO_PRIO(nice); -+#ifndef CONFIG_SCHED_ALT - set_load_weight(p, true); - old_prio = p->prio; -+#endif - p->prio = effective_prio(p); - } - } -@@ -169,7 +186,19 @@ SYSCALL_DEFINE1(nice, int, increment) - */ - int task_prio(const struct task_struct *p) - { -+#ifdef CONFIG_SCHED_ALT -+/* -+ * sched policy return value kernel prio user prio/nice -+ * -+ * (BMQ)normal, batch, idle[0 ... 53] [100 ... 139] 0/[-20 ... 19]/[-7 ... 7] -+ * (PDS)normal, batch, idle[0 ... 39] 100 0/[-20 ... 19] -+ * fifo, rr [-1 ... -100] [99 ... 0] [0 ... 99] -+ */ -+ return (p->prio < MAX_RT_PRIO) ? p->prio - MAX_RT_PRIO : -+ task_sched_prio_normal(p, task_rq(p)); -+#else - return p->prio - MAX_RT_PRIO; -+#endif /* !CONFIG_SCHED_ALT */ - } - - /** -@@ -248,11 +277,16 @@ static void __setscheduler_params(struct task_struct *p, - - p->policy = policy; - -+#ifndef CONFIG_SCHED_ALT - if (dl_policy(policy)) - __setparam_dl(p, attr); - else if (fair_policy(policy)) - __setparam_fair(p, attr); -+#else /* !CONFIG_SCHED_ALT */ -+ p->static_prio = NICE_TO_PRIO(attr->sched_nice); -+#endif /* CONFIG_SCHED_ALT */ - -+#ifndef CONFIG_SCHED_ALT - /* rt-policy tasks do not have a timerslack */ - if (rt_or_dl_task_policy(p)) { - p->timer_slack_ns = 0; -@@ -260,6 +294,7 @@ static void __setscheduler_params(struct task_struct *p, - /* when switching back to non-rt policy, restore timerslack */ - p->timer_slack_ns = p->default_timer_slack_ns; - } -+#endif /* !CONFIG_SCHED_ALT */ - - /* - * __sched_setscheduler() ensures attr->sched_priority == 0 when -@@ -268,7 +303,9 @@ static void __setscheduler_params(struct task_struct *p, - */ - p->rt_priority = attr->sched_priority; - p->normal_prio = normal_prio(p); -+#ifndef CONFIG_SCHED_ALT - set_load_weight(p, true); -+#endif /* !CONFIG_SCHED_ALT */ - } - - /* -@@ -284,7 +321,7 @@ static bool check_same_owner(struct task_struct *p) - uid_eq(cred->euid, pcred->uid)); - } - --#ifdef CONFIG_RT_MUTEXES -+#if defined(CONFIG_RT_MUTEXES) && !defined(CONFIG_SCHED_ALT) - static inline void __setscheduler_dl_pi(int newprio, int policy, - struct task_struct *p, - struct sched_change_ctx *scope) -@@ -313,6 +350,7 @@ static inline void __setscheduler_dl_pi(int newprio, int policy, - } - #endif /* !CONFIG_RT_MUTEXES */ - -+#ifndef CONFIG_SCHED_ALT - #ifdef CONFIG_UCLAMP_TASK - - static int uclamp_validate(struct task_struct *p, -@@ -426,6 +464,7 @@ static inline int uclamp_validate(struct task_struct *p, - static void __setscheduler_uclamp(struct task_struct *p, - const struct sched_attr *attr) { } - #endif /* !CONFIG_UCLAMP_TASK */ -+#endif /* !CONFIG_SCHED_ALT */ - - /* - * Allow unprivileged RT tasks to decrease priority. -@@ -436,11 +475,13 @@ static int user_check_sched_setscheduler(struct task_struct *p, - const struct sched_attr *attr, - int policy, int reset_on_fork) - { -+#ifndef CONFIG_SCHED_ALT - if (fair_policy(policy)) { - if (attr->sched_nice < task_nice(p) && - !is_nice_reduction(p, attr->sched_nice)) - goto req_priv; - } -+#endif /* !CONFIG_SCHED_ALT */ - - if (rt_policy(policy)) { - unsigned long rlim_rtprio = task_rlimit(p, RLIMIT_RTPRIO); -@@ -455,6 +496,7 @@ static int user_check_sched_setscheduler(struct task_struct *p, - goto req_priv; - } - -+#ifndef CONFIG_SCHED_ALT - /* - * Can't set/change SCHED_DEADLINE policy at all for now - * (safest behavior); in the future we would like to allow -@@ -472,6 +514,7 @@ static int user_check_sched_setscheduler(struct task_struct *p, - if (!is_nice_reduction(p, task_nice(p))) - goto req_priv; - } -+#endif /* !CONFIG_SCHED_ALT */ - - /* Can't change other user's priorities: */ - if (!check_same_owner(p)) -@@ -491,12 +534,22 @@ static int user_check_sched_setscheduler(struct task_struct *p, - } - - int __sched_setscheduler(struct task_struct *p, -- const struct sched_attr *attr, -- bool user, bool pi) -+ const struct sched_attr *attr, -+ bool user, bool pi) - { -+#ifdef CONFIG_SCHED_ALT -+ const struct sched_attr dl_squash_attr = { -+ .size = sizeof(struct sched_attr), -+ .sched_policy = SCHED_FIFO, -+ .sched_nice = 0, -+ .sched_priority = 99, -+ }; -+#endif /* CONFIG_SCHED_ALT */ - int oldpolicy = -1, policy = attr->sched_policy; - int retval, oldprio, newprio; -+#ifndef CONFIG_SCHED_ALT - const struct sched_class *prev_class, *next_class; -+#endif /* !CONFIG_SCHED_ALT */ - struct balance_callback *head; - struct rq_flags rf; - int reset_on_fork; -@@ -506,6 +559,15 @@ int __sched_setscheduler(struct task_struct *p, - - /* The pi code expects interrupts enabled */ - BUG_ON(pi && in_interrupt()); -+#ifdef CONFIG_SCHED_ALT -+ /* -+ * Alt schedule FW supports SCHED_DEADLINE by squash it as prio 0 SCHED_FIFO -+ */ -+ if (unlikely(SCHED_DEADLINE == policy)) { -+ attr = &dl_squash_attr; -+ policy = attr->sched_policy; -+ } -+#endif /* CONFIG_SCHED_ALT */ - recheck: - /* Double check policy once rq lock held: */ - if (policy < 0) { -@@ -528,8 +590,12 @@ int __sched_setscheduler(struct task_struct *p, - */ - if (attr->sched_priority > MAX_RT_PRIO-1) - return -EINVAL; -+#ifdef CONFIG_SCHED_ALT -+ if ((rt_policy(policy) != (attr->sched_priority != 0))) -+#else - if ((dl_policy(policy) && !__checkparam_dl(attr)) || - (rt_policy(policy) != (attr->sched_priority != 0))) -+#endif /* !CONFIG_SCHED_ALT */ - return -EINVAL; - - if (user) { -@@ -545,6 +611,7 @@ int __sched_setscheduler(struct task_struct *p, - return retval; - } - -+#ifndef CONFIG_SCHED_ALT - /* Update task specific "requested" clamps */ - if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP) { - retval = uclamp_validate(p, attr); -@@ -560,6 +627,7 @@ int __sched_setscheduler(struct task_struct *p, - cpuset_locked = true; - cpuset_lock(); - } -+#endif /* !CONFIG_SCHED_ALT */ - - /* - * Make sure no PI-waiters arrive (or leave) while we are -@@ -579,23 +647,31 @@ int __sched_setscheduler(struct task_struct *p, - goto unlock; - } - -+#ifndef CONFIG_SCHED_ALT - retval = scx_check_setscheduler(p, policy); - if (retval) - goto unlock; -+#endif /* !CONFIG_SCHED_ALT */ - - /* - * If not changing anything there's no need to proceed further, - * but store a possible modification of reset_on_fork. - */ - if (unlikely(policy == p->policy)) { -+#ifdef CONFIG_SCHED_ALT -+ if (!rt_policy(policy) && NICE_TO_PRIO(attr->sched_nice) != p->static_prio) -+#else - if (fair_policy(policy) && - (attr->sched_nice != task_nice(p) || - (attr->sched_runtime != p->se.slice))) -+#endif /* !CONFIG_SCHED_ALT */ - goto change; - if (rt_policy(policy) && attr->sched_priority != p->rt_priority) - goto change; -+#ifndef CONFIG_SCHED_ALT - if (dl_policy(policy) && dl_param_changed(p, attr)) - goto change; -+#endif /* !CONFIG_SCHED_ALT */ - if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP) - goto change; - -@@ -605,6 +681,7 @@ int __sched_setscheduler(struct task_struct *p, - } - change: - -+#ifndef CONFIG_SCHED_ALT - if (user) { - #ifdef CONFIG_RT_GROUP_SCHED - /* -@@ -635,6 +712,7 @@ int __sched_setscheduler(struct task_struct *p, - } - } - } -+#endif /* !CONFIG_SCHED_ALT */ - - /* Re-check policy now with rq lock held: */ - if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) { -@@ -645,6 +723,7 @@ int __sched_setscheduler(struct task_struct *p, - goto recheck; - } - -+#ifndef CONFIG_SCHED_ALT - /* - * If setscheduling to SCHED_DEADLINE (or changing the parameters - * of a SCHED_DEADLINE task) we need to check if enough bandwidth -@@ -654,11 +733,16 @@ int __sched_setscheduler(struct task_struct *p, - retval = -EBUSY; - goto unlock; - } -+#endif /* !CONFIG_SCHED_ALT */ - - p->sched_reset_on_fork = reset_on_fork; - oldprio = p->prio; - -+#ifdef CONFIG_SCHED_ALT -+ newprio = __normal_prio(policy, attr->sched_priority, NICE_TO_PRIO(attr->sched_nice)); -+#else - newprio = __normal_prio(policy, attr->sched_priority, attr->sched_nice); -+#endif /* !CONFIG_SCHED_ALT */ - if (pi) { - /* - * Take priority boosted tasks into account. If the new -@@ -672,21 +756,27 @@ int __sched_setscheduler(struct task_struct *p, - queue_flags &= ~DEQUEUE_MOVE; - } - -+#ifndef CONFIG_SCHED_ALT - prev_class = p->sched_class; - next_class = __setscheduler_class(policy, newprio); - - if (prev_class != next_class) - queue_flags |= DEQUEUE_CLASS; -+#endif /* !CONFIG_SCHED_ALT */ - - scoped_guard (sched_change, p, queue_flags) { - - if (!(attr->sched_flags & SCHED_FLAG_KEEP_PARAMS)) { - __setscheduler_params(p, attr); -+#ifndef CONFIG_SCHED_ALT - p->sched_class = next_class; -+#endif /* !CONFIG_SCHED_ALT */ - p->prio = newprio; - __setscheduler_dl_pi(newprio, policy, p, scope); - } -+#ifndef CONFIG_SCHED_ALT - __setscheduler_uclamp(p, attr); -+#endif /* !CONFIG_SCHED_ALT */ - - if (scope->queued) { - /* -@@ -731,8 +821,10 @@ static int _sched_setscheduler(struct task_struct *p, int policy, - .sched_nice = PRIO_TO_NICE(p->static_prio), - }; - -+#ifndef CONFIG_SCHED_ALT - if (p->se.custom_slice) - attr.sched_runtime = p->se.slice; -+#endif /* !CONFIG_SCHED_ALT */ - - /* Fixup the legacy SCHED_RESET_ON_FORK hack. */ - if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) { -@@ -913,13 +1005,18 @@ static int sched_copy_attr(struct sched_attr __user *uattr, struct sched_attr *a - - static void get_params(struct task_struct *p, struct sched_attr *attr, unsigned int flags) - { -+#ifndef CONFIG_SCHED_ALT - if (task_has_dl_policy(p)) { - __getparam_dl(p, attr, flags); -- } else if (task_has_rt_policy(p)) { -+ } else -+#endif -+ if (task_has_rt_policy(p)) { - attr->sched_priority = p->rt_priority; - } else { - attr->sched_nice = task_nice(p); -+#ifndef CONFIG_SCHED_ALT - attr->sched_runtime = p->se.slice; -+#endif - } - } - -@@ -1106,6 +1203,7 @@ SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr, - - int dl_task_check_affinity(struct task_struct *p, const struct cpumask *mask) - { -+#ifndef CONFIG_SCHED_ALT - /* - * If the task isn't a deadline task or admission control is - * disabled then we don't care about affinity changes. -@@ -1129,6 +1227,7 @@ int dl_task_check_affinity(struct task_struct *p, const struct cpumask *mask) - guard(rcu)(); - if (!cpumask_subset(task_rq(p)->rd->span, mask)) - return -EBUSY; -+#endif - - return 0; - } -@@ -1152,9 +1251,11 @@ int __sched_setaffinity(struct task_struct *p, struct affinity_context *ctx) - ctx->new_mask = new_mask; - ctx->flags |= SCA_CHECK; - -+#ifndef CONFIG_SCHED_ALT - retval = dl_task_check_affinity(p, new_mask); - if (retval) - goto out_free_new_mask; -+#endif - - retval = __set_cpus_allowed_ptr(p, ctx); - if (retval) -@@ -1334,13 +1435,34 @@ SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len, - - static void do_sched_yield(void) - { -- struct rq_flags rf; - struct rq *rq; -+ struct rq_flags rf; -+ -+#ifdef CONFIG_SCHED_ALT -+ struct task_struct *p; -+ -+ if (!sched_yield_type) -+ return; - - rq = this_rq_lock_irq(&rf); - -+ schedstat_inc(rq->yld_count); -+ -+ p = current; -+ if (rt_task(p)) { -+ if (task_on_rq_queued(p)) -+ requeue_task(p, rq, 0); -+ } else if (rq->nr_running > 1) { -+ do_sched_yield_type_1(p, rq); -+ if (task_on_rq_queued(p)) -+ requeue_task(p, rq, 0); -+ } -+#else /* !CONFIG_SCHED_ALT */ -+ rq = this_rq_lock_irq(&rf); -+ - schedstat_inc(rq->yld_count); - rq->donor->sched_class->yield_task(rq); -+#endif /* !CONFIG_SCHED_ALT */ - - preempt_disable(); - rq_unlock_irq(rq, &rf); -@@ -1409,6 +1531,9 @@ EXPORT_SYMBOL(yield); - */ - int __sched yield_to(struct task_struct *p, bool preempt) - { -+#ifdef CONFIG_SCHED_ALT -+ return 0; -+#else /* !CONFIG_SCHED_ALT */ - struct task_struct *curr; - struct rq *rq, *p_rq; - int yielded = 0; -@@ -1455,6 +1580,7 @@ int __sched yield_to(struct task_struct *p, bool preempt) - schedule(); - - return yielded; -+#endif /* !CONFIG_SCHED_ALT */ - } - EXPORT_SYMBOL_GPL(yield_to); - -@@ -1475,7 +1601,9 @@ SYSCALL_DEFINE1(sched_get_priority_max, int, policy) - case SCHED_RR: - ret = MAX_RT_PRIO-1; - break; -+#ifndef CONFIG_SCHED_ALT - case SCHED_DEADLINE: -+#endif - case SCHED_NORMAL: - case SCHED_BATCH: - case SCHED_IDLE: -@@ -1503,7 +1631,9 @@ SYSCALL_DEFINE1(sched_get_priority_min, int, policy) - case SCHED_RR: - ret = 1; - break; -+#ifndef CONFIG_SCHED_ALT - case SCHED_DEADLINE: -+#endif - case SCHED_NORMAL: - case SCHED_BATCH: - case SCHED_IDLE: -@@ -1515,7 +1645,9 @@ SYSCALL_DEFINE1(sched_get_priority_min, int, policy) - - static int sched_rr_get_interval(pid_t pid, struct timespec64 *t) - { -+#ifndef CONFIG_SCHED_ALT - unsigned int time_slice = 0; -+#endif - int retval; - - if (pid < 0) -@@ -1530,6 +1662,7 @@ static int sched_rr_get_interval(pid_t pid, struct timespec64 *t) - if (retval) - return retval; - -+#ifndef CONFIG_SCHED_ALT - scoped_guard (task_rq_lock, p) { - struct rq *rq = scope.rq; - if (p->sched_class->get_rr_interval) -@@ -1538,6 +1671,13 @@ static int sched_rr_get_interval(pid_t pid, struct timespec64 *t) - } - - jiffies_to_timespec64(time_slice, t); -+#else -+ } -+ -+ alt_sched_debug(); -+ -+ *t = ns_to_timespec64(sysctl_sched_base_slice); -+#endif /* !CONFIG_SCHED_ALT */ - return 0; - } - -diff --git a/kernel/sched/topology.c b/kernel/sched/topology.c -index 3dab025..4a3b08e 100644 ---- a/kernel/sched/topology.c -+++ b/kernel/sched/topology.c -@@ -3,6 +3,7 @@ - * Scheduler topology setup/handling methods - */ - -+#ifndef CONFIG_SCHED_ALT - #include - #include - #include -@@ -1790,8 +1791,10 @@ static void asym_cpu_capacity_scan(void) - */ - - static int default_relax_domain_level = -1; -+#endif /* CONFIG_SCHED_ALT */ - int sched_domain_level_max; - -+#ifndef CONFIG_SCHED_ALT - static int __init setup_relax_domain_level(char *str) - { - if (kstrtoint(str, 0, &default_relax_domain_level)) -@@ -2027,6 +2030,7 @@ sd_init(struct sched_domain_topology_level *tl, - - return sd; - } -+#endif /* CONFIG_SCHED_ALT */ - - #ifdef CONFIG_SCHED_SMT - int cpu_smt_flags(void) -@@ -2118,6 +2122,7 @@ void __init set_sched_topology(struct sched_domain_topology_level *tl) - sched_domain_topology_saved = NULL; - } - -+#ifndef CONFIG_SCHED_ALT - #ifdef CONFIG_NUMA - static int cpu_numa_flags(void) - { -@@ -3502,3 +3507,31 @@ void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[], - partition_sched_domains_locked(ndoms_new, doms_new, dattr_new); - sched_domains_mutex_unlock(); - } -+#else /* CONFIG_SCHED_ALT */ -+DEFINE_STATIC_KEY_FALSE(sched_asym_cpucapacity); -+ -+void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[], -+ struct sched_domain_attr *dattr_new) -+{} -+ -+#ifdef CONFIG_NUMA -+int sched_numa_find_closest(const struct cpumask *cpus, int cpu) -+{ -+ return best_mask_cpu(cpu, cpus); -+} -+ -+int sched_numa_find_nth_cpu(const struct cpumask *cpus, int cpu, int node) -+{ -+ return cpumask_nth(cpu, cpus); -+} -+ -+const struct cpumask *sched_numa_hop_mask(unsigned int node, unsigned int hops) -+{ -+ return ERR_PTR(-EOPNOTSUPP); -+} -+EXPORT_SYMBOL_GPL(sched_numa_hop_mask); -+#endif /* CONFIG_NUMA */ -+ -+void sched_update_asym_prefer_cpu(int cpu, int old_prio, int new_prio) -+{} -+#endif -diff --git a/kernel/sysctl.c b/kernel/sysctl.c -index 38597f2..b049896 100644 ---- a/kernel/sysctl.c -+++ b/kernel/sysctl.c -@@ -35,6 +35,10 @@ EXPORT_SYMBOL_GPL(sysctl_long_vals); - static const int ngroups_max = NGROUPS_MAX; - static const int cap_last_cap = CAP_LAST_CAP; - -+#ifdef CONFIG_SCHED_ALT -+extern int sched_yield_type; -+#endif -+ - #ifdef CONFIG_SYSCTL - - /** -@@ -1432,6 +1436,17 @@ static const struct ctl_table sysctl_subsys_table[] = { - .proc_handler = proc_dointvec, - }, - #endif -+#ifdef CONFIG_SCHED_ALT -+ { -+ .procname = "yield_type", -+ .data = &sched_yield_type, -+ .maxlen = sizeof (int), -+ .mode = 0644, -+ .proc_handler = &proc_dointvec_minmax, -+ .extra1 = SYSCTL_ZERO, -+ .extra2 = SYSCTL_TWO, -+ }, -+#endif - #ifdef CONFIG_SYSCTL_ARCH_UNALIGN_NO_WARN - { - .procname = "ignore-unaligned-usertrap", -diff --git a/kernel/time/posix-cpu-timers.c b/kernel/time/posix-cpu-timers.c -index 65cc612..895e2f1 100644 ---- a/kernel/time/posix-cpu-timers.c -+++ b/kernel/time/posix-cpu-timers.c -@@ -223,7 +223,7 @@ static void task_sample_cputime(struct task_struct *p, u64 *samples) - u64 stime, utime; - - task_cputime(p, &utime, &stime); -- store_samples(samples, stime, utime, p->se.sum_exec_runtime); -+ store_samples(samples, stime, utime, tsk_seruntime(p)); - } - - static void proc_sample_cputime_atomic(struct task_cputime_atomic *at, -@@ -903,6 +903,7 @@ static void collect_posix_cputimers(struct posix_cputimers *pct, u64 *samples, - } - } - -+#ifndef CONFIG_SCHED_ALT - static inline void check_dl_overrun(struct task_struct *tsk) - { - if (tsk->dl.dl_overrun) { -@@ -910,6 +911,7 @@ static inline void check_dl_overrun(struct task_struct *tsk) - send_signal_locked(SIGXCPU, SEND_SIG_PRIV, tsk, PIDTYPE_TGID); - } - } -+#endif - - static bool check_rlimit(u64 time, u64 limit, int signo, bool rt, bool hard) - { -@@ -937,8 +939,10 @@ static void check_thread_timers(struct task_struct *tsk, - u64 samples[CPUCLOCK_MAX]; - unsigned long soft; - -+#ifndef CONFIG_SCHED_ALT - if (dl_task(tsk)) - check_dl_overrun(tsk); -+#endif - - if (expiry_cache_is_inactive(pct)) - return; -@@ -952,7 +956,7 @@ static void check_thread_timers(struct task_struct *tsk, - soft = task_rlimit(tsk, RLIMIT_RTTIME); - if (soft != RLIM_INFINITY) { - /* Task RT timeout is accounted in jiffies. RTTIME is usec */ -- unsigned long rttime = tsk->rt.timeout * (USEC_PER_SEC / HZ); -+ unsigned long rttime = tsk_rttimeout(tsk) * (USEC_PER_SEC / HZ); - unsigned long hard = task_rlimit_max(tsk, RLIMIT_RTTIME); - - /* At the hard limit, send SIGKILL. No further action. */ -@@ -1183,8 +1187,10 @@ static inline bool fastpath_timer_check(struct task_struct *tsk) - return true; - } - -+#ifndef CONFIG_SCHED_ALT - if (dl_task(tsk) && tsk->dl.dl_overrun) - return true; -+#endif - - return false; - } -diff --git a/kernel/trace/trace_osnoise.c b/kernel/trace/trace_osnoise.c -index 0e1265a..b2111e6 100644 ---- a/kernel/trace/trace_osnoise.c -+++ b/kernel/trace/trace_osnoise.c -@@ -1673,6 +1673,9 @@ static void osnoise_sleep(bool skip_period) - */ - static inline int osnoise_migration_pending(void) - { -+#ifdef CONFIG_SCHED_ALT -+ return 0; -+#else - if (!current->migration_pending) - return 0; - -@@ -1694,6 +1697,7 @@ static inline int osnoise_migration_pending(void) - mutex_unlock(&interface_lock); - - return 1; -+#endif - } - - /* -diff --git a/kernel/trace/trace_selftest.c b/kernel/trace/trace_selftest.c -index 929c840..0cba8b0 100644 ---- a/kernel/trace/trace_selftest.c -+++ b/kernel/trace/trace_selftest.c -@@ -1423,10 +1423,15 @@ static int trace_wakeup_test_thread(void *data) - { - /* Make this a -deadline thread */ - static const struct sched_attr attr = { -+#ifdef CONFIG_SCHED_ALT -+ /* No deadline on BMQ/PDS, use RR */ -+ .sched_policy = SCHED_RR, -+#else - .sched_policy = SCHED_DEADLINE, - .sched_runtime = 100000ULL, - .sched_deadline = 10000000ULL, - .sched_period = 10000000ULL -+#endif - }; - struct wakeup_test_data *x = data; - -diff --git a/kernel/workqueue.c b/kernel/workqueue.c -index c1cb328..b20a0b6 100644 ---- a/kernel/workqueue.c -+++ b/kernel/workqueue.c -@@ -1291,6 +1291,7 @@ static bool kick_pool_pick(struct worker_pool *pool, struct task_struct **wakep) - - p = worker->task; - -+#ifndef CONFIG_SCHED_ALT - #ifdef CONFIG_SMP - /* - * Idle @worker is about to execute @work and waking up provides an -@@ -1321,6 +1322,7 @@ static bool kick_pool_pick(struct worker_pool *pool, struct task_struct **wakep) - } - } - #endif -+#endif /* !CONFIG_SCHED_ALT */ - /* Track the last idle worker woken, used for stall diagnostics. */ - pool->last_woken_worker = worker; - -@@ -1469,7 +1471,11 @@ void wq_worker_running(struct task_struct *task) - * CPU intensive auto-detection cares about how long a work item hogged - * CPU without sleeping. Reset the starting timestamp on wakeup. - */ -+#ifdef CONFIG_SCHED_ALT -+ worker->current_at = worker->task->sched_time; -+#else - worker->current_at = READ_ONCE(worker->task->se.sum_exec_runtime); -+#endif - - WRITE_ONCE(worker->sleeping, 0); - } -@@ -1558,7 +1564,11 @@ void wq_worker_tick(struct task_struct *task) - * We probably want to make this prettier in the future. - */ - if ((worker->flags & WORKER_NOT_RUNNING) || READ_ONCE(worker->sleeping) || -+#ifdef CONFIG_SCHED_ALT -+ worker->task->sched_time - worker->current_at < -+#else - READ_ONCE(worker->task->se.sum_exec_runtime) - worker->current_at < -+#endif - wq_cpu_intensive_thresh_us * NSEC_PER_USEC) - return; - -@@ -3315,7 +3325,11 @@ __acquires(&pool->lock) - worker->current_func = work->func; - worker->current_pwq = pwq; - if (worker->task) -+#ifdef CONFIG_SCHED_ALT -+ worker->current_at = worker->task->sched_time; -+#else - worker->current_at = READ_ONCE(worker->task->se.sum_exec_runtime); -+#endif - worker->current_start = jiffies; - work_data = *work_data_bits(work); - worker->current_color = get_work_color(work_data); -diff --git a/mm/Kconfig b/mm/Kconfig -index 604c581..317b1be 100644 ---- a/mm/Kconfig -+++ b/mm/Kconfig -@@ -657,7 +657,7 @@ config COMPACTION - config COMPACT_UNEVICTABLE_DEFAULT - int - depends on COMPACTION -- default 0 if PREEMPT_RT -+ default 0 if PREEMPT_RT || ZEN_INTERACTIVE - default 1 - - # -diff --git a/mm/damon/paddr.c b/mm/damon/paddr.c -index 9ddd1ec..bd78b4e 100644 ---- a/mm/damon/paddr.c -+++ b/mm/damon/paddr.c -@@ -255,7 +255,8 @@ static unsigned long damon_pa_pageout(struct damon_region *r, - else - *sz_filter_passed += folio_size(folio) / addr_unit; - -- folio_clear_referenced(folio); -+ /* The regions is cold, better drop the hotness info */ -+ folio_clear_lru_refs(folio); - folio_test_clear_young(folio); - if (!folio_isolate_lru(folio)) - goto put_folio; -diff --git a/mm/filemap.c b/mm/filemap.c -index 73a26cd..33b6223 100644 ---- a/mm/filemap.c -+++ b/mm/filemap.c -@@ -21,6 +21,7 @@ - #include - #include - #include -+#include - #include - #include - #include -diff --git a/mm/folio.c b/mm/folio.c -index 50a6dbe..cd9a49c 100644 ---- a/mm/folio.c -+++ b/mm/folio.c -@@ -273,7 +273,6 @@ static void lru_activate(struct lruvec *lruvec, struct folio *folio) - if (folio_test_active(folio) || folio_test_unevictable(folio)) - return; - -- - lruvec_del_folio(lruvec, folio); - folio_set_active(folio); - lruvec_add_folio(lruvec, folio); -@@ -350,63 +349,6 @@ static void __lru_cache_activate_folio(struct folio *folio) - local_unlock(&cpu_fbatches.lock); - } - --#ifdef CONFIG_LRU_GEN -- --static void lru_gen_inc_refs(struct folio *folio) --{ -- unsigned long new_flags, old_flags = READ_ONCE(folio->flags.f); -- -- if (folio_test_unevictable(folio)) -- return; -- -- /* see the comment on LRU_REFS_FLAGS */ -- if (!folio_test_referenced(folio)) { -- set_mask_bits(&folio->flags.f, LRU_REFS_MASK, BIT(PG_referenced)); -- return; -- } -- -- do { -- if ((old_flags & LRU_REFS_MASK) == LRU_REFS_MASK) { -- if (!folio_test_workingset(folio)) -- folio_set_workingset(folio); -- return; -- } -- -- new_flags = old_flags + BIT(LRU_REFS_PGOFF); -- } while (!try_cmpxchg(&folio->flags.f, &old_flags, new_flags)); --} -- --static bool lru_gen_clear_refs(struct folio *folio) --{ -- int gen = folio_lru_gen(folio); -- int type = folio_is_file_lru(folio); -- unsigned long seq; -- -- if (gen < 0) -- return true; -- -- set_mask_bits(&folio->flags.f, LRU_REFS_FLAGS | BIT(PG_workingset), 0); -- -- rcu_read_lock(); -- seq = READ_ONCE(folio_lruvec(folio)->lrugen.min_seq[type]); -- rcu_read_unlock(); -- /* whether can do without shuffling under the LRU lock */ -- return gen == lru_gen_from_seq(seq); --} -- --#else /* !CONFIG_LRU_GEN */ -- --static void lru_gen_inc_refs(struct folio *folio) --{ --} -- --static bool lru_gen_clear_refs(struct folio *folio) --{ -- return false; --} -- --#endif /* CONFIG_LRU_GEN */ -- - /** - * folio_mark_accessed - Mark a folio as having seen activity. - * @folio: The folio to mark. -@@ -425,7 +367,8 @@ void folio_mark_accessed(struct folio *folio) - if (folio_test_dropbehind(folio)) - return; - if (lru_gen_enabled()) { -- lru_gen_inc_refs(folio); -+ if (!folio_test_unevictable(folio)) -+ folio_inc_lru_refs(folio, 0); - return; - } - -@@ -471,21 +414,6 @@ void folio_add_lru(struct folio *folio) - folio_test_unevictable(folio), folio); - VM_BUG_ON_FOLIO(folio_test_lru(folio), folio); - -- /* -- * For refaulted workingset folios, set PG_active so they -- * can be added to active generations. -- * For prefaulted file folios, folio_mark_accessed() sets -- * PG_referenced so lru_gen_folio_seq() places them into -- * the second oldest generation. -- */ -- if (lru_gen_enabled() && !folio_test_unevictable(folio) && -- lru_gen_in_fault() && !(current->flags & PF_MEMALLOC)) { -- if (folio_test_workingset(folio)) -- folio_set_active(folio); -- else if (!folio_test_referenced(folio)) -- folio_mark_accessed(folio); -- } -- - folio_batch_add_and_move(folio, lru_add); - } - EXPORT_SYMBOL(folio_add_lru); -@@ -597,7 +525,7 @@ static void lru_lazyfree(struct lruvec *lruvec, struct folio *folio) - lruvec_del_folio(lruvec, folio); - folio_clear_active(folio); - if (lru_gen_enabled()) -- lru_gen_clear_refs(folio); -+ __folio_set_lru_refs(folio, 0); - else - folio_clear_referenced(folio); - /* -@@ -670,7 +598,7 @@ void deactivate_file_folio(struct folio *folio) - if (folio_test_unevictable(folio) || !folio_test_lru(folio)) - return; - -- if (lru_gen_enabled() && lru_gen_clear_refs(folio)) -+ if (lru_gen_enabled() && !folio_reset_lru_refs(folio)) - return; - - folio_batch_add_and_move(folio, lru_deactivate_file); -@@ -689,7 +617,7 @@ void folio_deactivate(struct folio *folio) - if (folio_test_unevictable(folio) || !folio_test_lru(folio)) - return; - -- if (lru_gen_enabled() ? lru_gen_clear_refs(folio) : !folio_test_active(folio)) -+ if (lru_gen_enabled() ? !folio_reset_lru_refs(folio) : !folio_test_active(folio)) - return; - - folio_batch_add_and_move(folio, lru_deactivate); -diff --git a/mm/gup.c b/mm/gup.c -index 4f58ad2..2edf28e 100644 ---- a/mm/gup.c -+++ b/mm/gup.c -@@ -2895,7 +2895,7 @@ static int gup_fast_pte_range(pmd_t pmd, pmd_t *pmdp, unsigned long addr, - gup_put_folio(folio, 1, flags); - goto pte_unmap; - } -- folio_set_referenced(folio); -+ folio_inc_lru_refs_fast(folio); - pages[*nr] = page; - (*nr)++; - } while (ptep++, addr += PAGE_SIZE, addr != end); -@@ -2964,7 +2964,7 @@ static int gup_fast_pmd_leaf(pmd_t orig, pmd_t *pmdp, unsigned long addr, - *nr += refs; - for (; refs; refs--) - *(pages++) = page++; -- folio_set_referenced(folio); -+ folio_inc_lru_refs_fast(folio); - return 1; - } - -@@ -3008,7 +3008,7 @@ static int gup_fast_pud_leaf(pud_t orig, pud_t *pudp, unsigned long addr, - *nr += refs; - for (; refs; refs--) - *(pages++) = page++; -- folio_set_referenced(folio); -+ folio_inc_lru_refs_fast(folio); - return 1; - } - -diff --git a/mm/huge_memory.c b/mm/huge_memory.c -index 5f7e332..89bf58e 100644 ---- a/mm/huge_memory.c -+++ b/mm/huge_memory.c -@@ -65,7 +65,11 @@ unsigned long transparent_hugepage_flags __read_mostly = - #ifdef CONFIG_TRANSPARENT_HUGEPAGE_MADVISE - (1<vm_mm, mm_counter_file(folio), - -HPAGE_PUD_NR); -@@ -3239,8 +3243,8 @@ static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd, - folio = page_folio(page); - if (!folio_test_dirty(folio) && pmd_dirty(old_pmd)) - folio_mark_dirty(folio); -- if (!folio_test_referenced(folio) && pmd_young(old_pmd)) -- folio_set_referenced(folio); -+ if (pmd_young(old_pmd) && vma_has_recency(vma)) -+ folio_mark_accessed(folio); - folio_remove_rmap_pmd(folio, page, vma); - add_mm_counter(mm, mm_counter_file(folio), -HPAGE_PMD_NR); - folio_put(folio); -diff --git a/mm/khugepaged.c b/mm/khugepaged.c -index 47ed64f..5be3234 100644 ---- a/mm/khugepaged.c -+++ b/mm/khugepaged.c -@@ -670,7 +670,9 @@ static bool folio_pte_referenced(struct folio *folio, - struct vm_area_struct *vma, unsigned long addr, pte_t pteval) - { - /* The folio was referenced previously ... */ -- if (folio_test_young(folio) || folio_test_referenced(folio)) -+ if (folio_test_young(folio)) -+ return true; -+ if (folio_check_lru_refs(folio)) - return true; - /* ... or the PTE mapping was recently used */ - return pte_young(pteval) || mmu_notifier_test_young(vma->vm_mm, addr); -diff --git a/mm/madvise.c b/mm/madvise.c -index 222c10e..3180eeb 100644 ---- a/mm/madvise.c -+++ b/mm/madvise.c -@@ -359,6 +359,45 @@ static inline int madvise_folio_pte_batch(unsigned long addr, unsigned long end, - FPB_MERGE_YOUNG_DIRTY); - } - -+static void madvise_cold_prep_folio(struct folio *folio) -+{ -+ /* -+ * VM couldn't reclaim the folio unless we clear PG_young. -+ * As a side effect, it makes confuse idle-page tracking -+ * because they will miss recent referenced history. -+ */ -+ folio_test_clear_young(folio); -+ -+ /* -+ * For the active/inactive LRU, a folio demoted out of the active -+ * list should have PG_workingset so its refault is still accounted -+ * as a workingset refault, and the referenced bit always needs to -+ * be cleared even for inactive folios. Nothing to do for MGLRU as -+ * folio_deactivate() clears the refs count through -+ * folio_reset_lru_refs(). -+ */ -+ if (!lru_gen_enabled()) { -+ folio_clear_referenced(folio); -+ if (folio_test_active(folio)) -+ folio_set_workingset(folio); -+ } -+} -+ -+static void madvise_pageout_prep_folio(struct folio *folio) -+{ -+ int refs = folio_lru_refs(folio); -+ -+ /* -+ * For MGLRU, drop the count below LRU_REFS_WORKINGSET and cap -+ * the rest at it: MADV is -+ * suggesting the folio is actually cold, so the eviction shadow -+ * should not record its hotness in the high tier counters, but -+ * the workingset classification is preserved for PSI. -+ */ -+ if (lru_gen_enabled()) -+ __folio_set_lru_refs(folio, refs >= LRU_REFS_WORKINGSET ? LRU_REFS_WORKINGSET : 0); -+} -+ - static int madvise_cold_or_pageout_pte_range(pmd_t *pmd, - unsigned long addr, unsigned long end, - struct mm_walk *walk) -@@ -433,12 +472,10 @@ static int madvise_cold_or_pageout_pte_range(pmd_t *pmd, - tlb_remove_pmd_tlb_entry(tlb, pmd, addr); - } - -- folio_clear_referenced(folio); -- folio_test_clear_young(folio); -- if (folio_test_active(folio)) -- folio_set_workingset(folio); -+ madvise_cold_prep_folio(folio); - if (pageout) { - if (folio_isolate_lru(folio)) { -+ madvise_pageout_prep_folio(folio); - if (folio_test_unevictable(folio)) - folio_putback_lru(folio); - else -@@ -543,18 +580,10 @@ static int madvise_cold_or_pageout_pte_range(pmd_t *pmd, - tlb_remove_tlb_entries(tlb, pte, nr, addr); - } - -- /* -- * We are deactivating a folio for accelerating reclaiming. -- * VM couldn't reclaim the folio unless we clear PG_young. -- * As a side effect, it makes confuse idle-page tracking -- * because they will miss recent referenced history. -- */ -- folio_clear_referenced(folio); -- folio_test_clear_young(folio); -- if (folio_test_active(folio)) -- folio_set_workingset(folio); -+ madvise_cold_prep_folio(folio); - if (pageout) { - if (folio_isolate_lru(folio)) { -+ madvise_pageout_prep_folio(folio); - if (folio_test_unevictable(folio)) - folio_putback_lru(folio); - else -diff --git a/mm/memcontrol.c b/mm/memcontrol.c -index b303bfc..411359e 100644 ---- a/mm/memcontrol.c -+++ b/mm/memcontrol.c -@@ -1536,28 +1536,12 @@ void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru, - int zid, long nr_pages) - { - struct mem_cgroup_per_node *mz; -- unsigned long *lru_size; -- long size; - - if (mem_cgroup_disabled()) - return; - - mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec); -- lru_size = &mz->lru_zone_size[zid][lru]; -- -- if (nr_pages < 0) -- *lru_size += nr_pages; -- -- size = *lru_size; -- if (WARN_ONCE(size < 0, -- "%s(%p, %d, %ld): lru_size %ld\n", -- __func__, lruvec, lru, nr_pages, size)) { -- VM_BUG_ON(1); -- *lru_size = 0; -- } -- -- if (nr_pages > 0) -- *lru_size += nr_pages; -+ mz->lru_zone_size[zid][lru] += nr_pages; - } - - /** -diff --git a/mm/migrate.c b/mm/migrate.c -index ee78577..0d33d88 100644 ---- a/mm/migrate.c -+++ b/mm/migrate.c -@@ -776,8 +776,9 @@ void folio_migrate_flags(struct folio *newfolio, struct folio *folio) - { - int cpupid; - -- if (folio_test_referenced(folio)) -- folio_set_referenced(newfolio); -+ /* Copy the reference state, including PG_referenced */ -+ folio_migrate_lru_refs(newfolio, folio); -+ - if (folio_test_uptodate(folio)) - folio_mark_uptodate(newfolio); - if (folio_test_clear_active(folio)) { -@@ -785,8 +786,6 @@ void folio_migrate_flags(struct folio *newfolio, struct folio *folio) - folio_set_active(newfolio); - } else if (folio_test_clear_unevictable(folio)) - folio_set_unevictable(newfolio); -- if (folio_test_workingset(folio)) -- folio_set_workingset(newfolio); - if (folio_test_checked(folio)) - folio_set_checked(newfolio); - /* -@@ -807,7 +806,6 @@ void folio_migrate_flags(struct folio *newfolio, struct folio *folio) - if (folio_test_idle(folio)) - folio_set_idle(newfolio); - -- folio_migrate_refs(newfolio, folio); - /* - * Copy NUMA information to the new page, to prevent over-eager - * future migrations of this same page. -diff --git a/mm/page_io.c b/mm/page_io.c -index 8896257..b811acf 100644 ---- a/mm/page_io.c -+++ b/mm/page_io.c -@@ -16,6 +16,7 @@ - #include - #include - #include -+#include - #include - #include - #include -diff --git a/mm/swap_state.c b/mm/swap_state.c -index 0d9b0d8..0d001d6 100644 ---- a/mm/swap_state.c -+++ b/mm/swap_state.c -@@ -1031,6 +1031,10 @@ static const struct ctl_table swap_readahead_sysctl_table[] = { - - static void __init swap_readahead_setup(void) - { -+#ifdef CONFIG_ZEN_INTERACTIVE -+ /* Only swap-in pages requested, avoid readahead */ -+ page_cluster = 0; -+#else - unsigned long megs = PAGES_TO_MB(totalram_pages()); - - /* Use a smaller cluster for small-memory machines */ -@@ -1042,6 +1046,7 @@ static void __init swap_readahead_setup(void) - * Right now other parts of the system means that we - * _really_ don't want to cluster much more - */ -+#endif - - register_sysctl_init("vm", swap_readahead_sysctl_table); - } -diff --git a/mm/vmscan.c b/mm/vmscan.c -index 88fd31d..30e3977 100644 ---- a/mm/vmscan.c -+++ b/mm/vmscan.c -@@ -182,17 +182,37 @@ struct scan_control { - }; - - #ifdef ARCH_HAS_PREFETCHW --#define prefetchw_prev_lru_folio(_folio, _base, _field) \ -- do { \ -- if ((_folio)->lru.prev != _base) { \ -- struct folio *prev; \ -- \ -- prev = lru_to_folio(&(_folio->lru)); \ -- prefetchw(&prev->_field); \ -- } \ -- } while (0) -+static inline void prefetchw_prev_lru_folio(struct folio *folio, -+ struct list_head *base) -+{ -+ if (folio->lru.prev != base) { -+ struct folio *prev; -+ -+ prev = lru_to_folio(&folio->lru); -+ prefetchw(&prev->flags); -+ } -+} -+ -+static inline void prefetchw_next_lru_folio(struct folio *folio, -+ struct list_head *base) -+{ -+ if (folio->lru.next != base) { -+ struct folio *next; -+ -+ next = list_entry(folio->lru.next, struct folio, lru); -+ prefetchw(&next->flags); -+ } -+} - #else --#define prefetchw_prev_lru_folio(_folio, _base, _field) do { } while (0) -+static inline void prefetchw_prev_lru_folio(struct folio *folio, -+ struct list_head *base) -+{ -+} -+ -+static inline void prefetchw_next_lru_folio(struct folio *folio, -+ struct list_head *base) -+{ -+} - #endif - - /* -@@ -830,35 +850,257 @@ enum folio_references { - }; - - #ifdef CONFIG_LRU_GEN -+/****************************************************************************** -+ * Referenced count feedback -+ ******************************************************************************/ -+ - /* -- * Only used on a mapped folio in the eviction (rmap walk) path, where promotion -- * needs to be done by taking the folio off the LRU list and then adding it back -- * with PG_active set. In contrast, the aging (page table walk) path uses -- * folio_update_gen(). -+ * The folio_inc_lru_refs{_*} helpers below collect the referenced info -+ * (hotness) from other parts, including the page table walker, the rmap walk -+ * upon eviction, the rmap lookaround, and file descriptors -+ * (folio_mark_accessed). -+ * -+ * Page table accesses use refs from either source. The first reference -+ * advances tail-gen folios by one generation; a second promotes to the -+ * newest. Executable file folios promote on their first access to avoid -+ * I/O thrashing. Isolated rmap accesses use evict_folios() for putback. -+ * -+ * Promotion changes folio->flags; sort_folio() or inc_min_seq() moves the -+ * folio later. Young PTEs found during unmapping use folio_mark_accessed() -+ * and follow the file descriptor rules below. -+ * -+ * File descriptor accesses do not promote. They only defer eviction from -+ * the tail gens of their type, and only once the folio is a workingset -+ * folio (LRU_REFS_WORKINGSET), leaving the rest to PID protection. Page -+ * table accesses are treated more generously because the accessed bit is -+ * sticky (it under-counts repeated accesses) and because a page fault is -+ * more costly than file descriptor I/O. -+ * -+ * PID protection operates on tier > 0 folios. The one proactive promotion -+ * outside of it and the page table path is the overflow case where the -+ * referenced count exceeds LRU_REFS_MAX, which means the folio is hotter -+ * than everything else in its generation. -+ * -+ * Whenever a folio changes generation here its referenced count is capped at -+ * LRU_REFS_PROTECTED, so it starts at or below the protected tier regardless -+ * of its old-generation access history. PID protection (folio_inc_gen) caps -+ * at LRU_REFS_WORKINGSET independently. -+ * -+ * folio_inc_lru_refs() retries with LRU_REF_FORCE if the aging recycled the -+ * gen index it was about to store: newest gen and an extra reference. -+ */ -+ -+/* -+ * Update the folio's lru refs indicator. The caller doesn't need to hold -+ * the folio lock, isolate the folio, or hold the lruvec lock. Used by both -+ * cache access (flags == 0) and page table access (LRU_REF_MAPPED, -+ * optionally with LRU_REF_EXEC). - */ --static bool lru_gen_set_refs(struct folio *folio, const vma_flags_t *vma_flags) -+void folio_inc_lru_refs(struct folio *folio, unsigned int flags) - { -- /* see the comment on LRU_REFS_FLAGS */ -- if (!folio_test_referenced(folio) && !folio_test_workingset(folio)) { -- /* Activate file-backed executable folios after first usage. */ -- if (is_exec_file_folio(folio, vma_flags)) { -- set_mask_bits(&folio->flags.f, LRU_REFS_FLAGS, BIT(PG_workingset)); -- return true; -+ int max_gen; -+ int file, old_refs, refs, old_gen, gen; -+ unsigned long new_flags, old_flags, max_seq; -+ long nr_pages = folio_nr_pages(folio); -+ struct lru_gen_folio *lrugen; -+ struct lruvec *lruvec = NULL; -+ bool aged = false; -+ -+retry: -+ old_flags = READ_ONCE(*folio_flags(folio, 0)); -+ do { -+ new_flags = old_flags; -+ old_gen = lru_get_gen_flags(old_flags); -+ old_refs = lru_get_refs_flags(old_flags); -+ refs = old_refs + 1; -+ gen = old_gen; -+ file = folio_flags_is_file_lru(&old_flags); -+ if (old_gen < 0) -+ goto out; -+ if (!lruvec) { -+ lruvec = folio_lruvec_live_get(folio); -+ lrugen = &lruvec->lrugen; -+ } -+ /* -+ * Read the flags before max_seq, paired with the store of a -+ * gen, which samples max_seq first. -+ */ -+ smp_rmb(); -+ max_seq = READ_ONCE(lrugen->max_seq); -+ max_gen = lru_gen_from_seq(max_seq); -+ if (old_gen == max_gen) -+ goto out; -+ if (flags & (LRU_REF_MAPPED | LRU_REF_EXEC | LRU_REF_FORCE)) { -+ if (refs > LRU_REFS_REFERENCED || -+ flags & (LRU_REF_EXEC | LRU_REF_FORCE)) -+ gen = max_gen; -+ /* First access only defers eviction of a tail gen */ -+ else if (lru_gen_at_tail(lruvec, file, old_gen)) -+ gen = (old_gen + 1) % MAX_NR_GENS; -+ refs = min(refs, LRU_REFS_PROTECTED); -+ } else if (refs > LRU_REFS_MAX) { -+ /* LRU refs counting overflow, bump the gen */ -+ gen = (old_gen + 1) % MAX_NR_GENS; -+ refs = LRU_REFS_PROTECTED; -+ } else if (lru_gen_at_tail(lruvec, file, old_gen) && refs >= LRU_REFS_WORKINGSET) { -+ /* Defer eviction of just accessed workingset */ -+ gen = (old_gen + 1) % MAX_NR_GENS; -+ refs = min(refs, LRU_REFS_PROTECTED); -+ } -+out: -+ refs = min(refs, LRU_REFS_MAX); -+ lru_set_refs_flags(&new_flags, refs); -+ if (gen != old_gen) -+ lru_set_gen_flags(&new_flags, gen); -+ if (new_flags == old_flags) -+ break; -+ } while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags)); -+ -+ if (gen != old_gen) { -+ /* -+ * Gen-index reuse can fool cmpxchg(). Retry locklessly, accepting -+ * an extra reference to avoid folio_activate() latency. -+ */ -+ if (unlikely(READ_ONCE(lrugen->max_seq) != max_seq)) { -+ flags = LRU_REF_FORCE; -+ aged = true; - } -+ lru_gen_update_size(lruvec, file, folio, old_gen, gen); -+ } - -- set_mask_bits(&folio->flags.f, LRU_REFS_MASK, BIT(PG_referenced)); -- return false; -+ if (lru_refs_is_active(old_refs) != lru_refs_is_active(refs) && gen >= 0) { -+ enum lru_list lru = file * LRU_INACTIVE_FILE; -+ -+ __update_lru_size(lruvec, lru + lru_refs_is_active(old_refs), -+ folio_zonenum(folio), -nr_pages); -+ __update_lru_size(lruvec, lru + lru_refs_is_active(refs), -+ folio_zonenum(folio), nr_pages); -+ } -+ if (aged) { -+ aged = false; -+ goto retry; - } -+ if (lruvec) -+ folio_lruvec_live_put(lruvec); -+} - -- /* Promote on second access */ -- if (folio_lru_refs(folio) > 1) -- set_mask_bits(&folio->flags.f, LRU_REFS_FLAGS, BIT(PG_workingset)); -- else -- folio_mark_accessed(folio); -- return true; -+/* -+ * Reset the folio's lru refs indicator. The caller doesn't need to hold -+ * the folio lock, isolate the folio, or hold the lruvec lock. -+ */ -+bool folio_reset_lru_refs(struct folio *folio) -+{ -+ int type, gen, refs; -+ unsigned long seq, new_flags, old_flags; -+ long nr_pages = folio_nr_pages(folio); -+ struct lruvec *lruvec; -+ bool reset = false; -+ -+ old_flags = READ_ONCE(*folio_flags(folio, 0)); -+ do { -+ new_flags = old_flags; -+ refs = lru_get_refs_flags(old_flags); -+ type = folio_flags_is_file_lru(&old_flags); -+ gen = lru_get_gen_flags(old_flags); -+ if (!refs) -+ break; -+ lru_set_refs_flags(&new_flags, 0); -+ } while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags)); -+ -+ if (gen >= 0) { -+ lruvec = folio_lruvec_live_get(folio); -+ -+ /* If the folio is on list, caller might also want to demote it */ -+ seq = READ_ONCE(lruvec->lrugen.min_seq[type]); -+ reset = (gen != lru_gen_from_seq(seq)); -+ if (lru_refs_is_active(refs)) { -+ __update_lru_size(lruvec, type * LRU_FILE + LRU_ACTIVE, -+ folio_zonenum(folio), -nr_pages); -+ __update_lru_size(lruvec, type * LRU_FILE, -+ folio_zonenum(folio), nr_pages); -+ } -+ -+ folio_lruvec_live_put(lruvec); -+ } -+ -+ return reset; -+} -+ -+/* -+ * Update the folio's lru refs indicator during a page table walk or the -+ * look-around. max_seq can be stale as neither holds the LRU lock. -+ * -+ * Returns the old generation, or -1 if the folio is off the LRU list. -+ * Old LRU refs, and updated gen and LRU refs info by the successful -+ * cmpxchg are all stored by returning arguments. -+ */ -+static int folio_inc_lru_refs_walk(struct folio *folio, struct lruvec *lruvec, -+ const vma_flags_t *vma_flags, int *new_gen, -+ int *old_refs, int *new_refs, int *type) -+{ -+ unsigned long new_flags, old_flags = READ_ONCE(*folio_flags(folio, 0)); -+ int refs, old_gen, max_gen; -+ unsigned long max_seq; -+ -+ do { -+ max_seq = READ_ONCE(lruvec->lrugen.max_seq); -+ max_gen = lru_gen_from_seq(max_seq); -+ old_gen = lru_get_gen_flags(old_flags); -+ refs = lru_get_refs_flags(old_flags) + 1; -+ *type = folio_flags_is_file_lru(&old_flags); -+ new_flags = old_flags; -+ -+ if (old_gen >= 0 && old_gen != max_gen) { -+ *new_refs = min(refs, LRU_REFS_PROTECTED); -+ /* Promote second page table access or executable */ -+ if (refs > LRU_REFS_REFERENCED || is_exec_file_folio(folio, vma_flags)) -+ *new_gen = max_gen; -+ /* First access only defers eviction of a tail gen */ -+ else if (lru_gen_at_tail(lruvec, *type, old_gen)) -+ *new_gen = (old_gen + 1) % MAX_NR_GENS; -+ else -+ *new_gen = old_gen; -+ lru_set_gen_flags(&new_flags, *new_gen); -+ lru_set_refs_flags(&new_flags, *new_refs); -+ } else { -+ *new_gen = old_gen; -+ *new_refs = min(refs, LRU_REFS_MAX); -+ lru_set_refs_flags(&new_flags, *new_refs); -+ } -+ if (new_flags == old_flags) -+ break; -+ } while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags)); -+ -+ *old_refs = lru_get_refs_flags(old_flags); -+ -+ return old_gen; -+} -+ -+/* -+ * Update the lru refs indicator of an isolated folio, only used on -+ * mapped folios upon the final eviction. -+ * -+ * Increments the refs count (capped at LRU_REFS_PROTECTED, evict_folios() -+ * then caps it at LRU_REFS_WORKINGSET). Returns true if the caller should -+ * activate the folio (second access or executable), false to put it back -+ * for a second chance. -+ */ -+static bool folio_inc_lru_refs_isolated(struct folio *folio, const vma_flags_t *vma_flags) -+{ -+ unsigned long new_flags, old_flags = READ_ONCE(*folio_flags(folio, 0)); -+ int refs; -+ -+ do { -+ new_flags = old_flags; -+ refs = lru_get_refs_flags(old_flags) + 1; -+ lru_set_refs_flags(&new_flags, min(refs, LRU_REFS_PROTECTED)); -+ } while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags)); -+ -+ /* Promote second page table access or executable */ -+ return refs > LRU_REFS_REFERENCED || is_exec_file_folio(folio, vma_flags); - } - #else --static bool lru_gen_set_refs(struct folio *folio, const vma_flags_t *vma_flags) -+static bool folio_inc_lru_refs_isolated(struct folio *folio, const vma_flags_t *vma_flags) - { - return false; - } -@@ -893,7 +1135,8 @@ static enum folio_references folio_check_references(struct folio *folio, - if (!referenced_ptes) - return FOLIOREF_RECLAIM; - -- return lru_gen_set_refs(folio, &vma_flags) ? FOLIOREF_ACTIVATE : FOLIOREF_KEEP; -+ return folio_inc_lru_refs_isolated(folio, &vma_flags) ? -+ FOLIOREF_ACTIVATE : FOLIOREF_KEEP; - } - - referenced_folio = folio_test_clear_referenced(folio); -@@ -1694,7 +1937,7 @@ static unsigned long isolate_lru_folios(unsigned long nr_to_scan, - struct folio *folio; - - folio = lru_to_folio(src); -- prefetchw_prev_lru_folio(folio, src, flags); -+ prefetchw_prev_lru_folio(folio, src); - - nr_pages = folio_nr_pages(folio); - total_scan += nr_pages; -@@ -3177,9 +3420,9 @@ static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long seq) - * P term over the generations previously evicted, using the smoothing factor - * 1/2; the D term isn't supported. - * -- * The setpoint (SP) is always the first tier of one type; the process variable -- * (PV) is either any tier of the other type or any other tier of the same -- * type. -+ * To select a type, the setpoint (SP) is all tiers of one type and the process -+ * variable (PV) is all tiers of the other type. To select a tier to protect, -+ * the SP is the tiers below it and the PV is the tier itself. - * - * The error is the difference between the SP and the PV; the correction is to - * turn off protection when SP>PV or turn on protection when SPflags.f); -+ unsigned long new_flags, old_flags = READ_ONCE(*folio_flags(folio, 0)); -+ int file, refs, old_refs, new_gen; - -- VM_WARN_ON_ONCE(gen >= MAX_NR_GENS); -+ do { -+ new_gen = lru_get_gen_flags(old_flags); - -- /* -- * See the comment on LRU_REFS_FLAGS, and activate file-backed -- * executable folios after first usage to avoid typical IO -- * thrashing from reclaiming. -- */ -- if (!folio_test_referenced(folio) && !folio_test_workingset(folio) && -- !is_exec_file_folio(folio, vma_flags)) { -- set_mask_bits(&folio->flags.f, LRU_REFS_MASK, BIT(PG_referenced)); -- return -1; -- } -+ /* folio_inc_lru_refs() has promoted this page? */ -+ if (new_gen >= 0 && new_gen != old_gen) { -+ if (increased) -+ *increased = false; -+ return new_gen; -+ } - -- do { -- /* lru_gen_del_folio() has isolated this page? */ -- if (!(old_flags & LRU_GEN_MASK)) -- return -1; -+ new_flags = old_flags; -+ new_gen = (old_gen + 1) % MAX_NR_GENS; -+ old_refs = lru_get_refs_flags(old_flags); -+ file = folio_flags_is_file_lru(&old_flags); -+ refs = min(old_refs, LRU_REFS_WORKINGSET); -+ lru_set_gen_flags(&new_flags, new_gen); -+ lru_set_refs_flags(&new_flags, refs); -+ } while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags)); -+ -+ /* Refs capped below PROTECTED: demote if previously active. */ -+ if (lru_refs_is_active(old_refs) != lru_refs_is_active(refs)) { -+ enum lru_list lru = file * LRU_INACTIVE_FILE; -+ int nr_pages = folio_nr_pages(folio); - -- new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_FLAGS); -- new_flags |= ((gen + 1UL) << LRU_GEN_PGOFF) | BIT(PG_workingset); -- } while (!try_cmpxchg(&folio->flags.f, &old_flags, new_flags)); -+ __update_lru_size(lruvec, lru + lru_refs_is_active(old_refs), -+ folio_zonenum(folio), -nr_pages); -+ __update_lru_size(lruvec, lru + lru_refs_is_active(refs), -+ folio_zonenum(folio), nr_pages); -+ } - -- return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1; -+ if (increased) -+ *increased = true; -+ return new_gen; - } - --/* protect pages accessed multiple times through file descriptors */ -+/* -+ * Force bump a folio's generation. Used for PID protection or to skip a -+ * folio from a zone ineligible for the current reclaim. -+ */ - static int folio_inc_gen(struct lruvec *lruvec, struct folio *folio) - { -+ bool gen_increased; - int type = folio_is_file_lru(folio); - struct lru_gen_folio *lrugen = &lruvec->lrugen; - int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]); -- unsigned long new_flags, old_flags = READ_ONCE(folio->flags.f); - -- VM_WARN_ON_ONCE_FOLIO(!(old_flags & LRU_GEN_MASK), folio); -- -- do { -- new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1; -- /* folio_update_gen() has promoted this page? */ -- if (new_gen >= 0 && new_gen != old_gen) -- return new_gen; -- -- new_gen = (old_gen + 1) % MAX_NR_GENS; -- -- new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_FLAGS); -- new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF; -- } while (!try_cmpxchg(&folio->flags.f, &old_flags, new_flags)); -- -- lru_gen_update_size(lruvec, folio, old_gen, new_gen); -+ new_gen = __folio_inc_gen(lruvec, folio, old_gen, &gen_increased); -+ if (gen_increased) -+ lru_gen_update_size(lruvec, type, folio, old_gen, new_gen); - - return new_gen; - } - - static void update_batch_size(struct lru_gen_mm_walk *walk, struct folio *folio, -- int old_gen, int new_gen) -+ int old_gen, int new_gen, int old_refs, int new_refs, int type) - { -- int type = folio_is_file_lru(folio); - int zone = folio_zonenum(folio); - int delta = folio_nr_pages(folio); - -- VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS); -- VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS); -- -- walk->batched++; -+ /* gen counter update */ -+ if (old_gen != new_gen) { -+ VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS); -+ VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS); -+ walk->batched++; -+ walk->nr_pages[old_gen][type][zone] -= delta; -+ walk->nr_pages[new_gen][type][zone] += delta; -+ } - -- walk->nr_pages[old_gen][type][zone] -= delta; -- walk->nr_pages[new_gen][type][zone] += delta; -+ /* active/inactive counter update */ -+ if (lru_refs_is_active(old_refs) != lru_refs_is_active(new_refs)) { -+ walk->nr_activated[type][zone] += -+ lru_refs_is_active(new_refs) ? delta : -delta; -+ walk->batched++; -+ } - } - - static void reset_batch_size(struct lru_gen_mm_walk *walk) -@@ -3349,19 +3601,28 @@ static void reset_batch_size(struct lru_gen_mm_walk *walk) - walk->batched = 0; - - for_each_gen_type_zone(gen, type, zone) { -- enum lru_list lru = type * LRU_INACTIVE_FILE; - int delta = walk->nr_pages[gen][type][zone]; - - if (!delta) - continue; - - walk->nr_pages[gen][type][zone] = 0; -- WRITE_ONCE(lrugen->nr_pages[gen][type][zone], -- lrugen->nr_pages[gen][type][zone] + delta); -+ atomic_long_add(delta, &lrugen->nr_pages[gen][type][zone]); -+ } -+ -+ /* apply batched active/inactive updates */ -+ for (type = 0; type < ANON_AND_FILE; type++) { -+ for (zone = 0; zone < MAX_NR_ZONES; zone++) { -+ enum lru_list lru = type * LRU_INACTIVE_FILE; -+ int delta = walk->nr_activated[type][zone]; - -- if (lru_gen_is_active(lruvec, gen)) -- lru += LRU_ACTIVE; -- __update_lru_size(lruvec, lru, zone, delta); -+ if (delta) { -+ __update_lru_size(lruvec, lru + LRU_ACTIVE, -+ zone, delta); -+ __update_lru_size(lruvec, lru, zone, -delta); -+ walk->nr_activated[type][zone] = 0; -+ } -+ } - } - - lruvec_unlock_irq(lruvec); -@@ -3514,9 +3775,10 @@ static bool suitable_to_scan(int total, int young) - } - - static void walk_update_folio(struct lru_gen_mm_walk *walk, struct vm_area_struct *vma, -- struct folio *folio, int new_gen, bool dirty) -+ struct lruvec *lruvec, struct folio *folio, bool dirty) - { -- int old_gen; -+ int new_gen, old_gen, old_refs, new_refs, type; -+ unsigned int flags = LRU_REF_MAPPED; - - if (!folio) - return; -@@ -3527,13 +3789,15 @@ static void walk_update_folio(struct lru_gen_mm_walk *walk, struct vm_area_struc - folio_mark_dirty(folio); - - if (walk) { -- old_gen = folio_update_gen(folio, new_gen, &vma->flags); -- if (old_gen >= 0 && old_gen != new_gen) -- update_batch_size(walk, folio, old_gen, new_gen); -- } else if (lru_gen_set_refs(folio, &vma->flags)) { -- old_gen = folio_lru_gen(folio); -- if (old_gen >= 0 && old_gen != new_gen) -- folio_activate(folio); -+ old_gen = folio_inc_lru_refs_walk(folio, lruvec, &vma->flags, -+ &new_gen, &old_refs, &new_refs, &type); -+ if (old_gen >= 0) -+ update_batch_size(walk, folio, old_gen, new_gen, -+ old_refs, new_refs, type); -+ } else { -+ if (is_exec_file_folio(folio, &vma->flags)) -+ flags |= LRU_REF_EXEC; -+ folio_inc_lru_refs(folio, flags); - } - } - -@@ -3551,8 +3815,6 @@ static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end, - struct lru_gen_mm_walk *walk = args->private; - struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec); - struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec); -- DEFINE_MAX_SEQ(walk->lruvec); -- int gen = lru_gen_from_seq(max_seq); - unsigned int nr; - pmd_t pmdval; - -@@ -3603,7 +3865,7 @@ static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end, - continue; - - if (last != folio) { -- walk_update_folio(walk, args->vma, last, gen, dirty); -+ walk_update_folio(walk, args->vma, walk->lruvec, last, dirty); - - last = folio; - dirty = false; -@@ -3616,7 +3878,7 @@ static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end, - walk->mm_stats[MM_LEAF_YOUNG] += nr; - } - -- walk_update_folio(walk, args->vma, last, gen, dirty); -+ walk_update_folio(walk, args->vma, walk->lruvec, last, dirty); - last = NULL; - - if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end)) -@@ -3639,8 +3901,6 @@ static void walk_pmd_range_locked(pud_t *pud, unsigned long addr, struct vm_area - struct lru_gen_mm_walk *walk = args->private; - struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec); - struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec); -- DEFINE_MAX_SEQ(walk->lruvec); -- int gen = lru_gen_from_seq(max_seq); - - VM_WARN_ON_ONCE(pud_leaf(*pud)); - -@@ -3694,7 +3954,7 @@ static void walk_pmd_range_locked(pud_t *pud, unsigned long addr, struct vm_area - goto next; - - if (last != folio) { -- walk_update_folio(walk, vma, last, gen, dirty); -+ walk_update_folio(walk, vma, walk->lruvec, last, dirty); - - last = folio; - dirty = false; -@@ -3708,7 +3968,7 @@ static void walk_pmd_range_locked(pud_t *pud, unsigned long addr, struct vm_area - i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1; - } while (i <= MIN_LRU_BATCH); - -- walk_update_folio(walk, vma, last, gen, dirty); -+ walk_update_folio(walk, vma, walk->lruvec, last, dirty); - - lazy_mmu_mode_disable(); - spin_unlock(ptl); -@@ -3892,6 +4152,7 @@ static void clear_mm_walk(void) - - VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages))); - VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats))); -+ VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_activated, 0, sizeof(walk->nr_activated))); - - current->reclaim_state->mm_walk = NULL; - -@@ -3899,6 +4160,19 @@ static void clear_mm_walk(void) - kfree(walk); - } - -+static inline void flush_lru_batch(struct list_head *head, struct list_head **batch_end, -+ struct list_head *dst) -+{ -+ LIST_HEAD(movable); -+ -+ if (!*batch_end) -+ return; -+ -+ list_cut_position(&movable, head, *batch_end); -+ list_splice_tail_init(&movable, dst); -+ *batch_end = NULL; -+} -+ - static bool inc_min_seq(struct lruvec *lruvec, int type, int swappiness) - { - int zone; -@@ -3906,6 +4180,7 @@ static bool inc_min_seq(struct lruvec *lruvec, int type, int swappiness) - struct lru_gen_folio *lrugen = &lruvec->lrugen; - int hist = lru_hist_from_seq(lrugen->min_seq[type]); - int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]); -+ int target_gen = (old_gen + 1) % MAX_NR_GENS; - - /* For file type, skip the check if swappiness is anon only */ - if (type && (swappiness == SWAPPINESS_ANON_ONLY)) -@@ -3915,35 +4190,53 @@ static bool inc_min_seq(struct lruvec *lruvec, int type, int swappiness) - if (!type && !swappiness) - goto done; - -+ VM_WARN_ON_ONCE(get_nr_gens(lruvec, type) != MAX_NR_GENS); - /* prevent cold/hot inversion if the type is evictable */ - for (zone = 0; zone < MAX_NR_ZONES; zone++) { -+ struct list_head *target_list = &lrugen->folios[target_gen][type][zone]; - struct list_head *head = &lrugen->folios[old_gen][type][zone]; -+ struct list_head *pos = head->next; -+ struct list_head *batch_end = NULL; -+ long delta = 0; - -- while (!list_empty(head)) { -- struct folio *folio = lru_to_folio(head); -+ while (pos != head) { -+ struct folio *folio = list_entry(pos, struct folio, lru); -+ long nr_pages = folio_nr_pages(folio); - int refs = folio_lru_refs(folio); -- bool workingset = folio_test_workingset(folio); -+ int tier = lru_tier_from_refs(refs); -+ bool gen_increased; - - VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio); - VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio); - VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio); - VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio); - -- new_gen = folio_inc_gen(lruvec, folio); -- list_move_tail(&folio->lru, &lrugen->folios[new_gen][type][zone]); -- -- /* don't count the workingset being lazily promoted */ -- if (refs + workingset != BIT(LRU_REFS_WIDTH) + 1) { -- int tier = lru_tier_from_refs(refs, workingset); -- int delta = folio_nr_pages(folio); -+ prefetchw_next_lru_folio(folio, head); -+ pos = pos->next; -+ new_gen = __folio_inc_gen(lruvec, folio, old_gen, &gen_increased); -+ /* -+ * If gen_increased is false, this is a promotion. Put folios -+ * at the head of the promoted gen. Otherwise, put them at -+ * the tail of the second-oldest gen. -+ */ -+ if (gen_increased) { -+ delta += nr_pages; -+ batch_end = &folio->lru; - - WRITE_ONCE(lrugen->protected[hist][type][tier], -- lrugen->protected[hist][type][tier] + delta); -+ lrugen->protected[hist][type][tier] + nr_pages); -+ } else { -+ flush_lru_batch(head, &batch_end, target_list); -+ list_move(&folio->lru, &lrugen->folios[new_gen][type][zone]); - } -- - if (!--remaining) -- return false; -+ break; - } -+ flush_lru_batch(head, &batch_end, target_list); -+ atomic_long_sub(delta, &lrugen->nr_pages[old_gen][type][zone]); -+ atomic_long_add(delta, &lrugen->nr_pages[target_gen][type][zone]); -+ if (!remaining) -+ return false; - } - done: - reset_ctrl_pos(lruvec, type, true); -@@ -4007,8 +4300,7 @@ static void try_to_inc_min_seq(struct lruvec *lruvec, int swappiness) - static bool inc_max_seq(struct lruvec *lruvec, unsigned long seq, int swappiness) - { - bool success; -- int prev, next; -- int type, zone; -+ int type, next; - struct lru_gen_folio *lrugen = &lruvec->lrugen; - restart: - if (seq < READ_ONCE(lrugen->max_seq)) -@@ -4034,32 +4326,10 @@ static bool inc_max_seq(struct lruvec *lruvec, unsigned long seq, int swappiness - goto restart; - } - -- /* -- * Update the active/inactive LRU sizes for compatibility. Both sides of -- * the current max_seq need to be covered, since max_seq+1 can overlap -- * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do -- * overlap, cold/hot inversion happens. -- */ -- prev = lru_gen_from_seq(lrugen->max_seq - 1); -- next = lru_gen_from_seq(lrugen->max_seq + 1); -- -- for (type = 0; type < ANON_AND_FILE; type++) { -- for (zone = 0; zone < MAX_NR_ZONES; zone++) { -- enum lru_list lru = type * LRU_INACTIVE_FILE; -- long delta = lrugen->nr_pages[prev][type][zone] - -- lrugen->nr_pages[next][type][zone]; -- -- if (!delta) -- continue; -- -- __update_lru_size(lruvec, lru, zone, delta); -- __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta); -- } -- } -- - for (type = 0; type < ANON_AND_FILE; type++) - reset_ctrl_pos(lruvec, type, false); - -+ next = lru_gen_from_seq(lrugen->max_seq + 1); - WRITE_ONCE(lrugen->timestamps[next], jiffies); - /* make sure preceding modifications appear */ - smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1); -@@ -4165,7 +4435,8 @@ static unsigned long lruvec_evictable_size(struct lruvec *lruvec, int swappiness - for (seq = min_seq[type]; seq <= max_seq; seq++) { - gen = lru_gen_from_seq(seq); - for (zone = 0; zone < MAX_NR_ZONES; zone++) -- total += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L); -+ total += max(atomic_long_read(&lrugen->nr_pages[gen][type][zone]), -+ 0L); - } - } - -@@ -4272,8 +4543,6 @@ bool lru_gen_look_around(struct page_vma_mapped_walk *pvmw, unsigned int nr) - struct pglist_data *pgdat = folio_pgdat(folio); - struct lruvec *lruvec; - struct lru_gen_mm_state *mm_state; -- unsigned long max_seq; -- int gen; - - lockdep_assert_held(pvmw->ptl); - VM_WARN_ON_ONCE_FOLIO(folio_test_lru(folio), folio); -@@ -4310,8 +4579,6 @@ bool lru_gen_look_around(struct page_vma_mapped_walk *pvmw, unsigned int nr) - - memcg = get_mem_cgroup_from_folio(folio); - lruvec = mem_cgroup_lruvec(memcg, pgdat); -- max_seq = READ_ONCE((lruvec)->lrugen.max_seq); -- gen = lru_gen_from_seq(max_seq); - mm_state = get_mm_state(lruvec); - - lazy_mmu_mode_enable(); -@@ -4343,7 +4610,7 @@ bool lru_gen_look_around(struct page_vma_mapped_walk *pvmw, unsigned int nr) - continue; - - if (last != folio) { -- walk_update_folio(walk, vma, last, gen, dirty); -+ walk_update_folio(walk, vma, lruvec, last, dirty); - - last = folio; - dirty = false; -@@ -4355,13 +4622,14 @@ bool lru_gen_look_around(struct page_vma_mapped_walk *pvmw, unsigned int nr) - young += nr; - } - -- walk_update_folio(walk, vma, last, gen, dirty); -+ walk_update_folio(walk, vma, lruvec, last, dirty); - - lazy_mmu_mode_disable(); - - /* feedback from rmap walkers to page table walkers */ - if (mm_state && suitable_to_scan(i, young)) -- update_bloom_filter(mm_state, max_seq, pvmw->pmd); -+ update_bloom_filter(mm_state, READ_ONCE(lruvec->lrugen.max_seq), -+ pvmw->pmd); - - mem_cgroup_put(memcg); - -@@ -4592,30 +4860,22 @@ static void __lru_gen_reparent_memcg(struct lruvec *child_lruvec, struct lruvec - int zone, int type) - { - struct lru_gen_folio *child_lrugen, *parent_lrugen; -- enum lru_list lru = type * LRU_INACTIVE_FILE; - int i; - - child_lrugen = &child_lruvec->lrugen; - parent_lrugen = &parent_lruvec->lrugen; - -- for (i = 0; i < get_nr_gens(child_lruvec, type); i++) { -+ /* Lockless promotion may leave folios outside the child's window */ -+ for (i = 0; i < MAX_NR_GENS; i++) { - int gen = lru_gen_from_seq(child_lrugen->max_seq - i); -- long nr_pages = child_lrugen->nr_pages[gen][type][zone]; -- int child_lru_active = lru_gen_is_active(child_lruvec, gen) ? LRU_ACTIVE : 0; -- int parent_lru_active = lru_gen_is_active(parent_lruvec, gen) ? LRU_ACTIVE : 0; -+ long nr_pages = atomic_long_read(&child_lrugen->nr_pages[gen][type][zone]); - - /* Assuming that child pages are colder than parent pages */ - list_splice_tail_init(&child_lrugen->folios[gen][type][zone], - &parent_lrugen->folios[gen][type][zone]); - -- WRITE_ONCE(child_lrugen->nr_pages[gen][type][zone], 0); -- WRITE_ONCE(parent_lrugen->nr_pages[gen][type][zone], -- parent_lrugen->nr_pages[gen][type][zone] + nr_pages); -- -- if (lru_gen_is_active(child_lruvec, gen) != lru_gen_is_active(parent_lruvec, gen)) { -- __update_lru_size(child_lruvec, lru + child_lru_active, zone, -nr_pages); -- __update_lru_size(parent_lruvec, lru + parent_lru_active, zone, nr_pages); -- } -+ atomic_long_set(&child_lrugen->nr_pages[gen][type][zone], 0); -+ atomic_long_add(nr_pages, &parent_lrugen->nr_pages[gen][type][zone]); - } - } - -@@ -4661,8 +4921,7 @@ static bool sort_folio(struct lruvec *lruvec, struct folio *folio, struct scan_c - int zone = folio_zonenum(folio); - int delta = folio_nr_pages(folio); - int refs = folio_lru_refs(folio); -- bool workingset = folio_test_workingset(folio); -- int tier = lru_tier_from_refs(refs, workingset); -+ int tier = lru_tier_from_refs(refs); - struct lru_gen_folio *lrugen = &lruvec->lrugen; - - VM_WARN_ON_ONCE_FOLIO(gen >= MAX_NR_GENS, folio); -@@ -4678,17 +4937,15 @@ static bool sort_folio(struct lruvec *lruvec, struct folio *folio, struct scan_c - } - - /* protected */ -- if (tier > tier_idx || refs + workingset == BIT(LRU_REFS_WIDTH) + 1) { -+ if (tier > tier_idx) { -+ int hist = lru_hist_from_seq(lrugen->min_seq[type]); -+ - gen = folio_inc_gen(lruvec, folio); - list_move(&folio->lru, &lrugen->folios[gen][type][zone]); - -- /* don't count the workingset being lazily promoted */ -- if (refs + workingset != BIT(LRU_REFS_WIDTH) + 1) { -- int hist = lru_hist_from_seq(lrugen->min_seq[type]); -+ WRITE_ONCE(lrugen->protected[hist][type][tier], -+ lrugen->protected[hist][type][tier] + delta); - -- WRITE_ONCE(lrugen->protected[hist][type][tier], -- lrugen->protected[hist][type][tier] + delta); -- } - return true; - } - -@@ -4716,10 +4973,6 @@ static bool isolate_folio(struct lruvec *lruvec, struct folio *folio, struct sca - return false; - } - -- /* see the comment on LRU_REFS_FLAGS */ -- if (!folio_test_referenced(folio)) -- set_mask_bits(&folio->flags.f, LRU_REFS_MASK, 0); -- - success = lru_gen_del_folio(lruvec, folio, true); - VM_WARN_ON_ONCE_FOLIO(!success, folio); - -@@ -4807,13 +5060,14 @@ static int get_tier_idx(struct lruvec *lruvec, int type) - struct ctrl_pos sp, pv; - - /* -- * To leave a margin for fluctuations, use a larger gain factor (2:3). -- * This value is chosen because any other tier would have at least twice -- * as many refaults as the first tier. -+ * To leave a margin for fluctuations, use a larger gain factor (1:2). -+ * Stop at the first tier whose refault rate is clearly worse than -+ * that of the cumulative mass of the tiers below it; the PID -+ * protects the tiers above it. - */ -- read_ctrl_pos(lruvec, type, LRU_TIER_MIN, LRU_TIER_MIN, 2, &sp); - for (tier = LRU_TIER_MIN + 1; tier <= LRU_TIER_MAX; tier++) { -- read_ctrl_pos(lruvec, type, tier, tier, 3, &pv); -+ read_ctrl_pos(lruvec, type, LRU_TIER_MIN, tier - 1, 1, &sp); -+ read_ctrl_pos(lruvec, type, tier, tier, 2, &pv); - if (!positive_ctrl_err(&sp, &pv)) - break; - } -@@ -4901,6 +5155,9 @@ static int evict_folios(unsigned long nr_to_scan, struct lruvec *lruvec, - scanned = isolate_folios(nr_to_scan, lruvec, sc, swappiness, - &list, &isolated, &type, &type_scanned); - nr_isolated = isolated; -+ if (nr_isolated) -+ __mod_node_page_state(pgdat, NR_ISOLATED_ANON + type, -+ nr_isolated); - - /* Scanning may have emptied the oldest gen, flush it */ - if (scanned) -@@ -4935,9 +5192,16 @@ static int evict_folios(unsigned long nr_to_scan, struct lruvec *lruvec, - continue; - } - -- /* don't add rejected folios to the oldest generation */ -+ /* -+ * The rejected folios are never added to the oldest generation, -+ * so this effectively promotes them by at least one generation. -+ * PG_active is the only placement hint here, so a folio kept on -+ * its first page table access lands in the second newest one. -+ * See "Referenced count feedback" above. -+ */ -+ __folio_set_lru_refs(folio, min(folio_lru_refs(folio), LRU_REFS_WORKINGSET)); - if (lru_gen_folio_seq(lruvec, folio, false) == min_seq[type]) -- set_mask_bits(&folio->flags.f, LRU_REFS_FLAGS, BIT(PG_active)); -+ folio_set_active(folio); - } - - move_folios_to_lru(&list); -@@ -4963,6 +5227,8 @@ static int evict_folios(unsigned long nr_to_scan, struct lruvec *lruvec, - goto retry; - } - -+ mod_node_page_state(pgdat, NR_ISOLATED_ANON + type, -nr_isolated); -+ - if (nr_isolated > total_reclaimed) - mod_lruvec_state(lruvec, PGROTATE_ANON + type, - nr_isolated - total_reclaimed); -@@ -5654,7 +5920,8 @@ static int lru_gen_seq_show(struct seq_file *m, void *v) - char mark = full && seq < min_seq[type] ? 'x' : ' '; - - for (zone = 0; zone < MAX_NR_ZONES; zone++) -- size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L); -+ size += max(atomic_long_read(&lrugen->nr_pages[gen][type][zone]), -+ 0L); - - seq_printf(m, " %10lu%c", size, mark); - } -@@ -5680,6 +5947,9 @@ static int run_aging(struct lruvec *lruvec, unsigned long seq, - { - DEFINE_MAX_SEQ(lruvec); - -+ if (seq < max_seq) -+ return 0; -+ - if (seq > max_seq) - return -EINVAL; - -diff --git a/mm/workingset.c b/mm/workingset.c -index 8412f48..a04d495 100644 ---- a/mm/workingset.c -+++ b/mm/workingset.c -@@ -188,6 +188,12 @@ - #define EVICTION_SHIFT_ANON (EVICTION_SHIFT + SWAP_COUNT_SHIFT) - #define EVICTION_MASK (~0UL >> EVICTION_SHIFT) - #define EVICTION_MASK_ANON (~0UL >> EVICTION_SHIFT_ANON) -+/* -+ * LRU refs uses LRU_REFS_WIDTH + 2 bits, the 2 bits being PG_workingset -+ * and PG_referenced. The lowest bit is recorded in the workingset field -+ * of the shadow entry (to reuse pack_shadow()). -+ */ -+#define LRU_REFS_BITS ((LRU_REFS_WIDTH + 2) - 1) - - /* - * Eviction timestamps need to be able to cover the full range of -@@ -242,13 +248,12 @@ static void *lru_gen_eviction(struct folio *folio) - int type = folio_is_file_lru(folio); - int delta = folio_nr_pages(folio); - int refs = folio_lru_refs(folio); -- bool workingset = folio_test_workingset(folio); -- int tier = lru_tier_from_refs(refs, workingset); -+ int tier = lru_tier_from_refs(refs); - struct mem_cgroup *memcg; - struct pglist_data *pgdat = folio_pgdat(folio); - unsigned short memcg_id; - -- BUILD_BUG_ON(LRU_GEN_WIDTH + LRU_REFS_WIDTH > -+ BUILD_BUG_ON(LRU_GEN_WIDTH + LRU_REFS_BITS > - BITS_PER_LONG - max(EVICTION_SHIFT, EVICTION_SHIFT_ANON)); - - rcu_read_lock(); -@@ -256,14 +261,14 @@ static void *lru_gen_eviction(struct folio *folio) - lruvec = mem_cgroup_lruvec(memcg, pgdat); - lrugen = &lruvec->lrugen; - min_seq = READ_ONCE(lrugen->min_seq[type]); -- token = (min_seq << LRU_REFS_WIDTH) | max(refs - 1, 0); -+ token = (min_seq << LRU_REFS_BITS) | refs >> 1; - - hist = lru_hist_from_seq(min_seq); - atomic_long_add(delta, &lrugen->evicted[hist][type][tier]); - memcg_id = mem_cgroup_private_id(memcg); - rcu_read_unlock(); - -- return pack_shadow(memcg_id, pgdat, token, workingset, type); -+ return pack_shadow(memcg_id, pgdat, token, refs & 1, type); - } - - /* -@@ -284,9 +289,9 @@ static bool lru_gen_test_recent(void *shadow, struct lruvec **lruvec, - *lruvec = mem_cgroup_lruvec(memcg, pgdat); - - max_seq = READ_ONCE((*lruvec)->lrugen.max_seq); -- max_seq &= (file ? EVICTION_MASK : EVICTION_MASK_ANON) >> LRU_REFS_WIDTH; -+ max_seq &= (file ? EVICTION_MASK : EVICTION_MASK_ANON) >> LRU_REFS_BITS; - -- return abs_diff(max_seq, *token >> LRU_REFS_WIDTH) < MAX_NR_GENS; -+ return abs_diff(max_seq, *token >> LRU_REFS_BITS) < MAX_NR_GENS; - } - - static void lru_gen_refault(struct folio *folio, void *shadow) -@@ -314,22 +319,26 @@ static void lru_gen_refault(struct folio *folio, void *shadow) - lrugen = &lruvec->lrugen; - - hist = lru_hist_from_seq(READ_ONCE(lrugen->min_seq[type])); -- refs = (token & (BIT(LRU_REFS_WIDTH) - 1)) + 1; -- tier = lru_tier_from_refs(refs, workingset); -+ refs = ((token & (BIT(LRU_REFS_BITS) - 1)) << 1) + workingset; -+ tier = lru_tier_from_refs(refs); - - atomic_long_add(delta, &lrugen->refaulted[hist][type][tier]); - -- if (workingset) { -- /* -- * see folio_add_lru(), where folio_set_active() is -- * called for workingset folios -- */ -- if (lru_gen_in_fault()) -+ /* -+ * Activate a fault-driven refault folio, which would have been -+ * promoted had it stayed in memory. -+ */ -+ if (refs >= LRU_REFS_REFERENCED) { -+ if (lru_gen_in_fault()) { -+ folio_set_active(folio); - mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta); -- folio_set_workingset(folio); -+ } -+ /* Refault is also promotion, cap the refs like folio_inc_lru_refs */ -+ __folio_set_lru_refs(folio, min(refs, LRU_REFS_PROTECTED)); -+ } -+ -+ if (refs >= LRU_REFS_WORKINGSET) - mod_lruvec_state(lruvec, WORKINGSET_RESTORE_BASE + type, delta); -- } else -- set_mask_bits(&folio->flags.f, LRU_REFS_MASK, (refs - 1UL) << LRU_REFS_PGOFF); - unlock: - rcu_read_unlock(); - } -diff --git a/mm/zswap.c b/mm/zswap.c -index e6e6377..9354ca1 100644 ---- a/mm/zswap.c -+++ b/mm/zswap.c -@@ -136,14 +136,25 @@ bool zswap_never_enabled(void) - * data structures - **********************************/ - --struct crypto_acomp_ctx { -- struct crypto_acomp *acomp; -+struct zswap_acomp_req { - struct acomp_req *req; - struct crypto_wait wait; -- u8 *buffer; - struct mutex mutex; - }; - -+/* The compression mutex also protects the output buffer. */ -+struct zswap_comp_ctx { -+ struct zswap_acomp_req areq; -+ u8 *buffer; -+}; -+ -+/* Separate requests, so that decompression does not wait for compression. */ -+struct crypto_acomp_ctx { -+ struct crypto_acomp *acomp; -+ struct zswap_comp_ctx comp; -+ struct zswap_acomp_req decomp; /* unused with on-stack requests */ -+}; -+ - /* - * The lock ordering is zswap_tree.lock -> zswap_pool.lru_lock. - * The only case where lru_lock is not acquired while holding tree.lock is -@@ -247,14 +258,10 @@ static void acomp_ctx_free(struct crypto_acomp_ctx *acomp_ctx) - if (!acomp_ctx) - return; - -- /* -- * If there was an error in allocating @acomp_ctx->req, it -- * would be set to NULL. -- */ -- if (acomp_ctx->req) -- acomp_request_free(acomp_ctx->req); -- -- acomp_ctx->req = NULL; -+ acomp_request_free(acomp_ctx->comp.areq.req); -+ acomp_ctx->comp.areq.req = NULL; -+ acomp_request_free(acomp_ctx->decomp.req); -+ acomp_ctx->decomp.req = NULL; - - /* - * We have to handle both cases here: an error pointer return from -@@ -266,8 +273,8 @@ static void acomp_ctx_free(struct crypto_acomp_ctx *acomp_ctx) - - acomp_ctx->acomp = NULL; - -- kfree(acomp_ctx->buffer); -- acomp_ctx->buffer = NULL; -+ kfree(acomp_ctx->comp.buffer); -+ acomp_ctx->comp.buffer = NULL; - } - - static struct zswap_pool *zswap_pool_create(char *compressor) -@@ -782,6 +789,33 @@ static void zswap_entry_free(struct zswap_entry *entry) - /********************************* - * compressed storage functions - **********************************/ -+static void zswap_set_acomp_req_callback(struct acomp_req *req, -+ struct crypto_wait *wait) -+{ -+ /* -+ * if the backend of acomp is async zip, crypto_req_done() will wakeup -+ * crypto_wait_req(); if the backend of acomp is scomp, the callback -+ * won't be called, crypto_wait_req() will return without blocking. -+ */ -+ acomp_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG, -+ crypto_req_done, wait); -+} -+ -+static int zswap_acomp_req_init(struct zswap_acomp_req *areq, -+ struct crypto_acomp *acomp) -+{ -+ /* acomp_request_alloc() returns NULL in case of an error. */ -+ areq->req = acomp_request_alloc(acomp); -+ if (!areq->req) -+ return -ENOMEM; -+ -+ crypto_init_wait(&areq->wait); -+ zswap_set_acomp_req_callback(areq->req, &areq->wait); -+ -+ mutex_init(&areq->mutex); -+ return 0; -+} -+ - static int zswap_cpu_comp_prepare(unsigned int cpu, struct hlist_node *node) - { - struct zswap_pool *pool = hlist_entry(node, struct zswap_pool, node); -@@ -797,8 +831,8 @@ static int zswap_cpu_comp_prepare(unsigned int cpu, struct hlist_node *node) - return 0; - } - -- acomp_ctx->buffer = kmalloc_node(PAGE_SIZE, GFP_KERNEL, cpu_to_node(cpu)); -- if (!acomp_ctx->buffer) -+ acomp_ctx->comp.buffer = kmalloc_node(PAGE_SIZE, GFP_KERNEL, cpu_to_node(cpu)); -+ if (!acomp_ctx->comp.buffer) - return ret; - - /* -@@ -813,27 +847,21 @@ static int zswap_cpu_comp_prepare(unsigned int cpu, struct hlist_node *node) - goto fail; - } - -- /* acomp_request_alloc() returns NULL in case of an error. */ -- acomp_ctx->req = acomp_request_alloc(acomp_ctx->acomp); -- if (!acomp_ctx->req) { -- pr_err("could not alloc crypto acomp_request %s\n", -- pool->tfm_name); -- goto fail; -- } -- -- crypto_init_wait(&acomp_ctx->wait); -+ ret = zswap_acomp_req_init(&acomp_ctx->comp.areq, acomp_ctx->acomp); -+ if (ret) -+ goto req_fail; - -- /* -- * if the backend of acomp is async zip, crypto_req_done() will wakeup -- * crypto_wait_req(); if the backend of acomp is scomp, the callback -- * won't be called, crypto_wait_req() will return without blocking. -- */ -- acomp_request_set_callback(acomp_ctx->req, CRYPTO_TFM_REQ_MAY_BACKLOG, -- crypto_req_done, &acomp_ctx->wait); -+ /* Skip the per-CPU request when decompression can use the stack. */ -+ if (acomp_is_async(acomp_ctx->acomp)) { -+ ret = zswap_acomp_req_init(&acomp_ctx->decomp, acomp_ctx->acomp); -+ if (ret) -+ goto req_fail; -+ } - -- mutex_init(&acomp_ctx->mutex); - return 0; - -+req_fail: -+ pr_err("could not alloc crypto acomp_request %s\n", pool->tfm_name); - fail: - acomp_ctx_free(acomp_ctx); - return ret; -@@ -842,7 +870,7 @@ static int zswap_cpu_comp_prepare(unsigned int cpu, struct hlist_node *node) - static bool zswap_compress(struct page *page, struct zswap_entry *entry, - struct zswap_pool *pool) - { -- struct crypto_acomp_ctx *acomp_ctx; -+ struct zswap_comp_ctx *comp_ctx; - struct scatterlist input, output; - int comp_ret = 0, alloc_ret = 0; - unsigned int dlen = PAGE_SIZE; -@@ -851,15 +879,16 @@ static bool zswap_compress(struct page *page, struct zswap_entry *entry, - u8 *dst; - bool mapped = false; - -- acomp_ctx = raw_cpu_ptr(pool->acomp_ctx); -- mutex_lock(&acomp_ctx->mutex); -+ comp_ctx = &raw_cpu_ptr(pool->acomp_ctx)->comp; -+ mutex_lock(&comp_ctx->areq.mutex); - -- dst = acomp_ctx->buffer; -+ dst = comp_ctx->buffer; - sg_init_table(&input, 1); - sg_set_page(&input, page, PAGE_SIZE, 0); - - sg_init_one(&output, dst, PAGE_SIZE); -- acomp_request_set_params(acomp_ctx->req, &input, &output, PAGE_SIZE, dlen); -+ acomp_request_set_params(comp_ctx->areq.req, &input, &output, -+ PAGE_SIZE, dlen); - - /* - * it maybe looks a little bit silly that we send an asynchronous request, -@@ -871,10 +900,12 @@ static bool zswap_compress(struct page *page, struct zswap_entry *entry, - * existing method to send the second page before the first page is done - * in one thread doing zswap. - * but in different threads running on different cpu, we have different -- * acomp instance, so multiple threads can do (de)compression in parallel. -+ * acomp instance, and compression and decompression use separate -+ * requests, so multiple threads can do (de)compression in parallel. - */ -- comp_ret = crypto_wait_req(crypto_acomp_compress(acomp_ctx->req), &acomp_ctx->wait); -- dlen = acomp_ctx->req->dlen; -+ comp_ret = crypto_wait_req(crypto_acomp_compress(comp_ctx->areq.req), -+ &comp_ctx->areq.wait); -+ dlen = comp_ctx->areq.req->dlen; - - /* - * If a page cannot be compressed into a size smaller than PAGE_SIZE, -@@ -919,20 +950,18 @@ static bool zswap_compress(struct page *page, struct zswap_entry *entry, - else if (alloc_ret) - zswap_reject_alloc_fail++; - -- mutex_unlock(&acomp_ctx->mutex); -+ mutex_unlock(&comp_ctx->areq.mutex); - return comp_ret == 0 && alloc_ret == 0; - } - --static bool zswap_decompress(struct zswap_entry *entry, struct folio *folio) -+static bool __zswap_decompress(struct zswap_entry *entry, -+ struct zswap_pool *pool, struct acomp_req *req, -+ struct crypto_wait *wait, struct folio *folio) - { -- struct zswap_pool *pool = entry->pool; - struct scatterlist input[2]; /* zsmalloc returns an SG list 1-2 entries */ - struct scatterlist output; -- struct crypto_acomp_ctx *acomp_ctx; - int ret = 0, dlen; - -- acomp_ctx = raw_cpu_ptr(pool->acomp_ctx); -- mutex_lock(&acomp_ctx->mutex); - zs_obj_read_sg_begin(pool->zs_pool, entry->handle, input, entry->length); - - /* zswap entries of length PAGE_SIZE are not compressed. */ -@@ -949,15 +978,13 @@ static bool zswap_decompress(struct zswap_entry *entry, struct folio *folio) - } else { - sg_init_table(&output, 1); - sg_set_folio(&output, folio, PAGE_SIZE, 0); -- acomp_request_set_params(acomp_ctx->req, input, &output, -- entry->length, PAGE_SIZE); -- ret = crypto_acomp_decompress(acomp_ctx->req); -- ret = crypto_wait_req(ret, &acomp_ctx->wait); -- dlen = acomp_ctx->req->dlen; -+ acomp_request_set_params(req, input, &output, entry->length, PAGE_SIZE); -+ ret = crypto_acomp_decompress(req); -+ ret = crypto_wait_req(ret, wait); -+ dlen = req->dlen; - } - - zs_obj_read_sg_end(pool->zs_pool, entry->handle); -- mutex_unlock(&acomp_ctx->mutex); - - if (!ret && dlen == PAGE_SIZE) - return true; -@@ -971,6 +998,32 @@ static bool zswap_decompress(struct zswap_entry *entry, struct folio *folio) - return false; - } - -+static bool zswap_decompress(struct zswap_entry *entry, struct folio *folio) -+{ -+ struct zswap_pool *pool = entry->pool; -+ struct crypto_acomp_ctx *acomp_ctx; -+ bool ret; -+ -+ acomp_ctx = raw_cpu_ptr(pool->acomp_ctx); -+ /* -+ * Use a private on-stack request when the transform supports it. -+ * Otherwise serialize decompression on the shared per-CPU request. -+ */ -+ if (!acomp_ctx->decomp.req) { -+ ACOMP_REQUEST_ON_STACK(req, acomp_ctx->acomp); -+ DECLARE_CRYPTO_WAIT(wait); -+ -+ zswap_set_acomp_req_callback(req, &wait); -+ return __zswap_decompress(entry, pool, req, &wait, folio); -+ } -+ -+ mutex_lock(&acomp_ctx->decomp.mutex); -+ ret = __zswap_decompress(entry, pool, acomp_ctx->decomp.req, -+ &acomp_ctx->decomp.wait, folio); -+ mutex_unlock(&acomp_ctx->decomp.mutex); -+ return ret; -+} -+ - /********************************* - * writeback code - **********************************/ -diff --git a/net/ipv4/Kconfig b/net/ipv4/Kconfig -index 301b476..b7476c5 100644 ---- a/net/ipv4/Kconfig -+++ b/net/ipv4/Kconfig -@@ -668,15 +668,33 @@ config TCP_CONG_BBR - default n - help - -- BBR (Bottleneck Bandwidth and RTT) TCP congestion control aims to -- maximize network utilization and minimize queues. It builds an explicit -- model of the bottleneck delivery rate and path round-trip propagation -- delay. It tolerates packet loss and delay unrelated to congestion. It -- can operate over LAN, WAN, cellular, wifi, or cable modem links. It can -- coexist with flows that use loss-based congestion control, and can -- operate with shallow buffers, deep buffers, bufferbloat, policers, or -- AQM schemes that do not provide a delay signal. It requires the fq -- ("Fair Queue") pacing packet scheduler. -+ BBR (Bottleneck Bandwidth and RTT) TCP congestion control aims to -+ maximize network utilization and minimize queues. It builds an explicit -+ model of the bottleneck delivery rate and path round-trip propagation -+ delay. It tolerates packet loss and delay unrelated to congestion. It -+ can operate over LAN, WAN, cellular, wifi, or cable modem links. It can -+ coexist with flows that use loss-based congestion control, and can -+ operate with shallow buffers, deep buffers, bufferbloat, policers, or -+ AQM schemes that do not provide a delay signal. It requires the fq -+ ("Fair Queue") pacing packet scheduler. -+ -+config TCP_CONG_BBR3 -+ tristate "BBR3 TCP" -+ default n -+ help -+ -+ BBR (Bottleneck Bandwidth and RTT) TCP congestion control is a -+ model-based congestion control algorithm that aims to maximize -+ network utilization, keep queues and retransmit rates low, and to be -+ able to coexist with Reno/CUBIC in common scenarios. It builds an -+ explicit model of the network path. It tolerates a targeted degree -+ of random packet loss and delay. It can operate over LAN, WAN, -+ cellular, wifi, or cable modem links, and can use shallow-threshold -+ ECN signals. It can coexist to some degree with flows that use -+ loss-based congestion control, and can operate with shallow buffers, -+ deep buffers, bufferbloat, policers, or AQM schemes that do not -+ provide a delay signal. It requires pacing, using either TCP internal -+ pacing or the fq ("Fair Queue") pacing packet scheduler. - - choice - prompt "Default TCP congestion control" -@@ -715,6 +733,9 @@ choice - config DEFAULT_BBR - bool "BBR" if TCP_CONG_BBR=y - -+ config DEFAULT_BBR3 -+ bool "BBR3" if TCP_CONG_BBR3=y -+ - config DEFAULT_RENO - bool "Reno" - endchoice -@@ -739,6 +760,7 @@ config DEFAULT_TCP_CONG - default "dctcp" if DEFAULT_DCTCP - default "cdg" if DEFAULT_CDG - default "bbr" if DEFAULT_BBR -+ default "bbr3" if DEFAULT_BBR3 - default "cubic" - - config TCP_AO -diff --git a/net/ipv4/Makefile b/net/ipv4/Makefile -index 06e21c2..2159821 100644 ---- a/net/ipv4/Makefile -+++ b/net/ipv4/Makefile -@@ -45,6 +45,7 @@ obj-$(CONFIG_INET_TCP_DIAG) += tcp_diag.o - obj-$(CONFIG_INET_UDP_DIAG) += udp_diag.o - obj-$(CONFIG_INET_RAW_DIAG) += raw_diag.o - obj-$(CONFIG_TCP_CONG_BBR) += tcp_bbr.o -+obj-$(CONFIG_TCP_CONG_BBR3) += tcp_bbr3.o - obj-$(CONFIG_TCP_CONG_BIC) += tcp_bic.o - obj-$(CONFIG_TCP_CONG_CDG) += tcp_cdg.o - obj-$(CONFIG_TCP_CONG_CUBIC) += tcp_cubic.o -diff --git a/net/ipv4/bpf_tcp_ca.c b/net/ipv4/bpf_tcp_ca.c -index 791e150..4f2c7bc 100644 ---- a/net/ipv4/bpf_tcp_ca.c -+++ b/net/ipv4/bpf_tcp_ca.c -@@ -284,7 +284,7 @@ static void bpf_tcp_ca_pkts_acked(struct sock *sk, const struct ack_sample *samp - { - } - --static u32 bpf_tcp_ca_min_tso_segs(struct sock *sk) -+static u32 bpf_tcp_ca_tso_segs(struct sock *sk, unsigned int mss_now) - { - return 0; - } -@@ -320,7 +320,7 @@ static struct tcp_congestion_ops __bpf_ops_tcp_congestion_ops = { - .cwnd_event_tx_start = bpf_tcp_ca_cwnd_event_tx_start, - .in_ack_event = bpf_tcp_ca_in_ack_event, - .pkts_acked = bpf_tcp_ca_pkts_acked, -- .min_tso_segs = bpf_tcp_ca_min_tso_segs, -+ .tso_segs = bpf_tcp_ca_tso_segs, - .cong_control = bpf_tcp_ca_cong_control, - .undo_cwnd = bpf_tcp_ca_undo_cwnd, - .sndbuf_expand = bpf_tcp_ca_sndbuf_expand, -diff --git a/net/ipv4/tcp.c b/net/ipv4/tcp.c -index 87ef6d5..67e951b 100644 ---- a/net/ipv4/tcp.c -+++ b/net/ipv4/tcp.c -@@ -3484,6 +3484,7 @@ int tcp_disconnect(struct sock *sk, int flags) - tp->rx_opt.dsack = 0; - tp->rx_opt.num_sacks = 0; - tp->rcv_ooopack = 0; -+ tp->fast_ack_mode = 0; - - - /* Clean up fastopen related fields */ -@@ -4269,6 +4270,8 @@ void tcp_get_info(struct sock *sk, struct tcp_info *info) - info->tcpi_options |= TCPI_OPT_ECN; - if (tp->ecn_flags & TCP_ECN_SEEN) - info->tcpi_options |= TCPI_OPT_ECN_SEEN; -+ if (tp->ecn_flags & TCP_ECN_LOW) -+ info->tcpi_options |= TCPI_OPT_ECN_LOW; - if (tp->syn_data_acked) - info->tcpi_options |= TCPI_OPT_SYN_DATA; - if (tp->tcp_usec_ts) -diff --git a/net/ipv4/tcp_bbr.c b/net/ipv4/tcp_bbr.c -index 82378a2..2ab73e5 100644 ---- a/net/ipv4/tcp_bbr.c -+++ b/net/ipv4/tcp_bbr.c -@@ -302,6 +302,23 @@ __bpf_kfunc static u32 bbr_min_tso_segs(struct sock *sk) - return READ_ONCE(sk->sk_pacing_rate) < (bbr_min_tso_rate >> 3) ? 1 : 2; - } - -+__bpf_kfunc static u32 bbr_tso_segs(struct sock *sk, unsigned int mss_now) -+{ -+ unsigned long bytes; -+ u32 r; -+ -+ bytes = READ_ONCE(sk->sk_pacing_rate) >> READ_ONCE(sk->sk_pacing_shift); -+ -+ r = tcp_min_rtt(tcp_sk(sk)) >> -+ READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_tso_rtt_log); -+ if (r < BITS_PER_TYPE(sk->sk_gso_max_size)) -+ bytes += sk->sk_gso_max_size >> r; -+ -+ bytes = min_t(unsigned long, bytes, sk->sk_gso_max_size); -+ -+ return max_t(u32, bytes / mss_now, bbr_min_tso_segs(sk)); -+} -+ - static u32 bbr_tso_segs_goal(struct sock *sk) - { - struct tcp_sock *tp = tcp_sk(sk); -@@ -1151,7 +1168,7 @@ static struct tcp_congestion_ops tcp_bbr_cong_ops __read_mostly = { - .undo_cwnd = bbr_undo_cwnd, - .cwnd_event_tx_start = bbr_cwnd_event_tx_start, - .ssthresh = bbr_ssthresh, -- .min_tso_segs = bbr_min_tso_segs, -+ .tso_segs = bbr_tso_segs, - .get_info = bbr_get_info, - .set_state = bbr_set_state, - }; -diff --git a/net/ipv4/tcp_bbr3.c b/net/ipv4/tcp_bbr3.c -new file mode 100644 -index 0000000..0697a9c ---- /dev/null -+++ b/net/ipv4/tcp_bbr3.c -@@ -0,0 +1,2418 @@ -+// SPDX-License-Identifier: GPL-2.0 -+/* BBR (Bottleneck Bandwidth and RTT) congestion control -+ * -+ * BBR is a model-based congestion control algorithm that aims for low queues, -+ * low loss, and (bounded) Reno/CUBIC coexistence. To maintain a model of the -+ * network path, it uses measurements of bandwidth and RTT, as well as (if they -+ * occur) packet loss and/or shallow-threshold ECN signals. Note that although -+ * it can use ECN or loss signals explicitly, it does not require either; it -+ * can bound its in-flight data based on its estimate of the BDP. -+ * -+ * The model has both higher and lower bounds for the operating range: -+ * lo: bw_lo, inflight_lo: conservative short-term lower bound -+ * hi: bw_hi, inflight_hi: robust long-term upper bound -+ * The bandwidth-probing time scale is (a) extended dynamically based on -+ * estimated BDP to improve coexistence with Reno/CUBIC; (b) bounded by -+ * an interactive wall-clock time-scale to be more scalable and responsive -+ * than Reno and CUBIC. -+ * -+ * Here is a state transition diagram for BBR: -+ * -+ * | -+ * V -+ * +---> STARTUP ----+ -+ * | | | -+ * | V | -+ * | DRAIN ----+ -+ * | | | -+ * | V | -+ * +---> PROBE_BW ----+ -+ * | ^ | | -+ * | | | | -+ * | +----+ | -+ * | | -+ * +---- PROBE_RTT <--+ -+ * -+ * A BBR flow starts in STARTUP, and ramps up its sending rate quickly. -+ * When it estimates the pipe is full, it enters DRAIN to drain the queue. -+ * In steady state a BBR flow only uses PROBE_BW and PROBE_RTT. -+ * A long-lived BBR flow spends the vast majority of its time remaining -+ * (repeatedly) in PROBE_BW, fully probing and utilizing the pipe's bandwidth -+ * in a fair manner, with a small, bounded queue. *If* a flow has been -+ * continuously sending for the entire min_rtt window, and hasn't seen an RTT -+ * sample that matches or decreases its min_rtt estimate for 10 seconds, then -+ * it briefly enters PROBE_RTT to cut inflight to a minimum value to re-probe -+ * the path's two-way propagation delay (min_rtt). When exiting PROBE_RTT, if -+ * we estimated that we reached the full bw of the pipe then we enter PROBE_BW; -+ * otherwise we enter STARTUP to try to fill the pipe. -+ * -+ * BBR is described in detail in: -+ * "BBR: Congestion-Based Congestion Control", -+ * Neal Cardwell, Yuchung Cheng, C. Stephen Gunn, Soheil Hassas Yeganeh, -+ * Van Jacobson. ACM Queue, Vol. 14 No. 5, September-October 2016. -+ * -+ * There is a public e-mail list for discussing BBR development and testing: -+ * https://groups.google.com/forum/#!forum/bbr-dev -+ * -+ * NOTE: BBR might be used with the fq qdisc ("man tc-fq") with pacing enabled, -+ * otherwise TCP stack falls back to an internal pacing using one high -+ * resolution timer per TCP socket and may use more resources. -+ */ -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+ -+#include -+#include "tcp_dctcp.h" -+ -+#define BBR_VERSION 3 -+ -+#define bbr_param(sk,name) (bbr_ ## name) -+ -+/* Scale factor for rate in pkt/uSec unit to avoid truncation in bandwidth -+ * estimation. The rate unit ~= (1500 bytes / 1 usec / 2^24) ~= 715 bps. -+ * This handles bandwidths from 0.06pps (715bps) to 256Mpps (3Tbps) in a u32. -+ * Since the minimum window is >=4 packets, the lower bound isn't -+ * an issue. The upper bound isn't an issue with existing technologies. -+ */ -+#define BW_SCALE 24 -+#define BW_UNIT (1 << BW_SCALE) -+ -+#define BBR_SCALE 8 /* scaling factor for fractions in BBR (e.g. gains) */ -+#define BBR_UNIT (1 << BBR_SCALE) -+ -+/* BBR has the following modes for deciding how fast to send: */ -+enum bbr_mode { -+ BBR_STARTUP, /* ramp up sending rate rapidly to fill pipe */ -+ BBR_DRAIN, /* drain any queue created during startup */ -+ BBR_PROBE_BW, /* discover, share bw: pace around estimated bw */ -+ BBR_PROBE_RTT, /* cut inflight to min to probe min_rtt */ -+}; -+ -+/* How does the incoming ACK stream relate to our bandwidth probing? */ -+enum bbr_ack_phase { -+ BBR_ACKS_INIT, /* not probing; not getting probe feedback */ -+ BBR_ACKS_REFILLING, /* sending at est. bw to fill pipe */ -+ BBR_ACKS_PROBE_STARTING, /* inflight rising to probe bw */ -+ BBR_ACKS_PROBE_FEEDBACK, /* getting feedback from bw probing */ -+ BBR_ACKS_PROBE_STOPPING, /* stopped probing; still getting feedback */ -+}; -+ -+/* BBR congestion control block */ -+struct bbr { -+ u32 min_rtt_us; /* min RTT in min_rtt_win_sec window */ -+ u32 min_rtt_stamp; /* timestamp of min_rtt_us */ -+ u32 probe_rtt_done_stamp; /* end time for BBR_PROBE_RTT mode */ -+ u32 probe_rtt_min_us; /* min RTT in probe_rtt_win_ms win */ -+ u32 probe_rtt_min_stamp; /* timestamp of probe_rtt_min_us*/ -+ u32 next_rtt_delivered; /* scb->tx.delivered at end of round */ -+ u64 cycle_mstamp; /* time of this cycle phase start */ -+ u32 mode:2, /* current bbr_mode in state machine */ -+ prev_ca_state:3, /* CA state on previous ACK */ -+ round_start:1, /* start of packet-timed tx->ack round? */ -+ ce_state:1, /* If most recent data has CE bit set */ -+ bw_probe_up_rounds:5, /* cwnd-limited rounds in PROBE_UP */ -+ try_fast_path:1, /* can we take fast path? */ -+ idle_restart:1, /* restarting after idle? */ -+ probe_rtt_round_done:1, /* a BBR_PROBE_RTT round at 4 pkts? */ -+ init_cwnd:7, /* initial cwnd */ -+ unused_1:10; -+ u32 pacing_gain:10, /* current gain for setting pacing rate */ -+ cwnd_gain:10, /* current gain for setting cwnd */ -+ full_bw_reached:1, /* reached full bw in Startup? */ -+ full_bw_cnt:2, /* number of rounds without large bw gains */ -+ cycle_idx:2, /* current index in pacing_gain cycle array */ -+ has_seen_rtt:1, /* have we seen an RTT sample yet? */ -+ unused_2:6; -+ u32 prior_cwnd; /* prior cwnd upon entering loss recovery */ -+ u32 full_bw; /* recent bw, to estimate if pipe is full */ -+ -+ /* For tracking ACK aggregation: */ -+ u64 ack_epoch_mstamp; /* start of ACK sampling epoch */ -+ u16 extra_acked[2]; /* max excess data ACKed in epoch */ -+ u32 ack_epoch_acked:20, /* packets (S)ACKed in sampling epoch */ -+ extra_acked_win_rtts:5, /* age of extra_acked, in round trips */ -+ extra_acked_win_idx:1, /* current index in extra_acked array */ -+ /* BBR v3 state: */ -+ full_bw_now:1, /* recently reached full bw plateau? */ -+ startup_ecn_rounds:2, /* consecutive hi ECN STARTUP rounds */ -+ loss_in_cycle:1, /* packet loss in this cycle? */ -+ ecn_in_cycle:1, /* ECN in this cycle? */ -+ unused_3:1; -+ u32 loss_round_delivered; /* scb->tx.delivered ending loss round */ -+ u32 undo_bw_lo; /* bw_lo before latest losses */ -+ u32 undo_inflight_lo; /* inflight_lo before latest losses */ -+ u32 undo_inflight_hi; /* inflight_hi before latest losses */ -+ u32 bw_latest; /* max delivered bw in last round trip */ -+ u32 bw_lo; /* lower bound on sending bandwidth */ -+ u32 bw_hi[2]; /* max recent measured bw sample */ -+ u32 inflight_latest; /* max delivered data in last round trip */ -+ u32 inflight_lo; /* lower bound of inflight data range */ -+ u32 inflight_hi; /* upper bound of inflight data range */ -+ u32 bw_probe_up_cnt; /* packets delivered per inflight_hi incr */ -+ u32 bw_probe_up_acks; /* packets (S)ACKed since inflight_hi incr */ -+ u32 probe_wait_us; /* PROBE_DOWN until next clock-driven probe */ -+ u32 prior_rcv_nxt; /* tp->rcv_nxt when CE state last changed */ -+ u32 ecn_eligible:1, /* sender can use ECN (RTT, handshake)? */ -+ ecn_alpha:9, /* EWMA delivered_ce/delivered; 0..256 */ -+ bw_probe_samples:1, /* rate samples reflect bw probing? */ -+ prev_probe_too_high:1, /* did last PROBE_UP go too high? */ -+ stopped_risky_probe:1, /* last PROBE_UP stopped due to risk? */ -+ rounds_since_probe:8, /* packet-timed rounds since probed bw */ -+ loss_round_start:1, /* loss_round_delivered round trip? */ -+ loss_in_round:1, /* loss marked in this round trip? */ -+ ecn_in_round:1, /* ECN marked in this round trip? */ -+ ack_phase:3, /* bbr_ack_phase: meaning of ACKs */ -+ loss_events_in_round:4,/* losses in STARTUP round */ -+ initialized:1; /* has bbr_init() been called? */ -+ u32 alpha_last_delivered; /* tp->delivered at alpha update */ -+ u32 alpha_last_delivered_ce; /* tp->delivered_ce at alpha update */ -+ -+ u8 unused_4; /* to preserve alignment */ -+ struct tcp_plb_state plb; -+}; -+ -+struct bbr_context { -+ u32 sample_bw; -+}; -+ -+/* Window length of min_rtt filter (in sec): */ -+static const u32 bbr_min_rtt_win_sec = 10; -+/* Minimum time (in ms) spent at bbr_cwnd_min_target in BBR_PROBE_RTT mode: */ -+static const u32 bbr_probe_rtt_mode_ms = 200; -+/* Window length of probe_rtt_min_us filter (in ms), and consequently the -+ * typical interval between PROBE_RTT mode entries. The default is 5000ms. -+ * Note that bbr_probe_rtt_win_ms must be <= bbr_min_rtt_win_sec * MSEC_PER_SEC -+ */ -+static const u32 bbr_probe_rtt_win_ms = 5000; -+/* Proportion of cwnd to estimated BDP in PROBE_RTT, in units of BBR_UNIT: */ -+static const u32 bbr_probe_rtt_cwnd_gain = BBR_UNIT * 1 / 2; -+ -+/* Use min_rtt to help adapt TSO burst size, with smaller min_rtt resulting -+ * in bigger TSO bursts. We cut the RTT-based allowance in half -+ * for every 2^9 usec (aka 512 us) of RTT, so that the RTT-based allowance -+ * is below 1500 bytes after 6 * ~500 usec = 3ms. -+ */ -+static const u32 bbr_tso_rtt_shift = 9; -+ -+/* Pace at ~1% below estimated bw, on average, to reduce queue at bottleneck. -+ * In order to help drive the network toward lower queues and low latency while -+ * maintaining high utilization, the average pacing rate aims to be slightly -+ * lower than the estimated bandwidth. This is an important aspect of the -+ * design. -+ */ -+static const int bbr_pacing_margin_percent = 1; -+ -+/* We use a startup_pacing_gain of 4*ln(2) because it's the smallest value -+ * that will allow a smoothly increasing pacing rate that will double each RTT -+ * and send the same number of packets per RTT that an un-paced, slow-starting -+ * Reno or CUBIC flow would: -+ */ -+static const int bbr_startup_pacing_gain = BBR_UNIT * 277 / 100 + 1; -+/* The gain for deriving startup cwnd: */ -+static const int bbr_startup_cwnd_gain = BBR_UNIT * 2; -+/* The pacing gain in BBR_DRAIN is calculated to typically drain -+ * the queue created in BBR_STARTUP in a single round: -+ */ -+static const int bbr_drain_gain = BBR_UNIT * 1000 / 2885; -+/* The gain for deriving steady-state cwnd tolerates delayed/stretched ACKs: */ -+static const int bbr_cwnd_gain = BBR_UNIT * 2; -+/* The pacing_gain values for the PROBE_BW gain cycle, to discover/share bw: */ -+static const int bbr_pacing_gain[] = { -+ BBR_UNIT * 5 / 4, /* UP: probe for more available bw */ -+ BBR_UNIT * 91 / 100, /* DOWN: drain queue and/or yield bw */ -+ BBR_UNIT, /* CRUISE: try to use pipe w/ some headroom */ -+ BBR_UNIT, /* REFILL: refill pipe to estimated 100% */ -+}; -+enum bbr_pacing_gain_phase { -+ BBR_BW_PROBE_UP = 0, /* push up inflight to probe for bw/vol */ -+ BBR_BW_PROBE_DOWN = 1, /* drain excess inflight from the queue */ -+ BBR_BW_PROBE_CRUISE = 2, /* use pipe, w/ headroom in queue/pipe */ -+ BBR_BW_PROBE_REFILL = 3, /* refill the pipe again to 100% */ -+}; -+ -+/* Try to keep at least this many packets in flight, if things go smoothly. For -+ * smooth functioning, a sliding window protocol ACKing every other packet -+ * needs at least 4 packets in flight: -+ */ -+static const u32 bbr_cwnd_min_target = 4; -+ -+/* To estimate if BBR_STARTUP or BBR_BW_PROBE_UP has filled pipe... */ -+/* If bw has increased significantly (1.25x), there may be more bw available: */ -+static const u32 bbr_full_bw_thresh = BBR_UNIT * 5 / 4; -+/* But after 3 rounds w/o significant bw growth, estimate pipe is full: */ -+static const u32 bbr_full_bw_cnt = 3; -+ -+/* Gain factor for adding extra_acked to target cwnd: */ -+static const int bbr_extra_acked_gain = BBR_UNIT; -+/* Window length of extra_acked window. */ -+static const u32 bbr_extra_acked_win_rtts = 5; -+/* Max allowed val for ack_epoch_acked, after which sampling epoch is reset */ -+static const u32 bbr_ack_epoch_acked_reset_thresh = 1U << 20; -+/* Time period for clamping cwnd increment due to ack aggregation */ -+static const u32 bbr_extra_acked_max_us = 100 * 1000; -+ -+/* Flags to control BBR ECN-related behavior... */ -+ -+/* Ensure ACKs only ACK packets with consistent ECN CE status? */ -+static const bool bbr_precise_ece_ack = true; -+ -+/* Max RTT (in usec) at which to use sender-side ECN logic. -+ * Disabled when 0 (ECN allowed at any RTT). -+ */ -+static const u32 bbr_ecn_max_rtt_us = 5000; -+ -+/* On losses, scale down inflight and pacing rate by beta scaled by BBR_SCALE. -+ * No loss response when 0. -+ */ -+static const u32 bbr_beta = BBR_UNIT * 30 / 100; -+ -+/* Gain factor for ECN mark ratio samples, scaled by BBR_SCALE (1/16 = 6.25%) */ -+static const u32 bbr_ecn_alpha_gain = BBR_UNIT * 1 / 16; -+ -+/* The initial value for ecn_alpha; 1.0 allows a flow to respond quickly -+ * to congestion if the bottleneck is congested when the flow starts up. -+ */ -+static const u32 bbr_ecn_alpha_init = BBR_UNIT; -+ -+/* On ECN, cut inflight_lo to (1 - ecn_factor * ecn_alpha) scaled by BBR_SCALE. -+ * No ECN based bounding when 0. -+ */ -+static const u32 bbr_ecn_factor = BBR_UNIT * 1 / 3; /* 1/3 = 33% */ -+ -+/* Estimate bw probing has gone too far if CE ratio exceeds this threshold. -+ * Scaled by BBR_SCALE. Disabled when 0. -+ */ -+static const u32 bbr_ecn_thresh = BBR_UNIT * 1 / 2; /* 1/2 = 50% */ -+ -+/* If non-zero, if in a cycle with no losses but some ECN marks, after ECN -+ * clears then make the first round's increment to inflight_hi the following -+ * fraction of inflight_hi. -+ */ -+static const u32 bbr_ecn_reprobe_gain = BBR_UNIT * 1 / 2; -+ -+/* Estimate bw probing has gone too far if loss rate exceeds this level. */ -+static const u32 bbr_loss_thresh = BBR_UNIT * 2 / 100; /* 2% loss */ -+ -+/* Slow down for a packet loss recovered by TLP? */ -+static const bool bbr_loss_probe_recovery = true; -+ -+/* Exit STARTUP if number of loss marking events in a Recovery round is >= N, -+ * and loss rate is higher than bbr_loss_thresh. -+ * Disabled if 0. -+ */ -+static const u32 bbr_full_loss_cnt = 6; -+ -+/* Exit STARTUP if number of round trips with ECN mark rate above ecn_thresh -+ * meets this count. -+ */ -+static const u32 bbr_full_ecn_cnt = 2; -+ -+/* Fraction of unutilized headroom to try to leave in path upon high loss. */ -+static const u32 bbr_inflight_headroom = BBR_UNIT * 15 / 100; -+ -+/* How much do we increase cwnd_gain when probing for bandwidth in -+ * BBR_BW_PROBE_UP? This specifies the increment in units of -+ * BBR_UNIT/4. The default is 1, meaning 0.25. -+ * The min value is 0 (meaning 0.0); max is 3 (meaning 0.75). -+ */ -+static const u32 bbr_bw_probe_cwnd_gain = 1; -+ -+/* Max number of packet-timed rounds to wait before probing for bandwidth. If -+ * we want to tolerate 1% random loss per round, and not have this cut our -+ * inflight too much, we must probe for bw periodically on roughly this scale. -+ * If low, limits Reno/CUBIC coexistence; if high, limits loss tolerance. -+ * We aim to be fair with Reno/CUBIC up to a BDP of at least: -+ * BDP = 25Mbps * .030sec /(1514bytes) = 61.9 packets -+ */ -+static const u32 bbr_bw_probe_max_rounds = 63; -+ -+/* Max amount of randomness to inject in round counting for Reno-coexistence. -+ */ -+static const u32 bbr_bw_probe_rand_rounds = 2; -+ -+/* Use BBR-native probe time scale starting at this many usec. -+ * We aim to be fair with Reno/CUBIC up to an inter-loss time epoch of at least: -+ * BDP*RTT = 25Mbps * .030sec /(1514bytes) * 0.030sec = 1.9 secs -+ */ -+static const u32 bbr_bw_probe_base_us = 2 * USEC_PER_SEC; /* 2 secs */ -+ -+/* Use BBR-native probes spread over this many usec: */ -+static const u32 bbr_bw_probe_rand_us = 1 * USEC_PER_SEC; /* 1 secs */ -+ -+/* Use fast path if app-limited, no loss/ECN, and target cwnd was reached? */ -+static const bool bbr_fast_path = true; -+ -+/* Use fast ack mode? */ -+static const bool bbr_fast_ack_mode = true; -+ -+static u32 bbr_max_bw(const struct sock *sk); -+static u32 bbr_bw(const struct sock *sk); -+static void bbr_exit_probe_rtt(struct sock *sk); -+static void bbr_reset_congestion_signals(struct sock *sk); -+static void bbr_run_loss_probe_recovery(struct sock *sk); -+ -+static void bbr_check_probe_rtt_done(struct sock *sk); -+ -+/* This connection can use ECN if both endpoints have signaled ECN support in -+ * the handshake and the per-route settings indicated this is a -+ * shallow-threshold ECN environment, meaning both: -+ * (a) ECN CE marks indicate low-latency/shallow-threshold congestion, and -+ * (b) TCP endpoints provide precise ACKs that only ACK data segments -+ * with consistent ECN CE status -+ */ -+static bool bbr_can_use_ecn(const struct sock *sk) -+{ -+ const struct tcp_sock *tp = tcp_sk(sk); -+ -+ return tcp_ecn_mode_any(tp) && -+ (tcp_sk(sk)->ecn_flags & TCP_ECN_LOW); -+} -+ -+/* Do we estimate that STARTUP filled the pipe? */ -+static bool bbr_full_bw_reached(const struct sock *sk) -+{ -+ const struct bbr *bbr = inet_csk_ca(sk); -+ -+ return bbr->full_bw_reached; -+} -+ -+/* Return the windowed max recent bandwidth sample, in pkts/uS << BW_SCALE. */ -+static u32 bbr_max_bw(const struct sock *sk) -+{ -+ const struct bbr *bbr = inet_csk_ca(sk); -+ -+ return max(bbr->bw_hi[0], bbr->bw_hi[1]); -+} -+ -+/* Return the estimated bandwidth of the path, in pkts/uS << BW_SCALE. */ -+static u32 bbr_bw(const struct sock *sk) -+{ -+ const struct bbr *bbr = inet_csk_ca(sk); -+ -+ return min(bbr_max_bw(sk), bbr->bw_lo); -+} -+ -+/* Return maximum extra acked in past k-2k round trips, -+ * where k = bbr_extra_acked_win_rtts. -+ */ -+static u16 bbr_extra_acked(const struct sock *sk) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ return max(bbr->extra_acked[0], bbr->extra_acked[1]); -+} -+ -+/* Return rate in bytes per second, optionally with a gain. -+ * The order here is chosen carefully to avoid overflow of u64. This should -+ * work for input rates of up to 2.9Tbit/sec and gain of 2.89x. -+ */ -+static u64 bbr_rate_bytes_per_sec(struct sock *sk, u64 rate, int gain, -+ int margin) -+{ -+ unsigned int mss = tcp_sk(sk)->mss_cache; -+ -+ rate *= mss; -+ rate *= gain; -+ rate >>= BBR_SCALE; -+ rate *= USEC_PER_SEC / 100 * (100 - margin); -+ rate >>= BW_SCALE; -+ rate = max(rate, 1ULL); -+ return rate; -+} -+ -+static u64 bbr_bw_bytes_per_sec(struct sock *sk, u64 rate) -+{ -+ return bbr_rate_bytes_per_sec(sk, rate, BBR_UNIT, 0); -+} -+ -+/* Convert a BBR bw and gain factor to a pacing rate in bytes per second. */ -+static unsigned long bbr_bw_to_pacing_rate(struct sock *sk, u32 bw, int gain) -+{ -+ u64 rate = bw; -+ -+ rate = bbr_rate_bytes_per_sec(sk, rate, gain, -+ bbr_pacing_margin_percent); -+ rate = min_t(u64, rate, READ_ONCE(sk->sk_max_pacing_rate)); -+ return rate; -+} -+ -+/* Initialize pacing rate to: startup_pacing_gain * init_cwnd / RTT. */ -+static void bbr_init_pacing_rate_from_rtt(struct sock *sk) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ u64 bw; -+ u32 rtt_us; -+ -+ if (tp->srtt_us) { /* any RTT sample yet? */ -+ rtt_us = max(tp->srtt_us >> 3, 1U); -+ bbr->has_seen_rtt = 1; -+ } else { /* no RTT sample yet */ -+ rtt_us = USEC_PER_MSEC; /* use nominal default RTT */ -+ } -+ bw = (u64)tcp_snd_cwnd(tp) * BW_UNIT; -+ do_div(bw, rtt_us); -+ WRITE_ONCE(sk->sk_pacing_rate, -+ bbr_bw_to_pacing_rate(sk, bw, -+ bbr_param(sk, startup_pacing_gain))); -+} -+ -+/* Pace using current bw estimate and a gain factor. */ -+static void bbr_set_pacing_rate(struct sock *sk, u32 bw, int gain) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ unsigned long rate = bbr_bw_to_pacing_rate(sk, bw, gain); -+ -+ if (unlikely(!bbr->has_seen_rtt && tp->srtt_us)) -+ bbr_init_pacing_rate_from_rtt(sk); -+ if (bbr_full_bw_reached(sk) || rate > READ_ONCE(sk->sk_pacing_rate)) -+ WRITE_ONCE(sk->sk_pacing_rate, rate); -+} -+ -+/* Return the number of segments BBR would like in a TSO/GSO skb, given a -+ * particular max gso size as a constraint. TODO: make this simpler and more -+ * consistent by switching bbr to just call tcp_tso_autosize(). -+ */ -+static u32 bbr_tso_segs_generic(struct sock *sk, unsigned int mss_now, -+ u32 gso_max_size) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ u32 segs, r; -+ u64 bytes; -+ -+ /* Budget a TSO/GSO burst size allowance based on bw (pacing_rate). */ -+ bytes = READ_ONCE(sk->sk_pacing_rate) >> READ_ONCE(sk->sk_pacing_shift); -+ -+ /* Budget a TSO/GSO burst size allowance based on min_rtt. For every -+ * K = 2^tso_rtt_shift microseconds of min_rtt, halve the burst. -+ * The min_rtt-based burst allowance is: 64 KBytes / 2^(min_rtt/K) -+ */ -+ if (bbr_param(sk, tso_rtt_shift)) { -+ r = bbr->min_rtt_us >> bbr_param(sk, tso_rtt_shift); -+ if (r < BITS_PER_TYPE(u32)) /* prevent undefined behavior */ -+ bytes += GSO_LEGACY_MAX_SIZE >> r; -+ } -+ -+ bytes = min_t(u32, bytes, gso_max_size - 1 - MAX_TCP_HEADER); -+ segs = max_t(u32, bytes / mss_now, -+ sock_net(sk)->ipv4.sysctl_tcp_min_tso_segs); -+ return segs; -+} -+ -+/* Custom tcp_tso_autosize() for BBR, used at transmit time to cap skb size. */ -+__bpf_kfunc static u32 bbr_tso_segs(struct sock *sk, unsigned int mss_now) -+{ -+ return bbr_tso_segs_generic(sk, mss_now, sk->sk_gso_max_size); -+} -+ -+/* Like bbr_tso_segs(), using mss_cache, ignoring driver's sk_gso_max_size. */ -+static u32 bbr_tso_segs_goal(struct sock *sk) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ -+ return bbr_tso_segs_generic(sk, tp->mss_cache, GSO_LEGACY_MAX_SIZE); -+} -+ -+/* Save "last known good" cwnd so we can restore it after losses or PROBE_RTT */ -+static void bbr_save_cwnd(struct sock *sk) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ if (bbr->prev_ca_state < TCP_CA_Recovery && bbr->mode != BBR_PROBE_RTT) -+ bbr->prior_cwnd = tcp_snd_cwnd(tp); /* this cwnd is good enough */ -+ else /* loss recovery or BBR_PROBE_RTT have temporarily cut cwnd */ -+ bbr->prior_cwnd = max(bbr->prior_cwnd, tcp_snd_cwnd(tp)); -+} -+ -+__bpf_kfunc static void bbr_cwnd_event(struct sock *sk, enum tcp_ca_event event) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ if ((event == CA_EVENT_ECN_IS_CE || -+ event == CA_EVENT_ECN_NO_CE) && -+ bbr_can_use_ecn(sk) && -+ bbr_param(sk, precise_ece_ack)) { -+ u32 state = bbr->ce_state; -+ dctcp_ece_ack_update(sk, event, &bbr->prior_rcv_nxt, &state); -+ bbr->ce_state = state; -+ } else if (event == CA_EVENT_TLP_RECOVERY && -+ bbr_param(sk, loss_probe_recovery)) { -+ bbr_run_loss_probe_recovery(sk); -+ } -+} -+ -+__bpf_kfunc static void bbr_cwnd_event_tx_start(struct sock *sk) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ if (tp->app_limited) { -+ bbr->idle_restart = 1; -+ bbr->ack_epoch_mstamp = tp->tcp_mstamp; -+ bbr->ack_epoch_acked = 0; -+ /* Avoid pointless buffer overflows: pace at est. bw if we don't -+ * need more speed (we're restarting from idle and app-limited). -+ */ -+ if (bbr->mode == BBR_PROBE_BW) -+ bbr_set_pacing_rate(sk, bbr_bw(sk), BBR_UNIT); -+ else if (bbr->mode == BBR_PROBE_RTT) -+ bbr_check_probe_rtt_done(sk); -+ } -+} -+ -+/* Calculate bdp based on min RTT and the estimated bottleneck bandwidth: -+ * -+ * bdp = ceil(bw * min_rtt * gain) -+ * -+ * The key factor, gain, controls the amount of queue. While a small gain -+ * builds a smaller queue, it becomes more vulnerable to noise in RTT -+ * measurements (e.g., delayed ACKs or other ACK compression effects). This -+ * noise may cause BBR to under-estimate the rate. -+ */ -+static u32 bbr_bdp(struct sock *sk, u32 bw, int gain) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ u32 bdp; -+ u64 w; -+ -+ /* If we've never had a valid RTT sample, cap cwnd at the initial -+ * default. This should only happen when the connection is not using TCP -+ * timestamps and has retransmitted all of the SYN/SYNACK/data packets -+ * ACKed so far. In this case, an RTO can cut cwnd to 1, in which -+ * case we need to slow-start up toward something safe: initial cwnd. -+ */ -+ if (unlikely(bbr->min_rtt_us == ~0U)) /* no valid RTT samples yet? */ -+ return bbr->init_cwnd; /* be safe: cap at initial cwnd */ -+ -+ w = (u64)bw * bbr->min_rtt_us; -+ -+ /* Apply a gain to the given value, remove the BW_SCALE shift, and -+ * round the value up to avoid a negative feedback loop. -+ */ -+ bdp = (((w * gain) >> BBR_SCALE) + BW_UNIT - 1) / BW_UNIT; -+ -+ return bdp; -+} -+ -+/* To achieve full performance in high-speed paths, we budget enough cwnd to -+ * fit full-sized skbs in-flight on both end hosts to fully utilize the path: -+ * - one skb in sending host Qdisc, -+ * - one skb in sending host TSO/GSO engine -+ * - one skb being received by receiver host LRO/GRO/delayed-ACK engine -+ * Don't worry, at low rates this won't bloat cwnd because -+ * in such cases tso_segs_goal is small. The minimum cwnd is 4 packets, -+ * which allows 2 outstanding 2-packet sequences, to try to keep pipe -+ * full even with ACK-every-other-packet delayed ACKs. -+ */ -+static u32 bbr_quantization_budget(struct sock *sk, u32 cwnd) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ u32 tso_segs_goal; -+ -+ tso_segs_goal = 3 * bbr_tso_segs_goal(sk); -+ -+ /* Allow enough full-sized skbs in flight to utilize end systems. */ -+ cwnd = max_t(u32, cwnd, tso_segs_goal); -+ cwnd = max_t(u32, cwnd, bbr_param(sk, cwnd_min_target)); -+ /* Ensure gain cycling gets inflight above BDP even for small BDPs. */ -+ if (bbr->mode == BBR_PROBE_BW && bbr->cycle_idx == BBR_BW_PROBE_UP) -+ cwnd += 2; -+ -+ return cwnd; -+} -+ -+/* Find inflight based on min RTT and the estimated bottleneck bandwidth. */ -+static u32 bbr_inflight(struct sock *sk, u32 bw, int gain) -+{ -+ u32 inflight; -+ -+ inflight = bbr_bdp(sk, bw, gain); -+ inflight = bbr_quantization_budget(sk, inflight); -+ -+ return inflight; -+} -+ -+/* With pacing at lower layers, there's often less data "in the network" than -+ * "in flight". With TSQ and departure time pacing at lower layers (e.g. fq), -+ * we often have several skbs queued in the pacing layer with a pre-scheduled -+ * earliest departure time (EDT). BBR adapts its pacing rate based on the -+ * inflight level that it estimates has already been "baked in" by previous -+ * departure time decisions. We calculate a rough estimate of the number of our -+ * packets that might be in the network at the earliest departure time for the -+ * next skb scheduled: -+ * in_network_at_edt = inflight_at_edt - (EDT - now) * bw -+ * If we're increasing inflight, then we want to know if the transmit of the -+ * EDT skb will push inflight above the target, so inflight_at_edt includes -+ * bbr_tso_segs_goal() from the skb departing at EDT. If decreasing inflight, -+ * then estimate if inflight will sink too low just before the EDT transmit. -+ */ -+static u32 bbr_packets_in_net_at_edt(struct sock *sk, u32 inflight_now) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ u64 now_ns, edt_ns, interval_us; -+ u32 interval_delivered, inflight_at_edt; -+ -+ now_ns = tp->tcp_clock_cache; -+ edt_ns = max(tp->tcp_wstamp_ns, now_ns); -+ interval_us = div_u64(edt_ns - now_ns, NSEC_PER_USEC); -+ interval_delivered = (u64)bbr_bw(sk) * interval_us >> BW_SCALE; -+ inflight_at_edt = inflight_now; -+ if (bbr->pacing_gain > BBR_UNIT) /* increasing inflight */ -+ inflight_at_edt += bbr_tso_segs_goal(sk); /* include EDT skb */ -+ if (interval_delivered >= inflight_at_edt) -+ return 0; -+ return inflight_at_edt - interval_delivered; -+} -+ -+/* Find the cwnd increment based on estimate of ack aggregation */ -+static u32 bbr_ack_aggregation_cwnd(struct sock *sk) -+{ -+ u32 max_aggr_cwnd, aggr_cwnd = 0; -+ -+ if (bbr_param(sk, extra_acked_gain)) { -+ max_aggr_cwnd = ((u64)bbr_bw(sk) * bbr_extra_acked_max_us) -+ / BW_UNIT; -+ aggr_cwnd = (bbr_param(sk, extra_acked_gain) * bbr_extra_acked(sk)) -+ >> BBR_SCALE; -+ aggr_cwnd = min(aggr_cwnd, max_aggr_cwnd); -+ } -+ -+ return aggr_cwnd; -+} -+ -+/* Returns the cwnd for PROBE_RTT mode. */ -+static u32 bbr_probe_rtt_cwnd(struct sock *sk) -+{ -+ return max_t(u32, bbr_param(sk, cwnd_min_target), -+ bbr_bdp(sk, bbr_bw(sk), bbr_param(sk, probe_rtt_cwnd_gain))); -+} -+ -+/* Slow-start up toward target cwnd (if bw estimate is growing, or packet loss -+ * has drawn us down below target), or snap down to target if we're above it. -+ */ -+static void bbr_set_cwnd(struct sock *sk, const struct rate_sample *rs, -+ u32 acked, u32 bw, int gain, u32 cwnd, -+ struct bbr_context *ctx) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ u32 target_cwnd = 0; -+ -+ if (!acked) -+ goto done; /* no packet fully ACKed; just apply caps */ -+ -+ target_cwnd = bbr_bdp(sk, bw, gain); -+ -+ /* Increment the cwnd to account for excess ACKed data that seems -+ * due to aggregation (of data and/or ACKs) visible in the ACK stream. -+ */ -+ target_cwnd += bbr_ack_aggregation_cwnd(sk); -+ target_cwnd = bbr_quantization_budget(sk, target_cwnd); -+ -+ /* Update cwnd and enable fast path if cwnd reaches target_cwnd. */ -+ bbr->try_fast_path = 0; -+ if (bbr_full_bw_reached(sk)) { /* only cut cwnd if we filled the pipe */ -+ cwnd += acked; -+ if (cwnd >= target_cwnd) { -+ cwnd = target_cwnd; -+ bbr->try_fast_path = 1; -+ } -+ } else if (cwnd < target_cwnd || cwnd < 2 * bbr->init_cwnd) { -+ cwnd += acked; -+ } else { -+ bbr->try_fast_path = 1; -+ } -+ -+ cwnd = max_t(u32, cwnd, bbr_param(sk, cwnd_min_target)); -+done: -+ tcp_snd_cwnd_set(tp, min(cwnd, tp->snd_cwnd_clamp)); /* global cap */ -+ if (bbr->mode == BBR_PROBE_RTT) /* drain queue, refresh min_rtt */ -+ tcp_snd_cwnd_set(tp, min_t(u32, tcp_snd_cwnd(tp), -+ bbr_probe_rtt_cwnd(sk))); -+} -+ -+static void bbr_reset_startup_mode(struct sock *sk) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ bbr->mode = BBR_STARTUP; -+} -+ -+/* See if we have reached next round trip. Upon start of the new round, -+ * returns packets delivered since previous round start plus this ACK. -+ */ -+static u32 bbr_update_round_start(struct sock *sk, -+ const struct rate_sample *rs, struct bbr_context *ctx) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ u32 round_delivered = 0; -+ -+ bbr->round_start = 0; -+ -+ /* See if we've reached the next RTT */ -+ if (rs->interval_us > 0 && -+ !before(rs->prior_delivered, bbr->next_rtt_delivered)) { -+ round_delivered = tp->delivered - bbr->next_rtt_delivered; -+ bbr->next_rtt_delivered = tp->delivered; -+ bbr->round_start = 1; -+ } -+ return round_delivered; -+} -+ -+/* Calculate the bandwidth based on how fast packets are delivered */ -+static void bbr_calculate_bw_sample(struct sock *sk, -+ const struct rate_sample *rs, struct bbr_context *ctx) -+{ -+ u64 bw = 0; -+ -+ /* Divide delivered by the interval to find a (lower bound) bottleneck -+ * bandwidth sample. Delivered is in packets and interval_us in uS and -+ * ratio will be <<1 for most connections. So delivered is first scaled. -+ * Round up to allow growth at low rates, even with integer division. -+ */ -+ if (rs->interval_us > 0) { -+ if (WARN_ONCE(rs->delivered < 0, -+ "negative delivered: %d interval_us: %ld\n", -+ rs->delivered, rs->interval_us)) -+ return; -+ -+ bw = DIV_ROUND_UP_ULL((u64)rs->delivered * BW_UNIT, rs->interval_us); -+ } -+ -+ ctx->sample_bw = bw; -+} -+ -+/* Estimates the windowed max degree of ack aggregation. -+ * This is used to provision extra in-flight data to keep sending during -+ * inter-ACK silences. -+ * -+ * Degree of ack aggregation is estimated as extra data acked beyond expected. -+ * -+ * max_extra_acked = "maximum recent excess data ACKed beyond max_bw * interval" -+ * cwnd += max_extra_acked -+ * -+ * Max extra_acked is clamped by cwnd and bw * bbr_extra_acked_max_us (100 ms). -+ * Max filter is an approximate sliding window of 5-10 (packet timed) round -+ * trips for non-startup phase, and 1-2 round trips for startup. -+ */ -+static void bbr_update_ack_aggregation(struct sock *sk, -+ const struct rate_sample *rs) -+{ -+ u32 epoch_us, expected_acked, extra_acked; -+ struct bbr *bbr = inet_csk_ca(sk); -+ struct tcp_sock *tp = tcp_sk(sk); -+ u32 extra_acked_win_rtts_thresh = bbr_param(sk, extra_acked_win_rtts); -+ -+ if (!bbr_param(sk, extra_acked_gain) || rs->acked_sacked <= 0 || -+ rs->delivered < 0 || rs->interval_us <= 0) -+ return; -+ -+ if (bbr->round_start) { -+ bbr->extra_acked_win_rtts = min(0x1F, -+ bbr->extra_acked_win_rtts + 1); -+ if (!bbr_full_bw_reached(sk)) -+ extra_acked_win_rtts_thresh = 1; -+ if (bbr->extra_acked_win_rtts >= -+ extra_acked_win_rtts_thresh) { -+ bbr->extra_acked_win_rtts = 0; -+ bbr->extra_acked_win_idx = bbr->extra_acked_win_idx ? -+ 0 : 1; -+ bbr->extra_acked[bbr->extra_acked_win_idx] = 0; -+ } -+ } -+ -+ /* Compute how many packets we expected to be delivered over epoch. */ -+ epoch_us = tcp_stamp_us_delta(tp->delivered_mstamp, -+ bbr->ack_epoch_mstamp); -+ expected_acked = ((u64)bbr_bw(sk) * epoch_us) / BW_UNIT; -+ -+ /* Reset the aggregation epoch if ACK rate is below expected rate or -+ * significantly large no. of ack received since epoch (potentially -+ * quite old epoch). -+ */ -+ if (bbr->ack_epoch_acked <= expected_acked || -+ (bbr->ack_epoch_acked + rs->acked_sacked >= -+ bbr_ack_epoch_acked_reset_thresh)) { -+ bbr->ack_epoch_acked = 0; -+ bbr->ack_epoch_mstamp = tp->delivered_mstamp; -+ expected_acked = 0; -+ } -+ -+ /* Compute excess data delivered, beyond what was expected. */ -+ bbr->ack_epoch_acked = min_t(u32, 0xFFFFF, -+ bbr->ack_epoch_acked + rs->acked_sacked); -+ extra_acked = bbr->ack_epoch_acked - expected_acked; -+ extra_acked = min(extra_acked, tcp_snd_cwnd(tp)); -+ if (extra_acked > bbr->extra_acked[bbr->extra_acked_win_idx]) -+ bbr->extra_acked[bbr->extra_acked_win_idx] = extra_acked; -+} -+ -+static void bbr_check_probe_rtt_done(struct sock *sk) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ if (!(bbr->probe_rtt_done_stamp && -+ after(tcp_jiffies32, bbr->probe_rtt_done_stamp))) -+ return; -+ -+ bbr->probe_rtt_min_stamp = tcp_jiffies32; /* schedule next PROBE_RTT */ -+ tcp_snd_cwnd_set(tp, max(tcp_snd_cwnd(tp), bbr->prior_cwnd)); -+ bbr_exit_probe_rtt(sk); -+} -+ -+/* The goal of PROBE_RTT mode is to have BBR flows cooperatively and -+ * periodically drain the bottleneck queue, to converge to measure the true -+ * min_rtt (unloaded propagation delay). This allows the flows to keep queues -+ * small (reducing queuing delay and packet loss) and achieve fairness among -+ * BBR flows. -+ * -+ * The min_rtt filter window is 10 seconds. When the min_rtt estimate expires, -+ * we enter PROBE_RTT mode and cap the cwnd at bbr_cwnd_min_target=4 packets. -+ * After at least bbr_probe_rtt_mode_ms=200ms and at least one packet-timed -+ * round trip elapsed with that flight size <= 4, we leave PROBE_RTT mode and -+ * re-enter the previous mode. BBR uses 200ms to approximately bound the -+ * performance penalty of PROBE_RTT's cwnd capping to roughly 2% (200ms/10s). -+ * -+ * Note that flows need only pay 2% if they are busy sending over the last 10 -+ * seconds. Interactive applications (e.g., Web, RPCs, video chunks) often have -+ * natural silences or low-rate periods within 10 seconds where the rate is low -+ * enough for long enough to drain its queue in the bottleneck. We pick up -+ * these min RTT measurements opportunistically with our min_rtt filter. :-) -+ */ -+static void bbr_update_min_rtt(struct sock *sk, const struct rate_sample *rs) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ bool probe_rtt_expired, min_rtt_expired; -+ u32 expire; -+ -+ /* Track min RTT in probe_rtt_win_ms to time next PROBE_RTT state. */ -+ expire = bbr->probe_rtt_min_stamp + -+ msecs_to_jiffies(bbr_param(sk, probe_rtt_win_ms)); -+ probe_rtt_expired = after(tcp_jiffies32, expire); -+ if (rs->rtt_us >= 0 && -+ (rs->rtt_us < bbr->probe_rtt_min_us || -+ (probe_rtt_expired && !rs->is_ack_delayed))) { -+ bbr->probe_rtt_min_us = rs->rtt_us; -+ bbr->probe_rtt_min_stamp = tcp_jiffies32; -+ } -+ /* Track min RTT seen in the min_rtt_win_sec filter window: */ -+ expire = bbr->min_rtt_stamp + bbr_param(sk, min_rtt_win_sec) * HZ; -+ min_rtt_expired = after(tcp_jiffies32, expire); -+ if (bbr->probe_rtt_min_us <= bbr->min_rtt_us || -+ min_rtt_expired) { -+ bbr->min_rtt_us = bbr->probe_rtt_min_us; -+ bbr->min_rtt_stamp = bbr->probe_rtt_min_stamp; -+ } -+ -+ if (bbr_param(sk, probe_rtt_mode_ms) > 0 && probe_rtt_expired && -+ !bbr->idle_restart && bbr->mode != BBR_PROBE_RTT) { -+ bbr->mode = BBR_PROBE_RTT; /* dip, drain queue */ -+ bbr_save_cwnd(sk); /* note cwnd so we can restore it */ -+ bbr->probe_rtt_done_stamp = 0; -+ bbr->ack_phase = BBR_ACKS_PROBE_STOPPING; -+ bbr->next_rtt_delivered = tp->delivered; -+ } -+ -+ if (bbr->mode == BBR_PROBE_RTT) { -+ /* Ignore low rate samples during this mode. */ -+ tp->app_limited = -+ (tp->delivered + tcp_packets_in_flight(tp)) ? : 1; -+ /* Maintain min packets in flight for max(200 ms, 1 round). */ -+ if (!bbr->probe_rtt_done_stamp && -+ tcp_packets_in_flight(tp) <= bbr_probe_rtt_cwnd(sk)) { -+ bbr->probe_rtt_done_stamp = tcp_jiffies32 + -+ msecs_to_jiffies(bbr_param(sk, probe_rtt_mode_ms)); -+ bbr->probe_rtt_round_done = 0; -+ bbr->next_rtt_delivered = tp->delivered; -+ } else if (bbr->probe_rtt_done_stamp) { -+ if (bbr->round_start) -+ bbr->probe_rtt_round_done = 1; -+ if (bbr->probe_rtt_round_done) -+ bbr_check_probe_rtt_done(sk); -+ } -+ } -+ /* Restart after idle ends only once we process a new S/ACK for data */ -+ if (rs->delivered > 0) -+ bbr->idle_restart = 0; -+} -+ -+static void bbr_update_gains(struct sock *sk) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ switch (bbr->mode) { -+ case BBR_STARTUP: -+ bbr->pacing_gain = bbr_param(sk, startup_pacing_gain); -+ bbr->cwnd_gain = bbr_param(sk, startup_cwnd_gain); -+ break; -+ case BBR_DRAIN: -+ bbr->pacing_gain = bbr_param(sk, drain_gain); /* slow, to drain */ -+ bbr->cwnd_gain = bbr_param(sk, startup_cwnd_gain); /* keep cwnd */ -+ break; -+ case BBR_PROBE_BW: -+ bbr->pacing_gain = bbr_pacing_gain[bbr->cycle_idx]; -+ bbr->cwnd_gain = bbr_param(sk, cwnd_gain); -+ if (bbr_param(sk, bw_probe_cwnd_gain) && -+ bbr->cycle_idx == BBR_BW_PROBE_UP) -+ bbr->cwnd_gain += -+ BBR_UNIT * bbr_param(sk, bw_probe_cwnd_gain) / 4; -+ break; -+ case BBR_PROBE_RTT: -+ bbr->pacing_gain = BBR_UNIT; -+ bbr->cwnd_gain = BBR_UNIT; -+ break; -+ default: -+ WARN_ONCE(1, "BBR bad mode: %u\n", bbr->mode); -+ break; -+ } -+} -+ -+__bpf_kfunc static u32 bbr_sndbuf_expand(struct sock *sk) -+{ -+ /* Provision 3 * cwnd since BBR may slow-start even during recovery. */ -+ return 3; -+} -+ -+/* Incorporate a new bw sample into the current window of our max filter. */ -+static void bbr_take_max_bw_sample(struct sock *sk, u32 bw) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ bbr->bw_hi[1] = max(bw, bbr->bw_hi[1]); -+} -+ -+/* Keep max of last 1-2 cycles. Each PROBE_BW cycle, flip filter window. */ -+static void bbr_advance_max_bw_filter(struct sock *sk) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ if (!bbr->bw_hi[1]) -+ return; /* no samples in this window; remember old window */ -+ bbr->bw_hi[0] = bbr->bw_hi[1]; -+ bbr->bw_hi[1] = 0; -+} -+ -+/* Reset the estimator for reaching full bandwidth based on bw plateau. */ -+static void bbr_reset_full_bw(struct sock *sk) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ bbr->full_bw = 0; -+ bbr->full_bw_cnt = 0; -+ bbr->full_bw_now = 0; -+} -+ -+/* How much do we want in flight? Our BDP, unless congestion cut cwnd. */ -+static u32 bbr_target_inflight(struct sock *sk) -+{ -+ u32 bdp = bbr_inflight(sk, bbr_bw(sk), BBR_UNIT); -+ -+ return min(bdp, tcp_sk(sk)->snd_cwnd); -+} -+ -+static bool bbr_is_probing_bandwidth(struct sock *sk) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ return (bbr->mode == BBR_STARTUP) || -+ (bbr->mode == BBR_PROBE_BW && -+ (bbr->cycle_idx == BBR_BW_PROBE_REFILL || -+ bbr->cycle_idx == BBR_BW_PROBE_UP)); -+} -+ -+/* Has the given amount of time elapsed since we marked the phase start? */ -+static bool bbr_has_elapsed_in_phase(const struct sock *sk, u32 interval_us) -+{ -+ const struct tcp_sock *tp = tcp_sk(sk); -+ const struct bbr *bbr = inet_csk_ca(sk); -+ -+ return tcp_stamp_us_delta(tp->tcp_mstamp, -+ bbr->cycle_mstamp + interval_us) > 0; -+} -+ -+static void bbr_handle_queue_too_high_in_startup(struct sock *sk) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ u32 bdp; /* estimated BDP in packets, with quantization budget */ -+ -+ bbr->full_bw_reached = 1; -+ -+ bdp = bbr_inflight(sk, bbr_max_bw(sk), BBR_UNIT); -+ bbr->inflight_hi = max(bdp, bbr->inflight_latest); -+} -+ -+/* Exit STARTUP upon N consecutive rounds with ECN mark rate > ecn_thresh. */ -+static void bbr_check_ecn_too_high_in_startup(struct sock *sk, u32 ce_ratio) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ if (bbr_full_bw_reached(sk) || !bbr->ecn_eligible || -+ !bbr_param(sk, full_ecn_cnt) || !bbr_param(sk, ecn_thresh)) -+ return; -+ -+ if (ce_ratio >= bbr_param(sk, ecn_thresh)) -+ bbr->startup_ecn_rounds++; -+ else -+ bbr->startup_ecn_rounds = 0; -+ -+ if (bbr->startup_ecn_rounds >= bbr_param(sk, full_ecn_cnt)) { -+ bbr_handle_queue_too_high_in_startup(sk); -+ return; -+ } -+} -+ -+/* Updates ecn_alpha and returns ce_ratio. -1 if not available. */ -+static int bbr_update_ecn_alpha(struct sock *sk) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct net *net = sock_net(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ s32 delivered, delivered_ce; -+ u64 alpha, ce_ratio; -+ u32 gain; -+ bool want_ecn_alpha; -+ -+ /* See if we should use ECN sender logic for this connection. */ -+ if (!bbr->ecn_eligible && bbr_can_use_ecn(sk) && -+ !!bbr_param(sk, ecn_factor) && -+ (bbr->min_rtt_us <= bbr_ecn_max_rtt_us || -+ !bbr_ecn_max_rtt_us)) -+ bbr->ecn_eligible = 1; -+ -+ /* Skip updating alpha only if not ECN-eligible and PLB is disabled. */ -+ want_ecn_alpha = (bbr->ecn_eligible || -+ (bbr_can_use_ecn(sk) && -+ READ_ONCE(net->ipv4.sysctl_tcp_plb_enabled))); -+ if (!want_ecn_alpha) -+ return -1; -+ -+ delivered = tp->delivered - bbr->alpha_last_delivered; -+ delivered_ce = tp->delivered_ce - bbr->alpha_last_delivered_ce; -+ -+ if (delivered == 0 || /* avoid divide by zero */ -+ WARN_ON_ONCE(delivered < 0 || delivered_ce < 0)) /* backwards? */ -+ return -1; -+ -+ BUILD_BUG_ON(BBR_SCALE != TCP_PLB_SCALE); -+ ce_ratio = (u64)delivered_ce << BBR_SCALE; -+ do_div(ce_ratio, delivered); -+ -+ gain = bbr_param(sk, ecn_alpha_gain); -+ alpha = ((BBR_UNIT - gain) * bbr->ecn_alpha) >> BBR_SCALE; -+ alpha += (gain * ce_ratio) >> BBR_SCALE; -+ bbr->ecn_alpha = min_t(u32, alpha, BBR_UNIT); -+ -+ bbr->alpha_last_delivered = tp->delivered; -+ bbr->alpha_last_delivered_ce = tp->delivered_ce; -+ -+ bbr_check_ecn_too_high_in_startup(sk, ce_ratio); -+ return (int)ce_ratio; -+} -+ -+/* Protective Load Balancing (PLB). PLB rehashes outgoing data (to a new IPv6 -+ * flow label) if it encounters sustained congestion in the form of ECN marks. -+ */ -+static void bbr_plb(struct sock *sk, const struct rate_sample *rs, int ce_ratio) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ if (bbr->round_start && ce_ratio >= 0) -+ tcp_plb_update_state(sk, &bbr->plb, ce_ratio); -+ -+ tcp_plb_check_rehash(sk, &bbr->plb); -+} -+ -+/* Each round trip of BBR_BW_PROBE_UP, double volume of probing data. */ -+static void bbr_raise_inflight_hi_slope(struct sock *sk) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ u32 growth_this_round, cnt; -+ -+ /* Calculate "slope": packets S/Acked per inflight_hi increment. */ -+ growth_this_round = 1 << bbr->bw_probe_up_rounds; -+ bbr->bw_probe_up_rounds = min(bbr->bw_probe_up_rounds + 1, 30); -+ cnt = tcp_snd_cwnd(tp) / growth_this_round; -+ cnt = max(cnt, 1U); -+ bbr->bw_probe_up_cnt = cnt; -+} -+ -+/* In BBR_BW_PROBE_UP, not seeing high loss/ECN/queue, so raise inflight_hi. */ -+static void bbr_probe_inflight_hi_upward(struct sock *sk, -+ const struct rate_sample *rs) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ u32 delta; -+ -+ if (!tp->is_cwnd_limited || tcp_snd_cwnd(tp) < bbr->inflight_hi) -+ return; /* not fully using inflight_hi, so don't grow it */ -+ -+ /* For each bw_probe_up_cnt packets ACKed, increase inflight_hi by 1. */ -+ bbr->bw_probe_up_acks += rs->acked_sacked; -+ if (bbr->bw_probe_up_acks >= bbr->bw_probe_up_cnt) { -+ delta = bbr->bw_probe_up_acks / bbr->bw_probe_up_cnt; -+ bbr->bw_probe_up_acks -= delta * bbr->bw_probe_up_cnt; -+ bbr->inflight_hi += delta; -+ bbr->try_fast_path = 0; /* Need to update cwnd */ -+ } -+ -+ if (bbr->round_start) -+ bbr_raise_inflight_hi_slope(sk); -+} -+ -+/* Does loss/ECN rate for this sample say inflight is "too high"? -+ * This is used by both the bbr_check_loss_too_high_in_startup() function, -+ * and in PROBE_UP. -+ */ -+static bool bbr_is_inflight_too_high(const struct sock *sk, -+ const struct rate_sample *rs) -+{ -+ const struct bbr *bbr = inet_csk_ca(sk); -+ u32 loss_thresh, ecn_thresh; -+ -+ if (rs->lost > 0 && rs->tx_in_flight) { -+ loss_thresh = (u64)rs->tx_in_flight * bbr_param(sk, loss_thresh) >> -+ BBR_SCALE; -+ if (rs->lost > loss_thresh) { -+ return true; -+ } -+ } -+ -+ if (rs->delivered_ce > 0 && rs->delivered > 0 && -+ bbr->ecn_eligible && !!bbr_param(sk, ecn_thresh)) { -+ ecn_thresh = (u64)rs->delivered * bbr_param(sk, ecn_thresh) >> -+ BBR_SCALE; -+ if (rs->delivered_ce > ecn_thresh) { -+ return true; -+ } -+ } -+ -+ return false; -+} -+ -+/* Calculate the tx_in_flight level that corresponded to excessive loss. -+ * We find "lost_prefix" segs of the skb where loss rate went too high, -+ * by solving for "lost_prefix" in the following equation: -+ * lost / inflight >= loss_thresh -+ * (lost_prev + lost_prefix) / (inflight_prev + lost_prefix) >= loss_thresh -+ * Then we take that equation, convert it to fixed point, and -+ * round up to the nearest packet. -+ */ -+static u32 bbr_inflight_hi_from_lost_skb(const struct sock *sk, -+ const struct rate_sample *rs, -+ const struct sk_buff *skb) -+{ -+ const struct tcp_sock *tp = tcp_sk(sk); -+ u32 loss_thresh = bbr_param(sk, loss_thresh); -+ u32 pcount, divisor, inflight_hi; -+ s32 inflight_prev, lost_prev; -+ u64 loss_budget, lost_prefix; -+ -+ pcount = tcp_skb_pcount(skb); -+ -+ /* How much data was in flight before this skb? */ -+ inflight_prev = rs->tx_in_flight - pcount; -+ if (inflight_prev < 0) { -+ WARN_ONCE(tcp_skb_tx_in_flight_is_suspicious( -+ pcount, -+ TCP_SKB_CB(skb)->sacked, -+ rs->tx_in_flight), -+ "tx_in_flight: %u pcount: %u reneg: %u", -+ rs->tx_in_flight, pcount, tcp_sk(sk)->is_sack_reneg); -+ return ~0U; -+ } -+ -+ /* How much inflight data was marked lost before this skb? */ -+ lost_prev = rs->lost - pcount; -+ if (WARN_ONCE(lost_prev < 0, -+ "cwnd: %u ca: %d out: %u lost: %u pif: %u " -+ "tx_in_flight: %u tx.lost: %u tp->lost: %u rs->lost: %d " -+ "lost_prev: %d pcount: %d seq: %u end_seq: %u reneg: %u", -+ tcp_snd_cwnd(tp), inet_csk(sk)->icsk_ca_state, -+ tp->packets_out, tp->lost_out, tcp_packets_in_flight(tp), -+ rs->tx_in_flight, TCP_SKB_CB(skb)->tx.lost, tp->lost, -+ rs->lost, lost_prev, pcount, -+ TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq, -+ tp->is_sack_reneg)) -+ return ~0U; -+ -+ /* At what prefix of this lost skb did losss rate exceed loss_thresh? */ -+ loss_budget = (u64)inflight_prev * loss_thresh + BBR_UNIT - 1; -+ loss_budget >>= BBR_SCALE; -+ if (lost_prev >= loss_budget) { -+ lost_prefix = 0; /* previous losses crossed loss_thresh */ -+ } else { -+ lost_prefix = loss_budget - lost_prev; -+ lost_prefix <<= BBR_SCALE; -+ divisor = BBR_UNIT - loss_thresh; -+ if (WARN_ON_ONCE(!divisor)) /* loss_thresh is 8 bits */ -+ return ~0U; -+ do_div(lost_prefix, divisor); -+ } -+ -+ inflight_hi = inflight_prev + lost_prefix; -+ return inflight_hi; -+} -+ -+/* If loss/ECN rates during probing indicated we may have overfilled a -+ * buffer, return an operating point that tries to leave unutilized headroom in -+ * the path for other flows, for fairness convergence and lower RTTs and loss. -+ */ -+static u32 bbr_inflight_with_headroom(const struct sock *sk) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ u32 headroom, headroom_fraction; -+ -+ if (bbr->inflight_hi == ~0U) -+ return ~0U; -+ -+ headroom_fraction = bbr_param(sk, inflight_headroom); -+ headroom = ((u64)bbr->inflight_hi * headroom_fraction) >> BBR_SCALE; -+ headroom = max(headroom, 1U); -+ return max_t(s32, bbr->inflight_hi - headroom, -+ bbr_param(sk, cwnd_min_target)); -+} -+ -+/* Bound cwnd to a sensible level, based on our current probing state -+ * machine phase and model of a good inflight level (inflight_lo, inflight_hi). -+ */ -+static void bbr_bound_cwnd_for_inflight_model(struct sock *sk) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ u32 cap; -+ -+ /* tcp_rcv_synsent_state_process() currently calls tcp_ack() -+ * and thus cong_control() without first initializing us(!). -+ */ -+ if (!bbr->initialized) -+ return; -+ -+ cap = ~0U; -+ if (bbr->mode == BBR_PROBE_BW && -+ bbr->cycle_idx != BBR_BW_PROBE_CRUISE) { -+ /* Probe to see if more packets fit in the path. */ -+ cap = bbr->inflight_hi; -+ } else { -+ if (bbr->mode == BBR_PROBE_RTT || -+ (bbr->mode == BBR_PROBE_BW && -+ bbr->cycle_idx == BBR_BW_PROBE_CRUISE)) -+ cap = bbr_inflight_with_headroom(sk); -+ } -+ /* Adapt to any loss/ECN since our last bw probe. */ -+ cap = min(cap, bbr->inflight_lo); -+ -+ cap = max_t(u32, cap, bbr_param(sk, cwnd_min_target)); -+ tcp_snd_cwnd_set(tp, min(cap, tcp_snd_cwnd(tp))); -+} -+ -+/* How should we multiplicatively cut bw or inflight limits based on ECN? */ -+static u32 bbr_ecn_cut(struct sock *sk) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ return BBR_UNIT - -+ ((bbr->ecn_alpha * bbr_param(sk, ecn_factor)) >> BBR_SCALE); -+} -+ -+/* Init lower bounds if have not inited yet. */ -+static void bbr_init_lower_bounds(struct sock *sk, bool init_bw) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ if (init_bw && bbr->bw_lo == ~0U) -+ bbr->bw_lo = bbr_max_bw(sk); -+ if (bbr->inflight_lo == ~0U) -+ bbr->inflight_lo = tcp_snd_cwnd(tp); -+} -+ -+/* Reduce bw and inflight to (1 - beta). */ -+static void bbr_loss_lower_bounds(struct sock *sk, u32 *bw, u32 *inflight) -+{ -+ struct bbr* bbr = inet_csk_ca(sk); -+ u32 loss_cut = BBR_UNIT - bbr_param(sk, beta); -+ -+ *bw = max_t(u32, bbr->bw_latest, -+ (u64)bbr->bw_lo * loss_cut >> BBR_SCALE); -+ *inflight = max_t(u32, bbr->inflight_latest, -+ (u64)bbr->inflight_lo * loss_cut >> BBR_SCALE); -+} -+ -+/* Reduce inflight to (1 - alpha*ecn_factor). */ -+static void bbr_ecn_lower_bounds(struct sock *sk, u32 *inflight) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ u32 ecn_cut = bbr_ecn_cut(sk); -+ -+ *inflight = (u64)bbr->inflight_lo * ecn_cut >> BBR_SCALE; -+} -+ -+/* Estimate a short-term lower bound on the capacity available now, based -+ * on measurements of the current delivery process and recent history. When we -+ * are seeing loss/ECN at times when we are not probing bw, then conservatively -+ * move toward flow balance by multiplicatively cutting our short-term -+ * estimated safe rate and volume of data (bw_lo and inflight_lo). We use a -+ * multiplicative decrease in order to converge to a lower capacity in time -+ * logarithmic in the magnitude of the decrease. -+ * -+ * However, we do not cut our short-term estimates lower than the current rate -+ * and volume of delivered data from this round trip, since from the current -+ * delivery process we can estimate the measured capacity available now. -+ * -+ * Anything faster than that approach would knowingly risk high loss, which can -+ * cause low bw for Reno/CUBIC and high loss recovery latency for -+ * request/response flows using any congestion control. -+ */ -+static void bbr_adapt_lower_bounds(struct sock *sk, -+ const struct rate_sample *rs) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ u32 ecn_inflight_lo = ~0U; -+ -+ /* We only use lower-bound estimates when not probing bw. -+ * When probing we need to push inflight higher to probe bw. -+ */ -+ if (bbr_is_probing_bandwidth(sk)) -+ return; -+ -+ /* ECN response. */ -+ if (bbr->ecn_in_round && !!bbr_param(sk, ecn_factor)) { -+ bbr_init_lower_bounds(sk, false); -+ bbr_ecn_lower_bounds(sk, &ecn_inflight_lo); -+ } -+ -+ /* Loss response. */ -+ if (bbr->loss_in_round) { -+ bbr_init_lower_bounds(sk, true); -+ bbr_loss_lower_bounds(sk, &bbr->bw_lo, &bbr->inflight_lo); -+ } -+ -+ /* Adjust to the lower of the levels implied by loss/ECN. */ -+ bbr->inflight_lo = min(bbr->inflight_lo, ecn_inflight_lo); -+ bbr->bw_lo = max(1U, bbr->bw_lo); -+} -+ -+/* Reset any short-term lower-bound adaptation to congestion, so that we can -+ * push our inflight up. -+ */ -+static void bbr_reset_lower_bounds(struct sock *sk) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ bbr->bw_lo = ~0U; -+ bbr->inflight_lo = ~0U; -+} -+ -+/* After bw probing (STARTUP/PROBE_UP), reset signals before entering a state -+ * machine phase where we adapt our lower bound based on congestion signals. -+ */ -+static void bbr_reset_congestion_signals(struct sock *sk) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ bbr->loss_in_round = 0; -+ bbr->ecn_in_round = 0; -+ bbr->loss_in_cycle = 0; -+ bbr->ecn_in_cycle = 0; -+ bbr->bw_latest = 0; -+ bbr->inflight_latest = 0; -+} -+ -+static void bbr_exit_loss_recovery(struct sock *sk) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ tcp_snd_cwnd_set(tp, max(tcp_snd_cwnd(tp), bbr->prior_cwnd)); -+ bbr->try_fast_path = 0; /* bound cwnd using latest model */ -+} -+ -+/* Update rate and volume of delivered data from latest round trip. */ -+static void bbr_update_latest_delivery_signals( -+ struct sock *sk, const struct rate_sample *rs, struct bbr_context *ctx) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ bbr->loss_round_start = 0; -+ if (rs->interval_us <= 0 || !rs->acked_sacked) -+ return; /* Not a valid observation */ -+ -+ bbr->bw_latest = max_t(u32, bbr->bw_latest, ctx->sample_bw); -+ bbr->inflight_latest = max_t(u32, bbr->inflight_latest, rs->delivered); -+ -+ if (!before(rs->prior_delivered, bbr->loss_round_delivered)) { -+ bbr->loss_round_delivered = tp->delivered; -+ bbr->loss_round_start = 1; /* mark start of new round trip */ -+ } -+} -+ -+/* Once per round, reset filter for latest rate and volume of delivered data. */ -+static void bbr_advance_latest_delivery_signals( -+ struct sock *sk, const struct rate_sample *rs, struct bbr_context *ctx) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ /* If ACK matches a TLP retransmit, persist the filter. If we detect -+ * that a TLP retransmit plugged a tail loss, we'll want to remember -+ * how much data the path delivered before the tail loss. -+ */ -+ if (bbr->loss_round_start && !rs->is_acking_tlp_retrans_seq) { -+ bbr->bw_latest = ctx->sample_bw; -+ bbr->inflight_latest = rs->delivered; -+ } -+} -+ -+/* Update (most of) our congestion signals: track the recent rate and volume of -+ * delivered data, presence of loss, and EWMA degree of ECN marking. -+ */ -+static void bbr_update_congestion_signals( -+ struct sock *sk, const struct rate_sample *rs, struct bbr_context *ctx) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ u64 bw; -+ -+ if (rs->interval_us <= 0 || !rs->acked_sacked) -+ return; /* Not a valid observation */ -+ bw = ctx->sample_bw; -+ -+ if (!rs->is_app_limited || bw >= bbr_max_bw(sk)) -+ bbr_take_max_bw_sample(sk, bw); -+ -+ bbr->loss_in_round |= (rs->losses > 0); -+ -+ if (!bbr->loss_round_start) -+ return; /* skip the per-round-trip updates */ -+ /* Now do per-round-trip updates. */ -+ bbr_adapt_lower_bounds(sk, rs); -+ -+ bbr->loss_in_round = 0; -+ bbr->ecn_in_round = 0; -+} -+ -+/* Bandwidth probing can cause loss. To help coexistence with loss-based -+ * congestion control we spread out our probing in a Reno-conscious way. Due to -+ * the shape of the Reno sawtooth, the time required between loss epochs for an -+ * idealized Reno flow is a number of round trips that is the BDP of that -+ * flow. We count packet-timed round trips directly, since measured RTT can -+ * vary widely, and Reno is driven by packet-timed round trips. -+ */ -+static bool bbr_is_reno_coexistence_probe_time(struct sock *sk) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ u32 rounds; -+ -+ /* Random loss can shave some small percentage off of our inflight -+ * in each round. To survive this, flows need robust periodic probes. -+ */ -+ rounds = min_t(u32, bbr_param(sk, bw_probe_max_rounds), bbr_target_inflight(sk)); -+ return bbr->rounds_since_probe >= rounds; -+} -+ -+/* How long do we want to wait before probing for bandwidth (and risking -+ * loss)? We randomize the wait, for better mixing and fairness convergence. -+ * -+ * We bound the Reno-coexistence inter-bw-probe time to be 62-63 round trips. -+ * This is calculated to allow fairness with a 25Mbps, 30ms Reno flow, -+ * (eg 4K video to a broadband user): -+ * BDP = 25Mbps * .030sec /(1514bytes) = 61.9 packets -+ * -+ * We bound the BBR-native inter-bw-probe wall clock time to be: -+ * (a) higher than 2 sec: to try to avoid causing loss for a long enough time -+ * to allow Reno at 30ms to get 4K video bw, the inter-bw-probe time must -+ * be at least: 25Mbps * .030sec / (1514bytes) * 0.030sec = 1.9secs -+ * (b) lower than 3 sec: to ensure flows can start probing in a reasonable -+ * amount of time to discover unutilized bw on human-scale interactive -+ * time-scales (e.g. perhaps traffic from a web page download that we -+ * were competing with is now complete). -+ */ -+static void bbr_pick_probe_wait(struct sock *sk) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ /* Decide the random round-trip bound for wait until probe: */ -+ bbr->rounds_since_probe = -+ get_random_u32_below(bbr_param(sk, bw_probe_rand_rounds)); -+ /* Decide the random wall clock bound for wait until probe: */ -+ bbr->probe_wait_us = bbr_param(sk, bw_probe_base_us) + -+ get_random_u32_below(bbr_param(sk, bw_probe_rand_us)); -+} -+ -+static void bbr_set_cycle_idx(struct sock *sk, int cycle_idx) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ bbr->cycle_idx = cycle_idx; -+ /* New phase, so need to update cwnd and pacing rate. */ -+ bbr->try_fast_path = 0; -+} -+ -+/* Send at estimated bw to fill the pipe, but not queue. We need this phase -+ * before PROBE_UP, because as soon as we send faster than the available bw -+ * we will start building a queue, and if the buffer is shallow we can cause -+ * loss. If we do not fill the pipe before we cause this loss, our bw_hi and -+ * inflight_hi estimates will underestimate. -+ */ -+static void bbr_start_bw_probe_refill(struct sock *sk, u32 bw_probe_up_rounds) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ bbr_reset_lower_bounds(sk); -+ bbr->bw_probe_up_rounds = bw_probe_up_rounds; -+ bbr->bw_probe_up_acks = 0; -+ bbr->stopped_risky_probe = 0; -+ bbr->ack_phase = BBR_ACKS_REFILLING; -+ bbr->next_rtt_delivered = tp->delivered; -+ bbr_set_cycle_idx(sk, BBR_BW_PROBE_REFILL); -+} -+ -+/* Now probe max deliverable data rate and volume. */ -+static void bbr_start_bw_probe_up(struct sock *sk, struct bbr_context *ctx) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ bbr->ack_phase = BBR_ACKS_PROBE_STARTING; -+ bbr->next_rtt_delivered = tp->delivered; -+ bbr->cycle_mstamp = tp->tcp_mstamp; -+ bbr_reset_full_bw(sk); -+ bbr->full_bw = ctx->sample_bw; -+ bbr_set_cycle_idx(sk, BBR_BW_PROBE_UP); -+ bbr_raise_inflight_hi_slope(sk); -+} -+ -+/* Start a new PROBE_BW probing cycle of some wall clock length. Pick a wall -+ * clock time at which to probe beyond an inflight that we think to be -+ * safe. This will knowingly risk packet loss, so we want to do this rarely, to -+ * keep packet loss rates low. Also start a round-trip counter, to probe faster -+ * if we estimate a Reno flow at our BDP would probe faster. -+ */ -+static void bbr_start_bw_probe_down(struct sock *sk) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ bbr_reset_congestion_signals(sk); -+ bbr->bw_probe_up_cnt = ~0U; /* not growing inflight_hi any more */ -+ bbr_pick_probe_wait(sk); -+ bbr->cycle_mstamp = tp->tcp_mstamp; /* start wall clock */ -+ bbr->ack_phase = BBR_ACKS_PROBE_STOPPING; -+ bbr->next_rtt_delivered = tp->delivered; -+ bbr_set_cycle_idx(sk, BBR_BW_PROBE_DOWN); -+} -+ -+/* Cruise: maintain what we estimate to be a neutral, conservative -+ * operating point, without attempting to probe up for bandwidth or down for -+ * RTT, and only reducing inflight in response to loss/ECN signals. -+ */ -+static void bbr_start_bw_probe_cruise(struct sock *sk) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ if (bbr->inflight_lo != ~0U) -+ bbr->inflight_lo = min(bbr->inflight_lo, bbr->inflight_hi); -+ -+ bbr_set_cycle_idx(sk, BBR_BW_PROBE_CRUISE); -+} -+ -+/* Loss and/or ECN rate is too high while probing. -+ * Adapt (once per bw probe) by cutting inflight_hi and then restarting cycle. -+ */ -+static void bbr_handle_inflight_too_high(struct sock *sk, -+ const struct rate_sample *rs) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ const u32 beta = bbr_param(sk, beta); -+ -+ bbr->prev_probe_too_high = 1; -+ bbr->bw_probe_samples = 0; /* only react once per probe */ -+ /* If we are app-limited then we are not robustly -+ * probing the max volume of inflight data we think -+ * might be safe (analogous to how app-limited bw -+ * samples are not known to be robustly probing bw). -+ */ -+ if (!rs->is_app_limited) { -+ bbr->inflight_hi = max_t(u32, rs->tx_in_flight, -+ (u64)bbr_target_inflight(sk) * -+ (BBR_UNIT - beta) >> BBR_SCALE); -+ } -+ if (bbr->mode == BBR_PROBE_BW && bbr->cycle_idx == BBR_BW_PROBE_UP) -+ bbr_start_bw_probe_down(sk); -+} -+ -+/* If we're seeing bw and loss samples reflecting our bw probing, adapt -+ * using the signals we see. If loss or ECN mark rate gets too high, then adapt -+ * inflight_hi downward. If we're able to push inflight higher without such -+ * signals, push higher: adapt inflight_hi upward. -+ */ -+static bool bbr_adapt_upper_bounds(struct sock *sk, -+ const struct rate_sample *rs, -+ struct bbr_context *ctx) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ /* Track when we'll see bw/loss samples resulting from our bw probes. */ -+ if (bbr->ack_phase == BBR_ACKS_PROBE_STARTING && bbr->round_start) -+ bbr->ack_phase = BBR_ACKS_PROBE_FEEDBACK; -+ if (bbr->ack_phase == BBR_ACKS_PROBE_STOPPING && bbr->round_start) { -+ /* End of samples from bw probing phase. */ -+ bbr->bw_probe_samples = 0; -+ bbr->ack_phase = BBR_ACKS_INIT; -+ /* At this point in the cycle, our current bw sample is also -+ * our best recent chance at finding the highest available bw -+ * for this flow. So now is the best time to forget the bw -+ * samples from the previous cycle, by advancing the window. -+ */ -+ if (bbr->mode == BBR_PROBE_BW && !rs->is_app_limited) -+ bbr_advance_max_bw_filter(sk); -+ /* If we had an inflight_hi, then probed and pushed inflight all -+ * the way up to hit that inflight_hi without seeing any -+ * high loss/ECN in all the resulting ACKs from that probing, -+ * then probe up again, this time letting inflight persist at -+ * inflight_hi for a round trip, then accelerating beyond. -+ */ -+ if (bbr->mode == BBR_PROBE_BW && -+ bbr->stopped_risky_probe && !bbr->prev_probe_too_high) { -+ bbr_start_bw_probe_refill(sk, 0); -+ return true; /* yes, decided state transition */ -+ } -+ } -+ if (bbr_is_inflight_too_high(sk, rs)) { -+ if (bbr->bw_probe_samples) /* sample is from bw probing? */ -+ bbr_handle_inflight_too_high(sk, rs); -+ } else { -+ /* Loss/ECN rate is declared safe. Adjust upper bound upward. */ -+ -+ if (bbr->inflight_hi == ~0U) -+ return false; /* no excess queue signals yet */ -+ -+ /* To be resilient to random loss, we must raise bw/inflight_hi -+ * if we observe in any phase that a higher level is safe. -+ */ -+ if (rs->tx_in_flight > bbr->inflight_hi) { -+ bbr->inflight_hi = rs->tx_in_flight; -+ } -+ -+ if (bbr->mode == BBR_PROBE_BW && -+ bbr->cycle_idx == BBR_BW_PROBE_UP) -+ bbr_probe_inflight_hi_upward(sk, rs); -+ } -+ -+ return false; -+} -+ -+/* Check if it's time to probe for bandwidth now, and if so, kick it off. */ -+static bool bbr_check_time_to_probe_bw(struct sock *sk, -+ const struct rate_sample *rs) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ u32 n; -+ -+ /* If we seem to be at an operating point where we are not seeing loss -+ * but we are seeing ECN marks, then when the ECN marks cease we reprobe -+ * quickly (in case cross-traffic has ceased and freed up bw). -+ */ -+ if (bbr_param(sk, ecn_reprobe_gain) && bbr->ecn_eligible && -+ bbr->ecn_in_cycle && !bbr->loss_in_cycle && -+ inet_csk(sk)->icsk_ca_state == TCP_CA_Open) { -+ /* Calculate n so that when bbr_raise_inflight_hi_slope() -+ * computes growth_this_round as 2^n it will be roughly the -+ * desired volume of data (inflight_hi*ecn_reprobe_gain). -+ */ -+ n = ilog2((((u64)bbr->inflight_hi * -+ bbr_param(sk, ecn_reprobe_gain)) >> BBR_SCALE)); -+ bbr_start_bw_probe_refill(sk, n); -+ return true; -+ } -+ -+ if (bbr_has_elapsed_in_phase(sk, bbr->probe_wait_us) || -+ bbr_is_reno_coexistence_probe_time(sk)) { -+ bbr_start_bw_probe_refill(sk, 0); -+ return true; -+ } -+ return false; -+} -+ -+/* Is it time to transition from PROBE_DOWN to PROBE_CRUISE? */ -+static bool bbr_check_time_to_cruise(struct sock *sk, u32 inflight, u32 bw) -+{ -+ /* Always need to pull inflight down to leave headroom in queue. */ -+ if (inflight > bbr_inflight_with_headroom(sk)) -+ return false; -+ -+ return inflight <= bbr_inflight(sk, bw, BBR_UNIT); -+} -+ -+/* PROBE_BW state machine: cruise, refill, probe for bw, or drain? */ -+static void bbr_update_cycle_phase(struct sock *sk, -+ const struct rate_sample *rs, -+ struct bbr_context *ctx) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ bool is_bw_probe_done = false; -+ u32 inflight, bw; -+ -+ if (!bbr_full_bw_reached(sk)) -+ return; -+ -+ /* In DRAIN, PROBE_BW, or PROBE_RTT, adjust upper bounds. */ -+ if (bbr_adapt_upper_bounds(sk, rs, ctx)) -+ return; /* already decided state transition */ -+ -+ if (bbr->mode != BBR_PROBE_BW) -+ return; -+ -+ inflight = bbr_packets_in_net_at_edt(sk, rs->prior_in_flight); -+ bw = bbr_max_bw(sk); -+ -+ switch (bbr->cycle_idx) { -+ /* First we spend most of our time cruising with a pacing_gain of 1.0, -+ * which paces at the estimated bw, to try to fully use the pipe -+ * without building queue. If we encounter loss/ECN marks, we adapt -+ * by slowing down. -+ */ -+ case BBR_BW_PROBE_CRUISE: -+ if (bbr_check_time_to_probe_bw(sk, rs)) -+ return; /* already decided state transition */ -+ break; -+ -+ /* After cruising, when it's time to probe, we first "refill": we send -+ * at the estimated bw to fill the pipe, before probing higher and -+ * knowingly risking overflowing the bottleneck buffer (causing loss). -+ */ -+ case BBR_BW_PROBE_REFILL: -+ if (bbr->round_start) { -+ /* After one full round trip of sending in REFILL, we -+ * start to see bw samples reflecting our REFILL, which -+ * may be putting too much data in flight. -+ */ -+ bbr->bw_probe_samples = 1; -+ bbr_start_bw_probe_up(sk, ctx); -+ } -+ break; -+ -+ /* After we refill the pipe, we probe by using a pacing_gain > 1.0, to -+ * probe for bw. If we have not seen loss/ECN, we try to raise inflight -+ * to at least pacing_gain*BDP; note that this may take more than -+ * min_rtt if min_rtt is small (e.g. on a LAN). -+ * -+ * We terminate PROBE_UP bandwidth probing upon any of the following: -+ * -+ * (1) We've pushed inflight up to hit the inflight_hi target set in the -+ * most recent previous bw probe phase. Thus we want to start -+ * draining the queue immediately because it's very likely the most -+ * recently sent packets will fill the queue and cause drops. -+ * (2) If inflight_hi has not limited bandwidth growth recently, and -+ * yet delivered bandwidth has not increased much recently -+ * (bbr->full_bw_now). -+ * (3) Loss filter says loss rate is "too high". -+ * (4) ECN filter says ECN mark rate is "too high". -+ * -+ * (1) (2) checked here, (3) (4) checked in bbr_is_inflight_too_high() -+ */ -+ case BBR_BW_PROBE_UP: -+ if (bbr->prev_probe_too_high && -+ inflight >= bbr->inflight_hi) { -+ bbr->stopped_risky_probe = 1; -+ is_bw_probe_done = true; -+ } else { -+ if (tp->is_cwnd_limited && -+ tcp_snd_cwnd(tp) >= bbr->inflight_hi) { -+ /* inflight_hi is limiting bw growth */ -+ bbr_reset_full_bw(sk); -+ bbr->full_bw = ctx->sample_bw; -+ } else if (bbr->full_bw_now) { -+ /* Plateau in estimated bw. Pipe looks full. */ -+ is_bw_probe_done = true; -+ } -+ } -+ if (is_bw_probe_done) { -+ bbr->prev_probe_too_high = 0; /* no loss/ECN (yet) */ -+ bbr_start_bw_probe_down(sk); /* restart w/ down */ -+ } -+ break; -+ -+ /* After probing in PROBE_UP, we have usually accumulated some data in -+ * the bottleneck buffer (if bw probing didn't find more bw). We next -+ * enter PROBE_DOWN to try to drain any excess data from the queue. To -+ * do this, we use a pacing_gain < 1.0. We hold this pacing gain until -+ * our inflight is less then that target cruising point, which is the -+ * minimum of (a) the amount needed to leave headroom, and (b) the -+ * estimated BDP. Once inflight falls to match the target, we estimate -+ * the queue is drained; persisting would underutilize the pipe. -+ */ -+ case BBR_BW_PROBE_DOWN: -+ if (bbr_check_time_to_probe_bw(sk, rs)) -+ return; /* already decided state transition */ -+ if (bbr_check_time_to_cruise(sk, inflight, bw)) -+ bbr_start_bw_probe_cruise(sk); -+ break; -+ -+ default: -+ WARN_ONCE(1, "BBR invalid cycle index %u\n", bbr->cycle_idx); -+ } -+} -+ -+/* Exiting PROBE_RTT, so return to bandwidth probing in STARTUP or PROBE_BW. */ -+static void bbr_exit_probe_rtt(struct sock *sk) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ bbr_reset_lower_bounds(sk); -+ if (bbr_full_bw_reached(sk)) { -+ bbr->mode = BBR_PROBE_BW; -+ /* Raising inflight after PROBE_RTT may cause loss, so reset -+ * the PROBE_BW clock and schedule the next bandwidth probe for -+ * a friendly and randomized future point in time. -+ */ -+ bbr_start_bw_probe_down(sk); -+ /* Since we are exiting PROBE_RTT, we know inflight is -+ * below our estimated BDP, so it is reasonable to cruise. -+ */ -+ bbr_start_bw_probe_cruise(sk); -+ } else { -+ bbr->mode = BBR_STARTUP; -+ } -+} -+ -+/* Exit STARTUP based on loss rate > 1% and loss gaps in round >= N. Wait until -+ * the end of the round in recovery to get a good estimate of how many packets -+ * have been lost, and how many we need to drain with a low pacing rate. -+ */ -+static void bbr_check_loss_too_high_in_startup(struct sock *sk, -+ const struct rate_sample *rs) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ if (bbr_full_bw_reached(sk)) -+ return; -+ -+ /* For STARTUP exit, check the loss rate at the end of each round trip -+ * of Recovery episodes in STARTUP. We check the loss rate at the end -+ * of the round trip to filter out noisy/low loss and have a better -+ * sense of inflight (extent of loss), so we can drain more accurately. -+ */ -+ if (rs->losses && bbr->loss_events_in_round < 0xf) -+ bbr->loss_events_in_round++; /* update saturating counter */ -+ if (bbr_param(sk, full_loss_cnt) && bbr->loss_round_start && -+ inet_csk(sk)->icsk_ca_state == TCP_CA_Recovery && -+ bbr->loss_events_in_round >= bbr_param(sk, full_loss_cnt) && -+ bbr_is_inflight_too_high(sk, rs)) { -+ bbr_handle_queue_too_high_in_startup(sk); -+ return; -+ } -+ if (bbr->loss_round_start) -+ bbr->loss_events_in_round = 0; -+} -+ -+/* Estimate when the pipe is full, using the change in delivery rate: BBR -+ * estimates bw probing filled the pipe if the estimated bw hasn't changed by -+ * at least bbr_full_bw_thresh (25%) after bbr_full_bw_cnt (3) non-app-limited -+ * rounds. Why 3 rounds: 1: rwin autotuning grows the rwin, 2: we fill the -+ * higher rwin, 3: we get higher delivery rate samples. Or transient -+ * cross-traffic or radio noise can go away. CUBIC Hystart shares a similar -+ * design goal, but uses delay and inter-ACK spacing instead of bandwidth. -+ */ -+static void bbr_check_full_bw_reached(struct sock *sk, -+ const struct rate_sample *rs, -+ struct bbr_context *ctx) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ u32 bw_thresh, full_cnt, thresh; -+ -+ if (bbr->full_bw_now || rs->is_app_limited) -+ return; -+ -+ thresh = bbr_param(sk, full_bw_thresh); -+ full_cnt = bbr_param(sk, full_bw_cnt); -+ bw_thresh = (u64)bbr->full_bw * thresh >> BBR_SCALE; -+ if (ctx->sample_bw >= bw_thresh) { -+ bbr_reset_full_bw(sk); -+ bbr->full_bw = ctx->sample_bw; -+ return; -+ } -+ if (!bbr->round_start) -+ return; -+ ++bbr->full_bw_cnt; -+ bbr->full_bw_now = bbr->full_bw_cnt >= full_cnt; -+ bbr->full_bw_reached |= bbr->full_bw_now; -+} -+ -+/* If pipe is probably full, drain the queue and then enter steady-state. */ -+static void bbr_check_drain(struct sock *sk, const struct rate_sample *rs, -+ struct bbr_context *ctx) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ if (bbr->mode == BBR_STARTUP && bbr_full_bw_reached(sk)) { -+ bbr->mode = BBR_DRAIN; /* drain queue we created */ -+ /* Set ssthresh to export purely for monitoring, to signal -+ * completion of initial STARTUP by setting to a non- -+ * TCP_INFINITE_SSTHRESH value (ssthresh is not used by BBR). -+ */ -+ tcp_sk(sk)->snd_ssthresh = -+ bbr_inflight(sk, bbr_max_bw(sk), BBR_UNIT); -+ bbr_reset_congestion_signals(sk); -+ } /* fall through to check if in-flight is already small: */ -+ if (bbr->mode == BBR_DRAIN && -+ bbr_packets_in_net_at_edt(sk, tcp_packets_in_flight(tcp_sk(sk))) <= -+ bbr_inflight(sk, bbr_max_bw(sk), BBR_UNIT)) { -+ bbr->mode = BBR_PROBE_BW; -+ bbr_start_bw_probe_down(sk); -+ } -+} -+ -+static void bbr_update_model(struct sock *sk, const struct rate_sample *rs, -+ struct bbr_context *ctx) -+{ -+ bbr_update_congestion_signals(sk, rs, ctx); -+ bbr_update_ack_aggregation(sk, rs); -+ bbr_check_loss_too_high_in_startup(sk, rs); -+ bbr_check_full_bw_reached(sk, rs, ctx); -+ bbr_check_drain(sk, rs, ctx); -+ bbr_update_cycle_phase(sk, rs, ctx); -+ bbr_update_min_rtt(sk, rs); -+} -+ -+/* Fast path for app-limited case. -+ * -+ * On each ack, we execute bbr state machine, which primarily consists of: -+ * 1) update model based on new rate sample, and -+ * 2) update control based on updated model or state change. -+ * -+ * There are certain workload/scenarios, e.g. app-limited case, where -+ * either we can skip updating model or we can skip update of both model -+ * as well as control. This provides signifcant softirq cpu savings for -+ * processing incoming acks. -+ * -+ * In case of app-limited, if there is no congestion (loss/ecn) and -+ * if observed bw sample is less than current estimated bw, then we can -+ * skip some of the computation in bbr state processing: -+ * -+ * - if there is no rtt/mode/phase change: In this case, since all the -+ * parameters of the network model are constant, we can skip model -+ * as well control update. -+ * -+ * - else we can skip rest of the model update. But we still need to -+ * update the control to account for the new rtt/mode/phase. -+ * -+ * Returns whether we can take fast path or not. -+ */ -+static bool bbr_run_fast_path(struct sock *sk, bool *update_model, -+ const struct rate_sample *rs, struct bbr_context *ctx) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ u32 prev_min_rtt_us, prev_mode; -+ -+ if (bbr_param(sk, fast_path) && bbr->try_fast_path && -+ rs->is_app_limited && ctx->sample_bw < bbr_max_bw(sk) && -+ !bbr->loss_in_round && !bbr->ecn_in_round ) { -+ prev_mode = bbr->mode; -+ prev_min_rtt_us = bbr->min_rtt_us; -+ bbr_check_drain(sk, rs, ctx); -+ bbr_update_cycle_phase(sk, rs, ctx); -+ bbr_update_min_rtt(sk, rs); -+ -+ if (bbr->mode == prev_mode && -+ bbr->min_rtt_us == prev_min_rtt_us && -+ bbr->try_fast_path) { -+ return true; -+ } -+ -+ /* Skip model update, but control still needs to be updated */ -+ *update_model = false; -+ } -+ return false; -+} -+ -+__bpf_kfunc static void bbr_main(struct sock *sk, u32 ack, int flag, -+ const struct rate_sample *rs) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ struct bbr_context ctx = { 0 }; -+ bool update_model = true; -+ u32 bw, round_delivered; -+ int ce_ratio = -1; -+ -+ round_delivered = bbr_update_round_start(sk, rs, &ctx); -+ if (bbr->round_start) { -+ bbr->rounds_since_probe = -+ min_t(s32, bbr->rounds_since_probe + 1, 0xFF); -+ ce_ratio = bbr_update_ecn_alpha(sk); -+ } -+ bbr_plb(sk, rs, ce_ratio); -+ -+ bbr->ecn_in_round |= (bbr->ecn_eligible && rs->is_ece); -+ bbr_calculate_bw_sample(sk, rs, &ctx); -+ bbr_update_latest_delivery_signals(sk, rs, &ctx); -+ -+ if (bbr_run_fast_path(sk, &update_model, rs, &ctx)) -+ goto out; -+ -+ if (update_model) -+ bbr_update_model(sk, rs, &ctx); -+ -+ bbr_update_gains(sk); -+ bw = bbr_bw(sk); -+ bbr_set_pacing_rate(sk, bw, bbr->pacing_gain); -+ bbr_set_cwnd(sk, rs, rs->acked_sacked, bw, bbr->cwnd_gain, -+ tcp_snd_cwnd(tp), &ctx); -+ bbr_bound_cwnd_for_inflight_model(sk); -+ -+out: -+ bbr_advance_latest_delivery_signals(sk, rs, &ctx); -+ bbr->prev_ca_state = inet_csk(sk)->icsk_ca_state; -+ bbr->loss_in_cycle |= rs->lost > 0; -+ bbr->ecn_in_cycle |= rs->delivered_ce > 0; -+} -+ -+__bpf_kfunc static void bbr_init(struct sock *sk) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ bbr->initialized = 1; -+ -+ bbr->init_cwnd = min(0x7FU, tcp_snd_cwnd(tp)); -+ bbr->prior_cwnd = tp->prior_cwnd; -+ WRITE_ONCE(tp->snd_ssthresh, TCP_INFINITE_SSTHRESH); -+ bbr->next_rtt_delivered = tp->delivered; -+ bbr->prev_ca_state = TCP_CA_Open; -+ -+ bbr->probe_rtt_done_stamp = 0; -+ bbr->probe_rtt_round_done = 0; -+ bbr->probe_rtt_min_us = tcp_min_rtt(tp); -+ bbr->probe_rtt_min_stamp = tcp_jiffies32; -+ bbr->min_rtt_us = tcp_min_rtt(tp); -+ bbr->min_rtt_stamp = tcp_jiffies32; -+ -+ bbr->has_seen_rtt = 0; -+ bbr_init_pacing_rate_from_rtt(sk); -+ -+ bbr->round_start = 0; -+ bbr->idle_restart = 0; -+ bbr->full_bw_reached = 0; -+ bbr->full_bw = 0; -+ bbr->full_bw_cnt = 0; -+ bbr->cycle_mstamp = 0; -+ bbr->cycle_idx = 0; -+ -+ bbr_reset_startup_mode(sk); -+ -+ bbr->ack_epoch_mstamp = tp->tcp_mstamp; -+ bbr->ack_epoch_acked = 0; -+ bbr->extra_acked_win_rtts = 0; -+ bbr->extra_acked_win_idx = 0; -+ bbr->extra_acked[0] = 0; -+ bbr->extra_acked[1] = 0; -+ -+ bbr->ce_state = 0; -+ bbr->prior_rcv_nxt = tp->rcv_nxt; -+ bbr->try_fast_path = 0; -+ -+ cmpxchg(&sk->sk_pacing_status, SK_PACING_NONE, SK_PACING_NEEDED); -+ -+ /* Start sampling ECN mark rate after first full flight is ACKed: */ -+ bbr->loss_round_delivered = tp->delivered + 1; -+ bbr->loss_round_start = 0; -+ bbr->undo_bw_lo = 0; -+ bbr->undo_inflight_lo = 0; -+ bbr->undo_inflight_hi = 0; -+ bbr->loss_events_in_round = 0; -+ bbr->startup_ecn_rounds = 0; -+ bbr_reset_congestion_signals(sk); -+ bbr->bw_lo = ~0U; -+ bbr->bw_hi[0] = 0; -+ bbr->bw_hi[1] = 0; -+ bbr->inflight_lo = ~0U; -+ bbr->inflight_hi = ~0U; -+ bbr_reset_full_bw(sk); -+ bbr->bw_probe_up_cnt = ~0U; -+ bbr->bw_probe_up_acks = 0; -+ bbr->bw_probe_up_rounds = 0; -+ bbr->probe_wait_us = 0; -+ bbr->stopped_risky_probe = 0; -+ bbr->ack_phase = BBR_ACKS_INIT; -+ bbr->rounds_since_probe = 0; -+ bbr->bw_probe_samples = 0; -+ bbr->prev_probe_too_high = 0; -+ bbr->ecn_eligible = 0; -+ bbr->ecn_alpha = bbr_param(sk, ecn_alpha_init); -+ bbr->alpha_last_delivered = 0; -+ bbr->alpha_last_delivered_ce = 0; -+ bbr->plb.pause_until = 0; -+ -+ tp->fast_ack_mode = bbr_fast_ack_mode ? 1 : 0; -+ -+ if (bbr_can_use_ecn(sk)) -+ tp->ecn_flags |= TCP_ECN_ECT_PERMANENT; -+} -+ -+/* BBR marks the current round trip as a loss round. */ -+static void bbr_note_loss(struct sock *sk) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ /* Capture "current" data over the full round trip of loss, to -+ * have a better chance of observing the full capacity of the path. -+ */ -+ if (!bbr->loss_in_round) /* first loss in this round trip? */ -+ bbr->loss_round_delivered = tp->delivered; /* set round trip */ -+ bbr->loss_in_round = 1; -+ bbr->loss_in_cycle = 1; -+} -+ -+/* Core TCP stack informs us that the given skb was just marked lost. */ -+__bpf_kfunc static void bbr_skb_marked_lost(struct sock *sk, -+ const struct sk_buff *skb) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ struct tcp_skb_cb *scb = TCP_SKB_CB(skb); -+ struct rate_sample rs = {}; -+ -+ bbr_note_loss(sk); -+ -+ if (!bbr->bw_probe_samples) -+ return; /* not an skb sent while probing for bandwidth */ -+ if (unlikely(!scb->tx.delivered_mstamp)) -+ return; /* skb was SACKed, reneged, marked lost; ignore it */ -+ /* We are probing for bandwidth. Construct a rate sample that -+ * estimates what happened in the flight leading up to this lost skb, -+ * then see if the loss rate went too high, and if so at which packet. -+ */ -+ rs.tx_in_flight = scb->tx.in_flight; -+ rs.lost = tp->lost - scb->tx.lost; -+ rs.is_app_limited = scb->tx.is_app_limited; -+ if (bbr_is_inflight_too_high(sk, &rs)) { -+ rs.tx_in_flight = bbr_inflight_hi_from_lost_skb(sk, &rs, skb); -+ bbr_handle_inflight_too_high(sk, &rs); -+ } -+} -+ -+static void bbr_run_loss_probe_recovery(struct sock *sk) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ struct rate_sample rs = {0}; -+ -+ bbr_note_loss(sk); -+ -+ if (!bbr->bw_probe_samples) -+ return; /* not sent while probing for bandwidth */ -+ /* We are probing for bandwidth. Construct a rate sample that -+ * estimates what happened in the flight leading up to this -+ * loss, then see if the loss rate went too high. -+ */ -+ rs.lost = 1; /* TLP probe repaired loss of a single segment */ -+ rs.tx_in_flight = bbr->inflight_latest + rs.lost; -+ rs.is_app_limited = tp->tlp_orig_data_app_limited; -+ if (bbr_is_inflight_too_high(sk, &rs)) -+ bbr_handle_inflight_too_high(sk, &rs); -+} -+ -+/* Revert short-term model if current loss recovery event was spurious. */ -+__bpf_kfunc static u32 bbr_undo_cwnd(struct sock *sk) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ bbr_reset_full_bw(sk); /* spurious slow-down; reset full bw detector */ -+ bbr->loss_in_round = 0; -+ -+ /* Revert to cwnd and other state saved before loss episode. */ -+ bbr->bw_lo = max(bbr->bw_lo, bbr->undo_bw_lo); -+ bbr->inflight_lo = max(bbr->inflight_lo, bbr->undo_inflight_lo); -+ bbr->inflight_hi = max(bbr->inflight_hi, bbr->undo_inflight_hi); -+ bbr->try_fast_path = 0; /* take slow path to set proper cwnd, pacing */ -+ return bbr->prior_cwnd; -+} -+ -+/* Entering loss recovery, so save state for when we undo recovery. */ -+__bpf_kfunc static u32 bbr_ssthresh(struct sock *sk) -+{ -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ bbr_save_cwnd(sk); -+ /* For undo, save state that adapts based on loss signal. */ -+ bbr->undo_bw_lo = bbr->bw_lo; -+ bbr->undo_inflight_lo = bbr->inflight_lo; -+ bbr->undo_inflight_hi = bbr->inflight_hi; -+ return tcp_sk(sk)->snd_ssthresh; -+} -+ -+static enum tcp_bbr_phase bbr_get_phase(struct bbr *bbr) -+{ -+ switch (bbr->mode) { -+ case BBR_STARTUP: -+ return BBR_PHASE_STARTUP; -+ case BBR_DRAIN: -+ return BBR_PHASE_DRAIN; -+ case BBR_PROBE_BW: -+ break; -+ case BBR_PROBE_RTT: -+ return BBR_PHASE_PROBE_RTT; -+ default: -+ return BBR_PHASE_INVALID; -+ } -+ switch (bbr->cycle_idx) { -+ case BBR_BW_PROBE_UP: -+ return BBR_PHASE_PROBE_BW_UP; -+ case BBR_BW_PROBE_DOWN: -+ return BBR_PHASE_PROBE_BW_DOWN; -+ case BBR_BW_PROBE_CRUISE: -+ return BBR_PHASE_PROBE_BW_CRUISE; -+ case BBR_BW_PROBE_REFILL: -+ return BBR_PHASE_PROBE_BW_REFILL; -+ default: -+ return BBR_PHASE_INVALID; -+ } -+} -+ -+static size_t bbr_get_info(struct sock *sk, u32 ext, int *attr, -+ union tcp_cc_info *info) -+{ -+ if (ext & (1 << (INET_DIAG_BBRINFO - 1)) || -+ ext & (1 << (INET_DIAG_VEGASINFO - 1))) { -+ struct bbr *bbr = inet_csk_ca(sk); -+ u64 bw = bbr_bw_bytes_per_sec(sk, bbr_bw(sk)); -+ u64 bw_hi = bbr_bw_bytes_per_sec(sk, bbr_max_bw(sk)); -+ u64 bw_lo = bbr->bw_lo == ~0U ? -+ ~0ULL : bbr_bw_bytes_per_sec(sk, bbr->bw_lo); -+ struct tcp_bbr_info *bbr_info = &info->bbr; -+ -+ memset(bbr_info, 0, sizeof(*bbr_info)); -+ bbr_info->bbr_bw_lo = (u32)bw; -+ bbr_info->bbr_bw_hi = (u32)(bw >> 32); -+ bbr_info->bbr_min_rtt = bbr->min_rtt_us; -+ bbr_info->bbr_pacing_gain = bbr->pacing_gain; -+ bbr_info->bbr_cwnd_gain = bbr->cwnd_gain; -+ bbr_info->bbr_bw_hi_lsb = (u32)bw_hi; -+ bbr_info->bbr_bw_hi_msb = (u32)(bw_hi >> 32); -+ bbr_info->bbr_bw_lo_lsb = (u32)bw_lo; -+ bbr_info->bbr_bw_lo_msb = (u32)(bw_lo >> 32); -+ bbr_info->bbr_mode = bbr->mode; -+ bbr_info->bbr_phase = (__u8)bbr_get_phase(bbr); -+ bbr_info->bbr_version = (__u8)BBR_VERSION; -+ bbr_info->bbr_inflight_lo = bbr->inflight_lo; -+ bbr_info->bbr_inflight_hi = bbr->inflight_hi; -+ bbr_info->bbr_extra_acked = bbr_extra_acked(sk); -+ *attr = INET_DIAG_BBRINFO; -+ return sizeof(*bbr_info); -+ } -+ return 0; -+} -+ -+__bpf_kfunc static void bbr_set_state(struct sock *sk, u8 new_state) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ struct bbr *bbr = inet_csk_ca(sk); -+ -+ if (new_state == TCP_CA_Loss) { -+ -+ bbr->prev_ca_state = TCP_CA_Loss; -+ tcp_plb_update_state_upon_rto(sk, &bbr->plb); -+ /* The tcp_write_timeout() call to sk_rethink_txhash() likely -+ * repathed this flow, so re-learn the min network RTT on the -+ * new path: -+ */ -+ bbr_reset_full_bw(sk); -+ if (!bbr_is_probing_bandwidth(sk) && bbr->inflight_lo == ~0U) { -+ /* bbr_adapt_lower_bounds() needs cwnd before -+ * we suffered an RTO, to update inflight_lo: -+ */ -+ bbr->inflight_lo = -+ max(tcp_snd_cwnd(tp), bbr->prior_cwnd); -+ } -+ } else if (bbr->prev_ca_state == TCP_CA_Loss && -+ new_state != TCP_CA_Loss) { -+ bbr_exit_loss_recovery(sk); -+ } -+} -+ -+ -+static struct tcp_congestion_ops tcp_bbr_cong_ops __read_mostly = { -+ .flags = TCP_CONG_NON_RESTRICTED | TCP_CONG_WANTS_CE_EVENTS, -+ .name = "bbr3", -+ .owner = THIS_MODULE, -+ .init = bbr_init, -+ .cong_control = bbr_main, -+ .sndbuf_expand = bbr_sndbuf_expand, -+ .skb_marked_lost = bbr_skb_marked_lost, -+ .undo_cwnd = bbr_undo_cwnd, -+ .cwnd_event = bbr_cwnd_event, -+ .cwnd_event_tx_start = bbr_cwnd_event_tx_start, -+ .ssthresh = bbr_ssthresh, -+ .tso_segs = bbr_tso_segs, -+ .get_info = bbr_get_info, -+ .set_state = bbr_set_state, -+}; -+ -+BTF_KFUNCS_START(tcp_bbr_check_kfunc_ids) -+BTF_ID_FLAGS(func, bbr_init) -+BTF_ID_FLAGS(func, bbr_main) -+BTF_ID_FLAGS(func, bbr_sndbuf_expand) -+BTF_ID_FLAGS(func, bbr_skb_marked_lost) -+BTF_ID_FLAGS(func, bbr_undo_cwnd) -+BTF_ID_FLAGS(func, bbr_cwnd_event) -+BTF_ID_FLAGS(func, bbr_cwnd_event_tx_start) -+BTF_ID_FLAGS(func, bbr_ssthresh) -+BTF_ID_FLAGS(func, bbr_tso_segs) -+BTF_ID_FLAGS(func, bbr_set_state) -+BTF_KFUNCS_END(tcp_bbr_check_kfunc_ids) -+ -+static const struct btf_kfunc_id_set tcp_bbr_kfunc_set = { -+ .owner = THIS_MODULE, -+ .set = &tcp_bbr_check_kfunc_ids, -+}; -+ -+static int __init bbr_register(void) -+{ -+ int ret; -+ -+ BUILD_BUG_ON(sizeof(struct bbr) > ICSK_CA_PRIV_SIZE); -+ -+ ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, &tcp_bbr_kfunc_set); -+ if (ret < 0) -+ return ret; -+ return tcp_register_congestion_control(&tcp_bbr_cong_ops); -+} -+ -+static void __exit bbr_unregister(void) -+{ -+ tcp_unregister_congestion_control(&tcp_bbr_cong_ops); -+} -+ -+module_init(bbr_register); -+module_exit(bbr_unregister); -+ -+MODULE_AUTHOR("Van Jacobson "); -+MODULE_AUTHOR("Neal Cardwell "); -+MODULE_AUTHOR("Yuchung Cheng "); -+MODULE_AUTHOR("Soheil Hassas Yeganeh "); -+MODULE_AUTHOR("Priyaranjan Jha "); -+MODULE_AUTHOR("Yousuk Seung "); -+MODULE_AUTHOR("Kevin Yang "); -+MODULE_AUTHOR("Arjun Roy "); -+MODULE_AUTHOR("David Morley "); -+ -+MODULE_LICENSE("Dual BSD/GPL"); -+MODULE_DESCRIPTION("TCP BBR (Bottleneck Bandwidth and RTT)"); -+MODULE_VERSION(__stringify(BBR_VERSION)); -diff --git a/net/ipv4/tcp_cong.c b/net/ipv4/tcp_cong.c -index e3f462f..6fce9ac 100644 ---- a/net/ipv4/tcp_cong.c -+++ b/net/ipv4/tcp_cong.c -@@ -238,6 +238,7 @@ void tcp_init_congestion_control(struct sock *sk) - struct inet_connection_sock *icsk = inet_csk(sk); - - tcp_sk(sk)->prior_ssthresh = 0; -+ tcp_sk(sk)->fast_ack_mode = 0; - if (icsk->icsk_ca_ops->init) - icsk->icsk_ca_ops->init(sk); - if (tcp_ca_needs_ecn(sk)) -diff --git a/net/ipv4/tcp_input.c b/net/ipv4/tcp_input.c -index 3583867..969a6db 100644 ---- a/net/ipv4/tcp_input.c -+++ b/net/ipv4/tcp_input.c -@@ -358,7 +358,7 @@ static void tcp_data_ecn_check(struct sock *sk, const struct sk_buff *skb) - tcp_enter_quickack_mode(sk, 2); - break; - case INET_ECN_CE: -- if (tcp_ca_needs_ecn(sk)) -+ if (tcp_ca_wants_ce_events(sk)) - tcp_ca_event(sk, CA_EVENT_ECN_IS_CE); - - if (!(tp->ecn_flags & TCP_ECN_DEMAND_CWR) && -@@ -376,7 +376,7 @@ static void tcp_data_ecn_check(struct sock *sk, const struct sk_buff *skb) - tp->ecn_flags |= TCP_ECN_SEEN; - break; - default: -- if (tcp_ca_needs_ecn(sk)) -+ if (tcp_ca_wants_ce_events(sk)) - tcp_ca_event(sk, CA_EVENT_ECN_NO_CE); - if (!tcp_ecn_mode_rfc3168(tp)) - break; -@@ -1323,7 +1323,12 @@ static void tcp_verify_retransmit_hint(struct tcp_sock *tp, struct sk_buff *skb) - */ - static void tcp_notify_skb_loss_event(struct tcp_sock *tp, const struct sk_buff *skb) - { -+ struct sock *sk = (struct sock *)tp; -+ const struct tcp_congestion_ops *ca_ops = inet_csk(sk)->icsk_ca_ops; -+ - tp->lost += tcp_skb_pcount(skb); -+ if (ca_ops->skb_marked_lost) -+ ca_ops->skb_marked_lost(sk, skb); - } - - void tcp_mark_skb_lost(struct sock *sk, struct sk_buff *skb) -@@ -1751,6 +1756,7 @@ static void tcp_rate_gen(struct sock *sk, u32 delivered, u32 lost, - return; - } - rs->delivered = tp->delivered - rs->prior_delivered; -+ rs->lost = tp->lost - rs->prior_lost; - - rs->delivered_ce = tp->delivered_ce - rs->prior_delivered_ce; - /* delivered_ce occupies less than 32 bits in the skb control block */ -@@ -1762,7 +1768,7 @@ static void tcp_rate_gen(struct sock *sk, u32 delivered, u32 lost, - * longer phase. - */ - snd_us = rs->interval_us; /* send phase */ -- ack_us = tcp_stamp_us_delta(tp->tcp_mstamp, -+ ack_us = tcp_stamp32_us_delta(tp->tcp_mstamp, - rs->prior_mstamp); /* ack phase */ - rs->interval_us = max(snd_us, ack_us); - -@@ -1819,19 +1825,21 @@ static void tcp_rate_skb_delivered(struct sock *sk, struct sk_buff *skb, - if (!rs->prior_delivered || - tcp_skb_sent_after(tx_tstamp, tp->first_tx_mstamp, - scb->end_seq, rs->last_end_seq)) { -+ rs->prior_lost = scb->tx.lost; - rs->prior_delivered_ce = scb->tx.delivered_ce; - rs->prior_delivered = scb->tx.delivered; - rs->prior_mstamp = scb->tx.delivered_mstamp; - rs->is_app_limited = scb->tx.is_app_limited; - rs->is_retrans = scb->sacked & TCPCB_RETRANS; -+ rs->tx_in_flight = scb->tx.in_flight; - rs->last_end_seq = scb->end_seq; - - /* Record send time of most recently ACKed packet: */ - tp->first_tx_mstamp = tx_tstamp; - /* Find the duration of the "send phase" of this window: */ -- rs->interval_us = tcp_stamp_us_delta(tp->first_tx_mstamp, -- scb->tx.first_tx_mstamp); -- -+ rs->interval_us = tcp_stamp32_us_delta( -+ tp->first_tx_mstamp, -+ scb->tx.first_tx_mstamp); - } - /* Mark off the skb delivered once it's sacked to avoid being - * used again when it's cumulatively acked. For acked packets -@@ -1874,6 +1882,17 @@ static bool tcp_shifted_skb(struct sock *sk, struct sk_buff *prev, - WARN_ON_ONCE(tcp_skb_pcount(skb) < pcount); - tcp_skb_pcount_add(skb, -pcount); - -+ /* Adjust tx.in_flight as pcount is shifted from skb to prev. */ -+ if (WARN_ONCE(TCP_SKB_CB(skb)->tx.in_flight < pcount, -+ "prev in_flight: %u skb in_flight: %u pcount: %u", -+ TCP_SKB_CB(prev)->tx.in_flight, -+ TCP_SKB_CB(skb)->tx.in_flight, -+ pcount)) -+ TCP_SKB_CB(skb)->tx.in_flight = 0; -+ else -+ TCP_SKB_CB(skb)->tx.in_flight -= pcount; -+ TCP_SKB_CB(prev)->tx.in_flight += pcount; -+ - /* When we're adding to gso_segs == 1, gso_size will be zero, - * in theory this shouldn't be necessary but as long as DSACK - * code can come after this skb later on it's better to keep -@@ -4139,7 +4158,8 @@ static int tcp_replace_ts_recent(struct tcp_sock *tp, u32 seq) - /* This routine deals with acks during a TLP episode and ends an episode by - * resetting tlp_high_seq. Ref: TLP algorithm in RFC8985 - */ --static void tcp_process_tlp_ack(struct sock *sk, u32 ack, int flag) -+static void tcp_process_tlp_ack(struct sock *sk, u32 ack, int flag, -+ struct rate_sample *rs) - { - struct tcp_sock *tp = tcp_sk(sk); - -@@ -4156,6 +4176,7 @@ static void tcp_process_tlp_ack(struct sock *sk, u32 ack, int flag) - /* ACK advances: there was a loss, so reduce cwnd. Reset - * tlp_high_seq in tcp_init_cwnd_reduction() - */ -+ tcp_ca_event(sk, CA_EVENT_TLP_RECOVERY); - tcp_init_cwnd_reduction(sk); - tcp_set_ca_state(sk, TCP_CA_CWR); - tcp_end_cwnd_reduction(sk); -@@ -4166,6 +4187,11 @@ static void tcp_process_tlp_ack(struct sock *sk, u32 ack, int flag) - FLAG_NOT_DUP | FLAG_DATA_SACKED))) { - /* Pure dupack: original and TLP probe arrived; no loss */ - tp->tlp_high_seq = 0; -+ } else { -+ /* This ACK matches a TLP retransmit. We cannot yet tell if -+ * this ACK is for the original or the TLP retransmit. -+ */ -+ rs->is_acking_tlp_retrans_seq = 1; - } - } - -@@ -4339,6 +4365,7 @@ static int tcp_ack(struct sock *sk, const struct sk_buff *skb, int flag) - - prior_fack = tcp_is_sack(tp) ? tcp_highest_sack_seq(tp) : tp->snd_una; - rs.prior_in_flight = tcp_packets_in_flight(tp); -+ tcp_rate_check_app_limited(sk); - - /* ts_recent update must be made after we are sure that the packet - * is in window. -@@ -4411,7 +4438,7 @@ static int tcp_ack(struct sock *sk, const struct sk_buff *skb, int flag) - tcp_in_ack_event(sk, flag); - - if (unlikely(tp->tlp_high_seq)) -- tcp_process_tlp_ack(sk, ack, flag); -+ tcp_process_tlp_ack(sk, ack, flag, &rs); - - if (tcp_ack_is_dubious(sk, flag)) { - if (!(flag & (FLAG_SND_UNA_ADVANCED | -@@ -4436,6 +4463,7 @@ static int tcp_ack(struct sock *sk, const struct sk_buff *skb, int flag) - - lost = tp->lost - lost; /* freshly marked lost */ - rs.is_ack_delayed = !!(flag & FLAG_ACK_MAYBE_DELAYED); -+ rs.is_ece = !!(flag & FLAG_ECE); - tcp_rate_gen(sk, delivered, lost, is_sack_reneg, sack_state.rate); - tcp_cong_control(sk, ack, delivered, flag, sack_state.rate); - tcp_xmit_recovery(sk, rexmit); -@@ -4461,7 +4489,7 @@ static int tcp_ack(struct sock *sk, const struct sk_buff *skb, int flag) - tcp_ack_probe(sk); - - if (unlikely(tp->tlp_high_seq)) -- tcp_process_tlp_ack(sk, ack, flag); -+ tcp_process_tlp_ack(sk, ack, flag, &rs); - return 1; - - old_ack: -@@ -6127,13 +6155,14 @@ static void __tcp_ack_snd_check(struct sock *sk, int ofo_possible) - - /* More than one full frame received... */ - if (((tp->rcv_nxt - tp->rcv_wup) > inet_csk(sk)->icsk_ack.rcv_mss && -+ (tp->fast_ack_mode == 1 || - /* ... and right edge of window advances far enough. - * (tcp_recvmsg() will send ACK otherwise). - * If application uses SO_RCVLOWAT, we want send ack now if - * we have not received enough bytes to satisfy the condition. - */ -- (tp->rcv_nxt - tp->copied_seq < sk->sk_rcvlowat || -- __tcp_select_window(sk) >= tp->rcv_wnd)) || -+ (tp->rcv_nxt - tp->copied_seq < sk->sk_rcvlowat || -+ __tcp_select_window(sk) >= tp->rcv_wnd))) || - /* We ACK each frame or... */ - tcp_in_quickack_mode(sk) || - /* Protocol state mandates a one-time immediate ACK */ -diff --git a/net/ipv4/tcp_minisocks.c b/net/ipv4/tcp_minisocks.c -index 0ddfd5a..72c2780 100644 ---- a/net/ipv4/tcp_minisocks.c -+++ b/net/ipv4/tcp_minisocks.c -@@ -500,6 +500,8 @@ void tcp_ca_openreq_child(struct sock *sk, const struct dst_entry *dst) - u32 ca_key = dst_metric(dst, RTAX_CC_ALGO); - bool ca_got_dst = false; - -+ tcp_set_ecn_low_from_dst(sk, dst); -+ - if (ca_key != TCP_CA_UNSPEC) { - const struct tcp_congestion_ops *ca; - -diff --git a/net/ipv4/tcp_output.c b/net/ipv4/tcp_output.c -index 9f47b66..7982197 100644 ---- a/net/ipv4/tcp_output.c -+++ b/net/ipv4/tcp_output.c -@@ -365,7 +365,8 @@ static void tcp_ecn_send(struct sock *sk, struct sk_buff *skb, - th->cwr = 1; - skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN; - } -- } else if (!tcp_ca_needs_ecn(sk)) { -+ } else if (!(tp->ecn_flags & TCP_ECN_ECT_PERMANENT) && -+ !tcp_ca_needs_ecn(sk)) { - /* ACK or retransmitted segment: clear ECT|CE */ - INET_ECN_dontxmit(sk); - } -@@ -1467,6 +1468,24 @@ static void tcp_update_skb_after_send(struct sock *sk, struct sk_buff *skb, - list_move_tail(&skb->tcp_tsorted_anchor, &tp->tsorted_sent_queue); - } - -+static void tcp_set_tx_in_flight(struct sock *sk, struct sk_buff *skb) -+{ -+ struct tcp_sock *tp = tcp_sk(sk); -+ u32 in_flight; -+ -+ /* Check, sanitize, and record packets in flight after skb was sent. */ -+ in_flight = tcp_packets_in_flight(tp) + tcp_skb_pcount(skb); -+ if (WARN_ONCE(in_flight > TCPCB_IN_FLIGHT_MAX, -+ "insane in_flight %u cc %s mss %u " -+ "cwnd %u pif %u %u %u %u\n", -+ in_flight, inet_csk(sk)->icsk_ca_ops->name, -+ tp->mss_cache, tp->snd_cwnd, -+ tp->packets_out, tp->retrans_out, -+ tp->sacked_out, tp->lost_out)) -+ in_flight = TCPCB_IN_FLIGHT_MAX; -+ TCP_SKB_CB(skb)->tx.in_flight = in_flight; -+} -+ - /* Snapshot the current delivery information in the skb, to generate - * a rate sample later when the skb is (s)acked in tcp_rate_skb_delivered(). - */ -@@ -1499,7 +1518,9 @@ static void tcp_rate_skb_sent(struct sock *sk, struct sk_buff *skb) - TCP_SKB_CB(skb)->tx.delivered_mstamp = tp->delivered_mstamp; - TCP_SKB_CB(skb)->tx.delivered = tp->delivered; - TCP_SKB_CB(skb)->tx.delivered_ce = tp->delivered_ce; -+ TCP_SKB_CB(skb)->tx.lost = tp->lost; - TCP_SKB_CB(skb)->tx.is_app_limited = tp->app_limited ? 1 : 0; -+ tcp_set_tx_in_flight(sk, skb); - } - - INDIRECT_CALLABLE_DECLARE(int ip_queue_xmit(struct sock *sk, struct sk_buff *skb, struct flowi *fl)); -@@ -1847,7 +1868,7 @@ int tcp_fragment(struct sock *sk, enum tcp_queue tcp_queue, - { - struct tcp_sock *tp = tcp_sk(sk); - struct sk_buff *buff; -- int old_factor; -+ int old_factor, inflight_prev; - long limit; - u16 flags; - int nlen; -@@ -1922,6 +1943,30 @@ int tcp_fragment(struct sock *sk, enum tcp_queue tcp_queue, - - if (diff) - tcp_adjust_pcount(sk, skb, diff); -+ -+ inflight_prev = TCP_SKB_CB(skb)->tx.in_flight - old_factor; -+ if (inflight_prev < 0) { -+ WARN_ONCE(tcp_skb_tx_in_flight_is_suspicious( -+ old_factor, -+ TCP_SKB_CB(skb)->sacked, -+ TCP_SKB_CB(skb)->tx.in_flight), -+ "inconsistent: tx.in_flight: %u " -+ "old_factor: %d mss: %u sacked: %u " -+ "1st pcount: %d 2nd pcount: %d " -+ "1st len: %u 2nd len: %u ", -+ TCP_SKB_CB(skb)->tx.in_flight, old_factor, -+ mss_now, TCP_SKB_CB(skb)->sacked, -+ tcp_skb_pcount(skb), tcp_skb_pcount(buff), -+ skb->len, buff->len); -+ inflight_prev = 0; -+ } -+ /* Set 1st tx.in_flight as if 1st were sent by itself: */ -+ TCP_SKB_CB(skb)->tx.in_flight = inflight_prev + -+ tcp_skb_pcount(skb); -+ /* Set 2nd tx.in_flight with new 1st and 2nd pcounts: */ -+ TCP_SKB_CB(buff)->tx.in_flight = inflight_prev + -+ tcp_skb_pcount(skb) + -+ tcp_skb_pcount(buff); - } - - /* Link BUFF into the send queue. */ -@@ -2276,13 +2321,12 @@ static u32 tcp_tso_autosize(const struct sock *sk, unsigned int mss_now, - static u32 tcp_tso_segs(struct sock *sk, unsigned int mss_now) - { - const struct tcp_congestion_ops *ca_ops = inet_csk(sk)->icsk_ca_ops; -- u32 min_tso, tso_segs; -- -- min_tso = ca_ops->min_tso_segs ? -- ca_ops->min_tso_segs(sk) : -- READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_min_tso_segs); -+ u32 tso_segs; - -- tso_segs = tcp_tso_autosize(sk, mss_now, min_tso); -+ tso_segs = ca_ops->tso_segs ? -+ ca_ops->tso_segs(sk, mss_now) : -+ tcp_tso_autosize(sk, mss_now, -+ sock_net(sk)->ipv4.sysctl_tcp_min_tso_segs); - return min_t(u32, tso_segs, sk->sk_gso_max_segs); - } - -@@ -3000,6 +3044,7 @@ static bool tcp_write_xmit(struct sock *sk, unsigned int mss_now, int nonagle, - skb_set_delivery_time(skb, tp->tcp_wstamp_ns, SKB_CLOCK_MONOTONIC); - list_move_tail(&skb->tcp_tsorted_anchor, &tp->tsorted_sent_queue); - tcp_init_tso_segs(skb, mss_now); -+ tcp_set_tx_in_flight(sk, skb); - goto repair; /* Skip network transmission */ - } - -@@ -3212,6 +3257,7 @@ void tcp_send_loss_probe(struct sock *sk) - if (WARN_ON(!skb || !tcp_skb_pcount(skb))) - goto rearm_timer; - -+ tp->tlp_orig_data_app_limited = TCP_SKB_CB(skb)->tx.is_app_limited; - if (__tcp_retransmit_skb(sk, skb, 1)) - goto rearm_timer; - -diff --git a/net/ipv4/tcp_timer.c b/net/ipv4/tcp_timer.c -index e56eae4..db33717 100644 ---- a/net/ipv4/tcp_timer.c -+++ b/net/ipv4/tcp_timer.c -@@ -708,6 +708,7 @@ void tcp_write_timer_handler(struct sock *sk) - tcp_timeout_expires(sk)); - return; - } -+ tcp_rate_check_app_limited(sk); - tcp_mstamp_refresh(tcp_sk(sk)); - event = icsk->icsk_pending; - -diff --git a/tools/testing/selftests/bpf/progs/tcp_ca_kfunc.c b/tools/testing/selftests/bpf/progs/tcp_ca_kfunc.c -index 0a3e9d3..4fb0a59 100644 ---- a/tools/testing/selftests/bpf/progs/tcp_ca_kfunc.c -+++ b/tools/testing/selftests/bpf/progs/tcp_ca_kfunc.c -@@ -8,6 +8,7 @@ extern void bbr_init(struct sock *sk) __ksym; - extern void bbr_main(struct sock *sk, u32 ack, int flag, const struct rate_sample *rs) __ksym; - extern u32 bbr_sndbuf_expand(struct sock *sk) __ksym; - extern u32 bbr_undo_cwnd(struct sock *sk) __ksym; -+extern void bbr_cwnd_event(struct sock *sk, enum tcp_ca_event event) __ksym; - extern void bbr_cwnd_event_tx_start(struct sock *sk) __ksym; - extern u32 bbr_ssthresh(struct sock *sk) __ksym; - extern u32 bbr_min_tso_segs(struct sock *sk) __ksym; -@@ -70,6 +71,7 @@ u32 BPF_PROG(undo_cwnd, struct sock *sk) - SEC("struct_ops") - void BPF_PROG(cwnd_event, struct sock *sk, enum tcp_ca_event event) - { -+ bbr_cwnd_event(sk, event); - dctcp_cwnd_event(sk, event); - } - diff --git a/patches/7.3.5/0002-sched-bore-7.0.0.patch b/patches/7.3.5/0002-sched-bore-7.0.0.patch deleted file mode 100644 index 4f47c2f..0000000 --- a/patches/7.3.5/0002-sched-bore-7.0.0.patch +++ /dev/null @@ -1,1409 +0,0 @@ -From 8e0f25bdcc68fa437072260acc6b4347ece2a794 Mon Sep 17 00:00:00 2001 -From: Masahito S -Date: Sat, 19 Sep 2026 00:31:35 +0900 -Subject: [PATCH] sched-bore-7.0.0-rebased-for-7.3.5 - -Rebased onto v7.3.5 (linux-libre 7.3.5 + 0001-zen-7.3.5-zen1). Two conflict -sites were resolved by hand: - - * kernel/sched/fair.c: the CONFIG_SCHED_BORE base-slice definitions are - nested inside the existing CONFIG_ZEN_INTERACTIVE block, so BORE wins - when it is enabled and zen's 400000/700000 values are kept otherwise. - * kernel/sched/debug.c: base_slice_ns / min_base_slice_ns and the - tunable_scaling helper are placed inside zen's existing - #ifndef CONFIG_SCHED_ALT regions. - -Signed-off-by: Masahito S ---- - include/linux/sched.h | 29 +++ - include/linux/sched/bore.h | 64 ++++++ - init/Kconfig | 17 ++ - kernel/Kconfig.hz | 17 ++ - kernel/exit.c | 4 + - kernel/fork.c | 13 ++ - kernel/futex/waitwake.c | 11 + - kernel/sched/Makefile | 1 + - kernel/sched/bore.c | 530 +++++++++++++++++++++++++++++++++++++++++++ - kernel/sched/build_utility.c | 4 + - kernel/sched/core.c | 12 + - kernel/sched/debug.c | 61 +++++ - kernel/sched/fair.c | 188 ++++++++++++++- - kernel/sched/sched.h | 9 + - 14 files changed, 948 insertions(+), 12 deletions(-) - -diff --git a/include/linux/sched.h b/include/linux/sched.h -index 2d1fa5440..8a7bfc9a4 100644 ---- a/include/linux/sched.h -+++ b/include/linux/sched.h -@@ -832,6 +832,32 @@ struct task_ipi_mask { - struct task_ipi_mask { }; - #endif - -+#ifdef CONFIG_SCHED_BORE -+#define BORE_BC_TIMESTAMP_SHIFT 16 -+ -+struct bore_bc { -+ union { -+ struct { -+ u64 timestamp: 48; -+ u64 penalty: 16; -+ }; -+ u64 value; -+ }; -+}; -+ -+struct bore_ctx { -+ u64 burst_time; -+ u64 credit_sleep; -+ u16 prev_penalty; -+ u16 curr_penalty; -+ u16 penalty; -+ bool stop_update; -+ bool futex_waiting; -+ struct bore_bc subtree; -+ struct bore_bc group; -+}; -+#endif /* CONFIG_SCHED_BORE */ -+ - struct task_struct { - #ifdef CONFIG_THREAD_INFO_IN_TASK - /* -@@ -915,6 +941,9 @@ struct task_struct { - #ifdef CONFIG_SCHED_CLASS_EXT - struct sched_ext_entity scx; - #endif -+#ifdef CONFIG_SCHED_BORE -+ struct bore_ctx bore; -+#endif /* CONFIG_SCHED_BORE */ - const struct sched_class *sched_class; - - #ifdef CONFIG_SCHED_CORE -diff --git a/include/linux/sched/bore.h b/include/linux/sched/bore.h -new file mode 100644 -index 000000000..017207fb8 ---- /dev/null -+++ b/include/linux/sched/bore.h -@@ -0,0 +1,64 @@ -+#ifndef _KERNEL_SCHED_BORE_H -+#define _KERNEL_SCHED_BORE_H -+ -+#include -+#include -+#include -+#include -+#include -+#include -+ -+#define SCHED_BORE_AUTHOR "Masahito Suzuki" -+#define SCHED_BORE_PROGNAME "BORE CPU Scheduler modification" -+ -+#define SCHED_BORE_VERSION "7.0.0" -+ -+extern u8 __read_mostly sched_bore; -+DECLARE_STATIC_KEY_TRUE(sched_bore_key); -+extern u8 __read_mostly sched_burst_inherit_type; -+extern u8 __read_mostly sched_burst_smoothness; -+extern u8 __read_mostly sched_burst_penalty_offset; -+extern uint __read_mostly sched_burst_penalty_scale; -+extern uint __read_mostly sched_burst_cache_lifetime; -+extern u8 __read_mostly sched_burst_protect_slice_lv; -+ -+extern uint __read_mostly sched_credit_cap_us; -+DECLARE_STATIC_KEY_FALSE(sched_credit_key); -+ -+extern void bore_note_sleep(struct task_struct *p, u64 now); -+extern u64 bore_credit_ns(struct task_struct *p); -+ -+DECLARE_STATIC_KEY_TRUE(sched_burst_protect_slice_cond_key); -+DECLARE_STATIC_KEY_FALSE(sched_burst_protect_slice_prefer_key); -+ -+static inline u8 bore_score(struct task_struct *p) -+{ return p->bore.penalty >> 8; } -+ -+extern u8 effective_prio_bore(struct task_struct *p); -+extern void update_curr_bore(struct task_struct *p, u64 delta_exec); -+extern void restart_burst_bore(struct task_struct *p); -+extern void restart_burst_rescale_deadline_bore(struct task_struct *p); -+extern void task_fork_bore(struct task_struct *p, struct task_struct *parent, -+ u64 clone_flags, u64 now); -+extern void sched_init_bore(void); -+extern void reset_task_bore(struct task_struct *p); -+ -+extern int sched_bore_update_handler(const struct ctl_table *table, -+ int write, void __user *buffer, size_t *lenp, loff_t *ppos); -+extern int sched_burst_inherit_type_update_handler(const struct ctl_table *table, -+ int write, void __user *buffer, size_t *lenp, loff_t *ppos); -+extern int sched_burst_protect_slice_lv_update_handler(const struct ctl_table *table, -+ int write, void __user *buffer, size_t *lenp, loff_t *ppos); -+extern int sched_credit_cap_us_update_handler(const struct ctl_table *table, -+ int write, void __user *buffer, size_t *lenp, loff_t *ppos); -+ -+/* -+ * v7.3 split the old reweight_entity() into reweight_entity() (raw se->load -+ * plus PELT) and reweight_eevdf() (the flattened EEVDF se->h_load carried on -+ * the root cfs_rq). reweight_task_fair() is the single entry point that keeps -+ * both halves consistent, so BORE drives that instead. -+ */ -+extern void reweight_task_fair(struct rq *rq, struct task_struct *p, -+ const struct load_weight *lw); -+ -+#endif /* _KERNEL_SCHED_BORE_H */ -diff --git a/init/Kconfig b/init/Kconfig -index 0f0ca9497..968ef263c 100644 ---- a/init/Kconfig -+++ b/init/Kconfig -@@ -1600,6 +1600,23 @@ config CHECKPOINT_RESTORE - - If unsure, say N here. - -+config SCHED_BORE -+ bool "Burst-Oriented Response Enhancer" -+ default y -+ help -+ In Desktop and Mobile computing, one might prefer interactive -+ tasks to keep responsive no matter what they run in the background. -+ -+ Enabling this kernel feature modifies the scheduler to discriminate -+ tasks by their burst time (runtime since it last went sleeping or -+ yielding state) and prioritize those that run less bursty. -+ Such tasks usually include window compositor, widgets backend, -+ terminal emulator, video playback, games and so on. -+ With a little impact to scheduling fairness, it may improve -+ responsiveness especially under heavy background workload. -+ -+ If unsure, say Y here. -+ - config SCHED_AUTOGROUP - bool "Automatic process group scheduling" - depends on !SCHED_ALT -diff --git a/kernel/Kconfig.hz b/kernel/Kconfig.hz -index ce1435cb0..9eee2005e 100644 ---- a/kernel/Kconfig.hz -+++ b/kernel/Kconfig.hz -@@ -57,3 +57,20 @@ config HZ - - config SCHED_HRTICK - def_bool HIGH_RES_TIMERS -+ -+config MIN_BASE_SLICE_NS -+ int "Default value for min_base_slice_ns" -+ default 2000000 -+ help -+ The BORE Scheduler automatically calculates the optimal base -+ slice for the configured HZ using the following equation: -+ -+ base_slice_ns = -+ 1000000000/HZ * DIV_ROUNDUP(min_base_slice_ns, 1000000000/HZ) -+ -+ This option sets the default lower bound limit of the base slice -+ to prevent the loss of task throughput due to overscheduling. -+ -+ Setting this value too high can cause the system to boot with -+ an unnecessarily large base slice, resulting in high scheduling -+ latency and poor system responsiveness. -diff --git a/kernel/exit.c b/kernel/exit.c -index 263b422f0..7cc1a36e3 100644 ---- a/kernel/exit.c -+++ b/kernel/exit.c -@@ -146,7 +146,11 @@ static void __unhash_process(struct release_task_post *post, struct task_struct - detach_pid(post->pids, p, PIDTYPE_SID); - - list_del_rcu(&p->tasks); -+#ifdef CONFIG_SCHED_BORE -+ list_del_rcu(&p->sibling); -+#else /* !CONFIG_SCHED_BORE */ - list_del_init(&p->sibling); -+#endif /* CONFIG_SCHED_BORE */ - __this_cpu_dec(process_counts); - } - list_del_rcu(&p->thread_node); -diff --git a/kernel/fork.c b/kernel/fork.c -index 9566b9977..088903782 100644 ---- a/kernel/fork.c -+++ b/kernel/fork.c -@@ -120,6 +120,10 @@ - /* For dup_mmap(). */ - #include "../mm/internal.h" - -+#ifdef CONFIG_SCHED_BORE -+#include -+#endif /* CONFIG_SCHED_BORE */ -+ - #include - - #define CREATE_TRACE_POINTS -@@ -2489,6 +2493,11 @@ __latent_entropy struct task_struct *copy_process( - p->start_time = ktime_get_ns(); - p->start_boottime = ktime_get_boottime_ns(); - -+#ifdef CONFIG_SCHED_BORE -+ if (likely(p->pid)) -+ task_fork_bore(p, current, clone_flags, p->start_time); -+#endif /* CONFIG_SCHED_BORE */ -+ - /* - * Make it visible to the rest of the system, but dont wake it up yet. - * Need tasklist lock for parent etc handling! -@@ -2574,7 +2583,11 @@ __latent_entropy struct task_struct *copy_process( - p->real_parent->signal->is_child_subreaper; - if (clone_flags & CLONE_AUTOREAP) - p->signal->autoreap = 1; -+#ifdef CONFIG_SCHED_BORE -+ list_add_tail_rcu(&p->sibling, &p->real_parent->children); -+#else /* !CONFIG_SCHED_BORE */ - list_add_tail(&p->sibling, &p->real_parent->children); -+#endif /* CONFIG_SCHED_BORE */ - list_add_tail_rcu(&p->tasks, &init_task.tasks); - attach_pid(p, PIDTYPE_TGID); - attach_pid(p, PIDTYPE_PGID); -diff --git a/kernel/futex/waitwake.c b/kernel/futex/waitwake.c -index d4483d15d..7fa31c8d7 100644 ---- a/kernel/futex/waitwake.c -+++ b/kernel/futex/waitwake.c -@@ -4,6 +4,9 @@ - #include - #include - #include -+#ifdef CONFIG_SCHED_BORE -+#include -+#endif /* CONFIG_SCHED_BORE */ - - #include "futex.h" - -@@ -384,7 +387,15 @@ void futex_do_wait(struct futex_q *q, struct hrtimer_sleeper *timeout) - * is no timeout, or if it has yet to expire. - */ - if (!timeout || timeout->task) -+#ifdef CONFIG_SCHED_BORE -+ { -+ current->bore.futex_waiting = true; -+#endif /* CONFIG_SCHED_BORE */ - schedule(); -+#ifdef CONFIG_SCHED_BORE -+ current->bore.futex_waiting = false; -+ } -+#endif /* CONFIG_SCHED_BORE */ - } - __set_current_state(TASK_RUNNING); - } -diff --git a/kernel/sched/Makefile b/kernel/sched/Makefile -index 0c1f4f030..b127506f4 100644 ---- a/kernel/sched/Makefile -+++ b/kernel/sched/Makefile -@@ -46,3 +46,4 @@ obj-y += fair.o - endif - obj-y += build_policy.o - obj-y += build_utility.o -+obj-$(CONFIG_SCHED_BORE) += bore.o -diff --git a/kernel/sched/bore.c b/kernel/sched/bore.c -new file mode 100644 -index 000000000..1a3952271 ---- /dev/null -+++ b/kernel/sched/bore.c -@@ -0,0 +1,530 @@ -+/* -+ * Burst-Oriented Response Enhancer (BORE) CPU Scheduler -+ * Copyright (C) 2021-2025 Masahito Suzuki -+ */ -+#include -+#include -+#include -+#include "sched.h" -+ -+#ifdef CONFIG_SCHED_BORE -+DEFINE_STATIC_KEY_TRUE(sched_bore_key); -+u8 __read_mostly sched_bore = 1; -+u8 __read_mostly sched_burst_inherit_type = 2; -+u8 __read_mostly sched_burst_protect_slice_lv = 1; -+u8 __read_mostly sched_burst_smoothness = 1; -+u8 __read_mostly sched_burst_penalty_offset = 24; -+uint __read_mostly sched_burst_penalty_scale = 1536; -+uint __read_mostly sched_burst_cache_lifetime = 75000000; -+ -+uint __read_mostly sched_credit_cap_us = 16000; -+ -+static int __maybe_unused maxval_prio = 39; -+static int __maybe_unused maxval_6_bits = 63; -+static int __maybe_unused maxval_8_bits = 255; -+static int __maybe_unused maxval_12_bits = 4095; -+static int __maybe_unused maxval_16_bits = 65535; -+static int __maybe_unused maxval_1_million = 1000000; -+ -+#define MAX_BURST_PENALTY ((40U << 8) - 1) -+#define BURST_CACHE_SAMPLE_LIMIT 63 -+#define BURST_CACHE_SCAN_LIMIT (BURST_CACHE_SAMPLE_LIMIT * 2) -+ -+static u32 bore_reciprocal_lut[BURST_CACHE_SAMPLE_LIMIT + 1]; -+ -+DEFINE_STATIC_KEY_TRUE(sched_burst_inherit_key); -+DEFINE_STATIC_KEY_TRUE(sched_burst_ancestor_key); -+DEFINE_STATIC_KEY_TRUE (sched_burst_protect_slice_cond_key); -+DEFINE_STATIC_KEY_FALSE(sched_burst_protect_slice_prefer_key); -+DEFINE_STATIC_KEY_FALSE(sched_credit_key); -+ -+static inline u32 log2p1_u64_u32fp(u64 v, u8 fp) { -+ if (unlikely(!v)) return 0; -+ int clz = __builtin_clzll(v); -+ int exponent = 64 - clz; -+ u32 mantissa = (u32)((v << clz) << 1 >> (64 - fp)); -+ return exponent << fp | mantissa; -+} -+ -+void bore_note_sleep(struct task_struct *p, u64 now) -+{ -+ p->bore.credit_sleep = now; -+} -+ -+u64 bore_credit_ns(struct task_struct *p) -+{ -+ u64 cap = (u64)sched_credit_cap_us * 1000ULL; -+ u64 slept = 0, credit = 0; -+ -+ if (p->bore.credit_sleep) { -+ slept = rq_clock(task_rq(p)) - p->bore.credit_sleep; -+ if ((s64)slept > 0) { -+ p->bore.credit_sleep = 0; -+ credit = slept < cap ? slept : cap; -+ } else { -+ slept = 0; -+ } -+ } -+ -+ return credit; -+} -+ -+static inline u32 calc_burst_penalty(u64 burst_time) { -+ u32 greed = log2p1_u64_u32fp(burst_time, 8), -+ tolerance = sched_burst_penalty_offset << 8; -+ s32 diff = (s32)(greed - tolerance); -+ u32 penalty = diff & ~(diff >> 31); -+ u32 scaled_penalty = penalty * sched_burst_penalty_scale >> 10; -+ s32 overflow = scaled_penalty - MAX_BURST_PENALTY; -+ return scaled_penalty - (overflow & ~(overflow >> 31)); -+} -+ -+static inline u64 rescale_slice(u64 delta, u8 old_prio, u8 new_prio) { -+ u64 unscaled, rescaled; -+ unscaled = mul_u64_u32_shr(delta , sched_prio_to_weight[old_prio], 10); -+ rescaled = mul_u64_u32_shr(unscaled, sched_prio_to_wmult [new_prio], 22); -+ return rescaled; -+} -+ -+static inline u32 binary_smooth(u32 new, u32 old) { -+ u32 is_growing = (new > old); -+ u32 increment = (new - old) * is_growing; -+ u32 shift = sched_burst_smoothness; -+ u32 smoothed = old + ((increment + (1U << shift) - 1) >> shift); -+ return (new & ~(-is_growing)) | (smoothed & (-is_growing)); -+} -+ -+static void reweight_task_by_prio(struct task_struct *p, int prio) { -+ if (task_has_idle_policy(p)) return; -+ -+ struct sched_entity *se = &p->se; -+ struct load_weight lw = { -+ .weight = scale_load(sched_prio_to_weight[prio]), -+ .inv_weight = sched_prio_to_wmult[prio], -+ }; -+ -+ if (se->on_rq) { -+ /* -+ * reweight_task_fair() commits the current task's runtime via -+ * update_curr_fair() first; stop_update keeps that from -+ * re-entering the burst accounting we are in the middle of. -+ */ -+ p->bore.stop_update = true; -+ reweight_task_fair(task_rq(p), p, &lw); -+ p->bore.stop_update = false; -+ } else { -+ se->load.weight = lw.weight; -+ se->load.inv_weight = lw.inv_weight; -+ } -+} -+ -+u8 effective_prio_bore(struct task_struct *p) { -+ int prio = p->static_prio - MAX_RT_PRIO; -+ if (static_branch_likely(&sched_bore_key)) -+ prio += bore_score(p); -+ prio &= ~(prio >> 31); -+ s32 diff = prio - maxval_prio; -+ prio -= (diff & ~(diff >> 31)); -+ return (u8)prio; -+} -+ -+static void update_penalty(struct task_struct *p) { -+ struct bore_ctx *ctx = &p->bore; -+ -+ u8 prev_prio = effective_prio_bore(p); -+ -+ s32 diff = (s32)ctx->curr_penalty - (s32)ctx->prev_penalty; -+ u16 max_val = ctx->curr_penalty - (diff & (diff >> 31)); -+ u32 is_kthread = !!(p->flags & PF_KTHREAD); -+ ctx->penalty = max_val & -(s32)(!is_kthread); -+ -+ u8 new_prio = effective_prio_bore(p); -+ if (new_prio != prev_prio) -+ reweight_task_by_prio(p, new_prio); -+} -+ -+void update_curr_bore(struct task_struct *p, u64 delta_exec) { -+ struct bore_ctx *ctx = &p->bore; -+ if (ctx->stop_update) return; -+ -+ ctx->burst_time += delta_exec; -+ u32 curr_penalty = ctx->curr_penalty = calc_burst_penalty(ctx->burst_time); -+ -+ if (curr_penalty <= ctx->prev_penalty) return; -+ update_penalty(p); -+} -+ -+void restart_burst_bore(struct task_struct *p) { -+ struct bore_ctx *ctx = &p->bore; -+ u32 new_penalty = binary_smooth(ctx->curr_penalty, ctx->prev_penalty); -+ ctx->prev_penalty = new_penalty; -+ ctx->curr_penalty = 0; -+ ctx->burst_time = 0; -+ update_penalty(p); -+} -+ -+void restart_burst_rescale_deadline_bore(struct task_struct *p) { -+ struct sched_entity *se = &p->se; -+ s64 vscaled, vremain = se->deadline - se->vruntime; -+ -+ u8 old_prio = effective_prio_bore(p); -+ restart_burst_bore(p); -+ u8 new_prio = effective_prio_bore(p); -+ -+ if (old_prio > new_prio) { -+ vscaled = rescale_slice(abs(vremain), old_prio, new_prio); -+ if (unlikely(vremain < 0)) -+ vscaled = -vscaled; -+ se->deadline = se->vruntime + vscaled; -+ } -+} -+ -+static inline bool task_is_bore_eligible(struct task_struct *p) -+{return p && p->sched_class == &fair_sched_class && !p->exit_state;} -+ -+#ifndef for_each_child_task -+#define for_each_child_task(p, t) \ -+ list_for_each_entry_rcu(t, &(p)->children, sibling) -+#endif -+ -+static inline u32 count_children_upto2(struct task_struct *p) { -+ struct list_head *head = &p->children; -+ struct list_head *first = READ_ONCE(head->next); -+ struct list_head *second = READ_ONCE(first->next); -+ return (first != head) + (second != head); -+} -+ -+static inline bool burst_cache_expired(struct bore_bc *bc, u64 now) { -+ struct bore_bc bc_val = { .value = READ_ONCE(bc->value) }; -+ u64 timestamp = (u64)bc_val.timestamp << BORE_BC_TIMESTAMP_SHIFT; -+ return now - timestamp > (u64)sched_burst_cache_lifetime; -+} -+ -+static void update_burst_cache(struct bore_bc *bc, -+ struct task_struct *p, u32 count, u32 total, u64 now) { -+ u32 average = (count == 1) ? total : -+ (u32)(((u64)total * bore_reciprocal_lut[count]) >> 32); -+ -+ struct bore_bc new_bc = { -+ .penalty = max(average, p->bore.penalty), -+ .timestamp = now >> BORE_BC_TIMESTAMP_SHIFT -+ }; -+ WRITE_ONCE(bc->value, new_bc.value); -+} -+ -+static u32 inherit_from_parent(struct task_struct *parent, -+ u64 clone_flags, u64 now) { -+ struct bore_bc bc_val; -+ -+ if (clone_flags & CLONE_PARENT) -+ parent = rcu_dereference(parent->real_parent); -+ -+ struct bore_bc *bc = &parent->bore.subtree; -+ -+ if (burst_cache_expired(bc, now)) { -+ struct task_struct *child; -+ u32 count = 0, total = 0, scan_count = 0; -+ for_each_child_task(parent, child) { -+ if (count >= BURST_CACHE_SAMPLE_LIMIT) break; -+ if (scan_count++ >= BURST_CACHE_SCAN_LIMIT) break; -+ -+ if (!task_is_bore_eligible(child)) continue; -+ count++; -+ total += child->bore.penalty; -+ } -+ -+ update_burst_cache(bc, parent, count, total, now); -+ } -+ -+ bc_val.value = READ_ONCE(bc->value); -+ return (u32)bc_val.penalty; -+} -+ -+static u32 inherit_from_ancestor_hub(struct task_struct *parent, -+ u64 clone_flags, u64 now) { -+ struct bore_bc bc_val; -+ struct task_struct *ancestor = parent; -+ u32 sole_child_count = 0; -+ -+ if (clone_flags & CLONE_PARENT) { -+ ancestor = rcu_dereference(ancestor->real_parent); -+ sole_child_count = 1; -+ } -+ -+ for (struct task_struct *next; -+ (next = rcu_dereference(ancestor->real_parent)) != ancestor && -+ count_children_upto2(ancestor) <= sole_child_count; -+ ancestor = next, sole_child_count = 1) {} -+ -+ struct bore_bc *bc = &ancestor->bore.subtree; -+ -+ if (burst_cache_expired(bc, now)) { -+ struct task_struct *direct_child; -+ u32 count = 0, total = 0, scan_count = 0; -+ for_each_child_task(ancestor, direct_child) { -+ if (count >= BURST_CACHE_SAMPLE_LIMIT) break; -+ if (scan_count++ >= BURST_CACHE_SCAN_LIMIT) break; -+ -+ struct task_struct *descendant = direct_child; -+ while (count_children_upto2(descendant) == 1) { -+ struct task_struct *next_descendant = -+ list_first_or_null_rcu(&descendant->children, -+ struct task_struct, sibling); -+ if (!next_descendant) break; -+ descendant = next_descendant; -+ } -+ -+ if (!task_is_bore_eligible(descendant)) continue; -+ count++; -+ total += descendant->bore.penalty; -+ } -+ -+ update_burst_cache(bc, ancestor, count, total, now); -+ } -+ -+ bc_val.value = READ_ONCE(bc->value); -+ return (u32)bc_val.penalty; -+} -+ -+static u32 inherit_from_thread_group(struct task_struct *p, u64 now) { -+ struct bore_bc bc_val; -+ struct task_struct *leader = p->group_leader; -+ struct bore_bc *bc = &leader->bore.group; -+ -+ if (burst_cache_expired(bc, now)) { -+ struct task_struct *sibling; -+ u32 count = 0, total = 0, scan_count = 0; -+ -+ for_each_thread(leader, sibling) { -+ if (count >= BURST_CACHE_SAMPLE_LIMIT) break; -+ if (scan_count++ >= BURST_CACHE_SCAN_LIMIT) break; -+ -+ if (!task_is_bore_eligible(sibling)) continue; -+ count++; -+ total += sibling->bore.penalty; -+ } -+ -+ update_burst_cache(bc, leader, count, total, now); -+ } -+ -+ bc_val.value = READ_ONCE(bc->value); -+ return (u32)bc_val.penalty; -+} -+ -+void task_fork_bore(struct task_struct *p, -+ struct task_struct *parent, u64 clone_flags, u64 now) { -+ if (!static_branch_likely(&sched_bore_key) || !task_is_bore_eligible(p)) return; -+ -+ rcu_read_lock(); -+ struct bore_ctx *ctx = &p->bore; -+ u32 inherited_penalty; -+ if (clone_flags & CLONE_THREAD) -+ inherited_penalty = inherit_from_thread_group(parent, now); -+ else if (static_branch_likely(&sched_burst_inherit_key)) -+ inherited_penalty = static_branch_likely(&sched_burst_ancestor_key)? -+ inherit_from_ancestor_hub(parent, clone_flags, now): -+ inherit_from_parent(parent, clone_flags, now); -+ else -+ inherited_penalty = 0; -+ -+ if (ctx->prev_penalty < inherited_penalty) -+ ctx->prev_penalty = inherited_penalty; -+ ctx->curr_penalty = 0; -+ ctx->burst_time = 0; -+ ctx->stop_update = false; -+ ctx->futex_waiting = false; -+ update_penalty(p); -+ rcu_read_unlock(); -+} -+ -+void reset_task_bore(struct task_struct *p) -+{ memset(&p->bore, 0, sizeof(struct bore_ctx)); } -+ -+static void update_inherit_type(void) { -+ switch(sched_burst_inherit_type) { -+ case 1: -+ static_branch_enable(&sched_burst_inherit_key); -+ static_branch_disable(&sched_burst_ancestor_key); -+ break; -+ case 2: -+ static_branch_enable(&sched_burst_inherit_key); -+ static_branch_enable(&sched_burst_ancestor_key); -+ break; -+ default: -+ static_branch_disable(&sched_burst_inherit_key); -+ break; -+ } -+} -+ -+void __init sched_init_bore(void) { -+ printk(KERN_INFO "%s %s by %s\n", -+ SCHED_BORE_PROGNAME, SCHED_BORE_VERSION, SCHED_BORE_AUTHOR); -+ -+ for (int i = 1; i <= BURST_CACHE_SAMPLE_LIMIT; i++) -+ bore_reciprocal_lut[i] = (u32)div64_u64(0xffffffffULL + i, i); -+ -+ reset_task_bore(&init_task); -+ update_inherit_type(); -+ -+ if (sched_credit_cap_us) -+ static_branch_enable(&sched_credit_key); -+} -+ -+static void readjust_all_task_weights(void) { -+ struct task_struct *task; -+ struct rq *rq; -+ struct rq_flags rf; -+ -+ scoped_guard(write_lock_irq, &tasklist_lock) -+ for_each_process(task) { -+ if (!task_is_bore_eligible(task)) continue; -+ rq = task_rq_lock(task, &rf); -+ update_rq_clock(rq); -+ reweight_task_by_prio(task, effective_prio_bore(task)); -+ task_rq_unlock(rq, task, &rf); -+ } -+} -+ -+int sched_bore_update_handler(const struct ctl_table *table, -+ int write, void __user *buffer, size_t *lenp, loff_t *ppos) { -+ int ret = proc_dou8vec_minmax(table, write, buffer, lenp, ppos); -+ if (ret || !write) -+ return ret; -+ -+ if (sched_bore) -+ static_branch_enable(&sched_bore_key); -+ else -+ static_branch_disable(&sched_bore_key); -+ -+ readjust_all_task_weights(); -+ -+ return 0; -+} -+ -+int sched_burst_inherit_type_update_handler(const struct ctl_table *table, -+ int write, void __user *buffer, size_t *lenp, loff_t *ppos) { -+ int ret = proc_dou8vec_minmax(table, write, buffer, lenp, ppos); -+ if (ret || !write) -+ return ret; -+ -+ update_inherit_type(); -+ -+ return 0; -+} -+ -+int sched_burst_protect_slice_lv_update_handler(const struct ctl_table *table, -+ int write, void __user *buffer, size_t *lenp, loff_t *ppos) { -+ int ret = proc_dou8vec_minmax(table, write, buffer, lenp, ppos); -+ if (ret || !write) -+ return ret; -+ -+ if (sched_burst_protect_slice_lv == 1 || -+ sched_burst_protect_slice_lv == 2) -+ static_branch_enable(&sched_burst_protect_slice_cond_key); -+ else -+ static_branch_disable(&sched_burst_protect_slice_cond_key); -+ -+ if (sched_burst_protect_slice_lv >= 2) -+ static_branch_enable(&sched_burst_protect_slice_prefer_key); -+ else -+ static_branch_disable(&sched_burst_protect_slice_prefer_key); -+ -+ return 0; -+} -+ -+int sched_credit_cap_us_update_handler(const struct ctl_table *table, -+ int write, void __user *buffer, size_t *lenp, loff_t *ppos) { -+ int ret = proc_douintvec_minmax(table, write, buffer, lenp, ppos); -+ if (ret || !write) -+ return ret; -+ -+ if (sched_credit_cap_us) -+ static_branch_enable(&sched_credit_key); -+ else -+ static_branch_disable(&sched_credit_key); -+ -+ return 0; -+} -+ -+#ifdef CONFIG_SYSCTL -+static struct ctl_table sched_bore_sysctls[] = { -+ { -+ .procname = "sched_bore", -+ .data = &sched_bore, -+ .maxlen = sizeof(u8), -+ .mode = 0644, -+ .proc_handler = sched_bore_update_handler, -+ .extra1 = SYSCTL_ZERO, -+ .extra2 = SYSCTL_ONE, -+ }, -+ { -+ .procname = "sched_burst_inherit_type", -+ .data = &sched_burst_inherit_type, -+ .maxlen = sizeof(u8), -+ .mode = 0644, -+ .proc_handler = sched_burst_inherit_type_update_handler, -+ .extra1 = SYSCTL_ZERO, -+ .extra2 = SYSCTL_TWO, -+ }, -+ { -+ .procname = "sched_burst_smoothness", -+ .data = &sched_burst_smoothness, -+ .maxlen = sizeof(u8), -+ .mode = 0644, -+ .proc_handler = proc_dou8vec_minmax, -+ .extra1 = SYSCTL_ZERO, -+ .extra2 = SYSCTL_THREE, -+ }, -+ { -+ .procname = "sched_burst_penalty_offset", -+ .data = &sched_burst_penalty_offset, -+ .maxlen = sizeof(u8), -+ .mode = 0644, -+ .proc_handler = proc_dou8vec_minmax, -+ .extra1 = SYSCTL_ZERO, -+ .extra2 = &maxval_6_bits, -+ }, -+ { -+ .procname = "sched_burst_penalty_scale", -+ .data = &sched_burst_penalty_scale, -+ .maxlen = sizeof(uint), -+ .mode = 0644, -+ .proc_handler = proc_douintvec_minmax, -+ .extra1 = SYSCTL_ZERO, -+ .extra2 = &maxval_12_bits, -+ }, -+ { -+ .procname = "sched_burst_cache_lifetime", -+ .data = &sched_burst_cache_lifetime, -+ .maxlen = sizeof(uint), -+ .mode = 0644, -+ .proc_handler = proc_douintvec, -+ }, -+ { -+ .procname = "sched_burst_protect_slice_lv", -+ .data = &sched_burst_protect_slice_lv, -+ .maxlen = sizeof(u8), -+ .mode = 0644, -+ .proc_handler = sched_burst_protect_slice_lv_update_handler, -+ .extra1 = SYSCTL_ZERO, -+ .extra2 = SYSCTL_THREE, -+ }, -+ { -+ .procname = "sched_credit_cap_us", -+ .data = &sched_credit_cap_us, -+ .maxlen = sizeof(uint), -+ .mode = 0644, -+ .proc_handler = sched_credit_cap_us_update_handler, -+ .extra1 = SYSCTL_ZERO, -+ .extra2 = &maxval_1_million, -+ }, -+}; -+ -+static int __init sched_bore_sysctl_init(void) { -+ register_sysctl_init("kernel", sched_bore_sysctls); -+ return 0; -+} -+late_initcall(sched_bore_sysctl_init); -+ -+#endif // CONFIG_SYSCTL -+#endif /* CONFIG_SCHED_BORE */ -diff --git a/kernel/sched/build_utility.c b/kernel/sched/build_utility.c -index a64bf71a6..6a20c28c0 100644 ---- a/kernel/sched/build_utility.c -+++ b/kernel/sched/build_utility.c -@@ -54,6 +54,10 @@ - #include "stats.h" - #include "autogroup.h" - -+#ifdef CONFIG_SCHED_BORE -+#include -+#endif /* CONFIG_SCHED_BORE */ -+ - #include "clock.c" - - #ifdef CONFIG_SCHED_ALT -diff --git a/kernel/sched/core.c b/kernel/sched/core.c -index 484913595..a8613f0b7 100644 ---- a/kernel/sched/core.c -+++ b/kernel/sched/core.c -@@ -99,6 +99,10 @@ - #include "../smpboot.h" - #include "../locking/mutex.h" - -+#ifdef CONFIG_SCHED_BORE -+#include -+#endif /* CONFIG_SCHED_BORE */ -+ - EXPORT_TRACEPOINT_SYMBOL_GPL(ipi_send_cpu); - EXPORT_TRACEPOINT_SYMBOL_GPL(ipi_send_cpumask); - -@@ -1533,7 +1537,11 @@ int tg_nop(struct task_group *tg, void *data) - - void set_load_weight(struct task_struct *p, bool update_load) - { -+#ifdef CONFIG_SCHED_BORE -+ int prio = effective_prio_bore(p); -+#else /* !CONFIG_SCHED_BORE */ - int prio = p->static_prio - MAX_RT_PRIO; -+#endif /* CONFIG_SCHED_BORE */ - struct load_weight lw; - - if (task_has_idle_policy(p)) { -@@ -8993,6 +9001,10 @@ void __init sched_init(void) - BUG_ON(!sched_class_above(&ext_sched_class, &idle_sched_class)); - #endif - -+#ifdef CONFIG_SCHED_BORE -+ sched_init_bore(); -+#endif /* CONFIG_SCHED_BORE */ -+ - wait_bit_init(); - - #ifdef CONFIG_FAIR_GROUP_SCHED -diff --git a/kernel/sched/debug.c b/kernel/sched/debug.c -index 70b7c3425..61776527a 100644 ---- a/kernel/sched/debug.c -+++ b/kernel/sched/debug.c -@@ -171,6 +171,53 @@ static const struct file_operations sched_feat_fops = { - .release = single_release, - }; - -+#ifdef CONFIG_SCHED_BORE -+#define DEFINE_SYSCTL_SCHED_FUNC(name, update_func) \ -+static ssize_t sched_##name##_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *ppos) \ -+{ \ -+ char buf[16]; \ -+ unsigned int value; \ -+\ -+ if (cnt > 15) \ -+ cnt = 15; \ -+\ -+ if (copy_from_user(&buf, ubuf, cnt)) \ -+ return -EFAULT; \ -+ buf[cnt] = '\0'; \ -+\ -+ if (kstrtouint(buf, 10, &value)) \ -+ return -EINVAL; \ -+\ -+ sysctl_sched_##name = value; \ -+ sched_update_##update_func(); \ -+\ -+ *ppos += cnt; \ -+ return cnt; \ -+} \ -+\ -+static int sched_##name##_show(struct seq_file *m, void *v) \ -+{ \ -+ seq_printf(m, "%d\n", sysctl_sched_##name); \ -+ return 0; \ -+} \ -+\ -+static int sched_##name##_open(struct inode *inode, struct file *filp) \ -+{ \ -+ return single_open(filp, sched_##name##_show, NULL); \ -+} \ -+\ -+static const struct file_operations sched_##name##_fops = { \ -+ .open = sched_##name##_open, \ -+ .write = sched_##name##_write, \ -+ .read = seq_read, \ -+ .llseek = seq_lseek, \ -+ .release = single_release, \ -+}; -+ -+DEFINE_SYSCTL_SCHED_FUNC(min_base_slice, min_base_slice) -+ -+#undef DEFINE_SYSCTL_SCHED_FUNC -+#else /* !CONFIG_SCHED_BORE */ - static ssize_t sched_scaling_write(struct file *filp, const char __user *ubuf, - size_t cnt, loff_t *ppos) - { -@@ -210,6 +257,7 @@ static const struct file_operations sched_scaling_fops = { - .llseek = seq_lseek, - .release = single_release, - }; -+#endif /* CONFIG_SCHED_BORE */ - - #ifdef CONFIG_SCHED_CACHE - static ssize_t -@@ -731,13 +779,20 @@ static __init int sched_init_debug(void) - debugfs_create_file("preempt", 0644, debugfs_sched, NULL, &sched_dynamic_fops); - #endif - -+#ifdef CONFIG_SCHED_BORE -+ debugfs_create_file("min_base_slice_ns", 0644, debugfs_sched, NULL, &sched_min_base_slice_fops); -+ debugfs_create_u32("base_slice_ns", 0444, debugfs_sched, &sysctl_sched_base_slice); -+#else /* !CONFIG_SCHED_BORE */ - debugfs_create_u32("base_slice_ns", 0644, debugfs_sched, &sysctl_sched_base_slice); -+#endif /* CONFIG_SCHED_BORE */ - - #ifndef CONFIG_SCHED_ALT - debugfs_create_u32("latency_warn_ms", 0644, debugfs_sched, &sysctl_resched_latency_warn_ms); - debugfs_create_u32("latency_warn_once", 0644, debugfs_sched, &sysctl_resched_latency_warn_once); - -+#if !defined(CONFIG_SCHED_BORE) - debugfs_create_file("tunable_scaling", 0644, debugfs_sched, NULL, &sched_scaling_fops); -+#endif /* CONFIG_SCHED_BORE */ - debugfs_create_u32("migration_cost_ns", 0644, debugfs_sched, &sysctl_sched_migration_cost); - debugfs_create_u32("nr_migrate", 0644, debugfs_sched, &sysctl_sched_nr_migrate); - -@@ -1008,6 +1063,9 @@ print_task(struct seq_file *m, struct rq *rq, struct task_struct *p) - SPLIT_NS(schedstat_val_or_zero(p->stats.sum_sleep_runtime)), - SPLIT_NS(schedstat_val_or_zero(p->stats.sum_block_runtime))); - -+#ifdef CONFIG_SCHED_BORE -+ SEQ_printf(m, " %2d", bore_score(p)); -+#endif /* CONFIG_SCHED_BORE */ - #ifdef CONFIG_NUMA_BALANCING - SEQ_printf(m, " %d %d", task_node(p), task_numa_group_id(p)); - #endif -@@ -1497,6 +1555,9 @@ void proc_sched_show_task(struct task_struct *p, struct pid_namespace *ns, - __PS("nr_involuntary_switches", p->nivcsw); - - P(se.load.weight); -+#ifdef CONFIG_SCHED_BORE -+ __PS("bore.score", bore_score(p)); -+#endif /* CONFIG_SCHED_BORE */ - P(se.avg.load_sum); - P(se.avg.runnable_sum); - P(se.avg.util_sum); -diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c -index 532c0de5b..c8e019cfe 100644 ---- a/kernel/sched/fair.c -+++ b/kernel/sched/fair.c -@@ -61,6 +61,10 @@ - #include "stats.h" - #include "autogroup.h" - -+#ifdef CONFIG_SCHED_BORE -+#include -+#endif /* CONFIG_SCHED_BORE */ -+ - /* - * The initial- and re-scaling of tunables is configurable - * -@@ -70,9 +74,14 @@ - * SCHED_TUNABLESCALING_LOG - scaled logarithmically, *1+ilog(ncpus) - * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus - * -- * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus)) -+ * BORE : default SCHED_TUNABLESCALING_NONE = *1 constant -+ * EEVDF: default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus)) - */ -+#ifdef CONFIG_SCHED_BORE -+unsigned int sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_NONE; -+#else /* !CONFIG_SCHED_BORE */ - unsigned int sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG; -+#endif /* CONFIG_SCHED_BORE */ - - /* - * Default base time slice (request size r_i) for SCHED_NORMAL/SCHED_BATCH: -@@ -80,15 +89,23 @@ unsigned int sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG; - * Under EEVDF this is the request size used to compute the virtual - * deadline; see update_deadline(). - * -- * (default: 0.70 msec * (1 + ilog(ncpus)), units: nanoseconds) -+ * BORE : base_slice = minimum multiple of nsecs_per_tick >= min_base_slice -+ * (default min_base_slice = 2000000 constant, units: nanoseconds) -+ * EEVDF: default 0.70 msec * (1 + ilog(ncpus)), units: nanoseconds - */ -+#ifdef CONFIG_SCHED_BORE -+static const unsigned int nsecs_per_tick = 1000000000ULL / HZ; -+unsigned int sysctl_sched_min_base_slice = CONFIG_MIN_BASE_SLICE_NS; -+__read_mostly uint sysctl_sched_base_slice = nsecs_per_tick; -+#else /* !CONFIG_SCHED_BORE */ - #ifdef CONFIG_ZEN_INTERACTIVE - unsigned int sysctl_sched_base_slice = 400000ULL; - static unsigned int normalized_sysctl_sched_base_slice = 400000ULL; - #else - unsigned int sysctl_sched_base_slice = 700000ULL; - static unsigned int normalized_sysctl_sched_base_slice = 700000ULL; --#endif -+#endif /* CONFIG_ZEN_INTERACTIVE */ -+#endif /* CONFIG_SCHED_BORE */ - - #ifdef CONFIG_ZEN_INTERACTIVE - __read_mostly unsigned int sysctl_sched_migration_cost = 300000UL; -@@ -208,6 +225,13 @@ static inline void update_load_set(struct load_weight *lw, unsigned long w) - * - * This idea comes from the SD scheduler of Con Kolivas: - */ -+#ifdef CONFIG_SCHED_BORE -+static void update_sysctl(void) { -+ sysctl_sched_base_slice = nsecs_per_tick * -+ max(1UL, DIV_ROUND_UP(sysctl_sched_min_base_slice, nsecs_per_tick)); -+} -+void sched_update_min_base_slice(void) { update_sysctl(); } -+#else /* !CONFIG_SCHED_BORE */ - static unsigned int get_update_sysctl_factor(void) - { - unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8); -@@ -238,6 +262,7 @@ static void update_sysctl(void) - SET_SYSCTL(sched_base_slice); - #undef SET_SYSCTL - } -+#endif /* CONFIG_SCHED_BORE */ - - void __init sched_init_granularity(void) - { -@@ -1140,7 +1165,11 @@ struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq) - */ - static inline void set_protect_slice(struct cfs_rq *cfs_rq, struct sched_entity *se) - { -+#ifdef CONFIG_SCHED_BORE -+ u64 slice = sysctl_sched_base_slice; -+#else /* CONFIG_SCHED_BORE */ - u64 slice = normalized_sysctl_sched_base_slice; -+#endif /* CONFIG_SCHED_BORE */ - u64 vprot = se->deadline; - - if (sched_feat(RUN_TO_PARITY)) -@@ -1224,8 +1253,17 @@ static struct sched_entity *pick_eevdf(struct cfs_rq *cfs_rq, bool protect) - if (curr && (!curr->on_rq || !entity_eligible(cfs_rq, curr))) - curr = NULL; - -- if (curr && protect && protect_slice(curr)) -- return curr; -+ if (curr && protect && protect_slice(curr)) { -+#ifdef CONFIG_SCHED_BORE -+ if (static_branch_likely(&sched_bore_key)) { -+ if ((static_branch_likely(&sched_burst_protect_slice_cond_key) || -+ static_branch_unlikely(&sched_burst_protect_slice_prefer_key)) && -+ (!entity_is_task(curr) || !task_of(curr)->bore.futex_waiting)) -+ return curr; -+ } else -+#endif /* CONFIG_SCHED_BORE */ -+ return curr; -+ } - - /* Pick the leftmost entity if it's eligible */ - if (se && entity_eligible(cfs_rq, se)) { -@@ -1281,6 +1319,7 @@ struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq) - /************************************************************** - * Scheduling class statistics methods: - */ -+#if !defined(CONFIG_SCHED_BORE) - int sched_update_scaling(void) - { - unsigned int factor = get_update_sysctl_factor(); -@@ -1292,6 +1331,7 @@ int sched_update_scaling(void) - - return 0; - } -+#endif /* CONFIG_SCHED_BORE */ - - static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se); - -@@ -2222,6 +2262,41 @@ static void pref_llc_running_dec(struct rq *rq, struct task_struct *p) {} - - #endif /* CONFIG_SCHED_CACHE */ - -+#ifdef CONFIG_SCHED_BORE -+static inline bool do_preempt_weight(struct cfs_rq *cfs_rq, -+ struct sched_entity *pse, struct sched_entity *se) -+{ -+ /* -+ * Companion to the PREEMPT_SHORT path: where that lets a shorter-slice -+ * waker cancel current's slice protection, this lets a heavier (under -+ * BORE: more interactive) waker do so. No RUN_TO_PARITY gate -- in 7.0 -+ * the slice protection (vprot) exists regardless of RUN_TO_PARITY, so -+ * the weight bypass must apply either way. -+ */ -+ if (!static_branch_likely(&sched_bore_key)) -+ return false; -+ -+ if (!static_branch_likely(&sched_burst_protect_slice_cond_key)) -+ return false; -+ -+ if (static_branch_unlikely(&sched_burst_protect_slice_prefer_key) -+ ? (pse->load.weight <= se->load.weight) -+ : (pse->load.weight < se->load.weight)) -+ return false; -+ -+ if (!entity_eligible(cfs_rq, pse)) -+ return false; -+ -+ if (entity_before(pse, se)) -+ return true; -+ -+ if (!entity_eligible(cfs_rq, se)) -+ return true; -+ -+ return false; -+} -+#endif /* CONFIG_SCHED_BORE */ -+ - /* - * Used by other classes to account runtime. - */ -@@ -2263,6 +2338,10 @@ static void update_curr(struct cfs_rq *cfs_rq) - curr->vruntime += calc_delta_fair(delta_exec, curr); - resched = update_deadline(cfs_rq, curr); - -+#ifdef CONFIG_SCHED_BORE -+ update_curr_bore(task_of(curr), delta_exec); -+#endif /* CONFIG_SCHED_BORE */ -+ - /* - * If the fair_server is active, we need to account for the - * fair_server time whether or not the task is running on -@@ -5016,8 +5095,22 @@ unsigned long __calc_prop_weight(struct cfs_rq *cfs_rq, struct sched_entity *se, - return max(weight, MIN_SHARES); - } - -+#ifdef CONFIG_SCHED_BORE -+/* -+ * BORE re-weights a task from its burst penalty and lives in a separate -+ * translation unit (kernel/sched/bore.c), so this must be globally visible. -+ * -+ * Note: in 7.2 BORE poked the old reweight_entity() directly. 7.3 split that -+ * into reweight_entity() (raw se->load + PELT) and reweight_eevdf() (the -+ * flattened EEVDF h_load on the root cfs_rq); reweight_task_fair() is the one -+ * entry point that performs both halves consistently. -+ */ -+void reweight_task_fair(struct rq *rq, struct task_struct *p, -+ const struct load_weight *lw) -+#else /* !CONFIG_SCHED_BORE */ - static void reweight_task_fair(struct rq *rq, struct task_struct *p, - const struct load_weight *lw) -+#endif /* CONFIG_SCHED_BORE */ - { - struct sched_entity *se = &p->se; - unsigned long weight = NICE_0_LOAD; -@@ -6398,14 +6491,13 @@ void __setparam_fair(struct task_struct *p, const struct sched_attr *attr) - static void - place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) - { -- u64 vslice, vruntime = avg_vruntime(cfs_rq); -+ u64 vslice = 0, vruntime = avg_vruntime(cfs_rq); - unsigned int nr_queued = cfs_rq->h_nr_queued; - bool update_zero = false; - s64 lag = 0; - - if (!se->custom_slice) - se->slice = sysctl_sched_base_slice; -- vslice = calc_delta_fair(se->slice, se); - - if (flags & ENQUEUE_QUEUED) - nr_queued -= 1; -@@ -6528,7 +6620,18 @@ place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) - se->rel_deadline = 0; - return; - } -- -+#ifdef CONFIG_SCHED_BORE -+ if (static_branch_likely(&sched_bore_key) && -+ entity_is_task(se) && -+ task_of(se)->bore.futex_waiting) -+ goto vslice_found; -+#endif /* !CONFIG_SCHED_BORE */ -+ vslice = calc_delta_fair(se->slice, se); -+#ifdef CONFIG_SCHED_BORE -+ if (static_branch_likely(&sched_bore_key)) -+ vslice >>= !!(flags & (ENQUEUE_INITIAL | ENQUEUE_WAKEUP)); -+ else -+#endif /* CONFIG_SCHED_BORE */ - /* - * When joining the competition; the existing tasks will be, - * on average, halfway through their slice, as such start tasks -@@ -6537,10 +6640,24 @@ place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) - if (sched_feat(PLACE_DEADLINE_INITIAL) && (flags & ENQUEUE_INITIAL)) - vslice /= 2; - -+#ifdef CONFIG_SCHED_BORE -+vslice_found: -+#endif /* CONFIG_SCHED_BORE */ - /* - * EEVDF: vd_i = ve_i + r_i/w_i - */ - se->deadline = se->vruntime + vslice; -+ -+#ifdef CONFIG_SCHED_BORE -+ if (static_branch_likely(&sched_bore_key) && -+ static_branch_unlikely(&sched_credit_key) && -+ entity_is_task(se) && (flags & ENQUEUE_WAKEUP)) { -+ u64 credit = bore_credit_ns(task_of(se)); -+ -+ if (credit && se->deadline > credit) -+ se->deadline -= credit; -+ } -+#endif /* CONFIG_SCHED_BORE */ - } - - static void check_enqueue_throttle(struct cfs_rq *cfs_rq); -@@ -8148,7 +8265,7 @@ static int choose_idle_cpu(int cpu, struct task_struct *p) - } - - static void --requeue_delayed_entity(struct cfs_rq *cfs_rq, struct sched_entity *se) -+requeue_delayed_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) - { - /* - * se->sched_delayed should imply: se->on_rq == 1. -@@ -8162,7 +8279,13 @@ requeue_delayed_entity(struct cfs_rq *cfs_rq, struct sched_entity *se) - cfs_rq->h_nr_queued--; - if (se != cfs_rq->curr) - __dequeue_entity(cfs_rq, se); -- place_entity(cfs_rq, se, 0); -+#ifdef CONFIG_SCHED_BORE -+ if (static_branch_likely(&sched_bore_key)) -+ flags |= ENQUEUE_WAKEUP; -+ else -+#endif /* CONFIG_SCHED_BORE */ -+ flags = 0; -+ place_entity(cfs_rq, se, flags); - if (se != cfs_rq->curr) - __enqueue_entity(cfs_rq, se); - cfs_rq->h_nr_queued++; -@@ -8250,7 +8373,7 @@ enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags) - update_curr_eevdf(cfs_rq); - - if (flags & ENQUEUE_DELAYED) { -- requeue_delayed_entity(cfs_rq, se); -+ requeue_delayed_entity(cfs_rq, se, flags); - return; - } - -@@ -8270,7 +8393,7 @@ enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags) - place_entity(cfs_rq, se, flags); - - if (se->on_rq && se->sched_delayed) -- requeue_delayed_entity(cfs_rq, se); -+ requeue_delayed_entity(cfs_rq, se, flags); - - weight = enqueue_hierarchy(p, flags); - -@@ -8440,6 +8563,23 @@ static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags) - if (!p->se.sched_delayed) - util_est_dequeue(&rq->cfs, p); - -+#ifdef CONFIG_SCHED_BORE -+ /* -+ * Commit the outstanding runtime of @p before folding the burst into -+ * the smoothed penalty, while @p is still queued (restart_burst_bore() -+ * reweights it). 7.3 flattened the EEVDF tree: the running task entity -+ * is tracked by rq->cfs.curr, and update_curr_eevdf() redirects to the -+ * cfs_rq that actually owns it, so use those rather than the old -+ * cfs_rq_of(&p->se)->curr. -+ */ -+ if (flags & DEQUEUE_SLEEP) { -+ if (rq->cfs.curr == &p->se) -+ update_curr_eevdf(&rq->cfs); -+ bore_note_sleep(p, rq_clock(rq)); -+ restart_burst_bore(p); -+ } -+#endif /* CONFIG_SCHED_BORE */ -+ - if (!__dequeue_task(rq, p, flags)) - return false; - -@@ -10230,6 +10370,18 @@ static void wakeup_preempt_fair(struct rq *rq, struct task_struct *p, int wake_f - goto pick; - } - -+#ifdef CONFIG_SCHED_BORE -+ /* -+ * Likewise, if @p is heavier than current (under BORE: more -+ * interactive), per kernel.sched_burst_protect_slice_lv, override -+ * current's slice protection to allow preemption. -+ */ -+ if (do_preempt_weight(cfs_rq, pse, se)) { -+ preempt_action = PREEMPT_WAKEUP_SHORT; -+ goto pick; -+ } -+#endif -+ - /* - * Ignore wakee preemption on WF_FORK as it is less likely that - * there is shared data as exec often follow fork. -@@ -10399,16 +10551,25 @@ static void yield_task_fair(struct rq *rq) - /* - * Are we the only task in the tree? - */ -+#if !defined(CONFIG_SCHED_BORE) - if (unlikely(rq->nr_running == 1)) - return; - - clear_buddies(cfs_rq, se); -+#endif /* CONFIG_SCHED_BORE */ - - update_rq_clock(rq); - /* - * Update run-time statistics of the 'current'. - */ - update_curr_eevdf(cfs_rq); -+#ifdef CONFIG_SCHED_BORE -+ restart_burst_rescale_deadline_bore(curr); -+ if (unlikely(rq->nr_running == 1)) -+ return; -+ -+ clear_buddies(cfs_rq, se); -+#endif /* CONFIG_SCHED_BORE */ - /* - * Tell update_rq_clock() that we've just updated, - * so we don't do microscopic update in schedule() -@@ -15536,6 +15697,9 @@ static void switched_to_fair(struct rq *rq, struct task_struct *p) - WARN_ON_ONCE(p->se.sched_delayed); - - attach_task_cfs_rq(p); -+#ifdef CONFIG_SCHED_BORE -+ reset_task_bore(p); -+#endif /* CONFIG_SCHED_BORE */ - - set_task_max_allowed_capacity(p); - -diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h -index 11f5b47aa..4f77a09b2 100644 ---- a/kernel/sched/sched.h -+++ b/kernel/sched/sched.h -@@ -2305,7 +2305,11 @@ extern int group_balance_cpu(struct sched_group *sg); - extern void update_sched_domain_debugfs(void); - extern void dirty_sched_domain_sysctl(int cpu); - -+#ifdef CONFIG_SCHED_BORE -+extern void sched_update_min_base_slice(void); -+#else /* !CONFIG_SCHED_BORE */ - extern int sched_update_scaling(void); -+#endif /* CONFIG_SCHED_BORE */ - - static inline const struct cpumask *task_user_cpus(struct task_struct *p) - { -@@ -3151,7 +3155,12 @@ static inline void attach_one_task(struct rq *rq, struct task_struct *p) - extern __read_mostly unsigned int sysctl_sched_nr_migrate; - extern __read_mostly unsigned int sysctl_sched_migration_cost; - -+#ifdef CONFIG_SCHED_BORE -+extern unsigned int sysctl_sched_min_base_slice; -+extern __read_mostly uint sysctl_sched_base_slice; -+#else /* !CONFIG_SCHED_BORE */ - extern unsigned int sysctl_sched_base_slice; -+#endif /* CONFIG_SCHED_BORE */ - - extern int sysctl_resched_latency_warn_ms; - extern int sysctl_resched_latency_warn_once; --- -2.34.1 diff --git a/releases/v7.3.5-zako1/patches/0001-zen-7.3.5-zen1.patch b/releases/v7.3.5-zako1/patches/0001-zen-7.3.5-zen1.patch new file mode 100644 index 0000000..56898e1 --- /dev/null +++ b/releases/v7.3.5-zako1/patches/0001-zen-7.3.5-zen1.patch @@ -0,0 +1,23684 @@ +diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt +index 4e64219..79121b0 100644 +--- a/Documentation/admin-guide/kernel-parameters.txt ++++ b/Documentation/admin-guide/kernel-parameters.txt +@@ -2532,6 +2532,9 @@ Kernel parameters + disable + Do not enable intel_pstate as the default + scaling driver for the supported processors ++ enable ++ Enable intel_pstate in-case "disable" was passed ++ previously in the kernel boot parameters + active + Use intel_pstate driver to bypass the scaling + governors layer of cpufreq and provides it own +@@ -4693,6 +4696,10 @@ Kernel parameters + + nosync [HW,M68K] Disables sync negotiation for all devices. + ++ nothreadirqs [KNL,EARLY] ++ Disable forced threading of interrupt handlers that ++ is enabled by default with CONFIG_FORCE_IRQ_THREADING. ++ + no_timer_check [X86,APIC] Disables the code which tests for broken + timer IRQ sources, i.e., the IO-APIC timer. This can + work around problems with incorrect timer +@@ -5312,6 +5319,19 @@ Kernel parameters + to disable PCIe TLP Processing Hints support + system-wide. + ++ pcie_acs_override= ++ [PCIE] Assert ACS isolation for PCIe devices ++ lacking it, splitting their IOMMU groups. Not a ++ security boundary: peer-to-peer DMA between ++ affected devices is unprotected. Taints the ++ kernel. Devices with real ACS, and devices the ++ firmware marked untrusted or external-facing, are ++ never affected. Comma-separated list of: ++ downstream Downstream and root ports ++ multifunction Multifunction endpoints and upstream ports ++ id:nnnn:nnnn Devices with this vendor:device ID, hex, ++ up to 16 ++ + pcie_aspm= [PCIE] Forcibly enable or ignore PCIe Active State Power + Management. + off Don't touch ASPM configuration at all. Leave any +@@ -6805,6 +6825,13 @@ Kernel parameters + cost of significant additional memory use for tables. + + ++ sched_pds_sleep_credit= ++ [KNL] Enable or disable the PDS sleep credit, which ++ moves a task that slept ahead of CPU-bound tasks of ++ the same nice level when it wakes up. ++ Format: ++ Default: CONFIG_SCHED_PDS_SLEEP_CREDIT ++ + sched_proxy_exec= [KNL] + Enables or disables "proxy execution" style + solution to mutex-based priority inversion. +diff --git a/Documentation/admin-guide/mm/multigen_lru.rst b/Documentation/admin-guide/mm/multigen_lru.rst +index 9cb54b4..808d2e9 100644 +--- a/Documentation/admin-guide/mm/multigen_lru.rst ++++ b/Documentation/admin-guide/mm/multigen_lru.rst +@@ -149,8 +149,8 @@ generations less than or equal to ``min_gen_nr``. + ``- memcg_id node_id min_gen_nr [swappiness [nr_to_reclaim]]`` + + ``min_gen_nr`` should be less than ``max_gen_nr-1``, since +-``max_gen_nr`` and ``max_gen_nr-1`` are not fully aged (equivalent to +-the active list) and therefore cannot be evicted. ``swappiness`` ++``max_gen_nr`` and ``max_gen_nr-1`` are not fully aged and therefore ++cannot be evicted. ``swappiness`` + overrides the default value in ``/proc/sys/vm/swappiness`` and the valid + range is [0-200, max], with max being exclusively used for the reclamation + of anonymous memory. ``nr_to_reclaim`` limits the number of pages to evict. +diff --git a/Documentation/admin-guide/sysctl/kernel.rst b/Documentation/admin-guide/sysctl/kernel.rst +index ffea61d..cdeb639 100644 +--- a/Documentation/admin-guide/sysctl/kernel.rst ++++ b/Documentation/admin-guide/sysctl/kernel.rst +@@ -1751,3 +1751,12 @@ is 10 seconds. + + The softlockup threshold is (``2 * watchdog_thresh``). Setting this + tunable to zero will disable lockup detection altogether. ++ ++yield_type: ++=========== ++ ++BMQ/PDS CPU scheduler only. This determines what type of yield calls ++to sched_yield() will be performed. ++ ++ 0 - No yield. ++ 1 - Requeue task. (default) +diff --git a/Documentation/mm/multigen_lru.rst b/Documentation/mm/multigen_lru.rst +index 52ed509..ec8744c 100644 +--- a/Documentation/mm/multigen_lru.rst ++++ b/Documentation/mm/multigen_lru.rst +@@ -95,16 +95,19 @@ at most ``MAX_NR_GENS`` generations. The gen counter stores a value + within ``[1, MAX_NR_GENS]`` while a page is on one of + ``lrugen->folios[]``; otherwise it stores zero. + +-Each generation is divided into multiple tiers. A page accessed ``N`` +-times through file descriptors is in tier ``order_base_2(N)``. Unlike +-generations, tiers do not have dedicated ``lrugen->folios[]``. In +-contrast to moving across generations, which requires the LRU lock, +-moving across tiers only involves atomic operations on +-``folio->flags`` and therefore has a negligible cost. A feedback loop +-modeled after the PID controller monitors refaults over all the tiers +-from anon and file types and decides which tiers from which types to +-evict or protect. The desired effect is to balance refault percentages +-between anon and file types proportional to the swappiness level. ++Each generation is divided into multiple tiers. A page's tier is ++derived from its referenced count, which counts the accesses collected ++from both channels above and is capped at ``LRU_REFS_MAX``: pages ++accessed at most once are in the lowest tier, and the tiers above hold ++pages accessed at least twice. Unlike generations, tiers do not have ++dedicated ``lrugen->folios[]``. In contrast to moving across ++generations, which requires the LRU lock, updating the referenced ++count only involves atomic operations on ``folio->flags`` and ++therefore has a negligible cost. A feedback loop modeled after the PID ++controller monitors refaults over all the tiers from anon and file ++types and decides which tiers from which types to evict or protect. ++The desired effect is to balance refault percentages between anon and ++file types proportional to the swappiness level. + + There are two conceptually independent procedures: the aging and the + eviction. They form a closed-loop system, i.e., the page reclaim. +@@ -122,25 +125,31 @@ and calls ``walk_page_range()`` with each ``mm_struct`` on this list + to scan PTEs, and after each iteration, it increments ``max_seq``. For + the latter, when the eviction walks the rmap and finds a young PTE, + the aging scans the adjacent PTEs. For both, on finding a young PTE, +-the aging clears the accessed bit and updates the gen counter of the +-page mapped by this PTE to ``(max_seq%MAX_NR_GENS)+1``. ++the aging clears the accessed bit and bumps the referenced count of ++the page mapped by this PTE. A second access promotes the page by ++updating its gen counter to ``(max_seq%MAX_NR_GENS)+1``; the first ++access only moves a page one generation forward if it is at the tail ++of its LRU, i.e., in one of the two oldest generations of its type, ++so that the next time it becomes the oldest one, its accessed bit ++reflects whether it has been used again. Executable file pages are ++promoted on their first access, since reclaiming them causes typical ++I/O thrashing. + + Eviction + -------- + The eviction consumes old generations. Given an ``lruvec``, it + increments ``min_seq`` when ``lrugen->folios[]`` indexed by +-``min_seq%MAX_NR_GENS`` becomes empty. To select a type and a tier to +-evict from, it first compares ``min_seq[]`` to select the older type. +-If both types are equally old, it selects the one whose first tier has +-a lower refault percentage. The first tier contains single-use +-unmapped clean pages, which are the best bet. The eviction sorts a +-page according to its gen counter if the aging has found this page +-accessed through page tables and updated its gen counter. It also +-moves a page to the next generation, i.e., ``min_seq+1``, if this page +-was accessed multiple times through file descriptors and the feedback +-loop has detected outlying refaults from the tier this page is in. To +-this end, the feedback loop uses the first tier as the baseline, for +-the reason stated earlier. ++``min_seq%MAX_NR_GENS`` becomes empty. To select a type to evict from, ++it first compares ``min_seq[]`` to select the older type. If both ++types are equally old, it compares the refault percentages of all the ++tiers of each type proportional to the swappiness level. To select a ++tier to protect, it compares the refault percentage of each tier ++against that of the tiers below it. The lowest tier contains pages ++accessed at most once, which are the best bet. The eviction sorts a ++page according to its gen counter if the aging or an access has ++updated its gen counter. It also moves a page to the next generation, ++i.e., ``min_seq+1``, if the feedback loop has detected outlying ++refaults from the tier this page is in. + + Working set protection + ---------------------- +diff --git a/Documentation/scheduler/sched-BMQ.txt b/Documentation/scheduler/sched-BMQ.txt +new file mode 100644 +index 0000000..05c84ee +--- /dev/null ++++ b/Documentation/scheduler/sched-BMQ.txt +@@ -0,0 +1,110 @@ ++ BitMap queue CPU Scheduler ++ -------------------------- ++ ++CONTENT ++======== ++ ++ Background ++ Design ++ Overview ++ Task policy ++ Priority management ++ BitMap Queue ++ CPU Assignment and Migration ++ ++ ++Background ++========== ++ ++BitMap Queue CPU scheduler, referred to as BMQ from here on, is an evolution ++of previous Priority and Deadline based Skiplist multiple queue scheduler(PDS), ++and inspired by Zircon scheduler. The goal of it is to keep the scheduler code ++simple, while efficiency and scalable for interactive tasks, such as desktop, ++movie playback and gaming etc. ++ ++Design ++====== ++ ++Overview ++-------- ++ ++BMQ use per CPU run queue design, each CPU(logical) has it's own run queue, ++each CPU is responsible for scheduling the tasks that are putting into it's ++run queue. ++ ++The run queue is a set of priority queues. Note that these queues are fifo ++queue for non-rt tasks or priority queue for rt tasks in data structure. See ++BitMap Queue below for details. BMQ is optimized for non-rt tasks in the fact ++that most applications are non-rt tasks. No matter the queue is fifo or ++priority, In each queue is an ordered list of runnable tasks awaiting execution ++and the data structures are the same. When it is time for a new task to run, ++the scheduler simply looks the lowest numbered queueue that contains a task, ++and runs the first task from the head of that queue. And per CPU idle task is ++also in the run queue, so the scheduler can always find a task to run on from ++its run queue. ++ ++Each task will assigned the same timeslice(default 4ms) when it is picked to ++start running. Task will be reinserted at the end of the appropriate priority ++queue when it uses its whole timeslice. When the scheduler selects a new task ++from the priority queue it sets the CPU's preemption timer for the remainder of ++the previous timeslice. When that timer fires the scheduler will stop execution ++on that task, select another task and start over again. ++ ++If a task blocks waiting for a shared resource then it's taken out of its ++priority queue and is placed in a wait queue for the shared resource. When it ++is unblocked it will be reinserted in the appropriate priority queue of an ++eligible CPU. ++ ++Task policy ++----------- ++ ++BMQ supports DEADLINE, FIFO, RR, NORMAL, BATCH and IDLE task policy like the ++mainline CFS scheduler. But BMQ is heavy optimized for non-rt task, that's ++NORMAL/BATCH/IDLE policy tasks. Below is the implementation detail of each ++policy. ++ ++DEADLINE ++ It is squashed as priority 0 FIFO task. ++ ++FIFO/RR ++ All RT tasks share one single priority queue in BMQ run queue designed. The ++complexity of insert operation is O(n). BMQ is not designed for system runs ++with major rt policy tasks. ++ ++NORMAL/BATCH/IDLE ++ BATCH and IDLE tasks are treated as the same policy. They compete CPU with ++NORMAL policy tasks, but they just don't boost. To control the priority of ++NORMAL/BATCH/IDLE tasks, simply use nice level. ++ ++ISO ++ ISO policy is not supported in BMQ. Please use nice level -20 NORMAL policy ++task instead. ++ ++Priority management ++------------------- ++ ++RT tasks have priority from 0-99. For non-rt tasks, there are three different ++factors used to determine the effective priority of a task. The effective ++priority being what is used to determine which queue it will be in. ++ ++The first factor is simply the task’s static priority. Which is assigned from ++task's nice level, within [-20, 19] in userland's point of view and [0, 39] ++internally. ++ ++The second factor is the priority boost. This is a value bounded between ++[-MAX_PRIORITY_ADJ, MAX_PRIORITY_ADJ] used to offset the base priority, it is ++modified by the following cases: ++ ++*When a thread has used up its entire timeslice, always deboost its boost by ++increasing by one. ++*When a thread gives up cpu control(voluntary or non-voluntary) to reschedule, ++and its switch-in time(time after last switch and run) below the thredhold ++based on its priority boost, will boost its boost by decreasing by one buti is ++capped at 0 (won’t go negative). ++ ++The intent in this system is to ensure that interactive threads are serviced ++quickly. These are usually the threads that interact directly with the user ++and cause user-perceivable latency. These threads usually do little work and ++spend most of their time blocked awaiting another user event. So they get the ++priority boost from unblocking while background threads that do most of the ++processing receive the priority penalty for using their entire timeslice. +diff --git a/Makefile b/Makefile +index 5e0123c..6c8a280 100644 +--- a/Makefile ++++ b/Makefile +@@ -3,7 +3,7 @@ VERSION = 7 + PATCHLEVEL = 3 + SUBLEVEL = 5 + EXTRAVERSION = -gnu +-NAME = Baby Opossum Posse ++NAME = Channeling Inner Peace for Peak Performance + + # *DOCUMENTATION* + # To see a list of typical targets execute "make help" +@@ -932,6 +932,9 @@ KBUILD_CFLAGS += -fno-delete-null-pointer-checks + ifdef CONFIG_CC_OPTIMIZE_FOR_PERFORMANCE + KBUILD_CFLAGS += -O2 + KBUILD_RUSTFLAGS += -Copt-level=2 ++else ifdef CONFIG_CC_OPTIMIZE_FOR_PERFORMANCE_O3 ++KBUILD_CFLAGS += -O3 ++KBUILD_RUSTFLAGS += -Copt-level=3 + else ifdef CONFIG_CC_OPTIMIZE_FOR_SIZE + KBUILD_CFLAGS += -Os + KBUILD_RUSTFLAGS += -Copt-level=s +diff --git a/arch/arm/include/asm/mmu_context.h b/arch/arm/include/asm/mmu_context.h +index db2cb06..bebde46 100644 +--- a/arch/arm/include/asm/mmu_context.h ++++ b/arch/arm/include/asm/mmu_context.h +@@ -80,7 +80,7 @@ static inline void check_and_switch_context(struct mm_struct *mm, + #ifndef MODULE + #define finish_arch_post_lock_switch \ + finish_arch_post_lock_switch +-static inline void finish_arch_post_lock_switch(void) ++static __always_inline void finish_arch_post_lock_switch(void) + { + struct mm_struct *mm = current->mm; + +diff --git a/arch/riscv/include/asm/sync_core.h b/arch/riscv/include/asm/sync_core.h +index 9153016..2fe6b7f 100644 +--- a/arch/riscv/include/asm/sync_core.h ++++ b/arch/riscv/include/asm/sync_core.h +@@ -6,7 +6,7 @@ + * RISC-V implements return to user-space through an xRET instruction, + * which is not core serializing. + */ +-static inline void sync_core_before_usermode(void) ++static __always_inline void sync_core_before_usermode(void) + { + asm volatile ("fence.i" ::: "memory"); + } +diff --git a/arch/s390/include/asm/mmu_context.h b/arch/s390/include/asm/mmu_context.h +index bd1ef5e..95d03be 100644 +--- a/arch/s390/include/asm/mmu_context.h ++++ b/arch/s390/include/asm/mmu_context.h +@@ -93,7 +93,7 @@ static inline void switch_mm(struct mm_struct *prev, struct mm_struct *next, + } + + #define finish_arch_post_lock_switch finish_arch_post_lock_switch +-static inline void finish_arch_post_lock_switch(void) ++static __always_inline void finish_arch_post_lock_switch(void) + { + struct task_struct *tsk = current; + struct mm_struct *mm = tsk->mm; +diff --git a/arch/sparc/include/asm/mmu_context_64.h b/arch/sparc/include/asm/mmu_context_64.h +index 78bbacc..d196721 100644 +--- a/arch/sparc/include/asm/mmu_context_64.h ++++ b/arch/sparc/include/asm/mmu_context_64.h +@@ -160,7 +160,7 @@ static inline void arch_start_context_switch(struct task_struct *prev) + } + + #define finish_arch_post_lock_switch finish_arch_post_lock_switch +-static inline void finish_arch_post_lock_switch(void) ++static __always_inline void finish_arch_post_lock_switch(void) + { + /* Restore the state of MCDPER register for the new process + * just switched to. +diff --git a/arch/x86/Kconfig.cpu b/arch/x86/Kconfig.cpu +index 6e7a366..e72e2c2 100644 +--- a/arch/x86/Kconfig.cpu ++++ b/arch/x86/Kconfig.cpu +@@ -229,6 +229,25 @@ config X86_NATIVE_CPU + + If unsure, say N. + ++config X86_64_VERSION ++ int "x86-64 ISA level" ++ range 1 3 ++ default 1 ++ depends on X86_64 && !X86_NATIVE_CPU ++ depends on CC_IS_CLANG || GCC_VERSION >= 110000 ++ help ++ Build the kernel for an x86-64 psABI micro-architecture level. ++ The kernel does not boot on a CPU below the selected level. ++ ++ 1: x86-64 (baseline) ++ 2: x86-64-v2 ++ 3: x86-64-v3 ++ ++ Run "/lib64/ld-linux-x86-64.so.2 --help" to see the levels ++ that this CPU supports. ++ ++ If unsure, say 1. ++ + config X86_GENERIC + bool "Generic x86 support" + depends on X86_32 +diff --git a/arch/x86/Makefile b/arch/x86/Makefile +index 8af6b80..9c25454 100644 +--- a/arch/x86/Makefile ++++ b/arch/x86/Makefile +@@ -73,7 +73,7 @@ export BITS + # + # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53383 + # +-KBUILD_CFLAGS += -mno-sse -mno-mmx -mno-sse2 -mno-3dnow -mno-avx -mno-sse4a ++KBUILD_CFLAGS += -mno-sse -mno-mmx -mno-sse2 -mno-3dnow -mno-avx -mno-sse4a -mno-avx2 -fno-tree-vectorize + KBUILD_RUSTFLAGS += --target=$(objtree)/scripts/target.json + KBUILD_RUSTFLAGS += -Ctarget-feature=-sse,-sse2,-sse3,-ssse3,-sse4.1,-sse4.2,-avx,-avx2 + +@@ -167,6 +167,9 @@ ifdef CONFIG_X86_NATIVE_CPU + + # generate_rust_target.rs handles Rust APX gating. + KBUILD_RUSTFLAGS += -Ctarget-cpu=native ++else ifneq ($(filter-out 1,$(CONFIG_X86_64_VERSION)),) ++ KBUILD_CFLAGS += -march=x86-64-v$(CONFIG_X86_64_VERSION) -mtune=generic ++ KBUILD_RUSTFLAGS += -Ctarget-cpu=x86-64-v$(CONFIG_X86_64_VERSION) -Ztune-cpu=generic + else + KBUILD_CFLAGS += -march=x86-64 -mtune=generic + KBUILD_RUSTFLAGS += -Ctarget-cpu=x86-64 -Ztune-cpu=generic +diff --git a/arch/x86/include/asm/sync_core.h b/arch/x86/include/asm/sync_core.h +index df22113..3b0ed46 100644 +--- a/arch/x86/include/asm/sync_core.h ++++ b/arch/x86/include/asm/sync_core.h +@@ -93,7 +93,7 @@ static __always_inline void sync_core(void) + * to user-mode. x86 implements return to user-space through sysexit, + * sysrel, and sysretq, which are not core serializing. + */ +-static inline void sync_core_before_usermode(void) ++static __always_inline void sync_core_before_usermode(void) + { + /* With PTI, we unconditionally serialize before running user code. */ + if (cpu_feature_enabled(X86_FEATURE_PTI)) +diff --git a/arch/x86/kernel/cpu/bus_lock.c b/arch/x86/kernel/cpu/bus_lock.c +index 177f964..a5c1338 100644 +--- a/arch/x86/kernel/cpu/bus_lock.c ++++ b/arch/x86/kernel/cpu/bus_lock.c +@@ -47,7 +47,11 @@ static const struct { + + static struct ratelimit_state bld_ratelimit; + ++#ifdef CONFIG_ZEN_INTERACTIVE ++static unsigned int sysctl_sld_mitigate; ++#else + static unsigned int sysctl_sld_mitigate = 1; ++#endif + static DEFINE_SEMAPHORE(buslock_sem, 1); + + #ifdef CONFIG_SYSCTL +diff --git a/block/elevator.c b/block/elevator.c +index 66edf1a..8fd2341 100644 +--- a/block/elevator.c ++++ b/block/elevator.c +@@ -729,7 +729,11 @@ void elv_update_nr_hw_queues(struct request_queue *q, + void elevator_set_default(struct request_queue *q) + { + struct elv_change_ctx ctx = { ++#if defined(CONFIG_ZEN_INTERACTIVE) && defined(CONFIG_IOSCHED_BFQ) ++ .name = "bfq", ++#else + .name = "mq-deadline", ++#endif + .no_uevent = true, + }; + int err; +@@ -745,17 +749,22 @@ void elevator_set_default(struct request_queue *q) + * have multiple queues or mq-deadline is not available, default + * to "none". + */ ++ if (q->nr_hw_queues != 1 && !blk_mq_is_shared_tags(q->tag_set->flags)) ++#if defined(CONFIG_ZEN_INTERACTIVE) && defined(CONFIG_MQ_IOSCHED_KYBER) ++ ctx.name = "kyber"; ++#else ++ return; ++#endif ++ + ctx.type = elevator_find_get(ctx.name); + if (!ctx.type) + return; + +- if ((q->nr_hw_queues == 1 || +- blk_mq_is_shared_tags(q->tag_set->flags))) { +- err = elevator_change(q, &ctx); +- if (err < 0) +- pr_warn("\"%s\" elevator initialization, failed %d, falling back to \"none\"\n", +- ctx.name, err); +- } ++ err = elevator_change(q, &ctx); ++ if (err < 0) ++ pr_warn("\"%s\" elevator initialization, failed %d, falling back to \"none\"\n", ++ ctx.name, err); ++ + elevator_put(ctx.type); + } + +diff --git a/crypto/acompress.c b/crypto/acompress.c +index 4de1a2a..c8b4b85 100644 +--- a/crypto/acompress.c ++++ b/crypto/acompress.c +@@ -92,10 +92,6 @@ static int crypto_acomp_init_tfm(struct crypto_tfm *tfm) + if (IS_ERR(fb)) + return PTR_ERR(fb); + +- err = -EINVAL; +- if (crypto_acomp_reqsize(fb) > MAX_SYNC_COMP_REQSIZE) +- goto out_free_fb; +- + tfm->fb = crypto_acomp_tfm(fb); + } + +@@ -105,15 +101,19 @@ static int crypto_acomp_init_tfm(struct crypto_tfm *tfm) + + acomp->base.exit = crypto_acomp_exit_tfm; + +- if (!alg->init) +- return 0; +- +- err = alg->init(acomp); +- if (err) ++ if (alg->init && ((err = alg->init(acomp)))) + goto out_free_fb; + ++ err = -EINVAL; ++ if (!acomp_is_async(acomp) && ++ crypto_acomp_reqsize(acomp) > MAX_SYNC_COMP_REQSIZE) ++ goto out_exit_tfm; ++ + return 0; + ++out_exit_tfm: ++ if (alg->exit) ++ alg->exit(acomp); + out_free_fb: + crypto_free_acomp(fb); + return err; +diff --git a/drivers/block/zram/backend_842.c b/drivers/block/zram/backend_842.c +index 3846a04..f911cd1 100644 +--- a/drivers/block/zram/backend_842.c ++++ b/drivers/block/zram/backend_842.c +@@ -1,6 +1,6 @@ + // SPDX-License-Identifier: GPL-2.0-or-later + +-#define pr_fmt(fmt) "842: " fmt ++#define pr_fmt(fmt) "zram: 842: " fmt + + #include + #include +@@ -63,8 +63,8 @@ static int decompress_842(struct zcomp_params *params, struct zcomp_ctx *ctx, + const struct zcomp_ops backend_842 = { + .compress = compress_842, + .decompress = decompress_842, +- .create_ctx = create_842, +- .destroy_ctx = destroy_842, ++ .create_cctx = create_842, ++ .destroy_cctx = destroy_842, + .setup_params = setup_params_842, + .release_params = release_params_842, + .name = "842", +diff --git a/drivers/block/zram/backend_deflate.c b/drivers/block/zram/backend_deflate.c +index f71b11b..5ffdaf8 100644 +--- a/drivers/block/zram/backend_deflate.c ++++ b/drivers/block/zram/backend_deflate.c +@@ -1,6 +1,6 @@ + // SPDX-License-Identifier: GPL-2.0-or-later + +-#define pr_fmt(fmt) "deflate: " fmt ++#define pr_fmt(fmt) "zram: deflate: " fmt + + #include + #include +@@ -13,11 +13,6 @@ + #define DEFLATE_DEF_WINBITS (-11) + #define DEFLATE_DEF_MEMLEVEL MAX_MEM_LEVEL + +-struct deflate_ctx { +- struct z_stream_s cctx; +- struct z_stream_s dctx; +-}; +- + static void deflate_release_params(struct zcomp_params *params) + { + } +@@ -51,70 +46,98 @@ static int deflate_setup_params(struct zcomp_params *params) + return 0; + } + +-static void deflate_destroy(struct zcomp_ctx *ctx) ++static void deflate_destroy_cctx(struct zcomp_ctx *ctx) + { +- struct deflate_ctx *zctx = ctx->context; ++ struct z_stream_s *cctx = ctx->context; + +- if (!zctx) ++ if (!cctx) + return; + +- if (zctx->cctx.workspace) { +- zlib_deflateEnd(&zctx->cctx); +- vfree(zctx->cctx.workspace); +- } +- if (zctx->dctx.workspace) { +- zlib_inflateEnd(&zctx->dctx); +- vfree(zctx->dctx.workspace); ++ if (cctx->workspace) { ++ zlib_deflateEnd(cctx); ++ vfree(cctx->workspace); + } +- kfree(zctx); ++ kfree(cctx); + } + +-static int deflate_create(struct zcomp_params *params, struct zcomp_ctx *ctx) ++static int deflate_create_cctx(struct zcomp_params *params, ++ struct zcomp_ctx *ctx) + { +- struct deflate_ctx *zctx; ++ struct z_stream_s *cctx; + size_t sz; + int ret; + +- zctx = kzalloc_obj(*zctx); +- if (!zctx) ++ cctx = kzalloc_obj(*cctx); ++ if (!cctx) + return -ENOMEM; + +- ctx->context = zctx; ++ ctx->context = cctx; + sz = zlib_deflate_workspacesize(params->deflate.winbits, MAX_MEM_LEVEL); +- zctx->cctx.workspace = vzalloc(sz); +- if (!zctx->cctx.workspace) ++ cctx->workspace = vzalloc(sz); ++ if (!cctx->workspace) + goto error; + +- ret = zlib_deflateInit2(&zctx->cctx, params->level, Z_DEFLATED, ++ ret = zlib_deflateInit2(cctx, params->level, Z_DEFLATED, + params->deflate.winbits, DEFLATE_DEF_MEMLEVEL, + Z_DEFAULT_STRATEGY); + if (ret != Z_OK) + goto error; + ++ return 0; ++ ++error: ++ deflate_destroy_cctx(ctx); ++ return -EINVAL; ++} ++ ++static void deflate_destroy_dctx(struct zcomp_ctx *ctx) ++{ ++ struct z_stream_s *dctx = ctx->context; ++ ++ if (!dctx) ++ return; ++ ++ if (dctx->workspace) { ++ zlib_inflateEnd(dctx); ++ vfree(dctx->workspace); ++ } ++ kfree(dctx); ++} ++ ++static int deflate_create_dctx(struct zcomp_params *params, ++ struct zcomp_ctx *ctx) ++{ ++ struct z_stream_s *dctx; ++ size_t sz; ++ int ret; ++ ++ dctx = kzalloc_obj(*dctx); ++ if (!dctx) ++ return -ENOMEM; ++ ++ ctx->context = dctx; + sz = zlib_inflate_workspacesize(); +- zctx->dctx.workspace = vzalloc(sz); +- if (!zctx->dctx.workspace) ++ dctx->workspace = vzalloc(sz); ++ if (!dctx->workspace) + goto error; + +- ret = zlib_inflateInit2(&zctx->dctx, params->deflate.winbits); ++ ret = zlib_inflateInit2(dctx, params->deflate.winbits); + if (ret != Z_OK) + goto error; + + return 0; + + error: +- deflate_destroy(ctx); ++ deflate_destroy_dctx(ctx); + return -EINVAL; + } + + static int deflate_compress(struct zcomp_params *params, struct zcomp_ctx *ctx, + struct zcomp_req *req) + { +- struct deflate_ctx *zctx = ctx->context; +- struct z_stream_s *deflate; ++ struct z_stream_s *deflate = ctx->context; + int ret; + +- deflate = &zctx->cctx; + ret = zlib_deflateReset(deflate); + if (ret != Z_OK) + return -EINVAL; +@@ -136,12 +159,9 @@ static int deflate_decompress(struct zcomp_params *params, + struct zcomp_ctx *ctx, + struct zcomp_req *req) + { +- struct deflate_ctx *zctx = ctx->context; +- struct z_stream_s *inflate; ++ struct z_stream_s *inflate = ctx->context; + int ret; + +- inflate = &zctx->dctx; +- + ret = zlib_inflateReset(inflate); + if (ret != Z_OK) + return -EINVAL; +@@ -161,8 +181,10 @@ static int deflate_decompress(struct zcomp_params *params, + const struct zcomp_ops backend_deflate = { + .compress = deflate_compress, + .decompress = deflate_decompress, +- .create_ctx = deflate_create, +- .destroy_ctx = deflate_destroy, ++ .create_cctx = deflate_create_cctx, ++ .destroy_cctx = deflate_destroy_cctx, ++ .create_dctx = deflate_create_dctx, ++ .destroy_dctx = deflate_destroy_dctx, + .setup_params = deflate_setup_params, + .release_params = deflate_release_params, + .name = "deflate", +diff --git a/drivers/block/zram/backend_lz4.c b/drivers/block/zram/backend_lz4.c +index 1e4ad31..9767482 100644 +--- a/drivers/block/zram/backend_lz4.c ++++ b/drivers/block/zram/backend_lz4.c +@@ -1,21 +1,13 @@ + // SPDX-License-Identifier: GPL-2.0-or-later + +-#define pr_fmt(fmt) "lz4: " fmt ++#define pr_fmt(fmt) "zram: lz4: " fmt + + #include + #include +-#include + #include + + #include "backend_lz4.h" + +-struct lz4_ctx { +- void *mem; +- +- LZ4_streamDecode_t *dstrm; +- LZ4_stream_t *cstrm; +-}; +- + static void lz4_release_params(struct zcomp_params *params) + { + LZ4_stream_t *dict_stream = params->drv_data; +@@ -24,7 +16,7 @@ static void lz4_release_params(struct zcomp_params *params) + if (!dict_stream) + return; + +- kfree(dict_stream); ++ vfree(dict_stream); + } + + static int lz4_setup_params(struct zcomp_params *params) +@@ -42,14 +34,13 @@ static int lz4_setup_params(struct zcomp_params *params) + if (!params->dict || !params->dict_sz) + return 0; + +- dict_stream = kzalloc_obj(*dict_stream); ++ dict_stream = vzalloc(sizeof(*dict_stream)); + if (!dict_stream) + return -ENOMEM; + +- ret = LZ4_loadDict(dict_stream, +- params->dict, params->dict_sz); ++ ret = LZ4_loadDict(dict_stream, params->dict, params->dict_sz); + if (ret != params->dict_sz) { +- kfree(dict_stream); ++ vfree(dict_stream); + return -EINVAL; + } + params->drv_data = dict_stream; +@@ -59,61 +50,32 @@ static int lz4_setup_params(struct zcomp_params *params) + + static void lz4_destroy(struct zcomp_ctx *ctx) + { +- struct lz4_ctx *zctx = ctx->context; +- +- if (!zctx) +- return; +- +- vfree(zctx->mem); +- kfree(zctx->dstrm); +- kfree(zctx->cstrm); +- kfree(zctx); ++ vfree(ctx->context); + } + + static int lz4_create(struct zcomp_params *params, struct zcomp_ctx *ctx) + { +- struct lz4_ctx *zctx; ++ BUILD_BUG_ON(sizeof(LZ4_stream_t) != LZ4_MEM_COMPRESS); + +- zctx = kzalloc_obj(*zctx); +- if (!zctx) ++ ctx->context = vmalloc(LZ4_MEM_COMPRESS); ++ if (!ctx->context) + return -ENOMEM; +- +- ctx->context = zctx; +- if (params->dict_sz == 0) { +- zctx->mem = vmalloc(LZ4_MEM_COMPRESS); +- if (!zctx->mem) +- goto error; +- } else { +- zctx->dstrm = kzalloc_obj(*zctx->dstrm); +- if (!zctx->dstrm) +- goto error; +- +- zctx->cstrm = kzalloc_obj(*zctx->cstrm); +- if (!zctx->cstrm) +- goto error; +- } +- + return 0; +- +-error: +- lz4_destroy(ctx); +- return -ENOMEM; + } + + static int lz4_compress(struct zcomp_params *params, struct zcomp_ctx *ctx, + struct zcomp_req *req) + { +- struct lz4_ctx *zctx = ctx->context; + int ret; + +- if (!zctx->cstrm) { ++ if (!params->drv_data) { + ret = LZ4_compress_fast(req->src, req->dst, req->src_len, + req->dst_len, params->level, +- zctx->mem); ++ ctx->context); + } else { + /* Cstrm needs to be reset */ +- memcpy(zctx->cstrm, params->drv_data, sizeof(*zctx->cstrm)); +- ret = LZ4_compress_fast_continue(zctx->cstrm, req->src, ++ memcpy(ctx->context, params->drv_data, sizeof(LZ4_stream_t)); ++ ret = LZ4_compress_fast_continue(ctx->context, req->src, + req->dst, req->src_len, + req->dst_len, params->level); + } +@@ -126,22 +88,11 @@ static int lz4_compress(struct zcomp_params *params, struct zcomp_ctx *ctx, + static int lz4_decompress(struct zcomp_params *params, struct zcomp_ctx *ctx, + struct zcomp_req *req) + { +- struct lz4_ctx *zctx = ctx->context; + int ret; + +- if (!zctx->dstrm) { +- ret = LZ4_decompress_safe(req->src, req->dst, req->src_len, +- req->dst_len); +- } else { +- /* Dstrm needs to be reset */ +- ret = LZ4_setStreamDecode(zctx->dstrm, params->dict, +- params->dict_sz); +- if (!ret) +- return -EINVAL; +- ret = LZ4_decompress_safe_continue(zctx->dstrm, req->src, +- req->dst, req->src_len, +- req->dst_len); +- } ++ ret = LZ4_decompress_safe_usingDict(req->src, req->dst, req->src_len, ++ req->dst_len, params->dict, ++ params->dict_sz); + if (ret < 0) + return -EINVAL; + return 0; +@@ -150,8 +101,8 @@ static int lz4_decompress(struct zcomp_params *params, struct zcomp_ctx *ctx, + const struct zcomp_ops backend_lz4 = { + .compress = lz4_compress, + .decompress = lz4_decompress, +- .create_ctx = lz4_create, +- .destroy_ctx = lz4_destroy, ++ .create_cctx = lz4_create, ++ .destroy_cctx = lz4_destroy, + .setup_params = lz4_setup_params, + .release_params = lz4_release_params, + .name = "lz4", +diff --git a/drivers/block/zram/backend_lz4hc.c b/drivers/block/zram/backend_lz4hc.c +index d8aa01b..2d1364a 100644 +--- a/drivers/block/zram/backend_lz4hc.c ++++ b/drivers/block/zram/backend_lz4hc.c +@@ -1,27 +1,29 @@ + // SPDX-License-Identifier: GPL-2.0-or-later + +-#define pr_fmt(fmt) "lz4hc: " fmt ++#define pr_fmt(fmt) "zram: lz4hc: " fmt + + #include + #include +-#include + #include + + #include "backend_lz4hc.h" + +-struct lz4hc_ctx { +- void *mem; +- +- LZ4_streamDecode_t *dstrm; +- LZ4_streamHC_t *cstrm; +-}; +- + static void lz4hc_release_params(struct zcomp_params *params) + { ++ LZ4_streamHC_t *dict_stream = params->drv_data; ++ ++ params->drv_data = NULL; ++ if (!dict_stream) ++ return; ++ ++ vfree(dict_stream); + } + + static int lz4hc_setup_params(struct zcomp_params *params) + { ++ LZ4_streamHC_t *dict_stream; ++ int ret; ++ + if (params->level == ZCOMP_PARAM_NOT_SET) { + params->level = LZ4HC_DEFAULT_CLEVEL; + } else if (params->level < 1 || params->level > LZ4HC_MAX_CLEVEL) { +@@ -35,70 +37,52 @@ static int lz4hc_setup_params(struct zcomp_params *params) + return -EINVAL; + } + ++ if (!params->dict || !params->dict_sz) ++ return 0; ++ ++ dict_stream = vzalloc(sizeof(*dict_stream)); ++ if (!dict_stream) ++ return -ENOMEM; ++ ++ LZ4_resetStreamHC(dict_stream, params->level); ++ ret = LZ4_loadDictHC(dict_stream, params->dict, params->dict_sz); ++ if (ret != params->dict_sz) { ++ vfree(dict_stream); ++ return -EINVAL; ++ } ++ params->drv_data = dict_stream; ++ + return 0; + } + + static void lz4hc_destroy(struct zcomp_ctx *ctx) + { +- struct lz4hc_ctx *zctx = ctx->context; +- +- if (!zctx) +- return; +- +- kfree(zctx->dstrm); +- kfree(zctx->cstrm); +- vfree(zctx->mem); +- kfree(zctx); ++ vfree(ctx->context); + } + + static int lz4hc_create(struct zcomp_params *params, struct zcomp_ctx *ctx) + { +- struct lz4hc_ctx *zctx; ++ BUILD_BUG_ON(sizeof(LZ4_streamHC_t) != LZ4HC_MEM_COMPRESS); + +- zctx = kzalloc_obj(*zctx); +- if (!zctx) ++ ctx->context = vmalloc(LZ4HC_MEM_COMPRESS); ++ if (!ctx->context) + return -ENOMEM; +- +- ctx->context = zctx; +- if (params->dict_sz == 0) { +- zctx->mem = vmalloc(LZ4HC_MEM_COMPRESS); +- if (!zctx->mem) +- goto error; +- } else { +- zctx->dstrm = kzalloc_obj(*zctx->dstrm); +- if (!zctx->dstrm) +- goto error; +- +- zctx->cstrm = kzalloc_obj(*zctx->cstrm); +- if (!zctx->cstrm) +- goto error; +- } +- + return 0; +- +-error: +- lz4hc_destroy(ctx); +- return -EINVAL; + } + + static int lz4hc_compress(struct zcomp_params *params, struct zcomp_ctx *ctx, + struct zcomp_req *req) + { +- struct lz4hc_ctx *zctx = ctx->context; + int ret; + +- if (!zctx->cstrm) { ++ if (!params->drv_data) { + ret = LZ4_compress_HC(req->src, req->dst, req->src_len, + req->dst_len, params->level, +- zctx->mem); ++ ctx->context); + } else { + /* Cstrm needs to be reset */ +- LZ4_resetStreamHC(zctx->cstrm, params->level); +- ret = LZ4_loadDictHC(zctx->cstrm, params->dict, +- params->dict_sz); +- if (ret != params->dict_sz) +- return -EINVAL; +- ret = LZ4_compress_HC_continue(zctx->cstrm, req->src, req->dst, ++ memcpy(ctx->context, params->drv_data, sizeof(LZ4_streamHC_t)); ++ ret = LZ4_compress_HC_continue(ctx->context, req->src, req->dst, + req->src_len, req->dst_len); + } + if (!ret) +@@ -110,22 +94,11 @@ static int lz4hc_compress(struct zcomp_params *params, struct zcomp_ctx *ctx, + static int lz4hc_decompress(struct zcomp_params *params, struct zcomp_ctx *ctx, + struct zcomp_req *req) + { +- struct lz4hc_ctx *zctx = ctx->context; + int ret; + +- if (!zctx->dstrm) { +- ret = LZ4_decompress_safe(req->src, req->dst, req->src_len, +- req->dst_len); +- } else { +- /* Dstrm needs to be reset */ +- ret = LZ4_setStreamDecode(zctx->dstrm, params->dict, +- params->dict_sz); +- if (!ret) +- return -EINVAL; +- ret = LZ4_decompress_safe_continue(zctx->dstrm, req->src, +- req->dst, req->src_len, +- req->dst_len); +- } ++ ret = LZ4_decompress_safe_usingDict(req->src, req->dst, req->src_len, ++ req->dst_len, params->dict, ++ params->dict_sz); + if (ret < 0) + return -EINVAL; + return 0; +@@ -134,8 +107,8 @@ static int lz4hc_decompress(struct zcomp_params *params, struct zcomp_ctx *ctx, + const struct zcomp_ops backend_lz4hc = { + .compress = lz4hc_compress, + .decompress = lz4hc_decompress, +- .create_ctx = lz4hc_create, +- .destroy_ctx = lz4hc_destroy, ++ .create_cctx = lz4hc_create, ++ .destroy_cctx = lz4hc_destroy, + .setup_params = lz4hc_setup_params, + .release_params = lz4hc_release_params, + .name = "lz4hc", +diff --git a/drivers/block/zram/backend_lzo.c b/drivers/block/zram/backend_lzo.c +index d83f92c..e703560 100644 +--- a/drivers/block/zram/backend_lzo.c ++++ b/drivers/block/zram/backend_lzo.c +@@ -1,6 +1,6 @@ + // SPDX-License-Identifier: GPL-2.0-or-later + +-#define pr_fmt(fmt) "lzo: " fmt ++#define pr_fmt(fmt) "zram: lzo: " fmt + + #include + #include +@@ -61,8 +61,8 @@ static int lzo_decompress(struct zcomp_params *params, struct zcomp_ctx *ctx, + const struct zcomp_ops backend_lzo = { + .compress = lzo_compress, + .decompress = lzo_decompress, +- .create_ctx = lzo_create, +- .destroy_ctx = lzo_destroy, ++ .create_cctx = lzo_create, ++ .destroy_cctx = lzo_destroy, + .setup_params = lzo_setup_params, + .release_params = lzo_release_params, + .name = "lzo", +diff --git a/drivers/block/zram/backend_lzorle.c b/drivers/block/zram/backend_lzorle.c +index 1b120d0..e95026e 100644 +--- a/drivers/block/zram/backend_lzorle.c ++++ b/drivers/block/zram/backend_lzorle.c +@@ -1,6 +1,6 @@ + // SPDX-License-Identifier: GPL-2.0-or-later + +-#define pr_fmt(fmt) "lzo-rle: " fmt ++#define pr_fmt(fmt) "zram: lzo-rle: " fmt + + #include + #include +@@ -61,8 +61,8 @@ static int lzorle_decompress(struct zcomp_params *params, struct zcomp_ctx *ctx, + const struct zcomp_ops backend_lzorle = { + .compress = lzorle_compress, + .decompress = lzorle_decompress, +- .create_ctx = lzorle_create, +- .destroy_ctx = lzorle_destroy, ++ .create_cctx = lzorle_create, ++ .destroy_cctx = lzorle_destroy, + .setup_params = lzorle_setup_params, + .release_params = lzorle_release_params, + .name = "lzo-rle", +diff --git a/drivers/block/zram/backend_zstd.c b/drivers/block/zram/backend_zstd.c +index 08da381..d55615f 100644 +--- a/drivers/block/zram/backend_zstd.c ++++ b/drivers/block/zram/backend_zstd.c +@@ -1,6 +1,6 @@ + // SPDX-License-Identifier: GPL-2.0-or-later + +-#define pr_fmt(fmt) "zstd: " fmt ++#define pr_fmt(fmt) "zram: zstd: " fmt + + #include + #include +@@ -10,10 +10,8 @@ + #include "backend_zstd.h" + + struct zstd_ctx { +- zstd_cctx *cctx; +- zstd_dctx *dctx; +- void *cctx_mem; +- void *dctx_mem; ++ void *ctx; ++ void *mem; + }; + + struct zstd_params { +@@ -26,10 +24,17 @@ struct zstd_params { + /* + * For C/D dictionaries we need to provide zstd with zstd_custom_mem, + * which zstd uses internally to allocate/free memory when needed. ++ * ++ * zstd allocations (C/D dictionaries and contexts) are large and ++ * long-lived. Don't use kvzalloc() for them: when enough physically ++ * contiguous memory is available it serves them from kmalloc(), which ++ * rounds them up to a power-of-two number of pages. + */ + static void *zstd_custom_alloc(void *opaque, size_t size) + { +- return kvzalloc(size, GFP_NOIO | __GFP_NOWARN); ++ if (size <= PAGE_SIZE) ++ return kzalloc(size, GFP_NOIO | __GFP_NOWARN); ++ return __vmalloc(size, GFP_NOIO | __GFP_NOWARN | __GFP_ZERO); + } + + static void zstd_custom_free(void *opaque, void *address) +@@ -76,6 +81,9 @@ static int zstd_setup_params(struct zcomp_params *params) + prm = zstd_get_cparams(params->level, PAGE_SIZE, + params->dict_sz); + ++ if (!params->dict || !params->dict_sz) ++ return 0; ++ + zp->cdict = zstd_create_cdict_byreference(params->dict, + params->dict_sz, + prm, +@@ -95,7 +103,7 @@ static int zstd_setup_params(struct zcomp_params *params) + return -EINVAL; + } + +-static void zstd_destroy(struct zcomp_ctx *ctx) ++static void zstd_destroy_cctx(struct zcomp_ctx *ctx) + { + struct zstd_ctx *zctx = ctx->context; + +@@ -103,30 +111,23 @@ static void zstd_destroy(struct zcomp_ctx *ctx) + return; + + /* +- * If ->cctx_mem and ->dctx_mem were allocated then we didn't use +- * C/D dictionary and ->cctx / ->dctx were "embedded" into these +- * buffers. ++ * If ->mem was allocated then we didn't use C/D dictionary and ++ * ->ctx was "embedded" into this buffer. + * +- * If otherwise then we need to explicitly release ->cctx / ->dctx. ++ * If otherwise then we need to explicitly release ->ctx. + */ +- if (zctx->cctx_mem) +- vfree(zctx->cctx_mem); +- else +- zstd_free_cctx(zctx->cctx); +- +- if (zctx->dctx_mem) +- vfree(zctx->dctx_mem); ++ if (zctx->mem) ++ vfree(zctx->mem); + else +- zstd_free_dctx(zctx->dctx); ++ zstd_free_cctx(zctx->ctx); + + kfree(zctx); + } + +-static int zstd_create(struct zcomp_params *params, struct zcomp_ctx *ctx) ++static int zstd_create_cctx(struct zcomp_params *params, struct zcomp_ctx *ctx) + { ++ struct zstd_params *zp = params->drv_data; + struct zstd_ctx *zctx; +- zstd_parameters prm; +- size_t sz; + + zctx = kzalloc_obj(*zctx); + if (!zctx) +@@ -134,40 +135,74 @@ static int zstd_create(struct zcomp_params *params, struct zcomp_ctx *ctx) + + ctx->context = zctx; + if (params->dict_sz == 0) { +- prm = zstd_get_params(params->level, PAGE_SIZE); +- sz = zstd_cctx_workspace_bound(&prm.cParams); +- zctx->cctx_mem = vzalloc(sz); +- if (!zctx->cctx_mem) +- goto error; ++ zstd_parameters prm = zp->cprm; ++ size_t sz = zstd_cctx_workspace_bound(&prm.cParams); + +- zctx->cctx = zstd_init_cctx(zctx->cctx_mem, sz); +- if (!zctx->cctx) ++ zctx->mem = vzalloc(sz); ++ if (!zctx->mem) + goto error; + +- sz = zstd_dctx_workspace_bound(); +- zctx->dctx_mem = vzalloc(sz); +- if (!zctx->dctx_mem) +- goto error; +- +- zctx->dctx = zstd_init_dctx(zctx->dctx_mem, sz); +- if (!zctx->dctx) ++ zctx->ctx = zstd_init_cctx(zctx->mem, sz); ++ if (!zctx->ctx) + goto error; + } else { +- struct zstd_params *zp = params->drv_data; ++ zctx->ctx = zstd_create_cctx_advanced(zp->custom_mem); ++ if (!zctx->ctx) ++ goto error; ++ } ++ ++ return 0; ++ ++error: ++ zstd_destroy_cctx(ctx); ++ return -EINVAL; ++} + +- zctx->cctx = zstd_create_cctx_advanced(zp->custom_mem); +- if (!zctx->cctx) ++static void zstd_destroy_dctx(struct zcomp_ctx *ctx) ++{ ++ struct zstd_ctx *zctx = ctx->context; ++ ++ if (!zctx) ++ return; ++ ++ if (zctx->mem) ++ vfree(zctx->mem); ++ else ++ zstd_free_dctx(zctx->ctx); ++ ++ kfree(zctx); ++} ++ ++static int zstd_create_dctx(struct zcomp_params *params, struct zcomp_ctx *ctx) ++{ ++ struct zstd_params *zp = params->drv_data; ++ struct zstd_ctx *zctx; ++ ++ zctx = kzalloc_obj(*zctx); ++ if (!zctx) ++ return -ENOMEM; ++ ++ ctx->context = zctx; ++ if (params->dict_sz == 0) { ++ size_t sz = zstd_dctx_workspace_bound(); ++ ++ zctx->mem = vzalloc(sz); ++ if (!zctx->mem) + goto error; + +- zctx->dctx = zstd_create_dctx_advanced(zp->custom_mem); +- if (!zctx->dctx) ++ zctx->ctx = zstd_init_dctx(zctx->mem, sz); ++ if (!zctx->ctx) ++ goto error; ++ } else { ++ zctx->ctx = zstd_create_dctx_advanced(zp->custom_mem); ++ if (!zctx->ctx) + goto error; + } + + return 0; + + error: +- zstd_destroy(ctx); ++ zstd_destroy_dctx(ctx); + return -EINVAL; + } + +@@ -179,10 +214,10 @@ static int zstd_compress(struct zcomp_params *params, struct zcomp_ctx *ctx, + size_t ret; + + if (params->dict_sz == 0) +- ret = zstd_compress_cctx(zctx->cctx, req->dst, req->dst_len, ++ ret = zstd_compress_cctx(zctx->ctx, req->dst, req->dst_len, + req->src, req->src_len, &zp->cprm); + else +- ret = zstd_compress_using_cdict(zctx->cctx, req->dst, ++ ret = zstd_compress_using_cdict(zctx->ctx, req->dst, + req->dst_len, req->src, + req->src_len, + zp->cdict); +@@ -200,10 +235,10 @@ static int zstd_decompress(struct zcomp_params *params, struct zcomp_ctx *ctx, + size_t ret; + + if (params->dict_sz == 0) +- ret = zstd_decompress_dctx(zctx->dctx, req->dst, req->dst_len, ++ ret = zstd_decompress_dctx(zctx->ctx, req->dst, req->dst_len, + req->src, req->src_len); + else +- ret = zstd_decompress_using_ddict(zctx->dctx, req->dst, ++ ret = zstd_decompress_using_ddict(zctx->ctx, req->dst, + req->dst_len, req->src, + req->src_len, zp->ddict); + if (zstd_is_error(ret)) +@@ -214,8 +249,10 @@ static int zstd_decompress(struct zcomp_params *params, struct zcomp_ctx *ctx, + const struct zcomp_ops backend_zstd = { + .compress = zstd_compress, + .decompress = zstd_decompress, +- .create_ctx = zstd_create, +- .destroy_ctx = zstd_destroy, ++ .create_cctx = zstd_create_cctx, ++ .destroy_cctx = zstd_destroy_cctx, ++ .create_dctx = zstd_create_dctx, ++ .destroy_dctx = zstd_destroy_dctx, + .setup_params = zstd_setup_params, + .release_params = zstd_release_params, + .name = "zstd", +diff --git a/drivers/block/zram/zcomp.c b/drivers/block/zram/zcomp.c +index 974c469..ad8c7dc 100644 +--- a/drivers/block/zram/zcomp.c ++++ b/drivers/block/zram/zcomp.c +@@ -7,6 +7,8 @@ + #include + #include + #include ++#include ++#include + #include + #include + +@@ -43,30 +45,65 @@ static const struct zcomp_ops *backends[] = { + NULL + }; + +-static void zcomp_strm_free(struct zcomp *comp, struct zcomp_strm *zstrm) ++static void zcomp_cstrm_free(struct zcomp *comp, struct zcomp_cstrm *zstrm) + { +- comp->ops->destroy_ctx(&zstrm->ctx); +- vfree(zstrm->local_copy); ++ if (comp->ops->destroy_cctx) ++ comp->ops->destroy_cctx(&zstrm->ctx); + vfree(zstrm->buffer); + zstrm->buffer = NULL; ++ zstrm->ctx.context = NULL; + } + +-static int zcomp_strm_init(struct zcomp *comp, struct zcomp_strm *zstrm) ++static int zcomp_cstrm_init(struct zcomp *comp, struct zcomp_cstrm *zstrm) + { + int ret; + +- ret = comp->ops->create_ctx(comp->params, &zstrm->ctx); +- if (ret) +- return ret; ++ if (comp->ops->create_cctx) { ++ ret = comp->ops->create_cctx(comp->params, &zstrm->ctx); ++ if (ret) { ++ /* backend has released partially created context */ ++ zstrm->ctx.context = NULL; ++ return ret; ++ } ++ } + +- zstrm->local_copy = vzalloc(PAGE_SIZE); + /* + * allocate 2 pages. 1 for compressed data, plus 1 extra for the + * case when compressed size is larger than the original one + */ + zstrm->buffer = vzalloc(2 * PAGE_SIZE); +- if (!zstrm->buffer || !zstrm->local_copy) { +- zcomp_strm_free(comp, zstrm); ++ if (!zstrm->buffer) { ++ zcomp_cstrm_free(comp, zstrm); ++ return -ENOMEM; ++ } ++ return 0; ++} ++ ++static void zcomp_dstrm_free(struct zcomp *comp, struct zcomp_dstrm *zstrm) ++{ ++ if (comp->ops->destroy_dctx) ++ comp->ops->destroy_dctx(&zstrm->ctx); ++ vfree(zstrm->local_copy); ++ zstrm->local_copy = NULL; ++ zstrm->ctx.context = NULL; ++} ++ ++static int zcomp_dstrm_init(struct zcomp *comp, struct zcomp_dstrm *zstrm) ++{ ++ int ret; ++ ++ if (comp->ops->create_dctx) { ++ ret = comp->ops->create_dctx(comp->params, &zstrm->ctx); ++ if (ret) { ++ /* backend has released partially created context */ ++ zstrm->ctx.context = NULL; ++ return ret; ++ } ++ } ++ ++ zstrm->local_copy = vzalloc(PAGE_SIZE); ++ if (!zstrm->local_copy) { ++ zcomp_dstrm_free(comp, zstrm); + return -ENOMEM; + } + return 0; +@@ -112,10 +149,15 @@ ssize_t zcomp_available_show(const char *comp, char *buf, ssize_t at) + return at; + } + +-struct zcomp_strm *zcomp_stream_get(struct zcomp *comp) ++struct zcomp_cstrm *zcomp_cstrm_get(struct zcomp *comp) + { ++ if (comp->recomp_cstream) { ++ mutex_lock(&comp->recomp_cstream->lock); ++ return comp->recomp_cstream; ++ } ++ + for (;;) { +- struct zcomp_strm *zstrm = raw_cpu_ptr(comp->stream); ++ struct zcomp_cstrm *zstrm = raw_cpu_ptr(comp->cstream); + + /* + * Inspired by zswap +@@ -128,18 +170,91 @@ struct zcomp_strm *zcomp_stream_get(struct zcomp *comp) + * so then unlock and re-try on the current CPU. + */ + mutex_lock(&zstrm->lock); +- if (likely(zstrm->buffer)) ++ if (zstrm->buffer) + return zstrm; + mutex_unlock(&zstrm->lock); + } + } + +-void zcomp_stream_put(struct zcomp_strm *zstrm) ++void zcomp_cstrm_put(struct zcomp_cstrm *zstrm) + { + mutex_unlock(&zstrm->lock); + } + +-int zcomp_compress(struct zcomp *comp, struct zcomp_strm *zstrm, ++bool zcomp_shared_decomp(struct zcomp *comp) ++{ ++ /* ++ * Shared decompression is only safe when the backend has no ++ * mutable per-stream decompression context. ++ */ ++ return !comp->ops->create_dctx; ++} ++ ++static bool zcomp_dstrm_excl_trylock(struct zcomp_dstrm *zstrm) ++{ ++ /* Cheap pre-check: don't touch a busy stream's cachelines */ ++ if (mutex_is_locked(&zstrm->excl_lock)) ++ return false; ++ /* ++ * Pin the stream. The write side of ->lock is only taken by ++ * zcomp_cpu_dead(), which also sets ->local_copy to NULL. ++ */ ++ if (!down_read_trylock(&zstrm->lock)) ++ return false; ++ if (zstrm->local_copy && mutex_trylock(&zstrm->excl_lock)) ++ return true; ++ up_read(&zstrm->lock); ++ return false; ++} ++ ++static struct zcomp_dstrm *zcomp_dstrm_excl_tryget(struct zcomp *comp) ++{ ++ unsigned int cpu, start = raw_smp_processor_id(); ++ struct zcomp_dstrm *zstrm; ++ ++ /* Best-effort start CPU hint; migration during the scan is fine */ ++ for_each_online_cpu_wrap(cpu, start) { ++ zstrm = per_cpu_ptr(comp->dstream, cpu); ++ if (zcomp_dstrm_excl_trylock(zstrm)) ++ return zstrm; ++ } ++ return NULL; ++} ++ ++struct zcomp_dstrm *zcomp_dstrm_get(struct zcomp *comp, ++ enum zcomp_dstrm_mode mode) ++{ ++ struct zcomp_dstrm *zstrm; ++ ++ if (mode == ZCOMP_DSTRM_SHARED) { ++ for (;;) { ++ zstrm = raw_cpu_ptr(comp->dstream); ++ down_read(&zstrm->lock); ++ if (zstrm->local_copy) ++ return zstrm; ++ up_read(&zstrm->lock); ++ } ++ } ++ ++ /* Checks zcomp_dstrm_excl_tryget() before touching the waitq */ ++ wait_event(comp->dstrm_waitq, (zstrm = zcomp_dstrm_excl_tryget(comp))); ++ return zstrm; ++} ++ ++void zcomp_dstrm_put(struct zcomp *comp, struct zcomp_dstrm *zstrm, ++ enum zcomp_dstrm_mode mode) ++{ ++ if (mode == ZCOMP_DSTRM_EXCLUSIVE) { ++ mutex_unlock(&zstrm->excl_lock); ++ up_read(&zstrm->lock); ++ if (wq_has_sleeper(&comp->dstrm_waitq)) ++ wake_up(&comp->dstrm_waitq); ++ return; ++ } ++ up_read(&zstrm->lock); ++} ++ ++int zcomp_compress(struct zcomp *comp, struct zcomp_cstrm *zstrm, + const void *src, unsigned int *dst_len) + { + struct zcomp_req req = { +@@ -157,58 +272,159 @@ int zcomp_compress(struct zcomp *comp, struct zcomp_strm *zstrm, + return ret; + } + +-int zcomp_decompress(struct zcomp *comp, struct zcomp_strm *zstrm, +- const void *src, unsigned int src_len, void *dst) ++static int zcomp_decompress_buf(struct zcomp *comp, struct zcomp_dstrm *zstrm, ++ struct scatterlist *sg, void *buf, ++ struct zcomp_req *req) ++{ ++ sg_copy_to_buffer(sg, 2, buf, req->src_len); ++ req->src = buf; ++ return comp->ops->decompress(comp->params, &zstrm->ctx, req); ++} ++ ++int zcomp_decompress(struct zcomp *comp, struct zcomp_dstrm *zstrm, ++ struct scatterlist *sg, unsigned int src_len, void *dst) + { + struct zcomp_req req = { +- .src = src, + .dst = dst, + .src_len = src_len, + .dst_len = PAGE_SIZE, + }; ++ void *src; ++ int ret; + + might_sleep(); +- return comp->ops->decompress(comp->params, &zstrm->ctx, &req); ++ lockdep_assert_held(&zstrm->lock); ++ if (!zcomp_shared_decomp(comp)) ++ lockdep_assert_held(&zstrm->excl_lock); ++ ++ if (sg_is_last(sg)) { ++ /* the object is contained within one page, read it in-place */ ++ src = kmap_local_page(sg_page(sg)); ++ req.src = src + sg->offset; ++ ret = comp->ops->decompress(comp->params, &zstrm->ctx, &req); ++ kunmap_local(src); ++ return ret; ++ } ++ ++ /* exclusive mode already holds ->excl_lock */ ++ if (!zcomp_shared_decomp(comp)) ++ return zcomp_decompress_buf(comp, zstrm, sg, zstrm->local_copy, ++ &req); ++ ++ /* shared mode: try a per-request bounce buffer first */ ++ src = kmalloc(src_len, GFP_NOWAIT | __GFP_NOWARN); ++ if (src) { ++ ret = zcomp_decompress_buf(comp, zstrm, sg, src, &req); ++ kfree(src); ++ return ret; ++ } ++ ++ /* fall back to ->local_copy serialized by ->excl_lock */ ++ mutex_lock(&zstrm->excl_lock); ++ ret = zcomp_decompress_buf(comp, zstrm, sg, zstrm->local_copy, &req); ++ mutex_unlock(&zstrm->excl_lock); ++ if (wq_has_sleeper(&comp->dstrm_waitq)) ++ wake_up(&comp->dstrm_waitq); ++ return ret; + } + + int zcomp_cpu_up_prepare(unsigned int cpu, struct hlist_node *node) + { + struct zcomp *comp = hlist_entry(node, struct zcomp, node); +- struct zcomp_strm *zstrm = per_cpu_ptr(comp->stream, cpu); ++ struct zcomp_cstrm *cstrm = NULL; ++ struct zcomp_dstrm *dstrm; + int ret; + +- ret = zcomp_strm_init(comp, zstrm); +- if (ret) +- pr_err("Can't allocate a compression stream\n"); +- return ret; ++ if (comp->cstream) { ++ cstrm = per_cpu_ptr(comp->cstream, cpu); ++ ret = zcomp_cstrm_init(comp, cstrm); ++ if (ret) { ++ pr_err("Can't allocate a compression stream\n"); ++ return ret; ++ } ++ } ++ ++ dstrm = per_cpu_ptr(comp->dstream, cpu); ++ ret = zcomp_dstrm_init(comp, dstrm); ++ if (ret) { ++ pr_err("Can't allocate a decompression stream\n"); ++ if (cstrm) ++ zcomp_cstrm_free(comp, cstrm); ++ return ret; ++ } ++ ++ return 0; + } + + int zcomp_cpu_dead(unsigned int cpu, struct hlist_node *node) + { + struct zcomp *comp = hlist_entry(node, struct zcomp, node); +- struct zcomp_strm *zstrm = per_cpu_ptr(comp->stream, cpu); ++ struct zcomp_cstrm *cstrm; ++ struct zcomp_dstrm *dstrm; ++ ++ if (comp->cstream) { ++ cstrm = per_cpu_ptr(comp->cstream, cpu); ++ mutex_lock(&cstrm->lock); ++ zcomp_cstrm_free(comp, cstrm); ++ mutex_unlock(&cstrm->lock); ++ } ++ ++ dstrm = per_cpu_ptr(comp->dstream, cpu); ++ down_write(&dstrm->lock); ++ zcomp_dstrm_free(comp, dstrm); ++ up_write(&dstrm->lock); + +- mutex_lock(&zstrm->lock); +- zcomp_strm_free(comp, zstrm); +- mutex_unlock(&zstrm->lock); + return 0; + } + +-static int zcomp_init(struct zcomp *comp, struct zcomp_params *params) ++static int zcomp_init(struct zcomp *comp, struct zcomp_params *params, ++ bool recomp) + { + int ret, cpu; + +- comp->stream = alloc_percpu(struct zcomp_strm); +- if (!comp->stream) +- return -ENOMEM; +- + comp->params = params; + ret = comp->ops->setup_params(comp->params); + if (ret) + goto cleanup; + +- for_each_possible_cpu(cpu) +- mutex_init(&per_cpu_ptr(comp->stream, cpu)->lock); ++ if (recomp) { ++ comp->recomp_cstream = kzalloc_obj(*comp->recomp_cstream); ++ if (!comp->recomp_cstream) { ++ ret = -ENOMEM; ++ goto cleanup; ++ } ++ mutex_init(&comp->recomp_cstream->lock); ++ ret = zcomp_cstrm_init(comp, comp->recomp_cstream); ++ if (ret) { ++ /* zcomp_cstrm_init() cleans up after itself */ ++ kfree(comp->recomp_cstream); ++ comp->recomp_cstream = NULL; ++ goto cleanup; ++ } ++ } else { ++ comp->cstream = alloc_percpu(struct zcomp_cstrm); ++ if (!comp->cstream) { ++ ret = -ENOMEM; ++ goto cleanup; ++ } ++ for_each_possible_cpu(cpu) ++ mutex_init(&per_cpu_ptr(comp->cstream, cpu)->lock); ++ } ++ ++ comp->dstream = alloc_percpu(struct zcomp_dstrm); ++ if (!comp->dstream) { ++ ret = -ENOMEM; ++ goto cleanup; ++ } ++ ++ init_waitqueue_head(&comp->dstrm_waitq); ++ ++ for_each_possible_cpu(cpu) { ++ struct zcomp_dstrm *zstrm = per_cpu_ptr(comp->dstream, cpu); ++ ++ init_rwsem(&zstrm->lock); ++ mutex_init(&zstrm->excl_lock); ++ } + + ret = cpuhp_state_add_instance(CPUHP_ZCOMP_PREPARE, &comp->node); + if (ret < 0) +@@ -217,20 +433,31 @@ static int zcomp_init(struct zcomp *comp, struct zcomp_params *params) + return 0; + + cleanup: ++ if (comp->recomp_cstream) { ++ zcomp_cstrm_free(comp, comp->recomp_cstream); ++ kfree(comp->recomp_cstream); ++ } + comp->ops->release_params(comp->params); +- free_percpu(comp->stream); ++ free_percpu(comp->dstream); ++ free_percpu(comp->cstream); + return ret; + } + + void zcomp_destroy(struct zcomp *comp) + { + cpuhp_state_remove_instance(CPUHP_ZCOMP_PREPARE, &comp->node); ++ if (comp->recomp_cstream) { ++ zcomp_cstrm_free(comp, comp->recomp_cstream); ++ kfree(comp->recomp_cstream); ++ } + comp->ops->release_params(comp->params); +- free_percpu(comp->stream); ++ free_percpu(comp->dstream); ++ free_percpu(comp->cstream); + kfree(comp); + } + +-struct zcomp *zcomp_create(const char *alg, struct zcomp_params *params) ++struct zcomp *zcomp_create(const char *alg, struct zcomp_params *params, ++ bool recomp) + { + struct zcomp *comp; + int error; +@@ -253,7 +480,7 @@ struct zcomp *zcomp_create(const char *alg, struct zcomp_params *params) + return ERR_PTR(-EINVAL); + } + +- error = zcomp_init(comp, params); ++ error = zcomp_init(comp, params, recomp); + if (error) { + kfree(comp); + return ERR_PTR(error); +diff --git a/drivers/block/zram/zcomp.h b/drivers/block/zram/zcomp.h +index 81a0f3f..39efefc 100644 +--- a/drivers/block/zram/zcomp.h ++++ b/drivers/block/zram/zcomp.h +@@ -4,9 +4,18 @@ + #define _ZCOMP_H_ + + #include ++#include ++#include ++ ++struct scatterlist; + + #define ZCOMP_PARAM_NOT_SET INT_MIN + ++enum zcomp_dstrm_mode { ++ ZCOMP_DSTRM_SHARED, ++ ZCOMP_DSTRM_EXCLUSIVE, ++}; ++ + struct deflate_params { + s32 winbits; + }; +@@ -31,16 +40,29 @@ struct zcomp_params { + /* + * Run-time driver context - scratch buffers, etc. It is modified during + * request execution (compression/decompression), cannot be shared, so +- * it's in per-CPU area. ++ * it's in per-CPU area (except for recompression, which uses a single ++ * per-device compression stream). + */ + struct zcomp_ctx { + void *context; + }; + +-struct zcomp_strm { ++struct zcomp_cstrm { + struct mutex lock; + /* compression buffer */ + void *buffer; ++ struct zcomp_ctx ctx; ++}; ++ ++struct zcomp_dstrm { ++ /* ++ * Pins the stream: held in read mode by every user, regardless ++ * of the decompression mode, and in write mode only by ++ * zcomp_cpu_dead(). ++ */ ++ struct rw_semaphore lock; ++ /* Serializes users of the mutable stream state: ->local_copy, ->ctx */ ++ struct mutex excl_lock; + /* local copy of handle memory */ + void *local_copy; + struct zcomp_ctx ctx; +@@ -60,8 +82,11 @@ struct zcomp_ops { + int (*decompress)(struct zcomp_params *params, struct zcomp_ctx *ctx, + struct zcomp_req *req); + +- int (*create_ctx)(struct zcomp_params *params, struct zcomp_ctx *ctx); +- void (*destroy_ctx)(struct zcomp_ctx *ctx); ++ int (*create_cctx)(struct zcomp_params *params, struct zcomp_ctx *ctx); ++ void (*destroy_cctx)(struct zcomp_ctx *ctx); ++ ++ int (*create_dctx)(struct zcomp_params *params, struct zcomp_ctx *ctx); ++ void (*destroy_dctx)(struct zcomp_ctx *ctx); + + int (*setup_params)(struct zcomp_params *params); + void (*release_params)(struct zcomp_params *params); +@@ -71,7 +96,10 @@ struct zcomp_ops { + + /* dynamic per-device compression frontend */ + struct zcomp { +- struct zcomp_strm __percpu *stream; ++ struct zcomp_dstrm __percpu *dstream; ++ wait_queue_head_t dstrm_waitq; ++ struct zcomp_cstrm __percpu *cstream; ++ struct zcomp_cstrm *recomp_cstream; + const struct zcomp_ops *ops; + struct zcomp_params *params; + struct hlist_node node; +@@ -82,15 +110,22 @@ int zcomp_cpu_dead(unsigned int cpu, struct hlist_node *node); + ssize_t zcomp_available_show(const char *comp, char *buf, ssize_t at); + const char *zcomp_lookup_backend_name(const char *comp); + +-struct zcomp *zcomp_create(const char *alg, struct zcomp_params *params); ++struct zcomp *zcomp_create(const char *alg, struct zcomp_params *params, ++ bool recomp); + void zcomp_destroy(struct zcomp *comp); + +-struct zcomp_strm *zcomp_stream_get(struct zcomp *comp); +-void zcomp_stream_put(struct zcomp_strm *zstrm); ++struct zcomp_cstrm *zcomp_cstrm_get(struct zcomp *comp); ++void zcomp_cstrm_put(struct zcomp_cstrm *zstrm); ++ ++bool zcomp_shared_decomp(struct zcomp *comp); ++struct zcomp_dstrm *zcomp_dstrm_get(struct zcomp *comp, ++ enum zcomp_dstrm_mode mode); ++void zcomp_dstrm_put(struct zcomp *comp, struct zcomp_dstrm *zstrm, ++ enum zcomp_dstrm_mode mode); + +-int zcomp_compress(struct zcomp *comp, struct zcomp_strm *zstrm, ++int zcomp_compress(struct zcomp *comp, struct zcomp_cstrm *zstrm, + const void *src, unsigned int *dst_len); +-int zcomp_decompress(struct zcomp *comp, struct zcomp_strm *zstrm, +- const void *src, unsigned int src_len, void *dst); ++int zcomp_decompress(struct zcomp *comp, struct zcomp_dstrm *zstrm, ++ struct scatterlist *sg, unsigned int src_len, void *dst); + + #endif /* _ZCOMP_H_ */ +diff --git a/drivers/block/zram/zram_drv.c b/drivers/block/zram/zram_drv.c +index 4ba0f77..5e5ad2e 100644 +--- a/drivers/block/zram/zram_drv.c ++++ b/drivers/block/zram/zram_drv.c +@@ -32,6 +32,7 @@ + #include + #include + #include ++#include + #include + #include + +@@ -693,6 +694,7 @@ static void reset_bdev(struct zram *zram) + zram->disk->fops = &zram_devops; + kvfree(zram->bitmap); + zram->bitmap = NULL; ++ zram->nr_pages = 0; + } + + static ssize_t backing_dev_show(struct device *dev, +@@ -1346,10 +1348,10 @@ static ssize_t writeback_store(struct device *dev, + static int decompress_bdev_page(struct zram *zram, struct page *page, + unsigned long index) + { +- struct zcomp_strm *zstrm; ++ struct zcomp_dstrm *zstrm; ++ struct scatterlist sg[1]; + unsigned int size; + int ret, prio; +- void *src; + + slot_lock(zram, index); + /* Since slot was unlocked we need to make sure it's still ZRAM_WB */ +@@ -1368,14 +1370,19 @@ static int decompress_bdev_page(struct zram *zram, struct page *page, + size = get_slot_size(zram, index); + prio = get_slot_comp_priority(zram, index); + +- zstrm = zcomp_stream_get(zram->comps[prio]); +- src = kmap_local_page(page); +- ret = zcomp_decompress(zram->comps[prio], zstrm, src, size, ++ sg_init_table(sg, 1); ++ sg_set_page(sg, page, size, 0); ++ ++ zstrm = zcomp_dstrm_get(zram->comps[prio], ZCOMP_DSTRM_EXCLUSIVE); ++ ret = zcomp_decompress(zram->comps[prio], zstrm, sg, size, + zstrm->local_copy); +- if (!ret) +- copy_page(src, zstrm->local_copy); +- kunmap_local(src); +- zcomp_stream_put(zstrm); ++ if (!ret) { ++ void *dst = kmap_local_page(page); ++ ++ copy_page(dst, zstrm->local_copy); ++ kunmap_local(dst); ++ } ++ zcomp_dstrm_put(zram->comps[prio], zstrm, ZCOMP_DSTRM_EXCLUSIVE); + slot_unlock(zram, index); + + return ret; +@@ -1547,68 +1554,70 @@ static void zram_debugfs_destroy(void) + debugfs_remove_recursive(zram_debugfs_root); + } + +-static ssize_t read_block_state(struct file *file, char __user *buf, +- size_t count, loff_t *ppos) ++static void *zram_block_state_start(struct seq_file *seq, loff_t *pos) + { +- char *kbuf; +- unsigned long index; +- ssize_t written = 0; +- struct zram *zram = file->private_data; ++ struct zram *zram = seq->private; + unsigned long nr_pages; + +- kbuf = kvmalloc(count, GFP_KERNEL); +- if (!kbuf) +- return -ENOMEM; +- +- guard(rwsem_read)(&zram->dev_lock); +- if (!init_done(zram)) { +- kvfree(kbuf); +- return -EINVAL; +- } ++ down_read(&zram->dev_lock); ++ if (!init_done(zram)) ++ return ERR_PTR(-EINVAL); + + nr_pages = zram->disksize >> PAGE_SHIFT; ++ if (*pos >= nr_pages) ++ return NULL; + +- for (index = *ppos; index < nr_pages; index++) { +- int copied; ++ return pos; ++} + +- slot_lock(zram, index); +- if (!slot_allocated(zram, index)) +- goto next; ++static void *zram_block_state_next(struct seq_file *seq, void *v, loff_t *pos) ++{ ++ struct zram *zram = seq->private; ++ unsigned long nr_pages = zram->disksize >> PAGE_SHIFT; + +- copied = snprintf(kbuf + written, count, +- "%12lu %12u.%06d %c%c%c%c%c%c\n", +- index, zram->table[index].attr.ac_time, 0, +- test_slot_flag(zram, index, ZRAM_SAME) ? 's' : '.', +- test_slot_flag(zram, index, ZRAM_WB) ? 'w' : '.', +- test_slot_flag(zram, index, ZRAM_HUGE) ? 'h' : '.', +- test_slot_flag(zram, index, ZRAM_IDLE) ? 'i' : '.', +- get_slot_comp_priority(zram, index) ? 'r' : '.', +- test_slot_flag(zram, index, +- ZRAM_INCOMPRESSIBLE) ? 'n' : '.'); +- +- if (count <= copied) { +- slot_unlock(zram, index); +- break; +- } +- written += copied; +- count -= copied; +-next: +- slot_unlock(zram, index); +- *ppos += 1; +- } ++ ++*pos; ++ if (*pos >= nr_pages) ++ return NULL; + +- if (copy_to_user(buf, kbuf, written)) +- written = -EFAULT; +- kvfree(kbuf); ++ return pos; ++} + +- return written; ++static void zram_block_state_stop(struct seq_file *seq, void *v) ++{ ++ struct zram *zram = seq->private; ++ ++ up_read(&zram->dev_lock); ++} ++ ++static int zram_block_state_show(struct seq_file *seq, void *v) ++{ ++ struct zram *zram = seq->private; ++ unsigned long index = *(loff_t *)v; ++ ++ slot_lock(zram, index); ++ if (slot_allocated(zram, index)) { ++ seq_printf(seq, "%12lu %12u.%06d %c%c%c%c%c%c\n", ++ index, zram->table[index].attr.ac_time, 0, ++ test_slot_flag(zram, index, ZRAM_SAME) ? 's' : '.', ++ test_slot_flag(zram, index, ZRAM_WB) ? 'w' : '.', ++ test_slot_flag(zram, index, ZRAM_HUGE) ? 'h' : '.', ++ test_slot_flag(zram, index, ZRAM_IDLE) ? 'i' : '.', ++ get_slot_comp_priority(zram, index) ? 'r' : '.', ++ test_slot_flag(zram, index, ++ ZRAM_INCOMPRESSIBLE) ? 'n' : '.'); ++ } ++ slot_unlock(zram, index); ++ ++ return 0; + } + +-static const struct file_operations proc_zram_block_state_op = { +- .open = simple_open, +- .read = read_block_state, +- .llseek = default_llseek, ++static const struct seq_operations zram_block_state_sops = { ++ .start = zram_block_state_start, ++ .next = zram_block_state_next, ++ .stop = zram_block_state_stop, ++ .show = zram_block_state_show, + }; ++DEFINE_SEQ_ATTRIBUTE(zram_block_state); + + static void zram_debugfs_register(struct zram *zram) + { +@@ -1618,7 +1627,7 @@ static void zram_debugfs_register(struct zram *zram) + zram->debugfs_dir = debugfs_create_dir(zram->disk->disk_name, + zram_debugfs_root); + debugfs_create_file("block_state", 0400, zram->debugfs_dir, +- zram, &proc_zram_block_state_op); ++ zram, &zram_block_state_fops); + } + + static void zram_debugfs_unregister(struct zram *zram) +@@ -2091,15 +2100,19 @@ static int read_same_filled_page(struct zram *zram, struct page *page, + static int read_incompressible_page(struct zram *zram, struct page *page, + unsigned long index) + { ++ struct scatterlist sg[2]; + unsigned long handle; + void *src, *dst; + + handle = get_slot_handle(zram, index); +- src = zs_obj_read_begin(zram->mem_pool, handle, PAGE_SIZE, NULL); ++ zs_obj_read_sg_begin(zram->mem_pool, handle, sg, PAGE_SIZE); ++ /* an incompressible object never spans two pages */ ++ src = kmap_local_page(sg_page(sg)); + dst = kmap_local_page(page); + copy_page(dst, src); + kunmap_local(dst); +- zs_obj_read_end(zram->mem_pool, handle, PAGE_SIZE, src); ++ kunmap_local(src); ++ zs_obj_read_sg_end(zram->mem_pool, handle); + + return 0; + } +@@ -2107,24 +2120,28 @@ static int read_incompressible_page(struct zram *zram, struct page *page, + static int read_compressed_page(struct zram *zram, struct page *page, + unsigned long index) + { +- struct zcomp_strm *zstrm; ++ enum zcomp_dstrm_mode mode = ZCOMP_DSTRM_EXCLUSIVE; ++ struct zcomp_dstrm *zstrm; ++ struct scatterlist sg[2]; + unsigned long handle; + unsigned int size; +- void *src, *dst; ++ void *dst; + int ret, prio; + + handle = get_slot_handle(zram, index); + size = get_slot_size(zram, index); + prio = get_slot_comp_priority(zram, index); + +- zstrm = zcomp_stream_get(zram->comps[prio]); +- src = zs_obj_read_begin(zram->mem_pool, handle, size, +- zstrm->local_copy); ++ zs_obj_read_sg_begin(zram->mem_pool, handle, sg, size); ++ if (zcomp_shared_decomp(zram->comps[prio])) ++ mode = ZCOMP_DSTRM_SHARED; ++ ++ zstrm = zcomp_dstrm_get(zram->comps[prio], mode); + dst = kmap_local_page(page); +- ret = zcomp_decompress(zram->comps[prio], zstrm, src, size, dst); ++ ret = zcomp_decompress(zram->comps[prio], zstrm, sg, size, dst); + kunmap_local(dst); +- zs_obj_read_end(zram->mem_pool, handle, size, src); +- zcomp_stream_put(zstrm); ++ zcomp_dstrm_put(zram->comps[prio], zstrm, mode); ++ zs_obj_read_sg_end(zram->mem_pool, handle); + + return ret; + } +@@ -2133,25 +2150,23 @@ static int read_compressed_page(struct zram *zram, struct page *page, + static int read_from_zspool_raw(struct zram *zram, struct page *page, + unsigned long index) + { +- struct zcomp_strm *zstrm; ++ struct scatterlist sg[2]; + unsigned long handle; + unsigned int size; +- void *src; ++ void *dst; + + handle = get_slot_handle(zram, index); + size = get_slot_size(zram, index); + + /* +- * We need to get stream just for ->local_copy buffer, in +- * case if object spans two physical pages. No decompression +- * takes place here, as we read raw compressed data. ++ * No decompression takes place here, we copy out raw compressed ++ * data directly into the destination page. + */ +- zstrm = zcomp_stream_get(zram->comps[ZRAM_PRIMARY_COMP]); +- src = zs_obj_read_begin(zram->mem_pool, handle, size, +- zstrm->local_copy); +- memcpy_to_page(page, 0, src, size); +- zs_obj_read_end(zram->mem_pool, handle, size, src); +- zcomp_stream_put(zstrm); ++ zs_obj_read_sg_begin(zram->mem_pool, handle, sg, size); ++ dst = kmap_local_page(page); ++ sg_copy_to_buffer(sg, sg_nents(sg), dst, size); ++ kunmap_local(dst); ++ zs_obj_read_sg_end(zram->mem_pool, handle); + + memzero_page(page, size, PAGE_SIZE - size); + +@@ -2182,6 +2197,7 @@ static int zram_read_page(struct zram *zram, struct page *page, + int ret; + + slot_lock(zram, index); ++ mark_slot_accessed(zram, index); + if (!test_slot_flag(zram, index, ZRAM_WB)) { + /* Slot should be locked through out the function call */ + ret = read_from_zspool(zram, page, index); +@@ -2197,10 +2213,6 @@ static int zram_read_page(struct zram *zram, struct page *page, + ret = read_from_bdev(zram, page, index, blk_idx, parent); + } + +- /* Should NEVER happen. Return bio error if it does. */ +- if (WARN_ON(ret < 0)) +- pr_err("Decompression failed! err=%d, page=%lu\n", ret, index); +- + return ret; + } + +@@ -2238,6 +2250,7 @@ static int write_same_filled_page(struct zram *zram, unsigned long fill, + slot_free(zram, index); + set_slot_flag(zram, index, ZRAM_SAME); + set_slot_handle(zram, index, fill); ++ mark_slot_accessed(zram, index); + slot_unlock(zram, index); + + atomic64_inc(&zram->stats.same_pages); +@@ -2277,6 +2290,7 @@ static int write_incompressible_page(struct zram *zram, struct page *page, + set_slot_flag(zram, index, ZRAM_HUGE); + set_slot_handle(zram, index, handle); + set_slot_size(zram, index, PAGE_SIZE); ++ mark_slot_accessed(zram, index); + slot_unlock(zram, index); + + atomic64_add(PAGE_SIZE, &zram->stats.compr_data_size); +@@ -2294,7 +2308,7 @@ static int zram_write_page(struct zram *zram, struct page *page, + unsigned long handle; + unsigned int comp_len; + void *mem; +- struct zcomp_strm *zstrm; ++ struct zcomp_cstrm *zstrm; + unsigned long element; + bool same_filled; + +@@ -2304,20 +2318,20 @@ static int zram_write_page(struct zram *zram, struct page *page, + if (same_filled) + return write_same_filled_page(zram, element, index); + +- zstrm = zcomp_stream_get(zram->comps[ZRAM_PRIMARY_COMP]); ++ zstrm = zcomp_cstrm_get(zram->comps[ZRAM_PRIMARY_COMP]); + mem = kmap_local_page(page); + ret = zcomp_compress(zram->comps[ZRAM_PRIMARY_COMP], zstrm, + mem, &comp_len); + kunmap_local(mem); + + if (unlikely(ret)) { +- zcomp_stream_put(zstrm); ++ zcomp_cstrm_put(zstrm); + pr_err("Compression failed! err=%d\n", ret); + return ret; + } + + if (comp_len >= huge_class_size) { +- zcomp_stream_put(zstrm); ++ zcomp_cstrm_put(zstrm); + return write_incompressible_page(zram, page, index); + } + +@@ -2325,23 +2339,24 @@ static int zram_write_page(struct zram *zram, struct page *page, + GFP_NOIO | __GFP_NOWARN | + __GFP_HIGHMEM | __GFP_MOVABLE, page_to_nid(page)); + if (IS_ERR_VALUE(handle)) { +- zcomp_stream_put(zstrm); ++ zcomp_cstrm_put(zstrm); + return PTR_ERR((void *)handle); + } + + if (!zram_can_store_page(zram)) { +- zcomp_stream_put(zstrm); ++ zcomp_cstrm_put(zstrm); + zs_free(zram->mem_pool, handle); + return -ENOMEM; + } + + zs_obj_write(zram->mem_pool, handle, zstrm->buffer, comp_len); +- zcomp_stream_put(zstrm); ++ zcomp_cstrm_put(zstrm); + + slot_lock(zram, index); + slot_free(zram, index); + set_slot_handle(zram, index, handle); + set_slot_size(zram, index, comp_len); ++ mark_slot_accessed(zram, index); + slot_unlock(zram, index); + + /* Update stats */ +@@ -2445,7 +2460,7 @@ static int recompress_slot(struct zram *zram, unsigned long index, + struct page *page, u64 *num_recomp_pages, + u32 threshold, u32 prio) + { +- struct zcomp_strm *zstrm = NULL; ++ struct zcomp_cstrm *zstrm = NULL; + unsigned long handle_old; + unsigned long handle_new; + unsigned int comp_len_old; +@@ -2477,7 +2492,7 @@ static int recompress_slot(struct zram *zram, unsigned long index, + */ + clear_slot_flag(zram, index, ZRAM_IDLE); + +- zstrm = zcomp_stream_get(zram->comps[prio]); ++ zstrm = zcomp_cstrm_get(zram->comps[prio]); + src = kmap_local_page(page); + ret = zcomp_compress(zram->comps[prio], zstrm, src, &comp_len_new); + kunmap_local(src); +@@ -2492,7 +2507,7 @@ static int recompress_slot(struct zram *zram, unsigned long index, + *num_recomp_pages -= 1; + + if (ret) { +- zcomp_stream_put(zstrm); ++ zcomp_cstrm_put(zstrm); + return ret; + } + +@@ -2501,7 +2516,7 @@ static int recompress_slot(struct zram *zram, unsigned long index, + + if (class_index_new >= class_index_old || + (threshold && comp_len_new >= threshold)) { +- zcomp_stream_put(zstrm); ++ zcomp_cstrm_put(zstrm); + + /* + * Secondary algorithms failed to re-compress the page +@@ -2516,7 +2531,7 @@ static int recompress_slot(struct zram *zram, unsigned long index, + } + + /* +- * We are holding per-CPU stream mutex and entry lock so better ++ * We are holding compression stream mutex and entry lock so better + * avoid direct reclaim. Allocation error is not fatal since + * we still have the old object in the mem_pool. + * +@@ -2530,12 +2545,12 @@ static int recompress_slot(struct zram *zram, unsigned long index, + __GFP_HIGHMEM | __GFP_MOVABLE, + page_to_nid(page)); + if (IS_ERR_VALUE(handle_new)) { +- zcomp_stream_put(zstrm); ++ zcomp_cstrm_put(zstrm); + return PTR_ERR((void *)handle_new); + } + + zs_obj_write(zram->mem_pool, handle_new, zstrm->buffer, comp_len_new); +- zcomp_stream_put(zstrm); ++ zcomp_cstrm_put(zstrm); + + slot_free(zram, index); + set_slot_handle(zram, index, handle_new); +@@ -2750,10 +2765,6 @@ static void zram_bio_read(struct zram *zram, struct bio *bio) + } + flush_dcache_page(bv.bv_page); + +- slot_lock(zram, index); +- mark_slot_accessed(zram, index); +- slot_unlock(zram, index); +- + bio_advance_iter_single(bio, &iter, bv.bv_len); + } while (iter.bi_size); + +@@ -2780,10 +2791,6 @@ static void zram_bio_write(struct zram *zram, struct bio *bio) + break; + } + +- slot_lock(zram, index); +- mark_slot_accessed(zram, index); +- slot_unlock(zram, index); +- + bio_advance_iter_single(bio, &iter, bv.bv_len); + } while (iter.bi_size); + +@@ -2876,6 +2883,12 @@ static void zram_reset_device(struct zram *zram) + zram_destroy_comps(zram); + memset(&zram->stats, 0, sizeof(zram->stats)); + reset_bdev(zram); ++#ifdef CONFIG_ZRAM_WRITEBACK ++ zram->wb_limit_enable = false; ++ zram->bd_wb_limit = 0; ++ zram->wb_batch_size = 32; ++ zram->compressed_wb = false; ++#endif + } + + static ssize_t disksize_store(struct device *dev, struct device_attribute *attr, +@@ -2912,7 +2925,8 @@ static ssize_t disksize_store(struct device *dev, struct device_attribute *attr, + continue; + + comp = zcomp_create(zram->comp_algs[prio], +- &zram->params[prio]); ++ &zram->params[prio], ++ prio != ZRAM_PRIMARY_COMP); + if (IS_ERR(comp)) { + pr_err("Cannot initialise %s compressing backend\n", + zram->comp_algs[prio]); +@@ -3292,6 +3306,7 @@ static int __init zram_init(void) + if (zram_major <= 0) { + pr_err("Unable to get major number\n"); + class_unregister(&zram_control_class); ++ zram_debugfs_destroy(); + cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE); + return -EBUSY; + } +diff --git a/drivers/cpufreq/Kconfig.x86 b/drivers/cpufreq/Kconfig.x86 +index d6190b8..9d10fde 100644 +--- a/drivers/cpufreq/Kconfig.x86 ++++ b/drivers/cpufreq/Kconfig.x86 +@@ -8,7 +8,6 @@ config X86_INTEL_PSTATE + select ACPI_PROCESSOR if ACPI + select ACPI_CPPC_LIB if X86_64 && ACPI && SCHED_MC_PRIO + select CPU_FREQ_GOV_PERFORMANCE +- select CPU_FREQ_GOV_SCHEDUTIL if SMP + help + This driver provides a P state for Intel core processors. + The driver implements an internal governor and will become +@@ -38,7 +37,6 @@ config X86_AMD_PSTATE + depends on ACPI + select ACPI_PROCESSOR + select ACPI_CPPC_LIB if X86_64 +- select CPU_FREQ_GOV_SCHEDUTIL if SMP + select ACPI_PLATFORM_PROFILE + select POWER_SUPPLY + help +diff --git a/drivers/cpufreq/cpufreq_ondemand.c b/drivers/cpufreq/cpufreq_ondemand.c +index 9942dbb..7f8f399 100644 +--- a/drivers/cpufreq/cpufreq_ondemand.c ++++ b/drivers/cpufreq/cpufreq_ondemand.c +@@ -18,10 +18,16 @@ + #include "cpufreq_ondemand.h" + + /* On-demand governor macros */ ++#if defined(CONFIG_ZEN_INTERACTIVE) ++#define DEF_FREQUENCY_UP_THRESHOLD (55) ++#define MICRO_FREQUENCY_UP_THRESHOLD (60) ++#define DEF_SAMPLING_DOWN_FACTOR (5) ++#else + #define DEF_FREQUENCY_UP_THRESHOLD (80) ++#define MICRO_FREQUENCY_UP_THRESHOLD (95) + #define DEF_SAMPLING_DOWN_FACTOR (1) ++#endif + #define MAX_SAMPLING_DOWN_FACTOR (100000) +-#define MICRO_FREQUENCY_UP_THRESHOLD (95) + #define MIN_FREQUENCY_UP_THRESHOLD (1) + #define MAX_FREQUENCY_UP_THRESHOLD (100) + +diff --git a/drivers/cpufreq/intel_pstate.c b/drivers/cpufreq/intel_pstate.c +index 0e6ae4c..90887b3 100644 +--- a/drivers/cpufreq/intel_pstate.c ++++ b/drivers/cpufreq/intel_pstate.c +@@ -3946,6 +3946,8 @@ static int __init intel_pstate_setup(char *str) + + if (!strcmp(str, "disable")) + no_load = 1; ++ else if (!strcmp(str, "enable")) ++ no_load = 0; + else if (!strcmp(str, "active")) + default_driver = &intel_pstate; + else if (!strcmp(str, "passive")) +diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu.h b/drivers/gpu/drm/amd/amdgpu/amdgpu.h +index a63404a..1fd4ca2 100644 +--- a/drivers/gpu/drm/amd/amdgpu/amdgpu.h ++++ b/drivers/gpu/drm/amd/amdgpu/amdgpu.h +@@ -157,6 +157,7 @@ struct amdgpu_watchdog_timer { + */ + extern int amdgpu_modeset; + extern unsigned int amdgpu_vram_limit; ++extern int amdgpu_ignore_min_pcap; + extern int amdgpu_vis_vram_limit; + extern int amdgpu_gart_size; + extern int amdgpu_gtt_size; +diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c +index 6927802..942283c 100644 +--- a/drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c ++++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c +@@ -150,6 +150,7 @@ enum AMDGPU_DEBUG_MASK { + }; + + unsigned int amdgpu_vram_limit = UINT_MAX; ++int amdgpu_ignore_min_pcap = 0; /* do not ignore by default */ + int amdgpu_vis_vram_limit; + int amdgpu_gart_size = -1; /* auto */ + int amdgpu_gtt_size = -1; /* auto */ +@@ -271,6 +272,15 @@ struct amdgpu_watchdog_timer amdgpu_watchdog_timer = { + .period = 0x0, /* default to 0x0 (timeout disable) */ + }; + ++/** ++ * DOC: ignore_min_pcap (int) ++ * Ignore the minimum power cap. ++ * Useful on graphics cards where the minimum power cap is very high. ++ * The default is 0 (Do not ignore). ++ */ ++MODULE_PARM_DESC(ignore_min_pcap, "Ignore the minimum power cap"); ++module_param_named(ignore_min_pcap, amdgpu_ignore_min_pcap, int, 0600); ++ + /** + * DOC: vramlimit (int) + * Restrict the total amount of VRAM in MiB for testing. The default is 0 (Use full VRAM). +diff --git a/drivers/gpu/drm/amd/pm/amdgpu_pm.c b/drivers/gpu/drm/amd/pm/amdgpu_pm.c +index c0e6773..2fa7a42 100644 +--- a/drivers/gpu/drm/amd/pm/amdgpu_pm.c ++++ b/drivers/gpu/drm/amd/pm/amdgpu_pm.c +@@ -3422,6 +3422,9 @@ static ssize_t amdgpu_hwmon_show_power_cap_min(struct device *dev, + struct device_attribute *attr, + char *buf) + { ++ if (amdgpu_ignore_min_pcap) ++ return sysfs_emit(buf, "%i\n", 0); ++ + return amdgpu_hwmon_show_power_cap_generic(dev, attr, buf, PP_PWR_LIMIT_MIN); + } + +diff --git a/drivers/gpu/drm/amd/pm/swsmu/amdgpu_smu.c b/drivers/gpu/drm/amd/pm/swsmu/amdgpu_smu.c +index 9e70a0f..1c4dce1 100644 +--- a/drivers/gpu/drm/amd/pm/swsmu/amdgpu_smu.c ++++ b/drivers/gpu/drm/amd/pm/swsmu/amdgpu_smu.c +@@ -3071,9 +3071,12 @@ int smu_get_ppt_limit(void *handle, + smu->ppt_limits.range[power_source][limit_type].max; + break; + case SMU_PPT_LIMIT_MIN: +- *limit = smu->od_enabled ? +- smu->ppt_limits.range[power_source][limit_type].od_min : +- smu->ppt_limits.range[power_source][limit_type].min; ++ if (amdgpu_ignore_min_pcap && limit_type == SMU_DEFAULT_PPT_LIMIT) ++ *limit = 0; ++ else ++ *limit = smu->od_enabled ? ++ smu->ppt_limits.range[power_source][limit_type].od_min : ++ smu->ppt_limits.range[power_source][limit_type].min; + break; + default: + return -EINVAL; +@@ -3110,7 +3113,9 @@ static int smu_set_ppt_limit(void *handle, uint32_t limit_type, uint32_t limit) + return ret; + } + +- if (limit > max_limit || limit < min_limit) { ++ if (limit > max_limit || ++ (!(amdgpu_ignore_min_pcap && limit_type == SMU_DEFAULT_PPT_LIMIT) && ++ limit < min_limit)) { + dev_err(smu->adev->dev, + "New PPT limit (%d) is out of range [%d,%d]\n", + limit, min_limit, max_limit); +diff --git a/drivers/gpu/drm/i915/display/intel_dp.c b/drivers/gpu/drm/i915/display/intel_dp.c +index d79b636..28cc65f 100644 +--- a/drivers/gpu/drm/i915/display/intel_dp.c ++++ b/drivers/gpu/drm/i915/display/intel_dp.c +@@ -4785,6 +4785,38 @@ intel_edp_set_sink_rates(struct intel_dp *intel_dp) + intel_edp_set_data_override_rates(intel_dp); + } + ++static void intel_edp_wake_sink(struct intel_dp *intel_dp) ++{ ++ u8 value = 0; ++ int ret; ++ ++ /* ++ * Read the current sink power state. drm_dp_dpcd_read_byte() already ++ * retries the AUX transaction internally, so a single read suffices. ++ * First commercial eDP panels are Ver1.0 or 1.1, on which DPCD ++ * DP_SET_POWER is supported. ++ */ ++ ret = drm_dp_dpcd_read_byte(&intel_dp->aux, DP_SET_POWER, &value); ++ ++ /* ++ * If the AUX read failed the sink may be asleep and not responding, ++ * or it read back D3; in either case wake it up to D0. ++ * In case of AUX read failure which is usually a POR case, the ++ * remaining bits of register 0x600 is set to '0' on POR. So a bare ++ * write should be fine. ++ */ ++ if (ret < 0 || value == DP_SET_POWER_D3) { ++ value &= ~DP_SET_POWER_MASK; ++ value |= DP_SET_POWER_D0; ++ drm_dp_dpcd_write_byte(&intel_dp->aux, DP_SET_POWER, ++ value); ++ /* After setting to D0 need a min of 1ms to wake (Spec DP2.1 sec 2.3.1.2) */ ++ fsleep(1000); ++ drm_dp_dpcd_write_byte(&intel_dp->aux, DP_SET_POWER, ++ value); ++ } ++} ++ + static bool + intel_edp_init_dpcd(struct intel_dp *intel_dp, struct intel_connector *connector) + { +@@ -4795,6 +4827,12 @@ intel_edp_init_dpcd(struct intel_dp *intel_dp, struct intel_connector *connector + /* this function is meant to be called only once */ + drm_WARN_ON(display->drm, intel_dp->dpcd[DP_DPCD_REV] != 0); + ++ /* ++ * Spec DP2.1 Section 3.5.2.16 page 966. ++ * Also if sink is asleep, this will wake the sink. ++ */ ++ intel_edp_wake_sink(intel_dp); ++ + if (drm_dp_read_dpcd_caps(&intel_dp->aux, intel_dp->dpcd) != 0) + return false; + +diff --git a/drivers/input/evdev.c b/drivers/input/evdev.c +index 8bfaaa4..cc37779 100644 +--- a/drivers/input/evdev.c ++++ b/drivers/input/evdev.c +@@ -47,6 +47,7 @@ struct evdev_client { + struct fasync_struct *fasync; + struct evdev *evdev; + struct list_head node; ++ struct rcu_head rcu; + enum input_clock_type clk_type; + bool revoked; + unsigned long *evmasks[EV_CNT]; +@@ -373,13 +374,22 @@ static void evdev_attach_client(struct evdev *evdev, + spin_unlock(&evdev->client_lock); + } + ++static void evdev_reclaim_client(struct rcu_head *rp) ++{ ++ struct evdev_client *client = container_of(rp, struct evdev_client, rcu); ++ unsigned int i; ++ for (i = 0; i < EV_CNT; ++i) ++ bitmap_free(client->evmasks[i]); ++ kvfree(client); ++} ++ + static void evdev_detach_client(struct evdev *evdev, + struct evdev_client *client) + { + spin_lock(&evdev->client_lock); + list_del_rcu(&client->node); + spin_unlock(&evdev->client_lock); +- synchronize_rcu(); ++ call_rcu(&client->rcu, evdev_reclaim_client); + } + + static int evdev_open_device(struct evdev *evdev) +@@ -432,7 +442,6 @@ static int evdev_release(struct inode *inode, struct file *file) + { + struct evdev_client *client = file->private_data; + struct evdev *evdev = client->evdev; +- unsigned int i; + + mutex_lock(&evdev->mutex); + +@@ -444,11 +453,6 @@ static int evdev_release(struct inode *inode, struct file *file) + + evdev_detach_client(evdev, client); + +- for (i = 0; i < EV_CNT; ++i) +- bitmap_free(client->evmasks[i]); +- +- kvfree(client); +- + evdev_close_device(evdev); + + return 0; +@@ -491,7 +495,6 @@ static int evdev_open(struct inode *inode, struct file *file) + + err_free_client: + evdev_detach_client(evdev, client); +- kvfree(client); + return error; + } + +diff --git a/drivers/pci/quirks.c b/drivers/pci/quirks.c +index d4fcc33..1f48544 100644 +--- a/drivers/pci/quirks.c ++++ b/drivers/pci/quirks.c +@@ -15,6 +15,7 @@ + #include + #include + #include ++#include + #include + #include + #include +@@ -5112,6 +5113,128 @@ static int pci_quirk_wangxun_nic_acs(struct pci_dev *dev, u16 acs_flags) + return false; + } + ++static bool acs_on_downstream; ++static bool acs_on_multifunction; ++ ++#define NUM_ACS_IDS 16 ++struct acs_on_id { ++ unsigned short vendor; ++ unsigned short device; ++}; ++static struct acs_on_id acs_on_ids[NUM_ACS_IDS]; ++static u8 max_acs_id; ++ ++static int __init pcie_acs_parse_id(const char *p, struct acs_on_id *id) ++{ ++ unsigned int val = 0; ++ int i, d; ++ ++ if (p[7] != ':') ++ return -EINVAL; ++ ++ for (i = 3; i < 12; i++) { ++ if (i == 7) ++ continue; ++ d = hex_to_bin(p[i]); ++ if (d < 0) ++ return -EINVAL; ++ val = (val << 4) | d; ++ } ++ ++ id->vendor = val >> 16; ++ id->device = val & 0xffff; ++ return 0; ++} ++ ++static int __init pcie_acs_override_setup(char *p) ++{ ++ if (!p) ++ return -EINVAL; ++ ++ while (*p) { ++ size_t len = strcspn(p, ","); ++ ++ if (len == strlen("downstream") && ++ !strncmp(p, "downstream", len)) { ++ acs_on_downstream = true; ++ } else if (len == strlen("multifunction") && ++ !strncmp(p, "multifunction", len)) { ++ acs_on_multifunction = true; ++ } else if (len == strlen("id:nnnn:nnnn") && ++ !strncmp(p, "id:", 3)) { ++ struct acs_on_id id; ++ ++ if (pcie_acs_parse_id(p, &id)) { ++ pr_warn("Invalid PCIe ACS override '%.*s'\n", ++ (int)len, p); ++ } else if (max_acs_id >= ARRAY_SIZE(acs_on_ids)) { ++ pr_warn("Out of PCIe ACS override slots (%d)\n", ++ NUM_ACS_IDS); ++ } else { ++ acs_on_ids[max_acs_id++] = id; ++ } ++ } else if (len) { ++ pr_warn("Invalid PCIe ACS override '%.*s'\n", ++ (int)len, p); ++ } ++ ++ p += len; ++ if (*p == ',') ++ p++; ++ } ++ ++ if (acs_on_downstream || acs_on_multifunction || max_acs_id) { ++ pr_warn("Warning: PCIe ACS overrides enabled; This may allow non-IOMMU protected peer-to-peer DMA\n"); ++ add_taint(TAINT_USER, LOCKDEP_STILL_OK); ++ } ++ ++ return 0; ++} ++early_param("pcie_acs_override", pcie_acs_override_setup); ++ ++static int pcie_acs_overrides(struct pci_dev *dev, u16 acs_flags) ++{ ++ int i; ++ ++ if (!acs_on_downstream && !acs_on_multifunction && !max_acs_id) ++ return -ENOTTY; ++ ++ /* Only answer the IOMMU group isolation query (REQ_ACS_FLAGS) */ ++ if (acs_flags != (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)) ++ return -ENOTTY; ++ ++ /* Never override ACS for legacy devices or devices with ACS caps */ ++ if (!pci_is_pcie(dev) || dev->acs_cap) ++ return -ENOTTY; ++ ++ if (dev->untrusted || dev->external_facing) ++ return -ENOTTY; ++ ++ switch (pci_pcie_type(dev)) { ++ case PCI_EXP_TYPE_DOWNSTREAM: ++ case PCI_EXP_TYPE_ROOT_PORT: ++ if (acs_on_downstream) ++ return 1; ++ break; ++ case PCI_EXP_TYPE_ENDPOINT: ++ case PCI_EXP_TYPE_UPSTREAM: ++ case PCI_EXP_TYPE_LEG_END: ++ case PCI_EXP_TYPE_RC_END: ++ if (acs_on_multifunction && dev->multifunction) ++ return 1; ++ break; ++ default: ++ return -ENOTTY; ++ } ++ ++ for (i = 0; i < max_acs_id; i++) ++ if (acs_on_ids[i].vendor == dev->vendor && ++ acs_on_ids[i].device == dev->device) ++ return 1; ++ ++ return -ENOTTY; ++} ++ + static const struct pci_dev_acs_enabled { + u16 vendor; + u16 device; +@@ -5280,6 +5403,7 @@ static const struct pci_dev_acs_enabled { + { PCI_VENDOR_ID_ZHAOXIN, PCI_ANY_ID, pci_quirk_zhaoxin_pcie_ports_acs }, + /* Wangxun nics */ + { PCI_VENDOR_ID_WANGXUN, PCI_ANY_ID, pci_quirk_wangxun_nic_acs }, ++ { PCI_ANY_ID, PCI_ANY_ID, pcie_acs_overrides }, + { 0 } + }; + +diff --git a/drivers/scsi/Kconfig b/drivers/scsi/Kconfig +index 1eec661..7552093 100644 +--- a/drivers/scsi/Kconfig ++++ b/drivers/scsi/Kconfig +@@ -1524,4 +1524,6 @@ endif # SCSI_LOWLEVEL + + source "drivers/scsi/device_handler/Kconfig" + ++source "drivers/scsi/vhba/Kconfig" ++ + endmenu +diff --git a/drivers/scsi/Makefile b/drivers/scsi/Makefile +index 5336233..7f61fa0 100644 +--- a/drivers/scsi/Makefile ++++ b/drivers/scsi/Makefile +@@ -176,6 +176,7 @@ obj-$(CONFIG_CHR_DEV_SCH) += ch.o + obj-$(CONFIG_SCSI_ENCLOSURE) += ses.o + + obj-$(CONFIG_SCSI_HISI_SAS) += hisi_sas/ ++obj-$(CONFIG_VHBA) += vhba/ + + # This goes last, so that "real" scsi devices probe earlier + obj-$(CONFIG_SCSI_DEBUG) += scsi_debug.o +diff --git a/drivers/scsi/vhba/Kconfig b/drivers/scsi/vhba/Kconfig +new file mode 100644 +index 0000000..e70a381 +--- /dev/null ++++ b/drivers/scsi/vhba/Kconfig +@@ -0,0 +1,9 @@ ++config VHBA ++ tristate "Virtual (SCSI) Host Bus Adapter" ++ depends on SCSI ++ help ++ This is the in-kernel part of CDEmu, a CD/DVD-ROM device ++ emulator. ++ ++ This driver can also be built as a module. If so, the module ++ will be called vhba. +diff --git a/drivers/scsi/vhba/Makefile b/drivers/scsi/vhba/Makefile +new file mode 100644 +index 0000000..c55e5c3 +--- /dev/null ++++ b/drivers/scsi/vhba/Makefile +@@ -0,0 +1,4 @@ ++VHBA_VERSION := 20260313 ++ ++obj-$(CONFIG_VHBA) += vhba.o ++ccflags-y := -DVHBA_VERSION=\"$(VHBA_VERSION)\" -Werror +diff --git a/drivers/scsi/vhba/vhba.c b/drivers/scsi/vhba/vhba.c +new file mode 100644 +index 0000000..e24e600 +--- /dev/null ++++ b/drivers/scsi/vhba/vhba.c +@@ -0,0 +1,1136 @@ ++/* ++ * vhba.c ++ * ++ * Copyright (C) 2007-2026 Chia-I Wu ++ * ++ * This program is free software; you can redistribute it and/or modify ++ * it under the terms of the GNU General Public License as published by ++ * the Free Software Foundation; either version 2 of the License, or ++ * (at your option) any later version. ++ * ++ * This program is distributed in the hope that it will be useful, ++ * but WITHOUT ANY WARRANTY; without even the implied warranty of ++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ++ * GNU General Public License for more details. ++ * ++ * You should have received a copy of the GNU General Public License along ++ * with this program; if not, write to the Free Software Foundation, Inc., ++ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ++ */ ++ ++#define pr_fmt(fmt) "vhba: " fmt ++ ++#include ++ ++#include ++#include ++#include ++#include ++#if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 11, 0) ++#include ++#else ++#include ++#endif ++#include ++#include ++#include ++#include ++#include ++#ifdef CONFIG_COMPAT ++#include ++#endif ++#include ++#include ++#include ++#include ++#include ++#include ++ ++ ++MODULE_AUTHOR("Chia-I Wu"); ++MODULE_VERSION(VHBA_VERSION); ++MODULE_DESCRIPTION("Virtual SCSI HBA"); ++MODULE_LICENSE("GPL"); ++ ++ ++#if LINUX_VERSION_CODE < KERNEL_VERSION(3, 15, 0) ++#define sdev_dbg(sdev, fmt, a...) \ ++ dev_dbg(&(sdev)->sdev_gendev, fmt, ##a) ++#define scmd_dbg(scmd, fmt, a...) \ ++ dev_dbg(&(scmd)->device->sdev_gendev, fmt, ##a) ++#endif ++ ++#define VHBA_MAX_SECTORS_PER_IO 256 ++#define VHBA_MAX_BUS 16 ++#define VHBA_MAX_ID 16 ++#define VHBA_MAX_DEVICES (VHBA_MAX_BUS * (VHBA_MAX_ID-1)) ++#define VHBA_KBUF_SIZE PAGE_SIZE ++ ++#define DATA_TO_DEVICE(dir) ((dir) == DMA_TO_DEVICE || (dir) == DMA_BIDIRECTIONAL) ++#define DATA_FROM_DEVICE(dir) ((dir) == DMA_FROM_DEVICE || (dir) == DMA_BIDIRECTIONAL) ++ ++ ++static int vhba_can_queue = 32; ++module_param_named(can_queue, vhba_can_queue, int, 0); ++ ++ ++enum vhba_req_state { ++ VHBA_REQ_FREE, ++ VHBA_REQ_PENDING, ++ VHBA_REQ_READING, ++ VHBA_REQ_SENT, ++ VHBA_REQ_WRITING, ++}; ++ ++struct vhba_command { ++ struct scsi_cmnd *cmd; ++ /* metatags are per-host. not to be confused with ++ queue tags that are usually per-lun */ ++ unsigned long metatag; ++ int status; ++ struct list_head entry; ++}; ++ ++struct vhba_device { ++ unsigned int num; ++ spinlock_t cmd_lock; ++ struct list_head cmd_list; ++ wait_queue_head_t cmd_wq; ++ atomic_t refcnt; ++ ++ unsigned char *kbuf; ++ size_t kbuf_size; ++}; ++ ++struct vhba_host { ++ struct Scsi_Host *shost; ++ spinlock_t cmd_lock; ++ int cmd_next; ++ struct vhba_command *commands; ++ spinlock_t dev_lock; ++ struct vhba_device *devices[VHBA_MAX_DEVICES]; ++ int num_devices; ++ DECLARE_BITMAP(chgmap, VHBA_MAX_DEVICES); ++ int chgtype[VHBA_MAX_DEVICES]; ++ struct work_struct scan_devices; ++}; ++ ++#define MAX_COMMAND_SIZE 16 ++ ++struct vhba_request { ++ __u32 metatag; ++ __u32 lun; ++ __u8 cdb[MAX_COMMAND_SIZE]; ++ __u8 cdb_len; ++ __u32 data_len; ++}; ++ ++struct vhba_response { ++ __u32 metatag; ++ __u32 status; ++ __u32 data_len; ++}; ++ ++ ++ ++static struct vhba_command *vhba_alloc_command (void); ++static void vhba_free_command (struct vhba_command *vcmd); ++ ++static struct platform_device vhba_platform_device; ++ ++ ++ ++/* These functions define a symmetric 1:1 mapping between device numbers and ++ the bus and id. We have reserved the last id per bus for the host itself. */ ++static void devnum_to_bus_and_id(unsigned int devnum, unsigned int *bus, unsigned int *id) ++{ ++ *bus = devnum / (VHBA_MAX_ID-1); ++ *id = devnum % (VHBA_MAX_ID-1); ++} ++ ++static unsigned int bus_and_id_to_devnum(unsigned int bus, unsigned int id) ++{ ++ return (bus * (VHBA_MAX_ID-1)) + id; ++} ++ ++static struct vhba_device *vhba_device_alloc (void) ++{ ++ struct vhba_device *vdev; ++ ++ vdev = kzalloc(sizeof(struct vhba_device), GFP_KERNEL); ++ if (!vdev) { ++ return NULL; ++ } ++ ++ spin_lock_init(&vdev->cmd_lock); ++ INIT_LIST_HEAD(&vdev->cmd_list); ++ init_waitqueue_head(&vdev->cmd_wq); ++ atomic_set(&vdev->refcnt, 1); ++ ++ vdev->kbuf = NULL; ++ vdev->kbuf_size = 0; ++ ++ return vdev; ++} ++ ++static void vhba_device_put (struct vhba_device *vdev) ++{ ++ if (atomic_dec_and_test(&vdev->refcnt)) { ++ kfree(vdev); ++ } ++} ++ ++static struct vhba_device *vhba_device_get (struct vhba_device *vdev) ++{ ++ atomic_inc(&vdev->refcnt); ++ ++ return vdev; ++} ++ ++static int vhba_device_queue (struct vhba_device *vdev, struct scsi_cmnd *cmd) ++{ ++ struct vhba_host *vhost; ++ struct vhba_command *vcmd; ++ unsigned long flags; ++ ++ vhost = platform_get_drvdata(&vhba_platform_device); ++ ++ vcmd = vhba_alloc_command(); ++ if (!vcmd) { ++ return SCSI_MLQUEUE_HOST_BUSY; ++ } ++ ++ vcmd->cmd = cmd; ++ ++ spin_lock_irqsave(&vdev->cmd_lock, flags); ++#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 15, 0) ++ vcmd->metatag = scsi_cmd_to_rq(vcmd->cmd)->tag; ++#else ++ vcmd->metatag = vcmd->cmd->request->tag; ++#endif ++ list_add_tail(&vcmd->entry, &vdev->cmd_list); ++ spin_unlock_irqrestore(&vdev->cmd_lock, flags); ++ ++ wake_up_interruptible(&vdev->cmd_wq); ++ ++ return 0; ++} ++ ++static int vhba_device_dequeue (struct vhba_device *vdev, struct scsi_cmnd *cmd) ++{ ++ struct vhba_command *vcmd; ++ int retval; ++ unsigned long flags; ++ ++ spin_lock_irqsave(&vdev->cmd_lock, flags); ++ list_for_each_entry(vcmd, &vdev->cmd_list, entry) { ++ if (vcmd->cmd == cmd) { ++ list_del_init(&vcmd->entry); ++ break; ++ } ++ } ++ ++ /* command not found */ ++ if (&vcmd->entry == &vdev->cmd_list) { ++ spin_unlock_irqrestore(&vdev->cmd_lock, flags); ++ return SUCCESS; ++ } ++ ++ while (vcmd->status == VHBA_REQ_READING || vcmd->status == VHBA_REQ_WRITING) { ++ spin_unlock_irqrestore(&vdev->cmd_lock, flags); ++ scmd_dbg(cmd, "wait for I/O before aborting\n"); ++ schedule_timeout(1); ++ spin_lock_irqsave(&vdev->cmd_lock, flags); ++ } ++ ++ retval = (vcmd->status == VHBA_REQ_SENT) ? FAILED : SUCCESS; ++ ++ vhba_free_command(vcmd); ++ ++ spin_unlock_irqrestore(&vdev->cmd_lock, flags); ++ ++ return retval; ++} ++ ++#if LINUX_VERSION_CODE < KERNEL_VERSION(3, 19, 0) ++static int vhba_slave_alloc(struct scsi_device *sdev) ++{ ++ struct Scsi_Host *shost = sdev->host; ++ ++ sdev_dbg(sdev, "enabling tagging (queue depth: %i).\n", sdev->queue_depth); ++#if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 17, 0) ++ if (!shost_use_blk_mq(shost) && shost->bqt) { ++#else ++ if (shost->bqt) { ++#endif ++ blk_queue_init_tags(sdev->request_queue, sdev->queue_depth, shost->bqt); ++ } ++ scsi_adjust_queue_depth(sdev, 0, sdev->queue_depth); ++ ++ return 0; ++} ++#endif ++ ++static void vhba_scan_devices_add (struct vhba_host *vhost, int bus, int id) ++{ ++ struct scsi_device *sdev; ++ ++ sdev = scsi_device_lookup(vhost->shost, bus, id, 0); ++ if (!sdev) { ++ scsi_add_device(vhost->shost, bus, id, 0); ++ } else { ++ dev_warn(&vhost->shost->shost_gendev, "tried to add an already-existing device %d:%d:0!\n", bus, id); ++ scsi_device_put(sdev); ++ } ++} ++ ++static void vhba_scan_devices_remove (struct vhba_host *vhost, int bus, int id) ++{ ++ struct scsi_device *sdev; ++ ++ sdev = scsi_device_lookup(vhost->shost, bus, id, 0); ++ if (sdev) { ++ scsi_remove_device(sdev); ++ scsi_device_put(sdev); ++ } else { ++ dev_warn(&vhost->shost->shost_gendev, "tried to remove non-existing device %d:%d:0!\n", bus, id); ++ } ++} ++ ++static void vhba_scan_devices (struct work_struct *work) ++{ ++ struct vhba_host *vhost = container_of(work, struct vhba_host, scan_devices); ++ unsigned long flags; ++ int change, exists; ++ unsigned int devnum; ++ unsigned int bus, id; ++ ++ for (;;) { ++ spin_lock_irqsave(&vhost->dev_lock, flags); ++ ++ devnum = find_first_bit(vhost->chgmap, VHBA_MAX_DEVICES); ++ if (devnum >= VHBA_MAX_DEVICES) { ++ spin_unlock_irqrestore(&vhost->dev_lock, flags); ++ break; ++ } ++ change = vhost->chgtype[devnum]; ++ exists = vhost->devices[devnum] != NULL; ++ ++ vhost->chgtype[devnum] = 0; ++ clear_bit(devnum, vhost->chgmap); ++ ++ spin_unlock_irqrestore(&vhost->dev_lock, flags); ++ ++ devnum_to_bus_and_id(devnum, &bus, &id); ++ ++ if (change < 0) { ++ dev_dbg(&vhost->shost->shost_gendev, "trying to remove target %d:%d:0\n", bus, id); ++ vhba_scan_devices_remove(vhost, bus, id); ++ } else if (change > 0) { ++ dev_dbg(&vhost->shost->shost_gendev, "trying to add target %d:%d:0\n", bus, id); ++ vhba_scan_devices_add(vhost, bus, id); ++ } else { ++ /* quick sequence of add/remove or remove/add; we determine ++ which one it was by checking if device structure exists */ ++ if (exists) { ++ /* remove followed by add: remove and (re)add */ ++ dev_dbg(&vhost->shost->shost_gendev, "trying to (re)add target %d:%d:0\n", bus, id); ++ vhba_scan_devices_remove(vhost, bus, id); ++ vhba_scan_devices_add(vhost, bus, id); ++ } else { ++ /* add followed by remove: no-op */ ++ dev_dbg(&vhost->shost->shost_gendev, "no-op for target %d:%d:0\n", bus, id); ++ } ++ } ++ } ++} ++ ++static int vhba_add_device (struct vhba_device *vdev) ++{ ++ struct vhba_host *vhost; ++ unsigned int devnum; ++ unsigned long flags; ++ ++ vhost = platform_get_drvdata(&vhba_platform_device); ++ ++ vhba_device_get(vdev); ++ ++ spin_lock_irqsave(&vhost->dev_lock, flags); ++ if (vhost->num_devices >= VHBA_MAX_DEVICES) { ++ spin_unlock_irqrestore(&vhost->dev_lock, flags); ++ vhba_device_put(vdev); ++ return -EBUSY; ++ } ++ ++ for (devnum = 0; devnum < VHBA_MAX_DEVICES; devnum++) { ++ if (vhost->devices[devnum] == NULL) { ++ vdev->num = devnum; ++ vhost->devices[devnum] = vdev; ++ vhost->num_devices++; ++ set_bit(devnum, vhost->chgmap); ++ vhost->chgtype[devnum]++; ++ break; ++ } ++ } ++ spin_unlock_irqrestore(&vhost->dev_lock, flags); ++ ++ schedule_work(&vhost->scan_devices); ++ ++ return 0; ++} ++ ++static int vhba_remove_device (struct vhba_device *vdev) ++{ ++ struct vhba_host *vhost; ++ unsigned long flags; ++ ++ vhost = platform_get_drvdata(&vhba_platform_device); ++ ++ spin_lock_irqsave(&vhost->dev_lock, flags); ++ set_bit(vdev->num, vhost->chgmap); ++ vhost->chgtype[vdev->num]--; ++ vhost->devices[vdev->num] = NULL; ++ vhost->num_devices--; ++ spin_unlock_irqrestore(&vhost->dev_lock, flags); ++ ++ vhba_device_put(vdev); ++ ++ schedule_work(&vhost->scan_devices); ++ ++ return 0; ++} ++ ++static struct vhba_device *vhba_lookup_device (int devnum) ++{ ++ struct vhba_host *vhost; ++ struct vhba_device *vdev = NULL; ++ unsigned long flags; ++ ++ vhost = platform_get_drvdata(&vhba_platform_device); ++ ++ if (likely(devnum < VHBA_MAX_DEVICES)) { ++ spin_lock_irqsave(&vhost->dev_lock, flags); ++ vdev = vhost->devices[devnum]; ++ if (vdev) { ++ vdev = vhba_device_get(vdev); ++ } ++ ++ spin_unlock_irqrestore(&vhost->dev_lock, flags); ++ } ++ ++ return vdev; ++} ++ ++static struct vhba_command *vhba_alloc_command (void) ++{ ++ struct vhba_host *vhost; ++ struct vhba_command *vcmd; ++ unsigned long flags; ++ int i; ++ ++ vhost = platform_get_drvdata(&vhba_platform_device); ++ ++ spin_lock_irqsave(&vhost->cmd_lock, flags); ++ ++ vcmd = vhost->commands + vhost->cmd_next++; ++ if (vcmd->status != VHBA_REQ_FREE) { ++ for (i = 0; i < vhba_can_queue; i++) { ++ vcmd = vhost->commands + i; ++ ++ if (vcmd->status == VHBA_REQ_FREE) { ++ vhost->cmd_next = i + 1; ++ break; ++ } ++ } ++ ++ if (i == vhba_can_queue) { ++ vcmd = NULL; ++ } ++ } ++ ++ if (vcmd) { ++ vcmd->status = VHBA_REQ_PENDING; ++ } ++ ++ vhost->cmd_next %= vhba_can_queue; ++ ++ spin_unlock_irqrestore(&vhost->cmd_lock, flags); ++ ++ return vcmd; ++} ++ ++static void vhba_free_command (struct vhba_command *vcmd) ++{ ++ struct vhba_host *vhost; ++ unsigned long flags; ++ ++ vhost = platform_get_drvdata(&vhba_platform_device); ++ ++ spin_lock_irqsave(&vhost->cmd_lock, flags); ++ vcmd->status = VHBA_REQ_FREE; ++ spin_unlock_irqrestore(&vhost->cmd_lock, flags); ++} ++ ++#if LINUX_VERSION_CODE >= KERNEL_VERSION(7, 0, 0) ++static enum scsi_qc_status vhba_queuecommand (struct Scsi_Host *shost, struct scsi_cmnd *cmd) ++#else ++static int vhba_queuecommand (struct Scsi_Host *shost, struct scsi_cmnd *cmd) ++#endif ++{ ++ struct vhba_device *vdev; ++ int retval; ++ unsigned int devnum; ++ ++#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 15, 0) ++ scmd_dbg(cmd, "queue %p tag %i\n", cmd, scsi_cmd_to_rq(cmd)->tag); ++#else ++ scmd_dbg(cmd, "queue %p tag %i\n", cmd, cmd->request->tag); ++#endif ++ ++ devnum = bus_and_id_to_devnum(cmd->device->channel, cmd->device->id); ++ vdev = vhba_lookup_device(devnum); ++ if (!vdev) { ++ scmd_dbg(cmd, "no such device\n"); ++ ++ cmd->result = DID_NO_CONNECT << 16; ++#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 16, 0) ++ scsi_done(cmd); ++#else ++ cmd->scsi_done(cmd); ++#endif ++ ++ return 0; ++ } ++ ++ retval = vhba_device_queue(vdev, cmd); ++ ++ vhba_device_put(vdev); ++ ++ return retval; ++} ++ ++static int vhba_abort (struct scsi_cmnd *cmd) ++{ ++ struct vhba_device *vdev; ++ int retval = SUCCESS; ++ unsigned int devnum; ++ ++ scmd_dbg(cmd, "abort %p\n", cmd); ++ ++ devnum = bus_and_id_to_devnum(cmd->device->channel, cmd->device->id); ++ vdev = vhba_lookup_device(devnum); ++ if (vdev) { ++ retval = vhba_device_dequeue(vdev, cmd); ++ vhba_device_put(vdev); ++ } else { ++ cmd->result = DID_NO_CONNECT << 16; ++ } ++ ++ return retval; ++} ++ ++static struct scsi_host_template vhba_template = { ++ .module = THIS_MODULE, ++ .name = "vhba", ++ .proc_name = "vhba", ++ .queuecommand = vhba_queuecommand, ++ .eh_abort_handler = vhba_abort, ++ .this_id = -1, ++ .max_sectors = VHBA_MAX_SECTORS_PER_IO, ++ .sg_tablesize = 256, ++#if LINUX_VERSION_CODE < KERNEL_VERSION(3, 19, 0) ++ .slave_alloc = vhba_slave_alloc, ++#endif ++#if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 14, 0) ++ .tag_alloc_policy_rr = true, ++#elif LINUX_VERSION_CODE >= KERNEL_VERSION(4, 0, 0) ++ .tag_alloc_policy = BLK_TAG_ALLOC_RR, ++#endif ++#if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 19, 0) && LINUX_VERSION_CODE < KERNEL_VERSION(4, 4, 0) ++ .use_blk_tags = 1, ++#endif ++#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 0, 0) ++ .max_segment_size = VHBA_KBUF_SIZE, ++#endif ++}; ++ ++static ssize_t do_request (struct vhba_device *vdev, unsigned long metatag, struct scsi_cmnd *cmd, char __user *buf, size_t buf_len) ++{ ++ struct vhba_request vreq; ++ ssize_t ret; ++ ++ scmd_dbg(cmd, "request %lu (%p), cdb 0x%x, bufflen %d, sg count %d\n", ++ metatag, cmd, cmd->cmnd[0], scsi_bufflen(cmd), scsi_sg_count(cmd)); ++ ++ ret = sizeof(vreq); ++ if (DATA_TO_DEVICE(cmd->sc_data_direction)) { ++ ret += scsi_bufflen(cmd); ++ } ++ ++ if (ret > buf_len) { ++ scmd_dbg(cmd, "buffer too small (%zd < %zd) for a request\n", buf_len, ret); ++ return -EIO; ++ } ++ ++ vreq.metatag = metatag; ++ vreq.lun = cmd->device->lun; ++ memcpy(vreq.cdb, cmd->cmnd, MAX_COMMAND_SIZE); ++ vreq.cdb_len = cmd->cmd_len; ++ vreq.data_len = scsi_bufflen(cmd); ++ ++ if (copy_to_user(buf, &vreq, sizeof(vreq))) { ++ return -EFAULT; ++ } ++ ++ if (DATA_TO_DEVICE(cmd->sc_data_direction) && vreq.data_len) { ++ buf += sizeof(vreq); ++ ++ if (scsi_sg_count(cmd)) { ++ unsigned char *kaddr, *uaddr; ++ struct scatterlist *sglist = scsi_sglist(cmd); ++ struct scatterlist *sg; ++ int i; ++ ++ uaddr = (unsigned char *) buf; ++ ++ for_each_sg(sglist, sg, scsi_sg_count(cmd), i) { ++ size_t len = sg->length; ++ ++ if (len > vdev->kbuf_size) { ++ scmd_dbg(cmd, "segment size (%zu) exceeds kbuf size (%zu)!", len, vdev->kbuf_size); ++ len = vdev->kbuf_size; ++ } ++ ++ kaddr = kmap_atomic(sg_page(sg)); ++ memcpy(vdev->kbuf, kaddr + sg->offset, len); ++ kunmap_atomic(kaddr); ++ ++ if (copy_to_user(uaddr, vdev->kbuf, len)) { ++ return -EFAULT; ++ } ++ uaddr += len; ++ } ++ } else { ++ if (copy_to_user(buf, scsi_sglist(cmd), vreq.data_len)) { ++ return -EFAULT; ++ } ++ } ++ } ++ ++ return ret; ++} ++ ++static ssize_t do_response (struct vhba_device *vdev, unsigned long metatag, struct scsi_cmnd *cmd, const char __user *buf, size_t buf_len, struct vhba_response *res) ++{ ++ ssize_t ret = 0; ++ ++ scmd_dbg(cmd, "response %lu (%p), status %x, data len %d, sg count %d\n", ++ metatag, cmd, res->status, res->data_len, scsi_sg_count(cmd)); ++ ++ if (res->status) { ++ if (res->data_len > SCSI_SENSE_BUFFERSIZE) { ++ scmd_dbg(cmd, "truncate sense (%d < %d)", SCSI_SENSE_BUFFERSIZE, res->data_len); ++ res->data_len = SCSI_SENSE_BUFFERSIZE; ++ } ++ ++ if (copy_from_user(cmd->sense_buffer, buf, res->data_len)) { ++ return -EFAULT; ++ } ++ ++ cmd->result = res->status; ++ ++ ret += res->data_len; ++ } else if (DATA_FROM_DEVICE(cmd->sc_data_direction) && scsi_bufflen(cmd)) { ++ size_t to_read; ++ ++ if (res->data_len > scsi_bufflen(cmd)) { ++ scmd_dbg(cmd, "truncate data (%d < %d)\n", scsi_bufflen(cmd), res->data_len); ++ res->data_len = scsi_bufflen(cmd); ++ } ++ ++ to_read = res->data_len; ++ ++ if (scsi_sg_count(cmd)) { ++ unsigned char *kaddr, *uaddr; ++ struct scatterlist *sglist = scsi_sglist(cmd); ++ struct scatterlist *sg; ++ int i; ++ ++ uaddr = (unsigned char *)buf; ++ ++ for_each_sg(sglist, sg, scsi_sg_count(cmd), i) { ++ size_t len = (sg->length < to_read) ? sg->length : to_read; ++ ++ if (len > vdev->kbuf_size) { ++ scmd_dbg(cmd, "segment size (%zu) exceeds kbuf size (%zu)!", len, vdev->kbuf_size); ++ len = vdev->kbuf_size; ++ } ++ ++ if (copy_from_user(vdev->kbuf, uaddr, len)) { ++ return -EFAULT; ++ } ++ uaddr += len; ++ ++ kaddr = kmap_atomic(sg_page(sg)); ++ memcpy(kaddr + sg->offset, vdev->kbuf, len); ++ kunmap_atomic(kaddr); ++ ++ to_read -= len; ++ if (to_read == 0) { ++ break; ++ } ++ } ++ } else { ++ if (copy_from_user(scsi_sglist(cmd), buf, res->data_len)) { ++ return -EFAULT; ++ } ++ ++ to_read -= res->data_len; ++ } ++ ++ scsi_set_resid(cmd, to_read); ++ ++ ret += res->data_len - to_read; ++ } ++ ++ return ret; ++} ++ ++static struct vhba_command *next_command (struct vhba_device *vdev) ++{ ++ struct vhba_command *vcmd; ++ ++ list_for_each_entry(vcmd, &vdev->cmd_list, entry) { ++ if (vcmd->status == VHBA_REQ_PENDING) { ++ break; ++ } ++ } ++ ++ if (&vcmd->entry == &vdev->cmd_list) { ++ vcmd = NULL; ++ } ++ ++ return vcmd; ++} ++ ++static struct vhba_command *match_command (struct vhba_device *vdev, __u32 metatag) ++{ ++ struct vhba_command *vcmd; ++ ++ list_for_each_entry(vcmd, &vdev->cmd_list, entry) { ++ if (vcmd->metatag == metatag) { ++ break; ++ } ++ } ++ ++ if (&vcmd->entry == &vdev->cmd_list) { ++ vcmd = NULL; ++ } ++ ++ return vcmd; ++} ++ ++static struct vhba_command *wait_command (struct vhba_device *vdev, unsigned long flags) ++{ ++ struct vhba_command *vcmd; ++ DEFINE_WAIT(wait); ++ ++ while (!(vcmd = next_command(vdev))) { ++ if (signal_pending(current)) { ++ break; ++ } ++ ++ prepare_to_wait(&vdev->cmd_wq, &wait, TASK_INTERRUPTIBLE); ++ ++ spin_unlock_irqrestore(&vdev->cmd_lock, flags); ++ ++ schedule(); ++ ++ spin_lock_irqsave(&vdev->cmd_lock, flags); ++ } ++ ++ finish_wait(&vdev->cmd_wq, &wait); ++ if (vcmd) { ++ vcmd->status = VHBA_REQ_READING; ++ } ++ ++ return vcmd; ++} ++ ++static ssize_t vhba_ctl_read (struct file *file, char __user *buf, size_t buf_len, loff_t *offset) ++{ ++ struct vhba_device *vdev; ++ struct vhba_command *vcmd; ++ ssize_t ret; ++ unsigned long flags; ++ ++ vdev = file->private_data; ++ ++ /* Get next command */ ++ if (file->f_flags & O_NONBLOCK) { ++ /* Non-blocking variant */ ++ spin_lock_irqsave(&vdev->cmd_lock, flags); ++ vcmd = next_command(vdev); ++ spin_unlock_irqrestore(&vdev->cmd_lock, flags); ++ ++ if (!vcmd) { ++ return -EWOULDBLOCK; ++ } ++ } else { ++ /* Blocking variant */ ++ spin_lock_irqsave(&vdev->cmd_lock, flags); ++ vcmd = wait_command(vdev, flags); ++ spin_unlock_irqrestore(&vdev->cmd_lock, flags); ++ ++ if (!vcmd) { ++ return -ERESTARTSYS; ++ } ++ } ++ ++ ret = do_request(vdev, vcmd->metatag, vcmd->cmd, buf, buf_len); ++ ++ spin_lock_irqsave(&vdev->cmd_lock, flags); ++ if (ret >= 0) { ++ vcmd->status = VHBA_REQ_SENT; ++ *offset += ret; ++ } else { ++ vcmd->status = VHBA_REQ_PENDING; ++ } ++ ++ spin_unlock_irqrestore(&vdev->cmd_lock, flags); ++ ++ return ret; ++} ++ ++static ssize_t vhba_ctl_write (struct file *file, const char __user *buf, size_t buf_len, loff_t *offset) ++{ ++ struct vhba_device *vdev; ++ struct vhba_command *vcmd; ++ struct vhba_response res; ++ ssize_t ret; ++ unsigned long flags; ++ ++ if (buf_len < sizeof(res)) { ++ return -EIO; ++ } ++ ++ if (copy_from_user(&res, buf, sizeof(res))) { ++ return -EFAULT; ++ } ++ ++ vdev = file->private_data; ++ ++ spin_lock_irqsave(&vdev->cmd_lock, flags); ++ vcmd = match_command(vdev, res.metatag); ++ if (!vcmd || vcmd->status != VHBA_REQ_SENT) { ++ spin_unlock_irqrestore(&vdev->cmd_lock, flags); ++ pr_debug("ctl dev #%u not expecting response\n", vdev->num); ++ return -EIO; ++ } ++ vcmd->status = VHBA_REQ_WRITING; ++ spin_unlock_irqrestore(&vdev->cmd_lock, flags); ++ ++ ret = do_response(vdev, vcmd->metatag, vcmd->cmd, buf + sizeof(res), buf_len - sizeof(res), &res); ++ ++ spin_lock_irqsave(&vdev->cmd_lock, flags); ++ if (ret >= 0) { ++#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 16, 0) ++ scsi_done(vcmd->cmd); ++#else ++ vcmd->cmd->scsi_done(vcmd->cmd); ++#endif ++ ret += sizeof(res); ++ ++ /* don't compete with vhba_device_dequeue */ ++ if (!list_empty(&vcmd->entry)) { ++ list_del_init(&vcmd->entry); ++ vhba_free_command(vcmd); ++ } ++ } else { ++ vcmd->status = VHBA_REQ_SENT; ++ } ++ ++ spin_unlock_irqrestore(&vdev->cmd_lock, flags); ++ ++ return ret; ++} ++ ++static long vhba_ctl_ioctl (struct file *file, unsigned int cmd, unsigned long arg) ++{ ++ struct vhba_device *vdev = file->private_data; ++ struct vhba_host *vhost = platform_get_drvdata(&vhba_platform_device); ++ ++ switch (cmd) { ++ case 0xBEEF001: { ++ unsigned int ident[4]; /* host, channel, id, lun */ ++ ++ ident[0] = vhost->shost->host_no; ++ devnum_to_bus_and_id(vdev->num, &ident[1], &ident[2]); ++ ident[3] = 0; /* lun */ ++ ++ if (copy_to_user((void *) arg, ident, sizeof(ident))) { ++ return -EFAULT; ++ } ++ ++ return 0; ++ } ++ case 0xBEEF002: { ++ unsigned int devnum = vdev->num; ++ ++ if (copy_to_user((void *) arg, &devnum, sizeof(devnum))) { ++ return -EFAULT; ++ } ++ ++ return 0; ++ } ++ } ++ ++ return -ENOTTY; ++} ++ ++#ifdef CONFIG_COMPAT ++static long vhba_ctl_compat_ioctl (struct file *file, unsigned int cmd, unsigned long arg) ++{ ++ unsigned long compat_arg = (unsigned long)compat_ptr(arg); ++ return vhba_ctl_ioctl(file, cmd, compat_arg); ++} ++#endif ++ ++static unsigned int vhba_ctl_poll (struct file *file, poll_table *wait) ++{ ++ struct vhba_device *vdev = file->private_data; ++ unsigned int mask = 0; ++ unsigned long flags; ++ ++ poll_wait(file, &vdev->cmd_wq, wait); ++ ++ spin_lock_irqsave(&vdev->cmd_lock, flags); ++ if (next_command(vdev)) { ++ mask |= POLLIN | POLLRDNORM; ++ } ++ spin_unlock_irqrestore(&vdev->cmd_lock, flags); ++ ++ return mask; ++} ++ ++static int vhba_ctl_open (struct inode *inode, struct file *file) ++{ ++ struct vhba_device *vdev; ++ int retval; ++ ++ pr_debug("ctl dev open\n"); ++ ++ /* check if vhba is probed */ ++ if (!platform_get_drvdata(&vhba_platform_device)) { ++ return -ENODEV; ++ } ++ ++ vdev = vhba_device_alloc(); ++ if (!vdev) { ++ return -ENOMEM; ++ } ++ ++ vdev->kbuf_size = VHBA_KBUF_SIZE; ++ vdev->kbuf = kzalloc(vdev->kbuf_size, GFP_KERNEL); ++ if (!vdev->kbuf) { ++ return -ENOMEM; ++ } ++ ++ if (!(retval = vhba_add_device(vdev))) { ++ file->private_data = vdev; ++ } ++ ++ vhba_device_put(vdev); ++ ++ return retval; ++} ++ ++static int vhba_ctl_release (struct inode *inode, struct file *file) ++{ ++ struct vhba_device *vdev; ++ struct vhba_command *vcmd; ++ unsigned long flags; ++ ++ vdev = file->private_data; ++ ++ pr_debug("ctl dev release\n"); ++ ++ vhba_device_get(vdev); ++ vhba_remove_device(vdev); ++ ++ spin_lock_irqsave(&vdev->cmd_lock, flags); ++ list_for_each_entry(vcmd, &vdev->cmd_list, entry) { ++ WARN_ON(vcmd->status == VHBA_REQ_READING || vcmd->status == VHBA_REQ_WRITING); ++ ++ scmd_dbg(vcmd->cmd, "device released with command %lu (%p)\n", vcmd->metatag, vcmd->cmd); ++ vcmd->cmd->result = DID_NO_CONNECT << 16; ++#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 16, 0) ++ scsi_done(vcmd->cmd); ++#else ++ vcmd->cmd->scsi_done(vcmd->cmd); ++#endif ++ vhba_free_command(vcmd); ++ } ++ INIT_LIST_HEAD(&vdev->cmd_list); ++ spin_unlock_irqrestore(&vdev->cmd_lock, flags); ++ ++ kfree(vdev->kbuf); ++ vdev->kbuf = NULL; ++ ++ vhba_device_put(vdev); ++ ++ return 0; ++} ++ ++static struct file_operations vhba_ctl_fops = { ++ .owner = THIS_MODULE, ++ .open = vhba_ctl_open, ++ .release = vhba_ctl_release, ++ .read = vhba_ctl_read, ++ .write = vhba_ctl_write, ++ .poll = vhba_ctl_poll, ++ .unlocked_ioctl = vhba_ctl_ioctl, ++#ifdef CONFIG_COMPAT ++ .compat_ioctl = vhba_ctl_compat_ioctl, ++#endif ++}; ++ ++static struct miscdevice vhba_miscdev = { ++ .minor = MISC_DYNAMIC_MINOR, ++ .name = "vhba_ctl", ++ .fops = &vhba_ctl_fops, ++}; ++ ++static int vhba_probe (struct platform_device *pdev) ++{ ++ struct Scsi_Host *shost; ++ struct vhba_host *vhost; ++ int i; ++ ++ vhba_can_queue = clamp(vhba_can_queue, 1, 256); ++ ++ shost = scsi_host_alloc(&vhba_template, sizeof(struct vhba_host)); ++ if (!shost) { ++ return -ENOMEM; ++ } ++ ++ shost->max_channel = VHBA_MAX_BUS-1; ++ shost->max_id = VHBA_MAX_ID; ++ /* we don't support lun > 0 */ ++ shost->max_lun = 1; ++ shost->max_cmd_len = MAX_COMMAND_SIZE; ++ shost->can_queue = vhba_can_queue; ++ shost->cmd_per_lun = vhba_can_queue; ++ ++ vhost = (struct vhba_host *)shost->hostdata; ++ memset(vhost, 0, sizeof(struct vhba_host)); ++ ++ vhost->shost = shost; ++ vhost->num_devices = 0; ++ spin_lock_init(&vhost->dev_lock); ++ spin_lock_init(&vhost->cmd_lock); ++ INIT_WORK(&vhost->scan_devices, vhba_scan_devices); ++ vhost->cmd_next = 0; ++ vhost->commands = kzalloc(vhba_can_queue * sizeof(struct vhba_command), GFP_KERNEL); ++ if (!vhost->commands) { ++ return -ENOMEM; ++ } ++ ++ for (i = 0; i < vhba_can_queue; i++) { ++ vhost->commands[i].status = VHBA_REQ_FREE; ++ } ++ ++ platform_set_drvdata(pdev, vhost); ++ ++#if LINUX_VERSION_CODE < KERNEL_VERSION(4, 4, 0) ++ i = scsi_init_shared_tag_map(shost, vhba_can_queue); ++ if (i) return i; ++#endif ++ ++ if (scsi_add_host(shost, &pdev->dev)) { ++ scsi_host_put(shost); ++ return -ENOMEM; ++ } ++ ++ return 0; ++} ++ ++#if LINUX_VERSION_CODE < KERNEL_VERSION(6, 11, 0) ++static int vhba_remove (struct platform_device *pdev) ++#else ++static void vhba_remove (struct platform_device *pdev) ++#endif ++{ ++ struct vhba_host *vhost; ++ struct Scsi_Host *shost; ++ ++ vhost = platform_get_drvdata(pdev); ++ shost = vhost->shost; ++ ++ scsi_remove_host(shost); ++ scsi_host_put(shost); ++ ++ kfree(vhost->commands); ++ ++#if LINUX_VERSION_CODE < KERNEL_VERSION(6, 11, 0) ++ return 0; ++#endif ++} ++ ++static void vhba_release (struct device * dev) ++{ ++ return; ++} ++ ++static struct platform_device vhba_platform_device = { ++ .name = "vhba", ++ .id = -1, ++ .dev = { ++ .release = vhba_release, ++ }, ++}; ++ ++static struct platform_driver vhba_platform_driver = { ++ .driver = { ++ .owner = THIS_MODULE, ++ .name = "vhba", ++ }, ++ .probe = vhba_probe, ++ .remove = vhba_remove, ++}; ++ ++static int __init vhba_init (void) ++{ ++ int ret; ++ ++ ret = platform_device_register(&vhba_platform_device); ++ if (ret < 0) { ++ return ret; ++ } ++ ++ ret = platform_driver_register(&vhba_platform_driver); ++ if (ret < 0) { ++ platform_device_unregister(&vhba_platform_device); ++ return ret; ++ } ++ ++ ret = misc_register(&vhba_miscdev); ++ if (ret < 0) { ++ platform_driver_unregister(&vhba_platform_driver); ++ platform_device_unregister(&vhba_platform_device); ++ return ret; ++ } ++ ++ return 0; ++} ++ ++static void __exit vhba_exit(void) ++{ ++ misc_deregister(&vhba_miscdev); ++ platform_driver_unregister(&vhba_platform_driver); ++ platform_device_unregister(&vhba_platform_device); ++} ++ ++module_init(vhba_init); ++module_exit(vhba_exit); ++ +diff --git a/fs/btrfs/compression.c b/fs/btrfs/compression.c +index c62b514..57d2441 100644 +--- a/fs/btrfs/compression.c ++++ b/fs/btrfs/compression.c +@@ -8,6 +8,7 @@ + #include + #include + #include ++#include + #include + #include + #include +diff --git a/fs/erofs/zdata.c b/fs/erofs/zdata.c +index 6b07e73..c618bbf 100644 +--- a/fs/erofs/zdata.c ++++ b/fs/erofs/zdata.c +@@ -6,6 +6,7 @@ + */ + #include "compress.h" + #include ++#include + #include + #include + +@@ -1713,7 +1714,7 @@ static void z_erofs_submit_queue(struct z_erofs_frontend *f, + DBG_BUGON(bvec.bv_len < sb->s_blocksize); + } + +- if (unlikely(PageWorkingset(bvec.bv_page)) && ++ if (unlikely(folio_test_workingset(page_folio(bvec.bv_page))) && + !memstall) { + psi_memstall_enter(&pflags); + memstall = 1; +diff --git a/fs/f2fs/checkpoint.c b/fs/f2fs/checkpoint.c +index a845170..08130b0 100644 +--- a/fs/f2fs/checkpoint.c ++++ b/fs/f2fs/checkpoint.c +@@ -28,7 +28,7 @@ static inline void get_lock_elapsed_time(struct f2fs_time_stat *ts) + { + ts->total_time = ktime_get(); + #ifdef CONFIG_64BIT +- ts->running_time = current->se.sum_exec_runtime; ++ ts->running_time = tsk_seruntime(current); + #endif + #if defined(CONFIG_SCHED_INFO) && defined(CONFIG_SCHEDSTATS) + ts->runnable_time = current->sched_info.run_delay; +diff --git a/fs/proc/base.c b/fs/proc/base.c +index 6a39de4..1acfa9f 100644 +--- a/fs/proc/base.c ++++ b/fs/proc/base.c +@@ -513,7 +513,7 @@ static int proc_pid_schedstat(struct seq_file *m, struct pid_namespace *ns, + seq_puts(m, "0 0 0\n"); + else + seq_printf(m, "%llu %llu %lu\n", +- (unsigned long long)task->se.sum_exec_runtime, ++ (unsigned long long)tsk_seruntime(task), + (unsigned long long)task->sched_info.run_delay, + task->sched_info.pcount); + +diff --git a/fs/proc/task_mmu.c b/fs/proc/task_mmu.c +index 2eaa79a..3cd136a 100644 +--- a/fs/proc/task_mmu.c ++++ b/fs/proc/task_mmu.c +@@ -970,7 +970,7 @@ static void smaps_account(struct mem_size_stats *mss, struct page *page, + + mss->resident += size; + /* Accumulate the size in pages that have been accessed. */ +- if (young || folio_test_young(folio) || folio_test_referenced(folio)) ++ if (young || folio_test_young(folio) || folio_check_lru_refs(folio)) + mss->referenced += size; + + /* +@@ -1793,7 +1793,7 @@ static int clear_refs_pte_range(pmd_t *pmd, unsigned long addr, + /* Clear accessed and referenced bits. */ + pmdp_test_and_clear_young(vma, addr, pmd); + folio_test_clear_young(folio); +- folio_clear_referenced(folio); ++ folio_clear_lru_refs(folio); + out: + spin_unlock(ptl); + return 0; +@@ -1822,7 +1822,7 @@ static int clear_refs_pte_range(pmd_t *pmd, unsigned long addr, + /* Clear accessed and referenced bits. */ + ptep_test_and_clear_young(vma, addr, pte); + folio_test_clear_young(folio); +- folio_clear_referenced(folio); ++ folio_clear_lru_refs(folio); + } + pte_unmap_unlock(pte - 1, ptl); + cond_resched(); +diff --git a/include/linux/interrupt.h b/include/linux/interrupt.h +index 5074560..da79173 100644 +--- a/include/linux/interrupt.h ++++ b/include/linux/interrupt.h +@@ -513,6 +513,9 @@ extern int irq_set_irqchip_state(unsigned int irq, enum irqchip_irq_state which, + #ifdef CONFIG_IRQ_FORCED_THREADING + # ifdef CONFIG_PREEMPT_RT + # define force_irqthreads() (true) ++# elif defined(CONFIG_FORCE_IRQ_THREADING) ++DECLARE_STATIC_KEY_TRUE(force_irqthreads_key); ++# define force_irqthreads() (static_branch_likely(&force_irqthreads_key)) + # else + DECLARE_STATIC_KEY_FALSE(force_irqthreads_key); + # define force_irqthreads() (static_branch_unlikely(&force_irqthreads_key)) +diff --git a/include/linux/memcontrol.h b/include/linux/memcontrol.h +index 6d1c9e9..961f433 100644 +--- a/include/linux/memcontrol.h ++++ b/include/linux/memcontrol.h +@@ -113,7 +113,7 @@ struct mem_cgroup_per_node { + /* Fields which get updated often at the end. */ + struct lruvec lruvec; + CACHELINE_PADDING(_pad2_); +- unsigned long lru_zone_size[MAX_NR_ZONES][NR_LRU_LISTS]; ++ long lru_zone_size[MAX_NR_ZONES][NR_LRU_LISTS]; + struct mem_cgroup_reclaim_iter iter; + + /* +@@ -903,10 +903,15 @@ static inline + unsigned long mem_cgroup_get_zone_lru_size(struct lruvec *lruvec, + enum lru_list lru, int zone_idx) + { ++ long val; + struct mem_cgroup_per_node *mz; + + mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec); +- return READ_ONCE(mz->lru_zone_size[zone_idx][lru]); ++ val = READ_ONCE(mz->lru_zone_size[zone_idx][lru]); ++ if (WARN_ON_ONCE(val < 0)) ++ return 0; ++ ++ return val; + } + + void __mem_cgroup_handle_over_high(gfp_t gfp_mask); +@@ -1503,6 +1508,45 @@ static inline void lruvec_lock_irq(struct lruvec *lruvec) + spin_lock_irq(&lruvec->lru_lock); + } + ++/** ++ * folio_lruvec_live_get - get a live lruvec for a folio under RCU ++ * @folio: the folio ++ * ++ * Computes @folio's lruvec and walks up to the nearest live ancestor ++ * if the folio's memcg is dying. Paired with folio_lruvec_live_put(). ++ * The result may be stale: RCU keeps it alive but does not pin @folio ++ * to it. That is fine as the counters are fixed up on reparenting. ++ * ++ * Return: the live lruvec, with rcu_read_lock held. ++ */ ++static inline struct lruvec *folio_lruvec_live_get(struct folio *folio) ++{ ++#ifdef CONFIG_MEMCG ++ struct lruvec *lruvec; ++ struct pglist_data *pgdat; ++ struct mem_cgroup *memcg; ++ ++ rcu_read_lock(); ++ lruvec = folio_lruvec(folio); ++ pgdat = lruvec_pgdat(lruvec); ++ memcg = lruvec_memcg(lruvec); ++ while (unlikely(memcg && css_is_dying(&memcg->css))) { ++ memcg = parent_mem_cgroup(memcg); ++ lruvec = mem_cgroup_lruvec(memcg, pgdat); ++ } ++ return lruvec; ++#else ++ return folio_lruvec(folio); ++#endif ++} ++ ++static inline void folio_lruvec_live_put(struct lruvec *lruvec) ++{ ++#ifdef CONFIG_MEMCG ++ rcu_read_unlock(); ++#endif ++} ++ + static inline struct lruvec *lruvec_live_lock_irq(struct lruvec *lruvec) + { + #ifdef CONFIG_MEMCG +diff --git a/include/linux/mm.h b/include/linux/mm.h +index dd09c43..31f606a 100644 +--- a/include/linux/mm.h ++++ b/include/linux/mm.h +@@ -206,7 +206,7 @@ static inline void __mm_zero_struct_page(struct page *page) + * that. + */ + #define MAPCOUNT_ELF_CORE_MARGIN (5) +-#define DEFAULT_MAX_MAP_COUNT (USHRT_MAX - MAPCOUNT_ELF_CORE_MARGIN) ++#define DEFAULT_MAX_MAP_COUNT (INT_MAX - MAPCOUNT_ELF_CORE_MARGIN) + + extern unsigned long sysctl_user_reserve_kbytes; + extern unsigned long sysctl_admin_reserve_kbytes; +diff --git a/include/linux/mm_inline.h b/include/linux/mm_inline.h +index 621c865..ae50f98 100644 +--- a/include/linux/mm_inline.h ++++ b/include/linux/mm_inline.h +@@ -30,17 +30,27 @@ static inline int folio_is_file_lru(const struct folio *folio) + return !folio_test_swapbacked(folio); + } + ++/** ++ * folio_flags_is_file_lru - Should the folio be on a file LRU or anon LRU? ++ * @flags: The folio's flags. ++ * ++ * Just like folio_is_file_lru but take the folio flags directly instead. ++ */ ++static inline int folio_flags_is_file_lru(const unsigned long *flags) ++{ ++ return !test_bit(PG_swapbacked, flags); ++} ++ + static __always_inline void __update_lru_size(struct lruvec *lruvec, + enum lru_list lru, enum zone_type zid, + long nr_pages) + { + struct pglist_data *pgdat = lruvec_pgdat(lruvec); + +- lockdep_assert_held(&lruvec->lru_lock); + WARN_ON_ONCE(nr_pages != (int)nr_pages); + + mod_lruvec_state(lruvec, NR_LRU_BASE + lru, nr_pages); +- __mod_zone_page_state(&pgdat->node_zones[zid], ++ mod_zone_page_state(&pgdat->node_zones[zid], + NR_ZONE_LRU_BASE + lru, nr_pages); + } + +@@ -95,6 +105,22 @@ static __always_inline enum lru_list folio_lru_list(const struct folio *folio) + return lru; + } + ++/** ++ * lru_get_gen_flags - Return the LRU generation number from folio flags. ++ * @flags: folio flags ++ * ++ * Returns: A number between 0 and (MAX_NR_GENS - 1), inclusive. Returns ++ * -1 if the flags indicate the folio is off the list (e.g., isolated). ++ */ ++static inline int lru_get_gen_flags(unsigned long flags) ++{ ++ int gen = ((flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1; ++ ++ /* Exclude the legal -1 from the unsigned MAX_NR_GENS comparison */ ++ VM_WARN_ON_ONCE(gen != -1 && gen >= MAX_NR_GENS); ++ return gen; ++} ++ + #ifdef CONFIG_LRU_GEN + + static inline bool lru_gen_switching(void) +@@ -134,51 +160,176 @@ static inline int lru_hist_from_seq(unsigned long seq) + return seq % NR_HIST_GENS; + } + +-static inline int lru_tier_from_refs(int refs, bool workingset) ++static inline int lru_tier_from_refs(unsigned int refs) + { +- VM_WARN_ON_ONCE(refs > BIT(LRU_REFS_WIDTH)); ++ BUILD_BUG_ON(fls(LRU_REFS_MAX - 1) > MAX_NR_TIERS - 1); ++ VM_WARN_ON_ONCE(refs > LRU_REFS_MAX); ++ if (refs < LRU_REFS_WORKINGSET) ++ return 0; ++ return fls(refs - 1); ++} + +- /* see the comment on MAX_NR_TIERS */ +- return workingset ? MAX_NR_TIERS - 1 : order_base_2(refs); ++/** ++ * lru_set_gen_flags - Set the LRU generation number to specified folio flags. ++ * @flags: pointer to the folio flags ++ * @gen: generation number, between 0 and (MAX_NR_GENS - 1), inclusive. ++ */ ++static inline void lru_set_gen_flags(unsigned long *flags, int gen) ++{ ++ BUILD_BUG_ON(LRU_GEN_MASK & LRU_REFS_MASK); ++ VM_WARN_ON_ONCE(gen >= MAX_NR_GENS || gen < 0); ++ /* Store gen offset by 1, zero means the folio is off-list. */ ++ *flags &= ~LRU_GEN_MASK; ++ *flags |= (gen + 1UL) << LRU_GEN_PGOFF; ++} ++ ++static inline int folio_lru_gen(const struct folio *folio) ++{ ++ return lru_get_gen_flags(READ_ONCE(*const_folio_flags(folio, 0))); ++} ++#endif ++ ++/** ++ * lru_set_refs_flags - Set the LRU referenced count to folio flags. ++ * @flags: pointer to the folio flags ++ * @refs: referenced / access count number, between 0 and LRU_REFS_MAX, inclusive. ++ * ++ * For MGLRU, PG_referenced, PG_workingset are used as the lower two bits of ++ * refs counter, and extra bits hold the remaining higher bits. For classical ++ * LRU the extra bits are not used, and the two flags has no direct ++ * relationship with each other, but this helper can still be used to sync ++ * them. For both cases, refs == 0 means these two flags and the extra bits ++ * are all unset. And refs == 1 / 2 / 3 means PG_referenced and PG_workingset ++ * are set in an bit order way, which is more meaningful for MGLRU though. ++ */ ++static inline void lru_set_refs_flags(unsigned long *flags, unsigned int refs) ++{ ++ VM_WARN_ON_ONCE(refs > LRU_REFS_MAX); ++ BUILD_BUG_ON(LRU_REFS_MASK & (BIT(PG_referenced) | BIT(PG_workingset))); ++ *flags &= ~LRU_REFS_FLAGS; ++ if (refs & BIT(0)) ++ *flags |= BIT(PG_referenced); ++ if (refs & BIT(1)) ++ *flags |= BIT(PG_workingset); ++ if (LRU_REFS_WIDTH) ++ *flags |= ((unsigned long)refs >> 2) << LRU_REFS_PGOFF; ++} ++ ++/** ++ * lru_get_refs_flags - Return LRU referenced / access count from folio flags. ++ * @flags: folio flags ++ * ++ * Reads the LRU referenced count set by lru_set_refs_flags(). ++ */ ++static inline int lru_get_refs_flags(unsigned long flags) ++{ ++ int refs; ++ ++ /* Return the total number of accesses. See the comment above MAX_NR_TIERS. */ ++ refs = (flags & BIT(PG_referenced)) ? BIT(0) : 0; ++ refs += (flags & BIT(PG_workingset)) ? BIT(1) : 0; ++ refs += ((flags & LRU_REFS_MASK) >> LRU_REFS_PGOFF) << 2; ++ return refs; + } + + static inline int folio_lru_refs(const struct folio *folio) + { +- unsigned long flags = READ_ONCE(folio->flags.f); ++ return lru_get_refs_flags(READ_ONCE(*const_folio_flags(folio, 0))); ++} + +- if (!(flags & BIT(PG_referenced))) +- return 0; +- /* +- * Return the total number of accesses including PG_referenced. Also see +- * the comment on LRU_REFS_FLAGS. +- */ +- return ((flags & LRU_REFS_MASK) >> LRU_REFS_PGOFF) + 1; ++/** ++ * __folio_set_lru_refs - Set a folio's LRU refs. ++ * @folio: the folio ++ * @refs: the new referenced count (0 .. LRU_REFS_MAX) ++ * ++ * Set the folio's LRU refs. The folio must be off the LRU list (e.g., ++ * isolated), or use folio_inc_lru_refs or folio_reset_lru_refs instead. ++ */ ++static inline void __folio_set_lru_refs(struct folio *folio, unsigned int refs) ++{ ++ unsigned long new_flags, old_flags = READ_ONCE(*folio_flags(folio, 0)); ++ ++ do { ++ new_flags = old_flags; ++ VM_WARN_ON_ONCE(lru_get_gen_flags(old_flags) != -1); ++ lru_set_refs_flags(&new_flags, refs); ++ } while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags)); + } + +-static inline int folio_lru_gen(const struct folio *folio) ++#ifdef CONFIG_LRU_GEN ++void folio_inc_lru_refs(struct folio *folio, unsigned int flags); ++bool folio_reset_lru_refs(struct folio *folio); ++#else ++static inline void folio_inc_lru_refs(struct folio *folio, unsigned int flags) ++{ ++ /* Should not be called with !CONFIG_LRU_GEN */ ++ WARN_ON_ONCE(1); ++} ++ ++static inline bool folio_reset_lru_refs(struct folio *folio) + { +- unsigned long flags = READ_ONCE(folio->flags.f); ++ return false; ++} ++#endif + +- return ((flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1; ++/** ++ * folio_migrate_lru_refs - copy the reference state to a new folio ++ * @new: the destination folio ++ * @old: the source folio ++ * ++ * Transfer the reference state to @new during migration: the MGLRU ++ * refs count, or PG_referenced and PG_workingset (bits 0-1 of the ++ * encoding) for the active/inactive LRU. ++ */ ++static inline void folio_migrate_lru_refs(struct folio *new, const struct folio *old) ++{ ++ VM_WARN_ON_ONCE_FOLIO(folio_test_lru(old), old); ++ VM_WARN_ON_ONCE_FOLIO(folio_test_lru(new), new); ++ __folio_set_lru_refs(new, folio_lru_refs(old)); ++} ++ ++/** ++ * folio_test_workingset - Test if a folio is in the workingset. ++ * @folio: the folio ++ * ++ * A folio is workingset when its LRU refs count reaches ++ * LRU_REFS_WORKINGSET. Under the classical LRU the extra refs counter ++ * are always zero so this is just testing the PG_workingset bit. ++ * NOTE: folio_set_workingset() must not be used under MGLRU, as the ++ * folio refs are tracked by folio_inc_lru_refs() with rules. ++ * ++ * Return: true if the folio is workingset. ++ */ ++static __always_inline bool folio_test_workingset(const struct folio *folio) ++{ ++ return folio_lru_refs(folio) >= LRU_REFS_WORKINGSET; + } + +-static inline bool lru_gen_is_active(const struct lruvec *lruvec, int gen) ++#ifdef CONFIG_LRU_GEN ++static inline bool lru_refs_is_active(unsigned int refs) + { +- unsigned long max_seq = lruvec->lrugen.max_seq; ++ VM_WARN_ON_ONCE(refs > LRU_REFS_MAX); ++ return refs >= LRU_REFS_ACTIVATED; ++} + +- VM_WARN_ON_ONCE(gen >= MAX_NR_GENS); ++static inline bool lru_gen_at_tail(struct lruvec *lruvec, int type, int gen) ++{ ++ unsigned long min_seq = READ_ONCE(lruvec->lrugen.min_seq[type]); + +- /* see the comment on MIN_NR_GENS */ +- return gen == lru_gen_from_seq(max_seq) || gen == lru_gen_from_seq(max_seq - 1); ++ /* ++ * Consider a folio is at the tail of its LRU when it is within ++ * MIN_NR_GENS of the oldest generation of its own type ++ */ ++ BUILD_BUG_ON(MIN_NR_GENS != 2); ++ return gen == lru_gen_from_seq(min_seq) || ++ gen == lru_gen_from_seq(min_seq + 1); + } + +-static inline void lru_gen_update_size(struct lruvec *lruvec, struct folio *folio, +- int old_gen, int new_gen) ++static inline void lru_gen_update_size(struct lruvec *lruvec, int type, ++ struct folio *folio, int old_gen, int new_gen) + { +- int type = folio_is_file_lru(folio); + int zone = folio_zonenum(folio); + int delta = folio_nr_pages(folio); +- enum lru_list lru = type * LRU_INACTIVE_FILE; + struct lru_gen_folio *lrugen = &lruvec->lrugen; + + VM_WARN_ON_ONCE(old_gen != -1 && old_gen >= MAX_NR_GENS); +@@ -186,36 +337,9 @@ static inline void lru_gen_update_size(struct lruvec *lruvec, struct folio *foli + VM_WARN_ON_ONCE(old_gen == -1 && new_gen == -1); + + if (old_gen >= 0) +- WRITE_ONCE(lrugen->nr_pages[old_gen][type][zone], +- lrugen->nr_pages[old_gen][type][zone] - delta); ++ atomic_long_sub(delta, &lrugen->nr_pages[old_gen][type][zone]); + if (new_gen >= 0) +- WRITE_ONCE(lrugen->nr_pages[new_gen][type][zone], +- lrugen->nr_pages[new_gen][type][zone] + delta); +- +- /* addition */ +- if (old_gen < 0) { +- if (lru_gen_is_active(lruvec, new_gen)) +- lru += LRU_ACTIVE; +- __update_lru_size(lruvec, lru, zone, delta); +- return; +- } +- +- /* deletion */ +- if (new_gen < 0) { +- if (lru_gen_is_active(lruvec, old_gen)) +- lru += LRU_ACTIVE; +- __update_lru_size(lruvec, lru, zone, -delta); +- return; +- } +- +- /* promotion */ +- if (!lru_gen_is_active(lruvec, old_gen) && lru_gen_is_active(lruvec, new_gen)) { +- __update_lru_size(lruvec, lru, zone, -delta); +- __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, delta); +- } +- +- /* demotion requires isolation, e.g., lru_deactivate_fn() */ +- VM_WARN_ON_ONCE(lru_gen_is_active(lruvec, old_gen) && !lru_gen_is_active(lruvec, new_gen)); ++ atomic_long_add(delta, &lrugen->nr_pages[new_gen][type][zone]); + } + + static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec, +@@ -223,23 +347,24 @@ static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec, + bool reclaiming) + { + int gen; ++ int refs = folio_lru_refs(folio); + int type = folio_is_file_lru(folio); + const struct lru_gen_folio *lrugen = &lruvec->lrugen; + + /* +- * +-----------------------------------+-----------------------------------+ +- * | Accessed through page tables and | Accessed through file descriptors | +- * | promoted by folio_update_gen() | and protected by folio_inc_gen() | +- * +-----------------------------------+-----------------------------------+ +- * | PG_active (set while isolated) | | +- * +-----------------+-----------------+-----------------+-----------------+ +- * | PG_workingset | PG_referenced | PG_workingset | LRU_REFS_FLAGS | +- * +-----------------------------------+-----------------------------------+ +- * |<---------- MIN_NR_GENS ---------->| | +- * |<---------------------------- MAX_NR_GENS ---------------------------->| ++ * +------------------------------------------+------------------------------------------+ ++ * | Accessed through page tables and | Accessed through file descriptors | ++ * | promoted by folio_inc_lru_refs_walk() | protected by folio_inc_lru_refs/inc_gen | ++ * +------------------------------------------+------------------------------------------+ ++ * | PG_active (set at isolation or refault) | | ++ * +--------------------+---------------------+--------------------+---------------------+ ++ * | LRU_REFS_MAX | LRU_REFS_WORKINGSET | LRU_REFS_MAX | LRU_REFS_WORKINGSET | ++ * +------------------------------------------+------------------------------------------+ ++ * |<-------------- MIN_NR_GENS ------------->| | ++ * |<----------------------------------- MAX_NR_GENS ----------------------------------->| + */ + if (folio_test_active(folio)) +- gen = MIN_NR_GENS - folio_test_workingset(folio); ++ gen = MIN_NR_GENS - (refs >= LRU_REFS_WORKINGSET); + else if (reclaiming) + gen = MAX_NR_GENS; + else if ((!folio_is_file_lru(folio) && !folio_test_swapcache(folio)) || +@@ -247,7 +372,7 @@ static inline unsigned long lru_gen_folio_seq(const struct lruvec *lruvec, + (folio_test_dirty(folio) || folio_test_writeback(folio)))) + gen = MIN_NR_GENS; + else +- gen = MAX_NR_GENS - (folio_test_workingset(folio) || folio_test_referenced(folio)); ++ gen = MAX_NR_GENS - (refs >= LRU_REFS_WORKINGSET); + + return max(READ_ONCE(lrugen->max_seq) - gen + 1, READ_ONCE(lrugen->min_seq[type])); + } +@@ -256,12 +381,15 @@ static inline bool lru_gen_add_folio(struct lruvec *lruvec, struct folio *folio, + { + unsigned long seq; + unsigned long flags; +- int gen = folio_lru_gen(folio); ++ int gen, refs; + int type = folio_is_file_lru(folio); + int zone = folio_zonenum(folio); ++ int delta = folio_nr_pages(folio); ++ enum lru_list lru = type * LRU_INACTIVE_FILE; + struct lru_gen_folio *lrugen = &lruvec->lrugen; + +- VM_WARN_ON_ONCE_FOLIO(gen != -1, folio); ++ BUILD_BUG_ON(BIT(LRU_GEN_WIDTH - 1) != MAX_NR_GENS); ++ VM_WARN_ON_ONCE_FOLIO(folio_lru_gen(folio) != -1, folio); + + if (folio_test_unevictable(folio) || !lrugen->enabled) + return false; +@@ -270,9 +398,15 @@ static inline bool lru_gen_add_folio(struct lruvec *lruvec, struct folio *folio, + gen = lru_gen_from_seq(seq); + flags = (gen + 1UL) << LRU_GEN_PGOFF; + /* see the comment on MIN_NR_GENS about PG_active */ +- set_mask_bits(&folio->flags.f, LRU_GEN_MASK | BIT(PG_active), flags); ++ flags = set_mask_bits(folio_flags(folio, 0), LRU_GEN_MASK | BIT(PG_active), flags); ++ /* use the refs from the atomic snapshot to avoid raced update */ ++ refs = lru_get_refs_flags(flags); ++ ++ lru_gen_update_size(lruvec, type, folio, -1, gen); ++ if (lru_refs_is_active(refs)) ++ lru += LRU_ACTIVE; ++ __update_lru_size(lruvec, lru, zone, delta); + +- lru_gen_update_size(lruvec, folio, -1, gen); + /* for folio_rotate_reclaimable() */ + if (reclaiming) + list_add_tail(&folio->lru, &lrugen->folios[gen][type][zone]); +@@ -285,31 +419,38 @@ static inline bool lru_gen_add_folio(struct lruvec *lruvec, struct folio *folio, + static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio, bool reclaiming) + { + unsigned long flags; +- int gen = folio_lru_gen(folio); ++ int gen, refs; ++ int type = folio_is_file_lru(folio); ++ int zone = folio_zonenum(folio); ++ int delta = folio_nr_pages(folio); ++ enum lru_list lru = folio_is_file_lru(folio) * LRU_INACTIVE_FILE; ++ unsigned long max_seq = READ_ONCE(lruvec->lrugen.max_seq); + ++ flags = set_mask_bits(folio_flags(folio, 0), LRU_GEN_MASK, 0); ++ gen = lru_get_gen_flags(flags); ++ refs = lru_get_refs_flags(flags); + if (gen < 0) + return false; + + VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio); + VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio); + +- /* for folio_migrate_flags() */ +- flags = !reclaiming && lru_gen_is_active(lruvec, gen) ? BIT(PG_active) : 0; +- flags = set_mask_bits(&folio->flags.f, LRU_GEN_MASK, flags); +- gen = ((flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1; ++ /* ++ * See the comment in lru_gen_folio_seq. For migration, compaction, ++ * or any other isolation of a hot folio, try best to retain its gen ++ * info. Ideally we would keep the full gen info. ++ */ ++ if (!reclaiming && ((max_seq - gen) % MAX_NR_GENS) < MIN_NR_GENS) ++ folio_set_active(folio); + +- lru_gen_update_size(lruvec, folio, gen, -1); ++ lru_gen_update_size(lruvec, type, folio, gen, -1); ++ if (lru_refs_is_active(refs)) ++ lru += LRU_ACTIVE; ++ __update_lru_size(lruvec, lru, zone, -delta); + list_del(&folio->lru); + + return true; + } +- +-static inline void folio_migrate_refs(struct folio *new, const struct folio *old) +-{ +- unsigned long refs = READ_ONCE(old->flags.f) & LRU_REFS_MASK; +- +- set_mask_bits(&new->flags.f, LRU_REFS_MASK, refs); +-} + #else /* !CONFIG_LRU_GEN */ + + static inline bool lru_gen_enabled(void) +@@ -336,12 +477,76 @@ static inline bool lru_gen_del_folio(struct lruvec *lruvec, struct folio *folio, + { + return false; + } ++#endif /* CONFIG_LRU_GEN */ + +-static inline void folio_migrate_refs(struct folio *new, const struct folio *old) ++/** ++ * folio_inc_lru_refs_fast - Bump folio refs count without promotion. ++ * @folio: the folio ++ * ++ * Raise refs from 0 to LRU_REFS_REFERENCED and leave hotter folios ++ * untouched. For the classical LRU, a plain PG_referenced set. ++ */ ++static __always_inline void folio_inc_lru_refs_fast(struct folio *folio) + { ++ unsigned long new_flags, old_flags; + ++ if (!lru_gen_enabled()) { ++ folio_set_referenced(folio); ++ return; ++ } ++ ++ BUILD_BUG_ON(LRU_REFS_REFERENCED >= LRU_REFS_ACTIVATED); ++ old_flags = READ_ONCE(*folio_flags(folio, 0)); ++ do { ++ if (lru_get_refs_flags(old_flags)) ++ break; ++ new_flags = old_flags; ++ lru_set_refs_flags(&new_flags, LRU_REFS_REFERENCED); ++ } while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags)); ++} ++ ++/** ++ * folio_check_lru_refs - Test if an LRU managed folio has been referenced. ++ * @folio: The folio to test. ++ * ++ * Returns true if the MGLRU refs count is nonzero, or PG_referenced is set, ++ * which is also correct for the non-MGLRU case. Kept as a separate helper, ++ * to avoid splattering the lru_gen_enabled() static key. ++ */ ++static inline bool folio_check_lru_refs(const struct folio *folio) ++{ ++ if (lru_gen_enabled()) ++ return folio_lru_refs(folio) > 0; ++ return folio_test_referenced(folio); ++} ++ ++/** ++ * folio_clear_lru_refs - Clear the referenced state of an LRU managed folio. ++ * @folio: The folio to clear. ++ * ++ * Reset the MGLRU refs count to zero, or clear PG_referenced, leaving ++ * PG_workingset alone for the non-MGLRU case. Kept as a separate helper ++ * just like folio_check_lru_refs(). ++ */ ++static inline void folio_clear_lru_refs(struct folio *folio) ++{ ++ if (lru_gen_enabled()) ++ folio_reset_lru_refs(folio); ++ else ++ folio_clear_referenced(folio); ++} ++ ++/* ++ * For the classical LRU only: with MGLRU the PG_workingset bit is ++ * part of the folio refs count maintained by folio_inc_lru_refs(), ++ * and a raw set would corrupt it. The switching window is exempt ++ * because the classical paths legitimately run alongside MGLRU then. ++ */ ++static __always_inline void folio_set_workingset(struct folio *folio) ++{ ++ VM_WARN_ON_ONCE(lru_gen_enabled() && !lru_gen_switching()); ++ set_bit(PG_workingset, folio_flags(folio, FOLIO_HEAD_PAGE)); + } +-#endif /* CONFIG_LRU_GEN */ + + static __always_inline + void lruvec_add_folio(struct lruvec *lruvec, struct folio *folio) +diff --git a/include/linux/mmzone.h b/include/linux/mmzone.h +index da8dd04..6bdbcc6 100644 +--- a/include/linux/mmzone.h ++++ b/include/linux/mmzone.h +@@ -453,15 +453,15 @@ enum lruvec_flags { + * least twice before handing this folio over to the eviction. The first check + * clears the accessed bit from the initial fault; the second check makes sure + * this folio hasn't been used since then. This process, AKA second chance, +- * requires a minimum of two generations, hence MIN_NR_GENS. And to maintain ABI +- * compatibility with the active/inactive LRU, e.g., /proc/vmstat, these two +- * generations are considered active; the rest of generations, if they exist, +- * are considered inactive. See lru_gen_is_active(). ++ * requires a minimum of two generations, hence MIN_NR_GENS. ++ * ++ * Active/inactive is per-folio based on the referenced count; ++ * see the comment above MAX_NR_TIERS. + * + * PG_active is always cleared while a folio is on one of lrugen->folios[] so +- * that the sliding window needs not to worry about it. And it's set again when +- * a folio considered active is isolated for non-reclaiming purposes, e.g., +- * migration. See lru_gen_add_folio() and lru_gen_del_folio(). ++ * that the sliding window needs not to worry about it. It is set on a ++ * fault-driven refault (see lru_gen_refault), or isolation (see ++ * lru_gen_del_folio). + * + * MAX_NR_GENS is set to 4 so that the multi-gen LRU can support twice the + * number of categories of the active/inactive LRU when keeping track of +@@ -472,56 +472,128 @@ enum lruvec_flags { + #define MAX_NR_GENS 4U + + /* +- * Each generation is divided into multiple tiers. A folio accessed N times +- * through file descriptors is in tier order_base_2(N). A folio in the first +- * tier (N=0,1) is marked by PG_referenced unless it was faulted in through page +- * tables or read ahead. A folio in the last tier (MAX_NR_TIERS-1) is marked by +- * PG_workingset. A folio in any other tier (1flags. ++ * Each generation is divided into multiple tiers. A folio's referenced ++ * count maps to a tier as shown below: + * +- * In contrast to moving across generations which requires the LRU lock, moving +- * across tiers only involves atomic operations on folio->flags and therefore +- * has a negligible cost in the buffered access path. In the eviction path, +- * comparisons of refaulted/(evicted+protected) from the first tier and the rest +- * infer whether folios accessed multiple times through file descriptors are +- * statistically hot and thus worth protecting. ++ * MGLRU (frequency guidance) ++ * Refs Tier |- Refs: how many times (at least) a folio has been referenced. ++ * 0 0 |- Mostly cold pages, readahead, etc. [1] ++ * 1 0 |= LRU_REFS_REFERENCED: Used at least once. [2] ++ * -WORKINGSET-+|- Pages beyond are workingset and never fall below this floor. [3] ++ * 2 1<-+|= LRU_REFS_WORKINGSET: Classical workingset, accessed twice, protected. [4] ++ * 3 2 |- LRU_REFS_PROTECTED: Protected workingset, promoted pages capped at here. [5] ++ * 4 2 | ++ * 5 3 |- The tier here is MAX_NR_TIERS - 1 ++ * 6 3 | ++ * 7 3 |= LRU_REFS_MAX: Promotion candidate. [6] ++ * -PROMOTION->-/ + * +- * MAX_NR_TIERS is set to 4 so that the multi-gen LRU can support twice the +- * number of categories of the active/inactive LRU when keeping track of +- * accesses through file descriptors. This uses MAX_NR_TIERS-2 spare bits in +- * folio->flags, masked by LRU_REFS_MASK. ++ * Ideally each tier holds folios of similar access patterns: lower tiers ++ * are less important and evicted faster. A page's reference count and ++ * tier are capped when it changes generation, preventing it from ++ * dominating the new generation based on old-generation access history. ++ * Generation ordering already ensures a newer-gen page is hotter than an ++ * older-gen one regardless of tier. ++ * ++ * Refs tracks accesses from two sources: page table (lazily collected by ++ * the page table aging walk or rmap eviction lookup) and file descriptors ++ * (by folio_mark_accessed). Page table accesses are weighted heavier ++ * because the accessed bit is sticky (undercounts repeated accesses), ++ * passively collected, and page faults are generally more important as ++ * userspace does not expect a memory access to block on reclaim. Both ++ * access types increment refs by one; the result is capped at ++ * LRU_REFS_PROTECTED on promotion or deferral, or LRU_REFS_MAX otherwise. ++ * ++ * 1. Tier is fls(N-1) for N > 1, 0 otherwise. Folios with zero ++ * accesses (refs == 0) are generally cold, e.g. readahead folios. ++ * ++ * Freshly allocated folios start with refs == 0; faulted and mapped ++ * folios have their page table access bit set, so the first page table ++ * access check always sets LRU_REFS_REFERENCED. That is the second ++ * chance described above MIN_NR_GENS: it moves the folio one ++ * generation forward if it is at the tail of its LRU, i.e., in one ++ * of the two oldest generations of its type. ++ * ++ * 2. Folios accessed once stay on tier 0: one-time usage does not ++ * qualify for protection. A second access advances the folio, ++ * aligning with classical LRU's use-twice threshold. A second page ++ * table access promotes to the latest gen; file access only defers ++ * eviction from the tail gens of its type. ++ * ++ * 3. Folios accessed at least twice are considered workingset. This ++ * mostly aligns with classical LRU: at least one I/O is saved by ++ * keeping them in memory. Folios at or above this level never fall ++ * below tier 1 (the workingset floor), so tier 0 stays a clean tier ++ * for cold cache while tier 1 serves as the fallback line for ++ * actually reused or historically hot folios. ++ * ++ * Folios refaulted through a page fault at refs 1 will enter the second ++ * newest gen, so faulting will be protected better. ++ * ++ * 4. Starting from tier 1, PID protection sacrifices lower tiers to ++ * protect higher tiers by comparing refault rates for long-term ++ * accuracy, and caps higher refs to this value. Since PID protection ++ * bypasses page table lookup and clearing, when a further eviction ++ * attempt occurs after PID loosens, the folio's page table access is ++ * rechecked and a referenced folio is put back with refs capped to ++ * this value as well. This also gives folios a fair opportunity to be ++ * promoted by file access again. ++ * ++ * Folios refaulted through a page fault at tier 1 or above are activated ++ * and enter the newest gen. Non fault page will enter second oldest gen, ++ * driving aging and workingset shifting. ++ * ++ * 5. Pages beyond the ordinary workingset tier form new tiers for the ++ * PID controller to protect differently. Folios at or above this ++ * level are capped at LRU_REFS_PROTECTED on promotion or deferral, ++ * and at LRU_REFS_WORKINGSET under PID protection in the oldest ++ * generation, where they represent a historical workingset. ++ * ++ * 6. Folios that reach LRU_REFS_MAX are advanced to the next generation ++ * on further access, with refs capped to LRU_REFS_PROTECTED. This ++ * gives them a fair start for advancement to an even newer generation ++ * while keeping hot folios distinguishable. ++ * ++ * Tiering uses PG_referenced and PG_workingset as the lower two bits, ++ * and the bits masked by LRU_REFS_MASK as the higher bits, so the refs ++ * count ranges from 0 to LRU_REFS_MAX. A folio is on the workingset ++ * tier once accessed at least twice, which is more consistent with the ++ * classical LRU. ++ * ++ * A folio's referenced count never goes backwards except upon gen ++ * increase as described above, or when explicitly reset by ++ * folio_reset_lru_refs(). Refault of a reclaimed folio restores ++ * its referenced count, capped at LRU_REFS_PROTECTED, which aligns with ++ * promotion. Page table refaults of previous workingset folios send ++ * them to the latest gen, driving aging faster. ++ * ++ * For the active/inactive LRU ABI (/proc/vmstat), a folio is active ++ * if its referenced count reaches LRU_REFS_ACTIVATED. The threshold ++ * currently set to LRU_REFS_PROTECTED, which is tier 2. ++ * ++ * MAX_NR_TIERS is set to 4 so that the multi-gen LRU can support twice ++ * the number of categories of the active/inactive LRU. + */ + #define MAX_NR_TIERS 4U + #define LRU_TIER_MIN 0U + #define LRU_TIER_MAX (MAX_NR_TIERS - 1) + ++/* Flags for folio_inc_lru_refs() */ ++#define LRU_REF_MAPPED 0x1U ++#define LRU_REF_EXEC 0x2U ++#define LRU_REF_FORCE 0x4U ++ ++#define LRU_REFS_REFERENCED 0x1 ++#define LRU_REFS_WORKINGSET 0x2 ++#define LRU_REFS_PROTECTED 0x3 ++#define LRU_REFS_ACTIVATED LRU_REFS_PROTECTED ++ + #ifndef __GENERATING_BOUNDS_H + + #define LRU_GEN_MASK ((BIT(LRU_GEN_WIDTH) - 1) << LRU_GEN_PGOFF) + #define LRU_REFS_MASK ((BIT(LRU_REFS_WIDTH) - 1) << LRU_REFS_PGOFF) +- +-/* +- * For folios accessed multiple times through file descriptors, +- * lru_gen_inc_refs() sets additional bits of LRU_REFS_WIDTH in folio->flags +- * after PG_referenced, then PG_workingset after LRU_REFS_WIDTH. After all its +- * bits are set, i.e., LRU_REFS_FLAGS|BIT(PG_workingset), a folio is lazily +- * promoted into the second oldest generation in the eviction path. And when +- * folio_inc_gen() does that, it clears LRU_REFS_FLAGS so that +- * lru_gen_inc_refs() can start over. Note that for this case, LRU_REFS_MASK is +- * only valid when PG_referenced is set. +- * +- * For folios accessed multiple times through page tables, folio_update_gen() +- * from a page table walk or lru_gen_set_refs() from a rmap walk sets +- * PG_referenced after the accessed bit is cleared for the first time. +- * Thereafter, those two paths set PG_workingset and promote folios to the +- * youngest generation. Like folio_inc_gen(), folio_update_gen() also clears +- * PG_referenced. Note that for this case, LRU_REFS_MASK is not used. +- * +- * For both cases above, after PG_workingset is set on a folio, it remains until +- * this folio is either reclaimed, or "deactivated" by lru_gen_clear_refs(). It +- * can be set again if lru_gen_test_recent() returns true upon a refault. +- */ +-#define LRU_REFS_FLAGS (LRU_REFS_MASK | BIT(PG_referenced)) ++#define LRU_REFS_FLAGS (LRU_REFS_MASK | BIT(PG_referenced) | BIT(PG_workingset)) ++#define LRU_REFS_MAX (BIT(LRU_REFS_WIDTH + 2) - 1) + + struct lruvec; + struct page_vma_mapped_walk; +@@ -572,7 +644,7 @@ struct lru_gen_folio { + /* the multi-gen LRU lists, lazily sorted on eviction */ + struct list_head folios[MAX_NR_GENS][ANON_AND_FILE][MAX_NR_ZONES]; + /* the multi-gen LRU sizes, eventually consistent */ +- long nr_pages[MAX_NR_GENS][ANON_AND_FILE][MAX_NR_ZONES]; ++ atomic_long_t nr_pages[MAX_NR_GENS][ANON_AND_FILE][MAX_NR_ZONES]; + /* the exponential moving average of refaulted */ + unsigned long avg_refaulted[ANON_AND_FILE][MAX_NR_TIERS]; + /* the exponential moving average of evicted+protected */ +@@ -623,6 +695,8 @@ struct lru_gen_mm_walk { + unsigned long seq; + /* the next address within an mm to scan */ + unsigned long next_addr; ++ /* to batch activated pages */ ++ int nr_activated[ANON_AND_FILE][MAX_NR_ZONES]; + /* to batch promoted pages */ + int nr_pages[MAX_NR_GENS][ANON_AND_FILE][MAX_NR_ZONES]; + /* to batch the mm stats */ +diff --git a/include/linux/page-flags.h b/include/linux/page-flags.h +index 7a86357..13f1b4a 100644 +--- a/include/linux/page-flags.h ++++ b/include/linux/page-flags.h +@@ -554,8 +554,6 @@ PAGEFLAG(LRU, lru, PF_HEAD) __CLEARPAGEFLAG(LRU, lru, PF_HEAD) + FOLIO_FLAG(active, FOLIO_HEAD_PAGE) + __FOLIO_CLEAR_FLAG(active, FOLIO_HEAD_PAGE) + FOLIO_TEST_CLEAR_FLAG(active, FOLIO_HEAD_PAGE) +-PAGEFLAG(Workingset, workingset, PF_HEAD) +- TESTCLEARFLAG(Workingset, workingset, PF_HEAD) + PAGEFLAG(Checked, checked, PF_NO_COMPOUND) /* Used by some filesystems */ + + /* Xen */ +diff --git a/include/linux/perf_event.h b/include/linux/perf_event.h +index 2d5e768..b422c06 100644 +--- a/include/linux/perf_event.h ++++ b/include/linux/perf_event.h +@@ -1616,7 +1616,7 @@ static inline void perf_event_task_migrate(struct task_struct *task) + task->sched_migrated = 1; + } + +-static inline void perf_event_task_sched_in(struct task_struct *prev, ++static __always_inline void perf_event_task_sched_in(struct task_struct *prev, + struct task_struct *task) + { + if (static_branch_unlikely(&perf_sched_events)) +diff --git a/include/linux/rseq_entry.h b/include/linux/rseq_entry.h +index 31ce349..23db2b3 100644 +--- a/include/linux/rseq_entry.h ++++ b/include/linux/rseq_entry.h +@@ -730,7 +730,10 @@ static __always_inline void rseq_syscall_exit_to_user_mode(void) + + /* Needed to remove the store for the !lockdep case */ + if (IS_ENABLED(CONFIG_LOCKDEP)) { ++#ifndef CONFIG_SCHED_ALT ++/* WA for sched/alt: [Sync] 9a723ed7facf sched/mmcid: Provide new scheduler CID mechanism */ + WARN_ON_ONCE(ev->sched_switch); ++#endif /* !CONFIG_SCHED_ALT */ + ev->events = 0; + } + } +diff --git a/include/linux/sched.h b/include/linux/sched.h +index 78bfc0e..2d1fa54 100644 +--- a/include/linux/sched.h ++++ b/include/linux/sched.h +@@ -871,6 +871,7 @@ struct task_struct { + unsigned long wakee_flip_decay_ts; + struct task_struct *last_wakee; + ++#ifndef CONFIG_SCHED_ALT + /* + * recent_used_cpu is initially set as the last CPU used by a task + * that wakes affine another task. Waker/wakee relationships can +@@ -880,12 +881,33 @@ struct task_struct { + */ + int recent_used_cpu; + int wake_cpu; ++#endif /* !CONFIG_SCHED_ALT */ + + int prio; + int static_prio; + int normal_prio; + unsigned int rt_priority; + ++#ifdef CONFIG_SCHED_ALT ++ u64 last_ran; ++ s64 time_slice; ++ u64 wake_start; ++ struct list_head sq_node; ++#ifdef CONFIG_SCHED_BMQ ++ int boost_prio; ++#endif /* CONFIG_SCHED_BMQ */ ++#ifdef CONFIG_SCHED_PDS ++ u64 deadline; ++ u64 sleep_start; ++ u64 sleep_credit; ++ u64 wake_sched_time; ++ u64 wake_period; ++ u64 credit_wake; ++ u64 credit_sched_time; ++#endif /* CONFIG_SCHED_PDS */ ++ /* sched_clock time spent running */ ++ u64 sched_time; ++#else /* !CONFIG_SCHED_ALT */ + struct sched_entity se; + struct sched_rt_entity rt; + struct sched_dl_entity dl; +@@ -900,6 +922,7 @@ struct task_struct { + unsigned long core_cookie; + unsigned int core_occupation; + #endif ++#endif /* !CONFIG_SCHED_ALT */ + + #ifdef CONFIG_CGROUP_SCHED + struct task_group *sched_task_group; +@@ -941,9 +964,13 @@ struct task_struct { + const cpumask_t *cpus_ptr; + cpumask_t *user_cpus_ptr; + cpumask_t cpus_mask; ++#ifndef CONFIG_SCHED_ALT + void *migration_pending; ++#endif + unsigned short migration_disabled; ++#ifndef CONFIG_SCHED_ALT + unsigned short migration_flags; ++#endif + + #ifdef CONFIG_PREEMPT_RCU + int rcu_read_lock_nesting; +@@ -974,8 +1001,10 @@ struct task_struct { + struct sched_info sched_info; + + struct list_head tasks; ++#ifndef CONFIG_SCHED_ALT + struct plist_node pushable_tasks; + struct rb_node pushable_dl_tasks; ++#endif + + struct mm_struct *mm; + struct mm_struct *active_mm; +@@ -1703,6 +1732,15 @@ static inline bool sched_proxy_exec(void) + } + #endif + ++#ifdef CONFIG_SCHED_ALT ++#define tsk_seruntime(t) ((t)->sched_time) ++/* replace the uncertian rt_timeout with 0UL */ ++#define tsk_rttimeout(t) (0UL) ++#else /* !CONFIG_SCHED_ALT: */ ++#define tsk_seruntime(t) ((t)->se.sum_exec_runtime) ++#define tsk_rttimeout(t) ((t)->rt.timeout) ++#endif /* !CONFIG_SCHED_ALT */ ++ + #define TASK_REPORT_IDLE (TASK_REPORT + 1) + #define TASK_REPORT_MAX (TASK_REPORT_IDLE << 1) + +@@ -2301,7 +2339,11 @@ static inline void set_task_cpu(struct task_struct *p, unsigned int cpu) + + static inline bool task_is_runnable(struct task_struct *p) + { ++#ifdef CONFIG_SCHED_ALT ++ return p->on_rq; ++#else + return p->on_rq && !p->se.sched_delayed; ++#endif /* !CONFIG_SCHED_ALT */ + } + + extern bool sched_task_on_rq(struct task_struct *p); +@@ -2460,10 +2502,33 @@ DECLARE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues); + #endif + #define this_rq_pinned() (*(unsigned int *)((void *)this_rq_raw() + RQ_nr_pinned)) + ++static inline void ++__do_set_cpus_ptr(struct task_struct *p, const struct cpumask *new_mask) ++{ ++ /* ++ * This here violates the locking rules for affinity, since we're only ++ * supposed to change these variables while holding both rq->lock and ++ * p->pi_lock. ++ * ++ * HOWEVER, it magically works, because ttwu() is the only code that ++ * accesses these variables under p->pi_lock and only does so after ++ * smp_cond_load_acquire(&p->on_cpu, !VAL), and we're in __schedule() ++ * before finish_task(). ++ * ++ * XXX do further audits, this smells like something putrid. ++ */ ++ WARN_ON_ONCE(!p->on_cpu); ++ p->cpus_ptr = new_mask; ++} ++ + static inline void __migrate_enable(void) + { + struct task_struct *p = current; + ++#ifdef CONFIG_SCHED_ALT ++ if (!p->migration_disabled) ++ return; ++#endif + #ifdef CONFIG_DEBUG_PREEMPT + /* + * Check both overflow from migrate_disable() and superfluous +@@ -2483,8 +2548,17 @@ static inline void __migrate_enable(void) + * __set_cpus_allowed_ptr(SCA_MIGRATE_ENABLE) doesn't schedule(). + */ + guard(preempt)(); ++#ifdef CONFIG_SCHED_ALT ++ /* ++ * Assumption: current should be running on allowed cpu ++ */ ++ WARN_ON_ONCE(!cpumask_test_cpu(smp_processor_id(), &p->cpus_mask)); ++ if (p->cpus_ptr != &p->cpus_mask) ++ __do_set_cpus_ptr(p, &p->cpus_mask); ++#else + if (unlikely(p->cpus_ptr != &p->cpus_mask)) + ___migrate_enable(); ++#endif + /* + * Mustn't clear migration_disabled() until cpus_ptr points back at the + * regular cpus_mask, otherwise things that race (eg. +@@ -2511,8 +2585,20 @@ static inline void __migrate_disable(void) + } + + guard(preempt)(); ++#ifdef CONFIG_SCHED_ALT ++ int cpu = smp_processor_id(); ++ if (cpumask_test_cpu(cpu, &p->cpus_mask)) { ++#endif + this_rq_pinned()++; + p->migration_disabled = 1; ++#ifdef CONFIG_SCHED_ALT ++ /* ++ * Violates locking rules! see comment in __do_set_cpus_ptr(). ++ */ ++ if (p->cpus_ptr == &p->cpus_mask) ++ __do_set_cpus_ptr(p, cpumask_of(cpu)); ++ } ++#endif + } + #else /* !COMPILE_OFFSETS */ + static inline void __migrate_disable(void) { } +diff --git a/include/linux/sched/deadline.h b/include/linux/sched/deadline.h +index 2735382..12b4150 100644 +--- a/include/linux/sched/deadline.h ++++ b/include/linux/sched/deadline.h +@@ -2,6 +2,25 @@ + #ifndef _LINUX_SCHED_DEADLINE_H + #define _LINUX_SCHED_DEADLINE_H + ++#ifdef CONFIG_SCHED_ALT ++ ++static inline int dl_task(struct task_struct *p) ++{ ++ return 0; ++} ++ ++#ifdef CONFIG_SCHED_BMQ ++#define __tsk_deadline(p) (0UL) ++#endif ++ ++#ifdef CONFIG_SCHED_PDS ++#define __tsk_deadline(p) ((((u64) ((p)->prio))<<56) | (p)->deadline) ++#endif ++ ++#else ++ ++#define __tsk_deadline(p) ((p)->dl.deadline) ++ + /* + * SCHED_DEADLINE tasks has negative priorities, reflecting + * the fact that any of them has higher prio than RT and +@@ -72,5 +91,6 @@ static inline bool dl_is_implicit(struct sched_dl_entity *dl_se) + { + return dl_se->dl_deadline == dl_se->dl_period; + } ++#endif /* !CONFIG_SCHED_ALT */ + + #endif /* _LINUX_SCHED_DEADLINE_H */ +diff --git a/include/linux/sched/mm.h b/include/linux/sched/mm.h +index d7c6a94..d1b4bdd 100644 +--- a/include/linux/sched/mm.h ++++ b/include/linux/sched/mm.h +@@ -44,7 +44,7 @@ static inline void smp_mb__after_mmgrab(void) + + extern void __mmdrop(struct mm_struct *mm); + +-static inline void mmdrop(struct mm_struct *mm) ++static __always_inline void mmdrop(struct mm_struct *mm) + { + /* + * The implicit full barrier implied by atomic_dec_and_test() is +@@ -71,14 +71,14 @@ static inline void __mmdrop_delayed(struct rcu_head *rhp) + * Invoked from finish_task_switch(). Delegates the heavy lifting on RT + * kernels via RCU. + */ +-static inline void mmdrop_sched(struct mm_struct *mm) ++static __always_inline void mmdrop_sched(struct mm_struct *mm) + { + /* Provides a full memory barrier. See mmdrop() */ + if (atomic_dec_and_test(&mm->mm_count)) + call_rcu(&mm->delayed_drop, __mmdrop_delayed); + } + #else +-static inline void mmdrop_sched(struct mm_struct *mm) ++static __always_inline void mmdrop_sched(struct mm_struct *mm) + { + mmdrop(mm); + } +@@ -104,7 +104,7 @@ static inline void mmdrop_lazy_tlb(struct mm_struct *mm) + } + } + +-static inline void mmdrop_lazy_tlb_sched(struct mm_struct *mm) ++static __always_inline void mmdrop_lazy_tlb_sched(struct mm_struct *mm) + { + if (IS_ENABLED(CONFIG_MMU_LAZY_TLB_REFCOUNT)) + mmdrop_sched(mm); +@@ -531,7 +531,7 @@ enum { + #include + #endif + +-static inline void membarrier_mm_sync_core_before_usermode(struct mm_struct *mm) ++static __always_inline void membarrier_mm_sync_core_before_usermode(struct mm_struct *mm) + { + /* + * The atomic_read() below prevents CSE. The following should +diff --git a/include/linux/sched/prio.h b/include/linux/sched/prio.h +index 6ab43b4..ef1cff5 100644 +--- a/include/linux/sched/prio.h ++++ b/include/linux/sched/prio.h +@@ -19,6 +19,28 @@ + #define MAX_PRIO (MAX_RT_PRIO + NICE_WIDTH) + #define DEFAULT_PRIO (MAX_RT_PRIO + NICE_WIDTH / 2) + ++#ifdef CONFIG_SCHED_ALT ++ ++/* Undefine MAX_PRIO and DEFAULT_PRIO */ ++#undef MAX_PRIO ++#undef DEFAULT_PRIO ++ ++/* +/- priority levels from the base priority */ ++#ifdef CONFIG_SCHED_BMQ ++#define MAX_PRIORITY_ADJ (12) ++#endif ++ ++#ifdef CONFIG_SCHED_PDS ++#define MAX_PRIORITY_ADJ (0) ++#endif ++ ++#define MIN_NORMAL_PRIO (128) ++#define NORMAL_PRIO_NUM (64) ++#define MAX_PRIO (MIN_NORMAL_PRIO + NORMAL_PRIO_NUM) ++#define DEFAULT_PRIO (MAX_PRIO - MAX_PRIORITY_ADJ - NICE_WIDTH / 2) ++ ++#endif /* CONFIG_SCHED_ALT */ ++ + /* + * Convert user-nice values [ -20 ... 0 ... 19 ] + * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ], +diff --git a/include/linux/sched/rt.h b/include/linux/sched/rt.h +index 922935c..9cb5c02 100644 +--- a/include/linux/sched/rt.h ++++ b/include/linux/sched/rt.h +@@ -45,8 +45,10 @@ static inline bool rt_or_dl_task_policy(struct task_struct *tsk) + + if (policy == SCHED_FIFO || policy == SCHED_RR) + return true; ++#ifndef CONFIG_SCHED_ALT + if (policy == SCHED_DEADLINE) + return true; ++#endif + return false; + } + +diff --git a/include/linux/sched/topology.h b/include/linux/sched/topology.h +index f96812d..8984fce 100644 +--- a/include/linux/sched/topology.h ++++ b/include/linux/sched/topology.h +@@ -226,7 +226,8 @@ extern void sched_update_asym_prefer_cpu(int cpu, int old_prio, int new_prio); + #define SDTL_INIT(maskfn, flagsfn, dname) ((struct sched_domain_topology_level) \ + { .mask = maskfn, .sd_flags = flagsfn, .name = #dname }) + +-#if defined(CONFIG_ENERGY_MODEL) && defined(CONFIG_CPU_FREQ_GOV_SCHEDUTIL) ++#if defined(CONFIG_ENERGY_MODEL) && defined(CONFIG_CPU_FREQ_GOV_SCHEDUTIL) && \ ++ !defined(CONFIG_SCHED_ALT) + extern void rebuild_sched_domains_energy(void); + #else + static inline void rebuild_sched_domains_energy(void) +diff --git a/include/linux/tcp.h b/include/linux/tcp.h +index 6a8c777..38498e2 100644 +--- a/include/linux/tcp.h ++++ b/include/linux/tcp.h +@@ -232,7 +232,8 @@ struct tcp_sock { + tcp_usec_ts : 1, /* TSval values in usec */ + is_sack_reneg:1, /* in recovery from loss with SACK reneg? */ + is_cwnd_limited:1,/* forward progress limited by snd_cwnd? */ +- recvmsg_inq : 1;/* Indicate # of bytes in queue upon recvmsg */ ++ recvmsg_inq : 1,/* Indicate # of bytes in queue upon recvmsg */ ++ fast_ack_mode:1;/* ack ASAP if >1 rcv_mss received? */ + __cacheline_group_end(tcp_sock_read_txrx); + + /* RX read-mostly hotpath cache lines */ +@@ -298,7 +299,8 @@ struct tcp_sock { + * 0x5?10 << 16 + snd_wnd in net byte order + */ + u8 nonagle : 4,/* Disable Nagle algorithm? */ +- rate_app_limited:1; /* rate_{delivered,interval_us} limited? */ ++ rate_app_limited:1, /* rate_{delivered,interval_us} limited? */ ++ tlp_orig_data_app_limited:1; /* app-limited before TLP rtx? */ + u8 received_ce_pending:4, /* Not yet transmit cnt of received_ce */ + accecn_opt_sent_w_dsack:1,/* Sent ACCECN opt in previous ACK w/ D-SACK */ + unused2:3; +diff --git a/include/linux/tick.h b/include/linux/tick.h +index b121c5d..ea7002a 100644 +--- a/include/linux/tick.h ++++ b/include/linux/tick.h +@@ -172,7 +172,7 @@ extern cpumask_var_t tick_nohz_full_mask; + #ifdef CONFIG_NO_HZ_FULL + extern bool tick_nohz_full_running; + +-static inline bool tick_nohz_full_enabled(void) ++static __always_inline bool tick_nohz_full_enabled(void) + { + if (!context_tracking_enabled()) + return false; +@@ -296,7 +296,7 @@ static inline void __tick_nohz_task_switch(void) { } + static inline void tick_nohz_full_setup(cpumask_var_t cpumask) { } + #endif + +-static inline void tick_nohz_task_switch(void) ++static __always_inline void tick_nohz_task_switch(void) + { + if (tick_nohz_full_enabled()) + __tick_nohz_task_switch(); +diff --git a/include/linux/vtime.h b/include/linux/vtime.h +index 82825e7..ce83fc7 100644 +--- a/include/linux/vtime.h ++++ b/include/linux/vtime.h +@@ -89,24 +89,24 @@ static __always_inline void vtime_account_guest_exit(void) + * For now vtime state is tied to context tracking. We might want to decouple + * those later if necessary. + */ +-static inline bool vtime_accounting_enabled(void) ++static __always_inline bool vtime_accounting_enabled(void) + { + return context_tracking_enabled(); + } + +-static inline bool vtime_accounting_enabled_cpu(int cpu) ++static __always_inline bool vtime_accounting_enabled_cpu(int cpu) + { + return vtime_generic_enabled_cpu(cpu); + } + +-static inline bool vtime_accounting_enabled_this_cpu(void) ++static __always_inline bool vtime_accounting_enabled_this_cpu(void) + { + return vtime_generic_enabled_this_cpu(); + } + + extern void vtime_task_switch_generic(struct task_struct *prev); + +-static inline void vtime_task_switch(struct task_struct *prev) ++static __always_inline void vtime_task_switch(struct task_struct *prev) + { + if (vtime_accounting_enabled_this_cpu()) + vtime_task_switch_generic(prev); +diff --git a/include/net/inet_connection_sock.h b/include/net/inet_connection_sock.h +index 433c2df..ce51146 100644 +--- a/include/net/inet_connection_sock.h ++++ b/include/net/inet_connection_sock.h +@@ -138,8 +138,8 @@ struct inet_connection_sock { + u32 icsk_probes_tstamp; + u32 icsk_user_timeout; + +- u64 icsk_ca_priv[104 / sizeof(u64)]; +-#define ICSK_CA_PRIV_SIZE sizeof_field(struct inet_connection_sock, icsk_ca_priv) ++#define ICSK_CA_PRIV_SIZE (144) ++ u64 icsk_ca_priv[ICSK_CA_PRIV_SIZE / sizeof(u64)]; + }; + + #define ICSK_TIME_RETRANS 1 /* Retransmit timer */ +diff --git a/include/net/tcp.h b/include/net/tcp.h +index 4416cdf..6828726 100644 +--- a/include/net/tcp.h ++++ b/include/net/tcp.h +@@ -428,6 +428,8 @@ static inline void tcp_dec_quickack_mode(struct sock *sk) + #define TCP_ECN_DEMAND_CWR BIT(2) + #define TCP_ECN_SEEN BIT(3) + #define TCP_ECN_MODE_ACCECN BIT(4) ++#define TCP_ECN_LOW BIT(5) ++#define TCP_ECN_ECT_PERMANENT BIT(6) + + #define TCP_ECN_DISABLED 0 + #define TCP_ECN_MODE_PENDING (TCP_ECN_MODE_RFC3168 | TCP_ECN_MODE_ACCECN) +@@ -891,6 +893,15 @@ static inline unsigned long tcp_reqsk_timeout(struct request_sock *req) + + u32 tcp_delack_max(const struct sock *sk); + ++static inline void tcp_set_ecn_low_from_dst(struct sock *sk, ++ const struct dst_entry *dst) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ ++ if (dst_feature(dst, RTAX_FEATURE_ECN_LOW)) ++ tp->ecn_flags |= TCP_ECN_LOW; ++} ++ + /* Compute the actual rto_min value */ + static inline u32 tcp_rto_min(const struct sock *sk) + { +@@ -1028,6 +1039,11 @@ static inline u32 tcp_stamp_us_delta(u64 t1, u64 t0) + return max_t(s64, t1 - t0, 0); + } + ++static inline u32 tcp_stamp32_us_delta(u32 t1, u32 t0) ++{ ++ return max_t(s32, t1 - t0, 0); ++} ++ + /* provide the departure time in us unit */ + static inline u64 tcp_skb_timestamp_us(const struct sk_buff *skb) + { +@@ -1141,9 +1157,14 @@ struct tcp_skb_cb { + /* pkts S/ACKed so far upon tx of skb, incl retrans: */ + __u32 delivered; + /* start of send pipeline phase */ +- u64 first_tx_mstamp; ++ u32 first_tx_mstamp; + /* when we reached the "delivered" count */ +- u64 delivered_mstamp; ++ u32 delivered_mstamp; ++#define TCPCB_IN_FLIGHT_BITS 20 ++#define TCPCB_IN_FLIGHT_MAX ((1U << TCPCB_IN_FLIGHT_BITS) - 1) ++ u32 in_flight:20, /* packets in flight at transmit */ ++ unused2:12; ++ u32 lost; /* packets lost so far upon tx of skb */ + } tx; /* only used for outgoing skbs */ + union { + struct inet_skb_parm h4; +@@ -1254,6 +1275,7 @@ enum tcp_ca_event { + CA_EVENT_LOSS, /* loss timeout */ + CA_EVENT_ECN_NO_CE, /* ECT set, but not CE marked */ + CA_EVENT_ECN_IS_CE, /* received CE marked IP packet */ ++ CA_EVENT_TLP_RECOVERY, /* a lost segment was repaired by TLP probe */ + }; + + /* Information about inbound ACK, passed to cong_ops->in_ack_event() */ +@@ -1282,9 +1304,11 @@ enum tcp_ca_ack_event_flags { + #define TCP_CONG_ECT_1_NEGOTIATION BIT(3) + /* Cannot fallback to RFC3168 during AccECN negotiation */ + #define TCP_CONG_NO_FALLBACK_RFC3168 BIT(4) ++/* Wants notification of CE events (CA_EVENT_ECN_IS_CE, CA_EVENT_ECN_NO_CE). */ ++#define TCP_CONG_WANTS_CE_EVENTS BIT(5) + #define TCP_CONG_MASK (TCP_CONG_NON_RESTRICTED | TCP_CONG_NEEDS_ECN | \ + TCP_CONG_NEEDS_ACCECN | TCP_CONG_ECT_1_NEGOTIATION | \ +- TCP_CONG_NO_FALLBACK_RFC3168) ++ TCP_CONG_NO_FALLBACK_RFC3168 | TCP_CONG_WANTS_CE_EVENTS) + + union tcp_cc_info; + +@@ -1304,10 +1328,13 @@ struct ack_sample { + */ + struct rate_sample { + u64 prior_mstamp; /* starting timestamp for interval */ ++ u32 prior_lost; /* tp->lost at "prior_mstamp" */ + u32 prior_delivered; /* tp->delivered at "prior_mstamp" */ + u32 prior_delivered_ce;/* tp->delivered_ce at "prior_mstamp" */ ++ u32 tx_in_flight; /* packets in flight at starting timestamp */ ++ s32 lost; /* number of packets lost over interval */ + s32 delivered; /* number of packets delivered over interval */ +- s32 delivered_ce; /* number of packets delivered w/ CE marks*/ ++ s32 delivered_ce; /* packets delivered w/ CE mark over interval */ + long interval_us; /* time for tp->delivered to incr "delivered" */ + u32 snd_interval_us; /* snd interval for delivered packets */ + u32 rcv_interval_us; /* rcv interval for delivered packets */ +@@ -1318,7 +1345,9 @@ struct rate_sample { + u32 last_end_seq; /* end_seq of most recently ACKed packet */ + bool is_app_limited; /* is sample from packet with bubble in pipe? */ + bool is_retrans; /* is sample from retransmission? */ ++ bool is_acking_tlp_retrans_seq; /* ACKed a TLP retransmit sequence? */ + bool is_ack_delayed; /* is this (likely) a delayed ACK? */ ++ bool is_ece; /* did this ACK have ECN marked? */ + }; + + struct tcp_congestion_ops { +@@ -1360,8 +1389,11 @@ struct tcp_congestion_ops { + /* hook for packet ack accounting (optional) */ + void (*pkts_acked)(struct sock *sk, const struct ack_sample *sample); + +- /* override sysctl_tcp_min_tso_segs (optional) */ +- u32 (*min_tso_segs)(struct sock *sk); ++ /* pick target number of segments per TSO/GSO skb (optional): */ ++ u32 (*tso_segs)(struct sock *sk, unsigned int mss_now); ++ ++ /* react to a specific lost skb (optional) */ ++ void (*skb_marked_lost)(struct sock *sk, const struct sk_buff *skb); + + /* new value of cwnd after loss (required) */ + u32 (*undo_cwnd)(struct sock *sk); +@@ -1421,6 +1453,14 @@ static inline char *tcp_ca_get_name_by_key(u32 key, char *buffer) + } + #endif + ++static inline bool tcp_ca_wants_ce_events(const struct sock *sk) ++{ ++ const struct inet_connection_sock *icsk = inet_csk(sk); ++ ++ return icsk->icsk_ca_ops->flags & (TCP_CONG_NEEDS_ECN | ++ TCP_CONG_WANTS_CE_EVENTS); ++} ++ + static inline bool tcp_ca_needs_ecn(const struct sock *sk) + { + const struct inet_connection_sock *icsk = inet_csk(sk); +@@ -1471,6 +1511,21 @@ static inline bool tcp_skb_sent_after(u64 t1, u64 t2, u32 seq1, u32 seq2) + return t1 > t2 || (t1 == t2 && after(seq1, seq2)); + } + ++/* If a retransmit failed due to local qdisc congestion or other local issues, ++ * then we may have called tcp_set_skb_tso_segs() to increase the number of ++ * segments in the skb without increasing the tx.in_flight. In all other cases, ++ * the tx.in_flight should be at least as big as the pcount of the sk_buff. We ++ * do not have the state to know whether a retransmit failed due to local qdisc ++ * congestion or other local issues, so to avoid spurious warnings we consider ++ * that any skb marked lost may have suffered that fate. ++ */ ++static inline bool tcp_skb_tx_in_flight_is_suspicious(u32 skb_pcount, ++ u32 skb_sacked_flags, ++ u32 tx_in_flight) ++{ ++ return (skb_pcount > tx_in_flight) && !(skb_sacked_flags & TCPCB_LOST); ++} ++ + /* These functions determine how the current flow behaves in respect of SACK + * handling. SACK is negotiated with the peer, and therefore it can vary + * between different flows. +@@ -2662,7 +2717,7 @@ struct tcp_plb_state { + u8 consec_cong_rounds:5, /* consecutive congested rounds */ + unused:3; + u32 pause_until; /* jiffies32 when PLB can resume rerouting */ +-}; ++} __attribute__ ((__packed__)); + + static inline void tcp_plb_init(const struct sock *sk, + struct tcp_plb_state *plb) +diff --git a/include/net/tcp_ecn.h b/include/net/tcp_ecn.h +index 865d5c5..b5cd7e5 100644 +--- a/include/net/tcp_ecn.h ++++ b/include/net/tcp_ecn.h +@@ -606,10 +606,9 @@ static inline void tcp_ecn_send_syn(struct sock *sk, struct sk_buff *skb) + use_ecn = tcp_ecn == TCP_ECN_IN_ECN_OUT_ECN || + tcp_ecn == TCP_ECN_IN_ACCECN_OUT_ECN || + tcp_ca_needs_ecn(sk) || bpf_needs_ecn || use_accecn; ++ const struct dst_entry *dst = __sk_dst_get(sk); + + if (!use_ecn) { +- const struct dst_entry *dst = __sk_dst_get(sk); +- + if (dst && dst_feature(dst, RTAX_FEATURE_ECN)) + use_ecn = true; + } +@@ -627,6 +626,9 @@ static inline void tcp_ecn_send_syn(struct sock *sk, struct sk_buff *skb) + tp->syn_ect_snt = inet_sk(sk)->tos & INET_ECN_MASK; + } else { + tcp_ecn_mode_set(tp, TCP_ECN_MODE_RFC3168); ++ ++ if (dst) ++ tcp_set_ecn_low_from_dst(sk, dst); + } + } + } +diff --git a/include/uapi/linux/inet_diag.h b/include/uapi/linux/inet_diag.h +index 21f0d73..80794f6 100644 +--- a/include/uapi/linux/inet_diag.h ++++ b/include/uapi/linux/inet_diag.h +@@ -238,6 +238,29 @@ struct tcp_bbr_info { + __u32 bbr_min_rtt; /* min-filtered RTT in uSec */ + __u32 bbr_pacing_gain; /* pacing gain shifted left 8 bits */ + __u32 bbr_cwnd_gain; /* cwnd gain shifted left 8 bits */ ++ __u32 bbr_bw_hi_lsb; /* lower 32 bits of bw_hi */ ++ __u32 bbr_bw_hi_msb; /* upper 32 bits of bw_hi */ ++ __u32 bbr_bw_lo_lsb; /* lower 32 bits of bw_lo */ ++ __u32 bbr_bw_lo_msb; /* upper 32 bits of bw_lo */ ++ __u8 bbr_mode; /* current bbr_mode in state machine */ ++ __u8 bbr_phase; /* current state machine phase */ ++ __u8 unused1; /* alignment padding; not used yet */ ++ __u8 bbr_version; /* BBR algorithm version */ ++ __u32 bbr_inflight_lo; /* lower short-term data volume bound */ ++ __u32 bbr_inflight_hi; /* higher long-term data volume bound */ ++ __u32 bbr_extra_acked; /* max excess packets ACKed in epoch */ ++}; ++ ++/* TCP BBR congestion control bbr_phase as reported in netlink/ss stats. */ ++enum tcp_bbr_phase { ++ BBR_PHASE_INVALID = 0, ++ BBR_PHASE_STARTUP = 1, ++ BBR_PHASE_DRAIN = 2, ++ BBR_PHASE_PROBE_RTT = 3, ++ BBR_PHASE_PROBE_BW_UP = 4, ++ BBR_PHASE_PROBE_BW_DOWN = 5, ++ BBR_PHASE_PROBE_BW_CRUISE = 6, ++ BBR_PHASE_PROBE_BW_REFILL = 7, + }; + + union tcp_cc_info { +diff --git a/include/uapi/linux/rtnetlink.h b/include/uapi/linux/rtnetlink.h +index 3988b51..f76b0f1 100644 +--- a/include/uapi/linux/rtnetlink.h ++++ b/include/uapi/linux/rtnetlink.h +@@ -542,12 +542,14 @@ enum { + #define RTAX_FEATURE_TIMESTAMP (1 << 2) /* unused */ + #define RTAX_FEATURE_ALLFRAG (1 << 3) /* unused */ + #define RTAX_FEATURE_TCP_USEC_TS (1 << 4) ++#define RTAX_FEATURE_ECN_LOW (1 << 5) + + #define RTAX_FEATURE_MASK (RTAX_FEATURE_ECN | \ + RTAX_FEATURE_SACK | \ + RTAX_FEATURE_TIMESTAMP | \ + RTAX_FEATURE_ALLFRAG | \ +- RTAX_FEATURE_TCP_USEC_TS) ++ RTAX_FEATURE_TCP_USEC_TS | \ ++ RTAX_FEATURE_ECN_LOW) + + struct rta_session { + __u8 proto; +diff --git a/include/uapi/linux/tcp.h b/include/uapi/linux/tcp.h +index 03772dd..83eaf13 100644 +--- a/include/uapi/linux/tcp.h ++++ b/include/uapi/linux/tcp.h +@@ -185,6 +185,7 @@ enum tcp_fastopen_client_fail { + #define TCPI_OPT_SYN_DATA 32 /* SYN-ACK acked data in SYN sent or rcvd */ + #define TCPI_OPT_USEC_TS 64 /* usec timestamps */ + #define TCPI_OPT_TFO_CHILD 128 /* child from a Fast Open option on SYN */ ++#define TCPI_OPT_ECN_LOW 256 /* Low-latency ECN enabled at conn init */ + + /* + * Sender's congestion state indicating normal or abnormal situations +diff --git a/init/Kconfig b/init/Kconfig +index ad592fd..0f0ca94 100644 +--- a/init/Kconfig ++++ b/init/Kconfig +@@ -223,6 +223,45 @@ config THREAD_INFO_IN_TASK + + menu "General setup" + ++config ZEN_INTERACTIVE ++ bool "Tune kernel for interactivity" ++ default y ++ help ++ Tunes the kernel for responsiveness at the cost of throughput and power usage. ++ ++ --- Block Layer ---------------------------------------- ++ ++ Default scheduler for SQ..: mq-deadline -> bfq ++ Default scheduler for MQ..: none -> kyber ++ ++ --- Virtual Memory Subsystem --------------------------- ++ ++ Background-reclaim hugepages...: no -> yes ++ Compact unevictable............: yes -> no ++ Swap-in readahead..............: 3 -> 0 ++ ++ --- EEVDF CPU Scheduler -------------------------------- ++ ++ Minimal granularity............: 0.7 -> 0.4 ms ++ Migration cost.................: 0.5 -> 0.3 ms ++ Bandwidth slice size...........: 5 -> 3 ms ++ Task rebalancing threshold.....: 32 -> 8 ++ ++ --- PDS/BMQ CPU Scheduler ------------------------------ ++ ++ Scheduling timeslice...........: 4 -> 2 ms ++ PDS sleep credit...............: 0 -> 1 ++ ++ --- CPUFreq Settings ----------------------------------- ++ ++ Ondemand sampling down factor..: 1 -> 5 ++ Ondemand default up threshold..: 80 -> 55 ++ Ondemand micro up threshold....: 95 -> 60 ++ ++ --- Split/Bus lock detection -------------------------- ++ ++ Split lock mitigation..........: 1 -> 0 ++ + config BROKEN + bool + help +@@ -947,10 +986,59 @@ config SCHED_PROXY_EXEC + depends on !SCHED_CLASS_EXT + # Not particularly useful until we get to multi-rq proxying + depends on EXPERT ++ depends on !SCHED_ALT + help + This option enables proxy execution, a mechanism for mutex-owning + tasks to inherit the scheduling context of higher priority waiters. + ++menuconfig SCHED_ALT ++ bool "Alternative CPU Schedulers" ++ default n ++ help ++ This feature enables the ProjectC alternative CPU schedulers. ++ ++if SCHED_ALT ++ ++choice ++ prompt "Alternative CPU schedulers" ++ default SCHED_PDS ++ ++config SCHED_BMQ ++ bool "BMQ CPU scheduler" ++ help ++ The BitMap Queue CPU scheduler for excellent interactivity and ++ responsiveness on the desktop and solid scalability on normal ++ hardware and commodity servers. ++ ++config SCHED_PDS ++ bool "PDS CPU scheduler" ++ help ++ The Priority and Deadline based Skip list multiple queue CPU ++ Scheduler. ++ ++endchoice ++ ++config SCHED_PDS_SLEEP_CREDIT ++ bool "PDS sleep credit on by default" ++ depends on SCHED_PDS ++ default y if ZEN_INTERACTIVE ++ help ++ Move a task that slept ahead of CPU-bound tasks of the same nice ++ level when it wakes up. This favours interactivity over fairness. ++ sched_pds_sleep_credit= on the command line overrides it. ++ ++config SCHED_ALT_TOPOLOGY_KUNIT_TEST ++ bool "KUnit tests for alternative scheduler CPU topology" if !KUNIT_ALL_TESTS ++ depends on KUNIT=y && SCHED_SMT ++ default KUNIT_ALL_TESTS ++ help ++ Test the policy which selects generic, homogeneous SMT, or ++ heterogeneous P/E scheduling from detected CPU topology. ++ The tests cover incomplete classification and the rule that ++ detected E-core SMT disables P/E-aware scheduling. ++ ++endif ++ + endmenu + + # +@@ -1029,6 +1117,7 @@ config NUMA_BALANCING + depends on ARCH_HAS_PTE_PROTNONE + depends on !ARCH_WANT_NUMA_VARIABLE_LOCALITY + depends on SMP && NUMA_MIGRATION && !PREEMPT_RT ++ depends on !SCHED_ALT + help + This option adds support for automatic NUMA aware memory/task placement. + The mechanism is quite primitive and is based on migrating memory when +@@ -1040,6 +1129,7 @@ config SCHED_CACHE + bool "Cache aware load balance" + default y + depends on SMP ++ depends on !SCHED_ALT + help + When enabled, the scheduler will attempt to aggregate tasks from + the same process onto a single Last Level Cache (LLC) domain when +@@ -1326,7 +1416,7 @@ config CPUSETS + + config CPUSETS_V1 + bool "Legacy cgroup v1 cpusets controller" +- depends on CPUSETS ++ depends on (CPUSETS && !SCHED_ALT) + default n + help + Legacy cgroup v1 cpusets controller which has been deprecated by +@@ -1462,6 +1552,22 @@ config USER_NS + + If unsure, say N. + ++config USER_NS_UNPRIVILEGED ++ bool "Allow unprivileged users to create namespaces" ++ default y ++ depends on USER_NS ++ help ++ When disabled, unprivileged users will not be able to create ++ new namespaces. Allowing users to create their own namespaces ++ has been part of several recent local privilege escalation ++ exploits, so if you need user namespaces but are ++ paranoid^Wsecurity-conscious you want to disable this. ++ ++ This setting can be overridden at runtime via the ++ kernel.unprivileged_userns_clone sysctl. ++ ++ If unsure, say Y. ++ + config PID_NS + bool "PID Namespaces" + default y +@@ -1496,6 +1602,7 @@ config CHECKPOINT_RESTORE + + config SCHED_AUTOGROUP + bool "Automatic process group scheduling" ++ depends on !SCHED_ALT + select CGROUPS + select CGROUP_SCHED + select FAIR_GROUP_SCHED +@@ -1666,6 +1773,12 @@ config CC_OPTIMIZE_FOR_PERFORMANCE + with the "-O2" compiler flag for best performance and most + helpful compile-time warnings. + ++config CC_OPTIMIZE_FOR_PERFORMANCE_O3 ++ bool "Optimize more for performance (-O3)" ++ help ++ Choosing this option will pass "-O3" to your compiler to optimize ++ the kernel yet more for performance. ++ + config CC_OPTIMIZE_FOR_SIZE + bool "Optimize for size (-Os)" + help +diff --git a/init/Makefile b/init/Makefile +index d6f75d8..b3d6a2b 100644 +--- a/init/Makefile ++++ b/init/Makefile +@@ -34,7 +34,7 @@ build-timestamp = $(or $(KBUILD_BUILD_TIMESTAMP), $(build-timestamp-auto)) + + # Maximum length of UTS_VERSION is 64 chars + filechk_uts_version = \ +- utsver=$$(echo '$(pound)'"$(build-version)" $(smp-flag-y) $(preempt-flag-y) "$(build-timestamp)" | cut -b -64); \ ++ utsver=$$(echo '$(pound)'"$(build-version)" ZEN $(smp-flag-y) $(preempt-flag-y) "$(build-timestamp)" | cut -b -64); \ + echo '$(pound)'define UTS_VERSION \""$${utsver}"\" + + # +diff --git a/init/init_task.c b/init/init_task.c +index adb207c..b136c5d 100644 +--- a/init/init_task.c ++++ b/init/init_task.c +@@ -111,9 +111,16 @@ struct task_struct init_task __aligned(L1_CACHE_BYTES) = { + .stack = init_stack, + .usage = REFCOUNT_INIT(2), + .flags = PF_KTHREAD, ++#ifdef CONFIG_SCHED_ALT ++ .on_cpu = 1, ++ .prio = DEFAULT_PRIO, ++ .static_prio = DEFAULT_PRIO, ++ .normal_prio = DEFAULT_PRIO, ++#else + .prio = MAX_PRIO - 20, + .static_prio = MAX_PRIO - 20, + .normal_prio = MAX_PRIO - 20, ++#endif + .policy = SCHED_NORMAL, + .cpus_ptr = &init_task.cpus_mask, + .user_cpus_ptr = NULL, +@@ -126,6 +133,16 @@ struct task_struct init_task __aligned(L1_CACHE_BYTES) = { + .restart_block = { + .fn = do_no_restart_syscall, + }, ++#ifdef CONFIG_SCHED_ALT ++ .sq_node = LIST_HEAD_INIT(init_task.sq_node), ++#ifdef CONFIG_SCHED_BMQ ++ .boost_prio = 0, ++#endif ++#ifdef CONFIG_SCHED_PDS ++ .deadline = 0, ++#endif ++ .time_slice = HZ, ++#else + .se = { + .group_node = LIST_HEAD_INIT(init_task.se.group_node), + }, +@@ -133,10 +150,13 @@ struct task_struct init_task __aligned(L1_CACHE_BYTES) = { + .run_list = LIST_HEAD_INIT(init_task.rt.run_list), + .time_slice = RR_TIMESLICE, + }, ++#endif + .tasks = LIST_HEAD_INIT(init_task.tasks), ++#ifndef CONFIG_SCHED_ALT + #ifdef CONFIG_SMP + .pushable_tasks = PLIST_NODE_INIT(init_task.pushable_tasks, MAX_PRIO), + #endif ++#endif + #ifdef CONFIG_CGROUP_SCHED + .sched_task_group = &root_task_group, + #endif +diff --git a/kernel/Kconfig.preempt b/kernel/Kconfig.preempt +index f294dad..1707b33 100644 +--- a/kernel/Kconfig.preempt ++++ b/kernel/Kconfig.preempt +@@ -91,7 +91,7 @@ endchoice + + config PREEMPT_RT + bool "Fully Preemptible Kernel (Real-Time)" +- depends on EXPERT && ARCH_SUPPORTS_RT && !COMPILE_TEST ++ depends on ARCH_SUPPORTS_RT && !COMPILE_TEST + select PREEMPTION + help + This option turns the kernel into a real-time kernel by replacing +@@ -154,7 +154,7 @@ config PREEMPT_DYNAMIC + + config SCHED_CORE + bool "Core Scheduling for SMT" +- depends on SCHED_SMT ++ depends on SCHED_SMT && !SCHED_ALT + help + This option permits Core Scheduling, a means of coordinated task + selection across SMT siblings. When enabled -- see +@@ -172,7 +172,7 @@ config SCHED_CORE + + config SCHED_CLASS_EXT + bool "Extensible Scheduling Class" +- depends on BPF_SYSCALL && BPF_JIT && DEBUG_INFO_BTF ++ depends on BPF_SYSCALL && BPF_JIT && DEBUG_INFO_BTF && !SCHED_ALT + select GENERIC_ALLOCATOR + select STACKTRACE if STACKTRACE_SUPPORT + help +diff --git a/kernel/bounds.c b/kernel/bounds.c +index 02b619e..06a0347 100644 +--- a/kernel/bounds.c ++++ b/kernel/bounds.c +@@ -25,7 +25,7 @@ int main(void) + DEFINE(SPINLOCK_SIZE, sizeof(spinlock_t)); + #ifdef CONFIG_LRU_GEN + DEFINE(LRU_GEN_WIDTH, order_base_2(MAX_NR_GENS + 1)); +- DEFINE(__LRU_REFS_WIDTH, MAX_NR_TIERS - 2); ++ DEFINE(__LRU_REFS_WIDTH, MAX_NR_TIERS - 3); + #else + DEFINE(LRU_GEN_WIDTH, 0); + DEFINE(__LRU_REFS_WIDTH, 0); +diff --git a/kernel/cgroup/cpuset.c b/kernel/cgroup/cpuset.c +index 86b5921..6f52bec 100644 +--- a/kernel/cgroup/cpuset.c ++++ b/kernel/cgroup/cpuset.c +@@ -827,7 +827,7 @@ static int validate_change(struct cpuset *cur, struct cpuset *trial) + return ret; + } + +-#ifdef CONFIG_SMP ++#if defined(CONFIG_SMP) && !defined(CONFIG_SCHED_ALT) + + /* + * generate_sched_domains() +@@ -1074,7 +1074,7 @@ void rebuild_sched_domains_locked(void) + /* Have scheduler rebuild the domains */ + partition_sched_domains(ndoms, doms, attr); + } +-#else /* !CONFIG_SMP */ ++#else /* !CONFIG_SMP || CONFIG_SCHED_ALT */ + void rebuild_sched_domains_locked(void) + { + } +@@ -3127,6 +3127,7 @@ static int cpuset_can_attach_check(struct cpuset *cs, struct cpuset *oldcs, + return 0; + } + ++#ifndef CONFIG_SCHED_ALT + static int cpuset_reserve_dl_bw(void) + { + struct cpuset *cs; +@@ -3148,6 +3149,7 @@ static int cpuset_reserve_dl_bw(void) + } + return 0; + } ++#endif /* !CONFIG_SCHED_ALT */ + + /* + * Clear and optionally apply (@cancel is false) the attach related data in the +@@ -3160,6 +3162,7 @@ static void clear_attach_data(struct llist_head *head, bool cancel) + + llist_for_each_entry_safe(cs, next, lnode, attach_node) { + init_llist_node(&cs->attach_node); ++#ifndef CONFIG_SCHED_ALT + if (cs->nr_migrate_dl_tasks) { + if (!cancel) + atomic_add(cs->nr_migrate_dl_tasks, &cs->nr_deadline_tasks); +@@ -3169,6 +3172,7 @@ static void clear_attach_data(struct llist_head *head, bool cancel) + cs->sum_migrate_dl_bw = 0; + cs->dl_bw_cpu = -1; + } ++#endif /* !CONFIG_SCHED_ALT */ + } + } + +@@ -3245,6 +3249,7 @@ static int cpuset_can_attach(struct cgroup_taskset *tset) + goto out_unlock; + } + ++#ifndef CONFIG_SCHED_ALT + if (dl_task(task)) { + /* + * Count all migrating DL tasks for cpuset task accounting. +@@ -3256,6 +3261,7 @@ static int cpuset_can_attach(struct cgroup_taskset *tset) + if (dl_task_needs_bw_move(task, cs->effective_cpus)) + cs->sum_migrate_dl_bw += task->dl.dl_bw; + } ++#endif /* !CONFIG_SCHED_ALT */ + } + + /* +@@ -3274,7 +3280,11 @@ static int cpuset_can_attach(struct cgroup_taskset *tset) + goto out_unlock; + } + ++#ifndef CONFIG_SCHED_ALT + ret = cpuset_reserve_dl_bw(); ++#else /* !CONFIG_SCHED_ALT */ ++ ret = 0; ++#endif /* CONFIG_SCHED_ALT */ + + out_unlock: + if (ret) { +@@ -3294,7 +3304,6 @@ static void cpuset_cancel_attach(struct cgroup_taskset *tset) + dec_attach_in_progress_locked(); + clear_attach_data(&src_cs_head, true); + clear_attach_data(&dst_cs_head, true); +- mutex_unlock(&cpuset_mutex); + } + + /* +diff --git a/kernel/delayacct.c b/kernel/delayacct.c +index 479e860..61440f7 100644 +--- a/kernel/delayacct.c ++++ b/kernel/delayacct.c +@@ -170,7 +170,7 @@ int delayacct_add_tsk(struct taskstats *d, struct task_struct *tsk) + */ + t1 = tsk->sched_info.pcount; + t2 = tsk->sched_info.run_delay; +- t3 = tsk->se.sum_exec_runtime; ++ t3 = tsk_seruntime(tsk); + + d->cpu_count += t1; + +diff --git a/kernel/exit.c b/kernel/exit.c +index 25a68e1..263b422 100644 +--- a/kernel/exit.c ++++ b/kernel/exit.c +@@ -206,7 +206,7 @@ static void __exit_signal(struct release_task_post *post, struct task_struct *ts + sig->inblock += task_io_get_inblock(tsk); + sig->oublock += task_io_get_oublock(tsk); + task_io_accounting_add(&sig->ioac, &tsk->ioac); +- sig->sum_sched_runtime += tsk->se.sum_exec_runtime; ++ sig->sum_sched_runtime += tsk_seruntime(tsk); + sig->nr_threads--; + __unhash_process(post, tsk, group_dead); + write_sequnlock(&sig->stats_lock); +@@ -297,8 +297,8 @@ void release_task(struct task_struct *p) + proc_flush_pid(thread_pid); + put_pid(thread_pid); + exit_cred_namespaces(p); +- add_device_randomness(&p->se.sum_exec_runtime, +- sizeof(p->se.sum_exec_runtime)); ++ add_device_randomness((const void*) &tsk_seruntime(p), ++ sizeof(unsigned long long)); + free_pids(post.pids); + release_thread(p); + /* +diff --git a/kernel/fork.c b/kernel/fork.c +index 48d7ca0..9566b99 100644 +--- a/kernel/fork.c ++++ b/kernel/fork.c +@@ -127,6 +127,16 @@ + + #include + ++#ifdef CONFIG_USER_NS ++# ifdef CONFIG_USER_NS_UNPRIVILEGED ++static int unprivileged_userns_clone = 1; ++# else ++static int unprivileged_userns_clone = 0; ++# endif ++#else ++#define unprivileged_userns_clone 1 ++#endif ++ + /* + * Minimum number of threads to boot the kernel + */ +@@ -2130,6 +2140,11 @@ __latent_entropy struct task_struct *copy_process( + return ERR_PTR(-EPERM); + } + ++ if ((clone_flags & CLONE_NEWUSER) && !unprivileged_userns_clone) { ++ if (!capable(CAP_SYS_ADMIN)) ++ return ERR_PTR(-EPERM); ++ } ++ + /* + * Force any signals received before this point to be delivered + * before the fork happens. Collect up signals sent to multiple +@@ -3213,6 +3228,10 @@ static int check_unshare_flags(unsigned long unshare_flags) + if (!current_is_single_threaded()) + return -EINVAL; + } ++ if ((unshare_flags & CLONE_NEWUSER) && !unprivileged_userns_clone) { ++ if (!capable(CAP_SYS_ADMIN)) ++ return -EPERM; ++ } + + return 0; + } +@@ -3446,6 +3465,15 @@ static const struct ctl_table fork_sysctl_table[] = { + .mode = 0644, + .proc_handler = sysctl_max_threads, + }, ++#ifdef CONFIG_USER_NS ++ { ++ .procname = "unprivileged_userns_clone", ++ .data = &unprivileged_userns_clone, ++ .maxlen = sizeof(int), ++ .mode = 0644, ++ .proc_handler = proc_dointvec, ++ }, ++#endif + }; + + static int __init init_fork_sysctl(void) +diff --git a/kernel/irq/Kconfig b/kernel/irq/Kconfig +index 6923f37..d15390a 100644 +--- a/kernel/irq/Kconfig ++++ b/kernel/irq/Kconfig +@@ -106,6 +106,23 @@ config GENERIC_IRQ_STAT_SNAPSHOT + config IRQ_FORCED_THREADING + bool + ++config FORCE_IRQ_THREADING ++ bool "Make IRQ threading compulsory" ++ depends on IRQ_FORCED_THREADING ++ default n ++ help ++ ++ Make IRQ threading mandatory for any IRQ handlers that support it ++ instead of being optional and requiring the threadirqs kernel ++ parameter. Instead they can be optionally disabled with the ++ nothreadirqs kernel parameter. ++ ++ Enabling this may expose bugs in some drivers and prevent some ++ systems from booting. ++ ++ Enable if you are building for a desktop or low latency system, ++ otherwise say N. ++ + config SPARSE_IRQ + bool "Support sparse irq numbering" if MAY_HAVE_SPARSE_IRQ + help +diff --git a/kernel/irq/manage.c b/kernel/irq/manage.c +index ec3ecb0..f6df1e8 100644 +--- a/kernel/irq/manage.c ++++ b/kernel/irq/manage.c +@@ -26,7 +26,18 @@ + #include "internals.h" + + #if defined(CONFIG_IRQ_FORCED_THREADING) && !defined(CONFIG_PREEMPT_RT) ++#ifdef CONFIG_FORCE_IRQ_THREADING ++DEFINE_STATIC_KEY_TRUE(force_irqthreads_key); ++#else + DEFINE_STATIC_KEY_FALSE(force_irqthreads_key); ++#endif ++ ++static int __init setup_noforced_irqthreads(char *arg) ++{ ++ static_branch_disable(&force_irqthreads_key); ++ return 0; ++} ++early_param("nothreadirqs", setup_noforced_irqthreads); + + static int __init setup_forced_irqthreads(char *arg) + { +diff --git a/kernel/locking/rtmutex.c b/kernel/locking/rtmutex.c +index 4728631..15772f6 100644 +--- a/kernel/locking/rtmutex.c ++++ b/kernel/locking/rtmutex.c +@@ -372,7 +372,7 @@ waiter_update_prio(struct rt_mutex_waiter *waiter, struct task_struct *task) + lockdep_assert(RB_EMPTY_NODE(&waiter->tree.entry)); + + waiter->tree.prio = __waiter_prio(task); +- waiter->tree.deadline = task->dl.deadline; ++ waiter->tree.deadline = __tsk_deadline(task); + } + + /* +@@ -393,16 +393,20 @@ waiter_clone_prio(struct rt_mutex_waiter *waiter, struct task_struct *task) + * Only use with rt_waiter_node_{less,equal}() + */ + #define task_to_waiter_node(p) \ +- &(struct rt_waiter_node){ .prio = __waiter_prio(p), .deadline = (p)->dl.deadline } ++ &(struct rt_waiter_node){ .prio = __waiter_prio(p), .deadline = __tsk_deadline(p) } + #define task_to_waiter(p) \ + &(struct rt_mutex_waiter){ .tree = *task_to_waiter_node(p) } + + static __always_inline int rt_waiter_node_less(struct rt_waiter_node *left, + struct rt_waiter_node *right) + { ++#ifdef CONFIG_SCHED_PDS ++ return (left->deadline < right->deadline); ++#else + if (left->prio < right->prio) + return 1; + ++#ifndef CONFIG_SCHED_BMQ + /* + * If both waiters have dl_prio(), we check the deadlines of the + * associated tasks. +@@ -411,16 +415,22 @@ static __always_inline int rt_waiter_node_less(struct rt_waiter_node *left, + */ + if (dl_prio(left->prio)) + return dl_time_before(left->deadline, right->deadline); ++#endif + + return 0; ++#endif + } + + static __always_inline int rt_waiter_node_equal(struct rt_waiter_node *left, + struct rt_waiter_node *right) + { ++#ifdef CONFIG_SCHED_PDS ++ return (left->deadline == right->deadline); ++#else + if (left->prio != right->prio) + return 0; + ++#ifndef CONFIG_SCHED_BMQ + /* + * If both waiters have dl_prio(), we check the deadlines of the + * associated tasks. +@@ -429,8 +439,10 @@ static __always_inline int rt_waiter_node_equal(struct rt_waiter_node *left, + */ + if (dl_prio(left->prio)) + return left->deadline == right->deadline; ++#endif + + return 1; ++#endif + } + + static inline bool rt_mutex_steal(struct rt_mutex_waiter *waiter, +diff --git a/kernel/locking/ww_mutex.h b/kernel/locking/ww_mutex.h +index d62b49b..a487885 100644 +--- a/kernel/locking/ww_mutex.h ++++ b/kernel/locking/ww_mutex.h +@@ -282,6 +282,7 @@ __ww_ctx_less(struct ww_acquire_ctx *a, struct ww_acquire_ctx *b) + + /* equal static prio */ + ++#ifndef CONFIG_SCHED_ALT + if (dl_prio(a_prio)) { + if (dl_time_before(b->task->dl.deadline, + a->task->dl.deadline)) +@@ -291,6 +292,7 @@ __ww_ctx_less(struct ww_acquire_ctx *a, struct ww_acquire_ctx *b) + b->task->dl.deadline)) + return false; + } ++#endif + + /* equal prio */ + } +diff --git a/kernel/sched/Makefile b/kernel/sched/Makefile +index b1f1a36..0c1f4f0 100644 +--- a/kernel/sched/Makefile ++++ b/kernel/sched/Makefile +@@ -2,6 +2,7 @@ + + CONTEXT_ANALYSIS_core.o := y + CONTEXT_ANALYSIS_fair.o := y ++CONTEXT_ANALYSIS_alt_core.o := y + + # The compilers are complaining about unused variables inside an if(0) scope + # block. This is daft, shut them up. +@@ -36,7 +37,12 @@ endif + # These compilation units have roughly the same size and complexity - so their + # build parallelizes well and finishes roughly at once: + # ++ifdef CONFIG_SCHED_ALT ++obj-y += alt_core.o ++obj-$(CONFIG_SCHED_DEBUG) += alt_debug.o ++else + obj-y += core.o + obj-y += fair.o ++endif + obj-y += build_policy.o + obj-y += build_utility.o +diff --git a/kernel/sched/alt_core.c b/kernel/sched/alt_core.c +new file mode 100644 +index 0000000..97e4246 +--- /dev/null ++++ b/kernel/sched/alt_core.c +@@ -0,0 +1,8280 @@ ++/* ++ * kernel/sched/alt_core.c ++ * ++ * Core alternative kernel scheduler code and related syscalls ++ * ++ * Copyright (C) 1991-2002 Linus Torvalds ++ * ++ * 2009-08-13 Brainfuck deadline scheduling policy by Con Kolivas deletes ++ * a whole lot of those previous things. ++ * 2017-09-06 Priority and Deadline based Skip list multiple queue kernel ++ * scheduler by Alfred Chen. ++ * 2019-02-20 BMQ(BitMap Queue) kernel scheduler by Alfred Chen. ++ */ ++#define INSTANTIATE_EXPORTED_MIGRATE_DISABLE ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#ifdef CONFIG_PREEMPT_DYNAMIC ++# ifdef CONFIG_GENERIC_IRQ_ENTRY ++# include ++# endif ++#endif ++ ++#include ++ ++#include ++#include ++ ++#define CREATE_TRACE_POINTS ++#include ++#include ++#undef CREATE_TRACE_POINTS ++ ++#include "sched.h" ++#include "smp.h" ++ ++#include "pelt.h" ++ ++#include "../../io_uring/io-wq.h" ++#include "../smpboot.h" ++ ++/* Use CONFIG_PARAVIRT as this will avoid more #ifdef in arch code. */ ++#ifdef CONFIG_PARAVIRT ++struct static_key paravirt_steal_rq_enabled; ++#endif ++ ++EXPORT_TRACEPOINT_SYMBOL_GPL(ipi_send_cpu); ++EXPORT_TRACEPOINT_SYMBOL_GPL(ipi_send_cpumask); ++ ++/* ++ * Export tracepoints that act as a bare tracehook (ie: have no trace event ++ * associated with them) to allow external modules to probe them. ++ */ ++EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_irq_tp); ++EXPORT_TRACEPOINT_SYMBOL_GPL(sched_entry_tp); ++EXPORT_TRACEPOINT_SYMBOL_GPL(sched_exit_tp); ++EXPORT_TRACEPOINT_SYMBOL_GPL(sched_set_need_resched_tp); ++ ++#define sched_feat(x) (0) ++/* ++ * Print a warning if need_resched is set for the given duration (if ++ * LATENCY_WARN is enabled). ++ * ++ * If sysctl_resched_latency_warn_once is set, only one warning will be shown ++ * per boot. ++ */ ++__read_mostly int sysctl_resched_latency_warn_ms = 100; ++__read_mostly int sysctl_resched_latency_warn_once = 1; ++ ++#define ALT_SCHED_VERSION "v7.3-r0" ++ ++#define STOP_PRIO (MAX_RT_PRIO - 1) ++ ++/* ++ * Time slice ++ * (default: 4 msec, units: nanoseconds) ++ */ ++#ifdef CONFIG_ZEN_INTERACTIVE ++unsigned int sysctl_sched_base_slice __read_mostly = (2 << 20); ++#else ++unsigned int sysctl_sched_base_slice __read_mostly = (4 << 20); ++#endif ++ ++#include "alt_core.h" ++#include "alt_topology.h" ++ ++/** ++ * sched_yield_type - Type of sched_yield() will be performed. ++ * 0: No yield. ++ * 1: Requeue task. (default) ++ */ ++int sched_yield_type __read_mostly = 1; ++ ++DEFINE_STATIC_KEY_MAYBE_RO(CONFIG_SCHED_PDS_SLEEP_CREDIT, sched_pds_sleep_credit); ++ ++static int __init setup_sched_pds_sleep_credit(char *str) ++{ ++ bool on; ++ ++ if (kstrtobool(str, &on)) ++ pr_warn("Unable to parse sched_pds_sleep_credit=\n"); ++ else if (on) ++ static_branch_enable(&sched_pds_sleep_credit); ++ else ++ static_branch_disable(&sched_pds_sleep_credit); ++ ++ return 1; ++} ++__setup("sched_pds_sleep_credit=", setup_sched_pds_sleep_credit); ++ ++cpumask_t sched_rq_pending_mask ____cacheline_aligned_in_smp; ++ ++DEFINE_PER_CPU_ALIGNED(cpumask_t [NR_CPU_AFFINITY_LEVELS], sched_cpu_topo_masks); ++DEFINE_PER_CPU_ALIGNED(cpumask_t *, sched_cpu_llc_mask); ++DEFINE_PER_CPU_ALIGNED(cpumask_t *, sched_cpu_topo_end_mask); ++ ++DEFINE_STATIC_KEY_FALSE(sched_smt_present); ++EXPORT_SYMBOL_GPL(sched_smt_present); ++ ++DEFINE_PER_CPU_ALIGNED(raw_spinlock_t, sched_smt_idle_lock); ++ ++cpumask_t sched_smt_mask ____cacheline_aligned_in_smp; ++ ++/* ++ * Keep a unique ID per domain (we use the first CPUs number in the cpumask of ++ * the domain), this allows us to quickly tell if two cpus are in the same cache ++ * domain, see cpus_share_cache(). ++ */ ++static DEFINE_PER_CPU_READ_MOSTLY(int, sd_llc_id); ++static DEFINE_PER_CPU_READ_MOSTLY(int, sd_llc_size); ++static DEFINE_PER_CPU_READ_MOSTLY(bool, sched_cpu_topology_valid); ++static cpumask_t sched_llc_id_merge_mask; ++ ++DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues); ++ ++#ifndef prepare_arch_switch ++# define prepare_arch_switch(next) do { } while (0) ++#endif ++#ifndef finish_arch_post_lock_switch ++# define finish_arch_post_lock_switch() do { } while (0) ++#endif ++ ++static struct { ++ cpumask_t pad; ++ cpumask_t mask[SCHED_QUEUE_BITS + 3]; ++} sched_preempt_masks ____cacheline_aligned_in_smp; ++ ++#define sched_preempt_mask sched_preempt_masks.mask ++ ++static_assert(offsetof(typeof(sched_preempt_masks), ++ mask[SCHED_QUEUE_BITS - 1]) % SMP_CACHE_BYTES == 0); ++ ++cpumask_t *const sched_idle_mask = &sched_preempt_mask[SCHED_QUEUE_BITS - 1]; ++cpumask_t *const sched_sg_idle_mask = &sched_preempt_mask[SCHED_QUEUE_BITS]; ++cpumask_t *const sched_pcore_idle_mask = &sched_preempt_mask[SCHED_QUEUE_BITS + 1]; ++cpumask_t *const sched_ecore_idle_mask = &sched_preempt_mask[SCHED_QUEUE_BITS + 2]; ++ ++/* task function */ ++static inline const struct cpumask *task_user_cpus(struct task_struct *p) ++{ ++ if (!p->user_cpus_ptr) ++ return cpu_possible_mask; /* &init_task.cpus_mask */ ++ return p->user_cpus_ptr; ++} ++ ++/* sched_queue related functions */ ++static inline void sched_queue_init(struct sched_queue *q) ++{ ++ int i; ++ ++ bitmap_zero(q->bitmap, SCHED_QUEUE_BITS); ++ for(i = 0; i < SCHED_LEVELS; i++) ++ INIT_LIST_HEAD(&q->heads[i]); ++} ++ ++/* ++ * Init idle task and put into queue structure of rq ++ * IMPORTANT: may be called multiple times for a single cpu ++ */ ++static inline void sched_queue_init_idle(struct sched_queue *q, ++ struct task_struct *idle) ++{ ++ INIT_LIST_HEAD(&q->heads[IDLE_TASK_SCHED_PRIO]); ++ list_add_tail(&idle->sq_node, &q->heads[IDLE_TASK_SCHED_PRIO]); ++ idle->on_rq = TASK_ON_RQ_QUEUED; ++} ++ ++static atomic_t sched_prio_record = ATOMIC_INIT(0); ++ ++/* water mark related functions */ ++static inline void update_sched_preempt_mask(struct rq *rq) ++{ ++ int prio = find_first_bit(rq->queue.bitmap, SCHED_QUEUE_BITS); ++ int last_prio = rq->prio; ++ ++ if (prio == last_prio) ++ return; ++ ++ sched_rq_set_prio(rq, prio); ++ ++ int cpu = cpu_of(rq); ++ bool set = prio > last_prio; ++ int low = set ? last_prio : prio; ++ int high = set ? prio : last_prio; ++ ++ if (IDLE_TASK_SCHED_PRIO == high) { ++ high -= 1; ++ if (set) ++ sched_set_idle_mask(cpu); ++ else ++ sched_clear_idle_mask(cpu); ++ } ++ int pr = atomic_read(&sched_prio_record); ++ if (low <= pr && pr < high) { ++ if (set) ++ cpumask_set_cpu(cpu, sched_preempt_mask + pr); ++ else ++ cpumask_clear_cpu(cpu, sched_preempt_mask + pr); ++ } ++} ++ ++/* need a wrapper since we may need to trace from modules */ ++EXPORT_TRACEPOINT_SYMBOL(sched_set_state_tp); ++ ++/* ++ * Call via the helper macro trace_set_current_state. ++ * Calls to this function MUST be guarded by a ++ * tracepoint_enabled(sched_set_state_tp) ++ */ ++void __trace_set_current_state(int state_value) ++{ ++ trace_call__sched_set_state_tp(current, state_value); ++} ++EXPORT_SYMBOL(__trace_set_current_state); ++ ++/* ++ * Serialization rules: ++ * ++ * Lock order: ++ * ++ * p->pi_lock ++ * rq->lock ++ * hrtimer_cpu_base->lock (hrtimer_start() for bandwidth controls) ++ * ++ * rq1->lock ++ * rq2->lock where: rq1 < rq2 ++ * ++ * Regular state: ++ * ++ * Normal scheduling state is serialized by rq->lock. __schedule() takes the ++ * local CPU's rq->lock, it optionally removes the task from the runqueue and ++ * always looks at the local rq data structures to find the most eligible task ++ * to run next. ++ * ++ * Task enqueue is also under rq->lock, possibly taken from another CPU. ++ * Wakeups from another LLC domain might use an IPI to transfer the enqueue to ++ * the local CPU to avoid bouncing the runqueue state around [ see ++ * ttwu_queue_wakelist() ] ++ * ++ * Task wakeup, specifically wakeups that involve migration, are horribly ++ * complicated to avoid having to take two rq->locks. ++ * ++ * Special state: ++ * ++ * System-calls and anything external will use task_rq_lock() which acquires ++ * both p->pi_lock and rq->lock. As a consequence the state they change is ++ * stable while holding either lock: ++ * ++ * - sched_setaffinity()/ ++ * set_cpus_allowed_ptr(): p->cpus_ptr, p->nr_cpus_allowed ++ * - set_user_nice(): p->se.load, p->*prio ++ * - __sched_setscheduler(): p->sched_class, p->policy, p->*prio, ++ * p->se.load, p->rt_priority, ++ * p->dl.dl_{runtime, deadline, period, flags, bw, density} ++ * - sched_setnuma(): p->numa_preferred_nid ++ * - sched_move_task(): p->sched_task_group ++ * - uclamp_update_active() p->uclamp* ++ * ++ * p->state <- TASK_*: ++ * ++ * is changed locklessly using set_current_state(), __set_current_state() or ++ * set_special_state(), see their respective comments, or by ++ * try_to_wake_up(). This latter uses p->pi_lock to serialize against ++ * concurrent self. ++ * ++ * p->on_rq <- { 0, 1 = TASK_ON_RQ_QUEUED, 2 = TASK_ON_RQ_MIGRATING }: ++ * ++ * is set by activate_task() and cleared by deactivate_task()/block_task(), ++ * under rq->lock. Non-zero indicates the task is runnable, the special ++ * ON_RQ_MIGRATING state is used for migration without holding both ++ * rq->locks. It indicates task_cpu() is not stable, see task_rq_lock(). ++ * ++ * Additionally it is possible to be ->on_rq but still be considered not ++ * runnable when p->se.sched_delayed is true. These tasks are on the runqueue ++ * but will be dequeued as soon as they get picked again. See the ++ * task_is_runnable() helper. ++ * ++ * p->on_cpu <- { 0, 1 }: ++ * ++ * is set by prepare_task() and cleared by finish_task() such that it will be ++ * set before p is scheduled-in and cleared after p is scheduled-out, both ++ * under rq->lock. Non-zero indicates the task is running on its CPU. ++ * ++ * [ The astute reader will observe that it is possible for two tasks on one ++ * CPU to have ->on_cpu = 1 at the same time. ] ++ * ++ * p->is_blocked <- { 0, 1 }: ++ * ++ * is set by try_to_block_task() and cleared by ttwu_do_wakeup() and tracks ++ * if the task is blocked. Traditionally this would mirror p->on_rq, however ++ * due things like DELAY_DEQUEUE and PROXY_EXEC, this can diverge. ++ * ++ * task_cpu(p): is changed by set_task_cpu(), the rules are: ++ * ++ * - Don't call set_task_cpu() on a blocked task: ++ * ++ * We don't care what CPU we're not running on, this simplifies hotplug, ++ * the CPU assignment of blocked tasks isn't required to be valid. ++ * ++ * - for try_to_wake_up(), called under p->pi_lock: ++ * ++ * This allows try_to_wake_up() to only take one rq->lock, see its comment. ++ * ++ * - for migration called under rq->lock: ++ * [ see task_on_rq_migrating() in task_rq_lock() ] ++ * ++ * o move_queued_task() ++ * o detach_task() ++ * ++ * - for migration called under double_rq_lock(): ++ * ++ * o __migrate_swap_task() ++ * o push_rt_task() / pull_rt_task() ++ * o push_dl_task() / pull_dl_task() ++ * o dl_task_offline_migration() ++ * ++ */ ++ ++/* ++ * __task_rq_lock - lock the rq @p resides on. ++ */ ++struct rq *___task_rq_lock(struct task_struct *p, struct rq_flags *rf) ++{ ++ struct rq *rq; ++ ++ lockdep_assert_held(&p->pi_lock); ++ ++ for (;;) { ++ rq = task_rq(p); ++ raw_spin_rq_lock(rq); ++ if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) { ++ rq_pin_lock(rq, rf); ++ return rq; ++ } ++ raw_spin_rq_unlock(rq); ++ ++ while (unlikely(task_on_rq_migrating(p))) ++ cpu_relax(); ++ } ++} ++ ++/* ++ * task_rq_lock - lock p->pi_lock and lock the rq @p resides on. ++ */ ++struct rq *_task_rq_lock(struct task_struct *p, struct rq_flags *rf) ++{ ++ struct rq *rq; ++ ++ for (;;) { ++ raw_spin_lock_irqsave(&p->pi_lock, rf->flags); ++ rq = task_rq(p); ++ raw_spin_rq_lock(rq); ++ /* ++ * move_queued_task() task_rq_lock() ++ * ++ * ACQUIRE (rq->lock) ++ * [S] ->on_rq = MIGRATING [L] rq = task_rq() ++ * WMB (__set_task_cpu()) ACQUIRE (rq->lock); ++ * [S] ->cpu = new_cpu [L] task_rq() ++ * [L] ->on_rq ++ * RELEASE (rq->lock) ++ * ++ * If we observe the old CPU in task_rq_lock(), the acquire of ++ * the old rq->lock will fully serialize against the stores. ++ * ++ * If we observe the new CPU in task_rq_lock(), the address ++ * dependency headed by '[L] rq = task_rq()' and the acquire ++ * will pair with the WMB to ensure we then also see migrating. ++ */ ++ if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) { ++ rq_pin_lock(rq, rf); ++ return rq; ++ } ++ raw_spin_rq_unlock(rq); ++ raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags); ++ ++ while (unlikely(task_on_rq_migrating(p))) ++ cpu_relax(); ++ } ++} ++ ++void raw_spin_rq_lock_nested(struct rq *rq, int subclass) ++{ ++ /* Matches synchronize_rcu() in __sched_core_enable() */ ++ preempt_disable(); ++ raw_spin_lock_nested(rq_lockp(rq), subclass); ++ /* preempt_count *MUST* be > 1 */ ++ preempt_enable_no_resched(); ++} ++ ++bool raw_spin_rq_trylock(struct rq *rq) ++{ ++ return raw_spin_trylock(rq_lockp(rq)); ++} ++ ++/* ++ * RQ-clock updating methods: ++ */ ++ ++static void update_rq_clock_task(struct rq *rq, s64 delta) ++{ ++/* ++ * In theory, the compile should just see 0 here, and optimize out the call ++ * to sched_rt_avg_update. But I don't trust it... ++ */ ++ s64 __maybe_unused steal = 0, irq_delta = 0; ++ ++#ifdef CONFIG_IRQ_TIME_ACCOUNTING ++ if (irqtime_enabled()) { ++ irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time; ++ ++ /* ++ * Since irq_time is only updated on {soft,}irq_exit, we might run into ++ * this case when a previous update_rq_clock() happened inside a ++ * {soft,}IRQ region. ++ * ++ * When this happens, we stop ->clock_task and only update the ++ * prev_irq_time stamp to account for the part that fit, so that a next ++ * update will consume the rest. This ensures ->clock_task is ++ * monotonic. ++ * ++ * It does however cause some slight miss-attribution of {soft,}IRQ ++ * time, a more accurate solution would be to update the irq_time using ++ * the current rq->clock timestamp, except that would require using ++ * atomic ops. ++ */ ++ if (irq_delta > delta) ++ irq_delta = delta; ++ ++ rq->prev_irq_time += irq_delta; ++ delta -= irq_delta; ++ delayacct_irq(rq->curr, irq_delta); ++ } ++#endif ++#ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING ++ if (static_key_false((¶virt_steal_rq_enabled))) { ++ u64 prev_steal; ++ ++ steal = prev_steal = paravirt_steal_clock(cpu_of(rq)); ++ steal -= rq->prev_steal_time_rq; ++ ++ if (unlikely(steal > delta)) ++ steal = delta; ++ ++ rq->prev_steal_time_rq = prev_steal; ++ delta -= steal; ++ } ++#endif ++ ++ rq->clock_task += delta; ++ ++#ifdef CONFIG_HAVE_SCHED_AVG_IRQ ++ if ((irq_delta + steal)) ++ update_irq_load_avg(rq, irq_delta + steal); ++#endif ++} ++ ++__always_inline void update_rq_clock(struct rq *rq) ++{ ++ s64 delta; ++ ++ lockdep_assert_rq_held(rq); ++ ++ delta = sched_clock_cpu(cpu_of(rq)) - rq->clock; ++ if (unlikely(delta <= 0)) ++ return; ++ rq->clock += delta; ++ sched_update_rq_clock(rq); ++ update_rq_clock_task(rq, delta); ++} ++ ++/* ++ * RQ Load update routine ++ */ ++#define RQ_LOAD_HISTORY_BITS (sizeof(s32) * 8ULL) ++#define RQ_UTIL_SHIFT (8) ++#define RQ_LOAD_HISTORY_TO_UTIL(l) (((l) >> (RQ_LOAD_HISTORY_BITS - 1 - RQ_UTIL_SHIFT)) & 0xff) ++ ++#define LOAD_BLOCK(t) ((t) >> 17) ++#define LOAD_HALF_BLOCK(t) ((t) >> 16) ++#define BLOCK_MASK(t) ((t) & ((0x01 << 18) - 1)) ++#define LOAD_BLOCK_BIT(b) (1UL << (RQ_LOAD_HISTORY_BITS - 1 - (b))) ++#define CURRENT_LOAD_BIT LOAD_BLOCK_BIT(0) ++ ++static inline void rq_load_update(struct rq *rq) ++{ ++ u64 time = rq->clock; ++ u64 delta = min(LOAD_BLOCK(time) - LOAD_BLOCK(rq->load_stamp), RQ_LOAD_HISTORY_BITS - 1); ++ u64 prev = !!(rq->load_history & CURRENT_LOAD_BIT); ++ u64 curr = !!rq->nr_running; ++ ++ if (delta) { ++ rq->load_history = rq->load_history >> delta; ++ ++ if (delta < RQ_UTIL_SHIFT) { ++ rq->load_block += (~BLOCK_MASK(rq->load_stamp)) * prev; ++ if (!!LOAD_HALF_BLOCK(rq->load_block) ^ curr) ++ rq->load_history ^= LOAD_BLOCK_BIT(delta); ++ } ++ ++ rq->load_block = BLOCK_MASK(time) * prev; ++ } else { ++ rq->load_block += (time - rq->load_stamp) * prev; ++ } ++ if (prev ^ curr) ++ rq->load_history ^= CURRENT_LOAD_BIT; ++ rq->load_stamp = time; ++} ++ ++unsigned long rq_load_util(struct rq *rq, unsigned long max) ++{ ++ return RQ_LOAD_HISTORY_TO_UTIL(rq->load_history) * (max >> RQ_UTIL_SHIFT); ++} ++ ++unsigned long sched_cpu_util(int cpu) ++{ ++ return rq_load_util(cpu_rq(cpu), arch_scale_cpu_capacity(cpu)); ++} ++ ++#ifdef CONFIG_CPU_FREQ ++/** ++ * cpufreq_update_util - Take a note about CPU utilization changes. ++ * @rq: Runqueue to carry out the update for. ++ * @flags: Update reason flags. ++ * ++ * This function is called by the scheduler on the CPU whose utilization is ++ * being updated. ++ * ++ * It can only be called from RCU-sched read-side critical sections. ++ * ++ * The way cpufreq is currently arranged requires it to evaluate the CPU ++ * performance state (frequency/voltage) on a regular basis to prevent it from ++ * being stuck in a completely inadequate performance level for too long. ++ * That is not guaranteed to happen if the updates are only triggered from CFS ++ * and DL, though, because they may not be coming in if only RT tasks are ++ * active all the time (or there are RT tasks only). ++ * ++ * As a workaround for that issue, this function is called periodically by the ++ * RT sched class to trigger extra cpufreq updates to prevent it from stalling, ++ * but that really is a band-aid. Going forward it should be replaced with ++ * solutions targeted more specifically at RT tasks. ++ */ ++static inline void cpufreq_update_util(struct rq *rq, unsigned int flags) ++{ ++ struct update_util_data *data; ++ ++ rq_load_update(rq); ++ data = rcu_dereference_sched(*per_cpu_ptr(&cpufreq_update_util_data, cpu_of(rq))); ++ if (data) ++ data->func(data, rq_clock(rq), flags); ++} ++#else /* !CONFIG_CPU_FREQ: */ ++static inline void cpufreq_update_util(struct rq *rq, unsigned int flags) ++{ ++ rq_load_update(rq); ++} ++#endif /* !CONFIG_CPU_FREQ */ ++ ++#ifdef CONFIG_NO_HZ_FULL ++/* ++ * Tick may be needed by tasks in the runqueue depending on their policy and ++ * requirements. If tick is needed, lets send the target an IPI to kick it out ++ * of nohz mode if necessary. ++ */ ++static inline void sched_update_tick_dependency(struct rq *rq) ++{ ++ int cpu = cpu_of(rq); ++ ++ if (!tick_nohz_full_cpu(cpu)) ++ return; ++ ++ if (rq->nr_running < 2) ++ tick_nohz_dep_clear_cpu(cpu, TICK_DEP_BIT_SCHED); ++ else ++ tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED); ++} ++#else /* !CONFIG_NO_HZ_FULL: */ ++static inline void sched_update_tick_dependency(struct rq *rq) { } ++#endif /* !CONFIG_NO_HZ_FULL */ ++ ++static inline void add_nr_running(struct rq *rq, unsigned count) ++{ ++ unsigned prev_nr = rq->nr_running; ++ ++ rq->nr_running = prev_nr + count; ++ trace_sched_update_nr_running_tp(rq, count); ++ if (rq->nr_running > 1) { ++ if (prev_nr < 2) ++ cpumask_set_cpu(cpu_of(rq), &sched_rq_pending_mask); ++ rq->prio_balance_time = rq->clock; ++ } ++ ++ sched_update_tick_dependency(rq); ++} ++ ++static inline void sub_nr_running(struct rq *rq, unsigned count) ++{ ++ unsigned prev_nr = rq->nr_running; ++ ++ rq->nr_running = prev_nr - count; ++ trace_sched_update_nr_running_tp(rq, -count); ++ if (rq->nr_running < 2) { ++ if (prev_nr > 1) ++ cpumask_clear_cpu(cpu_of(rq), &sched_rq_pending_mask); ++ rq->prio_balance_time = 0; ++ } ++ ++ sched_update_tick_dependency(rq); ++} ++ ++bool sched_task_on_rq(struct task_struct *p) ++{ ++ return task_on_rq_queued(p); ++} ++ ++unsigned long get_wchan(struct task_struct *p) ++{ ++ unsigned long ip = 0; ++ unsigned int state; ++ ++ if (!p || p == current) ++ return 0; ++ ++ /* Only get wchan if task is blocked and we can keep it that way. */ ++ raw_spin_lock_irq(&p->pi_lock); ++ state = READ_ONCE(p->__state); ++ smp_rmb(); /* see try_to_wake_up() */ ++ if (state != TASK_RUNNING && state != TASK_WAKING && !p->on_rq) ++ ip = __get_wchan(p); ++ raw_spin_unlock_irq(&p->pi_lock); ++ ++ return ip; ++} ++ ++/* ++ * Add/Remove/Requeue task to/from the runqueue routines ++ * Context: rq->lock ++ */ ++#define __SCHED_DEQUEUE_TASK(p, rq, func) \ ++ sched_info_dequeue(rq, p); \ ++ \ ++ __list_del_entry(&p->sq_node); \ ++ if (p->sq_node.prev == p->sq_node.next) { \ ++ __clear_bit(sched_idx2prio(p->sq_node.next - &rq->queue.heads[0], rq), \ ++ rq->queue.bitmap); \ ++ func; \ ++ } ++ ++#define __SCHED_ENQUEUE_TASK(p, rq, func) \ ++ sched_info_enqueue(rq, p); \ ++ { \ ++ int idx, prio; \ ++ TASK_SCHED_PRIO_IDX(p, rq, idx, prio); \ ++ list_add_tail(&p->sq_node, &rq->queue.heads[idx]); \ ++ if (list_is_first(&p->sq_node, &rq->queue.heads[idx])) { \ ++ __set_bit(prio, rq->queue.bitmap); \ ++ func; \ ++ } \ ++ } ++ ++static inline void __dequeue_task(struct task_struct *p, struct rq *rq) ++{ ++#ifdef ALT_SCHED_DEBUG ++ lockdep_assert_rq_held(rq); ++ ++ /*printk(KERN_INFO "sched: dequeue(%d) %px %016llx\n", cpu_of(rq), p, p->deadline);*/ ++ WARN_ONCE(task_rq(p) != rq, "sched: dequeue task reside on cpu%d from cpu%d\n", ++ task_cpu(p), cpu_of(rq)); ++#endif ++ ++ __SCHED_DEQUEUE_TASK(p, rq, update_sched_preempt_mask(rq)); ++} ++ ++static inline void dequeue_task(struct task_struct *p, struct rq *rq, int flags) ++{ ++ __dequeue_task(p, rq); ++ psi_dequeue(p, flags); ++ sub_nr_running(rq, 1); ++} ++ ++static inline void __enqueue_task(struct task_struct *p, struct rq *rq) ++{ ++#ifdef ALT_SCHED_DEBUG ++ lockdep_assert_rq_held(rq); ++ ++ /*printk(KERN_INFO "sched: enqueue(%d) %px %d\n", cpu_of(rq), p, p->prio);*/ ++ WARN_ONCE(task_rq(p) != rq, "sched: enqueue task reside on cpu%d to cpu%d\n", ++ task_cpu(p), cpu_of(rq)); ++#endif ++ ++ __SCHED_ENQUEUE_TASK(p, rq, update_sched_preempt_mask(rq)); ++} ++ ++static inline void enqueue_task(struct task_struct *p, struct rq *rq, int flags) ++{ ++ __enqueue_task(p, rq); ++ psi_enqueue(p, flags); ++ add_nr_running(rq, 1); ++} ++ ++void requeue_task(struct task_struct *p, struct rq *rq, int flags) ++{ ++ struct list_head *node = &p->sq_node; ++ int deq_idx, idx, prio; ++ ++ if (!rt_task(p)) ++ flags &= ~ENQUEUE_HEAD; ++ ++ TASK_SCHED_PRIO_IDX(p, rq, idx, prio); ++#ifdef ALT_SCHED_DEBUG ++ lockdep_assert_rq_held(rq); ++ /*printk(KERN_INFO "sched: requeue(%d) %px %016llx\n", cpu_of(rq), p, p->deadline);*/ ++ WARN_ONCE(task_rq(p) != rq, "sched: cpu[%d] requeue task reside on cpu%d\n", ++ cpu_of(rq), task_cpu(p)); ++#endif ++ if (flags & ENQUEUE_HEAD) { ++ if (list_is_first(node, &rq->queue.heads[idx])) ++ return; ++ } else if (list_is_last(node, &rq->queue.heads[idx])) ++ return; ++ ++ __list_del_entry(node); ++ if (node->prev == node->next && (deq_idx = node->next - &rq->queue.heads[0]) != idx) ++ __clear_bit(sched_idx2prio(deq_idx, rq), rq->queue.bitmap); ++ ++ if (flags & ENQUEUE_HEAD) ++ list_add(node, &rq->queue.heads[idx]); ++ else ++ list_add_tail(node, &rq->queue.heads[idx]); ++ if (list_is_first(node, &rq->queue.heads[idx])) ++ __set_bit(prio, rq->queue.bitmap); ++ update_sched_preempt_mask(rq); ++} ++ ++/* ++ * try_cmpxchg based fetch_or() macro so it works for different integer types: ++ */ ++#define fetch_or(ptr, mask) \ ++ ({ \ ++ typeof(ptr) _ptr = (ptr); \ ++ typeof(mask) _mask = (mask); \ ++ typeof(*_ptr) _val = *_ptr; \ ++ \ ++ do { \ ++ } while (!try_cmpxchg(_ptr, &_val, _val | _mask)); \ ++ _val; \ ++}) ++ ++#ifdef TIF_POLLING_NRFLAG ++/* ++ * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG, ++ * this avoids any races wrt polling state changes and thereby avoids ++ * spurious IPIs. ++ */ ++static inline bool set_nr_and_not_polling(struct thread_info *ti, int tif) ++{ ++ return !(fetch_or(&ti->flags, 1 << tif) & _TIF_POLLING_NRFLAG); ++} ++ ++/* ++ * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set. ++ * ++ * If this returns true, then the idle task promises to call ++ * sched_ttwu_pending() and reschedule soon. ++ */ ++static bool set_nr_if_polling(struct task_struct *p) ++{ ++ struct thread_info *ti = task_thread_info(p); ++ typeof(ti->flags) val = READ_ONCE(ti->flags); ++ ++ do { ++ if (!(val & _TIF_POLLING_NRFLAG)) ++ return false; ++ if (val & _TIF_NEED_RESCHED) ++ return true; ++ } while (!try_cmpxchg(&ti->flags, &val, val | _TIF_NEED_RESCHED)); ++ ++ return true; ++} ++ ++#else /* !TIF_POLLING_NRFLAG: */ ++static inline bool set_nr_and_not_polling(struct thread_info *ti, int tif) ++{ ++ set_ti_thread_flag(ti, tif); ++ return true; ++} ++ ++static inline bool set_nr_if_polling(struct task_struct *p) ++{ ++ return false; ++} ++#endif /* !TIF_POLLING_NRFLAG */ ++ ++static bool __wake_q_add(struct wake_q_head *head, struct task_struct *task) ++{ ++ struct wake_q_node *node = &task->wake_q; ++ ++ /* ++ * Atomically grab the task, if ->wake_q is !nil already it means ++ * it's already queued (either by us or someone else) and will get the ++ * wakeup due to that. ++ * ++ * In order to ensure that a pending wakeup will observe our pending ++ * state, even in the failed case, an explicit smp_mb() must be used. ++ */ ++ smp_mb__before_atomic(); ++ if (unlikely(cmpxchg_relaxed(&node->next, NULL, WAKE_Q_TAIL))) ++ return false; ++ ++ /* ++ * The head is context local, there can be no concurrency. ++ */ ++ *head->lastp = node; ++ head->lastp = &node->next; ++ return true; ++} ++ ++/** ++ * wake_q_add() - queue a wakeup for 'later' waking. ++ * @head: the wake_q_head to add @task to ++ * @task: the task to queue for 'later' wakeup ++ * ++ * Queue a task for later wakeup, most likely by the wake_up_q() call in the ++ * same context, _HOWEVER_ this is not guaranteed, the wakeup can come ++ * instantly. ++ * ++ * This function must be used as-if it were wake_up_process(); IOW the task ++ * must be ready to be woken at this location. ++ */ ++void wake_q_add(struct wake_q_head *head, struct task_struct *task) ++{ ++ if (__wake_q_add(head, task)) ++ get_task_struct(task); ++} ++ ++/** ++ * wake_q_add_safe() - safely queue a wakeup for 'later' waking. ++ * @head: the wake_q_head to add @task to ++ * @task: the task to queue for 'later' wakeup ++ * ++ * Queue a task for later wakeup, most likely by the wake_up_q() call in the ++ * same context, _HOWEVER_ this is not guaranteed, the wakeup can come ++ * instantly. ++ * ++ * This function must be used as-if it were wake_up_process(); IOW the task ++ * must be ready to be woken at this location. ++ * ++ * This function is essentially a task-safe equivalent to wake_q_add(). Callers ++ * that already hold reference to @task can call the 'safe' version and trust ++ * wake_q to do the right thing depending whether or not the @task is already ++ * queued for wakeup. ++ */ ++void wake_q_add_safe(struct wake_q_head *head, struct task_struct *task) ++{ ++ if (!__wake_q_add(head, task)) ++ put_task_struct(task); ++} ++ ++void wake_up_q(struct wake_q_head *head) ++{ ++ struct wake_q_node *node = head->first; ++ ++ while (node != WAKE_Q_TAIL) { ++ struct task_struct *task; ++ ++ task = container_of(node, struct task_struct, wake_q); ++ node = node->next; ++ /* pairs with cmpxchg_relaxed() in __wake_q_add() */ ++ WRITE_ONCE(task->wake_q.next, NULL); ++ /* Task can safely be re-inserted now. */ ++ ++ /* ++ * wake_up_process() executes a full barrier, which pairs with ++ * the queueing in wake_q_add() so as not to miss wakeups. ++ */ ++ wake_up_process(task); ++ put_task_struct(task); ++ } ++} ++ ++/* ++ * resched_curr - mark rq's current task 'to be rescheduled now'. ++ * ++ * On UP this means the setting of the need_resched flag, on SMP it ++ * might also involve a cross-CPU call to trigger the scheduler on ++ * the target CPU. ++ */ ++static inline void __resched_curr(struct rq *rq, int tif) ++{ ++ struct task_struct *curr = rq->curr; ++ struct thread_info *cti = task_thread_info(curr); ++ int cpu; ++ ++ lockdep_assert_rq_held(rq); ++ ++ /* ++ * Always immediately preempt the idle task; no point in delaying doing ++ * actual work. ++ */ ++ if (is_idle_task(curr) && tif == TIF_NEED_RESCHED_LAZY) ++ tif = TIF_NEED_RESCHED; ++ ++ if (cti->flags & ((1 << tif) | _TIF_NEED_RESCHED)) ++ return; ++ ++ cpu = cpu_of(rq); ++ ++ trace_sched_set_need_resched_tp(curr, cpu, tif); ++ if (cpu == smp_processor_id()) { ++ set_ti_thread_flag(cti, tif); ++ if (tif == TIF_NEED_RESCHED) ++ set_preempt_need_resched(); ++ return; ++ } ++ ++ if (set_nr_and_not_polling(cti, tif)) { ++ if (tif == TIF_NEED_RESCHED) ++ smp_send_reschedule(cpu); ++ } else { ++ trace_sched_wake_idle_without_ipi(cpu); ++ } ++} ++ ++/* ++ * Calls to this function MUST be guarded by a ++ * tracepoint_enabled(sched_set_need_resched_tp) ++ */ ++void __trace_set_need_resched(struct task_struct *curr, int tif) ++{ ++ trace_call__sched_set_need_resched_tp(curr, smp_processor_id(), tif); ++} ++EXPORT_SYMBOL_GPL(__trace_set_need_resched); ++ ++static inline void resched_curr(struct rq *rq) ++{ ++ __resched_curr(rq, TIF_NEED_RESCHED); ++} ++ ++#ifdef CONFIG_PREEMPT_DYNAMIC ++static DEFINE_STATIC_KEY_FALSE(sk_dynamic_preempt_lazy); ++static __always_inline bool dynamic_preempt_lazy(void) ++{ ++ return static_branch_unlikely(&sk_dynamic_preempt_lazy); ++} ++#else /* !CONFIG_PREEMPT_DYNAMIC: */ ++static __always_inline bool dynamic_preempt_lazy(void) ++{ ++ return IS_ENABLED(CONFIG_PREEMPT_LAZY); ++} ++#endif /* !CONFIG_PREEMPT_DYNAMIC */ ++ ++static __always_inline int get_lazy_tif_bit(void) ++{ ++ if (dynamic_preempt_lazy()) ++ return TIF_NEED_RESCHED_LAZY; ++ ++ return TIF_NEED_RESCHED; ++} ++ ++static inline void resched_curr_lazy(struct rq *rq) ++{ ++ __resched_curr(rq, get_lazy_tif_bit()); ++} ++ ++void resched_cpu(int cpu) ++{ ++ struct rq *rq = cpu_rq(cpu); ++ unsigned long flags; ++ ++ raw_spin_rq_lock_irqsave(rq, flags); ++ if (cpu_online(cpu) || cpu == smp_processor_id()) ++ resched_curr(rq); ++ raw_spin_rq_unlock_irqrestore(rq, flags); ++} ++ ++#ifdef CONFIG_NO_HZ_COMMON ++/* ++ * This routine will record that the CPU is going idle with tick stopped. ++ * This info will be used in performing idle load balancing in the future. ++ */ ++void nohz_balance_enter_idle(int cpu) {} ++ ++/* ++ * In the semi idle case, use the nearest busy CPU for migrating timers ++ * from an idle CPU. This is good for power-savings. ++ * ++ * We don't do similar optimization for completely idle system, as ++ * selecting an idle CPU will add more delays to the timers than intended ++ * (as that CPU's timer base may not be up to date wrt jiffies etc). ++ */ ++int get_nohz_timer_target(void) ++{ ++ int i, cpu = smp_processor_id(), default_cpu = -1; ++ struct cpumask *topo_masks, *mask; ++ const struct cpumask *hk_mask; ++ ++ if (housekeeping_cpu(cpu, HK_TYPE_KERNEL_NOISE)) { ++ if (!idle_cpu(cpu)) ++ return cpu; ++ default_cpu = cpu; ++ } ++ ++ hk_mask = housekeeping_cpumask(HK_TYPE_KERNEL_NOISE); ++ ++ topo_masks = per_cpu(sched_cpu_topo_masks, cpu); ++ for (mask = topo_masks; ++ mask < per_cpu(sched_cpu_topo_end_mask, cpu); mask++) { ++ if (sched_cpu_topo_level_repeats(topo_masks, mask)) ++ continue; ++ ++ for_each_cpu_and(i, mask, hk_mask) ++ if (!idle_cpu(i)) ++ return i; ++ } ++ ++ if (default_cpu == -1) ++ default_cpu = housekeeping_any_cpu(HK_TYPE_KERNEL_NOISE); ++ cpu = default_cpu; ++ ++ return cpu; ++} ++ ++/* ++ * When add_timer_on() enqueues a timer into the timer wheel of an ++ * idle CPU then this timer might expire before the next timer event ++ * which is scheduled to wake up that CPU. In case of a completely ++ * idle system the next event might even be infinite time into the ++ * future. wake_up_idle_cpu() ensures that the CPU is woken up and ++ * leaves the inner idle loop so the newly added timer is taken into ++ * account when the CPU goes back to idle and evaluates the timer ++ * wheel for the next timer event. ++ */ ++static inline void wake_up_idle_cpu(int cpu) ++{ ++ struct rq *rq = cpu_rq(cpu); ++ ++ if (cpu == smp_processor_id()) ++ return; ++ ++ /* ++ * Set TIF_NEED_RESCHED and send an IPI if in the non-polling ++ * part of the idle loop. This forces an exit from the idle loop ++ * and a round trip to schedule(). Now this could be optimized ++ * because a simple new idle loop iteration is enough to ++ * re-evaluate the next tick. Provided some re-ordering of tick ++ * nohz functions that would need to follow TIF_NR_POLLING ++ * clearing: ++ * ++ * - On most architectures, a simple fetch_or on ti::flags with a ++ * "0" value would be enough to know if an IPI needs to be sent. ++ * ++ * - x86 needs to perform a last need_resched() check between ++ * monitor and mwait which doesn't take timers into account. ++ * There a dedicated TIF_TIMER flag would be required to ++ * fetch_or here and be checked along with TIF_NEED_RESCHED ++ * before mwait(). ++ * ++ * However, remote timer enqueue is not such a frequent event ++ * and testing of the above solutions didn't appear to report ++ * much benefits. ++ */ ++ if (set_nr_and_not_polling(task_thread_info(rq->idle), TIF_NEED_RESCHED)) ++ smp_send_reschedule(cpu); ++ else ++ trace_sched_wake_idle_without_ipi(cpu); ++} ++ ++static inline bool wake_up_full_nohz_cpu(int cpu) ++{ ++ /* ++ * We just need the target to call irq_exit() and re-evaluate ++ * the next tick. The nohz full kick at least implies that. ++ * If needed we can still optimize that later with an ++ * empty IRQ. ++ */ ++ if (cpu_is_offline(cpu)) ++ return true; /* Don't try to wake offline CPUs. */ ++ if (tick_nohz_full_cpu(cpu)) { ++ if (cpu != smp_processor_id() || ++ tick_nohz_tick_stopped()) ++ tick_nohz_full_kick_cpu(cpu); ++ return true; ++ } ++ ++ return false; ++} ++ ++void wake_up_nohz_cpu(int cpu) ++{ ++ if (!wake_up_full_nohz_cpu(cpu)) ++ wake_up_idle_cpu(cpu); ++} ++ ++static void nohz_csd_func(void *info) ++{ ++ struct rq *rq = info; ++ int cpu = cpu_of(rq); ++ unsigned int flags; ++ ++ /* ++ * Release the rq::nohz_csd. ++ */ ++ flags = atomic_fetch_andnot(NOHZ_KICK_MASK, nohz_flags(cpu)); ++ WARN_ON(!(flags & NOHZ_KICK_MASK)); ++ ++ rq->idle_balance = idle_cpu(cpu); ++ if (rq->idle_balance) { ++ rq->nohz_idle_balance = flags; ++ __raise_softirq_irqoff(SCHED_SOFTIRQ); ++ } ++} ++ ++#endif /* CONFIG_NO_HZ_COMMON */ ++ ++static __always_inline void wakeup_preempt(struct rq *rq) ++{ ++ if (sched_rq_first_task(rq) != rq->curr) ++ resched_curr(rq); ++} ++ ++static __always_inline ++int __task_state_match(struct task_struct *p, unsigned int state) ++{ ++ if (READ_ONCE(p->__state) & state) ++ return 1; ++ ++ if (READ_ONCE(p->saved_state) & state) ++ return -1; ++ ++ return 0; ++} ++ ++static __always_inline ++int task_state_match(struct task_struct *p, unsigned int state) ++{ ++ /* ++ * Serialize against current_save_and_set_rtlock_wait_state(), ++ * current_restore_rtlock_saved_state(), and __refrigerator(). ++ */ ++ guard(raw_spinlock_irq)(&p->pi_lock); ++ ++ return __task_state_match(p, state); ++} ++ ++/* ++ * wait_task_inactive - wait for a thread to unschedule. ++ * ++ * Wait for the thread to block in any of the states set in @match_state. ++ * If it changes, i.e. @p might have woken up, then return zero. When we ++ * succeed in waiting for @p to be off its CPU, we return a positive number ++ * (its total switch count). If a second call a short while later returns the ++ * same number, the caller can be sure that @p has remained unscheduled the ++ * whole time. ++ * ++ * The caller must ensure that the task *will* unschedule sometime soon, ++ * else this function might spin for a *long* time. This function can't ++ * be called with interrupts off, or it may introduce deadlock with ++ * smp_call_function() if an IPI is sent by the same process we are ++ * waiting to become inactive. ++ */ ++unsigned long wait_task_inactive(struct task_struct *p, unsigned int match_state) ++{ ++ int running, queued, match; ++ struct rq_flags rf; ++ unsigned long ncsw; ++ struct rq *rq; ++ ++ for (;;) { ++ rq = task_rq(p); ++ ++ /* ++ * If the task is actively running on another CPU ++ * still, just relax and busy-wait without holding ++ * any locks. ++ * ++ * NOTE! Since we don't hold any locks, it's not ++ * even sure that "rq" stays as the right runqueue! ++ * But we don't care, since this will return false ++ * if the runqueue has changed and p is actually now ++ * running somewhere else! ++ */ ++ while (task_on_cpu(rq, p)) { ++ if (!task_state_match(p, match_state)) ++ return 0; ++ cpu_relax(); ++ } ++ ++ /* ++ * Ok, time to look more closely! We need the rq ++ * lock now, to be *sure*. If we're wrong, we'll ++ * just go back and repeat. ++ */ ++ rq = task_rq_lock(p, &rf); ++ trace_sched_wait_task(p); ++ running = task_on_cpu(rq, p); ++ queued = task_on_rq_queued(p); ++ ncsw = 0; ++ if ((match = __task_state_match(p, match_state))) { ++ /* ++ * When matching on p->saved_state, consider this task ++ * still queued so it will wait. ++ */ ++ if (match < 0) ++ queued = 1; ++ ncsw = p->nvcsw | LONG_MIN; /* sets MSB */ ++ } ++ task_rq_unlock(rq, p, &rf); ++ ++ /* ++ * If it changed from the expected state, bail out now. ++ */ ++ if (unlikely(!ncsw)) ++ break; ++ ++ /* ++ * Was it really running after all now that we ++ * checked with the proper locks actually held? ++ * ++ * Oops. Go back and try again.. ++ */ ++ if (unlikely(running)) { ++ cpu_relax(); ++ continue; ++ } ++ ++ /* ++ * It's not enough that it's not actively running, ++ * it must be off the runqueue _entirely_, and not ++ * preempted! ++ * ++ * So if it was still runnable (but just not actively ++ * running right now), it's preempted, and we should ++ * yield - it could be a while. ++ */ ++ if (unlikely(queued)) { ++ ktime_t to = NSEC_PER_SEC / HZ; ++ ++ set_current_state(TASK_UNINTERRUPTIBLE); ++ schedule_hrtimeout(&to, HRTIMER_MODE_REL_HARD); ++ continue; ++ } ++ ++ /* ++ * Ahh, all good. It wasn't running, and it wasn't ++ * runnable, which means that it will never become ++ * running in the future either. We're all done! ++ */ ++ break; ++ } ++ ++ return ncsw; ++} ++ ++#ifdef CONFIG_SCHED_HRTICK ++/* ++ * Use HR-timers to deliver accurate preemption points. ++ */ ++ ++enum { ++ HRTICK_SCHED_NONE = 0, ++ HRTICK_SCHED_DEFER = BIT(1), ++ HRTICK_SCHED_START = BIT(2), ++ HRTICK_SCHED_REARM_HRTIMER = BIT(3) ++}; ++ ++static void __used hrtick_clear(struct rq *rq) ++{ ++ if (hrtimer_active(&rq->hrtick_timer)) ++ hrtimer_cancel(&rq->hrtick_timer); ++} ++ ++/* ++ * High-resolution timer tick. ++ * Runs from hardirq context with interrupts disabled. ++ */ ++static enum hrtimer_restart hrtick(struct hrtimer *timer) ++{ ++ struct rq *rq = container_of(timer, struct rq, hrtick_timer); ++ ++ WARN_ON_ONCE(cpu_of(rq) != smp_processor_id()); ++ ++ raw_spin_rq_lock(rq); ++ resched_curr(rq); ++ raw_spin_rq_unlock(rq); ++ ++ return HRTIMER_NORESTART; ++} ++ ++/* ++ * Use hrtick when: ++ * - enabled by features ++ * - hrtimer is actually high res ++ */ ++static inline bool hrtick_enabled(struct rq *rq) ++{ ++ return cpu_active(cpu_of(rq)) && hrtimer_highres_enabled(); ++} ++ ++static inline bool hrtick_needs_rearm(struct hrtimer *timer, ktime_t expires) ++{ ++ /* ++ * Queued is false when the timer is not started or currently ++ * running the callback. In both cases, restart. If queued check ++ * whether the expiry time actually changes substantially. ++ */ ++ return !hrtimer_is_queued(timer) || ++ abs(expires - hrtimer_get_expires(timer)) > 5000; ++} ++ ++static void hrtick_cond_restart(struct rq *rq) ++{ ++ struct hrtimer *timer = &rq->hrtick_timer; ++ ktime_t time = rq->hrtick_time; ++ ++ if (hrtick_needs_rearm(timer, time)) ++ hrtimer_start(timer, time, HRTIMER_MODE_ABS_PINNED_HARD); ++} ++ ++/* ++ * called from hardirq (IPI) context ++ */ ++static void __hrtick_start(void *arg) ++{ ++ struct rq *rq = arg; ++ ++ raw_spin_rq_lock(rq); ++ hrtick_cond_restart(rq); ++ raw_spin_rq_unlock(rq); ++} ++ ++/* ++ * Called to set the hrtick timer state. ++ * ++ * called with rq->lock held and IRQs disabled ++ */ ++static inline void hrtick_start(struct rq *rq, u64 delay) ++{ ++ s64 delta; ++ ++ /* ++ * Don't schedule slices shorter than 10000ns, that just ++ * doesn't make sense and can cause timer DoS. ++ */ ++ delta = max_t(s64, delay, 10000LL); ++ ++ /* ++ * If this is in the middle of schedule() only note the delay ++ * and let hrtick_schedule_exit() deal with it. ++ */ ++ if (rq->hrtick_sched) { ++ rq->hrtick_sched |= HRTICK_SCHED_START; ++ rq->hrtick_delay = delta; ++ return; ++ } ++ ++ rq->hrtick_time = ktime_add_ns(ktime_get(), delta); ++ if (!hrtick_needs_rearm(&rq->hrtick_timer, rq->hrtick_time)) ++ return; ++ ++ if (rq == this_rq()) ++ hrtimer_start(&rq->hrtick_timer, rq->hrtick_time, HRTIMER_MODE_ABS_PINNED_HARD); ++ else ++ smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd); ++} ++ ++static inline void hrtick_schedule_enter(struct rq *rq) ++{ ++ rq->hrtick_sched = HRTICK_SCHED_DEFER; ++ if (hrtimer_test_and_clear_rearm_deferred()) ++ rq->hrtick_sched |= HRTICK_SCHED_REARM_HRTIMER; ++} ++ ++static inline void hrtick_schedule_exit(struct rq *rq) ++{ ++ if (rq->hrtick_sched & HRTICK_SCHED_START) { ++ rq->hrtick_time = ktime_add_ns(ktime_get(), rq->hrtick_delay); ++ hrtick_cond_restart(rq); ++ } else { ++ /* ++ * No need for using hrtimer_is_active(). The timer is CPU local ++ * and interrupts are disabled, so the callback cannot be ++ * running and the queued state is valid. ++ */ ++ if (hrtimer_is_queued(&rq->hrtick_timer)) ++ hrtimer_cancel(&rq->hrtick_timer); ++ } ++ ++ if (rq->hrtick_sched & HRTICK_SCHED_REARM_HRTIMER) ++ __hrtimer_rearm_deferred(); ++ ++ rq->hrtick_sched = HRTICK_SCHED_NONE; ++} ++ ++static void hrtick_rq_init(struct rq *rq) ++{ ++ INIT_CSD(&rq->hrtick_csd, __hrtick_start, rq); ++ rq->hrtick_sched = HRTICK_SCHED_NONE; ++ hrtimer_setup(&rq->hrtick_timer, hrtick, CLOCK_MONOTONIC, ++ HRTIMER_MODE_REL_HARD | HRTIMER_MODE_LAZY_REARM); ++} ++#else /* !CONFIG_SCHED_HRTICK: */ ++static inline void hrtick_clear(struct rq *rq) { } ++static inline void hrtick_start(struct rq *rq, u64 delay) { } ++static inline void hrtick_rq_init(struct rq *rq) { } ++static inline void hrtick_schedule_enter(struct rq *rq) { } ++static inline void hrtick_schedule_exit(struct rq *rq) { } ++#endif /* !CONFIG_SCHED_HRTICK */ ++ ++/* ++ * activate_task - move a task to the runqueue. ++ * ++ * Context: rq->lock ++ */ ++static void activate_task(struct task_struct *p, struct rq *rq, int flags) ++{ ++ enqueue_task(p, rq, flags); ++ ++ WRITE_ONCE(p->on_rq, TASK_ON_RQ_QUEUED); ++ ASSERT_EXCLUSIVE_WRITER(p->on_rq); ++ ++ /* ++ * If in_iowait is set, the code below may not trigger any cpufreq ++ * utilization updates, so do it here explicitly with the IOWAIT flag ++ * passed. ++ */ ++ cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT * p->in_iowait); ++} ++ ++static void block_task(struct rq *rq, struct task_struct *p, unsigned long task_state) ++{ ++ p->sched_contributes_to_load = ++ (task_state & TASK_UNINTERRUPTIBLE) && ++ !(task_state & TASK_NOLOAD) && ++ !(task_state & TASK_FROZEN); ++ ++ /* ++ * __schedule() ttwu() ++ * prev_state = prev->state; if (p->on_rq && ...) ++ * if (prev_state) goto out; ++ * p->on_rq = 0; smp_acquire__after_ctrl_dep(); ++ * p->state = TASK_WAKING ++ * ++ * Where __schedule() and ttwu() have matching control dependencies. ++ * ++ * After this, schedule() must not care about p->state any more. ++ */ ++ dequeue_task(p, rq, DEQUEUE_SLEEP); ++ __block_task(rq, p); ++} ++ ++static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu) ++{ ++ /* ++ * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be ++ * successfully executed on another CPU. We must ensure that updates of ++ * per-task data have been completed by this moment. ++ */ ++ smp_wmb(); ++ ++ WRITE_ONCE(task_thread_info(p)->cpu, cpu); ++ rseq_sched_set_ids_changed(p); ++} ++ ++void set_task_cpu(struct task_struct *p, unsigned int new_cpu) ++{ ++ unsigned int state = READ_ONCE(p->__state); ++ ++ /* ++ * We should never call set_task_cpu() on a blocked task, ++ * ttwu() will sort out the placement. ++ */ ++ WARN_ON_ONCE(state != TASK_RUNNING && state != TASK_WAKING && !p->on_rq); ++ ++#ifdef CONFIG_LOCKDEP ++ /* ++ * The caller should hold either p->pi_lock or rq->lock, when changing ++ * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks. ++ * ++ * sched_move_task() holds both and thus holding either pins the cgroup, ++ * see task_group(). ++ * ++ * Furthermore, all task_rq users should acquire both locks, see ++ * task_rq_lock(). ++ */ ++ WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) || ++ lockdep_is_held(__rq_lockp(task_rq(p))))); ++#endif ++ /* ++ * Clearly, migrating tasks to offline CPUs is a fairly daft thing. ++ */ ++ WARN_ON_ONCE(!cpu_online(new_cpu)); ++ ++ WARN_ON_ONCE(is_migration_disabled(p)); ++ trace_sched_migrate_task(p, new_cpu); ++ ++ if (task_cpu(p) != new_cpu) ++ perf_event_task_migrate(p); ++ ++ __set_task_cpu(p, new_cpu); ++} ++ ++void ___migrate_enable(void) ++{ ++ struct task_struct *p = current; ++ __do_set_cpus_ptr(p, &p->cpus_mask); ++} ++EXPORT_SYMBOL_GPL(___migrate_enable); ++ ++void migrate_disable(void) ++{ ++ __migrate_disable(); ++} ++EXPORT_SYMBOL_GPL(migrate_disable); ++ ++void migrate_enable(void) ++{ ++ __migrate_enable(); ++} ++EXPORT_SYMBOL_GPL(migrate_enable); ++ ++static void __migrate_force_enable(struct task_struct *p, struct rq *rq) ++{ ++ if (likely(p->cpus_ptr != &p->cpus_mask)) ++ __do_set_cpus_ptr(p, &p->cpus_mask); ++ p->migration_disabled = 0; ++ /* When p is migrate_disabled, rq->lock should be held */ ++ rq->nr_pinned--; ++} ++ ++static inline bool rq_has_pinned_tasks(struct rq *rq) ++{ ++ return rq->nr_pinned; ++} ++ ++/* ++ * Per-CPU kthreads are allowed to run on !active && online CPUs, see ++ * __set_cpus_allowed_ptr() and select_fallback_rq(). ++ */ ++static inline bool is_cpu_allowed(struct task_struct *p, int cpu) ++{ ++ /* When not in the task's cpumask, no point in looking further. */ ++ if (!task_allowed_on_cpu(p, cpu)) ++ return false; ++ ++ /* migrate_disabled() must be allowed to finish. */ ++ if (is_migration_disabled(p)) ++ return cpu_online(cpu); ++ ++ /* Non kernel threads are not allowed during either online or offline. */ ++ if (!(p->flags & PF_KTHREAD)) ++ return cpu_active(cpu); ++ ++ /* KTHREAD_IS_PER_CPU is always allowed. */ ++ if (kthread_is_per_cpu(p)) ++ return cpu_online(cpu); ++ ++ /* Regular kernel threads don't get to stay during offline. */ ++ if (cpu_dying(cpu)) ++ return false; ++ ++ /* But are allowed during online. */ ++ return cpu_online(cpu); ++} ++ ++/* ++ * This is how migration works: ++ * ++ * 1) we invoke migration_cpu_stop() on the target CPU using ++ * stop_one_cpu(). ++ * 2) stopper starts to run (implicitly forcing the migrated thread ++ * off the CPU) ++ * 3) it checks whether the migrated task is still in the wrong runqueue. ++ * 4) if it's in the wrong runqueue then the migration thread removes ++ * it and puts it into the right queue. ++ * 5) stopper completes and stop_one_cpu() returns and the migration ++ * is done. ++ */ ++ ++/* ++ * move_queued_task - move a queued task to new rq. ++ * ++ * Returns (locked) new rq. Old rq's lock is released. ++ */ ++struct rq *move_queued_task(struct rq *rq, struct rq_flags *rf, ++ struct task_struct *p, int new_cpu) ++ __must_hold(__rq_lockp(rq)) ++{ ++ lockdep_assert_rq_held(rq); ++ ++ WRITE_ONCE(p->on_rq, TASK_ON_RQ_MIGRATING); ++ dequeue_task(p, rq, 0); ++ set_task_cpu(p, new_cpu); ++ rq_unlock(rq, rf); ++ ++ rq = cpu_rq(new_cpu); ++ ++ rq_lock(rq, rf); ++ WARN_ON_ONCE(task_cpu(p) != new_cpu); ++ ++ sched_task_sanity_check(p, rq); ++ enqueue_task(p, rq, ENQUEUE_MIGRATED); ++ WRITE_ONCE(p->on_rq, TASK_ON_RQ_QUEUED); ++ wakeup_preempt(rq); ++ ++ return rq; ++} ++ ++struct migration_arg { ++ struct task_struct *task; ++ int dest_cpu; ++}; ++ ++/* ++ * Move (not current) task off this CPU, onto the destination CPU. We're doing ++ * this because either it can't run here any more (set_cpus_allowed() ++ * away from this CPU, or CPU going down), or because we're ++ * attempting to rebalance this task on exec (sched_exec). ++ * ++ * So we race with normal scheduler movements, but that's OK, as long ++ * as the task is no longer on this CPU. ++ */ ++static struct rq *__migrate_task(struct rq *rq, struct rq_flags *rf, ++ struct task_struct *p, int dest_cpu) ++ __must_hold(__rq_lockp(rq)) ++{ ++ /* Affinity changed (again). */ ++ if (!is_cpu_allowed(p, dest_cpu)) ++ return rq; ++ ++ return move_queued_task(rq, rf, p, dest_cpu); ++} ++ ++/* ++ * migration_cpu_stop - this will be executed by a high-prio stopper thread ++ * and performs thread migration by bumping thread off CPU then ++ * 'pushing' onto another runqueue. ++ */ ++static int migration_cpu_stop(void *data) ++{ ++ struct migration_arg *arg = data; ++ struct task_struct *p = arg->task; ++ struct rq *rq = this_rq(); ++ struct rq_flags rf; ++ ++ /* ++ * The original target CPU might have gone down and we might ++ * be on another CPU but it doesn't matter. ++ */ ++ local_irq_save(rf.flags); ++ /* ++ * We need to explicitly wake pending tasks before running ++ * __migrate_task() such that we will not miss enforcing cpus_ptr ++ * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test. ++ */ ++ flush_smp_call_function_queue(); ++ ++ /* ++ * We may change the underlying rq, but the locks held will ++ * appropriately be "transferred" when switching. ++ */ ++ context_unsafe_alias(rq); ++ ++ raw_spin_lock(&p->pi_lock); ++ rq_lock(rq, &rf); ++ /* ++ * If task_rq(p) != rq, it cannot be migrated here, because we're ++ * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because ++ * we're holding p->pi_lock. ++ */ ++ if (task_rq(p) == rq && task_on_rq_queued(p)) { ++ update_rq_clock(rq); ++ rq = __migrate_task(rq, &rf, p, arg->dest_cpu); ++ } ++ rq_unlock(rq, &rf); ++ raw_spin_unlock_irqrestore(&p->pi_lock, rf.flags); ++ ++ return 0; ++} ++ ++static inline void mm_update_cpus_allowed(struct mm_struct *mm, const cpumask_t *affmask); ++ ++static inline void ++set_cpus_allowed_common(struct task_struct *p, struct affinity_context *ctx) ++{ ++ cpumask_copy(&p->cpus_mask, ctx->new_mask); ++ p->nr_cpus_allowed = cpumask_weight(ctx->new_mask); ++ mm_update_cpus_allowed(p->mm, ctx->new_mask); ++ ++ /* ++ * Swap in a new user_cpus_ptr if SCA_USER flag set ++ */ ++ if (ctx->flags & SCA_USER) ++ swap(p->user_cpus_ptr, ctx->user_mask); ++} ++ ++static void ++do_set_cpus_allowed(struct task_struct *p, struct affinity_context *ctx) ++{ ++ lockdep_assert_held(&p->pi_lock); ++ set_cpus_allowed_common(p, ctx); ++} ++ ++/* ++ * Used for kthread_bind() and select_fallback_rq(), in both cases the user ++ * affinity (if any) should be destroyed too. ++ */ ++void set_cpus_allowed_force(struct task_struct *p, const struct cpumask *new_mask) ++{ ++ struct affinity_context ac = { ++ .new_mask = new_mask, ++ .user_mask = NULL, ++ .flags = SCA_USER, /* clear the user requested mask */ ++ }; ++ union cpumask_rcuhead { ++ cpumask_t cpumask; ++ struct rcu_head rcu; ++ }; ++ ++ do_set_cpus_allowed(p, &ac); ++ ++ if (is_migration_disabled(p) && !cpumask_test_cpu(task_cpu(p), &p->cpus_mask)) ++ __migrate_force_enable(p, task_rq(p)); ++ ++ /* ++ * Because this is called with p->pi_lock held, it is not possible ++ * to use kfree() here (when PREEMPT_RT=y), therefore punt to using ++ * kfree_rcu(). ++ */ ++ kfree_rcu((union cpumask_rcuhead *)ac.user_mask, rcu); ++} ++ ++int dup_user_cpus_ptr(struct task_struct *dst, struct task_struct *src, ++ int node) ++{ ++ cpumask_t *user_mask; ++ unsigned long flags; ++ ++ /* ++ * Always clear dst->user_cpus_ptr first as their user_cpus_ptr's ++ * may differ by now due to racing. ++ */ ++ dst->user_cpus_ptr = NULL; ++ ++ /* ++ * This check is racy and losing the race is a valid situation. ++ * It is not worth the extra overhead of taking the pi_lock on ++ * every fork/clone. ++ */ ++ if (data_race(!src->user_cpus_ptr)) ++ return 0; ++ ++ user_mask = alloc_user_cpus_ptr(node); ++ if (!user_mask) ++ return -ENOMEM; ++ ++ /* ++ * Use pi_lock to protect content of user_cpus_ptr ++ * ++ * Though unlikely, user_cpus_ptr can be reset to NULL by a concurrent ++ * set_cpus_allowed_force(). ++ */ ++ raw_spin_lock_irqsave(&src->pi_lock, flags); ++ if (src->user_cpus_ptr) { ++ swap(dst->user_cpus_ptr, user_mask); ++ cpumask_copy(dst->user_cpus_ptr, src->user_cpus_ptr); ++ } ++ raw_spin_unlock_irqrestore(&src->pi_lock, flags); ++ ++ if (unlikely(user_mask)) ++ kfree(user_mask); ++ ++ return 0; ++} ++ ++static inline struct cpumask *clear_user_cpus_ptr(struct task_struct *p) ++{ ++ struct cpumask *user_mask = NULL; ++ ++ swap(p->user_cpus_ptr, user_mask); ++ ++ return user_mask; ++} ++ ++void release_user_cpus_ptr(struct task_struct *p) ++{ ++ kfree(clear_user_cpus_ptr(p)); ++} ++ ++/** ++ * task_curr - is this task currently executing on a CPU? ++ * @p: the task in question. ++ * ++ * Return: 1 if the task is currently executing. 0 otherwise. ++ */ ++inline int task_curr(const struct task_struct *p) ++{ ++ return cpu_curr(task_cpu(p)) == p; ++} ++ ++/*** ++ * kick_process - kick a running thread to enter/exit the kernel ++ * @p: the to-be-kicked thread ++ * ++ * Cause a process which is running on another CPU to enter ++ * kernel-mode, without any delay. (to get signals handled.) ++ * ++ * NOTE: this function doesn't have to take the runqueue lock, ++ * because all it wants to ensure is that the remote task enters ++ * the kernel. If the IPI races and the task has been migrated ++ * to another CPU then no harm is done and the purpose has been ++ * achieved as well. ++ */ ++void kick_process(struct task_struct *p) ++{ ++ guard(preempt)(); ++ int cpu = task_cpu(p); ++ ++ if ((cpu != smp_processor_id()) && task_curr(p)) ++ smp_send_reschedule(cpu); ++} ++EXPORT_SYMBOL_GPL(kick_process); ++ ++/* ++ * ->cpus_ptr is protected by both rq->lock and p->pi_lock ++ * ++ * A few notes on cpu_active vs cpu_online: ++ * ++ * - cpu_active must be a subset of cpu_online ++ * ++ * - on CPU-up we allow per-CPU kthreads on the online && !active CPU, ++ * see __set_cpus_allowed_ptr(). At this point the newly online ++ * CPU isn't yet part of the sched domains, and balancing will not ++ * see it. ++ * ++ * - on cpu-down we clear cpu_active() to mask the sched domains and ++ * avoid the load balancer to place new tasks on the to be removed ++ * CPU. Existing tasks will remain running there and will be taken ++ * off. ++ * ++ * This means that fallback selection must not select !active CPUs. ++ * And can assume that any active CPU must be online. Conversely ++ * select_task_rq() below may allow selection of !active CPUs in order ++ * to satisfy the above rules. ++ */ ++static int select_fallback_rq(int cpu, struct task_struct *p) ++{ ++ int nid = cpu_to_node(cpu); ++ const struct cpumask *nodemask = NULL; ++ enum { cpuset, possible, fail } state = cpuset; ++ int dest_cpu; ++ ++ /* ++ * If the node that the CPU is on has been offlined, cpu_to_node() ++ * will return -1. There is no CPU on the node, and we should ++ * select the CPU on the other node. ++ */ ++ if (nid != -1) { ++ nodemask = cpumask_of_node(nid); ++ ++ /* Look for allowed, online CPU in same node. */ ++ for_each_cpu(dest_cpu, nodemask) { ++ if (is_cpu_allowed(p, dest_cpu)) ++ return dest_cpu; ++ } ++ } ++ ++ for (;;) { ++ /* Any allowed, online CPU? */ ++ for_each_cpu(dest_cpu, p->cpus_ptr) { ++ if (!is_cpu_allowed(p, dest_cpu)) ++ continue; ++ goto out; ++ } ++ ++ /* No more Mr. Nice Guy. */ ++ switch (state) { ++ case cpuset: ++ if (cpuset_cpus_allowed_fallback(p)) { ++ state = possible; ++ break; ++ } ++ fallthrough; ++ case possible: ++ set_cpus_allowed_force(p, task_cpu_fallback_mask(p)); ++ state = fail; ++ break; ++ ++ case fail: ++ BUG(); ++ break; ++ } ++ } ++ ++out: ++ if (state != cpuset) { ++ /* ++ * Don't tell them about moving exiting tasks or ++ * kernel threads (both mm NULL), since they never ++ * leave kernel. ++ */ ++ if (p->mm && printk_ratelimit()) { ++ printk_deferred("process %d (%s) no longer affine to cpu%d\n", ++ task_pid_nr(p), p->comm, cpu); ++ } ++ } ++ ++ return dest_cpu; ++} ++ ++static inline void ++sched_preempt_mask_flush(cpumask_t *mask, int prio, int ref) ++{ ++ int cpu; ++ ++ cpumask_copy(mask, sched_preempt_mask + ref); ++ if (prio < ref) { ++ for_each_clear_bit(cpu, cpumask_bits(mask), nr_cpumask_bits) { ++ if (prio < cpu_rq(cpu)->prio) ++ cpumask_set_cpu(cpu, mask); ++ } ++ } else { ++ for_each_cpu_andnot(cpu, mask, sched_idle_mask) { ++ if (prio >= cpu_rq(cpu)->prio) ++ cpumask_clear_cpu(cpu, mask); ++ } ++ } ++} ++ ++static inline int ++preempt_mask_check(cpumask_t *preempt_mask, const cpumask_t *allow_mask, int prio) ++{ ++ cpumask_t *mask = sched_preempt_mask + prio; ++ int pr = atomic_read(&sched_prio_record); ++ ++ if (pr != prio && SCHED_QUEUE_BITS - 1 != prio) { ++ sched_preempt_mask_flush(mask, prio, pr); ++ atomic_set(&sched_prio_record, prio); ++ } ++ ++ return cpumask_and(preempt_mask, allow_mask, mask); ++} ++ ++DEFINE_STATIC_CALL(sched_idle_select_func, cpumask_and); ++ ++static void record_wakee(struct task_struct *p) ++{ ++ /* ++ * Only decay a single time; tasks that have less then 1 wakeup per ++ * jiffy will not have built up many flips. ++ */ ++ if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) { ++ current->wakee_flips >>= 1; ++ WRITE_ONCE(current->wakee_flip_decay_ts, jiffies); ++ } ++ ++ if (current->last_wakee != p) { ++ WRITE_ONCE(current->last_wakee, p); ++ current->wakee_flips++; ++ } ++} ++ ++/* ++ * Detect M:N waker/wakee relationships via a switching-frequency heuristic. ++ * ++ * A waker of many should wake a different task than the one last awakened ++ * at a frequency roughly N times higher than one of its wakees. ++ * ++ * In order to determine whether we should let the load spread vs consolidating ++ * to shared cache, we look for a minimum 'flip' frequency of llc_size in one ++ * partner, and a factor of lls_size higher frequency in the other. ++ * ++ * With both conditions met, we can be relatively sure that the relationship is ++ * non-monogamous, with partner count exceeding socket size. ++ * ++ * Waker/wakee being client/server, worker/dispatcher, interrupt source or ++ * whatever is irrelevant, spread criteria is apparent partner count exceeds ++ * socket size. ++ */ ++static int wake_wide(struct task_struct *p) ++{ ++ unsigned int master = current->wakee_flips; ++ unsigned int slave = p->wakee_flips; ++ int factor = __this_cpu_read(sd_llc_size); ++ ++ if (master < slave) ++ swap(master, slave); ++ if (slave < factor || master < slave * factor) ++ return 0; ++ return 1; ++} ++ ++static int ++wake_affine_idle(int this_cpu, int prev_cpu, int sync) ++{ ++ /* ++ * If this_cpu is idle, it implies the wakeup is from interrupt ++ * context. Only allow the move if cache is shared. Otherwise an ++ * interrupt intensive workload could force all tasks onto one ++ * node depending on the IO topology or IRQ affinity settings. ++ * ++ * If the prev_cpu is idle and cache affine then avoid a migration. ++ * There is no guarantee that the cache hot data from an interrupt ++ * is more important than cache hot data on the prev_cpu and from ++ * a cpufreq perspective, it's better to have higher utilisation ++ * on one CPU. ++ */ ++ if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu)) ++ return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu; ++ ++ /* ++ * If the previous CPU is cache affine and idle, don't be stupid. ++ */ ++ if (prev_cpu != this_cpu && cpus_share_cache(this_cpu, prev_cpu) && ++ available_idle_cpu(prev_cpu)) ++ return prev_cpu; ++ ++ if (sync) { ++ struct rq *rq = cpu_rq(this_cpu); ++ ++ if (rq->nr_running == 1) ++ return this_cpu; ++ } ++ ++ if (available_idle_cpu(prev_cpu)) ++ return prev_cpu; ++ ++ return nr_cpu_ids; ++} ++ ++static inline int select_task_rq(struct task_struct *p, int wake_flags) ++{ ++ int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING); ++ cpumask_t allow_mask, mask; ++ int cpu = smp_processor_id(); ++ int prev_cpu = task_cpu(p); ++ int new_cpu = prev_cpu; ++ int want_affine = 0; ++ bool wakee_migratable = p->nr_cpus_allowed > 1 && !is_migration_disabled(p); ++ ++ /* ++ * required for stable ->cpus_allowed ++ */ ++ lockdep_assert_held(&p->pi_lock); ++ ++ if (!wakee_migratable) { ++ new_cpu = cpumask_any(p->cpus_ptr); ++ goto out; ++ } ++ ++ if (wake_flags & WF_TTWU) { ++ record_wakee(p); ++ ++ if ((wake_flags & WF_CURRENT_CPU) && ++ cpumask_test_cpu(cpu, p->cpus_ptr)) { ++ new_cpu = cpu; ++ goto out; ++ } ++ ++ want_affine = sync && cpumask_test_cpu(cpu, p->cpus_ptr) && ++ !wake_wide(p); ++ } ++ ++ if (unlikely(!cpumask_and(&allow_mask, p->cpus_ptr, cpu_active_mask))) { ++ new_cpu = select_fallback_rq(prev_cpu, p); ++ goto out; ++ } ++ ++ if (want_affine) { ++ int affine_cpu = nr_cpu_ids; ++ s64 waker_ran = READ_ONCE(this_rq()->clock) - ++ READ_ONCE(current->wake_start); ++ ++ if (!is_idle_task(current) && waker_ran < TICK_NSEC) { ++ cpumask_and(&mask, cpu_smt_mask(cpu), &allow_mask); ++ affine_cpu = cpumask_any_but(&mask, cpu); ++ if (affine_cpu >= nr_cpu_ids) ++ affine_cpu = cpu; ++ } ++ if (affine_cpu >= nr_cpu_ids) ++ affine_cpu = wake_affine_idle(cpu, prev_cpu, sync); ++ else if (!available_idle_cpu(affine_cpu) && ++ ((affine_cpu != cpu && ++ (rt_task(p) || sched_task_has_credit(p)) && ++ task_sched_prio(p) >= cpu_rq(affine_cpu)->prio) || ++ (cpu_rq(cpu)->nr_running + cpu_rq(affine_cpu)->nr_running > 3 && ++ cpumask_intersects(&allow_mask, sched_idle_mask)))) ++ affine_cpu = nr_cpu_ids; ++ if (affine_cpu < nr_cpu_ids && ++ cpumask_test_cpu(affine_cpu, &allow_mask)) { ++ new_cpu = affine_cpu; ++ goto out; ++ } ++ } ++ ++ if (static_call(sched_idle_select_func)(&mask, &allow_mask, sched_idle_mask)) { ++ do { ++ new_cpu = cpumask_test_cpu(prev_cpu, &mask) ? ++ prev_cpu : best_mask_cpu(prev_cpu, &mask); ++ if (!__is_defined(ALT_SCHED_TTWU_QUEUE) || ++ !cpu_rq(new_cpu)->ttwu_pending) ++ goto out; ++ __cpumask_clear_cpu(new_cpu, &mask); ++ } while (!cpumask_empty(&mask)); ++ } ++ ++ int prio = task_sched_prio(p); ++ ++ if (preempt_mask_check(&mask, &allow_mask, prio)) { ++ int preempt_cpu = nr_cpu_ids; ++ ++ guard(rcu)(); ++ do { ++ new_cpu = best_mask_cpu(prev_cpu, &mask); ++ if (prio < cpu_rq(new_cpu)->prio) { ++ struct task_struct *curr = rcu_dereference(cpu_rq(new_cpu)->curr); ++ ++ if (!rt_task(curr) && !sched_task_has_credit(curr) && ++ !test_tsk_need_resched(curr)) ++ goto out; ++ if (preempt_cpu >= nr_cpu_ids) ++ preempt_cpu = new_cpu; ++ } ++ __cpumask_clear_cpu(new_cpu, &mask); ++ } while (!cpumask_empty(&mask)); ++ ++ if (preempt_cpu < nr_cpu_ids) { ++ new_cpu = preempt_cpu; ++ goto out; ++ } ++ } ++ new_cpu = best_mask_cpu(prev_cpu, &allow_mask); ++ ++out: ++ if (unlikely(!is_cpu_allowed(p, new_cpu))) ++ new_cpu = select_fallback_rq(prev_cpu, p); ++ ++ return new_cpu; ++} ++ ++void sched_set_stop_task(int cpu, struct task_struct *stop) ++{ ++ static struct lock_class_key stop_pi_lock; ++ struct sched_param stop_param = { .sched_priority = STOP_PRIO }; ++ struct sched_param start_param = { .sched_priority = 0 }; ++ struct task_struct *old_stop = cpu_rq(cpu)->stop; ++ ++ if (stop) { ++ /* ++ * Make it appear like a SCHED_FIFO task, its something ++ * userspace knows about and won't get confused about. ++ * ++ * Also, it will make PI more or less work without too ++ * much confusion -- but then, stop work should not ++ * rely on PI working anyway. ++ */ ++ sched_setscheduler_nocheck(stop, SCHED_FIFO, &stop_param); ++ ++ /* ++ * The PI code calls rt_mutex_setprio() with ->pi_lock held to ++ * adjust the effective priority of a task. As a result, ++ * rt_mutex_setprio() can trigger (RT) balancing operations, ++ * which can then trigger wakeups of the stop thread to push ++ * around the current task. ++ * ++ * The stop task itself will never be part of the PI-chain, it ++ * never blocks, therefore that ->pi_lock recursion is safe. ++ * Tell lockdep about this by placing the stop->pi_lock in its ++ * own class. ++ */ ++ lockdep_set_class(&stop->pi_lock, &stop_pi_lock); ++ } ++ ++ cpu_rq(cpu)->stop = stop; ++ ++ if (old_stop) { ++ /* ++ * Reset it back to a normal scheduling policy so that ++ * it can die in pieces. ++ */ ++ sched_setscheduler_nocheck(old_stop, SCHED_NORMAL, &start_param); ++ } ++} ++ ++static int affine_move_task(struct rq *rq, struct task_struct *p, ++ struct rq_flags *rf, int dest_cpu) ++ __releases(__rq_lockp(rq), &p->pi_lock) ++{ ++ /* Can the task run on the task's current CPU? If so, we're done */ ++ if (!cpumask_test_cpu(task_cpu(p), &p->cpus_mask)) { ++ if (is_migration_disabled(p)) ++ __migrate_force_enable(p, rq); ++ ++ if (task_on_cpu(task_rq(p), p) || READ_ONCE(p->__state) == TASK_WAKING) { ++ struct migration_arg arg = { p, dest_cpu }; ++ ++ /* Need help from migration thread: drop lock and wait. */ ++ task_rq_unlock(rq, p, rf); ++ stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg); ++ return 0; ++ } ++ if (task_on_rq_queued(p)) { ++ /* ++ * OK, since we're going to drop the lock immediately ++ * afterwards anyway. ++ */ ++ update_rq_clock(rq); ++ rq = move_queued_task(rq, rf, p, dest_cpu); ++ } ++ } ++ task_rq_unlock(rq, p, rf); ++ return 0; ++} ++ ++static int __set_cpus_allowed_ptr_locked(struct task_struct *p, ++ struct affinity_context *ctx, ++ struct rq *rq, ++ struct rq_flags *rf) ++ __releases(__rq_lockp(rq), &p->pi_lock) ++{ ++ const struct cpumask *cpu_allowed_mask = task_cpu_possible_mask(p); ++ const struct cpumask *cpu_valid_mask = cpu_active_mask; ++ bool kthread = p->flags & PF_KTHREAD; ++ int dest_cpu; ++ int ret = 0; ++ ++ if (kthread || is_migration_disabled(p)) { ++ /* ++ * Kernel threads are allowed on online && !active CPUs, ++ * however, during cpu-hot-unplug, even these might get pushed ++ * away if not KTHREAD_IS_PER_CPU. ++ * ++ * Specifically, migration_disabled() tasks must not fail the ++ * cpumask_any_and_distribute() pick below, esp. so on ++ * SCA_MIGRATE_ENABLE, otherwise we'll not call ++ * set_cpus_allowed_common() and actually reset p->cpus_ptr. ++ */ ++ cpu_valid_mask = cpu_online_mask; ++ } ++ ++ if (!kthread && !cpumask_subset(ctx->new_mask, cpu_allowed_mask)) { ++ ret = -EINVAL; ++ goto out; ++ } ++ ++ /* ++ * Must re-check here, to close a race against __kthread_bind(), ++ * sched_setaffinity() is not guaranteed to observe the flag. ++ */ ++ if ((ctx->flags & SCA_CHECK) && (p->flags & PF_NO_SETAFFINITY)) { ++ ret = -EINVAL; ++ goto out; ++ } ++ ++ if (cpumask_equal(&p->cpus_mask, ctx->new_mask)) { ++ if (ctx->flags & SCA_USER) ++ swap(p->user_cpus_ptr, ctx->user_mask); ++ goto out; ++ } ++ ++ dest_cpu = cpumask_any_and_distribute(cpu_valid_mask, ctx->new_mask); ++ if (dest_cpu >= nr_cpu_ids) { ++ ret = -EINVAL; ++ goto out; ++ } ++ ++ do_set_cpus_allowed(p, ctx); ++ ++ return affine_move_task(rq, p, rf, dest_cpu); ++ ++out: ++ task_rq_unlock(rq, p, rf); ++ ++ return ret; ++} ++ ++/* ++ * Change a given task's CPU affinity. Migrate the thread to a ++ * is removed from the allowed bitmask. ++ * ++ * NOTE: the caller must have a valid reference to the task, the ++ * task must not exit() & deallocate itself prematurely. The ++ * call is not atomic; no spinlocks may be held. ++ */ ++int __set_cpus_allowed_ptr(struct task_struct *p, ++ struct affinity_context *ctx) ++{ ++ struct rq_flags rf; ++ struct rq *rq; ++ ++ rq = task_rq_lock(p, &rf); ++ /* ++ * Masking should be skipped if SCA_USER or any of the SCA_MIGRATE_* ++ * flags are set. ++ */ ++ if (p->user_cpus_ptr && ++ !(ctx->flags & (SCA_USER | SCA_MIGRATE_ENABLE | SCA_MIGRATE_DISABLE)) && ++ cpumask_and(rq->scratch_mask, ctx->new_mask, p->user_cpus_ptr)) ++ ctx->new_mask = rq->scratch_mask; ++ ++ ++ return __set_cpus_allowed_ptr_locked(p, ctx, rq, &rf); ++} ++ ++int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask) ++{ ++ struct affinity_context ac = { ++ .new_mask = new_mask, ++ .flags = 0, ++ }; ++ ++ return __set_cpus_allowed_ptr(p, &ac); ++} ++EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr); ++ ++/* ++ * Change a given task's CPU affinity to the intersection of its current ++ * affinity mask and @subset_mask, writing the resulting mask to @new_mask. ++ * If user_cpus_ptr is defined, use it as the basis for restricting CPU ++ * affinity or use cpu_online_mask instead. ++ * ++ * If the resulting mask is empty, leave the affinity unchanged and return ++ * -EINVAL. ++ */ ++static int restrict_cpus_allowed_ptr(struct task_struct *p, ++ struct cpumask *new_mask, ++ const struct cpumask *subset_mask) ++{ ++ struct affinity_context ac = { ++ .new_mask = new_mask, ++ .flags = 0, ++ }; ++ struct rq_flags rf; ++ struct rq *rq; ++ int err; ++ ++ rq = task_rq_lock(p, &rf); ++ ++ if (!cpumask_and(new_mask, task_user_cpus(p), subset_mask)) { ++ err = -EINVAL; ++ goto err_unlock; ++ } ++ ++ return __set_cpus_allowed_ptr_locked(p, &ac, rq, &rf); ++ ++err_unlock: ++ task_rq_unlock(rq, p, &rf); ++ return err; ++} ++ ++/* ++ * Restrict the CPU affinity of task @p so that it is a subset of ++ * task_cpu_possible_mask() and point @p->user_cpus_ptr to a copy of the ++ * old affinity mask. If the resulting mask is empty, we warn and walk ++ * up the cpuset hierarchy until we find a suitable mask. ++ */ ++void force_compatible_cpus_allowed_ptr(struct task_struct *p) ++{ ++ cpumask_var_t new_mask; ++ const struct cpumask *override_mask = task_cpu_possible_mask(p); ++ ++ alloc_cpumask_var(&new_mask, GFP_KERNEL); ++ ++ /* ++ * __migrate_task() can fail silently in the face of concurrent ++ * offlining of the chosen destination CPU, so take the hotplug ++ * lock to ensure that the migration succeeds. ++ */ ++ cpus_read_lock(); ++ if (!cpumask_available(new_mask)) ++ goto out_set_mask; ++ ++ if (!restrict_cpus_allowed_ptr(p, new_mask, override_mask)) ++ goto out_free_mask; ++ ++ /* ++ * We failed to find a valid subset of the affinity mask for the ++ * task, so override it based on its cpuset hierarchy. ++ */ ++ cpuset_cpus_allowed(p, new_mask); ++ override_mask = new_mask; ++ ++out_set_mask: ++ if (printk_ratelimit()) { ++ printk_deferred("Overriding affinity for process %d (%s) to CPUs %*pbl\n", ++ task_pid_nr(p), p->comm, ++ cpumask_pr_args(override_mask)); ++ } ++ ++ WARN_ON(set_cpus_allowed_ptr(p, override_mask)); ++out_free_mask: ++ cpus_read_unlock(); ++ free_cpumask_var(new_mask); ++} ++ ++/* ++ * Restore the affinity of a task @p which was previously restricted by a ++ * call to force_compatible_cpus_allowed_ptr(). ++ * ++ * It is the caller's responsibility to serialise this with any calls to ++ * force_compatible_cpus_allowed_ptr(@p). ++ */ ++void relax_compatible_cpus_allowed_ptr(struct task_struct *p) ++{ ++ struct affinity_context ac = { ++ .new_mask = task_user_cpus(p), ++ .flags = 0, ++ }; ++ int ret; ++ ++ /* ++ * Try to restore the old affinity mask with __sched_setaffinity(). ++ * Cpuset masking will be done there too. ++ */ ++ ret = __sched_setaffinity(p, &ac); ++ WARN_ON_ONCE(ret); ++} ++ ++static void ++ttwu_stat(struct task_struct *p, int cpu, int wake_flags) ++{ ++ struct rq *rq; ++ ++ if (!schedstat_enabled()) ++ return; ++ ++ rq = this_rq(); ++ ++ if (cpu == rq->cpu) { ++ __schedstat_inc(rq->ttwu_local); ++ __schedstat_inc(p->stats.nr_wakeups_local); ++ } else { ++ /** Alt schedule FW ToDo: ++ * How to do ttwu_wake_remote ++ */ ++ } ++ ++ __schedstat_inc(rq->ttwu_count); ++ __schedstat_inc(p->stats.nr_wakeups); ++} ++ ++/* ++ * Mark the task runnable. ++ */ ++static inline void ttwu_do_wakeup(struct task_struct *p) ++{ ++ p->is_blocked = 0; ++ WRITE_ONCE(p->__state, TASK_RUNNING); ++ trace_sched_wakeup(p); ++} ++ ++static inline void ++ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags) ++{ ++ int en_flags = ENQUEUE_WAKEUP; ++ ++ lockdep_assert_rq_held(rq); ++ ++ if (p->sched_contributes_to_load) ++ rq->nr_uninterruptible--; ++ ++ if (wake_flags & WF_MIGRATED) ++ en_flags |= ENQUEUE_MIGRATED; ++ else ++ if (p->in_iowait) { ++ delayacct_blkio_end(p); ++ atomic_dec(&task_rq(p)->nr_iowait); ++ } ++ ++ WRITE_ONCE(p->wake_start, rq->clock); ++ ++ activate_task(p, rq, en_flags); ++ wakeup_preempt(rq); ++ ++ ttwu_do_wakeup(p); ++} ++ ++/* ++ * Consider @p being inside a wait loop: ++ * ++ * for (;;) { ++ * set_current_state(TASK_UNINTERRUPTIBLE); ++ * ++ * if (CONDITION) ++ * break; ++ * ++ * schedule(); ++ * } ++ * __set_current_state(TASK_RUNNING); ++ * ++ * between set_current_state() and schedule(). In this case @p is still ++ * runnable, so all that needs doing is change p->state back to TASK_RUNNING in ++ * an atomic manner. ++ * ++ * By taking task_rq(p)->lock we serialize against schedule(), if @p->on_rq ++ * then schedule() must still happen and p->state can be changed to ++ * TASK_RUNNING. Otherwise we lost the race, schedule() has happened, and we ++ * need to do a full wakeup with enqueue. ++ * ++ * Returns: %true when the wakeup is done, ++ * %false otherwise. ++ */ ++static int ttwu_runnable(struct task_struct *p, int wake_flags) ++{ ++ struct rq *rq; ++ raw_spinlock_t *lock; ++ int ret = 0; ++ ++ rq = __task_access_lock(p, &lock); ++ if (task_on_rq_queued(p)) { ++ if (!task_on_cpu(task_rq(p), p)) { ++ /* ++ * When on_rq && !on_cpu the task is preempted, see if ++ * it should preempt the task that is current now. ++ */ ++ update_rq_clock(rq); ++ wakeup_preempt(rq); ++ } ++ ttwu_do_wakeup(p); ++ ret = 1; ++ } ++ __task_access_unlock(p, lock); ++ ++ return ret; ++} ++ ++void sched_ttwu_pending(void *arg) ++{ ++ struct llist_node *llist = arg; ++ struct rq *rq = this_rq(); ++ struct task_struct *p, *t; ++ struct rq_flags rf; ++ ++ if (!llist) ++ return; ++ ++ rq_lock_irqsave(rq, &rf); ++ update_rq_clock(rq); ++ ++ llist_for_each_entry_safe(p, t, llist, wake_entry.llist) { ++ if (WARN_ON_ONCE(p->on_cpu)) ++ smp_cond_load_acquire(&p->on_cpu, !VAL); ++ ++ if (WARN_ON_ONCE(task_cpu(p) != cpu_of(rq))) ++ set_task_cpu(p, cpu_of(rq)); ++ ++ ttwu_do_activate(rq, p, p->sched_remote_wakeup ? WF_MIGRATED : 0); ++ } ++ ++ /* ++ * Must be after enqueueing at least once task such that ++ * idle_cpu() does not observe a false-negative -- if it does, ++ * it is possible for select_idle_siblings() to stack a number ++ * of tasks on this CPU during that window. ++ * ++ * It is OK to clear ttwu_pending when another task pending. ++ * We will receive IPI after local IRQ enabled and then enqueue it. ++ * Since now nr_running > 0, idle_cpu() will always get correct result. ++ */ ++ WRITE_ONCE(rq->ttwu_pending, 0); ++ rq_unlock_irqrestore(rq, &rf); ++} ++ ++/* ++ * Prepare the scene for sending an IPI for a remote smp_call ++ * ++ * Returns true if the caller can proceed with sending the IPI. ++ * Returns false otherwise. ++ */ ++bool call_function_single_prep_ipi(int cpu) ++{ ++ if (set_nr_if_polling(cpu_rq(cpu)->idle)) { ++ trace_sched_wake_idle_without_ipi(cpu); ++ return false; ++ } ++ ++ return true; ++} ++ ++/* ++ * Queue a task on the target CPUs wake_list and wake the CPU via IPI if ++ * necessary. The wakee CPU on receipt of the IPI will queue the task ++ * via sched_ttwu_wakeup() for activation so the wakee incurs the cost ++ * of the wakeup instead of the waker. ++ */ ++static void __ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags) ++{ ++ struct rq *rq = cpu_rq(cpu); ++ ++ p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED); ++ ++ WRITE_ONCE(rq->ttwu_pending, 1); ++#ifdef CONFIG_SMP ++ __smp_call_single_queue(cpu, &p->wake_entry.llist); ++#endif ++} ++ ++static inline bool ttwu_queue_cond(struct task_struct *p, int cpu) ++{ ++ int this_cpu = smp_processor_id(); ++ ++ if (p == cpu_rq(cpu)->stop) ++ return false; ++ ++ /* ++ * Do not complicate things with the async wake_list while the CPU is ++ * in hotplug state. ++ */ ++ if (!cpu_active(cpu)) ++ return false; ++ ++ /* Ensure the task will still be allowed to run on the CPU. */ ++ if (!cpumask_test_cpu(cpu, p->cpus_ptr)) ++ return false; ++ ++ /* ++ * If the CPU does not share cache, then queue the task on the ++ * remote rqs wakelist to avoid accessing remote data. ++ */ ++ if (!cpus_share_cache(this_cpu, cpu)) ++ return true; ++ ++ if (cpu == this_cpu) ++ return false; ++ ++ /* ++ * If the wakee cpu is idle, or the task is descheduling and the ++ * only running task on the CPU, then use the wakelist to offload ++ * the task activation to the idle (or soon-to-be-idle) CPU as ++ * the current CPU is likely busy. nr_running is checked to ++ * avoid unnecessary task stacking. ++ * ++ * Note that we can only get here with (wakee) p->on_rq=0, ++ * p->on_cpu can be whatever, we've done the dequeue, so ++ * the wakee has been accounted out of ->nr_running. ++ */ ++ if (!cpu_rq(cpu)->nr_running) ++ return true; ++ ++ return false; ++} ++ ++static bool ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags) ++{ ++ if (__is_defined(ALT_SCHED_TTWU_QUEUE) && ttwu_queue_cond(p, cpu)) { ++ sched_clock_cpu(cpu); /* Sync clocks across CPUs */ ++ __ttwu_queue_wakelist(p, cpu, wake_flags); ++ return true; ++ } ++ ++ return false; ++} ++ ++void wake_up_if_idle(int cpu) ++{ ++ struct rq *rq = cpu_rq(cpu); ++ ++ guard(rcu)(); ++ if (is_idle_task(rcu_dereference(rq->curr))) { ++ guard(rq_lock_irqsave)(rq); ++ if (is_idle_task(rq->curr)) ++ resched_curr(rq); ++ } ++} ++ ++extern struct static_key_false sched_asym_cpucapacity; ++ ++static __always_inline bool sched_asym_cpucap_active(void) ++{ ++ return static_branch_unlikely(&sched_asym_cpucapacity); ++} ++ ++bool cpus_equal_capacity(int this_cpu, int that_cpu) ++{ ++ if (!sched_asym_cpucap_active()) ++ return true; ++ ++ if (this_cpu == that_cpu) ++ return true; ++ ++ return arch_scale_cpu_capacity(this_cpu) == arch_scale_cpu_capacity(that_cpu); ++} ++ ++bool cpus_share_cache(int this_cpu, int that_cpu) ++{ ++ if (this_cpu == that_cpu) ++ return true; ++ ++ return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu); ++} ++ ++static inline void ttwu_queue(struct task_struct *p, int cpu, int wake_flags) ++{ ++ struct rq *rq = cpu_rq(cpu); ++ ++ if (ttwu_queue_wakelist(p, cpu, wake_flags)) ++ return; ++ ++ raw_spin_rq_lock(rq); ++ update_rq_clock(rq); ++ ttwu_do_activate(rq, p, wake_flags); ++ raw_spin_rq_unlock(rq); ++} ++ ++/* ++ * Invoked from try_to_wake_up() to check whether the task can be woken up. ++ * ++ * The caller holds p::pi_lock if p != current or has preemption ++ * disabled when p == current. ++ * ++ * The rules of saved_state: ++ * ++ * The related locking code always holds p::pi_lock when updating ++ * p::saved_state, which means the code is fully serialized in both cases. ++ * ++ * For PREEMPT_RT, the lock wait and lock wakeups happen via TASK_RTLOCK_WAIT. ++ * No other bits set. This allows to distinguish all wakeup scenarios. ++ * ++ * For FREEZER, the wakeup happens via TASK_FROZEN. No other bits set. This ++ * allows us to prevent early wakeup of tasks before they can be run on ++ * asymmetric ISA architectures (eg ARMv9). ++ */ ++static __always_inline ++bool ttwu_state_match(struct task_struct *p, unsigned int state, int *success) ++{ ++ int match; ++ ++ if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)) { ++ WARN_ON_ONCE((state & TASK_RTLOCK_WAIT) && ++ state != TASK_RTLOCK_WAIT); ++ } ++ ++ *success = !!(match = __task_state_match(p, state)); ++ ++ /* ++ * Saved state preserves the task state across blocking on ++ * an RT lock or TASK_FREEZABLE tasks. If the state matches, ++ * set p::saved_state to TASK_RUNNING, but do not wake the task ++ * because it waits for a lock wakeup or __thaw_task(). Also ++ * indicate success because from the regular waker's point of ++ * view this has succeeded. ++ * ++ * After acquiring the lock the task will restore p::__state ++ * from p::saved_state which ensures that the regular ++ * wakeup is not lost. The restore will also set ++ * p::saved_state to TASK_RUNNING so any further tests will ++ * not result in false positives vs. @success ++ */ ++ if (match < 0) ++ p->saved_state = TASK_RUNNING; ++ ++ return match > 0; ++} ++ ++/* ++ * Notes on Program-Order guarantees on SMP systems. ++ * ++ * MIGRATION ++ * ++ * The basic program-order guarantee on SMP systems is that when a task [t] ++ * migrates, all its activity on its old CPU [c0] happens-before any subsequent ++ * execution on its new CPU [c1]. ++ * ++ * For migration (of runnable tasks) this is provided by the following means: ++ * ++ * A) UNLOCK of the rq(c0)->lock scheduling out task t ++ * B) migration for t is required to synchronize *both* rq(c0)->lock and ++ * rq(c1)->lock (if not at the same time, then in that order). ++ * C) LOCK of the rq(c1)->lock scheduling in task ++ * ++ * Transitivity guarantees that B happens after A and C after B. ++ * Note: we only require RCpc transitivity. ++ * Note: the CPU doing B need not be c0 or c1 ++ * ++ * Example: ++ * ++ * CPU0 CPU1 CPU2 ++ * ++ * LOCK rq(0)->lock ++ * sched-out X ++ * sched-in Y ++ * UNLOCK rq(0)->lock ++ * ++ * LOCK rq(0)->lock // orders against CPU0 ++ * dequeue X ++ * UNLOCK rq(0)->lock ++ * ++ * LOCK rq(1)->lock ++ * enqueue X ++ * UNLOCK rq(1)->lock ++ * ++ * LOCK rq(1)->lock // orders against CPU2 ++ * sched-out Z ++ * sched-in X ++ * UNLOCK rq(1)->lock ++ * ++ * ++ * BLOCKING -- aka. SLEEP + WAKEUP ++ * ++ * For blocking we (obviously) need to provide the same guarantee as for ++ * migration. However the means are completely different as there is no lock ++ * chain to provide order. Instead we do: ++ * ++ * 1) smp_store_release(X->on_cpu, 0) -- finish_task() ++ * 2) smp_cond_load_acquire(!X->on_cpu) -- try_to_wake_up() ++ * ++ * Example: ++ * ++ * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule) ++ * ++ * LOCK rq(0)->lock LOCK X->pi_lock ++ * dequeue X ++ * sched-out X ++ * smp_store_release(X->on_cpu, 0); ++ * ++ * smp_cond_load_acquire(&X->on_cpu, !VAL); ++ * X->state = WAKING ++ * set_task_cpu(X,2) ++ * ++ * LOCK rq(2)->lock ++ * enqueue X ++ * X->state = RUNNING ++ * UNLOCK rq(2)->lock ++ * ++ * LOCK rq(2)->lock // orders against CPU1 ++ * sched-out Z ++ * sched-in X ++ * UNLOCK rq(2)->lock ++ * ++ * UNLOCK X->pi_lock ++ * UNLOCK rq(0)->lock ++ * ++ * ++ * However; for wakeups there is a second guarantee we must provide, namely we ++ * must observe the state that lead to our wakeup. That is, not only must our ++ * task observe its own prior state, it must also observe the stores prior to ++ * its wakeup. ++ * ++ * This means that any means of doing remote wakeups must order the CPU doing ++ * the wakeup against the CPU the task is going to end up running on. This, ++ * however, is already required for the regular Program-Order guarantee above, ++ * since the waking CPU is the one issueing the ACQUIRE (smp_cond_load_acquire). ++ * ++ */ ++ ++/** ++ * try_to_wake_up - wake up a thread ++ * @p: the thread to be awakened ++ * @state: the mask of task states that can be woken ++ * @wake_flags: wake modifier flags (WF_*) ++ * ++ * Conceptually does: ++ * ++ * If (@state & @p->state) @p->state = TASK_RUNNING. ++ * ++ * If the task was not queued/runnable, also place it back on a runqueue. ++ * ++ * This function is atomic against schedule() which would dequeue the task. ++ * ++ * It issues a full memory barrier before accessing @p->state, see the comment ++ * with set_current_state(). ++ * ++ * Uses p->pi_lock to serialize against concurrent wake-ups. ++ * ++ * Relies on p->pi_lock stabilizing: ++ * - p->sched_class ++ * - p->cpus_ptr ++ * - p->sched_task_group ++ * in order to do migration, see its use of select_task_rq()/set_task_cpu(). ++ * ++ * Tries really hard to only take one task_rq(p)->lock for performance. ++ * Takes rq->lock in: ++ * - ttwu_runnable() -- old rq, unavoidable, see comment there; ++ * - ttwu_queue() -- new rq, for enqueue of the task; ++ * - psi_ttwu_dequeue() -- much sadness :-( accounting will kill us. ++ * ++ * As a consequence we race really badly with just about everything. See the ++ * many memory barriers and their comments for details. ++ * ++ * Return: %true if @p->state changes (an actual wakeup was done), ++ * %false otherwise. ++ */ ++int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags) ++{ ++ guard(preempt)(); ++ int cpu, success = 0; ++ ++ wake_flags |= WF_TTWU; ++ ++ if (p == current) { ++ /* ++ * We're waking current, this means 'p->on_rq' and 'task_cpu(p) ++ * == smp_processor_id()'. Together this means we can special ++ * case the whole 'p->on_rq && ttwu_runnable()' case below ++ * without taking any locks. ++ * ++ * In particular: ++ * - we rely on Program-Order guarantees for all the ordering, ++ * - we're serialized against set_special_state() by virtue of ++ * it disabling IRQs (this allows not taking ->pi_lock). ++ */ ++ WARN_ON_ONCE(p->is_blocked); ++ if (!ttwu_state_match(p, state, &success)) ++ goto out; ++ ++ trace_sched_waking(p); ++ ttwu_do_wakeup(p); ++ goto out; ++ } ++ ++ /* ++ * If we are going to wake up a thread waiting for CONDITION we ++ * need to ensure that CONDITION=1 done by the caller can not be ++ * reordered with p->state check below. This pairs with smp_store_mb() ++ * in set_current_state() that the waiting thread does. ++ */ ++ scoped_guard (raw_spinlock_irqsave, &p->pi_lock) { ++ smp_mb__after_spinlock(); ++ if (!ttwu_state_match(p, state, &success)) ++ break; ++ ++ trace_sched_waking(p); ++ ++ /* ++ * Ensure we load p->on_rq _after_ p->state, otherwise it would ++ * be possible to, falsely, observe p->on_rq == 0 and get stuck ++ * in smp_cond_load_acquire() below. ++ * ++ * sched_ttwu_pending() try_to_wake_up() ++ * STORE p->on_rq = 1 LOAD p->state ++ * UNLOCK rq->lock ++ * ++ * __schedule() (switch to task 'p') ++ * LOCK rq->lock smp_rmb(); ++ * smp_mb__after_spinlock(); ++ * UNLOCK rq->lock ++ * ++ * [task p] ++ * STORE p->state = UNINTERRUPTIBLE LOAD p->on_rq ++ * ++ * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in ++ * __schedule(). See the comment for smp_mb__after_spinlock(). ++ * ++ * A similar smp_rmb() lives in __task_needs_rq_lock(). ++ */ ++ smp_rmb(); ++ if (READ_ONCE(p->on_rq) && ttwu_runnable(p, wake_flags)) ++ break; ++ ++ /* ++ * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be ++ * possible to, falsely, observe p->on_cpu == 0. ++ * ++ * One must be running (->on_cpu == 1) in order to remove oneself ++ * from the runqueue. ++ * ++ * __schedule() (switch to task 'p') try_to_wake_up() ++ * STORE p->on_cpu = 1 LOAD p->on_rq ++ * UNLOCK rq->lock ++ * ++ * __schedule() (put 'p' to sleep) ++ * LOCK rq->lock smp_rmb(); ++ * smp_mb__after_spinlock(); ++ * STORE p->on_rq = 0 LOAD p->on_cpu ++ * ++ * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in ++ * __schedule(). See the comment for smp_mb__after_spinlock(). ++ * ++ * Form a control-dep-acquire with p->on_rq == 0 above, to ensure ++ * schedule()'s block_task() has 'happened' and p will no longer ++ * care about it's own p->state. See the comment in __schedule(). ++ */ ++ smp_acquire__after_ctrl_dep(); ++ ++ /* ++ * We're doing the wakeup (@success == 1), they did a dequeue (p->on_rq ++ * == 0), which means we need to do an enqueue, change p->state to ++ * TASK_WAKING such that we can unlock p->pi_lock before doing the ++ * enqueue, such as ttwu_queue_wakelist(). ++ */ ++ WRITE_ONCE(p->__state, TASK_WAKING); ++ ++ /* ++ * If the owning (remote) CPU is still in the middle of schedule() with ++ * this task as prev, considering queueing p on the remote CPUs wake_list ++ * which potentially sends an IPI instead of spinning on p->on_cpu to ++ * let the waker make forward progress. This is safe because IRQs are ++ * disabled and the IPI will deliver after on_cpu is cleared. ++ * ++ * Ensure we load task_cpu(p) after p->on_cpu: ++ * ++ * set_task_cpu(p, cpu); ++ * STORE p->cpu = @cpu ++ * __schedule() (switch to task 'p') ++ * LOCK rq->lock ++ * smp_mb__after_spin_lock() smp_cond_load_acquire(&p->on_cpu) ++ * STORE p->on_cpu = 1 LOAD p->cpu ++ * ++ * to ensure we observe the correct CPU on which the task is currently ++ * scheduling. ++ */ ++ if (smp_load_acquire(&p->on_cpu) && ++ ttwu_queue_wakelist(p, task_cpu(p), wake_flags)) ++ break; ++ ++ /* ++ * If the owning (remote) CPU is still in the middle of schedule() with ++ * this task as prev, wait until it's done referencing the task. ++ * ++ * Pairs with the smp_store_release() in finish_task(). ++ * ++ * This ensures that tasks getting woken will be fully ordered against ++ * their previous state and preserve Program Order. ++ */ ++ smp_cond_load_acquire(&p->on_cpu, !VAL); ++ ++ sched_task_ttwu(p); ++ ++ cpu = select_task_rq(p, wake_flags); ++ ++ if (cpu != task_cpu(p)) { ++ if (p->in_iowait) { ++ delayacct_blkio_end(p); ++ atomic_dec(&task_rq(p)->nr_iowait); ++ } ++ ++ wake_flags |= WF_MIGRATED; ++ psi_ttwu_dequeue(p); ++ set_task_cpu(p, cpu); ++ } ++ ++ ttwu_queue(p, cpu, wake_flags); ++ } ++out: ++ if (success) ++ ttwu_stat(p, task_cpu(p), wake_flags); ++ ++ return success; ++} ++ ++static bool __task_needs_rq_lock(struct task_struct *p) ++{ ++ unsigned int state = READ_ONCE(p->__state); ++ ++ /* ++ * Since pi->lock blocks try_to_wake_up(), we don't need rq->lock when ++ * the task is blocked. Make sure to check @state since ttwu() can drop ++ * locks at the end, see ttwu_queue_wakelist(). ++ */ ++ if (state == TASK_RUNNING || state == TASK_WAKING) ++ return true; ++ ++ /* ++ * Ensure we load p->on_rq after p->__state, otherwise it would be ++ * possible to, falsely, observe p->on_rq == 0. ++ * ++ * See try_to_wake_up() for a longer comment. ++ */ ++ smp_rmb(); ++ if (p->on_rq) ++ return true; ++ ++ /* ++ * Ensure the task has finished __schedule() and will not be referenced ++ * anymore. Again, see try_to_wake_up() for a longer comment. ++ */ ++ smp_rmb(); ++ smp_cond_load_acquire(&p->on_cpu, !VAL); ++ ++ return false; ++} ++ ++/** ++ * task_call_func - Invoke a function on task in fixed state ++ * @p: Process for which the function is to be invoked, can be @current. ++ * @func: Function to invoke. ++ * @arg: Argument to function. ++ * ++ * Fix the task in it's current state by avoiding wakeups and or rq operations ++ * and call @func(@arg) on it. This function can use task_is_runnable() and ++ * task_curr() to work out what the state is, if required. Given that @func ++ * can be invoked with a runqueue lock held, it had better be quite ++ * lightweight. ++ * ++ * Returns: ++ * Whatever @func returns ++ */ ++int task_call_func(struct task_struct *p, task_call_f func, void *arg) ++{ ++ struct rq_flags rf; ++ int ret; ++ ++ raw_spin_lock_irqsave(&p->pi_lock, rf.flags); ++ ++ if (__task_needs_rq_lock(p)) { ++ struct rq *rq = __task_rq_lock(p, &rf); ++ ++ /* ++ * At this point the task is pinned; either: ++ * - blocked and we're holding off wakeups (pi->lock) ++ * - woken, and we're holding off enqueue (rq->lock) ++ * - queued, and we're holding off schedule (rq->lock) ++ * - running, and we're holding off de-schedule (rq->lock) ++ * ++ * The called function (@func) can use: task_curr(), p->on_rq and ++ * p->__state to differentiate between these states. ++ */ ++ ret = func(p, arg); ++ ++ __task_rq_unlock(rq, p, &rf); ++ } else { ++ ret = func(p, arg); ++ } ++ ++ raw_spin_unlock_irqrestore(&p->pi_lock, rf.flags); ++ return ret; ++} ++ ++/** ++ * cpu_curr_snapshot - Return a snapshot of the currently running task ++ * @cpu: The CPU on which to snapshot the task. ++ * ++ * Returns the task_struct pointer of the task "currently" running on ++ * the specified CPU. ++ * ++ * If the specified CPU was offline, the return value is whatever it ++ * is, perhaps a pointer to the task_struct structure of that CPU's idle ++ * task, but there is no guarantee. Callers wishing a useful return ++ * value must take some action to ensure that the specified CPU remains ++ * online throughout. ++ * ++ * This function executes full memory barriers before and after fetching ++ * the pointer, which permits the caller to confine this function's fetch ++ * with respect to the caller's accesses to other shared variables. ++ */ ++struct task_struct *cpu_curr_snapshot(int cpu) ++{ ++ struct rq *rq = cpu_rq(cpu); ++ struct task_struct *t; ++ struct rq_flags rf; ++ ++ rq_lock_irqsave(rq, &rf); ++ smp_mb__after_spinlock(); /* Pairing determined by caller's synchronization design. */ ++ t = rcu_dereference(cpu_curr(cpu)); ++ rq_unlock_irqrestore(rq, &rf); ++ smp_mb(); /* Pairing determined by caller's synchronization design. */ ++ ++ return t; ++} ++ ++/** ++ * wake_up_process - Wake up a specific process ++ * @p: The process to be woken up. ++ * ++ * Attempt to wake up the nominated process and move it to the set of runnable ++ * processes. ++ * ++ * Return: 1 if the process was woken up, 0 if it was already running. ++ * ++ * This function executes a full memory barrier before accessing the task state. ++ */ ++int wake_up_process(struct task_struct *p) ++{ ++ return try_to_wake_up(p, TASK_NORMAL, 0); ++} ++EXPORT_SYMBOL(wake_up_process); ++ ++int wake_up_state(struct task_struct *p, unsigned int state) ++{ ++ return try_to_wake_up(p, state, 0); ++} ++ ++/* ++ * Perform scheduler related setup for a newly forked process p. ++ * p is forked by current. ++ * ++ * __sched_fork() is basic setup which is also used by sched_init() to ++ * initialize the boot CPU's idle task. ++ */ ++static inline void __sched_fork(u64 clone_flags, struct task_struct *p) ++{ ++ p->on_rq = 0; ++ p->on_cpu = 0; ++ p->utime = 0; ++ p->stime = 0; ++ p->sched_time = 0; ++ ++ WARN_ON_ONCE(p->is_blocked); ++ ++#ifdef CONFIG_SCHEDSTATS ++ /* Even if schedstat is disabled, there should not be garbage */ ++ memset(&p->stats, 0, sizeof(p->stats)); ++#endif ++ ++#ifdef CONFIG_PREEMPT_NOTIFIERS ++ INIT_HLIST_HEAD(&p->preempt_notifiers); ++#endif ++ ++#ifdef CONFIG_COMPACTION ++ p->capture_control = NULL; ++#endif ++ p->wake_entry.u_flags = CSD_TYPE_TTWU; ++} ++ ++/* ++ * fork()/clone()-time setup: ++ */ ++int sched_fork(u64 clone_flags, struct task_struct *p) ++{ ++ __sched_fork(clone_flags, p); ++ /* ++ * We mark the process as NEW here. This guarantees that ++ * nobody will actually run it, and a signal or other external ++ * event cannot wake it up and insert it on the runqueue either. ++ */ ++ p->__state = TASK_NEW; ++ ++ /* ++ * Make sure we do not leak PI boosting priority to the child. ++ */ ++ p->prio = current->normal_prio; ++ ++ /* ++ * Revert to default priority/policy on fork if requested. ++ */ ++ if (unlikely(p->sched_reset_on_fork)) { ++ if (task_has_rt_policy(p)) { ++ p->policy = SCHED_NORMAL; ++ p->static_prio = NICE_TO_PRIO(0); ++ p->rt_priority = 0; ++ p->timer_slack_ns = p->default_timer_slack_ns; ++ } else if (PRIO_TO_NICE(p->static_prio) < 0) ++ p->static_prio = NICE_TO_PRIO(0); ++ ++ p->prio = p->normal_prio = p->static_prio; ++ ++ /* ++ * We don't need the reset flag anymore after the fork. It has ++ * fulfilled its duty: ++ */ ++ p->sched_reset_on_fork = 0; ++ } ++ ++#ifdef CONFIG_SCHED_INFO ++ if (likely(sched_info_on())) ++ memset(&p->sched_info, 0, sizeof(p->sched_info)); ++#endif ++ init_task_preempt_count(p); ++ ++ return 0; ++} ++ ++static __always_inline void update_curr(struct rq *rq, struct task_struct *p); ++ ++int sched_cgroup_fork(struct task_struct *p, struct kernel_clone_args *kargs) ++{ ++ unsigned long flags; ++ struct rq *rq; ++ ++ /* ++ * Because we're not yet on the pid-hash, p->pi_lock isn't strictly ++ * required yet, but lockdep gets upset if rules are violated. ++ */ ++ raw_spin_lock_irqsave(&p->pi_lock, flags); ++ /* ++ * Share the timeslice between parent and child, thus the ++ * total amount of pending timeslices in the system doesn't change, ++ * resulting in more scheduling fairness. ++ */ ++ rq = this_rq(); ++ raw_spin_rq_lock(rq); ++ ++ update_rq_clock(rq); ++ update_curr(rq, rq->curr); ++ ++ rq->curr->time_slice /= 2; ++ p->time_slice = rq->curr->time_slice; ++ ++ if (p->time_slice < RESCHED_NS) { ++ p->time_slice = sysctl_sched_base_slice; ++ resched_curr(rq); ++ } else { ++ hrtick_start(rq, rq->curr->time_slice); ++ } ++ sched_task_fork(p, rq); ++ raw_spin_rq_unlock(rq); ++ ++ /* ++ * We're setting the CPU for the first time, we don't migrate, ++ * so use __set_task_cpu(). ++ */ ++ __set_task_cpu(p, smp_processor_id()); ++ raw_spin_unlock_irqrestore(&p->pi_lock, flags); ++ ++ return 0; ++} ++ ++void sched_cancel_fork(struct task_struct *p) ++{ ++} ++ ++static void sched_mm_cid_fork(struct task_struct *t); ++ ++void sched_post_fork(struct task_struct *p) ++{ ++ sched_mm_cid_fork(p); ++} ++ ++#ifdef CONFIG_SCHEDSTATS ++ ++DEFINE_STATIC_KEY_FALSE(sched_schedstats); ++ ++static void set_schedstats(bool enabled) ++{ ++ if (enabled) ++ static_branch_enable(&sched_schedstats); ++ else ++ static_branch_disable(&sched_schedstats); ++} ++ ++void force_schedstat_enabled(void) ++{ ++ if (!schedstat_enabled()) { ++ pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n"); ++ static_branch_enable(&sched_schedstats); ++ } ++} ++ ++static int __init setup_schedstats(char *str) ++{ ++ int ret = 0; ++ if (!str) ++ goto out; ++ ++ if (!strcmp(str, "enable")) { ++ set_schedstats(true); ++ ret = 1; ++ } else if (!strcmp(str, "disable")) { ++ set_schedstats(false); ++ ret = 1; ++ } ++out: ++ if (!ret) ++ pr_warn("Unable to parse schedstats=\n"); ++ ++ return ret; ++} ++__setup("schedstats=", setup_schedstats); ++ ++#ifdef CONFIG_SYSCTL ++static int sysctl_schedstats(const struct ctl_table *table, int write, void *buffer, ++ size_t *lenp, loff_t *ppos) ++{ ++ struct ctl_table t; ++ int err; ++ int state = static_branch_likely(&sched_schedstats); ++ ++ if (write && !capable(CAP_SYS_ADMIN)) ++ return -EPERM; ++ ++ t = *table; ++ t.data = &state; ++ err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos); ++ if (err < 0) ++ return err; ++ if (write) ++ set_schedstats(state); ++ return err; ++} ++#endif /* CONFIG_SYSCTL */ ++#endif /* CONFIG_SCHEDSTATS */ ++ ++#ifdef CONFIG_SYSCTL ++static const struct ctl_table sched_core_sysctls[] = { ++#ifdef CONFIG_SCHEDSTATS ++ { ++ .procname = "sched_schedstats", ++ .data = NULL, ++ .maxlen = sizeof(unsigned int), ++ .mode = 0644, ++ .proc_handler = sysctl_schedstats, ++ .extra1 = SYSCTL_ZERO, ++ .extra2 = SYSCTL_ONE, ++ }, ++#endif /* CONFIG_SCHEDSTATS */ ++}; ++static int __init sched_core_sysctl_init(void) ++{ ++ register_sysctl_init("kernel", sched_core_sysctls); ++ return 0; ++} ++late_initcall(sched_core_sysctl_init); ++#endif /* CONFIG_SYSCTL */ ++ ++/* ++ * wake_up_new_task - wake up a newly created task for the first time. ++ * ++ * This function will do some initial scheduler statistics housekeeping ++ * that must be done for every newly created context, then puts the task ++ * on the runqueue and wakes it. ++ */ ++void wake_up_new_task(struct task_struct *p) ++{ ++ unsigned long flags; ++ struct rq *rq; ++ ++ raw_spin_lock_irqsave(&p->pi_lock, flags); ++ WRITE_ONCE(p->__state, TASK_RUNNING); ++ rq = cpu_rq(select_task_rq(p, 0)); ++ /* ++ * Fork balancing, do it here and not earlier because: ++ * - cpus_ptr can change in the fork path ++ * - any previously selected CPU might disappear through hotplug ++ * ++ * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq, ++ * as we're not fully set-up yet. ++ */ ++ __set_task_cpu(p, cpu_of(rq)); ++ ++ raw_spin_rq_lock(rq); ++ update_rq_clock(rq); ++ ++ activate_task(p, rq, ENQUEUE_INITIAL); ++ trace_sched_wakeup_new(p); ++ wakeup_preempt(rq); ++ ++ raw_spin_rq_unlock(rq); ++ raw_spin_unlock_irqrestore(&p->pi_lock, flags); ++} ++ ++#ifdef CONFIG_PREEMPT_NOTIFIERS ++ ++static DEFINE_STATIC_KEY_FALSE(preempt_notifier_key); ++ ++void preempt_notifier_inc(void) ++{ ++ static_branch_inc(&preempt_notifier_key); ++} ++EXPORT_SYMBOL_GPL(preempt_notifier_inc); ++ ++void preempt_notifier_dec(void) ++{ ++ static_branch_dec(&preempt_notifier_key); ++} ++EXPORT_SYMBOL_GPL(preempt_notifier_dec); ++ ++/** ++ * preempt_notifier_register - tell me when current is being preempted & rescheduled ++ * @notifier: notifier struct to register ++ */ ++void preempt_notifier_register(struct preempt_notifier *notifier) ++{ ++ if (!static_branch_unlikely(&preempt_notifier_key)) ++ WARN(1, "registering preempt_notifier while notifiers disabled\n"); ++ ++ hlist_add_head(¬ifier->link, ¤t->preempt_notifiers); ++} ++EXPORT_SYMBOL_GPL(preempt_notifier_register); ++ ++/** ++ * preempt_notifier_unregister - no longer interested in preemption notifications ++ * @notifier: notifier struct to unregister ++ * ++ * This is *not* safe to call from within a preemption notifier. ++ */ ++void preempt_notifier_unregister(struct preempt_notifier *notifier) ++{ ++ hlist_del(¬ifier->link); ++} ++EXPORT_SYMBOL_GPL(preempt_notifier_unregister); ++ ++static void __fire_sched_in_preempt_notifiers(struct task_struct *curr) ++{ ++ struct preempt_notifier *notifier; ++ ++ hlist_for_each_entry(notifier, &curr->preempt_notifiers, link) ++ notifier->ops->sched_in(notifier, raw_smp_processor_id()); ++} ++ ++static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr) ++{ ++ if (static_branch_unlikely(&preempt_notifier_key)) ++ __fire_sched_in_preempt_notifiers(curr); ++} ++ ++static void ++__fire_sched_out_preempt_notifiers(struct task_struct *curr, ++ struct task_struct *next) ++{ ++ struct preempt_notifier *notifier; ++ ++ hlist_for_each_entry(notifier, &curr->preempt_notifiers, link) ++ notifier->ops->sched_out(notifier, next); ++} ++ ++static __always_inline void ++fire_sched_out_preempt_notifiers(struct task_struct *curr, ++ struct task_struct *next) ++{ ++ if (static_branch_unlikely(&preempt_notifier_key)) ++ __fire_sched_out_preempt_notifiers(curr, next); ++} ++ ++#else /* !CONFIG_PREEMPT_NOTIFIERS: */ ++ ++static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr) ++{ ++} ++ ++static inline void ++fire_sched_out_preempt_notifiers(struct task_struct *curr, ++ struct task_struct *next) ++{ ++} ++ ++#endif /* !CONFIG_PREEMPT_NOTIFIERS */ ++ ++static inline void prepare_task(struct task_struct *next) ++{ ++ /* ++ * Claim the task as running, we do this before switching to it ++ * such that any running task will have this set. ++ * ++ * See the smp_load_acquire(&p->on_cpu) case in ttwu() and ++ * its ordering comment. ++ */ ++ WRITE_ONCE(next->on_cpu, 1); ++} ++ ++static __always_inline void finish_task(struct task_struct *prev) ++{ ++ /* ++ * This must be the very last reference to @prev from this CPU. After ++ * p->on_cpu is cleared, the task can be moved to a different CPU. We ++ * must ensure this doesn't happen until the switch is completely ++ * finished. ++ * ++ * In particular, the load of prev->state in finish_task_switch() must ++ * happen before this. ++ * ++ * Pairs with the smp_cond_load_acquire() in try_to_wake_up(). ++ */ ++ smp_store_release(&prev->on_cpu, 0); ++} ++ ++static __always_inline void do_balance_callbacks(struct rq *rq, struct balance_callback *head) ++{ ++ void (*func)(struct rq *rq); ++ struct balance_callback *next; ++ ++ lockdep_assert_rq_held(rq); ++ ++ while (head) { ++ func = (void (*)(struct rq *))head->func; ++ next = head->next; ++ head->next = NULL; ++ head = next; ++ ++ func(rq); ++ } ++} ++ ++static void balance_push(struct rq *rq); ++ ++/* ++ * balance_push_callback is a right abuse of the callback interface and plays ++ * by significantly different rules. ++ * ++ * Where the normal balance_callback's purpose is to be ran in the same context ++ * that queued it (only later, when it's safe to drop rq->lock again), ++ * balance_push_callback is specifically targeted at __schedule(). ++ * ++ * This abuse is tolerated because it places all the unlikely/odd cases behind ++ * a single test, namely: rq->balance_callback == NULL. ++ */ ++struct balance_callback balance_push_callback = { ++ .next = NULL, ++ .func = balance_push, ++}; ++ ++static __always_inline struct balance_callback * ++__splice_balance_callbacks(struct rq *rq, bool split) ++{ ++ struct balance_callback *head = rq->balance_callback; ++ ++ if (likely(!head)) ++ return NULL; ++ ++ lockdep_assert_rq_held(rq); ++ /* ++ * Must not take balance_push_callback off the list when ++ * splice_balance_callbacks() and balance_callbacks() are not ++ * in the same rq->lock section. ++ * ++ * In that case it would be possible for __schedule() to interleave ++ * and observe the list empty. ++ */ ++ if (split && head == &balance_push_callback) ++ head = NULL; ++ else ++ rq->balance_callback = NULL; ++ ++ return head; ++} ++ ++struct balance_callback *splice_balance_callbacks(struct rq *rq) ++{ ++ return __splice_balance_callbacks(rq, true); ++} ++ ++__always_inline void __balance_callbacks(struct rq *rq, struct rq_flags *rf) ++{ ++ if (rf) ++ rq_unpin_lock(rq, rf); ++ do_balance_callbacks(rq, __splice_balance_callbacks(rq, false)); ++ if (rf) ++ rq_repin_lock(rq, rf); ++} ++ ++void balance_callbacks(struct rq *rq, struct balance_callback *head) ++{ ++ unsigned long flags; ++ ++ if (unlikely(head)) { ++ raw_spin_rq_lock_irqsave(rq, flags); ++ do_balance_callbacks(rq, head); ++ raw_spin_rq_unlock_irqrestore(rq, flags); ++ } ++} ++ ++static inline void ++prepare_lock_switch(struct rq *rq, struct task_struct *next, ++ struct rq_flags *rf) ++ __releases(__rq_lockp(rq)) ++ __acquires(__rq_lockp(this_rq())) ++{ ++ /* ++ * Since the runqueue lock will be released by the next ++ * task (which is an invalid locking op but in the case ++ * of the scheduler it's an obvious special-case), so we ++ * do an early lockdep release here: ++ */ ++ rq_unpin_lock(rq, rf); ++ spin_release(&__rq_lockp(rq)->dep_map, _THIS_IP_); ++#ifdef CONFIG_DEBUG_SPINLOCK ++ /* this is a valid case when another task releases the spinlock */ ++ rq_lockp(rq)->owner = next; ++#endif ++ /* ++ * Model the rq reference switcheroo. ++ */ ++ __release(__rq_lockp(rq)); ++ __acquire(__rq_lockp(this_rq())); ++} ++ ++static __always_inline void finish_lock_switch(struct rq *rq) ++ __releases(__rq_lockp(rq)) ++{ ++ /* ++ * If we are tracking spinlock dependencies then we have to ++ * fix up the runqueue lock - which gets 'carried over' from ++ * prev into current: ++ */ ++ spin_acquire(&__rq_lockp(rq)->dep_map, 0, 0, _THIS_IP_); ++ __balance_callbacks(rq, NULL); ++ hrtick_schedule_exit(rq); ++ raw_spin_rq_unlock_irq(rq); ++} ++ ++/* ++ * NOP if the arch has not defined these: ++ */ ++ ++#ifndef prepare_arch_switch ++# define prepare_arch_switch(next) do { } while (0) ++#endif ++ ++#ifndef finish_arch_post_lock_switch ++# define finish_arch_post_lock_switch() do { } while (0) ++#endif ++ ++static inline void kmap_local_sched_out(void) ++{ ++#ifdef CONFIG_KMAP_LOCAL ++ if (unlikely(current->kmap_ctrl.idx)) ++ __kmap_local_sched_out(); ++#endif ++} ++ ++static __always_inline void kmap_local_sched_in(void) ++{ ++#ifdef CONFIG_KMAP_LOCAL ++ if (unlikely(current->kmap_ctrl.idx)) ++ __kmap_local_sched_in(); ++#endif ++} ++ ++/** ++ * prepare_task_switch - prepare to switch tasks ++ * @rq: the runqueue preparing to switch ++ * @next: the task we are going to switch to. ++ * ++ * This is called with the rq lock held and interrupts off. It must ++ * be paired with a subsequent finish_task_switch after the context ++ * switch. ++ * ++ * prepare_task_switch sets up locking and calls architecture specific ++ * hooks. ++ */ ++static inline void ++prepare_task_switch(struct rq *rq, struct task_struct *prev, ++ struct task_struct *next) ++ __must_hold(__rq_lockp(rq)) ++{ ++ kcov_prepare_switch(prev); ++ sched_info_switch(rq, prev, next); ++ perf_event_task_sched_out(prev, next); ++ fire_sched_out_preempt_notifiers(prev, next); ++ kmap_local_sched_out(); ++ prepare_task(next); ++ prepare_arch_switch(next); ++} ++ ++/** ++ * finish_task_switch - clean up after a task-switch ++ * @rq: runqueue associated with task-switch ++ * @prev: the thread we just switched away from. ++ * ++ * finish_task_switch must be called after the context switch, paired ++ * with a prepare_task_switch call before the context switch. ++ * finish_task_switch will reconcile locking set up by prepare_task_switch, ++ * and do any other architecture-specific cleanup actions. ++ * ++ * Note that we may have delayed dropping an mm in context_switch(). If ++ * so, we finish that here outside of the runqueue lock. (Doing it ++ * with the lock held can cause deadlocks; see schedule() for ++ * details.) ++ * ++ * The context switch have flipped the stack from under us and restored the ++ * local variables which were saved when this task called schedule() in the ++ * past. 'prev == current' is still correct but we need to recalculate this_rq ++ * because prev may have moved to another CPU. ++ */ ++static __always_inline struct rq *finish_task_switch(struct task_struct *prev) ++ __releases(__rq_lockp(this_rq())) ++{ ++ struct rq *rq = this_rq(); ++ struct mm_struct *mm = rq->prev_mm; ++ unsigned int prev_state; ++ ++ /* ++ * The previous task will have left us with a preempt_count of 2 ++ * because it left us after: ++ * ++ * schedule() ++ * preempt_disable(); // 1 ++ * __schedule() ++ * raw_spin_lock_irq(&rq->lock) // 2 ++ * ++ * Also, see FORK_PREEMPT_COUNT. ++ */ ++ if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET, ++ "corrupted preempt_count: %s/%d/0x%x\n", ++ current->comm, current->pid, preempt_count())) ++ preempt_count_set(FORK_PREEMPT_COUNT); ++ ++ rq->prev_mm = NULL; ++ ++ /* ++ * A task struct has one reference for the use as "current". ++ * If a task dies, then it sets TASK_DEAD in tsk->state and calls ++ * schedule one last time. The schedule call will never return, and ++ * the scheduled task must drop that reference. ++ * ++ * We must observe prev->state before clearing prev->on_cpu (in ++ * finish_task), otherwise a concurrent wakeup can get prev ++ * running on another CPU and we could rave with its RUNNING -> DEAD ++ * transition, resulting in a double drop. ++ */ ++ prev_state = READ_ONCE(prev->__state); ++ vtime_task_switch(prev); ++ perf_event_task_sched_in(prev, current); ++ finish_task(prev); ++ tick_nohz_task_switch(); ++ finish_lock_switch(rq); ++ finish_arch_post_lock_switch(); ++ kcov_finish_switch(current); ++ /* ++ * kmap_local_sched_out() is invoked with rq::lock held and ++ * interrupts disabled. There is no requirement for that, but the ++ * sched out code does not have an interrupt enabled section. ++ * Restoring the maps on sched in does not require interrupts being ++ * disabled either. ++ */ ++ kmap_local_sched_in(); ++ ++ /* ++ * Any cached block-layer timestamp (plug->cur_ktime) is stale now, ++ * invalidate it. ++ */ ++ blk_plug_invalidate_ts(); ++ ++ fire_sched_in_preempt_notifiers(current); ++ /* ++ * When switching through a kernel thread, the loop in ++ * membarrier_{private,global}_expedited() may have observed that ++ * kernel thread and not issued an IPI. It is therefore possible to ++ * schedule between user->kernel->user threads without passing though ++ * switch_mm(). Membarrier requires a barrier after storing to ++ * rq->curr, before returning to userspace, so provide them here: ++ * ++ * - a full memory barrier for {PRIVATE,GLOBAL}_EXPEDITED, implicitly ++ * provided by mmdrop_lazy_tlb(), ++ * - a sync_core for SYNC_CORE. ++ */ ++ if (mm) { ++ membarrier_mm_sync_core_before_usermode(mm); ++ mmdrop_lazy_tlb_sched(mm); ++ } ++ if (unlikely(prev_state == TASK_DEAD)) { ++ cgroup_task_dead(prev); ++ ++ /* Task is done with its stack. */ ++ put_task_stack(prev); ++ ++ put_task_struct_rcu_user(prev); ++ } ++ ++ return rq; ++} ++ ++/** ++ * schedule_tail - first thing a freshly forked thread must call. ++ * @prev: the thread we just switched away from. ++ */ ++asmlinkage __visible void schedule_tail(struct task_struct *prev) ++ __releases(__rq_lockp(this_rq())) ++{ ++ /* ++ * New tasks start with FORK_PREEMPT_COUNT, see there and ++ * finish_task_switch() for details. ++ * ++ * finish_task_switch() will drop rq->lock() and lower preempt_count ++ * and the preempt_enable() will end up enabling preemption (on ++ * PREEMPT_COUNT kernels). ++ */ ++ ++ finish_task_switch(prev); ++ /* ++ * This is a special case: the newly created task has just ++ * switched the context for the first time. It is returning from ++ * schedule for the first time in this path. ++ */ ++ trace_sched_exit_tp(true); ++ preempt_enable(); ++ ++ if (current->set_child_tid) ++ put_user(task_pid_vnr(current), current->set_child_tid); ++ ++ calculate_sigpending(); ++} ++ ++/* ++ * context_switch - switch to the new MM and the new thread's register state. ++ */ ++static __always_inline struct rq * ++context_switch(struct rq *rq, struct task_struct *prev, ++ struct task_struct *next, struct rq_flags *rf) ++ __releases(__rq_lockp(rq)) ++{ ++ prepare_task_switch(rq, prev, next); ++ ++ /* ++ * For paravirt, this is coupled with an exit in switch_to to ++ * combine the page table reload and the switch backend into ++ * one hypercall. ++ */ ++ arch_start_context_switch(prev); ++ ++ /* ++ * kernel -> kernel lazy + transfer active ++ * user -> kernel lazy + mmgrab_lazy_tlb() active ++ * ++ * kernel -> user switch + mmdrop_lazy_tlb() active ++ * user -> user switch ++ */ ++ if (!next->mm) { // to kernel ++ enter_lazy_tlb(prev->active_mm, next); ++ ++ next->active_mm = prev->active_mm; ++ if (prev->mm) // from user ++ mmgrab_lazy_tlb(prev->active_mm); ++ else ++ prev->active_mm = NULL; ++ } else { // to user ++ membarrier_switch_mm(rq, prev->active_mm, next->mm); ++ /* ++ * sys_membarrier() requires an smp_mb() between setting ++ * rq->curr / membarrier_switch_mm() and returning to userspace. ++ * ++ * The below provides this either through switch_mm(), or in ++ * case 'prev->active_mm == next->mm' through ++ * finish_task_switch()'s mmdrop(). ++ */ ++ switch_mm_irqs_off(prev->active_mm, next->mm, next); ++ lru_gen_use_mm(next->mm); ++ ++ if (!prev->mm) { // from kernel ++ /* will mmdrop_lazy_tlb() in finish_task_switch(). */ ++ rq->prev_mm = prev->active_mm; ++ prev->active_mm = NULL; ++ } ++ } ++ ++ mm_cid_switch_to(prev, next); ++ ++ /* ++ * Tell rseq that the task was scheduled in. Must be after ++ * switch_mm_cid() to get the TIF flag set. ++ */ ++ rseq_sched_switch_event(next); ++ ++ prepare_lock_switch(rq, next, rf); ++ ++ /* Here we just switch the register state and the stack. */ ++ switch_to(prev, next, prev); ++ barrier(); ++ ++ return finish_task_switch(prev); ++} ++ ++/* ++ * nr_running, nr_uninterruptible and nr_context_switches: ++ * ++ * externally visible scheduler statistics: current number of runnable ++ * threads, total number of context switches performed since bootup. ++ */ ++unsigned int nr_running(void) ++{ ++ unsigned int i, sum = 0; ++ ++ for_each_online_cpu(i) ++ sum += cpu_rq(i)->nr_running; ++ ++ return sum; ++} ++ ++/* ++ * Check if only the current task is running on the CPU. ++ * ++ * Caution: this function does not check that the caller has disabled ++ * preemption, thus the result might have a time-of-check-to-time-of-use ++ * race. The caller is responsible to use it correctly, for example: ++ * ++ * - from a non-preemptible section (of course) ++ * ++ * - from a thread that is bound to a single CPU ++ * ++ * - in a loop with very short iterations (e.g. a polling loop) ++ */ ++bool single_task_running(void) ++{ ++ return raw_rq()->nr_running == 1; ++} ++EXPORT_SYMBOL(single_task_running); ++ ++unsigned long long nr_context_switches_cpu(int cpu) ++{ ++ return cpu_rq(cpu)->nr_switches; ++} ++ ++unsigned long long nr_context_switches(void) ++{ ++ int i; ++ unsigned long long sum = 0; ++ ++ for_each_possible_cpu(i) ++ sum += cpu_rq(i)->nr_switches; ++ ++ return sum; ++} ++ ++/* ++ * Consumers of these two interfaces, like for example the cpuidle menu ++ * governor, are using nonsensical data. Preferring shallow idle state selection ++ * for a CPU that has IO-wait which might not even end up running the task when ++ * it does become runnable. ++ */ ++ ++unsigned int nr_iowait_cpu(int cpu) ++{ ++ return atomic_read(&cpu_rq(cpu)->nr_iowait); ++} ++ ++/* ++ * IO-wait accounting, and how it's mostly bollocks (on SMP). ++ * ++ * The idea behind IO-wait account is to account the idle time that we could ++ * have spend running if it were not for IO. That is, if we were to improve the ++ * storage performance, we'd have a proportional reduction in IO-wait time. ++ * ++ * This all works nicely on UP, where, when a task blocks on IO, we account ++ * idle time as IO-wait, because if the storage were faster, it could've been ++ * running and we'd not be idle. ++ * ++ * This has been extended to SMP, by doing the same for each CPU. This however ++ * is broken. ++ * ++ * Imagine for instance the case where two tasks block on one CPU, only the one ++ * CPU will have IO-wait accounted, while the other has regular idle. Even ++ * though, if the storage were faster, both could've ran at the same time, ++ * utilising both CPUs. ++ * ++ * This means, that when looking globally, the current IO-wait accounting on ++ * SMP is a lower bound, by reason of under accounting. ++ * ++ * Worse, since the numbers are provided per CPU, they are sometimes ++ * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly ++ * associated with any one particular CPU, it can wake to another CPU than it ++ * blocked on. This means the per CPU IO-wait number is meaningless. ++ * ++ * Task CPU affinities can make all that even more 'interesting'. ++ */ ++ ++unsigned int nr_iowait(void) ++{ ++ unsigned int i, sum = 0; ++ ++ for_each_possible_cpu(i) ++ sum += nr_iowait_cpu(i); ++ ++ return sum; ++} ++ ++/* ++ * sched_exec - execve() is a valuable balancing opportunity, because at ++ * this point the task has the smallest effective memory and cache ++ * footprint. ++ */ ++void sched_exec(void) ++{ ++} ++ ++DEFINE_PER_CPU(struct kernel_stat, kstat); ++DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat) = { ++#ifdef CONFIG_NO_HZ_COMMON ++ .idle_sleeptime_seq = SEQCNT_ZERO(kernel_cpustat.idle_sleeptime_seq) ++#endif ++}; ++ ++EXPORT_PER_CPU_SYMBOL(kstat); ++EXPORT_PER_CPU_SYMBOL(kernel_cpustat); ++ ++static __always_inline void update_curr(struct rq *rq, struct task_struct *p) ++{ ++ s64 ns = rq->clock_task - p->last_ran; ++ ++ if (unlikely(ns <= 0)) ++ return; ++ ++ p->sched_time += ns; ++ cgroup_account_cputime(p, ns); ++ account_group_exec_runtime(p, ns); ++ ++ if (SCHED_FIFO != p->policy) ++ p->time_slice -= ns; ++ p->last_ran = rq->clock_task; ++} ++ ++/* ++ * Return accounted runtime for the task. ++ * Return separately the current's pending runtime that have not been ++ * accounted yet. ++ */ ++unsigned long long task_sched_runtime(struct task_struct *p) ++{ ++ struct rq_flags rf; ++ struct rq *rq; ++ u64 ns; ++ ++#ifdef CONFIG_64BIT ++ /* ++ * 64-bit doesn't need locks to atomically read a 64-bit value. ++ * So we have a optimization chance when the task's delta_exec is 0. ++ * Reading ->on_cpu is racy, but this is OK. ++ * ++ * If we race with it leaving CPU, we'll take a lock. So we're correct. ++ * If we race with it entering CPU, unaccounted time is 0. This is ++ * indistinguishable from the read occurring a few cycles earlier. ++ * If we see ->on_cpu without ->on_rq, the task is leaving, and has ++ * been accounted, so we're correct here as well. ++ */ ++ if (!p->on_cpu || !task_on_rq_queued(p)) ++ return tsk_seruntime(p); ++#endif ++ ++ rq = task_rq_lock(p, &rf); ++ /* ++ * Must be ->curr _and_ ->on_rq. If dequeued, we would ++ * project cycles that may never be accounted to this ++ * thread, breaking clock_gettime(). ++ */ ++ if (p == rq->curr && task_on_rq_queued(p)) { ++ update_rq_clock(rq); ++ update_curr(rq, p); ++ } ++ ns = tsk_seruntime(p); ++ task_rq_unlock(rq, p, &rf); ++ ++ return ns; ++} ++ ++/* This manages tasks that have run out of timeslice during a scheduler_tick */ ++static inline void scheduler_task_tick(struct rq *rq) ++{ ++ struct task_struct *p = rq->curr; ++ ++ if (is_idle_task(p)) ++ return; ++ ++ update_curr(rq, p); ++ cpufreq_update_util(rq, 0); ++ ++ /* ++ * Tasks have less than RESCHED_NS of time slice left they will be ++ * rescheduled. ++ */ ++ if (p->time_slice >= RESCHED_NS) ++ return; ++ set_tsk_need_resched(p); ++ set_preempt_need_resched(); ++} ++ ++static u64 cpu_resched_latency(struct rq *rq) ++{ ++ int latency_warn_ms = READ_ONCE(sysctl_resched_latency_warn_ms); ++ u64 resched_latency, now = rq_clock(rq); ++ static bool warned_once; ++ ++ if (sysctl_resched_latency_warn_once && warned_once) ++ return 0; ++ ++ if (!need_resched() || !latency_warn_ms) ++ return 0; ++ ++ if (system_state == SYSTEM_BOOTING) ++ return 0; ++ ++ if (!rq->last_seen_need_resched_ns) { ++ rq->last_seen_need_resched_ns = now; ++ rq->ticks_without_resched = 0; ++ return 0; ++ } ++ ++ rq->ticks_without_resched++; ++ resched_latency = now - rq->last_seen_need_resched_ns; ++ if (resched_latency <= latency_warn_ms * NSEC_PER_MSEC) ++ return 0; ++ ++ warned_once = true; ++ ++ return resched_latency; ++} ++ ++static int __init setup_resched_latency_warn_ms(char *str) ++{ ++ long val; ++ ++ if ((kstrtol(str, 0, &val))) { ++ pr_warn("Unable to set resched_latency_warn_ms\n"); ++ return 1; ++ } ++ ++ sysctl_resched_latency_warn_ms = val; ++ return 1; ++} ++__setup("resched_latency_warn_ms=", setup_resched_latency_warn_ms); ++ ++#ifdef CONFIG_SCHED_SMT ++static void smt_balance_kick(struct rq *rq) ++{ ++ int cpu = cpu_of(rq), sibling, target; ++ struct rq *target_rq; ++ cpumask_t mask; ++ ++ if (rq->nr_running != 1 || cpumask_empty(sched_idle_mask) || ++ !cpumask_test_cpu(cpu, &sched_smt_mask)) ++ return; ++ ++ for_each_cpu_and(sibling, cpu_smt_mask(cpu), &sched_smt_mask) ++ if (sibling != cpu && ++ (cpumask_test_cpu(sibling, sched_idle_mask) || ++ cpumask_test_cpu(sibling, &sched_rq_pending_mask))) ++ return; ++ ++ cpumask_copy(&mask, sched_sg_idle_mask); ++ if (per_cpu(sched_cpu_topo, cpu) == CPU_TOPOLOGY_PCORE && ++ cpumask_empty(sched_pcore_idle_mask)) ++ cpumask_or(&mask, &mask, sched_ecore_idle_mask); ++ ++ /* ++ * Other CPUs can clear the last idle core while we hold only this ++ * rq's lock. Select from a nonempty snapshot, restricted to CPUs the ++ * task can use, rather than looking up a CPU in the live idle mask. ++ */ ++ if (!cpumask_and(&mask, &mask, rq->curr->cpus_ptr) || ++ !cpumask_and(&mask, &mask, cpu_active_mask)) ++ return; ++ ++ if (sched_smt_group_paired(rq, cpu)) ++ return; ++ ++ target = best_mask_cpu(cpu, &mask); ++ if (target >= nr_cpu_ids) ++ return; ++ ++ target_rq = cpu_rq(target); ++ if (raw_spin_rq_trylock(target_rq)) { ++ if (target_rq->online && idle_rq(target_rq) && ++ (cpumask_test_cpu(target, sched_sg_idle_mask) || ++ cpumask_test_cpu(target, sched_ecore_idle_mask))) { ++ /* ++ * The target queues its own callback in __schedule(), ++ * including the SM_IDLE fast path. Callbacks must not ++ * remain queued across an rq unlock/relock boundary. ++ */ ++ resched_curr(target_rq); ++ } ++ raw_spin_rq_unlock(target_rq); ++ } ++} ++#else ++static inline void smt_balance_kick(struct rq *rq) { } ++#endif ++ ++/* ++ * This function gets called by the timer code, with HZ frequency. ++ * We call it with interrupts disabled. ++ */ ++void sched_tick(void) ++{ ++ int cpu __maybe_unused = smp_processor_id(); ++ struct rq *rq = cpu_rq(cpu); ++ /* scheduler accounting goes to the donor task */ ++ struct task_struct *curr; ++ struct rq_flags rf; ++ u64 resched_latency; ++ ++ if (housekeeping_cpu(cpu, HK_TYPE_KERNEL_NOISE)) ++ arch_scale_freq_tick(); ++ ++ sched_clock_tick(); ++ ++ rq_lock(rq, &rf); ++ curr = rq->curr; ++ ++ psi_account_irqtime(rq, curr, NULL); ++ update_rq_clock(rq); ++ ++ if (dynamic_preempt_lazy() && tif_test_bit(TIF_NEED_RESCHED_LAZY)) ++ resched_curr(rq); ++ ++ scheduler_task_tick(rq); ++ smt_balance_kick(rq); ++ if (sched_feat(LATENCY_WARN)) ++ resched_latency = cpu_resched_latency(rq); ++ calc_global_load_tick(rq); ++ ++ rq_unlock(rq, &rf); ++ ++ if (sched_feat(LATENCY_WARN) && resched_latency) ++ resched_latency_warn(cpu, resched_latency); ++ ++ perf_event_task_tick(); ++ ++ if (curr->flags & PF_WQ_WORKER) ++ wq_worker_tick(curr); ++} ++ ++#ifdef CONFIG_NO_HZ_FULL ++ ++struct tick_work { ++ int cpu; ++ atomic_t state; ++ struct delayed_work work; ++}; ++/* Values for ->state, see diagram below. */ ++#define TICK_SCHED_REMOTE_OFFLINE 0 ++#define TICK_SCHED_REMOTE_OFFLINING 1 ++#define TICK_SCHED_REMOTE_RUNNING 2 ++ ++/* ++ * State diagram for ->state: ++ * ++ * ++ * TICK_SCHED_REMOTE_OFFLINE ++ * | ^ ++ * | | ++ * | | sched_tick_remote() ++ * | | ++ * | | ++ * +--TICK_SCHED_REMOTE_OFFLINING ++ * | ^ ++ * | | ++ * sched_tick_start() | | sched_tick_stop() ++ * | | ++ * V | ++ * TICK_SCHED_REMOTE_RUNNING ++ * ++ * ++ * Other transitions get WARN_ON_ONCE(), except that sched_tick_remote() ++ * and sched_tick_start() are happy to leave the state in RUNNING. ++ */ ++ ++static struct tick_work __percpu *tick_work_cpu; ++ ++static void sched_tick_remote(struct work_struct *work) ++{ ++ struct delayed_work *dwork = to_delayed_work(work); ++ struct tick_work *twork = container_of(dwork, struct tick_work, work); ++ int cpu = twork->cpu; ++ struct rq *rq = cpu_rq(cpu); ++ int os; ++ ++ /* ++ * Handle the tick only if it appears the remote CPU is running in full ++ * dynticks mode. The check is racy by nature, but missing a tick or ++ * having one too much is no big deal because the scheduler tick updates ++ * statistics and checks timeslices in a time-independent way, regardless ++ * of when exactly it is running. ++ */ ++ if (tick_nohz_tick_stopped_cpu(cpu)) { ++ guard(rq_lock_irq)(rq); ++ struct task_struct *curr = rq->curr; ++ ++ if (cpu_online(cpu)) { ++ update_rq_clock(rq); ++ ++ if (!is_idle_task(curr)) { ++ /* ++ * Make sure the next tick runs within a ++ * reasonable amount of time. ++ */ ++ u64 delta = rq_clock_task(rq) - curr->last_ran; ++ WARN_ON_ONCE(delta > (u64)NSEC_PER_SEC * 30); ++ } ++ scheduler_task_tick(rq); ++ smt_balance_kick(rq); ++ ++ calc_load_nohz_remote(rq); ++ } ++ } ++ ++ /* ++ * Run the remote tick once per second (1Hz). This arbitrary ++ * frequency is large enough to avoid overload but short enough ++ * to keep scheduler internal stats reasonably up to date. But ++ * first update state to reflect hotplug activity if required. ++ */ ++ os = atomic_fetch_add_unless(&twork->state, -1, TICK_SCHED_REMOTE_RUNNING); ++ WARN_ON_ONCE(os == TICK_SCHED_REMOTE_OFFLINE); ++ if (os == TICK_SCHED_REMOTE_RUNNING) ++ queue_delayed_work(system_dfl_wq, dwork, HZ); ++} ++ ++static void sched_tick_start(int cpu) ++{ ++ int os; ++ struct tick_work *twork; ++ ++ if (housekeeping_cpu(cpu, HK_TYPE_KERNEL_NOISE)) ++ return; ++ ++ WARN_ON_ONCE(!tick_work_cpu); ++ ++ twork = per_cpu_ptr(tick_work_cpu, cpu); ++ os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_RUNNING); ++ WARN_ON_ONCE(os == TICK_SCHED_REMOTE_RUNNING); ++ if (os == TICK_SCHED_REMOTE_OFFLINE) { ++ twork->cpu = cpu; ++ INIT_DELAYED_WORK(&twork->work, sched_tick_remote); ++ queue_delayed_work(system_dfl_wq, &twork->work, HZ); ++ } ++} ++ ++#ifdef CONFIG_HOTPLUG_CPU ++static void sched_tick_stop(int cpu) ++{ ++ struct tick_work *twork; ++ int os; ++ ++ if (housekeeping_cpu(cpu, HK_TYPE_KERNEL_NOISE)) ++ return; ++ ++ WARN_ON_ONCE(!tick_work_cpu); ++ ++ twork = per_cpu_ptr(tick_work_cpu, cpu); ++ /* There cannot be competing actions, but don't rely on stop-machine. */ ++ os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_OFFLINING); ++ WARN_ON_ONCE(os != TICK_SCHED_REMOTE_RUNNING); ++ /* Don't cancel, as this would mess up the state machine. */ ++} ++#endif /* CONFIG_HOTPLUG_CPU */ ++ ++int __init sched_tick_offload_init(void) ++{ ++ tick_work_cpu = alloc_percpu(struct tick_work); ++ BUG_ON(!tick_work_cpu); ++ return 0; ++} ++ ++#else /* !CONFIG_NO_HZ_FULL: */ ++static inline void sched_tick_start(int cpu) { } ++static inline void sched_tick_stop(int cpu) { } ++#endif /* !CONFIG_NO_HZ_FULL */ ++ ++#if defined(CONFIG_PREEMPTION) && (defined(CONFIG_DEBUG_PREEMPT) || \ ++ defined(CONFIG_PREEMPT_TRACER)) ++/* ++ * If the value passed in is equal to the current preempt count ++ * then we just disabled preemption. Start timing the latency. ++ */ ++static inline void preempt_latency_start(int val) ++{ ++ if (preempt_count() == val) { ++ unsigned long ip = get_lock_parent_ip(); ++#ifdef CONFIG_DEBUG_PREEMPT ++ current->preempt_disable_ip = ip; ++#endif ++ trace_preempt_off(CALLER_ADDR0, ip); ++ } ++} ++ ++void preempt_count_add(int val) ++{ ++#ifdef CONFIG_DEBUG_PREEMPT ++ /* ++ * Underflow? ++ * Cannot detect underflow based on the current preempt_count() value ++ * if using HAS_SEPARATE_PREEMPT_RESCHED_BITS because preempt count takes all 32 ++ * bits. ++ */ ++ if (!IS_ENABLED(CONFIG_HAS_SEPARATE_PREEMPT_RESCHED_BITS) && ++ DEBUG_LOCKS_WARN_ON((preempt_count() < 0))) ++ return; ++#endif ++ __preempt_count_add(val); ++#ifdef CONFIG_DEBUG_PREEMPT ++ /* ++ * Spinlock count overflowing soon? ++ */ ++ DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >= ++ PREEMPT_MASK - 10); ++#endif ++ preempt_latency_start(val); ++} ++EXPORT_SYMBOL(preempt_count_add); ++NOKPROBE_SYMBOL(preempt_count_add); ++ ++/* ++ * If the value passed in equals to the current preempt count ++ * then we just enabled preemption. Stop timing the latency. ++ */ ++static inline void preempt_latency_stop(int val) ++{ ++ if (preempt_count() == val) ++ trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip()); ++} ++ ++void preempt_count_sub(int val) ++{ ++#ifdef CONFIG_DEBUG_PREEMPT ++ /* ++ * Underflow? ++ */ ++ unsigned int uval = val; ++ unsigned int pc = preempt_count(); ++ ++ if (DEBUG_LOCKS_WARN_ON(pc - uval > pc)) ++ return; ++ /* ++ * Is the spinlock portion underflowing? ++ */ ++ if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) && ++ !(preempt_count() & PREEMPT_MASK))) ++ return; ++#endif ++ ++ preempt_latency_stop(val); ++ __preempt_count_sub(val); ++} ++EXPORT_SYMBOL(preempt_count_sub); ++NOKPROBE_SYMBOL(preempt_count_sub); ++ ++#else ++static inline void preempt_latency_start(int val) { } ++static inline void preempt_latency_stop(int val) { } ++#endif ++ ++static inline unsigned long get_preempt_disable_ip(struct task_struct *p) ++{ ++#ifdef CONFIG_DEBUG_PREEMPT ++ return p->preempt_disable_ip; ++#else ++ return 0; ++#endif ++} ++ ++/* ++ * Print scheduling while atomic bug: ++ */ ++static noinline void __schedule_bug(struct task_struct *prev) ++{ ++ /* Save this before calling printk(), since that will clobber it */ ++ unsigned long preempt_disable_ip = get_preempt_disable_ip(current); ++ ++ if (oops_in_progress) ++ return; ++ ++ printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n", ++ prev->comm, prev->pid, preempt_count()); ++ ++ debug_show_held_locks(prev); ++ print_modules(); ++ if (irqs_disabled()) ++ print_irqtrace_events(prev); ++ if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)) { ++ pr_err("Preemption disabled at:"); ++ print_ip_sym(KERN_ERR, preempt_disable_ip); ++ } ++ check_panic_on_warn("scheduling while atomic"); ++ ++ dump_stack(); ++ add_taint(TAINT_WARN, LOCKDEP_STILL_OK); ++} ++ ++/* ++ * Various schedule()-time debugging checks and statistics: ++ */ ++static inline void schedule_debug(struct task_struct *prev, bool preempt) ++{ ++#ifdef CONFIG_SCHED_STACK_END_CHECK ++ if (task_stack_end_corrupted(prev)) ++ panic("corrupted stack end detected inside scheduler\n"); ++ ++ if (task_scs_end_corrupted(prev)) ++ panic("corrupted shadow stack detected inside scheduler\n"); ++#endif ++ ++#ifdef CONFIG_DEBUG_ATOMIC_SLEEP ++ if (!preempt && READ_ONCE(prev->__state) && prev->non_block_count) { ++ printk(KERN_ERR "BUG: scheduling in a non-blocking section: %s/%d/%i\n", ++ prev->comm, prev->pid, prev->non_block_count); ++ dump_stack(); ++ add_taint(TAINT_WARN, LOCKDEP_STILL_OK); ++ } ++#endif ++ ++ if (unlikely(in_atomic_preempt_off())) { ++ __schedule_bug(prev); ++ preempt_count_set(PREEMPT_DISABLED); ++ } ++ rcu_sleep_check(); ++ WARN_ON_ONCE(ct_state() == CT_STATE_USER); ++ ++ profile_hit(SCHED_PROFILING, __builtin_return_address(0)); ++ ++ schedstat_inc(this_rq()->sched_count); ++} ++ ++#ifdef ALT_SCHED_DEBUG ++void alt_sched_debug(void) ++{ ++ pr_info("sched: pending: 0x%04lx, idle: 0x%04lx, sg_idle: 0x%04lx\n", ++ sched_rq_pending_mask.bits[0], ++ sched_idle_mask->bits[0], ++ sched_sg_idle_mask->bits[0]); ++ pr_info("sched: pcore_idle: 0x%04lx, ecore_idle: 0x%04lx\n", ++ sched_pcore_idle_mask->bits[0], ++ sched_ecore_idle_mask->bits[0]); ++} ++#endif ++ ++ ++#if defined(CONFIG_PREEMPT_RT) || defined(CONFIG_ZEN_INTERACTIVE) ++#define SCHED_NR_MIGRATE_BREAK 8 ++#else ++#define SCHED_NR_MIGRATE_BREAK 32 ++#endif ++ ++__read_mostly unsigned int sysctl_sched_nr_migrate = SCHED_NR_MIGRATE_BREAK; ++ ++/* ++ * Migrate pending tasks in @rq to @dest_cpu ++ */ ++static inline int ++migrate_pending_tasks(struct rq *rq, struct rq *dest_rq, const int dest_cpu) ++{ ++ struct task_struct *p, *skip = rq->curr; ++ int nr_migrated = 0; ++ int nr_tries = min(rq->nr_running / 2, sysctl_sched_nr_migrate); ++ ++ /* WA to check rq->curr is still on rq */ ++ if (!task_on_rq_queued(skip)) ++ return 0; ++ ++ while (skip != rq->idle && nr_tries && ++ (p = sched_rq_next_task(skip, rq)) != rq->idle) { ++ skip = sched_rq_next_task(p, rq); ++ if (cpumask_test_cpu(dest_cpu, p->cpus_ptr)) { ++ psi_dequeue(p, 0); ++ __SCHED_DEQUEUE_TASK(p, rq, ); ++ set_task_cpu(p, dest_cpu); ++ sched_task_sanity_check(p, dest_rq); ++ __SCHED_ENQUEUE_TASK(p, dest_rq, ); ++ psi_enqueue(p, ENQUEUE_MIGRATED); ++ nr_migrated++; ++ } ++ nr_tries--; ++ } ++ ++ return nr_migrated; ++} ++ ++static inline int take_other_rq_tasks(struct rq *rq, int cpu) ++{ ++ cpumask_t *topo_masks, *topo_mask, *end_mask, chk; ++ ++ if (unlikely(!rq->online)) ++ return 0; ++ ++ if (cpumask_empty(&sched_rq_pending_mask)) ++ return 0; ++ ++ topo_masks = per_cpu(sched_cpu_topo_masks, cpu); ++ topo_mask = topo_masks; ++ end_mask = per_cpu(sched_cpu_topo_end_mask, cpu); ++ do { ++ int i; ++ ++ if (sched_cpu_topo_level_repeats(topo_masks, topo_mask)) ++ continue; ++ ++ if (!cpumask_and(&chk, &sched_rq_pending_mask, topo_mask)) ++ continue; ++ ++ for_each_cpu_wrap(i, &chk, cpu) { ++ int nr_migrated; ++ struct rq *src_rq; ++ ++ src_rq = cpu_rq(i); ++ if (!do_raw_spin_trylock(rq_lockp(src_rq))) ++ continue; ++ spin_acquire(&rq_lockp(src_rq)->dep_map, ++ SINGLE_DEPTH_NESTING, 1, _RET_IP_); ++ ++ if ((nr_migrated = migrate_pending_tasks(src_rq, rq, cpu))) { ++ sub_nr_running(src_rq, nr_migrated); ++ update_sched_preempt_mask(src_rq); ++ ++ spin_release(&rq_lockp(src_rq)->dep_map, _RET_IP_); ++ do_raw_spin_unlock(rq_lockp(src_rq)); ++ ++ add_nr_running(rq, nr_migrated); ++ ++ update_sched_preempt_mask(rq); ++ cpufreq_update_util(rq, 0); ++ ++ return 1; ++ } ++ ++ spin_release(&rq_lockp(src_rq)->dep_map, _RET_IP_); ++ do_raw_spin_unlock(rq_lockp(src_rq)); ++ } ++ } while (++topo_mask < end_mask); ++ ++ return 0; ++} ++ ++static inline void time_slice_expired(struct task_struct *p, struct rq *rq) ++{ ++ p->time_slice = sysctl_sched_base_slice; ++ ++ sched_task_renew(p, rq); ++ ++ if (SCHED_FIFO != p->policy && task_on_rq_queued(p)) ++ requeue_task(p, rq, 0); ++} ++ ++static inline int balance_select_task_rq(struct task_struct *p, cpumask_t *avail_mask) ++{ ++ cpumask_t mask; ++ ++ if (!preempt_mask_check(&mask, avail_mask, task_sched_prio(p))) ++ return -1; ++ ++ if (cpumask_and(&mask, &mask, p->cpus_ptr)) ++ return best_mask_cpu(task_cpu(p), &mask); ++ ++ return task_cpu(p); ++} ++ ++static inline void ++__move_queued_task(struct rq *rq, struct task_struct *p, struct rq *dest_rq, int dest_cpu) ++{ ++ WRITE_ONCE(p->on_rq, TASK_ON_RQ_MIGRATING); ++ dequeue_task(p, rq, 0); ++ set_task_cpu(p, dest_cpu); ++ ++ sched_task_sanity_check(p, dest_rq); ++ enqueue_task(p, dest_rq, ENQUEUE_MIGRATED); ++ WRITE_ONCE(p->on_rq, TASK_ON_RQ_QUEUED); ++ wakeup_preempt(dest_rq); ++} ++ ++static inline void prio_balance(struct rq *rq, const int cpu) ++{ ++ struct task_struct *p, *next; ++ cpumask_t mask; ++ int nr_tries = min(rq->nr_running / 2, sysctl_sched_nr_migrate); ++ ++ if (!rq->online) ++ return; ++ ++ if (0 == rq->prio_balance_time) ++ return; ++ ++ if (rq->clock - rq->prio_balance_time < sysctl_sched_base_slice << 1) ++ return; ++ ++ if (!cpumask_empty(sched_idle_mask)) ++ return; ++ ++ rq->prio_balance_time = rq->clock; ++ ++ cpumask_copy(&mask, cpu_active_mask); ++ __cpumask_clear_cpu(cpu, &mask); ++ ++ p = sched_rq_next_task(rq->curr, rq); ++ while (p != rq->idle && nr_tries--) { ++ next = sched_rq_next_task(p, rq); ++ if (!is_migration_disabled(p)) { ++ int dest_cpu; ++ ++ dest_cpu = balance_select_task_rq(p, &mask); ++ if (dest_cpu < 0) ++ return; ++ ++ if (cpu != dest_cpu) { ++ struct rq *dest_rq = cpu_rq(dest_cpu); ++ ++ if (do_raw_spin_trylock(rq_lockp(dest_rq))) { ++ __cpumask_clear_cpu(dest_cpu, &mask); ++ ++ spin_acquire(&rq_lockp(dest_rq)->dep_map, ++ SINGLE_DEPTH_NESTING, 1, _RET_IP_); ++ ++ __move_queued_task(rq, p, dest_rq, dest_cpu); ++ ++ spin_release(&rq_lockp(dest_rq)->dep_map, _RET_IP_); ++ do_raw_spin_unlock(rq_lockp(dest_rq)); ++ } ++ } ++ } ++ p = next; ++ } ++} ++ ++/* ++ * Timeslices below RESCHED_NS are considered as good as expired as there's no ++ * point rescheduling when there's so little time left. ++ */ ++static inline void check_curr(struct task_struct *p, struct rq *rq) ++{ ++ if (unlikely(rq->idle == p)) ++ return; ++ ++ update_curr(rq, p); ++ ++ if (p->time_slice < RESCHED_NS) ++ time_slice_expired(p, rq); ++} ++ ++static inline struct task_struct * ++choose_next_task(struct rq *rq, int cpu) ++ __must_hold(__rq_lockp(rq)) ++{ ++ struct task_struct *next = sched_rq_first_task(rq); ++ ++ if (next == rq->idle) { ++ if (!take_other_rq_tasks(rq, cpu)) { ++ sched_cpu_topology_balance(cpu, rq); ++ ++ schedstat_inc(rq->sched_goidle); ++ /*printk(KERN_INFO "sched: choose_next_task(%d) idle %px\n", cpu, next);*/ ++ return next; ++ } ++ next = sched_rq_first_task(rq); ++ } ++ if (SCHED_FIFO != next->policy) ++ hrtick_start(rq, next->time_slice); ++ /*printk(KERN_INFO "sched: choose_next_task(%d) next %px\n", cpu, next);*/ ++ return next; ++} ++ ++/* ++ * Constants for the sched_mode argument of __schedule(). ++ * ++ * The mode argument allows RT enabled kernels to differentiate a ++ * preemption from blocking on an 'sleeping' spin/rwlock. ++ */ ++ #define SM_IDLE (-1) ++ #define SM_NONE 0 ++ #define SM_PREEMPT 1 ++ #define SM_RTLOCK_WAIT 2 ++ ++/* ++ * Helper function for __schedule() ++ * ++ * If a task does not have signals pending, deactivate it ++ * Otherwise marks the task's __state as RUNNING ++ */ ++static bool try_to_block_task(struct rq *rq, struct task_struct *p, ++ unsigned long *task_state_p) ++{ ++ unsigned long task_state = *task_state_p; ++ ++ WARN_ON_ONCE(p->is_blocked); ++ ++ if (signal_pending_state(task_state, p)) { ++ WRITE_ONCE(p->__state, TASK_RUNNING); ++ *task_state_p = TASK_RUNNING; ++ return false; ++ } ++ ++ p->is_blocked = 1; ++ ++ sched_task_deactivate(p, rq); ++ ++ block_task(rq, p, task_state); ++ ++ return true; ++} ++ ++/* ++ * schedule() is the main scheduler function. ++ * ++ * The main means of driving the scheduler and thus entering this function are: ++ * ++ * 1. Explicit blocking: mutex, semaphore, waitqueue, etc. ++ * ++ * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return ++ * paths. For example, see arch/x86/entry_64.S. ++ * ++ * To drive preemption between tasks, the scheduler sets the flag in timer ++ * interrupt handler sched_tick(). ++ * ++ * 3. Wakeups don't really cause entry into schedule(). They add a ++ * task to the run-queue and that's it. ++ * ++ * Now, if the new task added to the run-queue preempts the current ++ * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets ++ * called on the nearest possible occasion: ++ * ++ * - If the kernel is preemptible (CONFIG_PREEMPTION=y): ++ * ++ * - in syscall or exception context, at the next outmost ++ * preempt_enable(). (this might be as soon as the wake_up()'s ++ * spin_unlock()!) ++ * ++ * - in IRQ context, return from interrupt-handler to ++ * preemptible context ++ * ++ * - If the kernel is not preemptible (CONFIG_PREEMPTION is not set) ++ * then at the next: ++ * ++ * - cond_resched() call ++ * - explicit schedule() call ++ * - return from syscall or exception to user-space ++ * - return from interrupt-handler to user-space ++ * ++ * WARNING: must be called with preemption disabled! ++ */ ++static void __sched notrace __schedule(int sched_mode) ++{ ++ struct task_struct *prev, *next; ++ /* ++ * On PREEMPT_RT kernel, SM_RTLOCK_WAIT is noted ++ * as a preemption by schedule_debug() and RCU. ++ */ ++ bool preempt = sched_mode > SM_NONE; ++ bool is_switch = false; ++ unsigned long *switch_count; ++ unsigned long prev_state; ++ struct rq_flags rf; ++ struct rq *rq; ++ int cpu; ++ ++ /* Trace preemptions consistently with task switches */ ++ trace_sched_entry_tp(sched_mode == SM_PREEMPT); ++ ++ cpu = smp_processor_id(); ++ rq = cpu_rq(cpu); ++ prev = rq->curr; ++ ++ schedule_debug(prev, preempt); ++ ++ klp_sched_try_switch(prev); ++ ++ local_irq_disable(); ++ rcu_note_context_switch(preempt); ++ ++ /* ++ * Make sure that signal_pending_state()->signal_pending() below ++ * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE) ++ * done by the caller to avoid the race with signal_wake_up(): ++ * ++ * __set_current_state(@state) signal_wake_up() ++ * schedule() set_tsk_thread_flag(p, TIF_SIGPENDING) ++ * wake_up_state(p, state) ++ * LOCK rq->lock LOCK p->pi_state ++ * smp_mb__after_spinlock() smp_mb__after_spinlock() ++ * if (signal_pending_state()) if (p->state & @state) ++ * ++ * Also, the membarrier system call requires a full memory barrier ++ * after coming from user-space, before storing to rq->curr; this ++ * barrier matches a full barrier in the proximity of the membarrier ++ * system call exit. ++ */ ++ rq_lock(rq, &rf); ++ smp_mb__after_spinlock(); ++ ++ hrtick_schedule_enter(rq); ++ ++ update_rq_clock(rq); ++ ++ switch_count = &prev->nivcsw; ++ ++ /* Task state changes only considers SM_PREEMPT as preemption */ ++ preempt = sched_mode == SM_PREEMPT; ++ ++ /* ++ * We must load prev->state once (task_struct::state is volatile), such ++ * that we form a control dependency vs deactivate_task() below. ++ */ ++ prev_state = READ_ONCE(prev->__state); ++ if (sched_mode == SM_IDLE) { ++ if (!rq->nr_running) { ++ sched_cpu_topology_balance(cpu, rq); ++ next = prev; ++ goto picked; ++ } ++ } else if (!preempt && prev_state) { ++ try_to_block_task(rq, prev, &prev_state); ++ switch_count = &prev->nvcsw; ++ } ++ ++ check_curr(prev, rq); ++ ++ next = choose_next_task(rq, cpu); ++picked: ++ clear_tsk_need_resched(prev); ++ clear_preempt_need_resched(); ++ rq->last_seen_need_resched_ns = 0; ++ ++ is_switch = prev != next; ++ if (likely(is_switch)) { ++ next->last_ran = rq->clock_task; ++ ++ /*printk(KERN_INFO "sched: %px -> %px\n", prev, next);*/ ++ rq->nr_switches++; ++ /* ++ * RCU users of rcu_dereference(rq->curr) may not see ++ * changes to task_struct made by pick_next_task(). ++ */ ++ RCU_INIT_POINTER(rq->curr, next); ++ /* ++ * The membarrier system call requires each architecture ++ * to have a full memory barrier after updating ++ * rq->curr, before returning to user-space. ++ * ++ * Here are the schemes providing that barrier on the ++ * various architectures: ++ * - mm ? switch_mm() : mmdrop() for x86, s390, sparc, PowerPC, ++ * RISC-V. switch_mm() relies on membarrier_arch_switch_mm() ++ * on PowerPC and on RISC-V. ++ * - finish_lock_switch() for weakly-ordered ++ * architectures where spin_unlock is a full barrier, ++ * - switch_to() for arm64 (weakly-ordered, spin_unlock ++ * is a RELEASE barrier), ++ * ++ * The barrier matches a full barrier in the proximity of ++ * the membarrier system call entry. ++ * ++ * On RISC-V, this barrier pairing is also needed for the ++ * SYNC_CORE command when switching between processes, cf. ++ * the inline comments in membarrier_arch_switch_mm(). ++ */ ++ ++*switch_count; ++ ++ psi_account_irqtime(rq, prev, next); ++ psi_sched_switch(prev, next, !task_on_rq_queued(prev)); ++ ++ trace_sched_switch(preempt, prev, next, prev_state); ++ ++ /* Also unlocks the rq: */ ++ rq = context_switch(rq, prev, next, &rf); ++ ++ cpu = cpu_of(rq); ++ } else { ++ rq_unpin_lock(rq, &rf); ++ __balance_callbacks(rq, NULL); ++ prio_balance(rq, cpu); ++ hrtick_schedule_exit(rq); ++ raw_spin_rq_unlock_irq(rq); ++ } ++ trace_sched_exit_tp(is_switch); ++} ++ ++void __noreturn do_task_dead(void) ++{ ++ /* Causes final put_task_struct in finish_task_switch(): */ ++ set_special_state(TASK_DEAD); ++ ++ /* Tell freezer to ignore us: */ ++ current->flags |= PF_NOFREEZE; ++ ++ __schedule(SM_NONE); ++ BUG(); ++ ++ /* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */ ++ for (;;) ++ cpu_relax(); ++} ++ ++static inline void sched_submit_work(struct task_struct *tsk) ++{ ++ static DEFINE_WAIT_OVERRIDE_MAP(sched_map, LD_WAIT_CONFIG); ++ unsigned int task_flags; ++ ++ /* ++ * Establish LD_WAIT_CONFIG context to ensure none of the code called ++ * will use a blocking primitive -- which would lead to recursion. ++ */ ++ lock_map_acquire_try(&sched_map); ++ ++ task_flags = tsk->flags; ++ /* ++ * If a worker goes to sleep, notify and ask workqueue whether it ++ * wants to wake up a task to maintain concurrency. ++ */ ++ if (task_flags & PF_WQ_WORKER) ++ wq_worker_sleeping(tsk); ++ else if (task_flags & PF_IO_WORKER) ++ io_wq_worker_sleeping(tsk); ++ ++ /* ++ * spinlock and rwlock must not flush block requests. This will ++ * deadlock if the callback attempts to acquire a lock which is ++ * already acquired. ++ */ ++ WARN_ON_ONCE(current->__state & TASK_RTLOCK_WAIT); ++ ++ /* ++ * If we are going to sleep and we have plugged IO queued, ++ * make sure to submit it to avoid deadlocks. ++ */ ++ blk_flush_plug(tsk->plug, true); ++ ++ lock_map_release(&sched_map); ++} ++ ++static void sched_update_worker(struct task_struct *tsk) ++{ ++ if (tsk->flags & (PF_WQ_WORKER | PF_IO_WORKER)) { ++ if (tsk->flags & PF_WQ_WORKER) ++ wq_worker_running(tsk); ++ else ++ io_wq_worker_running(tsk); ++ } ++} ++ ++static __always_inline void __schedule_loop(int sched_mode) ++{ ++ do { ++ preempt_disable(); ++ __schedule(sched_mode); ++ sched_preempt_enable_no_resched(); ++ } while (need_resched()); ++} ++ ++asmlinkage __visible void __sched schedule(void) ++{ ++ struct task_struct *tsk = current; ++ ++#ifdef CONFIG_RT_MUTEXES ++ lockdep_assert(!tsk->sched_rt_mutex); ++#endif ++ ++ if (!task_is_running(tsk)) ++ sched_submit_work(tsk); ++ __schedule_loop(SM_NONE); ++ sched_update_worker(tsk); ++} ++EXPORT_SYMBOL(schedule); ++ ++/* ++ * synchronize_rcu_tasks() makes sure that no task is stuck in preempted ++ * state (have scheduled out non-voluntarily) by making sure that all ++ * tasks have either left the run queue or have gone into user space. ++ * As idle tasks do not do either, they must not ever be preempted ++ * (schedule out non-voluntarily). ++ * ++ * schedule_idle() is similar to schedule_preempt_disable() except that it ++ * never enables preemption because it does not call sched_submit_work(). ++ */ ++void __sched schedule_idle(void) ++{ ++ /* ++ * As this skips calling sched_submit_work(), which the idle task does ++ * regardless because that function is a NOP when the task is in a ++ * TASK_RUNNING state, make sure this isn't used someplace that the ++ * current task can be in any other state. Note, idle is always in the ++ * TASK_RUNNING state. ++ */ ++ WARN_ON_ONCE(current->__state); ++ do { ++ __schedule(SM_IDLE); ++ } while (need_resched()); ++} ++ ++#if defined(CONFIG_CONTEXT_TRACKING_USER) && !defined(CONFIG_HAVE_CONTEXT_TRACKING_USER_OFFSTACK) ++asmlinkage __visible void __sched schedule_user(void) ++{ ++ /* ++ * If we come here after a random call to set_need_resched(), ++ * or we have been woken up remotely but the IPI has not yet arrived, ++ * we haven't yet exited the RCU idle mode. Do it here manually until ++ * we find a better solution. ++ * ++ * NB: There are buggy callers of this function. Ideally we ++ * should warn if prev_state != CT_STATE_USER, but that will trigger ++ * too frequently to make sense yet. ++ */ ++ enum ctx_state prev_state = exception_enter(); ++ schedule(); ++ exception_exit(prev_state); ++} ++#endif ++ ++/** ++ * schedule_preempt_disabled - called with preemption disabled ++ * ++ * Returns with preemption disabled. Note: preempt_count must be 1 ++ */ ++void __sched schedule_preempt_disabled(void) ++{ ++ sched_preempt_enable_no_resched(); ++ schedule(); ++ preempt_disable(); ++} ++ ++#ifdef CONFIG_PREEMPT_RT ++void __sched notrace schedule_rtlock(void) ++{ ++ __schedule_loop(SM_RTLOCK_WAIT); ++} ++NOKPROBE_SYMBOL(schedule_rtlock); ++#endif ++ ++static void __sched notrace preempt_schedule_common(void) ++{ ++ do { ++ /* ++ * Because the function tracer can trace preempt_count_sub() ++ * and it also uses preempt_enable/disable_notrace(), if ++ * NEED_RESCHED is set, the preempt_enable_notrace() called ++ * by the function tracer will call this function again and ++ * cause infinite recursion. ++ * ++ * Preemption must be disabled here before the function ++ * tracer can trace. Break up preempt_disable() into two ++ * calls. One to disable preemption without fear of being ++ * traced. The other to still record the preemption latency, ++ * which can also be traced by the function tracer. ++ */ ++ preempt_disable_notrace(); ++ preempt_latency_start(1); ++ __schedule(SM_PREEMPT); ++ preempt_latency_stop(1); ++ preempt_enable_no_resched_notrace(); ++ ++ /* ++ * Check again in case we missed a preemption opportunity ++ * between schedule and now. ++ */ ++ } while (need_resched()); ++} ++ ++#ifdef CONFIG_PREEMPTION ++/* ++ * This is the entry point to schedule() from in-kernel preemption ++ * off of preempt_enable. ++ */ ++asmlinkage __visible void __sched notrace preempt_schedule(void) ++{ ++ /* ++ * If there is a non-zero preempt_count or interrupts are disabled, ++ * we do not want to preempt the current task. Just return.. ++ */ ++ if (likely(!preemptible())) ++ return; ++ ++ preempt_schedule_common(); ++} ++NOKPROBE_SYMBOL(preempt_schedule); ++EXPORT_SYMBOL(preempt_schedule); ++ ++#ifdef CONFIG_PREEMPT_DYNAMIC ++# ifdef CONFIG_HAVE_PREEMPT_DYNAMIC_CALL ++# ifndef preempt_schedule_dynamic_enabled ++# define preempt_schedule_dynamic_enabled preempt_schedule ++# define preempt_schedule_dynamic_disabled NULL ++# endif ++DEFINE_STATIC_CALL(preempt_schedule, preempt_schedule_dynamic_enabled); ++EXPORT_STATIC_CALL_TRAMP(preempt_schedule); ++# elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY) ++static DEFINE_STATIC_KEY_TRUE(sk_dynamic_preempt_schedule); ++void __sched notrace dynamic_preempt_schedule(void) ++{ ++ if (!static_branch_unlikely(&sk_dynamic_preempt_schedule)) ++ return; ++ preempt_schedule(); ++} ++NOKPROBE_SYMBOL(dynamic_preempt_schedule); ++EXPORT_SYMBOL(dynamic_preempt_schedule); ++# endif ++#endif /* CONFIG_PREEMPT_DYNAMIC */ ++ ++/** ++ * preempt_schedule_notrace - preempt_schedule called by tracing ++ * ++ * The tracing infrastructure uses preempt_enable_notrace to prevent ++ * recursion and tracing preempt enabling caused by the tracing ++ * infrastructure itself. But as tracing can happen in areas coming ++ * from userspace or just about to enter userspace, a preempt enable ++ * can occur before user_exit() is called. This will cause the scheduler ++ * to be called when the system is still in usermode. ++ * ++ * To prevent this, the preempt_enable_notrace will use this function ++ * instead of preempt_schedule() to exit user context if needed before ++ * calling the scheduler. ++ */ ++asmlinkage __visible void __sched notrace preempt_schedule_notrace(void) ++{ ++ enum ctx_state prev_ctx; ++ ++ if (likely(!preemptible())) ++ return; ++ ++ do { ++ /* ++ * Because the function tracer can trace preempt_count_sub() ++ * and it also uses preempt_enable/disable_notrace(), if ++ * NEED_RESCHED is set, the preempt_enable_notrace() called ++ * by the function tracer will call this function again and ++ * cause infinite recursion. ++ * ++ * Preemption must be disabled here before the function ++ * tracer can trace. Break up preempt_disable() into two ++ * calls. One to disable preemption without fear of being ++ * traced. The other to still record the preemption latency, ++ * which can also be traced by the function tracer. ++ */ ++ preempt_disable_notrace(); ++ preempt_latency_start(1); ++ /* ++ * Needs preempt disabled in case user_exit() is traced ++ * and the tracer calls preempt_enable_notrace() causing ++ * an infinite recursion. ++ */ ++ prev_ctx = exception_enter(); ++ __schedule(SM_PREEMPT); ++ exception_exit(prev_ctx); ++ ++ preempt_latency_stop(1); ++ preempt_enable_no_resched_notrace(); ++ } while (need_resched()); ++} ++EXPORT_SYMBOL_GPL(preempt_schedule_notrace); ++ ++#ifdef CONFIG_PREEMPT_DYNAMIC ++# ifdef CONFIG_HAVE_PREEMPT_DYNAMIC_CALL ++# ifndef preempt_schedule_notrace_dynamic_enabled ++# define preempt_schedule_notrace_dynamic_enabled preempt_schedule_notrace ++# define preempt_schedule_notrace_dynamic_disabled NULL ++# endif ++DEFINE_STATIC_CALL(preempt_schedule_notrace, preempt_schedule_notrace_dynamic_enabled); ++EXPORT_STATIC_CALL_TRAMP(preempt_schedule_notrace); ++# elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY) ++static DEFINE_STATIC_KEY_TRUE(sk_dynamic_preempt_schedule_notrace); ++void __sched notrace dynamic_preempt_schedule_notrace(void) ++{ ++ if (!static_branch_unlikely(&sk_dynamic_preempt_schedule_notrace)) ++ return; ++ preempt_schedule_notrace(); ++} ++NOKPROBE_SYMBOL(dynamic_preempt_schedule_notrace); ++EXPORT_SYMBOL(dynamic_preempt_schedule_notrace); ++# endif ++#endif /* CONFIG_PREEMPT_DYNAMIC */ ++ ++#endif /* CONFIG_PREEMPTION */ ++ ++/* ++ * This is the entry point to schedule() from kernel preemption ++ * off of IRQ context. ++ * Note, that this is called and return with IRQs disabled. This will ++ * protect us against recursive calling from IRQ contexts. ++ */ ++asmlinkage __visible void __sched preempt_schedule_irq(void) ++{ ++ enum ctx_state prev_state; ++ ++ /* Catch callers which need to be fixed */ ++ BUG_ON(preempt_count() || !irqs_disabled()); ++ ++ prev_state = exception_enter(); ++ ++ do { ++ preempt_disable(); ++ local_irq_enable(); ++ __schedule(SM_PREEMPT); ++ local_irq_disable(); ++ sched_preempt_enable_no_resched(); ++ } while (need_resched()); ++ ++ exception_exit(prev_state); ++} ++ ++int default_wake_function(wait_queue_entry_t *curr, unsigned mode, int wake_flags, ++ void *key) ++{ ++ WARN_ON_ONCE(wake_flags & ~(WF_SYNC|WF_CURRENT_CPU)); ++ return try_to_wake_up(curr->private, mode, wake_flags); ++} ++EXPORT_SYMBOL(default_wake_function); ++ ++#ifdef CONFIG_RT_MUTEXES ++ ++/* ++ * Would be more useful with typeof()/auto_type but they don't mix with ++ * bit-fields. Since it's a local thing, use int. Keep the generic sounding ++ * name such that if someone were to implement this function we get to compare ++ * notes. ++ */ ++#define fetch_and_set(x, v) ({ int _x = (x); (x) = (v); _x; }) ++ ++void rt_mutex_pre_schedule(void) ++{ ++ lockdep_assert(!fetch_and_set(current->sched_rt_mutex, 1)); ++ sched_submit_work(current); ++} ++ ++/* ++ * Used within the futex syscall context, skips sched_submit_work() because none ++ * its work will be done. Asserts ensure that it is indeed the case. ++ */ ++void rt_mutex_futex_pre_schedule(void) ++{ ++ lockdep_assert(!(current->flags & (PF_WQ_WORKER | PF_IO_WORKER))); ++ lockdep_assert(!current->plug); ++ lockdep_assert(!fetch_and_set(current->sched_rt_mutex, 1)); ++} ++ ++void rt_mutex_schedule(void) ++{ ++ lockdep_assert(current->sched_rt_mutex); ++ __schedule_loop(SM_NONE); ++} ++ ++void rt_mutex_futex_post_schedule(void) ++{ ++ lockdep_assert(fetch_and_set(current->sched_rt_mutex, 0)); ++} ++ ++void rt_mutex_post_schedule(void) ++{ ++ sched_update_worker(current); ++ lockdep_assert(fetch_and_set(current->sched_rt_mutex, 0)); ++} ++ ++/* ++ * rt_mutex_setprio - set the current priority of a task ++ * @p: task to boost ++ * @pi_task: donor task ++ * ++ * This function changes the 'effective' priority of a task. It does ++ * not touch ->normal_prio like __setscheduler(). ++ * ++ * Used by the rt_mutex code to implement priority inheritance ++ * logic. Call site only calls if the priority of the task changed. ++ */ ++void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task) ++{ ++ int prio, queue_flag = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK; ++ struct rq_flags rf; ++ struct rq *rq; ++ ++ /* XXX used to be waiter->prio, not waiter->task->prio */ ++ prio = __rt_effective_prio(pi_task, p->normal_prio); ++ ++ /* ++ * If nothing changed; bail early. ++ */ ++ if (p->pi_top_task == pi_task && prio == p->prio) ++ return; ++ ++ rq = __task_rq_lock(p, &rf); ++ update_rq_clock(rq); ++ /* ++ * Set under pi_lock && rq->lock, such that the value can be used under ++ * either lock. ++ * ++ * Note that there is loads of tricky to make this pointer cache work ++ * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to ++ * ensure a task is de-boosted (pi_task is set to NULL) before the ++ * task is allowed to run again (and can exit). This ensures the pointer ++ * points to a blocked task -- which guarantees the task is present. ++ */ ++ p->pi_top_task = pi_task; ++ ++ /* ++ * For FIFO/RR we only need to set prio, if that matches we're done. ++ */ ++ if (prio == p->prio) ++ goto out_unlock; ++ ++ /* ++ * Idle task boosting is a no-no in general. There is one ++ * exception, when PREEMPT_RT and NOHZ is active: ++ * ++ * The idle task calls get_next_timer_interrupt() and holds ++ * the timer wheel base->lock on the CPU and another CPU wants ++ * to access the timer (probably to cancel it). We can safely ++ * ignore the boosting request, as the idle CPU runs this code ++ * with interrupts disabled and will complete the lock ++ * protected section without being interrupted. So there is no ++ * real need to boost. ++ */ ++ if (unlikely(p == rq->idle)) { ++ WARN_ON(p != rq->curr); ++ WARN_ON(p->pi_blocked_on); ++ goto out_unlock; ++ } ++ ++ trace_sched_pi_setprio(p, pi_task); ++ ++ scoped_guard (sched_change, p, queue_flag) { ++ if (rt_prio(prio) && p->prio < prio) ++ scope->flags |= ENQUEUE_HEAD; ++ p->prio = prio; ++ } ++ ++out_unlock: ++ /* Caller holds task_struct::pi_lock, IRQs are still disabled */ ++ ++ __balance_callbacks(rq, &rf); ++ __task_rq_unlock(rq, p, &rf); ++} ++#endif /* CONFIG_RT_MUTEXES */ ++ ++#if !defined(CONFIG_PREEMPTION) || defined(CONFIG_PREEMPT_DYNAMIC) ++int __sched __cond_resched(void) ++{ ++ if (should_resched(0) && !irqs_disabled()) { ++ preempt_schedule_common(); ++ return 1; ++ } ++ /* ++ * In PREEMPT_RCU kernels, ->rcu_read_lock_nesting tells the tick ++ * whether the current CPU is in an RCU read-side critical section, ++ * so the tick can report quiescent states even for CPUs looping ++ * in kernel context. In contrast, in non-preemptible kernels, ++ * RCU readers leave no in-memory hints, which means that CPU-bound ++ * processes executing in kernel context might never report an ++ * RCU quiescent state. Therefore, the following code causes ++ * cond_resched() to report a quiescent state, but only when RCU ++ * is in urgent need of one. ++ * A third case, preemptible, but non-PREEMPT_RCU provides for ++ * urgently needed quiescent states via rcu_flavor_sched_clock_irq(). ++ */ ++#ifndef CONFIG_PREEMPT_RCU ++ rcu_all_qs(); ++#endif ++ return 0; ++} ++EXPORT_SYMBOL(__cond_resched); ++#endif ++ ++#ifdef CONFIG_PREEMPT_DYNAMIC ++# ifdef CONFIG_HAVE_PREEMPT_DYNAMIC_CALL ++# define cond_resched_dynamic_enabled __cond_resched ++# define cond_resched_dynamic_disabled ((void *)&__static_call_return0) ++DEFINE_STATIC_CALL_RET0(cond_resched, __cond_resched); ++EXPORT_STATIC_CALL_TRAMP(cond_resched); ++ ++# define might_resched_dynamic_enabled __cond_resched ++# define might_resched_dynamic_disabled ((void *)&__static_call_return0) ++DEFINE_STATIC_CALL_RET0(might_resched, __cond_resched); ++EXPORT_STATIC_CALL_TRAMP(might_resched); ++# elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY) ++static DEFINE_STATIC_KEY_FALSE(sk_dynamic_cond_resched); ++int __sched dynamic_cond_resched(void) ++{ ++ if (!static_branch_unlikely(&sk_dynamic_cond_resched)) ++ return 0; ++ return __cond_resched(); ++} ++EXPORT_SYMBOL(dynamic_cond_resched); ++ ++static DEFINE_STATIC_KEY_FALSE(sk_dynamic_might_resched); ++int __sched dynamic_might_resched(void) ++{ ++ if (!static_branch_unlikely(&sk_dynamic_might_resched)) ++ return 0; ++ return __cond_resched(); ++} ++EXPORT_SYMBOL(dynamic_might_resched); ++# endif ++#endif /* CONFIG_PREEMPT_DYNAMIC */ ++ ++/* ++ * __cond_resched_lock() - if a reschedule is pending, drop the given lock, ++ * call schedule, and on return reacquire the lock. ++ * ++ * This works OK both with and without CONFIG_PREEMPTION. We do strange low-level ++ * operations here to prevent schedule() from being called twice (once via ++ * spin_unlock(), once by hand). ++ */ ++int __cond_resched_lock(spinlock_t *lock) ++{ ++ int resched = should_resched(PREEMPT_LOCK_OFFSET); ++ int ret = 0; ++ ++ lockdep_assert_held(lock); ++ ++ if (spin_needbreak(lock) || resched) { ++ spin_unlock(lock); ++ if (!_cond_resched()) ++ cpu_relax(); ++ ret = 1; ++ spin_lock(lock); ++ } ++ return ret; ++} ++EXPORT_SYMBOL(__cond_resched_lock); ++ ++int __cond_resched_rwlock_read(rwlock_t *lock) ++{ ++ int resched = should_resched(PREEMPT_LOCK_OFFSET); ++ int ret = 0; ++ ++ lockdep_assert_held_read(lock); ++ ++ if (rwlock_needbreak(lock) || resched) { ++ read_unlock(lock); ++ if (!_cond_resched()) ++ cpu_relax(); ++ ret = 1; ++ read_lock(lock); ++ } ++ return ret; ++} ++EXPORT_SYMBOL(__cond_resched_rwlock_read); ++ ++int __cond_resched_rwlock_write(rwlock_t *lock) ++{ ++ int resched = should_resched(PREEMPT_LOCK_OFFSET); ++ int ret = 0; ++ ++ lockdep_assert_held_write(lock); ++ ++ if (rwlock_needbreak(lock) || resched) { ++ write_unlock(lock); ++ if (!_cond_resched()) ++ cpu_relax(); ++ ret = 1; ++ write_lock(lock); ++ } ++ return ret; ++} ++EXPORT_SYMBOL(__cond_resched_rwlock_write); ++ ++#ifdef CONFIG_PREEMPT_DYNAMIC ++ ++# ifdef CONFIG_GENERIC_IRQ_ENTRY ++# include ++# endif ++ ++/* ++ * SC:cond_resched ++ * SC:might_resched ++ * SC:preempt_schedule ++ * SC:preempt_schedule_notrace ++ * SC:irqentry_exit_cond_resched ++ * ++ * ++ * NONE: ++ * cond_resched <- __cond_resched ++ * might_resched <- RET0 ++ * preempt_schedule <- NOP ++ * preempt_schedule_notrace <- NOP ++ * irqentry_exit_cond_resched <- NOP ++ * dynamic_preempt_lazy <- false ++ * ++ * VOLUNTARY: ++ * cond_resched <- __cond_resched ++ * might_resched <- __cond_resched ++ * preempt_schedule <- NOP ++ * preempt_schedule_notrace <- NOP ++ * irqentry_exit_cond_resched <- NOP ++ * dynamic_preempt_lazy <- false ++ * ++ * FULL: ++ * cond_resched <- RET0 ++ * might_resched <- RET0 ++ * preempt_schedule <- preempt_schedule ++ * preempt_schedule_notrace <- preempt_schedule_notrace ++ * irqentry_exit_cond_resched <- irqentry_exit_cond_resched ++ * dynamic_preempt_lazy <- false ++ * ++ * LAZY: ++ * cond_resched <- RET0 ++ * might_resched <- RET0 ++ * preempt_schedule <- preempt_schedule ++ * preempt_schedule_notrace <- preempt_schedule_notrace ++ * irqentry_exit_cond_resched <- irqentry_exit_cond_resched ++ * dynamic_preempt_lazy <- true ++ */ ++ ++enum { ++ preempt_dynamic_undefined = -1, ++ preempt_dynamic_none, ++ preempt_dynamic_voluntary, ++ preempt_dynamic_full, ++ preempt_dynamic_lazy, ++}; ++ ++int preempt_dynamic_mode = preempt_dynamic_undefined; ++ ++int sched_dynamic_mode(const char *str) ++{ ++# if !(defined(CONFIG_PREEMPT_RT) || defined(CONFIG_ARCH_HAS_PREEMPT_LAZY)) ++ if (!strcmp(str, "none")) ++ return preempt_dynamic_none; ++ ++ if (!strcmp(str, "voluntary")) ++ return preempt_dynamic_voluntary; ++# endif ++ ++ if (!strcmp(str, "full")) ++ return preempt_dynamic_full; ++ ++# ifdef CONFIG_ARCH_HAS_PREEMPT_LAZY ++ if (!strcmp(str, "lazy")) ++ return preempt_dynamic_lazy; ++# endif ++ ++ return -EINVAL; ++} ++ ++# define preempt_dynamic_key_enable(f) static_key_enable(&sk_dynamic_##f.key) ++# define preempt_dynamic_key_disable(f) static_key_disable(&sk_dynamic_##f.key) ++ ++# if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL) ++# define preempt_dynamic_enable(f) static_call_update(f, f##_dynamic_enabled) ++# define preempt_dynamic_disable(f) static_call_update(f, f##_dynamic_disabled) ++# elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY) ++# define preempt_dynamic_enable(f) preempt_dynamic_key_enable(f) ++# define preempt_dynamic_disable(f) preempt_dynamic_key_disable(f) ++# else ++# error "Unsupported PREEMPT_DYNAMIC mechanism" ++# endif ++ ++static DEFINE_MUTEX(sched_dynamic_mutex); ++ ++static void __sched_dynamic_update(int mode) ++{ ++ /* ++ * Avoid {NONE,VOLUNTARY} -> FULL transitions from ever ending up in ++ * the ZERO state, which is invalid. ++ */ ++ preempt_dynamic_enable(cond_resched); ++ preempt_dynamic_enable(might_resched); ++ preempt_dynamic_enable(preempt_schedule); ++ preempt_dynamic_enable(preempt_schedule_notrace); ++ preempt_dynamic_enable(irqentry_exit_cond_resched); ++ preempt_dynamic_key_disable(preempt_lazy); ++ ++ switch (mode) { ++ case preempt_dynamic_none: ++ preempt_dynamic_enable(cond_resched); ++ preempt_dynamic_disable(might_resched); ++ preempt_dynamic_disable(preempt_schedule); ++ preempt_dynamic_disable(preempt_schedule_notrace); ++ preempt_dynamic_disable(irqentry_exit_cond_resched); ++ preempt_dynamic_key_disable(preempt_lazy); ++ if (mode != preempt_dynamic_mode) ++ pr_info("Dynamic Preempt: none\n"); ++ break; ++ ++ case preempt_dynamic_voluntary: ++ preempt_dynamic_enable(cond_resched); ++ preempt_dynamic_enable(might_resched); ++ preempt_dynamic_disable(preempt_schedule); ++ preempt_dynamic_disable(preempt_schedule_notrace); ++ preempt_dynamic_disable(irqentry_exit_cond_resched); ++ preempt_dynamic_key_disable(preempt_lazy); ++ if (mode != preempt_dynamic_mode) ++ pr_info("Dynamic Preempt: voluntary\n"); ++ break; ++ ++ case preempt_dynamic_full: ++ preempt_dynamic_disable(cond_resched); ++ preempt_dynamic_disable(might_resched); ++ preempt_dynamic_enable(preempt_schedule); ++ preempt_dynamic_enable(preempt_schedule_notrace); ++ preempt_dynamic_enable(irqentry_exit_cond_resched); ++ preempt_dynamic_key_disable(preempt_lazy); ++ if (mode != preempt_dynamic_mode) ++ pr_info("Dynamic Preempt: full\n"); ++ break; ++ ++ case preempt_dynamic_lazy: ++ preempt_dynamic_disable(cond_resched); ++ preempt_dynamic_disable(might_resched); ++ preempt_dynamic_enable(preempt_schedule); ++ preempt_dynamic_enable(preempt_schedule_notrace); ++ preempt_dynamic_enable(irqentry_exit_cond_resched); ++ preempt_dynamic_key_enable(preempt_lazy); ++ if (mode != preempt_dynamic_mode) ++ pr_info("Dynamic Preempt: lazy\n"); ++ break; ++ } ++ ++ WRITE_ONCE(preempt_dynamic_mode, mode); ++} ++ ++void sched_dynamic_update(int mode) ++{ ++ mutex_lock(&sched_dynamic_mutex); ++ __sched_dynamic_update(mode); ++ mutex_unlock(&sched_dynamic_mutex); ++} ++ ++static int __init setup_preempt_mode(char *str) ++{ ++ int mode = sched_dynamic_mode(str); ++ if (mode < 0) { ++ pr_warn("Dynamic Preempt: unsupported mode: %s\n", str); ++ return 0; ++ } ++ ++ sched_dynamic_update(mode); ++ return 1; ++} ++__setup("preempt=", setup_preempt_mode); ++ ++static void __init preempt_dynamic_init(void) ++{ ++ if (preempt_dynamic_mode == preempt_dynamic_undefined) { ++ if (IS_ENABLED(CONFIG_PREEMPT_NONE)) { ++ sched_dynamic_update(preempt_dynamic_none); ++ } else if (IS_ENABLED(CONFIG_PREEMPT_VOLUNTARY)) { ++ sched_dynamic_update(preempt_dynamic_voluntary); ++ } else if (IS_ENABLED(CONFIG_PREEMPT_LAZY)) { ++ sched_dynamic_update(preempt_dynamic_lazy); ++ } else { ++ /* Default static call setting, nothing to do */ ++ WARN_ON_ONCE(!IS_ENABLED(CONFIG_PREEMPT)); ++ preempt_dynamic_mode = preempt_dynamic_full; ++ pr_info("Dynamic Preempt: full\n"); ++ } ++ } ++} ++ ++# define PREEMPT_MODEL_ACCESSOR(mode) \ ++ bool preempt_model_##mode(void) \ ++ { \ ++ int mode = READ_ONCE(preempt_dynamic_mode); \ ++ WARN_ON_ONCE(mode == preempt_dynamic_undefined); \ ++ return mode == preempt_dynamic_##mode; \ ++ } \ ++ EXPORT_SYMBOL_GPL(preempt_model_##mode) ++ ++PREEMPT_MODEL_ACCESSOR(none); ++PREEMPT_MODEL_ACCESSOR(voluntary); ++PREEMPT_MODEL_ACCESSOR(full); ++PREEMPT_MODEL_ACCESSOR(lazy); ++ ++#else /* !CONFIG_PREEMPT_DYNAMIC: */ ++ ++#define preempt_dynamic_mode -1 ++ ++static inline void preempt_dynamic_init(void) { } ++ ++#endif /* CONFIG_PREEMPT_DYNAMIC */ ++ ++const char *preempt_modes[] = { ++ "none", "voluntary", "full", "lazy", NULL, ++}; ++ ++const char *preempt_model_str(void) ++{ ++ bool brace = IS_ENABLED(CONFIG_PREEMPT_RT) && ++ (IS_ENABLED(CONFIG_PREEMPT_DYNAMIC) || ++ IS_ENABLED(CONFIG_PREEMPT_LAZY)); ++ static char buf[128]; ++ ++ if (IS_ENABLED(CONFIG_PREEMPT_BUILD)) { ++ struct seq_buf s; ++ ++ seq_buf_init(&s, buf, sizeof(buf)); ++ seq_buf_puts(&s, "PREEMPT"); ++ ++ if (IS_ENABLED(CONFIG_PREEMPT_RT)) ++ seq_buf_printf(&s, "%sRT%s", ++ brace ? "_{" : "_", ++ brace ? "," : ""); ++ ++ if (IS_ENABLED(CONFIG_PREEMPT_DYNAMIC)) { ++ seq_buf_printf(&s, "(%s)%s", ++ preempt_dynamic_mode >= 0 ? ++ preempt_modes[preempt_dynamic_mode] : "undef", ++ brace ? "}" : ""); ++ return seq_buf_str(&s); ++ } ++ ++ if (IS_ENABLED(CONFIG_PREEMPT_LAZY)) { ++ seq_buf_printf(&s, "LAZY%s", ++ brace ? "}" : ""); ++ return seq_buf_str(&s); ++ } ++ ++ return seq_buf_str(&s); ++ } ++ ++ if (IS_ENABLED(CONFIG_PREEMPT_VOLUNTARY_BUILD)) ++ return "VOLUNTARY"; ++ ++ return "NONE"; ++} ++ ++int io_schedule_prepare(void) ++{ ++ int old_iowait = current->in_iowait; ++ ++ current->in_iowait = 1; ++ blk_flush_plug(current->plug, true); ++ return old_iowait; ++} ++ ++void io_schedule_finish(int token) ++{ ++ current->in_iowait = token; ++} ++ ++/* ++ * This task is about to go to sleep on IO. Increment rq->nr_iowait so ++ * that process accounting knows that this is a task in IO wait state. ++ */ ++ ++long __sched io_schedule_timeout(long timeout) ++{ ++ int token; ++ long ret; ++ ++ token = io_schedule_prepare(); ++ ret = schedule_timeout(timeout); ++ io_schedule_finish(token); ++ ++ return ret; ++} ++EXPORT_SYMBOL(io_schedule_timeout); ++ ++void __sched io_schedule(void) ++{ ++ int token; ++ ++ token = io_schedule_prepare(); ++ schedule(); ++ io_schedule_finish(token); ++} ++EXPORT_SYMBOL(io_schedule); ++ ++void sched_show_task(struct task_struct *p) ++{ ++ unsigned long free; ++ int ppid; ++ ++ if (!try_get_task_stack(p)) ++ return; ++ ++ pr_info("task:%-15.15s state:%c", p->comm, task_state_to_char(p)); ++ ++ if (task_is_running(p)) ++ pr_cont(" running task "); ++ free = stack_not_used(p); ++ ppid = 0; ++ rcu_read_lock(); ++ if (pid_alive(p)) ++ ppid = task_pid_nr(rcu_dereference(p->real_parent)); ++ rcu_read_unlock(); ++ pr_cont(" stack:%-5lu pid:%-5d tgid:%-5d ppid:%-6d task_flags:0x%04x flags:0x%08lx\n", ++ free, task_pid_nr(p), task_tgid_nr(p), ++ ppid, p->flags, read_task_thread_flags(p)); ++ ++ print_worker_info(KERN_INFO, p); ++ print_stop_info(KERN_INFO, p); ++ show_stack(p, NULL, KERN_INFO); ++ put_task_stack(p); ++} ++EXPORT_SYMBOL_GPL(sched_show_task); ++ ++static inline bool ++state_filter_match(unsigned long state_filter, struct task_struct *p) ++{ ++ unsigned int state = READ_ONCE(p->__state); ++ ++ /* no filter, everything matches */ ++ if (!state_filter) ++ return true; ++ ++ /* filter, but doesn't match */ ++ if (!(state & state_filter)) ++ return false; ++ ++ /* ++ * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows ++ * TASK_KILLABLE). ++ */ ++ if (state_filter == TASK_UNINTERRUPTIBLE && (state & TASK_NOLOAD)) ++ return false; ++ ++ return true; ++} ++ ++ ++void show_state_filter(unsigned int state_filter) ++{ ++ struct task_struct *g, *p; ++ ++ rcu_read_lock(); ++ for_each_process_thread(g, p) { ++ /* ++ * reset the NMI-timeout, listing all files on a slow ++ * console might take a lot of time: ++ * Also, reset softlockup watchdogs on all CPUs, because ++ * another CPU might be blocked waiting for us to process ++ * an IPI. ++ */ ++ touch_nmi_watchdog(); ++ touch_all_softlockup_watchdogs(); ++ if (state_filter_match(state_filter, p)) ++ sched_show_task(p); ++ } ++ ++ /* TODO: Alt schedule FW should support this ++ if (!state_filter) ++ sysrq_sched_debug_show(); ++ */ ++ rcu_read_unlock(); ++ /* ++ * Only show locks if all tasks are dumped: ++ */ ++ if (!state_filter) ++ debug_show_all_locks(); ++} ++ ++void dump_cpu_task(int cpu) ++{ ++ if (in_hardirq() && cpu == smp_processor_id()) { ++ struct pt_regs *regs; ++ ++ regs = get_irq_regs(); ++ if (regs) { ++ show_regs(regs); ++ return; ++ } ++ } ++ ++ if (trigger_single_cpu_backtrace(cpu)) ++ return; ++ ++ pr_info("Task dump for CPU %d:\n", cpu); ++ sched_show_task(cpu_curr(cpu)); ++} ++ ++/** ++ * init_idle - set up an idle thread for a given CPU ++ * @idle: task in question ++ * @cpu: CPU the idle task belongs to ++ * ++ * NOTE: this function does not set the idle thread's NEED_RESCHED ++ * flag, to make booting more robust. ++ */ ++void __init init_idle(struct task_struct *idle, int cpu) ++{ ++ struct affinity_context ac = (struct affinity_context) { ++ .new_mask = cpumask_of(cpu), ++ .flags = 0, ++ }; ++ struct rq *rq = cpu_rq(cpu); ++ unsigned long flags; ++ ++ raw_spin_lock_irqsave(&idle->pi_lock, flags); ++ raw_spin_rq_lock(rq); ++ ++ idle->last_ran = rq->clock_task; ++ idle->__state = TASK_RUNNING; ++ /* ++ * PF_KTHREAD should already be set at this point; regardless, make it ++ * look like a proper per-CPU kthread. ++ */ ++ idle->flags |= PF_KTHREAD | PF_NO_SETAFFINITY; ++ kthread_set_per_cpu(idle, cpu); ++ ++ sched_queue_init_idle(&rq->queue, idle); ++ ++ /* ++ * No validation and serialization required at boot time and for ++ * setting up the idle tasks of not yet online CPUs. ++ */ ++ set_cpus_allowed_common(idle, &ac); ++ ++ /* Silence PROVE_RCU */ ++ rcu_read_lock(); ++ __set_task_cpu(idle, cpu); ++ rcu_read_unlock(); ++ ++ rq->idle = idle; ++ rcu_assign_pointer(rq->curr, idle); ++ idle->on_cpu = 1; ++ ++ raw_spin_rq_unlock(rq); ++ raw_spin_unlock_irqrestore(&idle->pi_lock, flags); ++ ++ /* Set the preempt count _outside_ the spinlocks! */ ++ init_idle_preempt_count(idle, cpu); ++ ++ ftrace_graph_init_idle_task(idle, cpu); ++ vtime_init_idle(idle, cpu); ++ sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu); ++} ++ ++int cpuset_cpumask_can_shrink(const struct cpumask __maybe_unused *cur, ++ const struct cpumask __maybe_unused *trial) ++{ ++ return 1; ++} ++ ++int task_can_attach(struct task_struct *p) ++{ ++ int ret = 0; ++ ++ /* ++ * Kthreads which disallow setaffinity shouldn't be moved ++ * to a new cpuset; we don't want to change their CPU ++ * affinity and isolating such threads by their set of ++ * allowed nodes is unnecessary. Thus, cpusets are not ++ * applicable for such threads. This prevents checking for ++ * success of set_cpus_allowed_ptr() on all attached tasks ++ * before cpus_mask may be changed. ++ */ ++ if (p->flags & PF_NO_SETAFFINITY) ++ ret = -EINVAL; ++ ++ return ret; ++} ++ ++bool sched_smp_initialized __read_mostly; ++ ++#ifdef CONFIG_HOTPLUG_CPU ++/* ++ * Invoked on the outgoing CPU in context of the CPU hotplug thread ++ * after ensuring that there are no user space tasks left on the CPU. ++ * ++ * If there is a lazy mm in use on the hotplug thread, drop it and ++ * switch to init_mm. ++ * ++ * The reference count on init_mm is dropped in finish_cpu(). ++ */ ++static void sched_force_init_mm(void) ++{ ++ struct mm_struct *mm = current->active_mm; ++ ++ if (mm != &init_mm) { ++ mmgrab_lazy_tlb(&init_mm); ++ local_irq_disable(); ++ current->active_mm = &init_mm; ++ switch_mm_irqs_off(mm, &init_mm, current); ++ local_irq_enable(); ++ finish_arch_post_lock_switch(); ++ mmdrop_lazy_tlb(mm); ++ } ++ ++ /* finish_cpu(), as ran on the BP, will clean up the active_mm state */ ++} ++ ++static int __balance_push_cpu_stop(void *arg) ++{ ++ struct task_struct *p = arg; ++ struct rq *rq = this_rq(); ++ struct rq_flags rf; ++ int cpu; ++ ++ scoped_guard (raw_spinlock_irq, &p->pi_lock) { ++ /* ++ * We may change the underlying rq, but the locks held will ++ * appropriately be "transferred" when switching. ++ */ ++ context_unsafe_alias(rq); ++ ++ cpu = select_fallback_rq(rq->cpu, p); ++ rq_lock(rq, &rf); ++ update_rq_clock(rq); ++ if (task_rq(p) == rq && task_on_rq_queued(p)) ++ rq = __migrate_task(rq, &rf, p, cpu); ++ rq_unlock(rq, &rf); ++ } ++ ++ put_task_struct(p); ++ ++ return 0; ++} ++ ++static DEFINE_PER_CPU(struct cpu_stop_work, push_work); ++ ++/* ++ * This is enabled below SCHED_AP_ACTIVE; when !cpu_active(), but only ++ * effective when the hotplug motion is down. ++ */ ++static void balance_push(struct rq *rq) ++ __must_hold(__rq_lockp(rq)) ++{ ++ struct task_struct *push_task = rq->curr; ++ ++ lockdep_assert_rq_held(rq); ++ ++ /* ++ * Ensure the thing is persistent until balance_push_set(.on = false); ++ */ ++ rq->balance_callback = &balance_push_callback; ++ ++ /* ++ * Only active while going offline and when invoked on the outgoing ++ * CPU. ++ */ ++ if (!cpu_dying(rq->cpu) || rq != this_rq()) ++ return; ++ ++ /* ++ * Both the cpu-hotplug and stop task are in this case and are ++ * required to complete the hotplug process. ++ */ ++ if (kthread_is_per_cpu(push_task) || ++ is_migration_disabled(push_task)) { ++ ++ /* ++ * If this is the idle task on the outgoing CPU try to wake ++ * up the hotplug control thread which might wait for the ++ * last task to vanish. The rcuwait_active() check is ++ * accurate here because the waiter is pinned on this CPU ++ * and can't obviously be running in parallel. ++ * ++ * On RT kernels this also has to check whether there are ++ * pinned and scheduled out tasks on the runqueue. They ++ * need to leave the migrate disabled section first. ++ */ ++ if (!rq->nr_running && !rq_has_pinned_tasks(rq) && ++ rcuwait_active(&rq->hotplug_wait)) { ++ raw_spin_rq_unlock(rq); ++ rcuwait_wake_up(&rq->hotplug_wait); ++ raw_spin_rq_lock(rq); ++ } ++ return; ++ } ++ ++ get_task_struct(push_task); ++ /* ++ * Temporarily drop rq->lock such that we can wake-up the stop task. ++ * Both preemption and IRQs are still disabled. ++ */ ++ preempt_disable(); ++ raw_spin_rq_unlock(rq); ++ stop_one_cpu_nowait(rq->cpu, __balance_push_cpu_stop, push_task, ++ this_cpu_ptr(&push_work)); ++ preempt_enable(); ++ /* ++ * At this point need_resched() is true and we'll take the loop in ++ * schedule(). The next pick is obviously going to be the stop task ++ * which kthread_is_per_cpu() and will push this task away. ++ */ ++ raw_spin_rq_lock(rq); ++} ++ ++static void balance_push_set(int cpu, bool on) ++{ ++ struct rq *rq = cpu_rq(cpu); ++ struct rq_flags rf; ++ ++ rq_lock_irqsave(rq, &rf); ++ if (on) { ++ WARN_ON_ONCE(rq->balance_callback); ++ rq->balance_callback = &balance_push_callback; ++ } else if (rq->balance_callback == &balance_push_callback) { ++ rq->balance_callback = NULL; ++ } ++ rq_unlock_irqrestore(rq, &rf); ++} ++ ++/* ++ * Invoked from a CPUs hotplug control thread after the CPU has been marked ++ * inactive. All tasks which are not per CPU kernel threads are either ++ * pushed off this CPU now via balance_push() or placed on a different CPU ++ * during wakeup. Wait until the CPU is quiescent. ++ */ ++static void balance_hotplug_wait(void) ++{ ++ struct rq *rq = this_rq(); ++ ++ rcuwait_wait_event(&rq->hotplug_wait, ++ rq->nr_running == 1 && !rq_has_pinned_tasks(rq), ++ TASK_UNINTERRUPTIBLE); ++} ++ ++#else /* !CONFIG_HOTPLUG_CPU: */ ++ ++static void balance_push(struct rq *rq) ++{ ++} ++ ++static void balance_push_set(int cpu, bool on) ++{ ++} ++ ++static inline void balance_hotplug_wait(void) ++{ ++} ++#endif /* !CONFIG_HOTPLUG_CPU */ ++ ++static void set_rq_offline(struct rq *rq) ++{ ++ if (rq->online) { ++ update_rq_clock(rq); ++ rq->online = false; ++ } ++} ++ ++static void set_rq_online(struct rq *rq) ++{ ++ if (!rq->online) ++ rq->online = true; ++} ++ ++static inline void sched_set_rq_online(struct rq *rq, int cpu) ++{ ++ unsigned long flags; ++ ++ raw_spin_rq_lock_irqsave(rq, flags); ++ set_rq_online(rq); ++ raw_spin_rq_unlock_irqrestore(rq, flags); ++} ++ ++static inline void sched_set_rq_offline(struct rq *rq, int cpu) ++{ ++ unsigned long flags; ++ ++ raw_spin_rq_lock_irqsave(rq, flags); ++ set_rq_offline(rq); ++ raw_spin_rq_unlock_irqrestore(rq, flags); ++} ++ ++/* ++ * used to mark begin/end of suspend/resume: ++ */ ++static int num_cpus_frozen; ++ ++/* ++ * Update cpusets according to cpu_active mask. If cpusets are ++ * disabled, cpuset_update_active_cpus() becomes a simple wrapper ++ * around partition_sched_domains(). ++ * ++ * If we come here as part of a suspend/resume, don't touch cpusets because we ++ * want to restore it back to its original state upon resume anyway. ++ */ ++static void cpuset_cpu_active(void) ++{ ++ if (cpuhp_tasks_frozen) { ++ /* ++ * num_cpus_frozen tracks how many CPUs are involved in suspend ++ * resume sequence. As long as this is not the last online ++ * operation in the resume sequence, just build a single sched ++ * domain, ignoring cpusets. ++ */ ++ cpuset_reset_sched_domains(); ++ if (--num_cpus_frozen) ++ return; ++ /* ++ * This is the last CPU online operation. So fall through and ++ * restore the original sched domains by considering the ++ * cpuset configurations. ++ */ ++ cpuset_force_rebuild(); ++ } ++ ++ cpuset_update_active_cpus(); ++} ++ ++static void cpuset_cpu_inactive(unsigned int cpu) ++{ ++ if (!cpuhp_tasks_frozen) { ++ cpuset_update_active_cpus(); ++ } else { ++ num_cpus_frozen++; ++ cpuset_reset_sched_domains(); ++ } ++} ++ ++static inline void sched_smt_present_inc(int cpu) ++{ ++ if (cpumask_weight(cpu_smt_mask(cpu)) == 2) ++ static_branch_inc_cpuslocked(&sched_smt_present); ++} ++ ++static inline void sched_smt_present_dec(int cpu) ++{ ++ if (cpumask_weight(cpu_smt_mask(cpu)) == 2) ++ static_branch_dec_cpuslocked(&sched_smt_present); ++} ++ ++static void sched_topology_hotplug_rebuild(unsigned int cpu, bool activate); ++ ++int sched_cpu_activate(unsigned int cpu) ++{ ++ struct rq *rq = cpu_rq(cpu); ++ ++ /* ++ * Clear the balance_push callback and prepare to schedule ++ * regular tasks. ++ */ ++ balance_push_set(cpu, false); ++ ++ /* ++ * When going up, increment the number of cores with SMT present. ++ */ ++ sched_smt_present_inc(cpu); ++ if (sched_smp_initialized) ++ sched_topology_hotplug_rebuild(cpu, true); ++ ++ set_cpu_active(cpu, true); ++ ++ if (sched_smp_initialized) ++ cpuset_cpu_active(); ++ ++ /* ++ * Put the rq online, if not already. This happens: ++ * ++ * 1) In the early boot process, because we build the real domains ++ * after all cpus have been brought up. ++ * ++ * 2) At runtime, if cpuset_cpu_active() fails to rebuild the ++ * domains. ++ */ ++ sched_set_rq_online(rq, cpu); ++ ++ return 0; ++} ++ ++int sched_cpu_deactivate(unsigned int cpu) ++{ ++ struct rq *rq = cpu_rq(cpu); ++ ++ set_cpu_active(cpu, false); ++ ++ /* ++ * From this point forward, this CPU will refuse to run any task that ++ * is not: migrate_disable() or KTHREAD_IS_PER_CPU, and will actively ++ * push those tasks away until this gets cleared, see ++ * sched_cpu_dying(). ++ */ ++ balance_push_set(cpu, true); ++ ++ /* ++ * We've cleared cpu_active_mask, wait for all preempt-disabled and RCU ++ * users of this state to go away such that all new such users will ++ * observe it. ++ * ++ * Specifically, we rely on ttwu to no longer target this CPU, see ++ * ttwu_queue_cond() and is_cpu_allowed(). ++ * ++ * Do sync before park smpboot threads to take care the RCU boost case. ++ */ ++ synchronize_rcu(); ++ ++ sched_set_rq_offline(rq, cpu); ++ ++ /* ++ * When going down, decrement the number of cores with SMT present. ++ */ ++ sched_smt_present_dec(cpu); ++ ++ if (!sched_smp_initialized) ++ return 0; ++ ++ sched_topology_hotplug_rebuild(cpu, false); ++ cpuset_cpu_inactive(cpu); ++ ++ return 0; ++} ++ ++static void sched_rq_cpu_starting(unsigned int cpu) ++{ ++ struct rq *rq = cpu_rq(cpu); ++ ++ rq->calc_load_update = calc_load_update; ++} ++ ++int sched_cpu_starting(unsigned int cpu) ++{ ++ sched_rq_cpu_starting(cpu); ++ sched_tick_start(cpu); ++ return 0; ++} ++ ++#ifdef CONFIG_HOTPLUG_CPU ++ ++/* ++ * Invoked immediately before the stopper thread is invoked to bring the ++ * CPU down completely. At this point all per CPU kthreads except the ++ * hotplug thread (current) and the stopper thread (inactive) have been ++ * either parked or have been unbound from the outgoing CPU. Ensure that ++ * any of those which might be on the way out are gone. ++ * ++ * If after this point a bound task is being woken on this CPU then the ++ * responsible hotplug callback has failed to do it's job. ++ * sched_cpu_dying() will catch it with the appropriate fireworks. ++ */ ++int sched_cpu_wait_empty(unsigned int cpu) ++{ ++ balance_hotplug_wait(); ++ sched_force_init_mm(); ++ return 0; ++} ++ ++/* ++ * Since this CPU is going 'away' for a while, fold any nr_active delta we ++ * might have. Called from the CPU stopper task after ensuring that the ++ * stopper is the last running task on the CPU, so nr_active count is ++ * stable. We need to take the tear-down thread which is calling this into ++ * account, so we hand in adjust = 1 to the load calculation. ++ * ++ * Also see the comment "Global load-average calculations". ++ */ ++static void calc_load_migrate(struct rq *rq) ++{ ++ long delta = calc_load_fold_active(rq, 1); ++ ++ if (delta) ++ atomic_long_add(delta, &calc_load_tasks); ++} ++ ++static void dump_rq_tasks(struct rq *rq, const char *loglvl) ++{ ++ struct task_struct *g, *p; ++ int cpu = cpu_of(rq); ++ ++ lockdep_assert_rq_held(rq); ++ ++ printk("%sCPU%d enqueued tasks (%u total):\n", loglvl, cpu, rq->nr_running); ++ for_each_process_thread(g, p) { ++ if (task_cpu(p) != cpu) ++ continue; ++ ++ if (!task_on_rq_queued(p)) ++ continue; ++ ++ printk("%s\tpid: %d, name: %s\n", loglvl, p->pid, p->comm); ++ } ++} ++ ++int sched_cpu_dying(unsigned int cpu) ++{ ++ struct rq *rq = cpu_rq(cpu); ++ unsigned long flags; ++ ++ /* Handle pending wakeups and then migrate everything off */ ++ sched_tick_stop(cpu); ++ ++ raw_spin_rq_lock_irqsave(rq, flags); ++ update_rq_clock(rq); ++ if (rq->nr_running != 1 || rq_has_pinned_tasks(rq)) { ++ WARN(true, "Dying CPU not properly vacated!"); ++ dump_rq_tasks(rq, KERN_WARNING); ++ } ++ raw_spin_rq_unlock_irqrestore(rq, flags); ++ ++ calc_load_migrate(rq); ++ hrtick_clear(rq); ++ return 0; ++} ++#endif /* CONFIG_HOTPLUG_CPU */ ++ ++static void sched_init_topology_cpumask_early(void) ++{ ++ int cpu, level; ++ cpumask_t *topo; ++ ++ for_each_possible_cpu(cpu) { ++ topo = per_cpu(sched_cpu_topo_masks, cpu); ++ for (level = 0; level < NR_CPU_AFFINITY_LEVELS; level++) ++ cpumask_clear(topo + level); ++ ++ cpumask_copy(topo + SCHED_CPU_AFFINITY_OTHER, ++ cpu_possible_mask); ++ per_cpu(sched_cpu_llc_mask, cpu) = ++ topo + SCHED_CPU_AFFINITY_LLC; ++ per_cpu(sched_cpu_topo_end_mask, cpu) = ++ topo + NR_CPU_AFFINITY_LEVELS; ++ per_cpu(sd_llc_id, cpu) = -1; ++ per_cpu(sd_llc_size, cpu) = cpumask_weight(cpu_possible_mask); ++ per_cpu(sched_cpu_topology_valid, cpu) = false; ++ } ++} ++ ++static bool sched_assign_llc_id(int cpu, const struct cpumask *active_mask) ++{ ++ int id, peer; ++ ++ cpumask_clear(&sched_llc_id_merge_mask); ++ if (per_cpu(sched_cpu_topology_valid, cpu) && ++ per_cpu(sd_llc_id, cpu) >= 0) ++ cpumask_set_cpu(per_cpu(sd_llc_id, cpu), ++ &sched_llc_id_merge_mask); ++ ++ for_each_cpu_and(peer, cpu_coregroup_mask(cpu), active_mask) { ++ if (peer == cpu || ++ !per_cpu(sched_cpu_topology_valid, peer)) ++ continue; ++ ++ id = per_cpu(sd_llc_id, peer); ++ if (id >= 0) ++ cpumask_set_cpu(id, &sched_llc_id_merge_mask); ++ } ++ ++ if (cpumask_empty(&sched_llc_id_merge_mask)) { ++ per_cpu(sd_llc_id, cpu) = cpu; ++ return false; ++ } ++ ++ id = cpumask_first(&sched_llc_id_merge_mask); ++ per_cpu(sd_llc_id, cpu) = id; ++ ++ if (cpumask_weight(&sched_llc_id_merge_mask) == 1) ++ return false; ++ ++ /* ++ * Independently discovered offline components can carry different ++ * tokens until they first become co-active. Merge every retained ++ * member so future hotplug cannot split the cache domain again. ++ */ ++ for_each_possible_cpu(peer) { ++ if (per_cpu(sched_cpu_topology_valid, peer) && ++ cpumask_test_cpu(per_cpu(sd_llc_id, peer), ++ &sched_llc_id_merge_mask)) ++ per_cpu(sd_llc_id, peer) = id; ++ } ++ ++ return true; ++} ++ ++static bool sched_build_topology_cpumask(int cpu, ++ const struct cpumask *active_mask) ++{ ++ cpumask_t *topo = per_cpu(sched_cpu_topo_masks, cpu); ++ bool llc_id_merged; ++ int level; ++ ++ for (level = 0; level < NR_CPU_AFFINITY_LEVELS; level++) ++ cpumask_clear(topo + level); ++ ++#ifdef CONFIG_SCHED_SMT ++ cpumask_and(topo + SCHED_CPU_AFFINITY_SMT, active_mask, ++ topology_sibling_cpumask(cpu)); ++#endif /* CONFIG_SCHED_SMT */ ++ cpumask_and(topo + SCHED_CPU_AFFINITY_CLUSTER, active_mask, ++ topology_cluster_cpumask(cpu)); ++ cpumask_and(topo + SCHED_CPU_AFFINITY_LLC, active_mask, ++ cpu_coregroup_mask(cpu)); ++ cpumask_and(topo + SCHED_CPU_AFFINITY_CORE, active_mask, ++ topology_core_cpumask(cpu)); ++ cpumask_copy(topo + SCHED_CPU_AFFINITY_OTHER, active_mask); ++ ++ per_cpu(sched_cpu_llc_mask, cpu) = ++ topo + SCHED_CPU_AFFINITY_LLC; ++ per_cpu(sched_cpu_topo_end_mask, cpu) = ++ topo + NR_CPU_AFFINITY_LEVELS; ++ ++ llc_id_merged = sched_assign_llc_id(cpu, active_mask); ++ per_cpu(sd_llc_size, cpu) = ++ max_t(int, 1, cpumask_weight_and(active_mask, ++ cpu_coregroup_mask(cpu))); ++ per_cpu(sched_cpu_topology_valid, cpu) = true; ++ ++ return llc_id_merged; ++} ++ ++static void sched_topology_add_cpu(int cpu, int added_cpu) ++{ ++ cpumask_t *topo = per_cpu(sched_cpu_topo_masks, cpu); ++ ++#ifdef CONFIG_SCHED_SMT ++ if (cpumask_test_cpu(added_cpu, topology_sibling_cpumask(cpu))) ++ cpumask_set_cpu(added_cpu, ++ topo + SCHED_CPU_AFFINITY_SMT); ++#endif ++ if (cpumask_test_cpu(added_cpu, topology_cluster_cpumask(cpu))) ++ cpumask_set_cpu(added_cpu, ++ topo + SCHED_CPU_AFFINITY_CLUSTER); ++ if (cpumask_test_cpu(added_cpu, cpu_coregroup_mask(cpu))) ++ cpumask_set_cpu(added_cpu, ++ topo + SCHED_CPU_AFFINITY_LLC); ++ if (cpumask_test_cpu(added_cpu, topology_core_cpumask(cpu))) ++ cpumask_set_cpu(added_cpu, ++ topo + SCHED_CPU_AFFINITY_CORE); ++ cpumask_set_cpu(added_cpu, topo + SCHED_CPU_AFFINITY_OTHER); ++} ++ ++static void sched_topology_remove_cpu(int cpu, int removed_cpu) ++{ ++ cpumask_t *topo = per_cpu(sched_cpu_topo_masks, cpu); ++ int level; ++ ++ for (level = 0; level < NR_CPU_AFFINITY_LEVELS; level++) ++ cpumask_clear_cpu(removed_cpu, topo + level); ++} ++ ++static void sched_topology_update_llc_size(const struct cpumask *active_mask, ++ int changed_cpu) ++{ ++ int cpu; ++ ++ for_each_cpu_and(cpu, cpu_coregroup_mask(changed_cpu), active_mask) ++ per_cpu(sd_llc_size, cpu) = ++ max_t(int, 1, cpumask_weight_and(active_mask, ++ cpu_coregroup_mask(cpu))); ++} ++ ++enum sched_topology_update { ++ SCHED_TOPOLOGY_BOOT, ++ SCHED_TOPOLOGY_ACTIVATE, ++ SCHED_TOPOLOGY_DEACTIVATE, ++}; ++ ++struct sched_topology_rebuild_context { ++ cpumask_t active_mask; ++ enum sched_topology_update update; ++ unsigned int cpu; ++ bool llc_id_merged; ++}; ++ ++/* Boot and CPU hotplug are serialized, so one context is sufficient. */ ++static struct sched_topology_rebuild_context sched_topology_context; ++ ++static void ++sched_topology_boot_update(const struct sched_topology_rebuild_context *ctx) ++{ ++ int cpu; ++ ++ for_each_cpu(cpu, &ctx->active_mask) { ++ cpu_rq(cpu)->idle->time_slice = sysctl_sched_base_slice; ++ sched_build_topology_cpumask(cpu, &ctx->active_mask); ++ } ++} ++ ++static void ++sched_topology_activate_update(struct sched_topology_rebuild_context *ctx) ++{ ++ int cpu, incoming = ctx->cpu; ++ ++ ctx->llc_id_merged = ++ sched_build_topology_cpumask(incoming, &ctx->active_mask); ++ ++ for_each_cpu(cpu, cpu_active_mask) { ++ sched_topology_add_cpu(cpu, incoming); ++ if (cpumask_test_cpu(incoming, cpu_coregroup_mask(cpu))) ++ per_cpu(sd_llc_size, cpu) = ++ max_t(int, 1, ++ cpumask_weight_and(&ctx->active_mask, ++ cpu_coregroup_mask(cpu))); ++ } ++} ++ ++static void ++sched_topology_deactivate_update(const struct sched_topology_rebuild_context *ctx) ++{ ++ int cpu, outgoing = ctx->cpu; ++ ++ for_each_cpu(cpu, &ctx->active_mask) ++ sched_topology_remove_cpu(cpu, outgoing); ++ ++ sched_topology_update_llc_size(&ctx->active_mask, outgoing); ++} ++ ++static void ++sched_topology_extend_inactive_snapshots(int incoming, ++ const struct cpumask *active_mask, ++ bool llc_id_merged) ++{ ++ int cpu, peer; ++ ++ /* ++ * A sleeping task may retain an offline previous CPU. Keep that CPU's ++ * locality row useful without extending the stop-machine section. ++ * Individual cpumask bit operations are atomic against lockless readers, ++ * and every placement candidate is independently restricted to active ++ * CPUs. ++ * ++ * Do not remove relationships when another CPU is deactivated. Some ++ * architectures clear their sibling masks later in CPU teardown, so ++ * that learned locality might be impossible to reconstruct. ++ */ ++ for_each_possible_cpu(cpu) { ++ cpumask_t *topo; ++ ++ if (cpu == incoming || cpu_active(cpu) || ++ !per_cpu(sched_cpu_topology_valid, cpu)) ++ continue; ++ ++ sched_topology_add_cpu(cpu, incoming); ++ ++ /* ++ * Retained architectural masks may already be cleared. A stable ++ * LLC token can still recover the cache and enclosing domains. ++ */ ++ if (per_cpu(sd_llc_id, cpu) != per_cpu(sd_llc_id, incoming)) ++ continue; ++ ++ topo = per_cpu(sched_cpu_topo_masks, cpu); ++ cpumask_set_cpu(incoming, topo + SCHED_CPU_AFFINITY_LLC); ++ cpumask_set_cpu(incoming, topo + SCHED_CPU_AFFINITY_CORE); ++ ++ if (!llc_id_merged) ++ continue; ++ ++ /* ++ * Token convergence joins independently retained components. ++ * Promote every active member of the joined LLC into every ++ * inactive row; otherwise those components stay topologically ++ * split even though cpus_share_cache() now agrees. ++ */ ++ for_each_cpu(peer, active_mask) { ++ if (!per_cpu(sched_cpu_topology_valid, peer) || ++ per_cpu(sd_llc_id, peer) != ++ per_cpu(sd_llc_id, incoming)) ++ continue; ++ ++ sched_topology_add_cpu(cpu, peer); ++ cpumask_set_cpu(peer, ++ topo + SCHED_CPU_AFFINITY_LLC); ++ cpumask_set_cpu(peer, ++ topo + SCHED_CPU_AFFINITY_CORE); ++ } ++ } ++} ++ ++static int sched_rebuild_topology_stop(void *data) ++{ ++ struct sched_topology_rebuild_context *ctx = data; ++ ++ sched_topology_apply(&ctx->active_mask); ++ ++ switch (ctx->update) { ++ case SCHED_TOPOLOGY_BOOT: ++ sched_topology_boot_update(ctx); ++ break; ++ case SCHED_TOPOLOGY_ACTIVATE: ++ sched_topology_activate_update(ctx); ++ break; ++ case SCHED_TOPOLOGY_DEACTIVATE: ++ sched_topology_deactivate_update(ctx); ++ break; ++ } ++ ++ return 0; ++} ++ ++static void sched_topology_hotplug_rebuild(unsigned int cpu, bool activate) ++{ ++ unsigned long flags; ++ int ret; ++ ++ cpumask_copy(&sched_topology_context.active_mask, cpu_active_mask); ++ if (activate) ++ cpumask_set_cpu(cpu, &sched_topology_context.active_mask); ++ ++ sched_topology_context.cpu = cpu; ++ sched_topology_context.update = activate ? ++ SCHED_TOPOLOGY_ACTIVATE : SCHED_TOPOLOGY_DEACTIVATE; ++ sched_topology_context.llc_id_merged = false; ++ ++ sched_topology_prepare(&sched_topology_context.active_mask); ++ ++ /* A preemption here would leave the other CPUs spinning with IRQs off. */ ++ local_irq_save(flags); ++ ret = stop_machine_from_inactive_cpu(sched_rebuild_topology_stop, ++ &sched_topology_context, ++ cpumask_of(cpu)); ++ local_irq_restore(flags); ++ ++ if (WARN_ON_ONCE(ret)) ++ return; ++ ++ if (activate) { ++ const struct cpumask *active_mask = ++ &sched_topology_context.active_mask; ++ bool llc_id_merged = sched_topology_context.llc_id_merged; ++ ++ sched_topology_extend_inactive_snapshots(cpu, active_mask, llc_id_merged); ++ } ++ sched_topology_report(); ++ sched_topology_queue_idle_select(); ++} ++ ++void __init sched_init_smp(void) ++{ ++ int ret; ++ ++ /* Move init over to a non-isolated CPU */ ++ if (set_cpus_allowed_ptr(current, housekeeping_cpumask(HK_TYPE_DOMAIN)) < 0) ++ BUG(); ++ current->flags &= ~PF_NO_SETAFFINITY; ++ ++ cpumask_copy(&sched_topology_context.active_mask, cpu_active_mask); ++ sched_topology_context.update = SCHED_TOPOLOGY_BOOT; ++ sched_topology_context.cpu = nr_cpu_ids; ++ sched_topology_context.llc_id_merged = false; ++ ++ sched_topology_prepare(&sched_topology_context.active_mask); ++ ret = stop_machine(sched_rebuild_topology_stop, ++ &sched_topology_context, NULL); ++ if (!WARN_ON_ONCE(ret)) { ++ sched_topology_report(); ++ sched_topology_init_idle_select(); ++ } ++ ++ sched_smp_initialized = true; ++} ++ ++static int __init migration_init(void) ++{ ++ sched_cpu_starting(smp_processor_id()); ++ return 0; ++} ++early_initcall(migration_init); ++ ++int in_sched_functions(unsigned long addr) ++{ ++ return in_lock_functions(addr) || ++ (addr >= (unsigned long)__sched_text_start ++ && addr < (unsigned long)__sched_text_end); ++} ++ ++#ifdef CONFIG_CGROUP_SCHED ++/* ++ * Default task group. ++ * Every task in system belongs to this group at bootup. ++ */ ++struct task_group root_task_group; ++LIST_HEAD(task_groups); ++ ++/* Cacheline aligned slab cache for task_group */ ++static struct kmem_cache *task_group_cache __ro_after_init; ++#endif /* CONFIG_CGROUP_SCHED */ ++ ++void __init sched_init(void) ++{ ++ int i; ++ struct rq *rq; ++ ++ printk(KERN_INFO "sched/alt: "ALT_SCHED_NAME" CPU Scheduler "ALT_SCHED_VERSION\ ++ " by Alfred Chen.\n"); ++ ++ wait_bit_init(); ++ ++ for (i = 0; i < SCHED_QUEUE_BITS; i++) ++ cpumask_copy(sched_preempt_mask + i, cpu_present_mask); ++ ++#ifdef CONFIG_CGROUP_SCHED ++ task_group_cache = KMEM_CACHE(task_group, 0); ++ ++ list_add(&root_task_group.list, &task_groups); ++ INIT_LIST_HEAD(&root_task_group.children); ++ INIT_LIST_HEAD(&root_task_group.siblings); ++#endif /* CONFIG_CGROUP_SCHED */ ++ for_each_possible_cpu(i) { ++ rq = cpu_rq(i); ++ ++#ifdef CONFIG_SCHED_SMT ++ raw_spin_lock_init(&per_cpu(sched_smt_idle_lock, i)); ++#endif ++ sched_queue_init(&rq->queue); ++ sched_rq_set_prio(rq, IDLE_TASK_SCHED_PRIO); ++ rq->prio_balance_time = 0; ++ ++ raw_spin_lock_init(rq_lockp(rq)); ++ rq->nr_running = rq->nr_uninterruptible = 0; ++ rq->calc_load_active = 0; ++ rq->calc_load_update = jiffies + LOAD_FREQ; ++ rq->online = false; ++ rq->cpu = i; ++ ++ rq->active_balance_arg.active = 0; ++ ++#ifdef CONFIG_NO_HZ_COMMON ++ INIT_CSD(&rq->nohz_csd, nohz_csd_func, rq); ++#endif ++ rq->balance_callback = &balance_push_callback; ++#ifdef CONFIG_HOTPLUG_CPU ++ rcuwait_init(&rq->hotplug_wait); ++#endif ++ rq->nr_switches = 0; ++ ++ hrtick_rq_init(rq); ++ atomic_set(&rq->nr_iowait, 0); ++ ++ zalloc_cpumask_var_node(&rq->scratch_mask, GFP_KERNEL, cpu_to_node(i)); ++ } ++ /* Set rq->online for cpu 0 */ ++ cpu_rq(0)->online = true; ++ /* ++ * The boot idle thread does lazy MMU switching as well: ++ */ ++ mmgrab_lazy_tlb(&init_mm); ++ enter_lazy_tlb(&init_mm, current); ++ ++ /* ++ * The idle task doesn't need the kthread struct to function, but it ++ * is dressed up as a per-CPU kthread and thus needs to play the part ++ * if we want to avoid special-casing it in code that deals with per-CPU ++ * kthreads. ++ */ ++ WARN_ON(!set_kthread_struct(current)); ++ ++ /* ++ * Make us the idle thread. Technically, schedule() should not be ++ * called from this thread, however somewhere below it might be, ++ * but because we are the idle thread, we just pick up running again ++ * when this runqueue becomes "idle". ++ */ ++ __sched_fork(0, current); ++ init_idle(current, smp_processor_id()); ++ ++ calc_load_update = jiffies + LOAD_FREQ; ++ ++ idle_thread_set_boot_cpu(); ++ balance_push_set(smp_processor_id(), false); ++ ++ sched_init_topology_cpumask_early(); ++ ++ psi_init(); ++ ++ preempt_dynamic_init(); ++} ++ ++#ifdef CONFIG_DEBUG_ATOMIC_SLEEP ++ ++void __might_sleep(const char *file, int line) ++{ ++ unsigned int state = get_current_state(); ++ /* ++ * Blocking primitives will set (and therefore destroy) current->state, ++ * since we will exit with TASK_RUNNING make sure we enter with it, ++ * otherwise we will destroy state. ++ */ ++ WARN_ONCE(state != TASK_RUNNING && current->task_state_change, ++ "do not call blocking ops when !TASK_RUNNING; " ++ "state=%x set at [<%p>] %pS\n", state, ++ (void *)current->task_state_change, ++ (void *)current->task_state_change); ++ ++ __might_resched(file, line, 0); ++} ++EXPORT_SYMBOL(__might_sleep); ++ ++static void print_preempt_disable_ip(int preempt_offset, unsigned long ip) ++{ ++ if (!IS_ENABLED(CONFIG_DEBUG_PREEMPT)) ++ return; ++ ++ if (preempt_count() == preempt_offset) ++ return; ++ ++ pr_err("Preemption disabled at:"); ++ print_ip_sym(KERN_ERR, ip); ++} ++ ++static inline bool resched_offsets_ok(unsigned int offsets) ++{ ++ unsigned int nested = preempt_count(); ++ ++ nested += rcu_preempt_depth() << MIGHT_RESCHED_RCU_SHIFT; ++ ++ return nested == offsets; ++} ++ ++void __might_resched(const char *file, int line, unsigned int offsets) ++{ ++ /* Ratelimiting timestamp: */ ++ static unsigned long prev_jiffy; ++ ++ unsigned long preempt_disable_ip; ++ ++ /* WARN_ON_ONCE() by default, no rate limit required: */ ++ rcu_sleep_check(); ++ ++ if ((resched_offsets_ok(offsets) && !irqs_disabled() && ++ !is_idle_task(current) && !current->non_block_count) || ++ system_state == SYSTEM_BOOTING || system_state > SYSTEM_RUNNING || ++ oops_in_progress) ++ return; ++ if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy) ++ return; ++ prev_jiffy = jiffies; ++ ++ /* Save this before calling printk(), since that will clobber it: */ ++ preempt_disable_ip = get_preempt_disable_ip(current); ++ ++ pr_err("BUG: sleeping function called from invalid context at %s:%d\n", ++ file, line); ++ pr_err("in_atomic(): %d, irqs_disabled(): %d, non_block: %d, pid: %d, name: %s\n", ++ in_atomic(), irqs_disabled(), current->non_block_count, ++ current->pid, current->comm); ++ pr_err("preempt_count: %x, expected: %x\n", preempt_count(), ++ offsets & MIGHT_RESCHED_PREEMPT_MASK); ++ ++ if (IS_ENABLED(CONFIG_PREEMPT_RCU)) { ++ pr_err("RCU nest depth: %d, expected: %u\n", ++ rcu_preempt_depth(), offsets >> MIGHT_RESCHED_RCU_SHIFT); ++ } ++ ++ if (task_stack_end_corrupted(current)) ++ pr_emerg("Thread overran stack, or stack corrupted\n"); ++ ++ debug_show_held_locks(current); ++ if (irqs_disabled()) ++ print_irqtrace_events(current); ++ ++ print_preempt_disable_ip(offsets & MIGHT_RESCHED_PREEMPT_MASK, ++ preempt_disable_ip); ++ ++ dump_stack(); ++ add_taint(TAINT_WARN, LOCKDEP_STILL_OK); ++} ++EXPORT_SYMBOL(__might_resched); ++ ++void __cant_sleep(const char *file, int line) ++{ ++ static unsigned long prev_jiffy; ++ ++ if (irqs_disabled()) ++ return; ++ ++ if (!IS_ENABLED(CONFIG_PREEMPT_COUNT)) ++ return; ++ ++ if (preempt_count()) ++ return; ++ ++ if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy) ++ return; ++ prev_jiffy = jiffies; ++ ++ printk(KERN_ERR "BUG: assuming atomic context at %s:%d\n", file, line); ++ printk(KERN_ERR "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n", ++ in_atomic(), irqs_disabled(), ++ current->pid, current->comm); ++ ++ debug_show_held_locks(current); ++ dump_stack(); ++ add_taint(TAINT_WARN, LOCKDEP_STILL_OK); ++} ++EXPORT_SYMBOL_GPL(__cant_sleep); ++ ++void __cant_migrate(const char *file, int line) ++{ ++ static unsigned long prev_jiffy; ++ ++ if (irqs_disabled()) ++ return; ++ ++ if (is_migration_disabled(current)) ++ return; ++ ++ if (!IS_ENABLED(CONFIG_PREEMPT_COUNT)) ++ return; ++ ++ if (preempt_count()) ++ return; ++ ++ if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy) ++ return; ++ prev_jiffy = jiffies; ++ ++ pr_err("BUG: assuming non migratable context at %s:%d\n", file, line); ++ pr_err("in_atomic(): %d, irqs_disabled(): %d, migration_disabled() %u pid: %d, name: %s\n", ++ in_atomic(), irqs_disabled(), is_migration_disabled(current), ++ current->pid, current->comm); ++ ++ debug_show_held_locks(current); ++ dump_stack(); ++ add_taint(TAINT_WARN, LOCKDEP_STILL_OK); ++} ++EXPORT_SYMBOL_GPL(__cant_migrate); ++#endif /* CONFIG_DEBUG_ATOMIC_SLEEP */ ++ ++#ifdef CONFIG_MAGIC_SYSRQ ++void normalize_rt_tasks(void) ++{ ++ struct task_struct *g, *p; ++ struct sched_attr attr = { ++ .sched_policy = SCHED_NORMAL, ++ }; ++ ++ read_lock(&tasklist_lock); ++ for_each_process_thread(g, p) { ++ /* ++ * Only normalize user tasks: ++ */ ++ if (p->flags & PF_KTHREAD) ++ continue; ++ ++ schedstat_set(p->stats.wait_start, 0); ++ schedstat_set(p->stats.sleep_start, 0); ++ schedstat_set(p->stats.block_start, 0); ++ ++ if (!rt_or_dl_task(p)) { ++ /* ++ * Renice negative nice level userspace ++ * tasks back to 0: ++ */ ++ if (task_nice(p) < 0) ++ set_user_nice(p, 0); ++ continue; ++ } ++ ++ __sched_setscheduler(p, &attr, false, false); ++ } ++ read_unlock(&tasklist_lock); ++} ++#endif /* CONFIG_MAGIC_SYSRQ */ ++ ++#ifdef CONFIG_KGDB_KDB ++/* ++ * These functions are only useful for KDB. ++ * ++ * They can only be called when the whole system has been ++ * stopped - every CPU needs to be quiescent, and no scheduling ++ * activity can take place. Using them for anything else would ++ * be a serious bug, and as a result, they aren't even visible ++ * under any other configuration. ++ */ ++ ++/** ++ * curr_task - return the current task for a given CPU. ++ * @cpu: the processor in question. ++ * ++ * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED! ++ * ++ * Return: The current task for @cpu. ++ */ ++struct task_struct *curr_task(int cpu) ++{ ++ return cpu_curr(cpu); ++} ++ ++#endif /* CONFIG_KGDB_KDB */ ++ ++#ifdef CONFIG_CGROUP_SCHED ++static void sched_free_group(struct task_group *tg) ++{ ++ kmem_cache_free(task_group_cache, tg); ++} ++ ++static void sched_free_group_rcu(struct rcu_head *rhp) ++{ ++ sched_free_group(container_of(rhp, struct task_group, rcu)); ++} ++ ++static void sched_unregister_group(struct task_group *tg) ++{ ++ /* ++ * We have to wait for yet another RCU grace period to expire, as ++ * print_cfs_stats() might run concurrently. ++ */ ++ call_rcu(&tg->rcu, sched_free_group_rcu); ++} ++ ++/* allocate runqueue etc for a new task group */ ++struct task_group *sched_create_group(struct task_group *parent) ++{ ++ struct task_group *tg; ++ ++ tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO); ++ if (!tg) ++ return ERR_PTR(-ENOMEM); ++ ++ return tg; ++} ++ ++void sched_online_group(struct task_group *tg, struct task_group *parent) ++{ ++} ++ ++/* RCU callback to free various structures associated with a task group */ ++static void sched_unregister_group_rcu(struct rcu_head *rhp) ++{ ++ /* Now it should be safe to free those cfs_rqs: */ ++ sched_unregister_group(container_of(rhp, struct task_group, rcu)); ++} ++ ++void sched_destroy_group(struct task_group *tg) ++{ ++ /* Wait for possible concurrent references to cfs_rqs complete: */ ++ call_rcu(&tg->rcu, sched_unregister_group_rcu); ++} ++ ++void sched_release_group(struct task_group *tg) ++{ ++} ++ ++static inline struct task_group *css_tg(struct cgroup_subsys_state *css) ++{ ++ return css ? container_of(css, struct task_group, css) : NULL; ++} ++ ++static struct cgroup_subsys_state * ++cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css) ++{ ++ struct task_group *parent = css_tg(parent_css); ++ struct task_group *tg; ++ ++ if (!parent) { ++ /* This is early initialization for the top cgroup */ ++ return &root_task_group.css; ++ } ++ ++ tg = sched_create_group(parent); ++ if (IS_ERR(tg)) ++ return ERR_PTR(-ENOMEM); ++ return &tg->css; ++} ++ ++/* Expose task group only after completing cgroup initialization */ ++static int cpu_cgroup_css_online(struct cgroup_subsys_state *css) ++{ ++ struct task_group *tg = css_tg(css); ++ struct task_group *parent = css_tg(css->parent); ++ ++ if (parent) ++ sched_online_group(tg, parent); ++ return 0; ++} ++ ++static void cpu_cgroup_css_released(struct cgroup_subsys_state *css) ++{ ++ struct task_group *tg = css_tg(css); ++ ++ sched_release_group(tg); ++} ++ ++static void cpu_cgroup_css_free(struct cgroup_subsys_state *css) ++{ ++ struct task_group *tg = css_tg(css); ++ ++ /* ++ * Relies on the RCU grace period between css_released() and this. ++ */ ++ sched_unregister_group(tg); ++} ++ ++#ifdef CONFIG_RT_GROUP_SCHED ++static int cpu_cgroup_can_attach(struct cgroup_taskset *tset) ++{ ++ return 0; ++} ++#endif /* CONFIG_RT_GROUP_SCHED */ ++ ++static void cpu_cgroup_attach(struct cgroup_taskset *tset) ++{ ++} ++ ++#ifdef CONFIG_GROUP_SCHED_WEIGHT ++static int sched_group_set_shares(struct task_group *tg, unsigned long shares) ++{ ++ return 0; ++} ++ ++static int sched_group_set_idle(struct task_group *tg, long idle) ++{ ++ return 0; ++} ++ ++static int cpu_shares_write_u64(struct cgroup_subsys_state *css, ++ struct cftype *cftype, u64 shareval) ++{ ++ return sched_group_set_shares(css_tg(css), shareval); ++} ++ ++static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css, ++ struct cftype *cft) ++{ ++ return 1024; ++} ++ ++static s64 cpu_idle_read_s64(struct cgroup_subsys_state *css, ++ struct cftype *cft) ++{ ++ return 0; ++} ++ ++static int cpu_idle_write_s64(struct cgroup_subsys_state *css, ++ struct cftype *cft, s64 idle) ++{ ++ return sched_group_set_idle(css_tg(css), idle); ++} ++#endif /* CONFIG_GROUP_SCHED_WEIGHT */ ++ ++#ifdef CONFIG_CFS_BANDWIDTH ++static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css, ++ struct cftype *cft) ++{ ++ return -1; ++} ++ ++static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css, ++ struct cftype *cftype, s64 cfs_quota_us) ++{ ++ return 0; ++} ++ ++static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css, ++ struct cftype *cft) ++{ ++ return 100000ULL; ++} ++ ++static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css, ++ struct cftype *cftype, u64 cfs_period_us) ++{ ++ return 0; ++} ++ ++static u64 cpu_cfs_burst_read_u64(struct cgroup_subsys_state *css, ++ struct cftype *cft) ++{ ++ return 0; ++} ++ ++static int cpu_cfs_burst_write_u64(struct cgroup_subsys_state *css, ++ struct cftype *cftype, u64 cfs_burst_us) ++{ ++ return 0; ++} ++ ++static int cpu_cfs_stat_show(struct seq_file *sf, void *v) ++{ ++ return 0; ++} ++ ++static int cpu_cfs_local_stat_show(struct seq_file *sf, void *v) ++{ ++ return 0; ++} ++#endif /* CONFIG_CFS_BANDWIDTH */ ++ ++#ifdef CONFIG_RT_GROUP_SCHED ++static int cpu_rt_runtime_write(struct cgroup_subsys_state *css, ++ struct cftype *cft, s64 val) ++{ ++ return 0; ++} ++ ++static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css, ++ struct cftype *cft) ++{ ++ return 0; ++} ++ ++static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css, ++ struct cftype *cftype, u64 rt_period_us) ++{ ++ return 0; ++} ++ ++static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css, ++ struct cftype *cft) ++{ ++ return 0; ++} ++#endif /* CONFIG_RT_GROUP_SCHED */ ++ ++#ifdef CONFIG_UCLAMP_TASK_GROUP ++static int cpu_uclamp_min_show(struct seq_file *sf, void *v) ++{ ++ seq_puts(sf, "0\n"); ++ return 0; ++} ++ ++static int cpu_uclamp_max_show(struct seq_file *sf, void *v) ++{ ++ seq_puts(sf, "max\n"); ++ return 0; ++} ++ ++static ssize_t cpu_uclamp_min_write(struct kernfs_open_file *of, ++ char *buf, size_t nbytes, ++ loff_t off) ++{ ++ return nbytes; ++} ++ ++static ssize_t cpu_uclamp_max_write(struct kernfs_open_file *of, ++ char *buf, size_t nbytes, ++ loff_t off) ++{ ++ return nbytes; ++} ++#endif /* CONFIG_UCLAMP_TASK_GROUP */ ++ ++static struct cftype cpu_legacy_files[] = { ++#ifdef CONFIG_GROUP_SCHED_WEIGHT ++ { ++ .name = "shares", ++ .read_u64 = cpu_shares_read_u64, ++ .write_u64 = cpu_shares_write_u64, ++ }, ++ { ++ .name = "idle", ++ .read_s64 = cpu_idle_read_s64, ++ .write_s64 = cpu_idle_write_s64, ++ }, ++#endif /* CONFIG_GROUP_SCHED_WEIGHT */ ++#ifdef CONFIG_CFS_BANDWIDTH ++ { ++ .name = "cfs_quota_us", ++ .read_s64 = cpu_cfs_quota_read_s64, ++ .write_s64 = cpu_cfs_quota_write_s64, ++ }, ++ { ++ .name = "cfs_period_us", ++ .read_u64 = cpu_cfs_period_read_u64, ++ .write_u64 = cpu_cfs_period_write_u64, ++ }, ++ { ++ .name = "cfs_burst_us", ++ .read_u64 = cpu_cfs_burst_read_u64, ++ .write_u64 = cpu_cfs_burst_write_u64, ++ }, ++ { ++ .name = "stat", ++ .seq_show = cpu_cfs_stat_show, ++ }, ++ { ++ .name = "stat.local", ++ .seq_show = cpu_cfs_local_stat_show, ++ }, ++#endif /* CONFIG_CFS_BANDWIDTH */ ++#ifdef CONFIG_RT_GROUP_SCHED ++ { ++ .name = "rt_runtime_us", ++ .read_s64 = cpu_rt_runtime_read, ++ .write_s64 = cpu_rt_runtime_write, ++ }, ++ { ++ .name = "rt_period_us", ++ .read_u64 = cpu_rt_period_read_uint, ++ .write_u64 = cpu_rt_period_write_uint, ++ }, ++#endif /* CONFIG_RT_GROUP_SCHED */ ++#ifdef CONFIG_UCLAMP_TASK_GROUP ++ { ++ .name = "uclamp.min", ++ .flags = CFTYPE_NOT_ON_ROOT, ++ .seq_show = cpu_uclamp_min_show, ++ .write = cpu_uclamp_min_write, ++ }, ++ { ++ .name = "uclamp.max", ++ .flags = CFTYPE_NOT_ON_ROOT, ++ .seq_show = cpu_uclamp_max_show, ++ .write = cpu_uclamp_max_write, ++ }, ++#endif /* CONFIG_UCLAMP_TASK_GROUP */ ++ { } /* Terminate */ ++}; ++ ++#ifdef CONFIG_GROUP_SCHED_WEIGHT ++static u64 cpu_weight_read_u64(struct cgroup_subsys_state *css, ++ struct cftype *cft) ++{ ++ return 100; ++} ++ ++static int cpu_weight_write_u64(struct cgroup_subsys_state *css, ++ struct cftype *cft, u64 weight) ++{ ++ return 0; ++} ++ ++static s64 cpu_weight_nice_read_s64(struct cgroup_subsys_state *css, ++ struct cftype *cft) ++{ ++ return 0; ++} ++ ++static int cpu_weight_nice_write_s64(struct cgroup_subsys_state *css, ++ struct cftype *cft, s64 nice) ++{ ++ return 0; ++} ++#endif /* CONFIG_GROUP_SCHED_WEIGHT */ ++ ++#ifdef CONFIG_CFS_BANDWIDTH ++static int cpu_max_show(struct seq_file *sf, void *v) ++{ ++ seq_puts(sf, "max 100000\n"); ++ return 0; ++} ++ ++static ssize_t cpu_max_write(struct kernfs_open_file *of, ++ char *buf, size_t nbytes, loff_t off) ++{ ++ return nbytes; ++} ++#endif /* CONFIG_CFS_BANDWIDTH */ ++ ++static struct cftype cpu_files[] = { ++#ifdef CONFIG_GROUP_SCHED_WEIGHT ++ { ++ .name = "weight", ++ .flags = CFTYPE_NOT_ON_ROOT, ++ .read_u64 = cpu_weight_read_u64, ++ .write_u64 = cpu_weight_write_u64, ++ }, ++ { ++ .name = "weight.nice", ++ .flags = CFTYPE_NOT_ON_ROOT, ++ .read_s64 = cpu_weight_nice_read_s64, ++ .write_s64 = cpu_weight_nice_write_s64, ++ }, ++ { ++ .name = "idle", ++ .flags = CFTYPE_NOT_ON_ROOT, ++ .read_s64 = cpu_idle_read_s64, ++ .write_s64 = cpu_idle_write_s64, ++ }, ++#endif /* CONFIG_GROUP_SCHED_WEIGHT */ ++#ifdef CONFIG_CFS_BANDWIDTH ++ { ++ .name = "max", ++ .flags = CFTYPE_NOT_ON_ROOT, ++ .seq_show = cpu_max_show, ++ .write = cpu_max_write, ++ }, ++ { ++ .name = "max.burst", ++ .flags = CFTYPE_NOT_ON_ROOT, ++ .read_u64 = cpu_cfs_burst_read_u64, ++ .write_u64 = cpu_cfs_burst_write_u64, ++ }, ++#endif /* CONFIG_CFS_BANDWIDTH */ ++#ifdef CONFIG_UCLAMP_TASK_GROUP ++ { ++ .name = "uclamp.min", ++ .flags = CFTYPE_NOT_ON_ROOT, ++ .seq_show = cpu_uclamp_min_show, ++ .write = cpu_uclamp_min_write, ++ }, ++ { ++ .name = "uclamp.max", ++ .flags = CFTYPE_NOT_ON_ROOT, ++ .seq_show = cpu_uclamp_max_show, ++ .write = cpu_uclamp_max_write, ++ }, ++#endif /* CONFIG_UCLAMP_TASK_GROUP */ ++ { } /* terminate */ ++}; ++ ++static int cpu_extra_stat_show(struct seq_file *sf, ++ struct cgroup_subsys_state *css) ++{ ++ return 0; ++} ++ ++static int cpu_local_stat_show(struct seq_file *sf, ++ struct cgroup_subsys_state *css) ++{ ++ return 0; ++} ++ ++struct cgroup_subsys cpu_cgrp_subsys = { ++ .css_alloc = cpu_cgroup_css_alloc, ++ .css_online = cpu_cgroup_css_online, ++ .css_released = cpu_cgroup_css_released, ++ .css_free = cpu_cgroup_css_free, ++ .css_extra_stat_show = cpu_extra_stat_show, ++ .css_local_stat_show = cpu_local_stat_show, ++#ifdef CONFIG_RT_GROUP_SCHED ++ .can_attach = cpu_cgroup_can_attach, ++#endif /* CONFIG_RT_GROUP_SCHED */ ++ .attach = cpu_cgroup_attach, ++ .legacy_cftypes = cpu_legacy_files, ++ .dfl_cftypes = cpu_files, ++ .early_init = true, ++ .threaded = true, ++}; ++#endif /* CONFIG_CGROUP_SCHED */ ++ ++#undef CREATE_TRACE_POINTS ++ ++#ifdef CONFIG_SCHED_MM_CID ++/* ++ * Concurrency IDentifier management ++ * ++ * Serialization rules: ++ * ++ * mm::mm_cid::mutex: Serializes fork() and exit() and therefore ++ * protects mm::mm_cid::users and mode switch ++ * transitions ++ * ++ * mm::mm_cid::lock: Serializes mm_update_max_cids() and ++ * mm_update_cpus_allowed(). Nests in mm_cid::mutex ++ * and runqueue lock. ++ * ++ * The mm_cidmask bitmap is not protected by any of the mm::mm_cid locks ++ * and can only be modified with atomic operations. ++ * ++ * The mm::mm_cid:pcpu per CPU storage is protected by the CPUs runqueue ++ * lock. ++ * ++ * CID ownership: ++ * ++ * A CID is either owned by a task (stored in task_struct::mm_cid.cid) or ++ * by a CPU (stored in mm::mm_cid.pcpu::cid). CIDs owned by CPUs have the ++ * MM_CID_ONCPU bit set. ++ * ++ * During the transition of ownership mode, the MM_CID_TRANSIT bit is set ++ * on the CIDs. When this bit is set the tasks drop the CID back into the ++ * pool when scheduling out. ++ * ++ * Both bits (ONCPU and TRANSIT) are filtered out by task_cid() when the ++ * CID is actually handed over to user space in the RSEQ memory. ++ * ++ * Mode switching: ++ * ++ * The ownership mode is per process and stored in mm:mm_cid::mode with the ++ * following possible states: ++ * ++ * 0: Per task ownership ++ * 0 | MM_CID_TRANSIT: Transition from per CPU to per task ++ * MM_CID_ONCPU: Per CPU ownership ++ * MM_CID_ONCPU | MM_CID_TRANSIT: Transition from per task to per CPU ++ * ++ * All transitions of ownership mode happen in two phases: ++ * ++ * 1) mm:mm_cid::mode has the MM_CID_TRANSIT bit set. This is OR'ed on the ++ * CIDs and denotes that the CID is only temporarily owned by a ++ * task. When the task schedules out it drops the CID back into the ++ * pool if this bit is set. ++ * ++ * 2) The initiating context walks the per CPU space or the tasks to fixup ++ * or drop the CIDs and after completion it clears MM_CID_TRANSIT in ++ * mm:mm_cid::mode. After that point the CIDs are strictly task or CPU ++ * owned again. ++ * ++ * This two phase transition is required to prevent CID space exhaustion ++ * during the transition as a direct transfer of ownership would fail: ++ * ++ * - On task to CPU mode switch if a task is scheduled in on one CPU and ++ * then migrated to another CPU before the fixup freed enough per task ++ * CIDs. ++ * ++ * - On CPU to task mode switch if two tasks are scheduled in on the same ++ * CPU before the fixup freed per CPU CIDs. ++ * ++ * Both scenarios can result in a live lock because sched_in() is invoked ++ * with runqueue lock held and loops in search of a CID and the fixup ++ * thread can't make progress freeing them up because it is stuck on the ++ * same runqueue lock. ++ * ++ * While MM_CID_TRANSIT is active during the transition phase the MM_CID ++ * bitmap can be contended, but that's a temporary contention bound to the ++ * transition period. After that everything goes back into steady state and ++ * nothing except fork() and exit() will touch the bitmap. This is an ++ * acceptable tradeoff as it completely avoids complex serialization, ++ * memory barriers and atomic operations for the common case. ++ * ++ * Aside of that this mechanism also ensures RT compability: ++ * ++ * - The task which runs the fixup is fully preemptible except for the ++ * short runqueue lock held sections. ++ * ++ * - The transient impact of the bitmap contention is only problematic ++ * when there is a thundering herd scenario of tasks scheduling in and ++ * out concurrently. There is not much which can be done about that ++ * except for avoiding mode switching by a proper overall system ++ * configuration. ++ * ++ * Switching to per CPU mode happens when the user count becomes greater ++ * than the maximum number of CIDs, which is calculated by: ++ * ++ * opt_cids = min(mm_cid::nr_cpus_allowed, mm_cid::users); ++ * max_cids = min(1.25 * opt_cids, num_possible_cpus()); ++ * ++ * The +25% allowance is useful for tight CPU masks in scenarios where only ++ * a few threads are created and destroyed to avoid frequent mode ++ * switches. Though this allowance shrinks, the closer opt_cids becomes to ++ * num_possible_cpus(), which is the (unfortunate) hard ABI limit. ++ * ++ * At the point of switching to per CPU mode the new user is not yet ++ * visible in the system, so the task which initiated the fork() runs the ++ * fixup function. mm_cid_fixup_tasks_to_cpu() walks the thread list and ++ * either marks each task owned CID with MM_CID_TRANSIT if the task is ++ * running on a CPU or drops it into the CID pool if a task is not on a ++ * CPU. Tasks which schedule in before the task walk reaches them do the ++ * handover in mm_cid_schedin(). When mm_cid_fixup_tasks_to_cpus() ++ * completes it is guaranteed that no task related to that MM owns a CID ++ * anymore. ++ * ++ * Switching back to task mode happens when the user count goes below the ++ * threshold which was recorded on the per CPU mode switch: ++ * ++ * pcpu_thrs = min(opt_cids - (opt_cids / 4), num_possible_cpus() / 2); ++ * ++ * This threshold is updated when a affinity change increases the number of ++ * allowed CPUs for the MM, which might cause a switch back to per task ++ * mode. ++ * ++ * If the switch back was initiated by a exiting task, then that task runs ++ * the fixup function. If it was initiated by a affinity change, then it's ++ * run either in the deferred update function in context of a workqueue or ++ * by a task which forks a new one or by a task which exits. Whatever ++ * happens first. mm_cid_fixup_cpus_to_task() walks through the possible ++ * CPUs and either transfers the CPU owned CIDs to a related task which ++ * runs on the CPU or drops it into the pool. Tasks which schedule in on a ++ * CPU which the walk did not cover yet do the handover themself. ++ * ++ * This transition from CPU to per task ownership happens in two phases: ++ * ++ * 1) mm:mm_cid.transit contains MM_CID_TRANSIT This is OR'ed on the task ++ * CID and denotes that the CID is only temporarily owned by the ++ * task. When it schedules out the task drops the CID back into the ++ * pool if this bit is set. ++ * ++ * 2) The initiating context walks the per CPU space and after completion ++ * clears mm:mm_cid.transit. So after that point the CIDs are strictly ++ * task owned again. ++ * ++ * This two phase transition is required to prevent CID space exhaustion ++ * during the transition as a direct transfer of ownership would fail if ++ * two tasks are scheduled in on the same CPU before the fixup freed per ++ * CPU CIDs. ++ * ++ * When mm_cid_fixup_cpus_to_tasks() completes it's guaranteed that no CID ++ * related to that MM is owned by a CPU anymore. ++ */ ++ ++/* ++ * Update the CID range properties when the constraints change. Invoked via ++ * fork(), exit() and affinity changes ++ */ ++static void __mm_update_max_cids(struct mm_mm_cid *mc) ++{ ++ unsigned int opt_cids, max_cids; ++ ++ /* Calculate the new optimal constraint */ ++ opt_cids = min(mc->nr_cpus_allowed, mc->users); ++ ++ /* Adjust the maximum CIDs to +25% limited by the number of possible CPUs */ ++ max_cids = min(opt_cids + (opt_cids / 4), num_possible_cpus()); ++ WRITE_ONCE(mc->max_cids, max_cids); ++} ++ ++static inline unsigned int mm_cid_calc_pcpu_thrs(struct mm_mm_cid *mc) ++{ ++ unsigned int opt_cids; ++ ++ opt_cids = min(mc->nr_cpus_allowed, mc->users); ++ /* Has to be at least 1 because 0 indicates PCPU mode off */ ++ return max(min(opt_cids - opt_cids / 4, num_possible_cpus() / 2), 1); ++} ++ ++static bool mm_update_max_cids(struct mm_struct *mm) ++{ ++ struct mm_mm_cid *mc = &mm->mm_cid; ++ bool percpu = cid_on_cpu(mc->mode); ++ ++ lockdep_assert_held(&mm->mm_cid.lock); ++ ++ /* Clear deferred mode switch flag. A change is handled by the caller */ ++ mc->update_deferred = false; ++ __mm_update_max_cids(mc); ++ ++ /* Check whether owner mode must be changed */ ++ if (!percpu) { ++ /* Enable per CPU mode when the number of users is above max_cids */ ++ if (mc->users > mc->max_cids) ++ mc->pcpu_thrs = mm_cid_calc_pcpu_thrs(mc); ++ } else { ++ /* Switch back to per task if user count under threshold */ ++ if (mc->users < mc->pcpu_thrs) ++ mc->pcpu_thrs = 0; ++ } ++ ++ /* Mode change required? */ ++ if (percpu == !!mc->pcpu_thrs) ++ return false; ++ ++ /* Flip the mode and set the transition flag to bridge the transfer */ ++ WRITE_ONCE(mc->mode, mc->mode ^ (MM_CID_TRANSIT | MM_CID_ONCPU)); ++ /* ++ * Order the store against the subsequent fixups so that ++ * acquire(rq::lock) cannot be reordered by the CPU before the ++ * store. ++ */ ++ smp_mb(); ++ return true; ++} ++ ++static inline void mm_update_cpus_allowed(struct mm_struct *mm, const struct cpumask *affmsk) ++{ ++ struct cpumask *mm_allowed; ++ struct mm_mm_cid *mc; ++ unsigned int weight; ++ ++ if (!mm || !READ_ONCE(mm->mm_cid.users)) ++ return; ++ /* ++ * mm::mm_cid::mm_cpus_allowed is the superset of each threads ++ * allowed CPUs mask which means it can only grow. ++ */ ++ mc = &mm->mm_cid; ++ guard(raw_spinlock)(&mc->lock); ++ mm_allowed = mm_cpus_allowed(mm); ++ weight = cpumask_weighted_or(mm_allowed, mm_allowed, affmsk); ++ if (weight == mc->nr_cpus_allowed) ++ return; ++ ++ WRITE_ONCE(mc->nr_cpus_allowed, weight); ++ __mm_update_max_cids(mc); ++ if (!cid_on_cpu(mc->mode)) ++ return; ++ ++ /* Adjust the threshold to the wider set */ ++ mc->pcpu_thrs = mm_cid_calc_pcpu_thrs(mc); ++ /* Switch back to per task mode? */ ++ if (mc->users >= mc->pcpu_thrs) ++ return; ++ ++ /* Don't queue twice */ ++ if (mc->update_deferred) ++ return; ++ ++ /* Queue the irq work, which schedules the real work */ ++ mc->update_deferred = true; ++ irq_work_queue(&mc->irq_work); ++} ++ ++static inline void mm_cid_complete_transit(struct mm_struct *mm, unsigned int mode) ++{ ++ /* ++ * Ensure that the store removing the TRANSIT bit cannot be ++ * reordered by the CPU before the fixups have been completed. ++ */ ++ smp_mb(); ++ WRITE_ONCE(mm->mm_cid.mode, mode); ++} ++ ++static inline void mm_cid_transit_to_task(struct task_struct *t, struct mm_cid_pcpu *pcp) ++{ ++ if (cid_on_cpu(t->mm_cid.cid)) { ++ unsigned int cid = cpu_cid_to_cid(t->mm_cid.cid); ++ ++ t->mm_cid.cid = cid_to_transit_cid(cid); ++ pcp->cid = t->mm_cid.cid; ++ } ++} ++ ++static void mm_cid_fixup_cpus_to_tasks(struct mm_struct *mm) ++{ ++ unsigned int cpu; ++ ++ /* Walk the CPUs and fixup all stale CIDs */ ++ for_each_possible_cpu(cpu) { ++ struct mm_cid_pcpu *pcp = per_cpu_ptr(mm->mm_cid.pcpu, cpu); ++ struct rq *rq = cpu_rq(cpu); ++ ++ /* Remote access to mm::mm_cid::pcpu requires rq_lock */ ++ guard(rq_lock_irq)(rq); ++ /* Is the CID still owned by the CPU? */ ++ if (cid_on_cpu(pcp->cid)) { ++ /* ++ * If rq->curr has @mm, transfer it with the ++ * transition bit set. Otherwise drop it. ++ */ ++ if (rq->curr->mm == mm && rq->curr->mm_cid.active) ++ mm_cid_transit_to_task(rq->curr, pcp); ++ else ++ mm_drop_cid_on_cpu(mm, pcp); ++ ++ } else if (rq->curr->mm == mm && rq->curr->mm_cid.active) { ++ unsigned int cid = rq->curr->mm_cid.cid; ++ ++ /* ++ * Set the transition bit only on a genuine task-owned ++ * CID. A running active task can legitimately have ++ * MM_CID_UNSET here: in per-CPU mode CIDs are assigned ++ * lazily on schedule-in, so the fork()/execve() window ++ * leaves the task active with no owned CID. Setting the ++ * transition bit on MM_CID_UNSET would later feed ++ * clear_bit() an out-of-bounds bit number via ++ * mm_cid_schedout(), so exclude it. A CPU-owned ++ * (MM_CID_ONCPU) CID is handled by the cid_on_cpu() ++ * branch above and never reaches here. ++ */ ++ if (cid != MM_CID_UNSET && !cid_in_transit(cid)) { ++ cid = cid_to_transit_cid(cid); ++ rq->curr->mm_cid.cid = cid; ++ pcp->cid = cid; ++ } ++ } ++ } ++ mm_cid_complete_transit(mm, 0); ++} ++ ++static inline void mm_cid_transit_to_cpu(struct task_struct *t, struct mm_cid_pcpu *pcp) ++{ ++ if (cid_on_task(t->mm_cid.cid)) { ++ t->mm_cid.cid = cid_to_transit_cid(t->mm_cid.cid); ++ pcp->cid = t->mm_cid.cid; ++ } ++} ++ ++static void mm_cid_fixup_task_to_cpu(struct task_struct *t, struct mm_struct *mm) ++{ ++ /* Remote access to mm::mm_cid::pcpu requires rq_lock */ ++ guard(task_rq_lock)(t); ++ if (cid_on_task(t->mm_cid.cid)) { ++ /* If running on the CPU, put the CID in transit mode, otherwise drop it */ ++ if (task_rq(t)->curr == t) ++ mm_cid_transit_to_cpu(t, per_cpu_ptr(mm->mm_cid.pcpu, task_cpu(t))); ++ else ++ mm_unset_cid_on_task(t); ++ } ++} ++ ++static void mm_cid_fixup_tasks_to_cpus(void) ++{ ++ struct mm_struct *mm = current->mm; ++ struct task_struct *t; ++ ++ lockdep_assert_held(&mm->mm_cid.mutex); ++ ++ hlist_for_each_entry(t, &mm->mm_cid.user_list, mm_cid.node) { ++ /* Current has already transferred before invoking the fixup. */ ++ if (t != current) ++ mm_cid_fixup_task_to_cpu(t, mm); ++ } ++ ++ mm_cid_complete_transit(mm, MM_CID_ONCPU); ++} ++ ++static bool sched_mm_cid_add_user(struct task_struct *t, struct mm_struct *mm) ++{ ++ lockdep_assert_held(&mm->mm_cid.lock); ++ ++ t->mm_cid.active = 1; ++ hlist_add_head(&t->mm_cid.node, &mm->mm_cid.user_list); ++ mm->mm_cid.users++; ++ return mm_update_max_cids(mm); ++} ++ ++static void sched_mm_cid_fork(struct task_struct *t) ++{ ++ struct mm_struct *mm = t->mm; ++ bool percpu; ++ ++ if (!mm) ++ return; ++ ++ WARN_ON_ONCE(t->mm_cid.cid != MM_CID_UNSET); ++ ++ guard(mutex)(&mm->mm_cid.mutex); ++ scoped_guard(raw_spinlock_irq, &mm->mm_cid.lock) { ++ struct mm_cid_pcpu *pcp = this_cpu_ptr(mm->mm_cid.pcpu); ++ ++ /* First user ? */ ++ if (!mm->mm_cid.users) { ++ sched_mm_cid_add_user(t, mm); ++ t->mm_cid.cid = mm_get_cid(mm); ++ /* Required for execve() */ ++ pcp->cid = t->mm_cid.cid; ++ return; ++ } ++ ++ if (!sched_mm_cid_add_user(t, mm)) { ++ if (!cid_on_cpu(mm->mm_cid.mode)) ++ t->mm_cid.cid = mm_get_cid(mm); ++ return; ++ } ++ ++ /* Handle the mode change and transfer current's CID */ ++ percpu = cid_on_cpu(mm->mm_cid.mode); ++ if (!percpu) ++ mm_cid_transit_to_task(current, pcp); ++ else ++ mm_cid_transit_to_cpu(current, pcp); ++ } ++ ++ if (percpu) { ++ mm_cid_fixup_tasks_to_cpus(); ++ } else { ++ mm_cid_fixup_cpus_to_tasks(mm); ++ t->mm_cid.cid = mm_get_cid(mm); ++ } ++} ++ ++static bool sched_mm_cid_remove_user(struct task_struct *t) ++{ ++ lockdep_assert_held(&t->mm->mm_cid.lock); ++ ++ t->mm_cid.active = 0; ++ /* Clear the transition bit */ ++ t->mm_cid.cid = cid_from_transit_cid(t->mm_cid.cid); ++ mm_unset_cid_on_task(t); ++ hlist_del_init(&t->mm_cid.node); ++ t->mm->mm_cid.users--; ++ return mm_update_max_cids(t->mm); ++} ++ ++static bool __sched_mm_cid_exit(struct task_struct *t) ++{ ++ struct mm_struct *mm = t->mm; ++ ++ if (!sched_mm_cid_remove_user(t)) ++ return false; ++ /* ++ * Contrary to fork() this only deals with a switch back to per ++ * task mode either because the above decreased users or an ++ * affinity change increased the number of allowed CPUs and the ++ * deferred fixup did not run yet. ++ */ ++ if (WARN_ON_ONCE(cid_on_cpu(mm->mm_cid.mode))) ++ return false; ++ /* ++ * A failed fork(2) cleanup never gets here, so @current must have ++ * the same MM as @t. That's true for exit() and the failed ++ * pthread_create() cleanup case. ++ */ ++ if (WARN_ON_ONCE(current->mm != mm)) ++ return false; ++ return true; ++} ++ ++/* ++ * When a task exits, the MM CID held by the task is not longer required as ++ * the task cannot return to user space. ++ */ ++void sched_mm_cid_exit(struct task_struct *t) ++{ ++ struct mm_struct *mm = t->mm; ++ ++ if (!mm || !t->mm_cid.active) ++ return; ++ /* ++ * Ensure that only one instance is doing MM CID operations within ++ * a MM. The common case is uncontended. The rare fixup case adds ++ * some overhead. ++ */ ++ scoped_guard(mutex, &mm->mm_cid.mutex) { ++ /* mm_cid::mutex is sufficient to protect mm_cid::users */ ++ if (likely(mm->mm_cid.users > 1)) { ++ scoped_guard(raw_spinlock_irq, &mm->mm_cid.lock) { ++ if (!__sched_mm_cid_exit(t)) ++ return; ++ /* ++ * Mode change. The task has the CID unset ++ * already and dealt with an eventually set ++ * TRANSIT bit. If the CID is owned by the CPU ++ * then drop it. ++ */ ++ mm_drop_cid_on_cpu(mm, this_cpu_ptr(mm->mm_cid.pcpu)); ++ } ++ mm_cid_fixup_cpus_to_tasks(mm); ++ return; ++ } ++ /* Last user */ ++ scoped_guard(raw_spinlock_irq, &mm->mm_cid.lock) { ++ /* Required across execve() */ ++ if (t == current) ++ mm_cid_transit_to_task(t, this_cpu_ptr(mm->mm_cid.pcpu)); ++ /* Ignore mode change. There is nothing to do. */ ++ sched_mm_cid_remove_user(t); ++ } ++ } ++ ++ /* ++ * As this is the last user (execve(), process exit or failed ++ * fork(2)) there is no concurrency anymore. ++ * ++ * Synchronize eventually pending work to ensure that there are no ++ * dangling references left. @t->mm_cid.users is zero so nothing ++ * can queue this work anymore. ++ */ ++ irq_work_sync(&mm->mm_cid.irq_work); ++ cancel_work_sync(&mm->mm_cid.work); ++} ++ ++/* Deactivate MM CID allocation across execve() */ ++void sched_mm_cid_before_execve(struct task_struct *t) ++{ ++ sched_mm_cid_exit(t); ++} ++ ++/* Reactivate MM CID after execve() */ ++void sched_mm_cid_after_execve(struct task_struct *t) ++{ ++ if (t->mm) ++ sched_mm_cid_fork(t); ++} ++ ++static void mm_cid_work_fn(struct work_struct *work) ++{ ++ struct mm_struct *mm = container_of(work, struct mm_struct, mm_cid.work); ++ ++ guard(mutex)(&mm->mm_cid.mutex); ++ /* Did the last user task exit already? */ ++ if (!mm->mm_cid.users) ++ return; ++ ++ scoped_guard(raw_spinlock_irq, &mm->mm_cid.lock) { ++ /* Have fork() or exit() handled it already? */ ++ if (!mm->mm_cid.update_deferred) ++ return; ++ /* This clears mm_cid::update_deferred */ ++ if (!mm_update_max_cids(mm)) ++ return; ++ /* Affinity changes can only switch back to task mode */ ++ if (WARN_ON_ONCE(cid_on_cpu(mm->mm_cid.mode))) ++ return; ++ } ++ mm_cid_fixup_cpus_to_tasks(mm); ++} ++ ++static void mm_cid_irq_work(struct irq_work *work) ++{ ++ struct mm_struct *mm = container_of(work, struct mm_struct, mm_cid.irq_work); ++ ++ /* ++ * Needs to be unconditional because mm_cid::lock cannot be held ++ * when scheduling work as mm_update_cpus_allowed() nests inside ++ * rq::lock and schedule_work() might end up in wakeup... ++ */ ++ schedule_work(&mm->mm_cid.work); ++} ++ ++void mm_init_cid(struct mm_struct *mm, struct task_struct *p) ++{ ++ mm->mm_cid.max_cids = 0; ++ mm->mm_cid.mode = 0; ++ mm->mm_cid.nr_cpus_allowed = p->nr_cpus_allowed; ++ mm->mm_cid.users = 0; ++ mm->mm_cid.pcpu_thrs = 0; ++ mm->mm_cid.update_deferred = 0; ++ raw_spin_lock_init(&mm->mm_cid.lock); ++ mutex_init(&mm->mm_cid.mutex); ++ mm->mm_cid.irq_work = IRQ_WORK_INIT_HARD(mm_cid_irq_work); ++ INIT_WORK(&mm->mm_cid.work, mm_cid_work_fn); ++ INIT_HLIST_HEAD(&mm->mm_cid.user_list); ++ cpumask_copy(mm_cpus_allowed(mm), &p->cpus_mask); ++ bitmap_zero(mm_cidmask(mm), num_possible_cpus()); ++} ++#else /* CONFIG_SCHED_MM_CID */ ++static inline void mm_update_cpus_allowed(struct mm_struct *mm, const struct cpumask *affmsk) { } ++static inline void sched_mm_cid_fork(struct task_struct *t) { } ++#endif /* !CONFIG_SCHED_MM_CID */ ++ ++static DEFINE_PER_CPU(struct sched_change_ctx, sched_change_ctx); ++ ++struct sched_change_ctx *sched_change_begin(struct task_struct *p, unsigned int flags) ++{ ++ struct sched_change_ctx *ctx = this_cpu_ptr(&sched_change_ctx); ++ struct rq *rq = task_rq(p); ++ ++ /* ++ * Must exclusively use matched flags since this is both dequeue and ++ * enqueue. ++ */ ++ WARN_ON_ONCE(flags & 0xFFFF0000); ++ ++ lockdep_assert_rq_held(rq); ++ ++ if (!(flags & DEQUEUE_NOCLOCK)) { ++ update_rq_clock(rq); ++ flags |= DEQUEUE_NOCLOCK; ++ } ++ ++ *ctx = (struct sched_change_ctx){ ++ .p = p, ++ .flags = flags, ++ .queued = task_on_rq_queued(p), ++ }; ++ ++ return ctx; ++} ++ ++void sched_change_end(struct sched_change_ctx *ctx) ++{ ++ struct task_struct *p = ctx->p; ++ struct rq *rq = task_rq(ctx->p); ++ ++ lockdep_assert_rq_held(rq); ++ ++ /* Trigger resched if task sched_prio has been modified. */ ++ if (ctx->queued) { ++ requeue_task(p, rq, ctx->flags); ++ wakeup_preempt(rq); ++ } ++} +diff --git a/kernel/sched/alt_core.h b/kernel/sched/alt_core.h +new file mode 100644 +index 0000000..f1b9d59 +--- /dev/null ++++ b/kernel/sched/alt_core.h +@@ -0,0 +1,109 @@ ++#ifndef _KERNEL_SCHED_ALT_CORE_H ++#define _KERNEL_SCHED_ALT_CORE_H ++ ++/* ++ * Compile time debug macro ++ * #define ALT_SCHED_DEBUG ++ */ ++ ++/* CONFIG_SCHED_CLASS_EXT is not supported */ ++#define scx_switched_all() false ++ ++/* ++ * Context API ++ */ ++static inline struct rq *__task_access_lock(struct task_struct *p, raw_spinlock_t **plock) ++ __context_unsafe(/* conditionally returns with the rq lock held */) ++{ ++ struct rq *rq; ++ for (;;) { ++ rq = task_rq(p); ++ if (p->on_cpu || task_on_rq_queued(p)) { ++ raw_spin_rq_lock(rq); ++ if (likely((p->on_cpu || task_on_rq_queued(p)) && rq == task_rq(p))) { ++ *plock = rq_lockp(rq); ++ return rq; ++ } ++ raw_spin_rq_unlock(rq); ++ } else if (task_on_rq_migrating(p)) { ++ do { ++ cpu_relax(); ++ } while (unlikely(task_on_rq_migrating(p))); ++ } else { ++ *plock = NULL; ++ return rq; ++ } ++ } ++} ++ ++static inline void __task_access_unlock(struct task_struct *p, raw_spinlock_t *lock) ++ __context_unsafe(/* conditionally releases the returned rq lock */) ++{ ++ if (NULL != lock) ++ raw_spin_unlock(lock); ++} ++ ++/* ++ * RQ related inlined functions ++ */ ++ ++/* ++ * This routine assume that the idle task always in queue ++ */ ++static inline struct task_struct *sched_rq_first_task(struct rq *rq) ++{ ++ const struct list_head *head = &rq->queue.heads[sched_rq_prio_idx(rq)]; ++ ++ return list_first_entry(head, struct task_struct, sq_node); ++} ++ ++static __always_inline struct task_struct * sched_rq_next_task(struct task_struct *p, struct rq *rq) ++{ ++ struct list_head *next = p->sq_node.next; ++ ++ if (&rq->queue.heads[0] <= next && next < &rq->queue.heads[SCHED_LEVELS]) { ++ struct list_head *head; ++ unsigned long idx = next - &rq->queue.heads[0]; ++ ++ idx = find_next_bit(rq->queue.bitmap, SCHED_QUEUE_BITS, ++ sched_idx2prio(idx, rq) + 1); ++ head = &rq->queue.heads[sched_prio2idx(idx, rq)]; ++ ++ return list_first_entry(head, struct task_struct, sq_node); ++ } ++ ++ return list_next_entry(p, sq_node); ++} ++ ++extern void requeue_task(struct task_struct *p, struct rq *rq, int flags); ++ ++#ifdef ALT_SCHED_DEBUG ++extern void alt_sched_debug(void); ++#else ++static inline void alt_sched_debug(void) {} ++#endif ++ ++extern int sched_yield_type; ++ ++extern cpumask_t sched_rq_pending_mask ____cacheline_aligned_in_smp; ++ ++DECLARE_STATIC_KEY_FALSE(sched_smt_present); ++DECLARE_PER_CPU_ALIGNED(cpumask_t *, sched_cpu_llc_mask); ++ ++extern cpumask_t sched_smt_mask ____cacheline_aligned_in_smp; ++#ifdef CONFIG_SCHED_SMT ++DECLARE_PER_CPU_ALIGNED(raw_spinlock_t, sched_smt_idle_lock); ++#endif ++ ++extern cpumask_t *const sched_idle_mask; ++extern cpumask_t *const sched_sg_idle_mask; ++extern cpumask_t *const sched_pcore_idle_mask; ++extern cpumask_t *const sched_ecore_idle_mask; ++ ++extern struct rq *move_queued_task(struct rq *rq, struct rq_flags *rf, ++ struct task_struct *p, int new_cpu) ++ __must_hold(__rq_lockp(rq)); ++ ++DECLARE_STATIC_CALL(sched_idle_select_func, cpumask_and); ++ ++#endif /* _KERNEL_SCHED_ALT_CORE_H */ +diff --git a/kernel/sched/alt_debug.c b/kernel/sched/alt_debug.c +new file mode 100644 +index 0000000..1dbd7eb +--- /dev/null ++++ b/kernel/sched/alt_debug.c +@@ -0,0 +1,32 @@ ++/* ++ * kernel/sched/alt_debug.c ++ * ++ * Print the alt scheduler debugging details ++ * ++ * Author: Alfred Chen ++ * Date : 2020 ++ */ ++#include "sched.h" ++#include "linux/sched/debug.h" ++ ++/* ++ * This allows printing both to /proc/sched_debug and ++ * to the console ++ */ ++#define SEQ_printf(m, x...) \ ++ do { \ ++ if (m) \ ++ seq_printf(m, x); \ ++ else \ ++ pr_cont(x); \ ++ } while (0) ++ ++void proc_sched_show_task(struct task_struct *p, struct pid_namespace *ns, ++ struct seq_file *m) ++{ ++ SEQ_printf(m, "%s (%d, #threads: %d)\n", p->comm, task_pid_nr_ns(p, ns), ++ get_nr_threads(p)); ++} ++ ++void proc_sched_set_task(struct task_struct *p) ++{} +diff --git a/kernel/sched/alt_sched.h b/kernel/sched/alt_sched.h +new file mode 100644 +index 0000000..a04751f +--- /dev/null ++++ b/kernel/sched/alt_sched.h +@@ -0,0 +1,1350 @@ ++#ifndef _KERNEL_SCHED_ALT_SCHED_H ++#define _KERNEL_SCHED_ALT_SCHED_H ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++#include ++ ++#include "../workqueue_internal.h" ++ ++struct rq; ++struct cpuidle_state; ++ ++#include "cpupri.h" ++ ++#ifdef CONFIG_CGROUP_SCHED ++/* task group related information */ ++struct task_group { ++ struct cgroup_subsys_state css; ++ ++ struct rcu_head rcu; ++ struct list_head list; ++ ++ struct task_group *parent; ++ struct list_head siblings; ++ struct list_head children; ++}; ++ ++extern struct task_group *sched_create_group(struct task_group *parent); ++extern void sched_online_group(struct task_group *tg, ++ struct task_group *parent); ++extern void sched_destroy_group(struct task_group *tg); ++extern void sched_release_group(struct task_group *tg); ++static inline void __sched_cgroup_mode_update(int mode) { } ++#endif /* CONFIG_CGROUP_SCHED */ ++ ++#define MIN_SCHED_NORMAL_PRIO (32) ++/* ++ * levels: RT(0-24), reserved(25-31), NORMAL(32-63), cpu idle task(64) ++ * ++ * -- BMQ -- ++ * NORMAL: (lower boost range 12, NICE_WIDTH 40, higher boost range 12) / 2 ++ * -- PDS -- ++ * NORMAL: SCHED_EDGE_DELTA + ((NICE_WIDTH 40) / 2) ++ */ ++#define SCHED_LEVELS (64 + 1) ++ ++#define IDLE_TASK_SCHED_PRIO (SCHED_LEVELS - 1) ++ ++/* task_struct::on_rq states: */ ++#define TASK_ON_RQ_QUEUED 1 ++#define TASK_ON_RQ_MIGRATING 2 ++ ++/* ++ * Increase resolution of nice-level calculations for 64-bit architectures. ++ * The extra resolution improves shares distribution and load balancing of ++ * low-weight task groups (eg. nice +19 on an autogroup), deeper taskgroup ++ * hierarchies, especially on larger systems. This is not a user-visible change ++ * and does not change the user-interface for setting shares/weights. ++ * ++ * We increase resolution only if we have enough bits to allow this increased ++ * resolution (i.e. 64-bit). The costs for increasing resolution when 32-bit ++ * are pretty high and the returns do not justify the increased costs. ++ * ++ * Really only required when CONFIG_FAIR_GROUP_SCHED=y is also set, but to ++ * increase coverage and consistency always enable it on 64-bit platforms. ++ */ ++#ifdef CONFIG_64BIT ++# define NICE_0_LOAD_SHIFT (SCHED_FIXEDPOINT_SHIFT + SCHED_FIXEDPOINT_SHIFT) ++# define scale_load(w) ((w) << SCHED_FIXEDPOINT_SHIFT) ++# define scale_load_down(w) \ ++({ \ ++ unsigned long __w = (w); \ ++ if (__w) \ ++ __w = max(2UL, __w >> SCHED_FIXEDPOINT_SHIFT); \ ++ __w; \ ++}) ++#else ++# define NICE_0_LOAD_SHIFT (SCHED_FIXEDPOINT_SHIFT) ++# define scale_load(w) (w) ++# define scale_load_down(w) (w) ++#endif ++ ++static inline int normal_policy(int policy) ++{ ++ return policy == SCHED_NORMAL; ++} ++ ++static inline int fair_policy(int policy) ++{ ++ return normal_policy(policy) || policy == SCHED_BATCH; ++} ++ ++static inline int rt_policy(int policy) ++{ ++ return policy == SCHED_FIFO || policy == SCHED_RR; ++} ++ ++#define valid_policy(policy) ((policy) <= SCHED_IDLE) ++ ++static inline int task_has_rt_policy(struct task_struct *p) ++{ ++ return rt_policy(p->policy); ++} ++ ++#define task_has_dl_policy(p) (false) ++#define dl_prio(prio) (false) ++ ++#define cap_scale(v, s) ((v)*(s) >> SCHED_CAPACITY_SHIFT) ++ ++/* ++ * !! For sched_setattr_nocheck() (kernel) only !! ++ * ++ * This is actually gross. :( ++ * ++ * It is used to make schedutil kworker(s) higher priority than SCHED_DEADLINE ++ * tasks, but still be able to sleep. We need this on platforms that cannot ++ * atomically change clock frequency. Remove once fast switching will be ++ * available on such platforms. ++ * ++ * SUGOV stands for SchedUtil GOVernor. ++ */ ++#define SCHED_FLAG_SUGOV 0x10000000 ++ ++#define SCHED_QUEUE_BITS (SCHED_LEVELS - 1) ++ ++struct sched_queue { ++ DECLARE_BITMAP(bitmap, SCHED_QUEUE_BITS); ++ struct list_head heads[SCHED_LEVELS]; ++}; ++ ++struct balance_callback { ++ struct balance_callback *next; ++ void (*func)(struct rq *rq); ++}; ++ ++struct balance_arg { ++ struct task_struct *task; ++ int active; ++ cpumask_t *cpumask; ++}; ++ ++/* ++ * This is the main, per-CPU runqueue data structure. ++ * This data should only be modified by the local cpu. ++ */ ++struct rq { ++ /* runqueue lock: */ ++ raw_spinlock_t __lock; ++ ++ struct task_struct __rcu *curr; ++ struct task_struct *idle; ++ struct task_struct *stop; ++ struct mm_struct *prev_mm; ++ ++ /* switch count */ ++ u64 nr_switches; ++ ++ u64 last_seen_need_resched_ns; ++ int ticks_without_resched; ++ ++ struct sched_queue queue ____cacheline_aligned; ++ ++ int prio; ++#ifdef CONFIG_SCHED_PDS ++ int prio_idx; ++ u64 time_edge; ++#endif ++ ++ atomic_t nr_iowait; ++ ++#ifdef CONFIG_MEMBARRIER ++ int membarrier_state; ++#endif ++ ++ int cpu; /* cpu of this runqueue */ ++ bool online; ++ ++ unsigned int ttwu_pending; ++ unsigned char nohz_idle_balance; ++ unsigned char idle_balance; ++ ++#ifdef CONFIG_HAVE_SCHED_AVG_IRQ ++ struct sched_avg avg_irq; ++#endif ++ ++ struct balance_arg active_balance_arg ____cacheline_aligned; ++ struct cpu_stop_work active_balance_work; ++ ++ struct balance_callback *balance_callback; ++ ++#ifdef CONFIG_HOTPLUG_CPU ++ struct rcuwait hotplug_wait; ++#endif ++ unsigned int nr_pinned; ++ ++#ifdef CONFIG_IRQ_TIME_ACCOUNTING ++ u64 psi_irq_time; ++#endif /* CONFIG_IRQ_TIME_ACCOUNTING */ ++#ifdef CONFIG_PARAVIRT ++ u64 prev_steal_time; ++#endif /* CONFIG_PARAVIRT */ ++#ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING ++ u64 prev_steal_time_rq; ++#endif /* CONFIG_PARAVIRT_TIME_ACCOUNTING */ ++ ++ /* calc_load related fields */ ++ unsigned long calc_load_update; ++ long calc_load_active; ++ ++ /* Ensure that all clocks are in the same cache line */ ++ u64 clock ____cacheline_aligned; ++ u64 clock_task; ++ u64 prio_balance_time; ++#ifdef CONFIG_IRQ_TIME_ACCOUNTING ++ u64 prev_irq_time; ++#endif /* CONFIG_IRQ_TIME_ACCOUNTING */ ++ ++ /* For genenal cpu load util */ ++ u64 load_block; ++ u64 load_stamp; ++ s32 load_history; ++ ++ unsigned int nr_running; ++ unsigned long nr_uninterruptible; ++ ++#ifdef CONFIG_SCHED_HRTICK ++ call_single_data_t hrtick_csd; ++ struct hrtimer hrtick_timer; ++ ktime_t hrtick_time; ++ ktime_t hrtick_delay; ++ unsigned int hrtick_sched; ++#endif ++ ++#ifdef CONFIG_SCHEDSTATS ++ ++ /* latency stats */ ++ struct sched_info rq_sched_info; ++ unsigned long long rq_cpu_time; ++ /* could above be rq->cfs_rq.exec_clock + rq->rt_rq.rt_runtime ? */ ++ ++ /* sys_sched_yield() stats */ ++ unsigned int yld_count; ++ ++ /* schedule() stats */ ++ unsigned int sched_count; ++ unsigned int sched_goidle; ++ ++ /* try_to_wake_up() stats */ ++ unsigned int ttwu_count; ++ unsigned int ttwu_local; ++#endif /* CONFIG_SCHEDSTATS */ ++ ++#ifdef CONFIG_CPU_IDLE ++ /* Must be inspected within a rcu lock section */ ++ struct cpuidle_state *idle_state; ++#endif ++ ++#ifdef CONFIG_NO_HZ_COMMON ++ call_single_data_t nohz_csd; ++ atomic_t nohz_flags; ++#endif /* CONFIG_NO_HZ_COMMON */ ++ ++ /* Scratch cpumask to be temporarily used under rq_lock */ ++ cpumask_var_t scratch_mask; ++} __no_randomize_layout; ++ ++static inline int cpu_of(const struct rq *rq) ++{ ++ return rq->cpu; ++} ++ ++static inline bool is_migration_disabled(struct task_struct *p) ++{ ++ return p->migration_disabled; ++} ++ ++extern unsigned int sysctl_sched_base_slice; ++ ++/* Reschedule if less than this many μs left */ ++#define RESCHED_NS (100 << 10) ++ ++extern unsigned long rq_load_util(struct rq *rq, unsigned long max); ++ ++extern unsigned long calc_load_update; ++extern atomic_long_t calc_load_tasks; ++ ++extern void calc_global_load_tick(struct rq *this_rq); ++extern long calc_load_fold_active(struct rq *this_rq, long adjust); ++ ++DECLARE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues); ++#define cpu_rq(cpu) (&per_cpu(runqueues, (cpu))) ++static __always_inline struct rq *__this_rq(void) ++{ ++ return this_cpu_ptr(&runqueues); ++} ++ ++#define this_rq() __this_rq() ++#define task_rq(p) cpu_rq(task_cpu(p)) ++#define cpu_curr(cpu) (cpu_rq(cpu)->curr) ++#define raw_rq() raw_cpu_ptr(&runqueues) ++ ++static inline bool idle_rq(struct rq *rq) ++{ ++ return rq->curr == rq->idle && !rq->nr_running && !rq->ttwu_pending; ++} ++ ++/** ++ * available_idle_cpu - is a given CPU idle for enqueuing work. ++ * @cpu: the CPU in question. ++ * ++ * Return: 1 if the CPU is currently idle. 0 otherwise. ++ */ ++static inline bool available_idle_cpu(int cpu) ++{ ++ if (!idle_rq(cpu_rq(cpu))) ++ return 0; ++ ++ if (vcpu_is_preempted(cpu)) ++ return 0; ++ ++ return 1; ++} ++ ++#ifdef CONFIG_SYSCTL ++void register_sched_domain_sysctl(void); ++void unregister_sched_domain_sysctl(void); ++#else ++static inline void register_sched_domain_sysctl(void) ++{ ++} ++static inline void unregister_sched_domain_sysctl(void) ++{ ++} ++#endif ++ ++extern bool sched_smp_initialized; ++ ++enum { ++#ifdef CONFIG_SCHED_SMT ++ SCHED_CPU_AFFINITY_SMT, ++#endif ++ SCHED_CPU_AFFINITY_CLUSTER, ++ SCHED_CPU_AFFINITY_LLC, ++ SCHED_CPU_AFFINITY_CORE, ++ SCHED_CPU_AFFINITY_OTHER, ++ NR_CPU_AFFINITY_LEVELS ++}; ++ ++DECLARE_PER_CPU_ALIGNED(cpumask_t [NR_CPU_AFFINITY_LEVELS], sched_cpu_topo_masks); ++DECLARE_PER_CPU_ALIGNED(cpumask_t *, sched_cpu_topo_end_mask); ++ ++/* ++ * Affinity levels are nested, so a level which covers the same CPUs as the ++ * level below it repeats a search which has already failed. ++ */ ++static inline bool ++sched_cpu_topo_level_repeats(const cpumask_t *topo_masks, const cpumask_t *mask) ++{ ++ return mask > topo_masks && cpumask_equal(mask, mask - 1); ++} ++ ++static inline int ++__best_mask_cpu(const cpumask_t *cpumask, const cpumask_t *mask, ++ const cpumask_t *end_mask) ++{ ++ int cpu; ++ ++ while (mask < end_mask) { ++ cpu = cpumask_any_and(cpumask, mask); ++ if (cpu < nr_cpu_ids) ++ return cpu; ++ mask++; ++ } ++ ++ return cpumask_any(cpumask); ++} ++ ++static inline int best_mask_cpu(int cpu, const cpumask_t *mask) ++{ ++ return __best_mask_cpu(mask, per_cpu(sched_cpu_topo_masks, cpu), ++ per_cpu(sched_cpu_topo_end_mask, cpu)); ++} ++ ++extern void resched_latency_warn(int cpu, u64 latency); ++ ++static __always_inline raw_spinlock_t *rq_lockp(struct rq *rq) ++{ ++ return &rq->__lock; ++} ++ ++static __always_inline raw_spinlock_t *__rq_lockp(struct rq *rq) ++ __returns_ctx_lock(rq_lockp(rq)) /* alias them */ ++{ ++ return &rq->__lock; ++} ++ ++static inline void lockdep_assert_rq_held(struct rq *rq) ++ __assumes_ctx_lock(__rq_lockp(rq)) ++{ ++ lockdep_assert_held(__rq_lockp(rq)); ++} ++ ++extern void raw_spin_rq_lock_nested(struct rq *rq, int subclass) ++ __acquires(__rq_lockp(rq)); ++ ++extern bool raw_spin_rq_trylock(struct rq *rq) ++ __cond_acquires(true, __rq_lockp(rq)); ++ ++static __always_inline void raw_spin_rq_lock(struct rq *rq) ++ __acquires(__rq_lockp(rq)) ++{ ++ raw_spin_rq_lock_nested(rq, 0); ++} ++ ++static __always_inline void raw_spin_rq_unlock(struct rq *rq) ++ __releases(__rq_lockp(rq)) ++{ ++ raw_spin_unlock(rq_lockp(rq)); ++} ++ ++static __always_inline void raw_spin_rq_lock_irq(struct rq *rq) ++ __acquires(__rq_lockp(rq)) ++{ ++ local_irq_disable(); ++ raw_spin_rq_lock(rq); ++} ++ ++static __always_inline void raw_spin_rq_unlock_irq(struct rq *rq) ++ __releases(__rq_lockp(rq)) ++{ ++ raw_spin_rq_unlock(rq); ++ local_irq_enable(); ++} ++ ++static inline unsigned long _raw_spin_rq_lock_irqsave(struct rq *rq) ++ __acquires(__rq_lockp(rq)) ++{ ++ unsigned long flags; ++ ++ local_irq_save(flags); ++ raw_spin_rq_lock(rq); ++ ++ return flags; ++} ++ ++static inline void raw_spin_rq_unlock_irqrestore(struct rq *rq, ++ unsigned long flags) ++ __releases(__rq_lockp(rq)) ++{ ++ raw_spin_rq_unlock(rq); ++ local_irq_restore(flags); ++} ++ ++#define raw_spin_rq_lock_irqsave(rq, flags) \ ++do { \ ++ flags = _raw_spin_rq_lock_irqsave(rq); \ ++} while (0) ++ ++struct rq_flags { ++ unsigned long flags; ++ struct pin_cookie cookie; ++ raw_spinlock_t *lock; ++}; ++ ++extern struct balance_callback balance_push_callback; ++ ++static inline void assert_balance_callbacks_empty(struct rq *rq) ++{ ++ WARN_ON_ONCE(IS_ENABLED(CONFIG_PROVE_LOCKING) && ++ rq->balance_callback && ++ rq->balance_callback != &balance_push_callback); ++} ++ ++static inline void rq_pin_lock(struct rq *rq, struct rq_flags *rf) ++{ ++ rf->cookie = lockdep_pin_lock(__rq_lockp(rq)); ++ ++ assert_balance_callbacks_empty(rq); ++} ++ ++static inline void rq_unpin_lock(struct rq *rq, struct rq_flags *rf) ++{ ++ lockdep_unpin_lock(__rq_lockp(rq), rf->cookie); ++} ++ ++static inline void rq_repin_lock(struct rq *rq, struct rq_flags *rf) ++{ ++ lockdep_repin_lock(__rq_lockp(rq), rf->cookie); ++} ++ ++extern void update_rq_clock(struct rq *rq); ++ ++static inline u64 rq_clock(struct rq *rq) ++{ ++ lockdep_assert_rq_held(rq); ++ ++ return rq->clock; ++} ++ ++static inline u64 rq_clock_task(struct rq *rq) ++{ ++ lockdep_assert_rq_held(rq); ++ ++ return rq->clock_task; ++} ++ ++#define __task_rq_lock(...) __acquire_ret(___task_rq_lock(__VA_ARGS__), __rq_lockp(__ret)) ++extern struct rq *___task_rq_lock(struct task_struct *p, struct rq_flags *rf) __acquires_ret; ++ ++#define task_rq_lock(...) __acquire_ret(_task_rq_lock(__VA_ARGS__), __rq_lockp(__ret)) ++extern struct rq *_task_rq_lock(struct task_struct *p, struct rq_flags *rf) ++ __acquires(&p->pi_lock) __acquires_ret; ++ ++static inline void ++__task_rq_unlock(struct rq *rq, struct task_struct *p, struct rq_flags *rf) ++ __releases(__rq_lockp(rq)) ++{ ++ rq_unpin_lock(rq, rf); ++ raw_spin_rq_unlock(rq); ++} ++ ++static inline void ++task_rq_unlock(struct rq *rq, struct task_struct *p, struct rq_flags *rf) ++ __releases(__rq_lockp(rq), &p->pi_lock) ++{ ++ __task_rq_unlock(rq, p, rf); ++ raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags); ++} ++ ++DEFINE_LOCK_GUARD_1(task_rq_lock, struct task_struct, ++ _T->rq = task_rq_lock(_T->lock, &_T->rf), ++ task_rq_unlock(_T->rq, _T->lock, &_T->rf), ++ struct rq *rq; struct rq_flags rf) ++DECLARE_LOCK_GUARD_1_ATTRS(task_rq_lock, __acquires(&_T->pi_lock), ++ __releases(&(*(struct task_struct **)_T)->pi_lock)) ++#define class_task_rq_lock_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(task_rq_lock, _T) ++ ++DEFINE_LOCK_GUARD_1(__task_rq_lock, struct task_struct, ++ _T->rq = __task_rq_lock(_T->lock, &_T->rf), ++ __task_rq_unlock(_T->rq, _T->lock, &_T->rf), ++ struct rq *rq; struct rq_flags rf) ++ ++static inline void rq_lock_irqsave(struct rq *rq, struct rq_flags *rf) ++ __acquires(__rq_lockp(rq)) ++{ ++ raw_spin_rq_lock_irqsave(rq, rf->flags); ++ rq_pin_lock(rq, rf); ++} ++ ++static inline void ++rq_lock_irq(struct rq *rq, struct rq_flags *rf) ++ __acquires(__rq_lockp(rq)) ++{ ++ raw_spin_rq_lock_irq(rq); ++ rq_pin_lock(rq, rf); ++} ++ ++static inline void ++rq_lock(struct rq *rq, struct rq_flags *rf) ++ __acquires(__rq_lockp(rq)) ++{ ++ raw_spin_rq_lock(rq); ++ rq_pin_lock(rq, rf); ++} ++ ++static inline void rq_unlock_irqrestore(struct rq *rq, struct rq_flags *rf) ++ __releases(__rq_lockp(rq)) ++{ ++ rq_unpin_lock(rq, rf); ++ raw_spin_rq_unlock_irqrestore(rq, rf->flags); ++} ++ ++static inline void ++rq_unlock_irq(struct rq *rq, struct rq_flags *rf) ++ __releases(__rq_lockp(rq)) ++{ ++ rq_unpin_lock(rq, rf); ++ raw_spin_rq_unlock_irq(rq); ++} ++ ++static inline void ++rq_unlock(struct rq *rq, struct rq_flags *rf) ++ __releases(__rq_lockp(rq)) ++{ ++ rq_unpin_lock(rq, rf); ++ raw_spin_rq_unlock(rq); ++} ++ ++DEFINE_LOCK_GUARD_1(rq_lock, struct rq, ++ rq_lock(_T->lock, &_T->rf), ++ rq_unlock(_T->lock, &_T->rf), ++ struct rq_flags rf) ++DECLARE_LOCK_GUARD_1_ATTRS(rq_lock, __acquires(__rq_lockp(_T)), ++ __releases(__rq_lockp(*(struct rq **)_T))) ++#define class_rq_lock_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(rq_lock, _T) ++ ++DEFINE_LOCK_GUARD_1(rq_lock_irq, struct rq, ++ rq_lock_irq(_T->lock, &_T->rf), ++ rq_unlock_irq(_T->lock, &_T->rf), ++ struct rq_flags rf) ++DECLARE_LOCK_GUARD_1_ATTRS(rq_lock_irq, __acquires(__rq_lockp(_T)), ++ __releases(__rq_lockp(*(struct rq **)_T))) ++#define class_rq_lock_irq_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(rq_lock_irq, _T) ++ ++DEFINE_LOCK_GUARD_1(rq_lock_irqsave, struct rq, ++ rq_lock_irqsave(_T->lock, &_T->rf), ++ rq_unlock_irqrestore(_T->lock, &_T->rf), ++ struct rq_flags rf) ++DECLARE_LOCK_GUARD_1_ATTRS(rq_lock_irqsave, __acquires(__rq_lockp(_T)), ++ __releases(__rq_lockp(*(struct rq **)_T))) ++#define class_rq_lock_irqsave_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(rq_lock_irqsave, _T) ++ ++#define this_rq_lock_irq(...) __acquire_ret(_this_rq_lock_irq(__VA_ARGS__), __rq_lockp(__ret)) ++static inline struct rq *_this_rq_lock_irq(struct rq_flags *rf) __acquires_ret ++{ ++ struct rq *rq; ++ ++ local_irq_disable(); ++ rq = this_rq(); ++ rq_lock(rq, rf); ++ ++ return rq; ++} ++ ++extern struct static_key_false sched_schedstats; ++ ++static inline int task_current(struct rq *rq, struct task_struct *p) ++{ ++ return rq->curr == p; ++} ++ ++static inline bool task_on_cpu(struct rq *rq, struct task_struct *p) ++{ ++ return p->on_cpu; ++} ++ ++static inline int task_on_rq_queued(struct task_struct *p) ++{ ++ return READ_ONCE(p->on_rq) == TASK_ON_RQ_QUEUED; ++} ++ ++static inline int task_on_rq_migrating(struct task_struct *p) ++{ ++ return READ_ONCE(p->on_rq) == TASK_ON_RQ_MIGRATING; ++} ++ ++/* Wake flags. The first three directly map to some SD flag value */ ++#define WF_EXEC 0x02 /* Wakeup after exec; maps to SD_BALANCE_EXEC */ ++#define WF_FORK 0x04 /* Wakeup after fork; maps to SD_BALANCE_FORK */ ++#define WF_TTWU 0x08 /* Wakeup; maps to SD_BALANCE_WAKE */ ++ ++#define WF_SYNC 0x10 /* Waker goes to sleep after wakeup */ ++#define WF_MIGRATED 0x20 /* Internal use, task got migrated */ ++#define WF_CURRENT_CPU 0x40 /* Prefer to move the wakee to the current CPU. */ ++#define WF_RQ_SELECTED 0x80 /* ->select_task_rq() was called */ ++ ++static_assert(WF_EXEC == SD_BALANCE_EXEC); ++static_assert(WF_FORK == SD_BALANCE_FORK); ++static_assert(WF_TTWU == SD_BALANCE_WAKE); ++ ++/* ++ * {de,en}queue flags: ++ * ++ * SLEEP/WAKEUP - task is no-longer/just-became runnable ++ * ++ * SAVE/RESTORE - an otherwise spurious dequeue/enqueue, done to ensure tasks ++ * are in a known state which allows modification. Such pairs ++ * should preserve as much state as possible. ++ * ++ * MOVE - paired with SAVE/RESTORE, explicitly does not preserve the location ++ * in the runqueue. ++ * ++ * NOCLOCK - skip the update_rq_clock() (avoids double updates) ++ * ++ * MIGRATION - p->on_rq == TASK_ON_RQ_MIGRATING (used for DEADLINE) ++ * ++ * DELAYED - de/re-queue a sched_delayed task ++ * ++ * CLASS - going to update p->sched_class; makes sched_change call the ++ * various switch methods. ++ * ++ * ENQUEUE_HEAD - place at front of runqueue (tail if not specified) ++ * ENQUEUE_REPLENISH - CBS (replenish runtime and postpone deadline) ++ * ENQUEUE_MIGRATED - the task was migrated during wakeup ++ * ENQUEUE_RQ_SELECTED - ->select_task_rq() was called ++ * ++ * XXX SAVE/RESTORE in combination with CLASS doesn't really make sense, but ++ * SCHED_DEADLINE seems to rely on this for now. ++ */ ++ ++#define DEQUEUE_SLEEP 0x0001 /* Matches ENQUEUE_WAKEUP */ ++#define DEQUEUE_SAVE 0x0002 /* Matches ENQUEUE_RESTORE */ ++#define DEQUEUE_MOVE 0x0004 /* Matches ENQUEUE_MOVE */ ++#define DEQUEUE_NOCLOCK 0x0008 /* Matches ENQUEUE_NOCLOCK */ ++ ++#define DEQUEUE_MIGRATING 0x0010 /* Matches ENQUEUE_MIGRATING */ ++#define DEQUEUE_DELAYED 0x0020 /* Matches ENQUEUE_DELAYED */ ++#define DEQUEUE_CLASS 0x0040 /* Matches ENQUEUE_CLASS */ ++ ++#define DEQUEUE_SPECIAL 0x00010000 ++#define DEQUEUE_THROTTLE 0x00020000 ++ ++#define ENQUEUE_WAKEUP 0x0001 ++#define ENQUEUE_RESTORE 0x0002 ++#define ENQUEUE_MOVE 0x0004 ++#define ENQUEUE_NOCLOCK 0x0008 ++ ++#define ENQUEUE_MIGRATING 0x0010 ++#define ENQUEUE_DELAYED 0x0020 ++#define ENQUEUE_CLASS 0x0040 ++ ++#define ENQUEUE_HEAD 0x00010000 ++#define ENQUEUE_REPLENISH 0x00020000 ++#define ENQUEUE_MIGRATED 0x00040000 ++#define ENQUEUE_INITIAL 0x00080000 ++#define ENQUEUE_RQ_SELECTED 0x00100000 ++ ++ ++struct affinity_context { ++ const struct cpumask *new_mask; ++ struct cpumask *user_mask; ++ unsigned int flags; ++}; ++ ++#define SCA_CHECK 0x01 ++#define SCA_MIGRATE_DISABLE 0x02 ++#define SCA_MIGRATE_ENABLE 0x04 ++#define SCA_USER 0x08 ++ ++extern int __set_cpus_allowed_ptr(struct task_struct *p, struct affinity_context *ctx); ++ ++static inline bool task_allowed_on_cpu(struct task_struct *p, int cpu) ++{ ++ /* When not in the task's cpumask, no point in looking further. */ ++ if (!cpumask_test_cpu(cpu, p->cpus_ptr)) ++ return false; ++ ++ /* Can @cpu run a user thread? */ ++ if (!(p->flags & PF_KTHREAD) && !task_cpu_possible(cpu, p)) ++ return false; ++ ++ return true; ++} ++ ++static inline cpumask_t *alloc_user_cpus_ptr(int node) ++{ ++ /* ++ * See set_cpus_allowed_force() above for the rcu_head usage. ++ */ ++ int size = max_t(int, cpumask_size(), sizeof(struct rcu_head)); ++ ++ return kmalloc_node(size, GFP_KERNEL, node); ++} ++ ++#ifdef CONFIG_CPU_IDLE ++static inline void idle_set_state(struct rq *rq, ++ struct cpuidle_state *idle_state) ++{ ++ rq->idle_state = idle_state; ++} ++#else ++static inline void idle_set_state(struct rq *rq, ++ struct cpuidle_state *idle_state) ++{ ++} ++#endif ++ ++extern void resched_cpu(int cpu); ++ ++#ifdef CONFIG_NO_HZ_FULL ++extern int __init sched_tick_offload_init(void); ++#else ++static inline int sched_tick_offload_init(void) { return 0; } ++#endif ++ ++static inline void __block_task(struct rq *rq, struct task_struct *p) ++{ ++ if (p->sched_contributes_to_load) ++ rq->nr_uninterruptible++; ++ ++ if (p->in_iowait) { ++ atomic_inc(&rq->nr_iowait); ++ delayacct_blkio_start(); ++ } ++ ++ ASSERT_EXCLUSIVE_WRITER(p->on_rq); ++ ++ /* ++ * The moment this write goes through, ttwu() can swoop in and migrate ++ * this task, rendering our rq->__lock ineffective. ++ * ++ * __schedule() try_to_wake_up() ++ * LOCK rq->__lock LOCK p->pi_lock ++ * pick_next_task() ++ * pick_next_task_fair() ++ * pick_next_entity() ++ * dequeue_entities() ++ * __block_task() ++ * RELEASE p->on_rq = 0 if (p->on_rq && ...) ++ * break; ++ * ++ * ACQUIRE (after ctrl-dep) ++ * ++ * cpu = select_task_rq(); ++ * set_task_cpu(p, cpu); ++ * ttwu_queue() ++ * ttwu_do_activate() ++ * LOCK rq->__lock ++ * activate_task() ++ * STORE p->on_rq = 1 ++ * UNLOCK rq->__lock ++ * ++ * Callers must ensure to not reference @p after this -- we no longer ++ * own it. ++ */ ++ smp_store_release(&p->on_rq, 0); ++} ++ ++#ifndef arch_scale_freq_tick ++static __always_inline ++void arch_scale_freq_tick(void) ++{ ++} ++#endif ++ ++#ifndef arch_scale_freq_capacity ++static __always_inline ++unsigned long arch_scale_freq_capacity(int cpu) ++{ ++ return SCHED_CAPACITY_SCALE; ++} ++#endif ++ ++#ifdef CONFIG_NO_HZ_COMMON ++#define NOHZ_BALANCE_KICK_BIT 0 ++#define NOHZ_STATS_KICK_BIT 1 ++ ++#define NOHZ_BALANCE_KICK BIT(NOHZ_BALANCE_KICK_BIT) ++#define NOHZ_STATS_KICK BIT(NOHZ_STATS_KICK_BIT) ++ ++#define NOHZ_KICK_MASK (NOHZ_BALANCE_KICK | NOHZ_STATS_KICK) ++ ++#define nohz_flags(cpu) (&cpu_rq(cpu)->nohz_flags) ++ ++/* TODO: needed? ++extern void nohz_balance_exit_idle(struct rq *rq); ++#else ++static inline void nohz_balance_exit_idle(struct rq *rq) { } ++*/ ++#endif ++ ++static inline void nohz_run_idle_balance(int cpu) { } ++ ++#include "stats.h" ++ ++#ifdef CONFIG_IRQ_TIME_ACCOUNTING ++struct irqtime { ++ u64 total; ++ u64 tick_delta; ++ u64 irq_start_time; ++ struct u64_stats_sync sync; ++}; ++ ++DECLARE_PER_CPU(struct irqtime, cpu_irqtime); ++DECLARE_STATIC_KEY_FALSE(sched_clock_irqtime); ++ ++static inline int irqtime_enabled(void) ++{ ++ return static_branch_likely(&sched_clock_irqtime); ++} ++ ++/* ++ * Returns the irqtime minus the softirq time computed by ksoftirqd. ++ * Otherwise ksoftirqd's sum_exec_runtime is substracted its own runtime ++ * and never move forward. ++ */ ++static inline u64 irq_time_read(int cpu) ++{ ++ struct irqtime *irqtime = &per_cpu(cpu_irqtime, cpu); ++ unsigned int seq; ++ u64 total; ++ ++ do { ++ seq = __u64_stats_fetch_begin(&irqtime->sync); ++ total = irqtime->total; ++ } while (__u64_stats_fetch_retry(&irqtime->sync, seq)); ++ ++ return total; ++} ++#else ++ ++static inline int irqtime_enabled(void) ++{ ++ return 0; ++} ++ ++#endif /* CONFIG_IRQ_TIME_ACCOUNTING */ ++ ++#ifdef CONFIG_CPU_FREQ ++DECLARE_PER_CPU(struct update_util_data __rcu *, cpufreq_update_util_data); ++#endif /* CONFIG_CPU_FREQ */ ++ ++#ifdef arch_scale_freq_capacity ++#ifndef arch_scale_freq_invariant ++#define arch_scale_freq_invariant() (true) ++#endif ++#else /* arch_scale_freq_capacity */ ++#define arch_scale_freq_invariant() (false) ++#endif ++ ++unsigned long sugov_effective_cpu_perf(int cpu, unsigned long actual, ++ unsigned long min, ++ unsigned long max); ++ ++extern void schedule_idle(void); ++ ++asmlinkage void schedule_user(void); ++ ++#ifdef CONFIG_MEMBARRIER ++/* ++ * The scheduler provides memory barriers required by membarrier between: ++ * - prior user-space memory accesses and store to rq->membarrier_state, ++ * - store to rq->membarrier_state and following user-space memory accesses. ++ * In the same way it provides those guarantees around store to rq->curr. ++ */ ++static inline void membarrier_switch_mm(struct rq *rq, ++ struct mm_struct *prev_mm, ++ struct mm_struct *next_mm) ++{ ++ int membarrier_state; ++ ++ if (prev_mm == next_mm) ++ return; ++ ++ membarrier_state = atomic_read(&next_mm->membarrier_state); ++ if (READ_ONCE(rq->membarrier_state) == membarrier_state) ++ return; ++ ++ WRITE_ONCE(rq->membarrier_state, membarrier_state); ++} ++#else ++static inline void membarrier_switch_mm(struct rq *rq, ++ struct mm_struct *prev_mm, ++ struct mm_struct *next_mm) ++{ ++} ++#endif ++ ++#ifdef CONFIG_NUMA ++extern int sched_numa_find_closest(const struct cpumask *cpus, int cpu); ++#else ++static inline int sched_numa_find_closest(const struct cpumask *cpus, int cpu) ++{ ++ return nr_cpu_ids; ++} ++#endif ++ ++extern void swake_up_all_locked(struct swait_queue_head *q); ++extern void __prepare_to_swait(struct swait_queue_head *q, struct swait_queue *wait); ++ ++extern int try_to_wake_up(struct task_struct *tsk, unsigned int state, int wake_flags); ++ ++#ifdef CONFIG_PREEMPT_DYNAMIC ++extern int preempt_dynamic_mode; ++extern int sched_dynamic_mode(const char *str); ++extern void sched_dynamic_update(int mode); ++#endif ++extern const char *preempt_modes[]; ++ ++static inline unsigned long ++uclamp_eff_value(struct task_struct *p, enum uclamp_id clamp_id) ++{ ++ if (clamp_id == UCLAMP_MIN) ++ return 0; ++ ++ return SCHED_CAPACITY_SCALE; ++} ++ ++static inline bool uclamp_rq_is_capped(struct rq *rq) { return false; } ++ ++static inline bool uclamp_is_used(void) ++{ ++ return false; ++} ++ ++static inline unsigned long ++uclamp_rq_get(struct rq *rq, enum uclamp_id clamp_id) ++{ ++ if (clamp_id == UCLAMP_MIN) ++ return 0; ++ ++ return SCHED_CAPACITY_SCALE; ++} ++ ++static inline void ++uclamp_rq_set(struct rq *rq, enum uclamp_id clamp_id, unsigned int value) ++{ ++} ++ ++static inline bool uclamp_rq_is_idle(struct rq *rq) ++{ ++ return false; ++} ++ ++#ifdef CONFIG_SCHED_MM_CID ++ ++static __always_inline bool cid_on_cpu(unsigned int cid) ++{ ++ return cid & MM_CID_ONCPU; ++} ++ ++static __always_inline bool cid_in_transit(unsigned int cid) ++{ ++ return cid & MM_CID_TRANSIT; ++} ++ ++static __always_inline unsigned int cpu_cid_to_cid(unsigned int cid) ++{ ++ return cid & ~MM_CID_ONCPU; ++} ++ ++static __always_inline unsigned int cid_to_cpu_cid(unsigned int cid) ++{ ++ return cid | MM_CID_ONCPU; ++} ++ ++static __always_inline unsigned int cid_to_transit_cid(unsigned int cid) ++{ ++ return cid | MM_CID_TRANSIT; ++} ++ ++static __always_inline unsigned int cid_from_transit_cid(unsigned int cid) ++{ ++ return cid & ~MM_CID_TRANSIT; ++} ++ ++static __always_inline bool cid_on_task(unsigned int cid) ++{ ++ /* True if none of the MM_CID_ONCPU, MM_CID_TRANSIT, MM_CID_UNSET bits is set */ ++ return cid < MM_CID_TRANSIT; ++} ++ ++static __always_inline void mm_drop_cid(struct mm_struct *mm, unsigned int cid) ++{ ++ clear_bit(cid, mm_cidmask(mm)); ++} ++ ++static __always_inline void mm_unset_cid_on_task(struct task_struct *t) ++{ ++ unsigned int cid = t->mm_cid.cid; ++ ++ t->mm_cid.cid = MM_CID_UNSET; ++ if (cid_on_task(cid)) ++ mm_drop_cid(t->mm, cid); ++} ++ ++static __always_inline void mm_drop_cid_on_cpu(struct mm_struct *mm, struct mm_cid_pcpu *pcp) ++{ ++ /* Clear the ONCPU bit, but do not set UNSET in the per CPU storage */ ++ if (cid_on_cpu(pcp->cid)) { ++ pcp->cid = cpu_cid_to_cid(pcp->cid); ++ mm_drop_cid(mm, pcp->cid); ++ } ++} ++ ++static inline unsigned int __mm_get_cid(struct mm_struct *mm, unsigned int max_cids) ++{ ++ unsigned int cid = find_first_zero_bit(mm_cidmask(mm), max_cids); ++ ++ if (cid >= max_cids) ++ return MM_CID_UNSET; ++ if (test_and_set_bit(cid, mm_cidmask(mm))) ++ return MM_CID_UNSET; ++ return cid; ++} ++ ++static inline unsigned int mm_get_cid(struct mm_struct *mm) ++{ ++ unsigned int cid = __mm_get_cid(mm, READ_ONCE(mm->mm_cid.max_cids)); ++ ++ while (cid == MM_CID_UNSET) { ++ cpu_relax(); ++ cid = __mm_get_cid(mm, num_possible_cpus()); ++ } ++ return cid; ++} ++ ++static inline unsigned int mm_cid_converge(struct mm_struct *mm, unsigned int orig_cid, ++ unsigned int max_cids) ++{ ++ unsigned int new_cid, cid = cpu_cid_to_cid(orig_cid); ++ ++ /* Is it in the optimal CID space? */ ++ if (likely(cid < max_cids)) ++ return orig_cid; ++ ++ /* Try to find one in the optimal space. Otherwise keep the provided. */ ++ new_cid = __mm_get_cid(mm, max_cids); ++ if (new_cid != MM_CID_UNSET) { ++ mm_drop_cid(mm, cid); ++ /* Preserve the ONCPU mode of the original CID */ ++ return new_cid | (orig_cid & MM_CID_ONCPU); ++ } ++ return orig_cid; ++} ++ ++static __always_inline void mm_cid_update_task_cid(struct task_struct *t, unsigned int cid) ++{ ++ if (t->mm_cid.cid != cid) { ++ t->mm_cid.cid = cid; ++ rseq_sched_set_ids_changed(t); ++ } ++} ++ ++static __always_inline void mm_cid_update_pcpu_cid(struct mm_struct *mm, unsigned int cid) ++{ ++ __this_cpu_write(mm->mm_cid.pcpu->cid, cid); ++} ++ ++static __always_inline void mm_cid_from_cpu(struct task_struct *t, unsigned int cpu_cid, ++ unsigned int mode) ++{ ++ unsigned int max_cids, tcid = t->mm_cid.cid; ++ struct mm_struct *mm = t->mm; ++ ++ max_cids = READ_ONCE(mm->mm_cid.max_cids); ++ /* Optimize for the common case where both have the ONCPU bit set */ ++ if (likely(cid_on_cpu(cpu_cid & tcid))) { ++ if (likely(cpu_cid_to_cid(cpu_cid) < max_cids)) { ++ mm_cid_update_task_cid(t, cpu_cid); ++ return; ++ } ++ /* Try to converge into the optimal CID space */ ++ cpu_cid = mm_cid_converge(mm, cpu_cid, max_cids); ++ } else { ++ /* Hand over or drop the task owned CID */ ++ if (cid_on_task(tcid)) { ++ if (cid_on_cpu(cpu_cid)) ++ mm_unset_cid_on_task(t); ++ else ++ cpu_cid = cid_to_cpu_cid(tcid); ++ } ++ /* Still nothing, allocate a new one */ ++ if (!cid_on_cpu(cpu_cid)) ++ cpu_cid = cid_to_cpu_cid(mm_get_cid(mm)); ++ ++ /* Handle the transition mode flag if required */ ++ if (mode & MM_CID_TRANSIT) ++ cpu_cid = cpu_cid_to_cid(cpu_cid) | MM_CID_TRANSIT; ++ } ++ mm_cid_update_pcpu_cid(mm, cpu_cid); ++ mm_cid_update_task_cid(t, cpu_cid); ++} ++ ++static __always_inline void mm_cid_from_task(struct task_struct *t, unsigned int cpu_cid, ++ unsigned int mode) ++{ ++ unsigned int max_cids, tcid = t->mm_cid.cid; ++ struct mm_struct *mm = t->mm; ++ ++ max_cids = READ_ONCE(mm->mm_cid.max_cids); ++ /* Optimize for the common case, where both have the ONCPU bit clear */ ++ if (likely(cid_on_task(tcid | cpu_cid))) { ++ if (likely(tcid < max_cids)) { ++ mm_cid_update_pcpu_cid(mm, tcid); ++ return; ++ } ++ /* Try to converge into the optimal CID space */ ++ tcid = mm_cid_converge(mm, tcid, max_cids); ++ } else { ++ /* Hand over or drop the CPU owned CID */ ++ if (cid_on_cpu(cpu_cid)) { ++ if (cid_on_task(tcid)) ++ mm_drop_cid_on_cpu(mm, this_cpu_ptr(mm->mm_cid.pcpu)); ++ else ++ tcid = cpu_cid_to_cid(cpu_cid); ++ } ++ /* Still nothing, allocate a new one */ ++ if (!cid_on_task(tcid)) ++ tcid = mm_get_cid(mm); ++ /* Set the transition mode flag if required */ ++ tcid |= mode & MM_CID_TRANSIT; ++ } ++ mm_cid_update_pcpu_cid(mm, tcid); ++ mm_cid_update_task_cid(t, tcid); ++} ++ ++static __always_inline void mm_cid_schedin(struct task_struct *next) ++{ ++ struct mm_struct *mm = next->mm; ++ unsigned int cpu_cid, mode; ++ ++ if (!next->mm_cid.active) ++ return; ++ ++ cpu_cid = __this_cpu_read(mm->mm_cid.pcpu->cid); ++ mode = READ_ONCE(mm->mm_cid.mode); ++ if (likely(!cid_on_cpu(mode))) ++ mm_cid_from_task(next, cpu_cid, mode); ++ else ++ mm_cid_from_cpu(next, cpu_cid, mode); ++} ++ ++static __always_inline void mm_cid_schedout(struct task_struct *prev) ++{ ++ struct mm_struct *mm = prev->mm; ++ unsigned int mode, cid; ++ ++ /* During mode transitions CIDs are temporary and need to be dropped */ ++ if (likely(!cid_in_transit(prev->mm_cid.cid))) ++ return; ++ ++ mode = READ_ONCE(mm->mm_cid.mode); ++ cid = cid_from_transit_cid(prev->mm_cid.cid); ++ ++ /* ++ * If transition mode is done, transfer ownership when the CID is ++ * within the convergence range to optimize the next schedule in. ++ */ ++ if (!cid_in_transit(mode) && cid < READ_ONCE(mm->mm_cid.max_cids)) { ++ if (cid_on_cpu(mode)) ++ cid = cid_to_cpu_cid(cid); ++ ++ /* Update both so that the next schedule in goes into the fast path */ ++ mm_cid_update_pcpu_cid(mm, cid); ++ prev->mm_cid.cid = cid; ++ } else { ++ mm_drop_cid(mm, cid); ++ prev->mm_cid.cid = MM_CID_UNSET; ++ } ++} ++ ++static inline void mm_cid_switch_to(struct task_struct *prev, struct task_struct *next) ++{ ++ mm_cid_schedout(prev); ++ mm_cid_schedin(next); ++} ++ ++#else /* !CONFIG_SCHED_MM_CID: */ ++static inline void mm_cid_switch_to(struct task_struct *prev, struct task_struct *next) { } ++#endif /* !CONFIG_SCHED_MM_CID */ ++ ++static inline void ++queue_balance_callback(struct rq *rq, ++ struct balance_callback *head, ++ void (*func)(struct rq *rq)) ++{ ++ lockdep_assert_rq_held(rq); ++ ++ /* ++ * Don't (re)queue an already queued item; nor queue anything when ++ * balance_push() is active, see the comment with ++ * balance_push_callback. ++ */ ++ if (unlikely(head->next || rq->balance_callback == &balance_push_callback)) ++ return; ++ ++ head->func = func; ++ head->next = rq->balance_callback; ++ rq->balance_callback = head; ++} ++ ++#ifdef CONFIG_RT_MUTEXES ++ ++static inline int __rt_effective_prio(struct task_struct *pi_task, int prio) ++{ ++ if (pi_task) ++ prio = min(prio, pi_task->prio); ++ ++ return prio; ++} ++ ++static inline int rt_effective_prio(struct task_struct *p, int prio) ++{ ++ struct task_struct *pi_task = rt_mutex_get_top_task(p); ++ ++ return __rt_effective_prio(pi_task, prio); ++} ++ ++#else /* !CONFIG_RT_MUTEXES: */ ++ ++static inline int rt_effective_prio(struct task_struct *p, int prio) ++{ ++ return prio; ++} ++ ++#endif /* !CONFIG_RT_MUTEXES */ ++ ++extern int __sched_setscheduler(struct task_struct *p, const struct sched_attr *attr, bool user, bool pi); ++extern int __sched_setaffinity(struct task_struct *p, struct affinity_context *ctx); ++ ++/* balance callback */ ++extern void __balance_callbacks(struct rq *rq, struct rq_flags *rf); ++extern struct balance_callback *splice_balance_callbacks(struct rq *rq); ++extern void balance_callbacks(struct rq *rq, struct balance_callback *head); ++ ++/* ++ * The 'sched_change' pattern is the safe, easy and slow way of changing a ++ * task's scheduling properties. It dequeues a task, such that the scheduler ++ * is fully unaware of it; at which point its properties can be modified; ++ * after which it is enqueued again. ++ * ++ * Typically this must be called while holding task_rq_lock, since most/all ++ * properties are serialized under those locks. There is currently one ++ * exception to this rule in sched/ext which only holds rq->lock. ++ */ ++ ++/* ++ * This structure is a temporary, used to preserve/convey the queueing state ++ * of the task between sched_change_begin() and sched_change_end(). Ensuring ++ * the task's queueing state is idempotent across the operation. ++ */ ++struct sched_change_ctx { ++ u64 prio; ++ struct task_struct *p; ++ int flags; ++ bool queued; ++ bool running; ++}; ++ ++struct sched_change_ctx *sched_change_begin(struct task_struct *p, unsigned int flags); ++void sched_change_end(struct sched_change_ctx *ctx); ++ ++DEFINE_CLASS(sched_change, struct sched_change_ctx *, ++ sched_change_end(_T), ++ sched_change_begin(p, flags), ++ struct task_struct *p, unsigned int flags) ++ ++DEFINE_CLASS_IS_UNCONDITIONAL(sched_change) ++ ++#ifdef CONFIG_SCHED_BMQ ++#include "bmq.h" ++#endif ++#ifdef CONFIG_SCHED_PDS ++#include "pds.h" ++#endif ++ ++#endif /* _KERNEL_SCHED_ALT_SCHED_H */ +diff --git a/kernel/sched/alt_topology.c b/kernel/sched/alt_topology.c +new file mode 100644 +index 0000000..8fde696 +--- /dev/null ++++ b/kernel/sched/alt_topology.c +@@ -0,0 +1,731 @@ ++#include "alt_core.h" ++#include "alt_topology.h" ++ ++/* ++ * The override has been removed, but keep an obsolete setup entry so stale ++ * bootloader configurations are not passed to PID 1 as environment variables. ++ */ ++__setup_param("pcore_cpus=", pcore_cpus_obsolete, NULL, 0); ++ ++enum sched_idle_select_mode { ++ SCHED_IDLE_SELECT_GENERIC, ++#ifdef CONFIG_SCHED_SMT ++ SCHED_IDLE_SELECT_SMT, ++#endif ++ SCHED_IDLE_SELECT_HYBRID, ++}; ++ ++static cpumask_t sched_pcore_mask ____cacheline_aligned_in_smp; ++static cpumask_t sched_ecore_mask; ++static cpumask_t sched_unknown_mask; ++static cpumask_t sched_topology_active_mask; ++ ++/* CPU hotplug is serialized, so one set of rebuild masks is sufficient. */ ++static cpumask_t sched_rebuild_pcore_mask; ++static cpumask_t sched_rebuild_ecore_mask; ++static cpumask_t sched_rebuild_unknown_mask; ++static cpumask_t sched_rebuild_smt_mask; ++static cpumask_t sched_rebuild_visited_mask; ++#ifdef CONFIG_SCHED_SMT ++static cpumask_t sched_rebuild_group_mask; ++#endif ++ ++static enum sched_idle_select_mode sched_idle_select_mode __read_mostly; ++static enum sched_idle_select_mode sched_idle_select_applied __read_mostly; ++static bool sched_heterogeneous __read_mostly; ++static bool sched_mixed_cpu_types __read_mostly; ++static bool sched_unsupported_ecore_smt __read_mostly; ++static bool sched_topology_initialized; ++static bool sched_topology_changed; ++static bool sched_topology_active_changed; ++static bool sched_topology_warn_unknown; ++static bool sched_topology_warn_ecore_smt; ++static bool sched_topology_warn_smt_class; ++ ++#ifdef CONFIG_X86 ++static void sched_detect_cpu_types(const struct cpumask *active_mask) ++{ ++ int cpu; ++ ++ for_each_cpu(cpu, active_mask) { ++ switch (cpu_data(cpu).topo.cpu_type) { ++ case TOPO_CPU_TYPE_PERFORMANCE: ++ cpumask_set_cpu(cpu, &sched_rebuild_pcore_mask); ++ break; ++ case TOPO_CPU_TYPE_EFFICIENCY: ++ case TOPO_CPU_TYPE_LOW_POWER: ++ cpumask_set_cpu(cpu, &sched_rebuild_ecore_mask); ++ break; ++ case TOPO_CPU_TYPE_UNKNOWN: ++ default: ++ cpumask_set_cpu(cpu, &sched_rebuild_unknown_mask); ++ break; ++ } ++ } ++} ++#else ++static inline void sched_detect_cpu_types(const struct cpumask *active_mask) ++{ ++ cpumask_copy(&sched_rebuild_unknown_mask, active_mask); ++} ++#endif ++ ++#ifdef CONFIG_SCHED_SMT ++static bool ++sched_group_has_single_class(const struct cpumask *group, ++ const struct cpumask *pcore_mask, ++ const struct cpumask *ecore_mask, ++ const struct cpumask *unknown_mask) ++{ ++ return cpumask_subset(group, pcore_mask) || ++ cpumask_subset(group, ecore_mask) || ++ cpumask_subset(group, unknown_mask); ++} ++ ++static void sched_detect_smt(const struct cpumask *active_mask) ++{ ++ int cpu, sibling; ++ ++ cpumask_clear(&sched_rebuild_visited_mask); ++ ++ for_each_cpu(cpu, active_mask) { ++ int threads = 0; ++ ++ if (cpumask_test_cpu(cpu, &sched_rebuild_visited_mask)) ++ continue; ++ ++ cpumask_clear(&sched_rebuild_group_mask); ++ for_each_cpu(sibling, cpu_smt_mask(cpu)) { ++ if (!cpumask_test_cpu(sibling, active_mask)) ++ continue; ++ ++ cpumask_set_cpu(sibling, &sched_rebuild_group_mask); ++ cpumask_set_cpu(sibling, &sched_rebuild_visited_mask); ++ threads++; ++ } ++ ++ if (!threads) { ++ cpumask_set_cpu(cpu, &sched_rebuild_group_mask); ++ cpumask_set_cpu(cpu, &sched_rebuild_visited_mask); ++ threads = 1; ++ } ++ ++ if (threads < 2) ++ continue; ++ ++ cpumask_or(&sched_rebuild_smt_mask, &sched_rebuild_smt_mask, ++ &sched_rebuild_group_mask); ++ ++ if (sched_group_has_single_class(&sched_rebuild_group_mask, ++ &sched_rebuild_pcore_mask, ++ &sched_rebuild_ecore_mask, ++ &sched_rebuild_unknown_mask)) ++ continue; ++ ++ cpumask_andnot(&sched_rebuild_pcore_mask, ++ &sched_rebuild_pcore_mask, ++ &sched_rebuild_group_mask); ++ cpumask_andnot(&sched_rebuild_ecore_mask, ++ &sched_rebuild_ecore_mask, ++ &sched_rebuild_group_mask); ++ cpumask_or(&sched_rebuild_unknown_mask, ++ &sched_rebuild_unknown_mask, ++ &sched_rebuild_group_mask); ++ } ++} ++#else ++static inline void sched_detect_smt(const struct cpumask *active_mask) { } ++#endif ++ ++struct sched_topology_policy { ++ enum sched_idle_select_mode idle_select_mode; ++ bool heterogeneous; ++ bool mixed_cpu_types; ++ bool unsupported_ecore_smt; ++}; ++ ++static struct sched_topology_policy sched_rebuild_policy; ++ ++static void ++sched_select_topology_policy(const struct cpumask *active_mask, ++ const struct cpumask *pcore_mask, ++ const struct cpumask *ecore_mask, ++ const struct cpumask *unknown_mask, ++ const struct cpumask *smt_mask, ++ struct sched_topology_policy *policy) ++{ ++ bool have_known = !cpumask_empty(pcore_mask) || ++ !cpumask_empty(ecore_mask); ++ bool complete_hybrid = ++ !cpumask_empty(pcore_mask) && ++ !cpumask_empty(ecore_mask) && ++ cpumask_empty(unknown_mask); ++ ++ policy->idle_select_mode = SCHED_IDLE_SELECT_GENERIC; ++ policy->mixed_cpu_types = ++ have_known && !cpumask_empty(unknown_mask); ++#ifdef CONFIG_SCHED_SMT ++ policy->unsupported_ecore_smt = ++ cpumask_intersects(ecore_mask, smt_mask); ++#else ++ policy->unsupported_ecore_smt = false; ++#endif ++ policy->heterogeneous = ++ complete_hybrid && !policy->unsupported_ecore_smt; ++ ++ if (policy->heterogeneous) { ++ policy->idle_select_mode = SCHED_IDLE_SELECT_HYBRID; ++ return; ++ } ++ ++#ifdef CONFIG_SCHED_SMT ++ if (!cpumask_empty(active_mask) && ++ cpumask_equal(smt_mask, active_mask)) ++ policy->idle_select_mode = SCHED_IDLE_SELECT_SMT; ++#endif ++} ++ ++DEFINE_PER_CPU_READ_MOSTLY(enum cpu_topo_type, sched_cpu_topo); ++DEFINE_PER_CPU_READ_MOSTLY(enum cpu_topo_balance_type, sched_cpu_topo_balance); ++DEFINE_PER_CPU(struct balance_callback, active_balance_head); ++ ++/* ++ * Idle cpu/rq selection functions ++ */ ++#ifdef CONFIG_SCHED_SMT ++static bool p1_idle_select_func(struct cpumask *dstp, const struct cpumask *src1p, ++ const struct cpumask *src2p) ++{ ++ return (cpumask_and(dstp, src1p, sched_sg_idle_mask) && ++ cpumask_and(dstp, dstp, src2p)) || ++ cpumask_and(dstp, src1p, src2p); ++} ++#endif ++ ++static bool p1p2_idle_select_func(struct cpumask *dstp, const struct cpumask *src1p, ++ const struct cpumask *src2p) ++{ ++ return (cpumask_and(dstp, src1p, sched_pcore_idle_mask) && ++ cpumask_and(dstp, dstp, src2p)) || ++ (cpumask_and(dstp, src1p, sched_ecore_idle_mask) && ++ cpumask_and(dstp, dstp, src2p)) || ++ cpumask_and(dstp, src1p, src2p); ++} ++ ++/* common balance functions */ ++static int active_balance_cpu_stop(void *data) ++{ ++ struct balance_arg *arg = data; ++ struct task_struct *p = arg->task; ++ struct rq *rq = this_rq(); ++ struct rq_flags rf; ++ cpumask_t tmp; ++ ++ local_irq_save(rf.flags); ++ ++ raw_spin_lock(&p->pi_lock); ++ rq_lock(rq, &rf); ++ ++ arg->active = 0; ++ ++ if (task_on_rq_queued(p) && task_rq(p) == rq && ++ cpumask_and(&tmp, p->cpus_ptr, arg->cpumask) && ++ cpumask_and(&tmp, &tmp, sched_idle_mask) && ++ cpumask_and(&tmp, &tmp, cpu_active_mask) && ++ !is_migration_disabled(p)) { ++ int dcpu = __best_mask_cpu(&tmp, per_cpu(sched_cpu_llc_mask, cpu_of(rq)), ++ per_cpu(sched_cpu_topo_end_mask, cpu_of(rq))); ++ rq = move_queued_task(rq, &rf, p, dcpu); ++ } ++ ++ rq_unlock(rq, &rf); ++ raw_spin_unlock_irqrestore(&p->pi_lock, rf.flags); ++ ++ put_task_struct(p); ++ ++ return 0; ++} ++ ++/* trigger_active_balance - for @rq */ ++static inline int ++trigger_active_balance(struct rq *src_rq, struct rq *rq, cpumask_t *target_mask) ++{ ++ struct balance_arg *arg; ++ unsigned long flags; ++ struct task_struct *p; ++ int res; ++ ++ local_irq_save(flags); ++ if (!raw_spin_rq_trylock(rq)) { ++ local_irq_restore(flags); ++ return 0; ++ } ++ ++ arg = &rq->active_balance_arg; ++ res = (1 == rq->nr_running) && \ ++ !is_migration_disabled((p = sched_rq_first_task(rq))) && \ ++ cpumask_intersects(p->cpus_ptr, target_mask) && \ ++ !arg->active; ++ if (res) { ++ arg->task = p; ++ arg->cpumask = target_mask; ++ get_task_struct(p); ++ ++ arg->active = 1; ++ } ++ ++ raw_spin_rq_unlock_irqrestore(rq, flags); ++ ++ if (res) { ++ preempt_disable(); ++ raw_spin_rq_unlock(src_rq); ++ ++ stop_one_cpu_nowait(cpu_of(rq), active_balance_cpu_stop, arg, ++ &rq->active_balance_work); ++ ++ preempt_enable(); ++ raw_spin_rq_lock(src_rq); ++ } ++ ++ return res; ++} ++ ++static inline int ++ecore_source_balance(struct rq *rq, cpumask_t *single_task_mask, cpumask_t *target_mask) ++{ ++ if (cpumask_and(single_task_mask, single_task_mask, &sched_ecore_mask)) { ++ int i, cpu = cpu_of(rq); ++ ++ for_each_cpu_wrap(i, single_task_mask, cpu) ++ if (trigger_active_balance(rq, cpu_rq(i), target_mask)) ++ return 1; ++ } ++ ++ return 0; ++} ++ ++#ifdef CONFIG_SCHED_SMT ++static bool sched_smt_group_busy(int cpu, const struct cpumask *busy_mask) ++{ ++ int sibling; ++ ++ for_each_cpu_and(sibling, cpu_smt_mask(cpu), &sched_smt_mask) ++ if (!cpumask_test_cpu(sibling, busy_mask)) ++ return false; ++ ++ return true; ++} ++ ++static bool sched_wakee_recent(struct task_struct *p, u64 now) ++{ ++ s64 delta = now - READ_ONCE(p->wake_start); ++ ++ return time_before(jiffies, READ_ONCE(p->wakee_flip_decay_ts) + 2 * HZ) && ++ delta >= 0 && delta < TICK_NSEC; ++} ++ ++bool sched_smt_group_paired(struct rq *rq, int cpu) ++{ ++ struct task_struct *p = rcu_dereference_all(cpu_rq(cpu)->curr); ++ u64 now = rq_clock(rq); ++ int sibling; ++ ++ if (!sched_wakee_recent(p, now)) ++ return false; ++ ++ for_each_cpu_and(sibling, cpu_smt_mask(cpu), &sched_smt_mask) { ++ struct task_struct *q; ++ ++ if (sibling == cpu) ++ continue; ++ ++ q = rcu_dereference_all(cpu_rq(sibling)->curr); ++ if (READ_ONCE(p->last_wakee) == q && ++ READ_ONCE(q->last_wakee) == p && ++ sched_wakee_recent(q, now)) ++ return true; ++ } ++ ++ return false; ++} ++ ++static inline int ++smt_source_balance(struct rq *rq, cpumask_t *single_task_mask, ++ const struct cpumask *source_mask, cpumask_t *target_mask) ++{ ++ cpumask_t smt_single_mask; ++ ++ if (cpumask_and(&smt_single_mask, single_task_mask, &sched_smt_mask)) { ++ int i, cpu = cpu_of(rq); ++ ++ if (source_mask && ++ !cpumask_and(&smt_single_mask, &smt_single_mask, ++ source_mask)) ++ return 0; ++ ++ for_each_cpu_wrap(i, &smt_single_mask, cpu) { ++ if (sched_smt_group_busy(i, &smt_single_mask) && ++ !sched_smt_group_paired(rq, i) && ++ trigger_active_balance(rq, cpu_rq(i), target_mask)) ++ return 1; ++ } ++ } ++ ++ return 0; ++} ++ ++/* smt p core balance functions */ ++void smt_pcore_balance(struct rq *rq) ++{ ++ cpumask_t single_task_mask; ++ ++ if (cpumask_andnot(&single_task_mask, cpu_active_mask, sched_idle_mask) && ++ cpumask_andnot(&single_task_mask, &single_task_mask, &sched_rq_pending_mask) && ++ (/* smt core group balance */ ++ smt_source_balance(rq, &single_task_mask, &sched_pcore_mask, ++ sched_pcore_idle_mask) || ++ /* e core to idle smt core balance */ ++ ecore_source_balance(rq, &single_task_mask, ++ sched_pcore_idle_mask))) ++ return; ++} ++ ++/* smt balance functions */ ++void smt_balance(struct rq *rq) ++{ ++ cpumask_t single_task_mask; ++ ++ if (cpumask_andnot(&single_task_mask, cpu_active_mask, sched_idle_mask) && ++ cpumask_andnot(&single_task_mask, &single_task_mask, &sched_rq_pending_mask) && ++ smt_source_balance(rq, &single_task_mask, NULL, ++ sched_sg_idle_mask)) ++ return; ++} ++ ++/* e core balance functions */ ++void ecore_balance(struct rq *rq) ++{ ++ cpumask_t single_task_mask; ++ ++ if (cpumask_andnot(&single_task_mask, cpu_active_mask, sched_idle_mask) && ++ cpumask_andnot(&single_task_mask, &single_task_mask, &sched_rq_pending_mask) && ++ cpumask_empty(sched_pcore_idle_mask) && ++ /* smt occupied p core to idle e core balance */ ++ smt_source_balance(rq, &single_task_mask, &sched_pcore_mask, ++ sched_ecore_idle_mask)) ++ return; ++} ++#endif /* CONFIG_SCHED_SMT */ ++ ++/* p core balance functions */ ++void pcore_balance(struct rq *rq) ++{ ++ cpumask_t single_task_mask; ++ ++ if (cpumask_andnot(&single_task_mask, cpu_active_mask, sched_idle_mask) && ++ cpumask_andnot(&single_task_mask, &single_task_mask, &sched_rq_pending_mask) && ++ /* idle e core to p core balance */ ++ ecore_source_balance(rq, &single_task_mask, sched_pcore_idle_mask)) ++ return; ++} ++ ++static const char *sched_idle_select_mode_name(enum sched_idle_select_mode mode) ++{ ++ switch (mode) { ++ case SCHED_IDLE_SELECT_GENERIC: ++ return "generic"; ++#ifdef CONFIG_SCHED_SMT ++ case SCHED_IDLE_SELECT_SMT: ++ return "SMT"; ++#endif ++ case SCHED_IDLE_SELECT_HYBRID: ++ return "hybrid"; ++ } ++ ++ return "unknown"; ++} ++ ++static void sched_idle_select_update(enum sched_idle_select_mode mode) ++{ ++ if (mode == READ_ONCE(sched_idle_select_applied)) ++ return; ++ ++ switch (mode) { ++ case SCHED_IDLE_SELECT_GENERIC: ++ static_call_update(sched_idle_select_func, cpumask_and); ++ break; ++#ifdef CONFIG_SCHED_SMT ++ case SCHED_IDLE_SELECT_SMT: ++ static_call_update(sched_idle_select_func, p1_idle_select_func); ++ break; ++#endif ++ case SCHED_IDLE_SELECT_HYBRID: ++ static_call_update(sched_idle_select_func, p1p2_idle_select_func); ++ break; ++ } ++ ++ WRITE_ONCE(sched_idle_select_applied, mode); ++} ++ ++static void sched_idle_select_workfn(struct work_struct *work) ++{ ++ enum sched_idle_select_mode mode; ++ ++ do { ++ /* static_call_update() takes cpus_read_lock() itself. */ ++ mode = READ_ONCE(sched_idle_select_mode); ++ sched_idle_select_update(mode); ++ } while (mode != READ_ONCE(sched_idle_select_mode)); ++} ++ ++static DECLARE_WORK(sched_idle_select_work, sched_idle_select_workfn); ++ ++void sched_topology_queue_idle_select(void) ++{ ++ if (READ_ONCE(sched_idle_select_mode) != ++ READ_ONCE(sched_idle_select_applied)) ++ schedule_work(&sched_idle_select_work); ++} ++ ++void __init sched_topology_init_idle_select(void) ++{ ++ sched_idle_select_update(READ_ONCE(sched_idle_select_mode)); ++} ++ ++/* Reports outside the stopped machine; CPU hotplug serializes against itself. */ ++void sched_topology_report(void) ++{ ++ bool changed = sched_topology_changed; ++ bool active_changed = sched_topology_active_changed; ++ bool warn_ecore_smt = sched_topology_warn_ecore_smt; ++ bool warn_smt_class = sched_topology_warn_smt_class; ++ bool warn_unknown = sched_topology_warn_unknown; ++ ++ sched_topology_changed = false; ++ sched_topology_active_changed = false; ++ sched_topology_warn_ecore_smt = false; ++ sched_topology_warn_smt_class = false; ++ sched_topology_warn_unknown = false; ++ ++ WARN_ONCE(warn_smt_class, ++ "sched/alt: P/E scheduling with a non-performance SMT group in %*pbl\n", ++ cpumask_pr_args(&sched_smt_mask)); ++ ++ if (warn_unknown) ++ pr_warn_once("sched/alt: UNKNOWN CPU types in %*pbl; disabling P/E auto-detection\n", ++ cpumask_pr_args(&sched_unknown_mask)); ++ ++ if (warn_ecore_smt) ++ pr_warn_once("sched/alt: E-core SMT is unsupported; using homogeneous scheduling\n"); ++ ++ if (!changed) { ++ if (active_changed) ++ pr_debug_ratelimited("sched/alt: active CPUs: %*pbl\n", ++ cpumask_pr_args(&sched_topology_active_mask)); ++ return; ++ } ++ ++ pr_info("sched/alt: %s topology, idle select: %s, active: %*pbl, SMT: %*pbl%s%*pbl%s%*pbl%s%*pbl\n", ++ sched_heterogeneous ? "heterogeneous" : "homogeneous", ++ sched_idle_select_mode_name(READ_ONCE(sched_idle_select_mode)), ++ cpumask_pr_args(&sched_topology_active_mask), ++ cpumask_pr_args(&sched_smt_mask), ++ cpumask_empty(&sched_pcore_mask) ? "" : ", P: ", ++ cpumask_pr_args(&sched_pcore_mask), ++ cpumask_empty(&sched_ecore_mask) ? "" : ", E: ", ++ cpumask_pr_args(&sched_ecore_mask), ++ sched_mixed_cpu_types ? ", UNKNOWN: " : "", ++ cpumask_pr_args(sched_mixed_cpu_types ? ++ &sched_unknown_mask : cpu_none_mask)); ++} ++ ++#ifdef CONFIG_SCHED_SMT ++static bool sched_rebuild_smt_group_idle(int cpu) ++{ ++ int sibling; ++ ++ for_each_cpu_and(sibling, cpu_smt_mask(cpu), &sched_smt_mask) ++ if (!cpumask_test_cpu(sibling, sched_idle_mask)) ++ return false; ++ ++ return true; ++} ++#endif ++ ++static void sched_rebuild_idle_masks(const struct cpumask *active_mask) ++{ ++ int cpu; ++ ++ /* ++ * Every active CPU runs a stopper here, so a remaining bit belongs to ++ * a CPU which is not active and cannot be a placement candidate. ++ */ ++ cpumask_and(sched_idle_mask, sched_idle_mask, active_mask); ++ cpumask_clear(sched_sg_idle_mask); ++ cpumask_clear(sched_pcore_idle_mask); ++ cpumask_clear(sched_ecore_idle_mask); ++ cpumask_clear(&sched_rebuild_visited_mask); ++ ++ for_each_cpu(cpu, active_mask) { ++#ifdef CONFIG_SCHED_SMT ++ if (cpumask_test_cpu(cpu, &sched_smt_mask)) { ++ int sibling; ++ ++ if (cpumask_test_cpu(cpu, &sched_rebuild_visited_mask)) ++ continue; ++ ++ cpumask_clear(&sched_rebuild_group_mask); ++ for_each_cpu_and(sibling, cpu_smt_mask(cpu), ++ &sched_smt_mask) { ++ cpumask_set_cpu(sibling, ++ &sched_rebuild_group_mask); ++ cpumask_set_cpu(sibling, ++ &sched_rebuild_visited_mask); ++ } ++ ++ if (!sched_rebuild_smt_group_idle(cpu)) ++ continue; ++ ++ cpumask_or(sched_sg_idle_mask, sched_sg_idle_mask, ++ &sched_rebuild_group_mask); ++ if (per_cpu(sched_cpu_topo, cpu) == ++ CPU_TOPOLOGY_PCORE) ++ cpumask_or(sched_pcore_idle_mask, ++ sched_pcore_idle_mask, ++ &sched_rebuild_group_mask); ++ continue; ++ } ++#endif ++ ++ if (!cpumask_test_cpu(cpu, sched_idle_mask)) ++ continue; ++ ++ switch (per_cpu(sched_cpu_topo, cpu)) { ++ case CPU_TOPOLOGY_DEFAULT: ++ break; ++ case CPU_TOPOLOGY_PCORE: ++ cpumask_set_cpu(cpu, sched_pcore_idle_mask); ++ break; ++ case CPU_TOPOLOGY_ECORE: ++ cpumask_set_cpu(cpu, sched_ecore_idle_mask); ++ break; ++ } ++ } ++} ++ ++void sched_topology_prepare(const struct cpumask *active_mask) ++{ ++ cpumask_clear(&sched_rebuild_pcore_mask); ++ cpumask_clear(&sched_rebuild_ecore_mask); ++ cpumask_clear(&sched_rebuild_unknown_mask); ++ cpumask_clear(&sched_rebuild_smt_mask); ++ ++ sched_detect_cpu_types(active_mask); ++ sched_detect_smt(active_mask); ++ sched_select_topology_policy(active_mask, ++ &sched_rebuild_pcore_mask, ++ &sched_rebuild_ecore_mask, ++ &sched_rebuild_unknown_mask, ++ &sched_rebuild_smt_mask, ++ &sched_rebuild_policy); ++} ++ ++void sched_topology_apply(const struct cpumask *active_mask) ++{ ++ bool active_changed = ++ !cpumask_equal(active_mask, &sched_topology_active_mask); ++ bool semantic_changed = ++ !sched_topology_initialized || ++ sched_rebuild_policy.heterogeneous != sched_heterogeneous || ++ sched_rebuild_policy.mixed_cpu_types != sched_mixed_cpu_types || ++ sched_rebuild_policy.unsupported_ecore_smt != ++ sched_unsupported_ecore_smt || ++ sched_rebuild_policy.idle_select_mode != sched_idle_select_mode; ++#ifdef CONFIG_SCHED_SMT ++ bool pcore_smt = ++ cpumask_intersects(&sched_rebuild_pcore_mask, ++ &sched_rebuild_smt_mask); ++#endif ++ int cpu; ++ ++ cpumask_or(&sched_rebuild_visited_mask, &sched_topology_active_mask, ++ active_mask); ++ ++ if (sched_rebuild_policy.mixed_cpu_types && ++ !sched_mixed_cpu_types) ++ sched_topology_warn_unknown = true; ++ if (sched_rebuild_policy.unsupported_ecore_smt && ++ !sched_unsupported_ecore_smt) ++ sched_topology_warn_ecore_smt = true; ++ ++ cpumask_copy(&sched_topology_active_mask, active_mask); ++ cpumask_copy(&sched_smt_mask, &sched_rebuild_smt_mask); ++ cpumask_copy(&sched_pcore_mask, &sched_rebuild_pcore_mask); ++ cpumask_copy(&sched_ecore_mask, &sched_rebuild_ecore_mask); ++ cpumask_copy(&sched_unknown_mask, &sched_rebuild_unknown_mask); ++ sched_heterogeneous = sched_rebuild_policy.heterogeneous; ++ sched_mixed_cpu_types = sched_rebuild_policy.mixed_cpu_types; ++ sched_unsupported_ecore_smt = ++ sched_rebuild_policy.unsupported_ecore_smt; ++ WRITE_ONCE(sched_idle_select_mode, ++ sched_rebuild_policy.idle_select_mode); ++ ++ for_each_cpu(cpu, &sched_rebuild_visited_mask) { ++ per_cpu(sched_cpu_topo, cpu) = CPU_TOPOLOGY_DEFAULT; ++ per_cpu(sched_cpu_topo_balance, cpu) = CPU_TOPOLOGY_BALANCE_NONE; ++ } ++ ++ for_each_cpu(cpu, active_mask) { ++ if (sched_heterogeneous) { ++ if (cpumask_test_cpu(cpu, &sched_pcore_mask)) ++ per_cpu(sched_cpu_topo, cpu) = ++ CPU_TOPOLOGY_PCORE; ++ else if (cpumask_test_cpu(cpu, &sched_ecore_mask)) ++ per_cpu(sched_cpu_topo, cpu) = ++ CPU_TOPOLOGY_ECORE; ++ } ++ ++#ifdef CONFIG_SCHED_SMT ++ if (cpumask_test_cpu(cpu, &sched_smt_mask)) { ++ if (sched_heterogeneous) { ++ if (per_cpu(sched_cpu_topo, cpu) != ++ CPU_TOPOLOGY_PCORE) ++ sched_topology_warn_smt_class = true; ++ per_cpu(sched_cpu_topo_balance, cpu) = ++ CPU_TOPOLOGY_BALANCE_SMT_PCORE; ++ } else { ++ per_cpu(sched_cpu_topo_balance, cpu) = ++ CPU_TOPOLOGY_BALANCE_SMT; ++ } ++ ++ continue; ++ } ++#endif ++ if (!sched_heterogeneous) ++ continue; ++ ++ if (per_cpu(sched_cpu_topo, cpu) == CPU_TOPOLOGY_PCORE) { ++ per_cpu(sched_cpu_topo_balance, cpu) = ++ CPU_TOPOLOGY_BALANCE_PCORE; ++ continue; ++ } ++ ++ if (per_cpu(sched_cpu_topo, cpu) == CPU_TOPOLOGY_ECORE) { ++#ifdef CONFIG_SCHED_SMT ++ if (pcore_smt) ++ per_cpu(sched_cpu_topo_balance, cpu) = ++ CPU_TOPOLOGY_BALANCE_ECORE; ++#endif ++ } ++ } ++ ++ sched_rebuild_idle_masks(active_mask); ++ ++ sched_topology_initialized = true; ++ sched_topology_changed |= semantic_changed; ++ sched_topology_active_changed |= active_changed; ++} ++ ++#ifdef CONFIG_SCHED_ALT_TOPOLOGY_KUNIT_TEST ++#include "alt_topology_test.c" ++#endif +diff --git a/kernel/sched/alt_topology.h b/kernel/sched/alt_topology.h +new file mode 100644 +index 0000000..9deb40c +--- /dev/null ++++ b/kernel/sched/alt_topology.h +@@ -0,0 +1,178 @@ ++#ifndef _KERNEL_SCHED_ALT_TOPOLOGY_H ++#define _KERNEL_SCHED_ALT_TOPOLOGY_H ++ ++/* ++ * CPU topology type ++ */ ++enum cpu_topo_type { ++ CPU_TOPOLOGY_DEFAULT = 0, ++ CPU_TOPOLOGY_PCORE, ++ CPU_TOPOLOGY_ECORE, ++}; ++ ++DECLARE_PER_CPU_READ_MOSTLY(enum cpu_topo_type, sched_cpu_topo); ++ ++#ifdef CONFIG_SCHED_SMT ++static inline bool sched_smt_active_group_idle(const unsigned int cpu) ++{ ++ unsigned int sibling; ++ ++ for_each_cpu_and(sibling, cpu_smt_mask(cpu), &sched_smt_mask) ++ if (!cpumask_test_cpu(sibling, sched_idle_mask)) ++ return false; ++ ++ return true; ++} ++ ++static inline void sched_set_smt_idle_masks(const unsigned int cpu) ++{ ++ enum cpu_topo_type class = per_cpu(sched_cpu_topo, cpu); ++ unsigned int sibling; ++ ++ for_each_cpu_and(sibling, cpu_smt_mask(cpu), &sched_smt_mask) { ++ cpumask_set_cpu(sibling, sched_sg_idle_mask); ++ if (class == CPU_TOPOLOGY_PCORE) ++ cpumask_set_cpu(sibling, sched_pcore_idle_mask); ++ } ++} ++ ++static inline void sched_clear_smt_idle_masks(const unsigned int cpu) ++{ ++ enum cpu_topo_type class = per_cpu(sched_cpu_topo, cpu); ++ unsigned int sibling; ++ ++ for_each_cpu_and(sibling, cpu_smt_mask(cpu), &sched_smt_mask) { ++ cpumask_clear_cpu(sibling, sched_sg_idle_mask); ++ if (class == CPU_TOPOLOGY_PCORE) ++ cpumask_clear_cpu(sibling, sched_pcore_idle_mask); ++ } ++} ++#endif ++ ++static inline void sched_set_idle_mask(const unsigned int cpu) ++{ ++#ifdef CONFIG_SCHED_SMT ++ if (cpumask_test_cpu(cpu, &sched_smt_mask)) { ++ cpumask_set_cpu(cpu, sched_idle_mask); ++ smp_mb__after_atomic(); ++ ++ if (!sched_smt_active_group_idle(cpu)) ++ return; ++ ++ unsigned int leader = ++ cpumask_first_and(cpu_smt_mask(cpu), &sched_smt_mask); ++ raw_spinlock_t *lock = &per_cpu(sched_smt_idle_lock, leader); ++ ++ raw_spin_lock(lock); ++ if (sched_smt_active_group_idle(cpu)) ++ sched_set_smt_idle_masks(cpu); ++ raw_spin_unlock(lock); ++ return; ++ } ++#endif ++ ++ cpumask_set_cpu(cpu, sched_idle_mask); ++ ++ switch (per_cpu(sched_cpu_topo, cpu)) { ++ case CPU_TOPOLOGY_DEFAULT: ++ break; ++ case CPU_TOPOLOGY_PCORE: ++ cpumask_set_cpu(cpu, sched_pcore_idle_mask); ++ break; ++ case CPU_TOPOLOGY_ECORE: ++ cpumask_set_cpu(cpu, sched_ecore_idle_mask); ++ break; ++ } ++} ++ ++static inline void sched_clear_idle_mask(const unsigned int cpu) ++{ ++#ifdef CONFIG_SCHED_SMT ++ if (cpumask_test_cpu(cpu, &sched_smt_mask)) { ++ unsigned int leader = ++ cpumask_first_and(cpu_smt_mask(cpu), &sched_smt_mask); ++ raw_spinlock_t *lock = &per_cpu(sched_smt_idle_lock, leader); ++ ++ raw_spin_lock(lock); ++ if (cpumask_test_cpu(cpu, sched_sg_idle_mask)) ++ sched_clear_smt_idle_masks(cpu); ++ cpumask_clear_cpu(cpu, sched_idle_mask); ++ raw_spin_unlock(lock); ++ return; ++ } ++#endif ++ ++ cpumask_clear_cpu(cpu, sched_idle_mask); ++ ++ switch (per_cpu(sched_cpu_topo, cpu)) { ++ case CPU_TOPOLOGY_DEFAULT: ++ break; ++ case CPU_TOPOLOGY_PCORE: ++ cpumask_clear_cpu(cpu, sched_pcore_idle_mask); ++ break; ++ case CPU_TOPOLOGY_ECORE: ++ cpumask_clear_cpu(cpu, sched_ecore_idle_mask); ++ break; ++ } ++} ++ ++/* ++ * CPU topology balance type ++ */ ++enum cpu_topo_balance_type { ++ CPU_TOPOLOGY_BALANCE_NONE = 0, ++ CPU_TOPOLOGY_BALANCE_PCORE, ++#ifdef CONFIG_SCHED_SMT ++ CPU_TOPOLOGY_BALANCE_ECORE, ++ CPU_TOPOLOGY_BALANCE_SMT, ++ CPU_TOPOLOGY_BALANCE_SMT_PCORE, ++#endif ++}; ++ ++DECLARE_PER_CPU_READ_MOSTLY(enum cpu_topo_balance_type, sched_cpu_topo_balance); ++DECLARE_PER_CPU(struct balance_callback, active_balance_head); ++ ++extern void pcore_balance(struct rq *rq); ++#ifdef CONFIG_SCHED_SMT ++extern void ecore_balance(struct rq *rq); ++extern void smt_balance(struct rq *rq); ++bool sched_smt_group_paired(struct rq *rq, int cpu); ++extern void smt_pcore_balance(struct rq *rq); ++#endif ++ ++static inline void sched_cpu_topology_balance(const unsigned int cpu, struct rq *rq) ++{ ++ struct balance_callback *head = &per_cpu(active_balance_head, cpu); ++ ++ if (!rq->online) ++ return; ++ ++ switch (per_cpu(sched_cpu_topo_balance, cpu)) { ++ case CPU_TOPOLOGY_BALANCE_NONE: ++ break; ++ case CPU_TOPOLOGY_BALANCE_PCORE: ++ queue_balance_callback(rq, head, pcore_balance); ++ break; ++#ifdef CONFIG_SCHED_SMT ++ case CPU_TOPOLOGY_BALANCE_ECORE: ++ queue_balance_callback(rq, head, ecore_balance); ++ break; ++ case CPU_TOPOLOGY_BALANCE_SMT: ++ if (cpumask_test_cpu(cpu, sched_sg_idle_mask)) ++ queue_balance_callback(rq, head, smt_balance); ++ break; ++ case CPU_TOPOLOGY_BALANCE_SMT_PCORE: ++ if (cpumask_test_cpu(cpu, sched_sg_idle_mask)) ++ queue_balance_callback(rq, head, smt_pcore_balance); ++ break; ++#endif ++ } ++} ++ ++void sched_topology_prepare(const struct cpumask *active_mask); ++void sched_topology_apply(const struct cpumask *active_mask); ++void sched_topology_report(void); ++void sched_topology_init_idle_select(void); ++void sched_topology_queue_idle_select(void); ++ ++#endif /* _KERNEL_SCHED_ALT_TOPOLOGY_H */ +diff --git a/kernel/sched/alt_topology_test.c b/kernel/sched/alt_topology_test.c +new file mode 100644 +index 0000000..6bdf2d4 +--- /dev/null ++++ b/kernel/sched/alt_topology_test.c +@@ -0,0 +1,211 @@ ++// SPDX-License-Identifier: GPL-2.0-only ++ ++#include ++ ++/* This file is included by alt_topology.c so it can exercise static helpers. */ ++ ++struct sched_topology_test_case { ++ const char *name; ++ unsigned long active; ++ unsigned long pcore; ++ unsigned long ecore; ++ unsigned long unknown; ++ unsigned long smt; ++ enum sched_idle_select_mode mode; ++ bool heterogeneous; ++ bool mixed_cpu_types; ++ bool unsupported_ecore_smt; ++}; ++ ++struct sched_topology_test_masks { ++ cpumask_t active; ++ cpumask_t pcore; ++ cpumask_t ecore; ++ cpumask_t unknown; ++ cpumask_t smt; ++}; ++ ++static void sched_topology_test_mask(cpumask_t *mask, unsigned long bits) ++{ ++ unsigned int cpu; ++ ++ cpumask_clear(mask); ++ for_each_set_bit(cpu, &bits, ++ min_t(unsigned int, BITS_PER_LONG, nr_cpu_ids)) ++ cpumask_set_cpu(cpu, mask); ++} ++ ++static void sched_topology_policy_test(struct kunit *test) ++{ ++ static const struct sched_topology_test_case cases[] = { ++ { ++ .name = "uniformly unknown", ++ .active = BIT(0) | BIT(1), ++ .unknown = BIT(0) | BIT(1), ++ .mode = SCHED_IDLE_SELECT_GENERIC, ++ }, ++ { ++ .name = "performance only", ++ .active = BIT(0) | BIT(1), ++ .pcore = BIT(0) | BIT(1), ++ .mode = SCHED_IDLE_SELECT_GENERIC, ++ }, ++ { ++ .name = "efficiency only", ++ .active = BIT(0) | BIT(1), ++ .ecore = BIT(0) | BIT(1), ++ .mode = SCHED_IDLE_SELECT_GENERIC, ++ }, ++ { ++ .name = "hybrid without SMT", ++ .active = BIT(0) | BIT(1), ++ .pcore = BIT(0), ++ .ecore = BIT(1), ++ .mode = SCHED_IDLE_SELECT_HYBRID, ++ .heterogeneous = true, ++ }, ++ { ++ .name = "hybrid with P-core SMT", ++ .active = BIT(0) | BIT(1) | BIT(2), ++ .pcore = BIT(0) | BIT(1), ++ .ecore = BIT(2), ++ .smt = BIT(0) | BIT(1), ++ .mode = SCHED_IDLE_SELECT_HYBRID, ++ .heterogeneous = true, ++ }, ++ { ++ .name = "hybrid with partial E-core SMT", ++ .active = BIT(0) | BIT(1) | BIT(2), ++ .pcore = BIT(0), ++ .ecore = BIT(1) | BIT(2), ++ .smt = BIT(1) | BIT(2), ++ .mode = SCHED_IDLE_SELECT_GENERIC, ++ .unsupported_ecore_smt = true, ++ }, ++ { ++ .name = "hybrid with universal SMT", ++ .active = BIT(0) | BIT(1) | BIT(2) | BIT(3), ++ .pcore = BIT(0) | BIT(1), ++ .ecore = BIT(2) | BIT(3), ++ .smt = BIT(0) | BIT(1) | BIT(2) | BIT(3), ++ .mode = SCHED_IDLE_SELECT_SMT, ++ .unsupported_ecore_smt = true, ++ }, ++ { ++ .name = "homogeneous SMT", ++ .active = BIT(0) | BIT(1), ++ .unknown = BIT(0) | BIT(1), ++ .smt = BIT(0) | BIT(1), ++ .mode = SCHED_IDLE_SELECT_SMT, ++ }, ++ { ++ .name = "mixed known and unknown", ++ .active = BIT(0) | BIT(1) | BIT(2), ++ .pcore = BIT(0), ++ .ecore = BIT(1), ++ .unknown = BIT(2), ++ .mode = SCHED_IDLE_SELECT_GENERIC, ++ .mixed_cpu_types = true, ++ }, ++ { ++ .name = "mixed topology with E-core SMT", ++ .active = BIT(0) | BIT(1) | BIT(2) | BIT(3), ++ .pcore = BIT(0), ++ .ecore = BIT(1) | BIT(2), ++ .unknown = BIT(3), ++ .smt = BIT(1) | BIT(2), ++ .mode = SCHED_IDLE_SELECT_GENERIC, ++ .mixed_cpu_types = true, ++ .unsupported_ecore_smt = true, ++ }, ++ }; ++ struct sched_topology_test_masks *masks; ++ struct sched_topology_policy policy; ++ int i; ++ ++ if (nr_cpu_ids < 4) { ++ kunit_skip(test, "at least four CPU bits are required"); ++ return; ++ } ++ ++ masks = kunit_kzalloc(test, sizeof(*masks), GFP_KERNEL); ++ KUNIT_ASSERT_NOT_NULL(test, masks); ++ ++ for (i = 0; i < ARRAY_SIZE(cases); i++) { ++ const struct sched_topology_test_case *casep = &cases[i]; ++ ++ sched_topology_test_mask(&masks->active, casep->active); ++ sched_topology_test_mask(&masks->pcore, casep->pcore); ++ sched_topology_test_mask(&masks->ecore, casep->ecore); ++ sched_topology_test_mask(&masks->unknown, casep->unknown); ++ sched_topology_test_mask(&masks->smt, casep->smt); ++ ++ sched_select_topology_policy(&masks->active, &masks->pcore, ++ &masks->ecore, &masks->unknown, ++ &masks->smt, &policy); ++ ++ KUNIT_EXPECT_EQ_MSG(test, policy.idle_select_mode, ++ casep->mode, "%s", casep->name); ++ KUNIT_EXPECT_EQ_MSG(test, policy.heterogeneous, ++ casep->heterogeneous, "%s", casep->name); ++ KUNIT_EXPECT_EQ_MSG(test, policy.mixed_cpu_types, ++ casep->mixed_cpu_types, "%s", casep->name); ++ KUNIT_EXPECT_EQ_MSG(test, policy.unsupported_ecore_smt, ++ casep->unsupported_ecore_smt, ++ "%s", casep->name); ++ } ++} ++ ++static void sched_topology_group_class_test(struct kunit *test) ++{ ++ struct sched_topology_test_masks *masks; ++ bool single_class; ++ ++ if (nr_cpu_ids < 2) { ++ kunit_skip(test, "at least two CPU bits are required"); ++ return; ++ } ++ ++ masks = kunit_kzalloc(test, sizeof(*masks), GFP_KERNEL); ++ KUNIT_ASSERT_NOT_NULL(test, masks); ++ ++ sched_topology_test_mask(&masks->active, BIT(0) | BIT(1)); ++ sched_topology_test_mask(&masks->pcore, BIT(0) | BIT(1)); ++ sched_topology_test_mask(&masks->ecore, 0); ++ sched_topology_test_mask(&masks->unknown, 0); ++ single_class = sched_group_has_single_class(&masks->active, ++ &masks->pcore, ++ &masks->ecore, ++ &masks->unknown); ++ KUNIT_EXPECT_TRUE(test, single_class); ++ ++ sched_topology_test_mask(&masks->pcore, BIT(0)); ++ sched_topology_test_mask(&masks->ecore, BIT(1)); ++ single_class = sched_group_has_single_class(&masks->active, ++ &masks->pcore, ++ &masks->ecore, ++ &masks->unknown); ++ KUNIT_EXPECT_FALSE(test, single_class); ++ ++ sched_topology_test_mask(&masks->pcore, 0); ++ sched_topology_test_mask(&masks->ecore, 0); ++ sched_topology_test_mask(&masks->unknown, BIT(0) | BIT(1)); ++ single_class = sched_group_has_single_class(&masks->active, ++ &masks->pcore, ++ &masks->ecore, ++ &masks->unknown); ++ KUNIT_EXPECT_TRUE(test, single_class); ++} ++ ++static struct kunit_case sched_topology_test_cases[] = { ++ KUNIT_CASE(sched_topology_policy_test), ++ KUNIT_CASE(sched_topology_group_class_test), ++ {} ++}; ++ ++static struct kunit_suite sched_topology_test_suite = { ++ .name = "sched-alt-topology", ++ .test_cases = sched_topology_test_cases, ++}; ++ ++kunit_test_suite(sched_topology_test_suite); +diff --git a/kernel/sched/bmq.h b/kernel/sched/bmq.h +new file mode 100644 +index 0000000..bb46790 +--- /dev/null ++++ b/kernel/sched/bmq.h +@@ -0,0 +1,112 @@ ++#ifndef _KERNEL_SCHED_BMQ_H ++#define _KERNEL_SCHED_BMQ_H ++ ++#define ALT_SCHED_NAME "BMQ" ++ ++/* ++ * BMQ only routines ++ */ ++static inline void boost_task(struct task_struct *p, int n) ++{ ++ int limit; ++ ++ switch (p->policy) { ++ case SCHED_NORMAL: ++ limit = -MAX_PRIORITY_ADJ; ++ break; ++ case SCHED_BATCH: ++ limit = 0; ++ break; ++ default: ++ return; ++ } ++ ++ p->boost_prio = max(limit, p->boost_prio - n); ++} ++ ++static inline void deboost_task(struct task_struct *p) ++{ ++ if ((SCHED_NORMAL == p->policy || SCHED_BATCH == p->policy) && ++ p->boost_prio < MAX_PRIORITY_ADJ) ++ p->boost_prio++; ++} ++ ++/* ++ * Common interfaces ++ */ ++/* This API is used in task_prio(), return value readed by human users */ ++static inline int ++task_sched_prio_normal(const struct task_struct *p, const struct rq *rq) ++{ ++ return p->prio + p->boost_prio - MIN_NORMAL_PRIO; ++} ++ ++static inline int task_sched_prio(const struct task_struct *p) ++{ ++ return (p->prio < MIN_NORMAL_PRIO)? (p->prio >> 2) : ++ MIN_SCHED_NORMAL_PRIO + (p->prio + p->boost_prio - MIN_NORMAL_PRIO) / 2; ++} ++ ++#define TASK_SCHED_PRIO_IDX(p, rq, idx, prio) \ ++ prio = task_sched_prio(p); \ ++ idx = prio; ++ ++static inline int sched_prio2idx(int prio, struct rq *rq) ++{ ++ return prio; ++} ++ ++static inline int sched_idx2prio(int idx, struct rq *rq) ++{ ++ return idx; ++} ++ ++static inline int sched_rq_prio_idx(struct rq *rq) ++{ ++ return rq->prio; ++} ++ ++static inline void sched_rq_set_prio(struct rq *rq, int prio) ++{ ++ rq->prio = prio; ++} ++ ++static inline int task_running_nice(struct task_struct *p) ++{ ++ return (p->prio + p->boost_prio > DEFAULT_PRIO); ++} ++ ++static inline void sched_update_rq_clock(struct rq *rq) {} ++ ++static inline void sched_task_renew(struct task_struct *p, const struct rq *rq) ++{ ++ deboost_task(p); ++} ++ ++static inline void sched_task_sanity_check(struct task_struct *p, struct rq *rq) {} ++static inline void sched_task_fork(struct task_struct *p, struct rq *rq) {} ++ ++static inline void do_sched_yield_type_1(struct task_struct *p, struct rq *rq) ++{ ++ p->boost_prio = MAX_PRIORITY_ADJ; ++} ++ ++static inline void sched_task_ttwu(struct task_struct *p) ++{ ++ s64 delta = this_rq()->clock_task - p->last_ran; ++ ++ if (likely(delta > 0)) ++ boost_task(p, delta >> 22); ++} ++ ++static inline bool sched_task_has_credit(const struct task_struct *p) ++{ ++ return false; ++} ++ ++static inline void sched_task_deactivate(struct task_struct *p, struct rq *rq) ++{ ++ boost_task(p, 1); ++} ++ ++#endif /* _KERNEL_SCHED_BMQ_H */ +diff --git a/kernel/sched/build_policy.c b/kernel/sched/build_policy.c +index 2a82872..89f1fbf 100644 +--- a/kernel/sched/build_policy.c ++++ b/kernel/sched/build_policy.c +@@ -49,13 +49,17 @@ + + #include "idle.c" + +-#include "rt.c" +-#include "cpudeadline.c" ++#ifndef CONFIG_SCHED_ALT ++# include "rt.c" ++# include "cpudeadline.c" ++#endif + + #include "pelt.c" + + #include "cputime.c" ++#ifndef CONFIG_SCHED_ALT + #include "deadline.c" ++#endif + + #ifdef CONFIG_SCHED_CLASS_EXT + # include +diff --git a/kernel/sched/build_utility.c b/kernel/sched/build_utility.c +index e2cf3b0..a64bf71 100644 +--- a/kernel/sched/build_utility.c ++++ b/kernel/sched/build_utility.c +@@ -56,6 +56,10 @@ + + #include "clock.c" + ++#ifdef CONFIG_SCHED_ALT ++# include "alt_topology.c" ++#endif ++ + #ifdef CONFIG_CGROUP_CPUACCT + # include "cpuacct.c" + #endif +@@ -68,7 +72,7 @@ + # include "cpufreq_schedutil.c" + #endif + +-#include "debug.c" ++# include "debug.c" + + #ifdef CONFIG_SCHEDSTATS + # include "stats.c" +@@ -81,7 +85,9 @@ + #include "wait.c" + + #include "cpupri.c" +-#include "stop_task.c" ++#ifndef CONFIG_SCHED_ALT ++# include "stop_task.c" ++#endif + + #include "topology.c" + +diff --git a/kernel/sched/core.c b/kernel/sched/core.c +index 1754d9f..4849135 100644 +--- a/kernel/sched/core.c ++++ b/kernel/sched/core.c +@@ -5097,7 +5097,7 @@ static inline void prepare_task(struct task_struct *next) + WRITE_ONCE(next->on_cpu, 1); + } + +-static inline void finish_task(struct task_struct *prev) ++static __always_inline void finish_task(struct task_struct *prev) + { + /* + * This must be the very last reference to @prev from this CPU. After +@@ -5141,7 +5141,7 @@ static void zap_balance_callbacks(struct rq *rq) + rq->balance_callback = found ? &balance_push_callback : NULL; + } + +-static void do_balance_callbacks(struct rq *rq, struct balance_callback *head) ++static __always_inline void do_balance_callbacks(struct rq *rq, struct balance_callback *head) + { + void (*func)(struct rq *rq); + struct balance_callback *next; +@@ -5176,7 +5176,7 @@ struct balance_callback balance_push_callback = { + .func = balance_push, + }; + +-static inline struct balance_callback * ++static __always_inline struct balance_callback * + __splice_balance_callbacks(struct rq *rq, bool split) + { + struct balance_callback *head = rq->balance_callback; +@@ -5206,7 +5206,7 @@ struct balance_callback *splice_balance_callbacks(struct rq *rq) + return __splice_balance_callbacks(rq, true); + } + +-void __balance_callbacks(struct rq *rq, struct rq_flags *rf) ++__always_inline void __balance_callbacks(struct rq *rq, struct rq_flags *rf) + { + if (rf) + rq_unpin_lock(rq, rf); +@@ -5250,7 +5250,7 @@ prepare_lock_switch(struct rq *rq, struct task_struct *next, struct rq_flags *rf + __acquire(__rq_lockp(this_rq())); + } + +-static inline void finish_lock_switch(struct rq *rq) ++static __always_inline void finish_lock_switch(struct rq *rq) + __releases(__rq_lockp(rq)) + { + /* +@@ -5284,7 +5284,7 @@ static inline void kmap_local_sched_out(void) + #endif + } + +-static inline void kmap_local_sched_in(void) ++static __always_inline void kmap_local_sched_in(void) + { + #ifdef CONFIG_KMAP_LOCAL + if (unlikely(current->kmap_ctrl.idx)) +@@ -5338,7 +5338,7 @@ prepare_task_switch(struct rq *rq, struct task_struct *prev, + * past. 'prev == current' is still correct but we need to recalculate this_rq + * because prev may have moved to another CPU. + */ +-static struct rq *finish_task_switch(struct task_struct *prev) ++static __always_inline struct rq *finish_task_switch(struct task_struct *prev) + __releases(__rq_lockp(this_rq())) + { + struct rq *rq = this_rq(); +diff --git a/kernel/sched/cpufreq_schedutil.c b/kernel/sched/cpufreq_schedutil.c +index 14405a6..158f1c0 100644 +--- a/kernel/sched/cpufreq_schedutil.c ++++ b/kernel/sched/cpufreq_schedutil.c +@@ -249,6 +249,7 @@ unsigned long sugov_effective_cpu_perf(int cpu, unsigned long actual, + + static void sugov_get_util(struct sugov_cpu *sg_cpu, unsigned long boost) + { ++#ifndef CONFIG_SCHED_ALT + unsigned long min, max, util = scx_cpuperf_target(sg_cpu->cpu); + + if (!scx_switched_all()) +@@ -258,6 +259,10 @@ static void sugov_get_util(struct sugov_cpu *sg_cpu, unsigned long boost) + sg_cpu->bw_min = min; + sg_cpu->bw_max = max; + sg_cpu->util = sugov_effective_cpu_perf(sg_cpu->cpu, util, min, max); ++#else /* CONFIG_SCHED_ALT */ ++ sg_cpu->bw_min = 0; ++ sg_cpu->util = rq_load_util(cpu_rq(sg_cpu->cpu), arch_scale_cpu_capacity(sg_cpu->cpu)); ++#endif /* CONFIG_SCHED_ALT */ + } + + /** +@@ -385,6 +390,7 @@ static bool sugov_hold_freq(struct sugov_cpu *sg_cpu) + unsigned long idle_calls; + bool ret; + ++#ifndef CONFIG_SCHED_ALT + /* + * The heuristics in this function is for the fair class. For SCX, the + * performance target comes directly from the BPF scheduler. Let's just +@@ -392,6 +398,7 @@ static bool sugov_hold_freq(struct sugov_cpu *sg_cpu) + */ + if (scx_switched_all()) + return false; ++#endif /* !CONFIG_SCHED_ALT */ + + /* if capped by uclamp_max, always update to be in compliance */ + if (uclamp_rq_is_capped(cpu_rq(sg_cpu->cpu))) +@@ -417,8 +424,10 @@ static inline bool sugov_hold_freq(struct sugov_cpu *sg_cpu) { return false; } + */ + static inline void ignore_dl_rate_limit(struct sugov_cpu *sg_cpu) + { ++#ifndef CONFIG_SCHED_ALT + if (cpu_bw_dl(cpu_rq(sg_cpu->cpu)) > sg_cpu->bw_min) +- sg_cpu->sg_policy->need_freq_update = true; ++ sg_cpu->sg_policy->limits_changed = true; ++#endif + } + + static inline bool sugov_update_single_common(struct sugov_cpu *sg_cpu, +@@ -714,6 +723,7 @@ static int sugov_kthread_create(struct sugov_policy *sg_policy) + } + + ret = sched_setattr_nocheck(thread, &attr); ++ + if (ret) { + kthread_stop(thread); + pr_warn("%s: failed to set SCHED_DEADLINE\n", __func__); +diff --git a/kernel/sched/cputime.c b/kernel/sched/cputime.c +index 06bddaa..0bc9d14 100644 +--- a/kernel/sched/cputime.c ++++ b/kernel/sched/cputime.c +@@ -130,7 +130,7 @@ void account_user_time(struct task_struct *p, u64 cputime) + p->utime += cputime; + account_group_user_time(p, cputime); + +- index = (task_nice(p) > 0) ? CPUTIME_NICE : CPUTIME_USER; ++ index = task_running_nice(p) ? CPUTIME_NICE : CPUTIME_USER; + + /* Add user time to cpustat. */ + task_group_account_field(p, index, cputime); +@@ -154,7 +154,7 @@ void account_guest_time(struct task_struct *p, u64 cputime) + p->gtime += cputime; + + /* Add guest time to cpustat. */ +- if (task_nice(p) > 0) { ++ if (task_running_nice(p)) { + task_group_account_field(p, CPUTIME_NICE, cputime); + cpustat[CPUTIME_GUEST_NICE] += cputime; + } else { +@@ -305,7 +305,7 @@ static inline u64 account_other_time(u64 max) + #ifdef CONFIG_64BIT + static inline u64 read_sum_exec_runtime(struct task_struct *t) + { +- return t->se.sum_exec_runtime; ++ return tsk_seruntime(t); + } + #else /* !CONFIG_64BIT: */ + static u64 read_sum_exec_runtime(struct task_struct *t) +@@ -315,7 +315,7 @@ static u64 read_sum_exec_runtime(struct task_struct *t) + struct rq *rq; + + rq = task_rq_lock(t, &rf); +- ns = t->se.sum_exec_runtime; ++ ns = tsk_seruntime(t); + task_rq_unlock(rq, t, &rf); + + return ns; +@@ -811,7 +811,7 @@ void cputime_adjust(struct task_cputime *curr, struct prev_cputime *prev, + void task_cputime_adjusted(struct task_struct *p, u64 *ut, u64 *st) + { + struct task_cputime cputime = { +- .sum_exec_runtime = p->se.sum_exec_runtime, ++ .sum_exec_runtime = tsk_seruntime(p), + }; + + if (task_cputime(p, &cputime.utime, &cputime.stime)) +diff --git a/kernel/sched/debug.c b/kernel/sched/debug.c +index 72236db..70b7c34 100644 +--- a/kernel/sched/debug.c ++++ b/kernel/sched/debug.c +@@ -11,6 +11,7 @@ + #include + #include "sched.h" + ++#ifndef CONFIG_SCHED_ALT + /* + * This allows printing both to /sys/kernel/debug/sched/debug and + * to the console +@@ -251,6 +252,7 @@ static const struct file_operations sched_cache_enable_fops = { + .release = single_release, + }; + #endif ++#endif /* !CONFIG_SCHED_ALT */ + + #ifdef CONFIG_PREEMPT_DYNAMIC + +@@ -318,6 +320,7 @@ static const struct file_operations sched_dynamic_fops = { + + #endif /* CONFIG_PREEMPT_DYNAMIC */ + ++#ifndef CONFIG_SCHED_ALT + __read_mostly bool sched_debug_verbose; + + static struct dentry *sd_dentry; +@@ -611,7 +614,11 @@ static const struct file_operations fair_server_period_fops = { + .llseek = seq_lseek, + .release = single_release, + }; ++#endif /* !CONFIG_SCHED_ALT */ + ++static struct dentry *debugfs_sched; ++ ++#ifndef CONFIG_SCHED_ALT + static void debugfs_fair_server_init(void) + { + struct dentry *d_fair; +@@ -632,6 +639,7 @@ static void debugfs_fair_server_init(void) + debugfs_create_file("period", 0644, d_cpu, (void *) cpu, &fair_server_period_fops); + } + } ++#endif /* !CONFIG_SCHED_ALT */ + + #ifdef CONFIG_FAIR_GROUP_SCHED + static int cgroup_mode = 2; +@@ -715,14 +723,17 @@ static __init int sched_init_debug(void) + + debugfs_sched = debugfs_create_dir("sched", NULL); + ++#ifndef CONFIG_SCHED_ALT + debugfs_create_file("features", 0644, debugfs_sched, NULL, &sched_feat_fops); + debugfs_create_file_unsafe("verbose", 0644, debugfs_sched, &sched_debug_verbose, &sched_verbose_fops); ++#endif /* !CONFIG_SCHED_ALT */ + #ifdef CONFIG_PREEMPT_DYNAMIC + debugfs_create_file("preempt", 0644, debugfs_sched, NULL, &sched_dynamic_fops); + #endif + + debugfs_create_u32("base_slice_ns", 0644, debugfs_sched, &sysctl_sched_base_slice); + ++#ifndef CONFIG_SCHED_ALT + debugfs_create_u32("latency_warn_ms", 0644, debugfs_sched, &sysctl_resched_latency_warn_ms); + debugfs_create_u32("latency_warn_once", 0644, debugfs_sched, &sysctl_resched_latency_warn_once); + +@@ -761,20 +772,25 @@ static __init int sched_init_debug(void) + #endif + + debugfs_create_file("debug", 0444, debugfs_sched, NULL, &sched_debug_fops); ++#endif /* !CONFIG_SCHED_ALT */ + + #ifdef CONFIG_FAIR_GROUP_SCHED + debugfs_create_file("cgroup_mode", 0644, debugfs_sched, NULL, &sched_cgroup_fops); + #endif + ++#ifndef CONFIG_SCHED_ALT + debugfs_fair_server_init(); + #ifdef CONFIG_SCHED_CLASS_EXT + debugfs_ext_server_init(); + #endif ++#endif /* !CONFIG_SCHED_ALT */ + + return 0; + } + late_initcall(sched_init_debug); + ++#ifndef CONFIG_SCHED_ALT ++ + static cpumask_var_t sd_sysctl_cpus; + + static int sd_flags_show(struct seq_file *m, void *v) +@@ -1520,6 +1536,11 @@ void proc_sched_show_task(struct task_struct *p, struct pid_namespace *ns, + + sched_show_numa(p, m); + } ++#else ++void proc_sched_show_task(struct task_struct *p, struct pid_namespace *ns, ++ struct seq_file *m) ++{ } ++#endif /* !CONFIG_SCHED_ALT */ + + void proc_sched_set_task(struct task_struct *p) + { +diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c +index 913630c..532c0de 100644 +--- a/kernel/sched/fair.c ++++ b/kernel/sched/fair.c +@@ -82,10 +82,19 @@ unsigned int sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG; + * + * (default: 0.70 msec * (1 + ilog(ncpus)), units: nanoseconds) + */ ++#ifdef CONFIG_ZEN_INTERACTIVE ++unsigned int sysctl_sched_base_slice = 400000ULL; ++static unsigned int normalized_sysctl_sched_base_slice = 400000ULL; ++#else + unsigned int sysctl_sched_base_slice = 700000ULL; + static unsigned int normalized_sysctl_sched_base_slice = 700000ULL; ++#endif + ++#ifdef CONFIG_ZEN_INTERACTIVE ++__read_mostly unsigned int sysctl_sched_migration_cost = 300000UL; ++#else + __read_mostly unsigned int sysctl_sched_migration_cost = 500000UL; ++#endif + + static int __init setup_sched_thermal_decay_shift(char *str) + { +@@ -128,8 +137,12 @@ int __weak arch_asym_cpu_priority(int cpu) + * + * (default: 5 msec, units: microseconds) + */ ++#ifdef CONFIG_ZEN_INTERACTIVE ++static unsigned int sysctl_sched_cfs_bandwidth_slice = 3000UL; ++#else + static unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL; + #endif ++#endif + + #ifdef CONFIG_NUMA_BALANCING + /* Restrict the NUMA promotion throughput (MB/s) for each target node. */ +diff --git a/kernel/sched/idle.c b/kernel/sched/idle.c +index eb73b65..c6a01e7 100644 +--- a/kernel/sched/idle.c ++++ b/kernel/sched/idle.c +@@ -454,6 +454,7 @@ void cpu_startup_entry(enum cpuhp_state state) + do_idle(); + } + ++#ifndef CONFIG_SCHED_ALT + /* + * idle-task scheduling class. + */ +@@ -597,3 +598,4 @@ DEFINE_SCHED_CLASS(idle) = { + .switching_to = switching_to_idle, + .update_curr = update_curr_idle, + }; ++#endif +diff --git a/kernel/sched/pds.h b/kernel/sched/pds.h +new file mode 100644 +index 0000000..1bcfcd2 +--- /dev/null ++++ b/kernel/sched/pds.h +@@ -0,0 +1,230 @@ ++#ifndef _KERNEL_SCHED_PDS_H ++#define _KERNEL_SCHED_PDS_H ++ ++#define ALT_SCHED_NAME "PDS" ++ ++static const u64 RT_MASK = ((1ULL << MIN_SCHED_NORMAL_PRIO) - 1); ++ ++#define SCHED_NORMAL_PRIO_NUM (32) ++#define SCHED_EDGE_DELTA (SCHED_NORMAL_PRIO_NUM - NICE_WIDTH / 2) ++ ++/* PDS assume SCHED_NORMAL_PRIO_NUM is power of 2 */ ++#define SCHED_NORMAL_PRIO_MOD(x) ((x) & (SCHED_NORMAL_PRIO_NUM - 1)) ++ ++/* default time slice 4ms -> shift 22, 2 time slice slots -> shift 23 */ ++static const int sched_timeslice_shift = 23; ++static const int sched_boost_shift = 21; ++DECLARE_STATIC_KEY_MAYBE(CONFIG_SCHED_PDS_SLEEP_CREDIT, sched_pds_sleep_credit); ++ ++#define SCHED_NICE_DELTA(p) (((p)->static_prio - (MAX_PRIO - NICE_WIDTH)) / 2) ++ ++/* ++ * Common interfaces ++ */ ++static inline int ++task_sched_prio_normal(const struct task_struct *p, const struct rq *rq) ++{ ++ u64 sched_dl = max(p->deadline, rq->time_edge); ++ ++#ifdef ALT_SCHED_DEBUG ++ if (WARN_ONCE(sched_dl - rq->time_edge > SCHED_NORMAL_PRIO_NUM - 1, ++ "pds: task_sched_prio_normal() delta %lld\n", sched_dl - rq->time_edge)) ++ return SCHED_NORMAL_PRIO_NUM - 1; ++#endif ++ ++ return sched_dl - rq->time_edge; ++} ++ ++static inline int task_sched_prio(const struct task_struct *p) ++{ ++ return (p->prio < MIN_NORMAL_PRIO) ? (p->prio >> 2) : ++ MIN_SCHED_NORMAL_PRIO + task_sched_prio_normal(p, task_rq(p)); ++} ++ ++#define TASK_SCHED_PRIO_IDX(p, rq, idx, prio) \ ++ if (p->prio < MIN_NORMAL_PRIO) { \ ++ prio = p->prio >> 2; \ ++ idx = prio; \ ++ } else { \ ++ u64 sched_dl = max(p->deadline, rq->time_edge); \ ++ prio = MIN_SCHED_NORMAL_PRIO + sched_dl - rq->time_edge; \ ++ idx = MIN_SCHED_NORMAL_PRIO + SCHED_NORMAL_PRIO_MOD(sched_dl); \ ++ } ++ ++static_assert(MIN_SCHED_NORMAL_PRIO + SCHED_NORMAL_PRIO_NUM == IDLE_TASK_SCHED_PRIO); ++ ++static inline int sched_prio2idx(int sched_prio, struct rq *rq) ++{ ++ return ((unsigned int)(sched_prio - MIN_SCHED_NORMAL_PRIO) < SCHED_NORMAL_PRIO_NUM) ? ++ MIN_SCHED_NORMAL_PRIO + SCHED_NORMAL_PRIO_MOD(sched_prio + rq->time_edge) : ++ sched_prio; ++} ++ ++static inline int sched_idx2prio(int sched_idx, struct rq *rq) ++{ ++ return (sched_idx < MIN_SCHED_NORMAL_PRIO) ? ++ sched_idx : ++ MIN_SCHED_NORMAL_PRIO + SCHED_NORMAL_PRIO_MOD(sched_idx - rq->time_edge); ++} ++ ++static inline int sched_rq_prio_idx(struct rq *rq) ++{ ++ return rq->prio_idx; ++} ++ ++static inline void sched_rq_set_prio(struct rq *rq, int prio) ++{ ++ rq->prio = prio; ++ rq->prio_idx = sched_prio2idx(prio, rq); ++} ++ ++static inline int task_running_nice(struct task_struct *p) ++{ ++ return (p->prio > DEFAULT_PRIO); ++} ++ ++static noinline __maybe_unused void ++sched_rq_time_edge_advance(struct rq *rq, u64 old, u64 now) ++{ ++ struct list_head head; ++ u64 prio, delta; ++ DECLARE_BITMAP(normal, SCHED_QUEUE_BITS); ++ ++ rq->time_edge = now; ++ delta = min_t(u64, SCHED_NORMAL_PRIO_NUM, now - old); ++ INIT_LIST_HEAD(&head); ++ ++ prio = MIN_SCHED_NORMAL_PRIO; ++ for_each_set_bit_from(prio, rq->queue.bitmap, MIN_SCHED_NORMAL_PRIO + delta) ++ list_splice_tail_init(rq->queue.heads + MIN_SCHED_NORMAL_PRIO + ++ SCHED_NORMAL_PRIO_MOD(prio + old), &head); ++ ++ bitmap_shift_right(normal, rq->queue.bitmap, delta, SCHED_QUEUE_BITS); ++ if (!list_empty(&head)) { ++ u64 idx = MIN_SCHED_NORMAL_PRIO + SCHED_NORMAL_PRIO_MOD(now); ++ ++ __list_splice(&head, rq->queue.heads + idx, rq->queue.heads[idx].next); ++ __set_bit(MIN_SCHED_NORMAL_PRIO, normal); ++ } ++ bitmap_replace(rq->queue.bitmap, normal, rq->queue.bitmap, ++ (const unsigned long *)&RT_MASK, SCHED_QUEUE_BITS); ++ ++ if (rq->prio < MIN_SCHED_NORMAL_PRIO || IDLE_TASK_SCHED_PRIO == rq->prio) ++ return; ++ ++ sched_rq_set_prio(rq, max_t(u64, MIN_SCHED_NORMAL_PRIO, rq->prio - delta)); ++} ++ ++static inline void sched_update_rq_clock(struct rq *rq) ++{ ++ u64 old = rq->time_edge; ++ u64 now = rq->clock >> sched_timeslice_shift; ++ ++ if (likely(now == old)) ++ return; ++ ++ sched_rq_time_edge_advance(rq, old, now); ++} ++ ++static inline void sched_task_deadline_reset(struct task_struct *p, const struct rq *rq) ++{ ++ p->sleep_credit = 0; ++ if (p->prio >= MIN_NORMAL_PRIO) ++ p->deadline = rq->time_edge + SCHED_EDGE_DELTA + SCHED_NICE_DELTA(p); ++} ++ ++static inline bool sched_task_used_slice(const struct task_struct *p) ++{ ++ return p->sched_time - p->wake_sched_time >= ++ 2 * (sysctl_sched_base_slice - RESCHED_NS); ++} ++ ++static inline void sched_task_renew(struct task_struct *p, const struct rq *rq) ++{ ++ if (p->prio >= MIN_NORMAL_PRIO) { ++ u64 cap = (normal_policy(p->policy) && !sched_task_used_slice(p)) ? ++ max(SCHED_NICE_DELTA(p) - (NICE_WIDTH / 8 + 1), 0) : 0; ++ ++ if (p->sleep_credit > cap) ++ p->sleep_credit = cap; ++ p->deadline = rq->time_edge + SCHED_EDGE_DELTA + SCHED_NICE_DELTA(p) - ++ p->sleep_credit; ++ } ++} ++ ++static inline void sched_task_sanity_check(struct task_struct *p, struct rq *rq) ++{ ++ u64 max_dl = rq->time_edge + SCHED_EDGE_DELTA + NICE_WIDTH / 2 - 1; ++ if (unlikely(p->deadline > max_dl)) ++ p->deadline = max_dl; ++} ++ ++static inline void sched_task_fork(struct task_struct *p, struct rq *rq) ++{ ++ p->wake_sched_time = 0; ++ p->wake_period = 64 * NSEC_PER_MSEC; ++ p->credit_wake = 0; ++ sched_task_deadline_reset(p, rq); ++} ++ ++static inline void do_sched_yield_type_1(struct task_struct *p, struct rq *rq) ++{ ++ p->time_slice = sysctl_sched_base_slice; ++ sched_task_deadline_reset(p, rq); ++} ++ ++static inline void sched_task_ttwu(struct task_struct *p) ++{ ++ if (!static_branch_maybe(CONFIG_SCHED_PDS_SLEEP_CREDIT, &sched_pds_sleep_credit)) ++ return; ++ ++ u64 now = local_clock(); ++ s64 delta = now - p->sleep_start; ++ s64 credit; ++ u64 boost; ++ bool used_slice = sched_task_used_slice(p); ++ ++ p->wake_sched_time = p->sched_time; ++ if (used_slice) { ++ p->deadline += p->sleep_credit; ++ p->sleep_credit = 0; ++ } ++ ++ if (p->prio < MIN_NORMAL_PRIO || !normal_policy(p->policy) || ++ delta < (1LL << (sched_boost_shift - 2))) ++ return; ++ ++ if (p->credit_wake) { ++ p->wake_period += (s64)(now - p->credit_wake - p->wake_period) >> 3; ++ if (p->sched_time - p->credit_sched_time > (u64)delta) ++ used_slice = true; ++ } ++ p->credit_wake = now; ++ p->credit_sched_time = p->sched_time; ++ ++ boost = min_t(u64, NICE_WIDTH / 4, ++ max_t(u64, 1, (u64)delta >> sched_boost_shift)); ++ if (p->wake_period <= (1ULL << sched_boost_shift)) ++ boost = max_t(u64, boost, 4); ++ else if (p->wake_period <= (1ULL << (sched_boost_shift + 4))) ++ boost = max_t(u64, boost, 3); ++ credit = SCHED_NICE_DELTA(p) - max_t(s64, NICE_WIDTH / 8 + 1, ++ SCHED_NICE_DELTA(p) - (s64)boost); ++ credit = used_slice ? 0 : max_t(s64, credit, 0); ++ ++ p->deadline = min(p->deadline, (now >> sched_timeslice_shift) + SCHED_EDGE_DELTA + ++ SCHED_NICE_DELTA(p) - credit); ++ p->sleep_credit = credit; ++} ++ ++static inline bool sched_task_has_credit(const struct task_struct *p) ++{ ++ return p->sleep_credit; ++} ++ ++static inline void sched_task_deactivate(struct task_struct *p, struct rq *rq) ++{ ++ p->sleep_start = rq->clock; ++} ++ ++#endif /* _KERNEL_SCHED_PDS_H */ +diff --git a/kernel/sched/pelt.c b/kernel/sched/pelt.c +index 779eb58..4657534 100644 +--- a/kernel/sched/pelt.c ++++ b/kernel/sched/pelt.c +@@ -267,6 +267,7 @@ ___update_load_avg(struct sched_avg *sa, unsigned long load) + WRITE_ONCE(sa->util_avg, sa->util_sum / divider); + } + ++#ifndef CONFIG_SCHED_ALT + /* + * sched_entity: + * +@@ -384,8 +385,9 @@ int update_dl_rq_load_avg(u64 now, struct rq *rq, int running) + + return 0; + } ++#endif + +-#ifdef CONFIG_SCHED_HW_PRESSURE ++#if defined(CONFIG_SCHED_HW_PRESSURE) && !defined(CONFIG_SCHED_ALT) + /* + * hardware: + * +@@ -469,6 +471,7 @@ int update_irq_load_avg(struct rq *rq, u64 running) + } + #endif /* CONFIG_HAVE_SCHED_AVG_IRQ */ + ++#ifndef CONFIG_SCHED_ALT + /* + * Load avg and utiliztion metrics need to be updated periodically and before + * consumption. This function updates the metrics for all subsystems except for +@@ -488,3 +491,4 @@ bool update_other_load_avgs(struct rq *rq) + update_hw_load_avg(rq_clock_task(rq), rq, hw_pressure) | + update_irq_load_avg(rq, 0); + } ++#endif /* !CONFIG_SCHED_ALT */ +diff --git a/kernel/sched/pelt.h b/kernel/sched/pelt.h +index f921302..2fade7d 100644 +--- a/kernel/sched/pelt.h ++++ b/kernel/sched/pelt.h +@@ -5,14 +5,16 @@ + + #include "sched-pelt.h" + ++#ifndef CONFIG_SCHED_ALT + int __update_load_avg_blocked_se(u64 now, struct sched_entity *se); + int __update_load_avg_se(u64 now, struct cfs_rq *cfs_rq, struct sched_entity *se); + int __update_load_avg_cfs_rq(u64 now, struct cfs_rq *cfs_rq); + int update_rt_rq_load_avg(u64 now, struct rq *rq, int running); + int update_dl_rq_load_avg(u64 now, struct rq *rq, int running); + bool update_other_load_avgs(struct rq *rq); ++#endif + +-#ifdef CONFIG_SCHED_HW_PRESSURE ++#if defined(CONFIG_SCHED_HW_PRESSURE) && !defined(CONFIG_SCHED_ALT) + int update_hw_load_avg(u64 now, struct rq *rq, u64 capacity); + + static inline u64 hw_load_avg(struct rq *rq) +@@ -49,6 +51,7 @@ static inline u32 get_pelt_divider(struct sched_avg *avg) + return PELT_MIN_DIVIDER + avg->period_contrib; + } + ++#ifndef CONFIG_SCHED_ALT + static inline void cfs_se_util_change(struct sched_avg *avg) + { + unsigned int enqueued; +@@ -185,5 +188,6 @@ static inline u64 cfs_rq_clock_pelt(struct cfs_rq *cfs_rq) + return rq_clock_pelt(rq_of(cfs_rq)); + } + #endif /* !CONFIG_CFS_BANDWIDTH */ ++#endif /* CONFIG_SCHED_ALT */ + + #endif /* _KERNEL_SCHED_PELT_H */ +diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h +index 4c25fbe..11f5b47 100644 +--- a/kernel/sched/sched.h ++++ b/kernel/sched/sched.h +@@ -5,6 +5,10 @@ + #ifndef _KERNEL_SCHED_SCHED_H + #define _KERNEL_SCHED_SCHED_H + ++#ifdef CONFIG_SCHED_ALT ++#include "alt_sched.h" ++#else ++ + #include + #include + #include +@@ -1481,12 +1485,12 @@ static inline struct cpumask *sched_group_span(struct sched_group *sg); + + DECLARE_STATIC_KEY_FALSE(__sched_core_enabled); + +-static inline bool sched_core_enabled(struct rq *rq) ++static __always_inline bool sched_core_enabled(struct rq *rq) + { + return static_branch_unlikely(&__sched_core_enabled) && rq->core_enabled; + } + +-static inline bool sched_core_disabled(void) ++static __always_inline bool sched_core_disabled(void) + { + return !static_branch_unlikely(&__sched_core_enabled); + } +@@ -1495,7 +1499,7 @@ static inline bool sched_core_disabled(void) + * Be careful with this function; not for general use. The return value isn't + * stable unless you actually hold a relevant rq->__lock. + */ +-static inline raw_spinlock_t *rq_lockp(struct rq *rq) ++static __always_inline raw_spinlock_t *rq_lockp(struct rq *rq) + { + if (sched_core_enabled(rq)) + return &rq->core->__lock; +@@ -1503,7 +1507,7 @@ static inline raw_spinlock_t *rq_lockp(struct rq *rq) + return &rq->__lock; + } + +-static inline raw_spinlock_t *__rq_lockp(struct rq *rq) ++static __always_inline raw_spinlock_t *__rq_lockp(struct rq *rq) + __returns_ctx_lock(rq_lockp(rq)) /* alias them */ + { + if (rq->core_enabled) +@@ -1606,12 +1610,12 @@ static inline bool sched_core_disabled(void) + return true; + } + +-static inline raw_spinlock_t *rq_lockp(struct rq *rq) ++static __always_inline raw_spinlock_t *rq_lockp(struct rq *rq) + { + return &rq->__lock; + } + +-static inline raw_spinlock_t *__rq_lockp(struct rq *rq) ++static __always_inline raw_spinlock_t *__rq_lockp(struct rq *rq) + __returns_ctx_lock(rq_lockp(rq)) /* alias them */ + { + return &rq->__lock; +@@ -1671,26 +1675,26 @@ extern void raw_spin_rq_lock_nested(struct rq *rq, int subclass) + extern bool raw_spin_rq_trylock(struct rq *rq) + __cond_acquires(true, __rq_lockp(rq)); + +-static inline void raw_spin_rq_lock(struct rq *rq) ++static __always_inline void raw_spin_rq_lock(struct rq *rq) + __acquires(__rq_lockp(rq)) + { + raw_spin_rq_lock_nested(rq, 0); + } + +-static inline void raw_spin_rq_unlock(struct rq *rq) ++static __always_inline void raw_spin_rq_unlock(struct rq *rq) + __releases(__rq_lockp(rq)) + { + raw_spin_unlock(rq_lockp(rq)); + } + +-static inline void raw_spin_rq_lock_irq(struct rq *rq) ++static __always_inline void raw_spin_rq_lock_irq(struct rq *rq) + __acquires(__rq_lockp(rq)) + { + local_irq_disable(); + raw_spin_rq_lock(rq); + } + +-static inline void raw_spin_rq_unlock_irq(struct rq *rq) ++static __always_inline void raw_spin_rq_unlock_irq(struct rq *rq) + __releases(__rq_lockp(rq)) + { + raw_spin_rq_unlock(rq); +@@ -3138,7 +3142,7 @@ static inline void attach_one_task(struct rq *rq, struct task_struct *p) + attach_task(rq, p); + } + +-#ifdef CONFIG_PREEMPT_RT ++#if defined(CONFIG_PREEMPT_RT) || defined(CONFIG_ZEN_INTERACTIVE) + # define SCHED_NR_MIGRATE_BREAK 8 + #else + # define SCHED_NR_MIGRATE_BREAK 32 +@@ -4252,4 +4256,9 @@ DEFINE_CLASS_IS_UNCONDITIONAL(sched_change) + + #include "ext/ext.h" + ++static inline int task_running_nice(struct task_struct *p) ++{ ++ return (task_nice(p) > 0); ++} ++#endif /* !CONFIG_SCHED_ALT */ + #endif /* _KERNEL_SCHED_SCHED_H */ +diff --git a/kernel/sched/stats.c b/kernel/sched/stats.c +index d1c9429..cc37640 100644 +--- a/kernel/sched/stats.c ++++ b/kernel/sched/stats.c +@@ -115,8 +115,10 @@ static int show_schedstat(struct seq_file *seq, void *v) + seq_printf(seq, "timestamp %lu\n", jiffies); + } else { + struct rq *rq; ++#ifndef CONFIG_SCHED_ALT + struct sched_domain *sd; + int dcount = 0; ++#endif + cpu = (unsigned long)(v - 2); + rq = cpu_rq(cpu); + +@@ -131,6 +133,7 @@ static int show_schedstat(struct seq_file *seq, void *v) + + seq_printf(seq, "\n"); + ++#ifndef CONFIG_SCHED_ALT + /* domain-specific stats */ + rcu_read_lock(); + for_each_domain(cpu, sd) { +@@ -161,6 +164,7 @@ static int show_schedstat(struct seq_file *seq, void *v) + sd->ttwu_move_balance); + } + rcu_read_unlock(); ++#endif + } + return 0; + } +diff --git a/kernel/sched/stats.h b/kernel/sched/stats.h +index ebe0a77..7533602 100644 +--- a/kernel/sched/stats.h ++++ b/kernel/sched/stats.h +@@ -89,6 +89,7 @@ static inline void rq_sched_info_depart (struct rq *rq, unsigned long long delt + + #endif /* CONFIG_SCHEDSTATS */ + ++#ifndef CONFIG_SCHED_ALT + static inline struct sched_statistics * + __schedstats_from_se(struct sched_entity *se) + { +@@ -98,6 +99,7 @@ __schedstats_from_se(struct sched_entity *se) + #endif + return &task_of(se)->stats; + } ++#endif /* CONFIG_SCHED_ALT */ + + #ifdef CONFIG_PSI + void psi_task_change(struct task_struct *task, int clear, int set); +@@ -135,6 +137,7 @@ static inline void psi_enqueue(struct task_struct *p, int flags) + if (task_on_cpu(task_rq(p), p)) + return; + ++#ifndef CONFIG_SCHED_ALT + if (p->se.sched_delayed) { + /* CPU migration of "sleeping" task */ + WARN_ON_ONCE(!(flags & ENQUEUE_MIGRATED)); +@@ -142,7 +145,9 @@ static inline void psi_enqueue(struct task_struct *p, int flags) + set |= TSK_MEMSTALL; + if (p->in_iowait) + set |= TSK_IOWAIT; +- } else if (flags & ENQUEUE_MIGRATED) { ++ } else ++#endif ++ if (flags & ENQUEUE_MIGRATED) { + /* CPU migration of runnable task */ + set = TSK_RUNNING; + if (p->in_memstall) +diff --git a/kernel/sched/syscalls.c b/kernel/sched/syscalls.c +index b215b0e..6ce19b8 100644 +--- a/kernel/sched/syscalls.c ++++ b/kernel/sched/syscalls.c +@@ -16,6 +16,14 @@ + #include "sched.h" + #include "autogroup.h" + ++#ifdef CONFIG_SCHED_ALT ++#include "alt_core.h" ++ ++static inline int __normal_prio(int policy, int rt_prio, int static_prio) ++{ ++ return rt_policy(policy) ? (MAX_RT_PRIO - 1 - rt_prio) : static_prio; ++} ++#else /* !CONFIG_SCHED_ALT */ + static inline int __normal_prio(int policy, int rt_prio, int nice) + { + int prio; +@@ -29,6 +37,7 @@ static inline int __normal_prio(int policy, int rt_prio, int nice) + + return prio; + } ++#endif /* !CONFIG_SCHED_ALT */ + + /* + * Calculate the expected normal priority: i.e. priority +@@ -39,7 +48,11 @@ static inline int __normal_prio(int policy, int rt_prio, int nice) + */ + static inline int normal_prio(struct task_struct *p) + { ++#ifdef CONFIG_SCHED_ALT ++ return __normal_prio(p->policy, p->rt_priority, p->static_prio); ++#else /* !CONFIG_SCHED_ALT */ + return __normal_prio(p->policy, p->rt_priority, PRIO_TO_NICE(p->static_prio)); ++#endif /* !CONFIG_SCHED_ALT */ + } + + /* +@@ -64,7 +77,9 @@ static int effective_prio(struct task_struct *p) + + void set_user_nice(struct task_struct *p, long nice) + { ++#ifndef CONFIG_SCHED_ALT + int old_prio; ++#endif + + if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE) + return; +@@ -87,8 +102,10 @@ void set_user_nice(struct task_struct *p, long nice) + + scoped_guard (sched_change, p, DEQUEUE_SAVE) { + p->static_prio = NICE_TO_PRIO(nice); ++#ifndef CONFIG_SCHED_ALT + set_load_weight(p, true); + old_prio = p->prio; ++#endif + p->prio = effective_prio(p); + } + } +@@ -169,7 +186,19 @@ SYSCALL_DEFINE1(nice, int, increment) + */ + int task_prio(const struct task_struct *p) + { ++#ifdef CONFIG_SCHED_ALT ++/* ++ * sched policy return value kernel prio user prio/nice ++ * ++ * (BMQ)normal, batch, idle[0 ... 53] [100 ... 139] 0/[-20 ... 19]/[-7 ... 7] ++ * (PDS)normal, batch, idle[0 ... 39] 100 0/[-20 ... 19] ++ * fifo, rr [-1 ... -100] [99 ... 0] [0 ... 99] ++ */ ++ return (p->prio < MAX_RT_PRIO) ? p->prio - MAX_RT_PRIO : ++ task_sched_prio_normal(p, task_rq(p)); ++#else + return p->prio - MAX_RT_PRIO; ++#endif /* !CONFIG_SCHED_ALT */ + } + + /** +@@ -248,11 +277,16 @@ static void __setscheduler_params(struct task_struct *p, + + p->policy = policy; + ++#ifndef CONFIG_SCHED_ALT + if (dl_policy(policy)) + __setparam_dl(p, attr); + else if (fair_policy(policy)) + __setparam_fair(p, attr); ++#else /* !CONFIG_SCHED_ALT */ ++ p->static_prio = NICE_TO_PRIO(attr->sched_nice); ++#endif /* CONFIG_SCHED_ALT */ + ++#ifndef CONFIG_SCHED_ALT + /* rt-policy tasks do not have a timerslack */ + if (rt_or_dl_task_policy(p)) { + p->timer_slack_ns = 0; +@@ -260,6 +294,7 @@ static void __setscheduler_params(struct task_struct *p, + /* when switching back to non-rt policy, restore timerslack */ + p->timer_slack_ns = p->default_timer_slack_ns; + } ++#endif /* !CONFIG_SCHED_ALT */ + + /* + * __sched_setscheduler() ensures attr->sched_priority == 0 when +@@ -268,7 +303,9 @@ static void __setscheduler_params(struct task_struct *p, + */ + p->rt_priority = attr->sched_priority; + p->normal_prio = normal_prio(p); ++#ifndef CONFIG_SCHED_ALT + set_load_weight(p, true); ++#endif /* !CONFIG_SCHED_ALT */ + } + + /* +@@ -284,7 +321,7 @@ static bool check_same_owner(struct task_struct *p) + uid_eq(cred->euid, pcred->uid)); + } + +-#ifdef CONFIG_RT_MUTEXES ++#if defined(CONFIG_RT_MUTEXES) && !defined(CONFIG_SCHED_ALT) + static inline void __setscheduler_dl_pi(int newprio, int policy, + struct task_struct *p, + struct sched_change_ctx *scope) +@@ -313,6 +350,7 @@ static inline void __setscheduler_dl_pi(int newprio, int policy, + } + #endif /* !CONFIG_RT_MUTEXES */ + ++#ifndef CONFIG_SCHED_ALT + #ifdef CONFIG_UCLAMP_TASK + + static int uclamp_validate(struct task_struct *p, +@@ -426,6 +464,7 @@ static inline int uclamp_validate(struct task_struct *p, + static void __setscheduler_uclamp(struct task_struct *p, + const struct sched_attr *attr) { } + #endif /* !CONFIG_UCLAMP_TASK */ ++#endif /* !CONFIG_SCHED_ALT */ + + /* + * Allow unprivileged RT tasks to decrease priority. +@@ -436,11 +475,13 @@ static int user_check_sched_setscheduler(struct task_struct *p, + const struct sched_attr *attr, + int policy, int reset_on_fork) + { ++#ifndef CONFIG_SCHED_ALT + if (fair_policy(policy)) { + if (attr->sched_nice < task_nice(p) && + !is_nice_reduction(p, attr->sched_nice)) + goto req_priv; + } ++#endif /* !CONFIG_SCHED_ALT */ + + if (rt_policy(policy)) { + unsigned long rlim_rtprio = task_rlimit(p, RLIMIT_RTPRIO); +@@ -455,6 +496,7 @@ static int user_check_sched_setscheduler(struct task_struct *p, + goto req_priv; + } + ++#ifndef CONFIG_SCHED_ALT + /* + * Can't set/change SCHED_DEADLINE policy at all for now + * (safest behavior); in the future we would like to allow +@@ -472,6 +514,7 @@ static int user_check_sched_setscheduler(struct task_struct *p, + if (!is_nice_reduction(p, task_nice(p))) + goto req_priv; + } ++#endif /* !CONFIG_SCHED_ALT */ + + /* Can't change other user's priorities: */ + if (!check_same_owner(p)) +@@ -491,12 +534,22 @@ static int user_check_sched_setscheduler(struct task_struct *p, + } + + int __sched_setscheduler(struct task_struct *p, +- const struct sched_attr *attr, +- bool user, bool pi) ++ const struct sched_attr *attr, ++ bool user, bool pi) + { ++#ifdef CONFIG_SCHED_ALT ++ const struct sched_attr dl_squash_attr = { ++ .size = sizeof(struct sched_attr), ++ .sched_policy = SCHED_FIFO, ++ .sched_nice = 0, ++ .sched_priority = 99, ++ }; ++#endif /* CONFIG_SCHED_ALT */ + int oldpolicy = -1, policy = attr->sched_policy; + int retval, oldprio, newprio; ++#ifndef CONFIG_SCHED_ALT + const struct sched_class *prev_class, *next_class; ++#endif /* !CONFIG_SCHED_ALT */ + struct balance_callback *head; + struct rq_flags rf; + int reset_on_fork; +@@ -506,6 +559,15 @@ int __sched_setscheduler(struct task_struct *p, + + /* The pi code expects interrupts enabled */ + BUG_ON(pi && in_interrupt()); ++#ifdef CONFIG_SCHED_ALT ++ /* ++ * Alt schedule FW supports SCHED_DEADLINE by squash it as prio 0 SCHED_FIFO ++ */ ++ if (unlikely(SCHED_DEADLINE == policy)) { ++ attr = &dl_squash_attr; ++ policy = attr->sched_policy; ++ } ++#endif /* CONFIG_SCHED_ALT */ + recheck: + /* Double check policy once rq lock held: */ + if (policy < 0) { +@@ -528,8 +590,12 @@ int __sched_setscheduler(struct task_struct *p, + */ + if (attr->sched_priority > MAX_RT_PRIO-1) + return -EINVAL; ++#ifdef CONFIG_SCHED_ALT ++ if ((rt_policy(policy) != (attr->sched_priority != 0))) ++#else + if ((dl_policy(policy) && !__checkparam_dl(attr)) || + (rt_policy(policy) != (attr->sched_priority != 0))) ++#endif /* !CONFIG_SCHED_ALT */ + return -EINVAL; + + if (user) { +@@ -545,6 +611,7 @@ int __sched_setscheduler(struct task_struct *p, + return retval; + } + ++#ifndef CONFIG_SCHED_ALT + /* Update task specific "requested" clamps */ + if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP) { + retval = uclamp_validate(p, attr); +@@ -560,6 +627,7 @@ int __sched_setscheduler(struct task_struct *p, + cpuset_locked = true; + cpuset_lock(); + } ++#endif /* !CONFIG_SCHED_ALT */ + + /* + * Make sure no PI-waiters arrive (or leave) while we are +@@ -579,23 +647,31 @@ int __sched_setscheduler(struct task_struct *p, + goto unlock; + } + ++#ifndef CONFIG_SCHED_ALT + retval = scx_check_setscheduler(p, policy); + if (retval) + goto unlock; ++#endif /* !CONFIG_SCHED_ALT */ + + /* + * If not changing anything there's no need to proceed further, + * but store a possible modification of reset_on_fork. + */ + if (unlikely(policy == p->policy)) { ++#ifdef CONFIG_SCHED_ALT ++ if (!rt_policy(policy) && NICE_TO_PRIO(attr->sched_nice) != p->static_prio) ++#else + if (fair_policy(policy) && + (attr->sched_nice != task_nice(p) || + (attr->sched_runtime != p->se.slice))) ++#endif /* !CONFIG_SCHED_ALT */ + goto change; + if (rt_policy(policy) && attr->sched_priority != p->rt_priority) + goto change; ++#ifndef CONFIG_SCHED_ALT + if (dl_policy(policy) && dl_param_changed(p, attr)) + goto change; ++#endif /* !CONFIG_SCHED_ALT */ + if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP) + goto change; + +@@ -605,6 +681,7 @@ int __sched_setscheduler(struct task_struct *p, + } + change: + ++#ifndef CONFIG_SCHED_ALT + if (user) { + #ifdef CONFIG_RT_GROUP_SCHED + /* +@@ -635,6 +712,7 @@ int __sched_setscheduler(struct task_struct *p, + } + } + } ++#endif /* !CONFIG_SCHED_ALT */ + + /* Re-check policy now with rq lock held: */ + if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) { +@@ -645,6 +723,7 @@ int __sched_setscheduler(struct task_struct *p, + goto recheck; + } + ++#ifndef CONFIG_SCHED_ALT + /* + * If setscheduling to SCHED_DEADLINE (or changing the parameters + * of a SCHED_DEADLINE task) we need to check if enough bandwidth +@@ -654,11 +733,16 @@ int __sched_setscheduler(struct task_struct *p, + retval = -EBUSY; + goto unlock; + } ++#endif /* !CONFIG_SCHED_ALT */ + + p->sched_reset_on_fork = reset_on_fork; + oldprio = p->prio; + ++#ifdef CONFIG_SCHED_ALT ++ newprio = __normal_prio(policy, attr->sched_priority, NICE_TO_PRIO(attr->sched_nice)); ++#else + newprio = __normal_prio(policy, attr->sched_priority, attr->sched_nice); ++#endif /* !CONFIG_SCHED_ALT */ + if (pi) { + /* + * Take priority boosted tasks into account. If the new +@@ -672,21 +756,27 @@ int __sched_setscheduler(struct task_struct *p, + queue_flags &= ~DEQUEUE_MOVE; + } + ++#ifndef CONFIG_SCHED_ALT + prev_class = p->sched_class; + next_class = __setscheduler_class(policy, newprio); + + if (prev_class != next_class) + queue_flags |= DEQUEUE_CLASS; ++#endif /* !CONFIG_SCHED_ALT */ + + scoped_guard (sched_change, p, queue_flags) { + + if (!(attr->sched_flags & SCHED_FLAG_KEEP_PARAMS)) { + __setscheduler_params(p, attr); ++#ifndef CONFIG_SCHED_ALT + p->sched_class = next_class; ++#endif /* !CONFIG_SCHED_ALT */ + p->prio = newprio; + __setscheduler_dl_pi(newprio, policy, p, scope); + } ++#ifndef CONFIG_SCHED_ALT + __setscheduler_uclamp(p, attr); ++#endif /* !CONFIG_SCHED_ALT */ + + if (scope->queued) { + /* +@@ -731,8 +821,10 @@ static int _sched_setscheduler(struct task_struct *p, int policy, + .sched_nice = PRIO_TO_NICE(p->static_prio), + }; + ++#ifndef CONFIG_SCHED_ALT + if (p->se.custom_slice) + attr.sched_runtime = p->se.slice; ++#endif /* !CONFIG_SCHED_ALT */ + + /* Fixup the legacy SCHED_RESET_ON_FORK hack. */ + if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) { +@@ -913,13 +1005,18 @@ static int sched_copy_attr(struct sched_attr __user *uattr, struct sched_attr *a + + static void get_params(struct task_struct *p, struct sched_attr *attr, unsigned int flags) + { ++#ifndef CONFIG_SCHED_ALT + if (task_has_dl_policy(p)) { + __getparam_dl(p, attr, flags); +- } else if (task_has_rt_policy(p)) { ++ } else ++#endif ++ if (task_has_rt_policy(p)) { + attr->sched_priority = p->rt_priority; + } else { + attr->sched_nice = task_nice(p); ++#ifndef CONFIG_SCHED_ALT + attr->sched_runtime = p->se.slice; ++#endif + } + } + +@@ -1106,6 +1203,7 @@ SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr, + + int dl_task_check_affinity(struct task_struct *p, const struct cpumask *mask) + { ++#ifndef CONFIG_SCHED_ALT + /* + * If the task isn't a deadline task or admission control is + * disabled then we don't care about affinity changes. +@@ -1129,6 +1227,7 @@ int dl_task_check_affinity(struct task_struct *p, const struct cpumask *mask) + guard(rcu)(); + if (!cpumask_subset(task_rq(p)->rd->span, mask)) + return -EBUSY; ++#endif + + return 0; + } +@@ -1152,9 +1251,11 @@ int __sched_setaffinity(struct task_struct *p, struct affinity_context *ctx) + ctx->new_mask = new_mask; + ctx->flags |= SCA_CHECK; + ++#ifndef CONFIG_SCHED_ALT + retval = dl_task_check_affinity(p, new_mask); + if (retval) + goto out_free_new_mask; ++#endif + + retval = __set_cpus_allowed_ptr(p, ctx); + if (retval) +@@ -1334,13 +1435,34 @@ SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len, + + static void do_sched_yield(void) + { +- struct rq_flags rf; + struct rq *rq; ++ struct rq_flags rf; ++ ++#ifdef CONFIG_SCHED_ALT ++ struct task_struct *p; ++ ++ if (!sched_yield_type) ++ return; + + rq = this_rq_lock_irq(&rf); + ++ schedstat_inc(rq->yld_count); ++ ++ p = current; ++ if (rt_task(p)) { ++ if (task_on_rq_queued(p)) ++ requeue_task(p, rq, 0); ++ } else if (rq->nr_running > 1) { ++ do_sched_yield_type_1(p, rq); ++ if (task_on_rq_queued(p)) ++ requeue_task(p, rq, 0); ++ } ++#else /* !CONFIG_SCHED_ALT */ ++ rq = this_rq_lock_irq(&rf); ++ + schedstat_inc(rq->yld_count); + rq->donor->sched_class->yield_task(rq); ++#endif /* !CONFIG_SCHED_ALT */ + + preempt_disable(); + rq_unlock_irq(rq, &rf); +@@ -1409,6 +1531,9 @@ EXPORT_SYMBOL(yield); + */ + int __sched yield_to(struct task_struct *p, bool preempt) + { ++#ifdef CONFIG_SCHED_ALT ++ return 0; ++#else /* !CONFIG_SCHED_ALT */ + struct task_struct *curr; + struct rq *rq, *p_rq; + int yielded = 0; +@@ -1455,6 +1580,7 @@ int __sched yield_to(struct task_struct *p, bool preempt) + schedule(); + + return yielded; ++#endif /* !CONFIG_SCHED_ALT */ + } + EXPORT_SYMBOL_GPL(yield_to); + +@@ -1475,7 +1601,9 @@ SYSCALL_DEFINE1(sched_get_priority_max, int, policy) + case SCHED_RR: + ret = MAX_RT_PRIO-1; + break; ++#ifndef CONFIG_SCHED_ALT + case SCHED_DEADLINE: ++#endif + case SCHED_NORMAL: + case SCHED_BATCH: + case SCHED_IDLE: +@@ -1503,7 +1631,9 @@ SYSCALL_DEFINE1(sched_get_priority_min, int, policy) + case SCHED_RR: + ret = 1; + break; ++#ifndef CONFIG_SCHED_ALT + case SCHED_DEADLINE: ++#endif + case SCHED_NORMAL: + case SCHED_BATCH: + case SCHED_IDLE: +@@ -1515,7 +1645,9 @@ SYSCALL_DEFINE1(sched_get_priority_min, int, policy) + + static int sched_rr_get_interval(pid_t pid, struct timespec64 *t) + { ++#ifndef CONFIG_SCHED_ALT + unsigned int time_slice = 0; ++#endif + int retval; + + if (pid < 0) +@@ -1530,6 +1662,7 @@ static int sched_rr_get_interval(pid_t pid, struct timespec64 *t) + if (retval) + return retval; + ++#ifndef CONFIG_SCHED_ALT + scoped_guard (task_rq_lock, p) { + struct rq *rq = scope.rq; + if (p->sched_class->get_rr_interval) +@@ -1538,6 +1671,13 @@ static int sched_rr_get_interval(pid_t pid, struct timespec64 *t) + } + + jiffies_to_timespec64(time_slice, t); ++#else ++ } ++ ++ alt_sched_debug(); ++ ++ *t = ns_to_timespec64(sysctl_sched_base_slice); ++#endif /* !CONFIG_SCHED_ALT */ + return 0; + } + +diff --git a/kernel/sched/topology.c b/kernel/sched/topology.c +index 3dab025..4a3b08e 100644 +--- a/kernel/sched/topology.c ++++ b/kernel/sched/topology.c +@@ -3,6 +3,7 @@ + * Scheduler topology setup/handling methods + */ + ++#ifndef CONFIG_SCHED_ALT + #include + #include + #include +@@ -1790,8 +1791,10 @@ static void asym_cpu_capacity_scan(void) + */ + + static int default_relax_domain_level = -1; ++#endif /* CONFIG_SCHED_ALT */ + int sched_domain_level_max; + ++#ifndef CONFIG_SCHED_ALT + static int __init setup_relax_domain_level(char *str) + { + if (kstrtoint(str, 0, &default_relax_domain_level)) +@@ -2027,6 +2030,7 @@ sd_init(struct sched_domain_topology_level *tl, + + return sd; + } ++#endif /* CONFIG_SCHED_ALT */ + + #ifdef CONFIG_SCHED_SMT + int cpu_smt_flags(void) +@@ -2118,6 +2122,7 @@ void __init set_sched_topology(struct sched_domain_topology_level *tl) + sched_domain_topology_saved = NULL; + } + ++#ifndef CONFIG_SCHED_ALT + #ifdef CONFIG_NUMA + static int cpu_numa_flags(void) + { +@@ -3502,3 +3507,31 @@ void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[], + partition_sched_domains_locked(ndoms_new, doms_new, dattr_new); + sched_domains_mutex_unlock(); + } ++#else /* CONFIG_SCHED_ALT */ ++DEFINE_STATIC_KEY_FALSE(sched_asym_cpucapacity); ++ ++void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[], ++ struct sched_domain_attr *dattr_new) ++{} ++ ++#ifdef CONFIG_NUMA ++int sched_numa_find_closest(const struct cpumask *cpus, int cpu) ++{ ++ return best_mask_cpu(cpu, cpus); ++} ++ ++int sched_numa_find_nth_cpu(const struct cpumask *cpus, int cpu, int node) ++{ ++ return cpumask_nth(cpu, cpus); ++} ++ ++const struct cpumask *sched_numa_hop_mask(unsigned int node, unsigned int hops) ++{ ++ return ERR_PTR(-EOPNOTSUPP); ++} ++EXPORT_SYMBOL_GPL(sched_numa_hop_mask); ++#endif /* CONFIG_NUMA */ ++ ++void sched_update_asym_prefer_cpu(int cpu, int old_prio, int new_prio) ++{} ++#endif +diff --git a/kernel/sysctl.c b/kernel/sysctl.c +index 38597f2..b049896 100644 +--- a/kernel/sysctl.c ++++ b/kernel/sysctl.c +@@ -35,6 +35,10 @@ EXPORT_SYMBOL_GPL(sysctl_long_vals); + static const int ngroups_max = NGROUPS_MAX; + static const int cap_last_cap = CAP_LAST_CAP; + ++#ifdef CONFIG_SCHED_ALT ++extern int sched_yield_type; ++#endif ++ + #ifdef CONFIG_SYSCTL + + /** +@@ -1432,6 +1436,17 @@ static const struct ctl_table sysctl_subsys_table[] = { + .proc_handler = proc_dointvec, + }, + #endif ++#ifdef CONFIG_SCHED_ALT ++ { ++ .procname = "yield_type", ++ .data = &sched_yield_type, ++ .maxlen = sizeof (int), ++ .mode = 0644, ++ .proc_handler = &proc_dointvec_minmax, ++ .extra1 = SYSCTL_ZERO, ++ .extra2 = SYSCTL_TWO, ++ }, ++#endif + #ifdef CONFIG_SYSCTL_ARCH_UNALIGN_NO_WARN + { + .procname = "ignore-unaligned-usertrap", +diff --git a/kernel/time/posix-cpu-timers.c b/kernel/time/posix-cpu-timers.c +index 65cc612..895e2f1 100644 +--- a/kernel/time/posix-cpu-timers.c ++++ b/kernel/time/posix-cpu-timers.c +@@ -223,7 +223,7 @@ static void task_sample_cputime(struct task_struct *p, u64 *samples) + u64 stime, utime; + + task_cputime(p, &utime, &stime); +- store_samples(samples, stime, utime, p->se.sum_exec_runtime); ++ store_samples(samples, stime, utime, tsk_seruntime(p)); + } + + static void proc_sample_cputime_atomic(struct task_cputime_atomic *at, +@@ -903,6 +903,7 @@ static void collect_posix_cputimers(struct posix_cputimers *pct, u64 *samples, + } + } + ++#ifndef CONFIG_SCHED_ALT + static inline void check_dl_overrun(struct task_struct *tsk) + { + if (tsk->dl.dl_overrun) { +@@ -910,6 +911,7 @@ static inline void check_dl_overrun(struct task_struct *tsk) + send_signal_locked(SIGXCPU, SEND_SIG_PRIV, tsk, PIDTYPE_TGID); + } + } ++#endif + + static bool check_rlimit(u64 time, u64 limit, int signo, bool rt, bool hard) + { +@@ -937,8 +939,10 @@ static void check_thread_timers(struct task_struct *tsk, + u64 samples[CPUCLOCK_MAX]; + unsigned long soft; + ++#ifndef CONFIG_SCHED_ALT + if (dl_task(tsk)) + check_dl_overrun(tsk); ++#endif + + if (expiry_cache_is_inactive(pct)) + return; +@@ -952,7 +956,7 @@ static void check_thread_timers(struct task_struct *tsk, + soft = task_rlimit(tsk, RLIMIT_RTTIME); + if (soft != RLIM_INFINITY) { + /* Task RT timeout is accounted in jiffies. RTTIME is usec */ +- unsigned long rttime = tsk->rt.timeout * (USEC_PER_SEC / HZ); ++ unsigned long rttime = tsk_rttimeout(tsk) * (USEC_PER_SEC / HZ); + unsigned long hard = task_rlimit_max(tsk, RLIMIT_RTTIME); + + /* At the hard limit, send SIGKILL. No further action. */ +@@ -1183,8 +1187,10 @@ static inline bool fastpath_timer_check(struct task_struct *tsk) + return true; + } + ++#ifndef CONFIG_SCHED_ALT + if (dl_task(tsk) && tsk->dl.dl_overrun) + return true; ++#endif + + return false; + } +diff --git a/kernel/trace/trace_osnoise.c b/kernel/trace/trace_osnoise.c +index 0e1265a..b2111e6 100644 +--- a/kernel/trace/trace_osnoise.c ++++ b/kernel/trace/trace_osnoise.c +@@ -1673,6 +1673,9 @@ static void osnoise_sleep(bool skip_period) + */ + static inline int osnoise_migration_pending(void) + { ++#ifdef CONFIG_SCHED_ALT ++ return 0; ++#else + if (!current->migration_pending) + return 0; + +@@ -1694,6 +1697,7 @@ static inline int osnoise_migration_pending(void) + mutex_unlock(&interface_lock); + + return 1; ++#endif + } + + /* +diff --git a/kernel/trace/trace_selftest.c b/kernel/trace/trace_selftest.c +index 929c840..0cba8b0 100644 +--- a/kernel/trace/trace_selftest.c ++++ b/kernel/trace/trace_selftest.c +@@ -1423,10 +1423,15 @@ static int trace_wakeup_test_thread(void *data) + { + /* Make this a -deadline thread */ + static const struct sched_attr attr = { ++#ifdef CONFIG_SCHED_ALT ++ /* No deadline on BMQ/PDS, use RR */ ++ .sched_policy = SCHED_RR, ++#else + .sched_policy = SCHED_DEADLINE, + .sched_runtime = 100000ULL, + .sched_deadline = 10000000ULL, + .sched_period = 10000000ULL ++#endif + }; + struct wakeup_test_data *x = data; + +diff --git a/kernel/workqueue.c b/kernel/workqueue.c +index c1cb328..b20a0b6 100644 +--- a/kernel/workqueue.c ++++ b/kernel/workqueue.c +@@ -1291,6 +1291,7 @@ static bool kick_pool_pick(struct worker_pool *pool, struct task_struct **wakep) + + p = worker->task; + ++#ifndef CONFIG_SCHED_ALT + #ifdef CONFIG_SMP + /* + * Idle @worker is about to execute @work and waking up provides an +@@ -1321,6 +1322,7 @@ static bool kick_pool_pick(struct worker_pool *pool, struct task_struct **wakep) + } + } + #endif ++#endif /* !CONFIG_SCHED_ALT */ + /* Track the last idle worker woken, used for stall diagnostics. */ + pool->last_woken_worker = worker; + +@@ -1469,7 +1471,11 @@ void wq_worker_running(struct task_struct *task) + * CPU intensive auto-detection cares about how long a work item hogged + * CPU without sleeping. Reset the starting timestamp on wakeup. + */ ++#ifdef CONFIG_SCHED_ALT ++ worker->current_at = worker->task->sched_time; ++#else + worker->current_at = READ_ONCE(worker->task->se.sum_exec_runtime); ++#endif + + WRITE_ONCE(worker->sleeping, 0); + } +@@ -1558,7 +1564,11 @@ void wq_worker_tick(struct task_struct *task) + * We probably want to make this prettier in the future. + */ + if ((worker->flags & WORKER_NOT_RUNNING) || READ_ONCE(worker->sleeping) || ++#ifdef CONFIG_SCHED_ALT ++ worker->task->sched_time - worker->current_at < ++#else + READ_ONCE(worker->task->se.sum_exec_runtime) - worker->current_at < ++#endif + wq_cpu_intensive_thresh_us * NSEC_PER_USEC) + return; + +@@ -3315,7 +3325,11 @@ __acquires(&pool->lock) + worker->current_func = work->func; + worker->current_pwq = pwq; + if (worker->task) ++#ifdef CONFIG_SCHED_ALT ++ worker->current_at = worker->task->sched_time; ++#else + worker->current_at = READ_ONCE(worker->task->se.sum_exec_runtime); ++#endif + worker->current_start = jiffies; + work_data = *work_data_bits(work); + worker->current_color = get_work_color(work_data); +diff --git a/mm/Kconfig b/mm/Kconfig +index 604c581..317b1be 100644 +--- a/mm/Kconfig ++++ b/mm/Kconfig +@@ -657,7 +657,7 @@ config COMPACTION + config COMPACT_UNEVICTABLE_DEFAULT + int + depends on COMPACTION +- default 0 if PREEMPT_RT ++ default 0 if PREEMPT_RT || ZEN_INTERACTIVE + default 1 + + # +diff --git a/mm/damon/paddr.c b/mm/damon/paddr.c +index 9ddd1ec..bd78b4e 100644 +--- a/mm/damon/paddr.c ++++ b/mm/damon/paddr.c +@@ -255,7 +255,8 @@ static unsigned long damon_pa_pageout(struct damon_region *r, + else + *sz_filter_passed += folio_size(folio) / addr_unit; + +- folio_clear_referenced(folio); ++ /* The regions is cold, better drop the hotness info */ ++ folio_clear_lru_refs(folio); + folio_test_clear_young(folio); + if (!folio_isolate_lru(folio)) + goto put_folio; +diff --git a/mm/filemap.c b/mm/filemap.c +index 73a26cd..33b6223 100644 +--- a/mm/filemap.c ++++ b/mm/filemap.c +@@ -21,6 +21,7 @@ + #include + #include + #include ++#include + #include + #include + #include +diff --git a/mm/folio.c b/mm/folio.c +index 50a6dbe..cd9a49c 100644 +--- a/mm/folio.c ++++ b/mm/folio.c +@@ -273,7 +273,6 @@ static void lru_activate(struct lruvec *lruvec, struct folio *folio) + if (folio_test_active(folio) || folio_test_unevictable(folio)) + return; + +- + lruvec_del_folio(lruvec, folio); + folio_set_active(folio); + lruvec_add_folio(lruvec, folio); +@@ -350,63 +349,6 @@ static void __lru_cache_activate_folio(struct folio *folio) + local_unlock(&cpu_fbatches.lock); + } + +-#ifdef CONFIG_LRU_GEN +- +-static void lru_gen_inc_refs(struct folio *folio) +-{ +- unsigned long new_flags, old_flags = READ_ONCE(folio->flags.f); +- +- if (folio_test_unevictable(folio)) +- return; +- +- /* see the comment on LRU_REFS_FLAGS */ +- if (!folio_test_referenced(folio)) { +- set_mask_bits(&folio->flags.f, LRU_REFS_MASK, BIT(PG_referenced)); +- return; +- } +- +- do { +- if ((old_flags & LRU_REFS_MASK) == LRU_REFS_MASK) { +- if (!folio_test_workingset(folio)) +- folio_set_workingset(folio); +- return; +- } +- +- new_flags = old_flags + BIT(LRU_REFS_PGOFF); +- } while (!try_cmpxchg(&folio->flags.f, &old_flags, new_flags)); +-} +- +-static bool lru_gen_clear_refs(struct folio *folio) +-{ +- int gen = folio_lru_gen(folio); +- int type = folio_is_file_lru(folio); +- unsigned long seq; +- +- if (gen < 0) +- return true; +- +- set_mask_bits(&folio->flags.f, LRU_REFS_FLAGS | BIT(PG_workingset), 0); +- +- rcu_read_lock(); +- seq = READ_ONCE(folio_lruvec(folio)->lrugen.min_seq[type]); +- rcu_read_unlock(); +- /* whether can do without shuffling under the LRU lock */ +- return gen == lru_gen_from_seq(seq); +-} +- +-#else /* !CONFIG_LRU_GEN */ +- +-static void lru_gen_inc_refs(struct folio *folio) +-{ +-} +- +-static bool lru_gen_clear_refs(struct folio *folio) +-{ +- return false; +-} +- +-#endif /* CONFIG_LRU_GEN */ +- + /** + * folio_mark_accessed - Mark a folio as having seen activity. + * @folio: The folio to mark. +@@ -425,7 +367,8 @@ void folio_mark_accessed(struct folio *folio) + if (folio_test_dropbehind(folio)) + return; + if (lru_gen_enabled()) { +- lru_gen_inc_refs(folio); ++ if (!folio_test_unevictable(folio)) ++ folio_inc_lru_refs(folio, 0); + return; + } + +@@ -471,21 +414,6 @@ void folio_add_lru(struct folio *folio) + folio_test_unevictable(folio), folio); + VM_BUG_ON_FOLIO(folio_test_lru(folio), folio); + +- /* +- * For refaulted workingset folios, set PG_active so they +- * can be added to active generations. +- * For prefaulted file folios, folio_mark_accessed() sets +- * PG_referenced so lru_gen_folio_seq() places them into +- * the second oldest generation. +- */ +- if (lru_gen_enabled() && !folio_test_unevictable(folio) && +- lru_gen_in_fault() && !(current->flags & PF_MEMALLOC)) { +- if (folio_test_workingset(folio)) +- folio_set_active(folio); +- else if (!folio_test_referenced(folio)) +- folio_mark_accessed(folio); +- } +- + folio_batch_add_and_move(folio, lru_add); + } + EXPORT_SYMBOL(folio_add_lru); +@@ -597,7 +525,7 @@ static void lru_lazyfree(struct lruvec *lruvec, struct folio *folio) + lruvec_del_folio(lruvec, folio); + folio_clear_active(folio); + if (lru_gen_enabled()) +- lru_gen_clear_refs(folio); ++ __folio_set_lru_refs(folio, 0); + else + folio_clear_referenced(folio); + /* +@@ -670,7 +598,7 @@ void deactivate_file_folio(struct folio *folio) + if (folio_test_unevictable(folio) || !folio_test_lru(folio)) + return; + +- if (lru_gen_enabled() && lru_gen_clear_refs(folio)) ++ if (lru_gen_enabled() && !folio_reset_lru_refs(folio)) + return; + + folio_batch_add_and_move(folio, lru_deactivate_file); +@@ -689,7 +617,7 @@ void folio_deactivate(struct folio *folio) + if (folio_test_unevictable(folio) || !folio_test_lru(folio)) + return; + +- if (lru_gen_enabled() ? lru_gen_clear_refs(folio) : !folio_test_active(folio)) ++ if (lru_gen_enabled() ? !folio_reset_lru_refs(folio) : !folio_test_active(folio)) + return; + + folio_batch_add_and_move(folio, lru_deactivate); +diff --git a/mm/gup.c b/mm/gup.c +index 4f58ad2..2edf28e 100644 +--- a/mm/gup.c ++++ b/mm/gup.c +@@ -2895,7 +2895,7 @@ static int gup_fast_pte_range(pmd_t pmd, pmd_t *pmdp, unsigned long addr, + gup_put_folio(folio, 1, flags); + goto pte_unmap; + } +- folio_set_referenced(folio); ++ folio_inc_lru_refs_fast(folio); + pages[*nr] = page; + (*nr)++; + } while (ptep++, addr += PAGE_SIZE, addr != end); +@@ -2964,7 +2964,7 @@ static int gup_fast_pmd_leaf(pmd_t orig, pmd_t *pmdp, unsigned long addr, + *nr += refs; + for (; refs; refs--) + *(pages++) = page++; +- folio_set_referenced(folio); ++ folio_inc_lru_refs_fast(folio); + return 1; + } + +@@ -3008,7 +3008,7 @@ static int gup_fast_pud_leaf(pud_t orig, pud_t *pudp, unsigned long addr, + *nr += refs; + for (; refs; refs--) + *(pages++) = page++; +- folio_set_referenced(folio); ++ folio_inc_lru_refs_fast(folio); + return 1; + } + +diff --git a/mm/huge_memory.c b/mm/huge_memory.c +index 5f7e332..89bf58e 100644 +--- a/mm/huge_memory.c ++++ b/mm/huge_memory.c +@@ -65,7 +65,11 @@ unsigned long transparent_hugepage_flags __read_mostly = + #ifdef CONFIG_TRANSPARENT_HUGEPAGE_MADVISE + (1<vm_mm, mm_counter_file(folio), + -HPAGE_PUD_NR); +@@ -3239,8 +3243,8 @@ static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd, + folio = page_folio(page); + if (!folio_test_dirty(folio) && pmd_dirty(old_pmd)) + folio_mark_dirty(folio); +- if (!folio_test_referenced(folio) && pmd_young(old_pmd)) +- folio_set_referenced(folio); ++ if (pmd_young(old_pmd) && vma_has_recency(vma)) ++ folio_mark_accessed(folio); + folio_remove_rmap_pmd(folio, page, vma); + add_mm_counter(mm, mm_counter_file(folio), -HPAGE_PMD_NR); + folio_put(folio); +diff --git a/mm/khugepaged.c b/mm/khugepaged.c +index 47ed64f..5be3234 100644 +--- a/mm/khugepaged.c ++++ b/mm/khugepaged.c +@@ -670,7 +670,9 @@ static bool folio_pte_referenced(struct folio *folio, + struct vm_area_struct *vma, unsigned long addr, pte_t pteval) + { + /* The folio was referenced previously ... */ +- if (folio_test_young(folio) || folio_test_referenced(folio)) ++ if (folio_test_young(folio)) ++ return true; ++ if (folio_check_lru_refs(folio)) + return true; + /* ... or the PTE mapping was recently used */ + return pte_young(pteval) || mmu_notifier_test_young(vma->vm_mm, addr); +diff --git a/mm/madvise.c b/mm/madvise.c +index 222c10e..3180eeb 100644 +--- a/mm/madvise.c ++++ b/mm/madvise.c +@@ -359,6 +359,45 @@ static inline int madvise_folio_pte_batch(unsigned long addr, unsigned long end, + FPB_MERGE_YOUNG_DIRTY); + } + ++static void madvise_cold_prep_folio(struct folio *folio) ++{ ++ /* ++ * VM couldn't reclaim the folio unless we clear PG_young. ++ * As a side effect, it makes confuse idle-page tracking ++ * because they will miss recent referenced history. ++ */ ++ folio_test_clear_young(folio); ++ ++ /* ++ * For the active/inactive LRU, a folio demoted out of the active ++ * list should have PG_workingset so its refault is still accounted ++ * as a workingset refault, and the referenced bit always needs to ++ * be cleared even for inactive folios. Nothing to do for MGLRU as ++ * folio_deactivate() clears the refs count through ++ * folio_reset_lru_refs(). ++ */ ++ if (!lru_gen_enabled()) { ++ folio_clear_referenced(folio); ++ if (folio_test_active(folio)) ++ folio_set_workingset(folio); ++ } ++} ++ ++static void madvise_pageout_prep_folio(struct folio *folio) ++{ ++ int refs = folio_lru_refs(folio); ++ ++ /* ++ * For MGLRU, drop the count below LRU_REFS_WORKINGSET and cap ++ * the rest at it: MADV is ++ * suggesting the folio is actually cold, so the eviction shadow ++ * should not record its hotness in the high tier counters, but ++ * the workingset classification is preserved for PSI. ++ */ ++ if (lru_gen_enabled()) ++ __folio_set_lru_refs(folio, refs >= LRU_REFS_WORKINGSET ? LRU_REFS_WORKINGSET : 0); ++} ++ + static int madvise_cold_or_pageout_pte_range(pmd_t *pmd, + unsigned long addr, unsigned long end, + struct mm_walk *walk) +@@ -433,12 +472,10 @@ static int madvise_cold_or_pageout_pte_range(pmd_t *pmd, + tlb_remove_pmd_tlb_entry(tlb, pmd, addr); + } + +- folio_clear_referenced(folio); +- folio_test_clear_young(folio); +- if (folio_test_active(folio)) +- folio_set_workingset(folio); ++ madvise_cold_prep_folio(folio); + if (pageout) { + if (folio_isolate_lru(folio)) { ++ madvise_pageout_prep_folio(folio); + if (folio_test_unevictable(folio)) + folio_putback_lru(folio); + else +@@ -543,18 +580,10 @@ static int madvise_cold_or_pageout_pte_range(pmd_t *pmd, + tlb_remove_tlb_entries(tlb, pte, nr, addr); + } + +- /* +- * We are deactivating a folio for accelerating reclaiming. +- * VM couldn't reclaim the folio unless we clear PG_young. +- * As a side effect, it makes confuse idle-page tracking +- * because they will miss recent referenced history. +- */ +- folio_clear_referenced(folio); +- folio_test_clear_young(folio); +- if (folio_test_active(folio)) +- folio_set_workingset(folio); ++ madvise_cold_prep_folio(folio); + if (pageout) { + if (folio_isolate_lru(folio)) { ++ madvise_pageout_prep_folio(folio); + if (folio_test_unevictable(folio)) + folio_putback_lru(folio); + else +diff --git a/mm/memcontrol.c b/mm/memcontrol.c +index b303bfc..411359e 100644 +--- a/mm/memcontrol.c ++++ b/mm/memcontrol.c +@@ -1536,28 +1536,12 @@ void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru, + int zid, long nr_pages) + { + struct mem_cgroup_per_node *mz; +- unsigned long *lru_size; +- long size; + + if (mem_cgroup_disabled()) + return; + + mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec); +- lru_size = &mz->lru_zone_size[zid][lru]; +- +- if (nr_pages < 0) +- *lru_size += nr_pages; +- +- size = *lru_size; +- if (WARN_ONCE(size < 0, +- "%s(%p, %d, %ld): lru_size %ld\n", +- __func__, lruvec, lru, nr_pages, size)) { +- VM_BUG_ON(1); +- *lru_size = 0; +- } +- +- if (nr_pages > 0) +- *lru_size += nr_pages; ++ mz->lru_zone_size[zid][lru] += nr_pages; + } + + /** +diff --git a/mm/migrate.c b/mm/migrate.c +index ee78577..0d33d88 100644 +--- a/mm/migrate.c ++++ b/mm/migrate.c +@@ -776,8 +776,9 @@ void folio_migrate_flags(struct folio *newfolio, struct folio *folio) + { + int cpupid; + +- if (folio_test_referenced(folio)) +- folio_set_referenced(newfolio); ++ /* Copy the reference state, including PG_referenced */ ++ folio_migrate_lru_refs(newfolio, folio); ++ + if (folio_test_uptodate(folio)) + folio_mark_uptodate(newfolio); + if (folio_test_clear_active(folio)) { +@@ -785,8 +786,6 @@ void folio_migrate_flags(struct folio *newfolio, struct folio *folio) + folio_set_active(newfolio); + } else if (folio_test_clear_unevictable(folio)) + folio_set_unevictable(newfolio); +- if (folio_test_workingset(folio)) +- folio_set_workingset(newfolio); + if (folio_test_checked(folio)) + folio_set_checked(newfolio); + /* +@@ -807,7 +806,6 @@ void folio_migrate_flags(struct folio *newfolio, struct folio *folio) + if (folio_test_idle(folio)) + folio_set_idle(newfolio); + +- folio_migrate_refs(newfolio, folio); + /* + * Copy NUMA information to the new page, to prevent over-eager + * future migrations of this same page. +diff --git a/mm/page_io.c b/mm/page_io.c +index 8896257..b811acf 100644 +--- a/mm/page_io.c ++++ b/mm/page_io.c +@@ -16,6 +16,7 @@ + #include + #include + #include ++#include + #include + #include + #include +diff --git a/mm/swap_state.c b/mm/swap_state.c +index 0d9b0d8..0d001d6 100644 +--- a/mm/swap_state.c ++++ b/mm/swap_state.c +@@ -1031,6 +1031,10 @@ static const struct ctl_table swap_readahead_sysctl_table[] = { + + static void __init swap_readahead_setup(void) + { ++#ifdef CONFIG_ZEN_INTERACTIVE ++ /* Only swap-in pages requested, avoid readahead */ ++ page_cluster = 0; ++#else + unsigned long megs = PAGES_TO_MB(totalram_pages()); + + /* Use a smaller cluster for small-memory machines */ +@@ -1042,6 +1046,7 @@ static void __init swap_readahead_setup(void) + * Right now other parts of the system means that we + * _really_ don't want to cluster much more + */ ++#endif + + register_sysctl_init("vm", swap_readahead_sysctl_table); + } +diff --git a/mm/vmscan.c b/mm/vmscan.c +index 88fd31d..30e3977 100644 +--- a/mm/vmscan.c ++++ b/mm/vmscan.c +@@ -182,17 +182,37 @@ struct scan_control { + }; + + #ifdef ARCH_HAS_PREFETCHW +-#define prefetchw_prev_lru_folio(_folio, _base, _field) \ +- do { \ +- if ((_folio)->lru.prev != _base) { \ +- struct folio *prev; \ +- \ +- prev = lru_to_folio(&(_folio->lru)); \ +- prefetchw(&prev->_field); \ +- } \ +- } while (0) ++static inline void prefetchw_prev_lru_folio(struct folio *folio, ++ struct list_head *base) ++{ ++ if (folio->lru.prev != base) { ++ struct folio *prev; ++ ++ prev = lru_to_folio(&folio->lru); ++ prefetchw(&prev->flags); ++ } ++} ++ ++static inline void prefetchw_next_lru_folio(struct folio *folio, ++ struct list_head *base) ++{ ++ if (folio->lru.next != base) { ++ struct folio *next; ++ ++ next = list_entry(folio->lru.next, struct folio, lru); ++ prefetchw(&next->flags); ++ } ++} + #else +-#define prefetchw_prev_lru_folio(_folio, _base, _field) do { } while (0) ++static inline void prefetchw_prev_lru_folio(struct folio *folio, ++ struct list_head *base) ++{ ++} ++ ++static inline void prefetchw_next_lru_folio(struct folio *folio, ++ struct list_head *base) ++{ ++} + #endif + + /* +@@ -830,35 +850,257 @@ enum folio_references { + }; + + #ifdef CONFIG_LRU_GEN ++/****************************************************************************** ++ * Referenced count feedback ++ ******************************************************************************/ ++ + /* +- * Only used on a mapped folio in the eviction (rmap walk) path, where promotion +- * needs to be done by taking the folio off the LRU list and then adding it back +- * with PG_active set. In contrast, the aging (page table walk) path uses +- * folio_update_gen(). ++ * The folio_inc_lru_refs{_*} helpers below collect the referenced info ++ * (hotness) from other parts, including the page table walker, the rmap walk ++ * upon eviction, the rmap lookaround, and file descriptors ++ * (folio_mark_accessed). ++ * ++ * Page table accesses use refs from either source. The first reference ++ * advances tail-gen folios by one generation; a second promotes to the ++ * newest. Executable file folios promote on their first access to avoid ++ * I/O thrashing. Isolated rmap accesses use evict_folios() for putback. ++ * ++ * Promotion changes folio->flags; sort_folio() or inc_min_seq() moves the ++ * folio later. Young PTEs found during unmapping use folio_mark_accessed() ++ * and follow the file descriptor rules below. ++ * ++ * File descriptor accesses do not promote. They only defer eviction from ++ * the tail gens of their type, and only once the folio is a workingset ++ * folio (LRU_REFS_WORKINGSET), leaving the rest to PID protection. Page ++ * table accesses are treated more generously because the accessed bit is ++ * sticky (it under-counts repeated accesses) and because a page fault is ++ * more costly than file descriptor I/O. ++ * ++ * PID protection operates on tier > 0 folios. The one proactive promotion ++ * outside of it and the page table path is the overflow case where the ++ * referenced count exceeds LRU_REFS_MAX, which means the folio is hotter ++ * than everything else in its generation. ++ * ++ * Whenever a folio changes generation here its referenced count is capped at ++ * LRU_REFS_PROTECTED, so it starts at or below the protected tier regardless ++ * of its old-generation access history. PID protection (folio_inc_gen) caps ++ * at LRU_REFS_WORKINGSET independently. ++ * ++ * folio_inc_lru_refs() retries with LRU_REF_FORCE if the aging recycled the ++ * gen index it was about to store: newest gen and an extra reference. ++ */ ++ ++/* ++ * Update the folio's lru refs indicator. The caller doesn't need to hold ++ * the folio lock, isolate the folio, or hold the lruvec lock. Used by both ++ * cache access (flags == 0) and page table access (LRU_REF_MAPPED, ++ * optionally with LRU_REF_EXEC). + */ +-static bool lru_gen_set_refs(struct folio *folio, const vma_flags_t *vma_flags) ++void folio_inc_lru_refs(struct folio *folio, unsigned int flags) + { +- /* see the comment on LRU_REFS_FLAGS */ +- if (!folio_test_referenced(folio) && !folio_test_workingset(folio)) { +- /* Activate file-backed executable folios after first usage. */ +- if (is_exec_file_folio(folio, vma_flags)) { +- set_mask_bits(&folio->flags.f, LRU_REFS_FLAGS, BIT(PG_workingset)); +- return true; ++ int max_gen; ++ int file, old_refs, refs, old_gen, gen; ++ unsigned long new_flags, old_flags, max_seq; ++ long nr_pages = folio_nr_pages(folio); ++ struct lru_gen_folio *lrugen; ++ struct lruvec *lruvec = NULL; ++ bool aged = false; ++ ++retry: ++ old_flags = READ_ONCE(*folio_flags(folio, 0)); ++ do { ++ new_flags = old_flags; ++ old_gen = lru_get_gen_flags(old_flags); ++ old_refs = lru_get_refs_flags(old_flags); ++ refs = old_refs + 1; ++ gen = old_gen; ++ file = folio_flags_is_file_lru(&old_flags); ++ if (old_gen < 0) ++ goto out; ++ if (!lruvec) { ++ lruvec = folio_lruvec_live_get(folio); ++ lrugen = &lruvec->lrugen; ++ } ++ /* ++ * Read the flags before max_seq, paired with the store of a ++ * gen, which samples max_seq first. ++ */ ++ smp_rmb(); ++ max_seq = READ_ONCE(lrugen->max_seq); ++ max_gen = lru_gen_from_seq(max_seq); ++ if (old_gen == max_gen) ++ goto out; ++ if (flags & (LRU_REF_MAPPED | LRU_REF_EXEC | LRU_REF_FORCE)) { ++ if (refs > LRU_REFS_REFERENCED || ++ flags & (LRU_REF_EXEC | LRU_REF_FORCE)) ++ gen = max_gen; ++ /* First access only defers eviction of a tail gen */ ++ else if (lru_gen_at_tail(lruvec, file, old_gen)) ++ gen = (old_gen + 1) % MAX_NR_GENS; ++ refs = min(refs, LRU_REFS_PROTECTED); ++ } else if (refs > LRU_REFS_MAX) { ++ /* LRU refs counting overflow, bump the gen */ ++ gen = (old_gen + 1) % MAX_NR_GENS; ++ refs = LRU_REFS_PROTECTED; ++ } else if (lru_gen_at_tail(lruvec, file, old_gen) && refs >= LRU_REFS_WORKINGSET) { ++ /* Defer eviction of just accessed workingset */ ++ gen = (old_gen + 1) % MAX_NR_GENS; ++ refs = min(refs, LRU_REFS_PROTECTED); ++ } ++out: ++ refs = min(refs, LRU_REFS_MAX); ++ lru_set_refs_flags(&new_flags, refs); ++ if (gen != old_gen) ++ lru_set_gen_flags(&new_flags, gen); ++ if (new_flags == old_flags) ++ break; ++ } while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags)); ++ ++ if (gen != old_gen) { ++ /* ++ * Gen-index reuse can fool cmpxchg(). Retry locklessly, accepting ++ * an extra reference to avoid folio_activate() latency. ++ */ ++ if (unlikely(READ_ONCE(lrugen->max_seq) != max_seq)) { ++ flags = LRU_REF_FORCE; ++ aged = true; + } ++ lru_gen_update_size(lruvec, file, folio, old_gen, gen); ++ } + +- set_mask_bits(&folio->flags.f, LRU_REFS_MASK, BIT(PG_referenced)); +- return false; ++ if (lru_refs_is_active(old_refs) != lru_refs_is_active(refs) && gen >= 0) { ++ enum lru_list lru = file * LRU_INACTIVE_FILE; ++ ++ __update_lru_size(lruvec, lru + lru_refs_is_active(old_refs), ++ folio_zonenum(folio), -nr_pages); ++ __update_lru_size(lruvec, lru + lru_refs_is_active(refs), ++ folio_zonenum(folio), nr_pages); ++ } ++ if (aged) { ++ aged = false; ++ goto retry; + } ++ if (lruvec) ++ folio_lruvec_live_put(lruvec); ++} + +- /* Promote on second access */ +- if (folio_lru_refs(folio) > 1) +- set_mask_bits(&folio->flags.f, LRU_REFS_FLAGS, BIT(PG_workingset)); +- else +- folio_mark_accessed(folio); +- return true; ++/* ++ * Reset the folio's lru refs indicator. The caller doesn't need to hold ++ * the folio lock, isolate the folio, or hold the lruvec lock. ++ */ ++bool folio_reset_lru_refs(struct folio *folio) ++{ ++ int type, gen, refs; ++ unsigned long seq, new_flags, old_flags; ++ long nr_pages = folio_nr_pages(folio); ++ struct lruvec *lruvec; ++ bool reset = false; ++ ++ old_flags = READ_ONCE(*folio_flags(folio, 0)); ++ do { ++ new_flags = old_flags; ++ refs = lru_get_refs_flags(old_flags); ++ type = folio_flags_is_file_lru(&old_flags); ++ gen = lru_get_gen_flags(old_flags); ++ if (!refs) ++ break; ++ lru_set_refs_flags(&new_flags, 0); ++ } while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags)); ++ ++ if (gen >= 0) { ++ lruvec = folio_lruvec_live_get(folio); ++ ++ /* If the folio is on list, caller might also want to demote it */ ++ seq = READ_ONCE(lruvec->lrugen.min_seq[type]); ++ reset = (gen != lru_gen_from_seq(seq)); ++ if (lru_refs_is_active(refs)) { ++ __update_lru_size(lruvec, type * LRU_FILE + LRU_ACTIVE, ++ folio_zonenum(folio), -nr_pages); ++ __update_lru_size(lruvec, type * LRU_FILE, ++ folio_zonenum(folio), nr_pages); ++ } ++ ++ folio_lruvec_live_put(lruvec); ++ } ++ ++ return reset; ++} ++ ++/* ++ * Update the folio's lru refs indicator during a page table walk or the ++ * look-around. max_seq can be stale as neither holds the LRU lock. ++ * ++ * Returns the old generation, or -1 if the folio is off the LRU list. ++ * Old LRU refs, and updated gen and LRU refs info by the successful ++ * cmpxchg are all stored by returning arguments. ++ */ ++static int folio_inc_lru_refs_walk(struct folio *folio, struct lruvec *lruvec, ++ const vma_flags_t *vma_flags, int *new_gen, ++ int *old_refs, int *new_refs, int *type) ++{ ++ unsigned long new_flags, old_flags = READ_ONCE(*folio_flags(folio, 0)); ++ int refs, old_gen, max_gen; ++ unsigned long max_seq; ++ ++ do { ++ max_seq = READ_ONCE(lruvec->lrugen.max_seq); ++ max_gen = lru_gen_from_seq(max_seq); ++ old_gen = lru_get_gen_flags(old_flags); ++ refs = lru_get_refs_flags(old_flags) + 1; ++ *type = folio_flags_is_file_lru(&old_flags); ++ new_flags = old_flags; ++ ++ if (old_gen >= 0 && old_gen != max_gen) { ++ *new_refs = min(refs, LRU_REFS_PROTECTED); ++ /* Promote second page table access or executable */ ++ if (refs > LRU_REFS_REFERENCED || is_exec_file_folio(folio, vma_flags)) ++ *new_gen = max_gen; ++ /* First access only defers eviction of a tail gen */ ++ else if (lru_gen_at_tail(lruvec, *type, old_gen)) ++ *new_gen = (old_gen + 1) % MAX_NR_GENS; ++ else ++ *new_gen = old_gen; ++ lru_set_gen_flags(&new_flags, *new_gen); ++ lru_set_refs_flags(&new_flags, *new_refs); ++ } else { ++ *new_gen = old_gen; ++ *new_refs = min(refs, LRU_REFS_MAX); ++ lru_set_refs_flags(&new_flags, *new_refs); ++ } ++ if (new_flags == old_flags) ++ break; ++ } while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags)); ++ ++ *old_refs = lru_get_refs_flags(old_flags); ++ ++ return old_gen; ++} ++ ++/* ++ * Update the lru refs indicator of an isolated folio, only used on ++ * mapped folios upon the final eviction. ++ * ++ * Increments the refs count (capped at LRU_REFS_PROTECTED, evict_folios() ++ * then caps it at LRU_REFS_WORKINGSET). Returns true if the caller should ++ * activate the folio (second access or executable), false to put it back ++ * for a second chance. ++ */ ++static bool folio_inc_lru_refs_isolated(struct folio *folio, const vma_flags_t *vma_flags) ++{ ++ unsigned long new_flags, old_flags = READ_ONCE(*folio_flags(folio, 0)); ++ int refs; ++ ++ do { ++ new_flags = old_flags; ++ refs = lru_get_refs_flags(old_flags) + 1; ++ lru_set_refs_flags(&new_flags, min(refs, LRU_REFS_PROTECTED)); ++ } while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags)); ++ ++ /* Promote second page table access or executable */ ++ return refs > LRU_REFS_REFERENCED || is_exec_file_folio(folio, vma_flags); + } + #else +-static bool lru_gen_set_refs(struct folio *folio, const vma_flags_t *vma_flags) ++static bool folio_inc_lru_refs_isolated(struct folio *folio, const vma_flags_t *vma_flags) + { + return false; + } +@@ -893,7 +1135,8 @@ static enum folio_references folio_check_references(struct folio *folio, + if (!referenced_ptes) + return FOLIOREF_RECLAIM; + +- return lru_gen_set_refs(folio, &vma_flags) ? FOLIOREF_ACTIVATE : FOLIOREF_KEEP; ++ return folio_inc_lru_refs_isolated(folio, &vma_flags) ? ++ FOLIOREF_ACTIVATE : FOLIOREF_KEEP; + } + + referenced_folio = folio_test_clear_referenced(folio); +@@ -1694,7 +1937,7 @@ static unsigned long isolate_lru_folios(unsigned long nr_to_scan, + struct folio *folio; + + folio = lru_to_folio(src); +- prefetchw_prev_lru_folio(folio, src, flags); ++ prefetchw_prev_lru_folio(folio, src); + + nr_pages = folio_nr_pages(folio); + total_scan += nr_pages; +@@ -3177,9 +3420,9 @@ static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long seq) + * P term over the generations previously evicted, using the smoothing factor + * 1/2; the D term isn't supported. + * +- * The setpoint (SP) is always the first tier of one type; the process variable +- * (PV) is either any tier of the other type or any other tier of the same +- * type. ++ * To select a type, the setpoint (SP) is all tiers of one type and the process ++ * variable (PV) is all tiers of the other type. To select a tier to protect, ++ * the SP is the tiers below it and the PV is the tier itself. + * + * The error is the difference between the SP and the PV; the correction is to + * turn off protection when SP>PV or turn on protection when SPflags.f); ++ unsigned long new_flags, old_flags = READ_ONCE(*folio_flags(folio, 0)); ++ int file, refs, old_refs, new_gen; + +- VM_WARN_ON_ONCE(gen >= MAX_NR_GENS); ++ do { ++ new_gen = lru_get_gen_flags(old_flags); + +- /* +- * See the comment on LRU_REFS_FLAGS, and activate file-backed +- * executable folios after first usage to avoid typical IO +- * thrashing from reclaiming. +- */ +- if (!folio_test_referenced(folio) && !folio_test_workingset(folio) && +- !is_exec_file_folio(folio, vma_flags)) { +- set_mask_bits(&folio->flags.f, LRU_REFS_MASK, BIT(PG_referenced)); +- return -1; +- } ++ /* folio_inc_lru_refs() has promoted this page? */ ++ if (new_gen >= 0 && new_gen != old_gen) { ++ if (increased) ++ *increased = false; ++ return new_gen; ++ } + +- do { +- /* lru_gen_del_folio() has isolated this page? */ +- if (!(old_flags & LRU_GEN_MASK)) +- return -1; ++ new_flags = old_flags; ++ new_gen = (old_gen + 1) % MAX_NR_GENS; ++ old_refs = lru_get_refs_flags(old_flags); ++ file = folio_flags_is_file_lru(&old_flags); ++ refs = min(old_refs, LRU_REFS_WORKINGSET); ++ lru_set_gen_flags(&new_flags, new_gen); ++ lru_set_refs_flags(&new_flags, refs); ++ } while (!try_cmpxchg(folio_flags(folio, 0), &old_flags, new_flags)); ++ ++ /* Refs capped below PROTECTED: demote if previously active. */ ++ if (lru_refs_is_active(old_refs) != lru_refs_is_active(refs)) { ++ enum lru_list lru = file * LRU_INACTIVE_FILE; ++ int nr_pages = folio_nr_pages(folio); + +- new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_FLAGS); +- new_flags |= ((gen + 1UL) << LRU_GEN_PGOFF) | BIT(PG_workingset); +- } while (!try_cmpxchg(&folio->flags.f, &old_flags, new_flags)); ++ __update_lru_size(lruvec, lru + lru_refs_is_active(old_refs), ++ folio_zonenum(folio), -nr_pages); ++ __update_lru_size(lruvec, lru + lru_refs_is_active(refs), ++ folio_zonenum(folio), nr_pages); ++ } + +- return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1; ++ if (increased) ++ *increased = true; ++ return new_gen; + } + +-/* protect pages accessed multiple times through file descriptors */ ++/* ++ * Force bump a folio's generation. Used for PID protection or to skip a ++ * folio from a zone ineligible for the current reclaim. ++ */ + static int folio_inc_gen(struct lruvec *lruvec, struct folio *folio) + { ++ bool gen_increased; + int type = folio_is_file_lru(folio); + struct lru_gen_folio *lrugen = &lruvec->lrugen; + int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]); +- unsigned long new_flags, old_flags = READ_ONCE(folio->flags.f); + +- VM_WARN_ON_ONCE_FOLIO(!(old_flags & LRU_GEN_MASK), folio); +- +- do { +- new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1; +- /* folio_update_gen() has promoted this page? */ +- if (new_gen >= 0 && new_gen != old_gen) +- return new_gen; +- +- new_gen = (old_gen + 1) % MAX_NR_GENS; +- +- new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_FLAGS); +- new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF; +- } while (!try_cmpxchg(&folio->flags.f, &old_flags, new_flags)); +- +- lru_gen_update_size(lruvec, folio, old_gen, new_gen); ++ new_gen = __folio_inc_gen(lruvec, folio, old_gen, &gen_increased); ++ if (gen_increased) ++ lru_gen_update_size(lruvec, type, folio, old_gen, new_gen); + + return new_gen; + } + + static void update_batch_size(struct lru_gen_mm_walk *walk, struct folio *folio, +- int old_gen, int new_gen) ++ int old_gen, int new_gen, int old_refs, int new_refs, int type) + { +- int type = folio_is_file_lru(folio); + int zone = folio_zonenum(folio); + int delta = folio_nr_pages(folio); + +- VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS); +- VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS); +- +- walk->batched++; ++ /* gen counter update */ ++ if (old_gen != new_gen) { ++ VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS); ++ VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS); ++ walk->batched++; ++ walk->nr_pages[old_gen][type][zone] -= delta; ++ walk->nr_pages[new_gen][type][zone] += delta; ++ } + +- walk->nr_pages[old_gen][type][zone] -= delta; +- walk->nr_pages[new_gen][type][zone] += delta; ++ /* active/inactive counter update */ ++ if (lru_refs_is_active(old_refs) != lru_refs_is_active(new_refs)) { ++ walk->nr_activated[type][zone] += ++ lru_refs_is_active(new_refs) ? delta : -delta; ++ walk->batched++; ++ } + } + + static void reset_batch_size(struct lru_gen_mm_walk *walk) +@@ -3349,19 +3601,28 @@ static void reset_batch_size(struct lru_gen_mm_walk *walk) + walk->batched = 0; + + for_each_gen_type_zone(gen, type, zone) { +- enum lru_list lru = type * LRU_INACTIVE_FILE; + int delta = walk->nr_pages[gen][type][zone]; + + if (!delta) + continue; + + walk->nr_pages[gen][type][zone] = 0; +- WRITE_ONCE(lrugen->nr_pages[gen][type][zone], +- lrugen->nr_pages[gen][type][zone] + delta); ++ atomic_long_add(delta, &lrugen->nr_pages[gen][type][zone]); ++ } ++ ++ /* apply batched active/inactive updates */ ++ for (type = 0; type < ANON_AND_FILE; type++) { ++ for (zone = 0; zone < MAX_NR_ZONES; zone++) { ++ enum lru_list lru = type * LRU_INACTIVE_FILE; ++ int delta = walk->nr_activated[type][zone]; + +- if (lru_gen_is_active(lruvec, gen)) +- lru += LRU_ACTIVE; +- __update_lru_size(lruvec, lru, zone, delta); ++ if (delta) { ++ __update_lru_size(lruvec, lru + LRU_ACTIVE, ++ zone, delta); ++ __update_lru_size(lruvec, lru, zone, -delta); ++ walk->nr_activated[type][zone] = 0; ++ } ++ } + } + + lruvec_unlock_irq(lruvec); +@@ -3514,9 +3775,10 @@ static bool suitable_to_scan(int total, int young) + } + + static void walk_update_folio(struct lru_gen_mm_walk *walk, struct vm_area_struct *vma, +- struct folio *folio, int new_gen, bool dirty) ++ struct lruvec *lruvec, struct folio *folio, bool dirty) + { +- int old_gen; ++ int new_gen, old_gen, old_refs, new_refs, type; ++ unsigned int flags = LRU_REF_MAPPED; + + if (!folio) + return; +@@ -3527,13 +3789,15 @@ static void walk_update_folio(struct lru_gen_mm_walk *walk, struct vm_area_struc + folio_mark_dirty(folio); + + if (walk) { +- old_gen = folio_update_gen(folio, new_gen, &vma->flags); +- if (old_gen >= 0 && old_gen != new_gen) +- update_batch_size(walk, folio, old_gen, new_gen); +- } else if (lru_gen_set_refs(folio, &vma->flags)) { +- old_gen = folio_lru_gen(folio); +- if (old_gen >= 0 && old_gen != new_gen) +- folio_activate(folio); ++ old_gen = folio_inc_lru_refs_walk(folio, lruvec, &vma->flags, ++ &new_gen, &old_refs, &new_refs, &type); ++ if (old_gen >= 0) ++ update_batch_size(walk, folio, old_gen, new_gen, ++ old_refs, new_refs, type); ++ } else { ++ if (is_exec_file_folio(folio, &vma->flags)) ++ flags |= LRU_REF_EXEC; ++ folio_inc_lru_refs(folio, flags); + } + } + +@@ -3551,8 +3815,6 @@ static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end, + struct lru_gen_mm_walk *walk = args->private; + struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec); + struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec); +- DEFINE_MAX_SEQ(walk->lruvec); +- int gen = lru_gen_from_seq(max_seq); + unsigned int nr; + pmd_t pmdval; + +@@ -3603,7 +3865,7 @@ static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end, + continue; + + if (last != folio) { +- walk_update_folio(walk, args->vma, last, gen, dirty); ++ walk_update_folio(walk, args->vma, walk->lruvec, last, dirty); + + last = folio; + dirty = false; +@@ -3616,7 +3878,7 @@ static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end, + walk->mm_stats[MM_LEAF_YOUNG] += nr; + } + +- walk_update_folio(walk, args->vma, last, gen, dirty); ++ walk_update_folio(walk, args->vma, walk->lruvec, last, dirty); + last = NULL; + + if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end)) +@@ -3639,8 +3901,6 @@ static void walk_pmd_range_locked(pud_t *pud, unsigned long addr, struct vm_area + struct lru_gen_mm_walk *walk = args->private; + struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec); + struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec); +- DEFINE_MAX_SEQ(walk->lruvec); +- int gen = lru_gen_from_seq(max_seq); + + VM_WARN_ON_ONCE(pud_leaf(*pud)); + +@@ -3694,7 +3954,7 @@ static void walk_pmd_range_locked(pud_t *pud, unsigned long addr, struct vm_area + goto next; + + if (last != folio) { +- walk_update_folio(walk, vma, last, gen, dirty); ++ walk_update_folio(walk, vma, walk->lruvec, last, dirty); + + last = folio; + dirty = false; +@@ -3708,7 +3968,7 @@ static void walk_pmd_range_locked(pud_t *pud, unsigned long addr, struct vm_area + i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1; + } while (i <= MIN_LRU_BATCH); + +- walk_update_folio(walk, vma, last, gen, dirty); ++ walk_update_folio(walk, vma, walk->lruvec, last, dirty); + + lazy_mmu_mode_disable(); + spin_unlock(ptl); +@@ -3892,6 +4152,7 @@ static void clear_mm_walk(void) + + VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages))); + VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats))); ++ VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_activated, 0, sizeof(walk->nr_activated))); + + current->reclaim_state->mm_walk = NULL; + +@@ -3899,6 +4160,19 @@ static void clear_mm_walk(void) + kfree(walk); + } + ++static inline void flush_lru_batch(struct list_head *head, struct list_head **batch_end, ++ struct list_head *dst) ++{ ++ LIST_HEAD(movable); ++ ++ if (!*batch_end) ++ return; ++ ++ list_cut_position(&movable, head, *batch_end); ++ list_splice_tail_init(&movable, dst); ++ *batch_end = NULL; ++} ++ + static bool inc_min_seq(struct lruvec *lruvec, int type, int swappiness) + { + int zone; +@@ -3906,6 +4180,7 @@ static bool inc_min_seq(struct lruvec *lruvec, int type, int swappiness) + struct lru_gen_folio *lrugen = &lruvec->lrugen; + int hist = lru_hist_from_seq(lrugen->min_seq[type]); + int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]); ++ int target_gen = (old_gen + 1) % MAX_NR_GENS; + + /* For file type, skip the check if swappiness is anon only */ + if (type && (swappiness == SWAPPINESS_ANON_ONLY)) +@@ -3915,35 +4190,53 @@ static bool inc_min_seq(struct lruvec *lruvec, int type, int swappiness) + if (!type && !swappiness) + goto done; + ++ VM_WARN_ON_ONCE(get_nr_gens(lruvec, type) != MAX_NR_GENS); + /* prevent cold/hot inversion if the type is evictable */ + for (zone = 0; zone < MAX_NR_ZONES; zone++) { ++ struct list_head *target_list = &lrugen->folios[target_gen][type][zone]; + struct list_head *head = &lrugen->folios[old_gen][type][zone]; ++ struct list_head *pos = head->next; ++ struct list_head *batch_end = NULL; ++ long delta = 0; + +- while (!list_empty(head)) { +- struct folio *folio = lru_to_folio(head); ++ while (pos != head) { ++ struct folio *folio = list_entry(pos, struct folio, lru); ++ long nr_pages = folio_nr_pages(folio); + int refs = folio_lru_refs(folio); +- bool workingset = folio_test_workingset(folio); ++ int tier = lru_tier_from_refs(refs); ++ bool gen_increased; + + VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio); + VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio); + VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio); + VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio); + +- new_gen = folio_inc_gen(lruvec, folio); +- list_move_tail(&folio->lru, &lrugen->folios[new_gen][type][zone]); +- +- /* don't count the workingset being lazily promoted */ +- if (refs + workingset != BIT(LRU_REFS_WIDTH) + 1) { +- int tier = lru_tier_from_refs(refs, workingset); +- int delta = folio_nr_pages(folio); ++ prefetchw_next_lru_folio(folio, head); ++ pos = pos->next; ++ new_gen = __folio_inc_gen(lruvec, folio, old_gen, &gen_increased); ++ /* ++ * If gen_increased is false, this is a promotion. Put folios ++ * at the head of the promoted gen. Otherwise, put them at ++ * the tail of the second-oldest gen. ++ */ ++ if (gen_increased) { ++ delta += nr_pages; ++ batch_end = &folio->lru; + + WRITE_ONCE(lrugen->protected[hist][type][tier], +- lrugen->protected[hist][type][tier] + delta); ++ lrugen->protected[hist][type][tier] + nr_pages); ++ } else { ++ flush_lru_batch(head, &batch_end, target_list); ++ list_move(&folio->lru, &lrugen->folios[new_gen][type][zone]); + } +- + if (!--remaining) +- return false; ++ break; + } ++ flush_lru_batch(head, &batch_end, target_list); ++ atomic_long_sub(delta, &lrugen->nr_pages[old_gen][type][zone]); ++ atomic_long_add(delta, &lrugen->nr_pages[target_gen][type][zone]); ++ if (!remaining) ++ return false; + } + done: + reset_ctrl_pos(lruvec, type, true); +@@ -4007,8 +4300,7 @@ static void try_to_inc_min_seq(struct lruvec *lruvec, int swappiness) + static bool inc_max_seq(struct lruvec *lruvec, unsigned long seq, int swappiness) + { + bool success; +- int prev, next; +- int type, zone; ++ int type, next; + struct lru_gen_folio *lrugen = &lruvec->lrugen; + restart: + if (seq < READ_ONCE(lrugen->max_seq)) +@@ -4034,32 +4326,10 @@ static bool inc_max_seq(struct lruvec *lruvec, unsigned long seq, int swappiness + goto restart; + } + +- /* +- * Update the active/inactive LRU sizes for compatibility. Both sides of +- * the current max_seq need to be covered, since max_seq+1 can overlap +- * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do +- * overlap, cold/hot inversion happens. +- */ +- prev = lru_gen_from_seq(lrugen->max_seq - 1); +- next = lru_gen_from_seq(lrugen->max_seq + 1); +- +- for (type = 0; type < ANON_AND_FILE; type++) { +- for (zone = 0; zone < MAX_NR_ZONES; zone++) { +- enum lru_list lru = type * LRU_INACTIVE_FILE; +- long delta = lrugen->nr_pages[prev][type][zone] - +- lrugen->nr_pages[next][type][zone]; +- +- if (!delta) +- continue; +- +- __update_lru_size(lruvec, lru, zone, delta); +- __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta); +- } +- } +- + for (type = 0; type < ANON_AND_FILE; type++) + reset_ctrl_pos(lruvec, type, false); + ++ next = lru_gen_from_seq(lrugen->max_seq + 1); + WRITE_ONCE(lrugen->timestamps[next], jiffies); + /* make sure preceding modifications appear */ + smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1); +@@ -4165,7 +4435,8 @@ static unsigned long lruvec_evictable_size(struct lruvec *lruvec, int swappiness + for (seq = min_seq[type]; seq <= max_seq; seq++) { + gen = lru_gen_from_seq(seq); + for (zone = 0; zone < MAX_NR_ZONES; zone++) +- total += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L); ++ total += max(atomic_long_read(&lrugen->nr_pages[gen][type][zone]), ++ 0L); + } + } + +@@ -4272,8 +4543,6 @@ bool lru_gen_look_around(struct page_vma_mapped_walk *pvmw, unsigned int nr) + struct pglist_data *pgdat = folio_pgdat(folio); + struct lruvec *lruvec; + struct lru_gen_mm_state *mm_state; +- unsigned long max_seq; +- int gen; + + lockdep_assert_held(pvmw->ptl); + VM_WARN_ON_ONCE_FOLIO(folio_test_lru(folio), folio); +@@ -4310,8 +4579,6 @@ bool lru_gen_look_around(struct page_vma_mapped_walk *pvmw, unsigned int nr) + + memcg = get_mem_cgroup_from_folio(folio); + lruvec = mem_cgroup_lruvec(memcg, pgdat); +- max_seq = READ_ONCE((lruvec)->lrugen.max_seq); +- gen = lru_gen_from_seq(max_seq); + mm_state = get_mm_state(lruvec); + + lazy_mmu_mode_enable(); +@@ -4343,7 +4610,7 @@ bool lru_gen_look_around(struct page_vma_mapped_walk *pvmw, unsigned int nr) + continue; + + if (last != folio) { +- walk_update_folio(walk, vma, last, gen, dirty); ++ walk_update_folio(walk, vma, lruvec, last, dirty); + + last = folio; + dirty = false; +@@ -4355,13 +4622,14 @@ bool lru_gen_look_around(struct page_vma_mapped_walk *pvmw, unsigned int nr) + young += nr; + } + +- walk_update_folio(walk, vma, last, gen, dirty); ++ walk_update_folio(walk, vma, lruvec, last, dirty); + + lazy_mmu_mode_disable(); + + /* feedback from rmap walkers to page table walkers */ + if (mm_state && suitable_to_scan(i, young)) +- update_bloom_filter(mm_state, max_seq, pvmw->pmd); ++ update_bloom_filter(mm_state, READ_ONCE(lruvec->lrugen.max_seq), ++ pvmw->pmd); + + mem_cgroup_put(memcg); + +@@ -4592,30 +4860,22 @@ static void __lru_gen_reparent_memcg(struct lruvec *child_lruvec, struct lruvec + int zone, int type) + { + struct lru_gen_folio *child_lrugen, *parent_lrugen; +- enum lru_list lru = type * LRU_INACTIVE_FILE; + int i; + + child_lrugen = &child_lruvec->lrugen; + parent_lrugen = &parent_lruvec->lrugen; + +- for (i = 0; i < get_nr_gens(child_lruvec, type); i++) { ++ /* Lockless promotion may leave folios outside the child's window */ ++ for (i = 0; i < MAX_NR_GENS; i++) { + int gen = lru_gen_from_seq(child_lrugen->max_seq - i); +- long nr_pages = child_lrugen->nr_pages[gen][type][zone]; +- int child_lru_active = lru_gen_is_active(child_lruvec, gen) ? LRU_ACTIVE : 0; +- int parent_lru_active = lru_gen_is_active(parent_lruvec, gen) ? LRU_ACTIVE : 0; ++ long nr_pages = atomic_long_read(&child_lrugen->nr_pages[gen][type][zone]); + + /* Assuming that child pages are colder than parent pages */ + list_splice_tail_init(&child_lrugen->folios[gen][type][zone], + &parent_lrugen->folios[gen][type][zone]); + +- WRITE_ONCE(child_lrugen->nr_pages[gen][type][zone], 0); +- WRITE_ONCE(parent_lrugen->nr_pages[gen][type][zone], +- parent_lrugen->nr_pages[gen][type][zone] + nr_pages); +- +- if (lru_gen_is_active(child_lruvec, gen) != lru_gen_is_active(parent_lruvec, gen)) { +- __update_lru_size(child_lruvec, lru + child_lru_active, zone, -nr_pages); +- __update_lru_size(parent_lruvec, lru + parent_lru_active, zone, nr_pages); +- } ++ atomic_long_set(&child_lrugen->nr_pages[gen][type][zone], 0); ++ atomic_long_add(nr_pages, &parent_lrugen->nr_pages[gen][type][zone]); + } + } + +@@ -4661,8 +4921,7 @@ static bool sort_folio(struct lruvec *lruvec, struct folio *folio, struct scan_c + int zone = folio_zonenum(folio); + int delta = folio_nr_pages(folio); + int refs = folio_lru_refs(folio); +- bool workingset = folio_test_workingset(folio); +- int tier = lru_tier_from_refs(refs, workingset); ++ int tier = lru_tier_from_refs(refs); + struct lru_gen_folio *lrugen = &lruvec->lrugen; + + VM_WARN_ON_ONCE_FOLIO(gen >= MAX_NR_GENS, folio); +@@ -4678,17 +4937,15 @@ static bool sort_folio(struct lruvec *lruvec, struct folio *folio, struct scan_c + } + + /* protected */ +- if (tier > tier_idx || refs + workingset == BIT(LRU_REFS_WIDTH) + 1) { ++ if (tier > tier_idx) { ++ int hist = lru_hist_from_seq(lrugen->min_seq[type]); ++ + gen = folio_inc_gen(lruvec, folio); + list_move(&folio->lru, &lrugen->folios[gen][type][zone]); + +- /* don't count the workingset being lazily promoted */ +- if (refs + workingset != BIT(LRU_REFS_WIDTH) + 1) { +- int hist = lru_hist_from_seq(lrugen->min_seq[type]); ++ WRITE_ONCE(lrugen->protected[hist][type][tier], ++ lrugen->protected[hist][type][tier] + delta); + +- WRITE_ONCE(lrugen->protected[hist][type][tier], +- lrugen->protected[hist][type][tier] + delta); +- } + return true; + } + +@@ -4716,10 +4973,6 @@ static bool isolate_folio(struct lruvec *lruvec, struct folio *folio, struct sca + return false; + } + +- /* see the comment on LRU_REFS_FLAGS */ +- if (!folio_test_referenced(folio)) +- set_mask_bits(&folio->flags.f, LRU_REFS_MASK, 0); +- + success = lru_gen_del_folio(lruvec, folio, true); + VM_WARN_ON_ONCE_FOLIO(!success, folio); + +@@ -4807,13 +5060,14 @@ static int get_tier_idx(struct lruvec *lruvec, int type) + struct ctrl_pos sp, pv; + + /* +- * To leave a margin for fluctuations, use a larger gain factor (2:3). +- * This value is chosen because any other tier would have at least twice +- * as many refaults as the first tier. ++ * To leave a margin for fluctuations, use a larger gain factor (1:2). ++ * Stop at the first tier whose refault rate is clearly worse than ++ * that of the cumulative mass of the tiers below it; the PID ++ * protects the tiers above it. + */ +- read_ctrl_pos(lruvec, type, LRU_TIER_MIN, LRU_TIER_MIN, 2, &sp); + for (tier = LRU_TIER_MIN + 1; tier <= LRU_TIER_MAX; tier++) { +- read_ctrl_pos(lruvec, type, tier, tier, 3, &pv); ++ read_ctrl_pos(lruvec, type, LRU_TIER_MIN, tier - 1, 1, &sp); ++ read_ctrl_pos(lruvec, type, tier, tier, 2, &pv); + if (!positive_ctrl_err(&sp, &pv)) + break; + } +@@ -4901,6 +5155,9 @@ static int evict_folios(unsigned long nr_to_scan, struct lruvec *lruvec, + scanned = isolate_folios(nr_to_scan, lruvec, sc, swappiness, + &list, &isolated, &type, &type_scanned); + nr_isolated = isolated; ++ if (nr_isolated) ++ __mod_node_page_state(pgdat, NR_ISOLATED_ANON + type, ++ nr_isolated); + + /* Scanning may have emptied the oldest gen, flush it */ + if (scanned) +@@ -4935,9 +5192,16 @@ static int evict_folios(unsigned long nr_to_scan, struct lruvec *lruvec, + continue; + } + +- /* don't add rejected folios to the oldest generation */ ++ /* ++ * The rejected folios are never added to the oldest generation, ++ * so this effectively promotes them by at least one generation. ++ * PG_active is the only placement hint here, so a folio kept on ++ * its first page table access lands in the second newest one. ++ * See "Referenced count feedback" above. ++ */ ++ __folio_set_lru_refs(folio, min(folio_lru_refs(folio), LRU_REFS_WORKINGSET)); + if (lru_gen_folio_seq(lruvec, folio, false) == min_seq[type]) +- set_mask_bits(&folio->flags.f, LRU_REFS_FLAGS, BIT(PG_active)); ++ folio_set_active(folio); + } + + move_folios_to_lru(&list); +@@ -4963,6 +5227,8 @@ static int evict_folios(unsigned long nr_to_scan, struct lruvec *lruvec, + goto retry; + } + ++ mod_node_page_state(pgdat, NR_ISOLATED_ANON + type, -nr_isolated); ++ + if (nr_isolated > total_reclaimed) + mod_lruvec_state(lruvec, PGROTATE_ANON + type, + nr_isolated - total_reclaimed); +@@ -5654,7 +5920,8 @@ static int lru_gen_seq_show(struct seq_file *m, void *v) + char mark = full && seq < min_seq[type] ? 'x' : ' '; + + for (zone = 0; zone < MAX_NR_ZONES; zone++) +- size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L); ++ size += max(atomic_long_read(&lrugen->nr_pages[gen][type][zone]), ++ 0L); + + seq_printf(m, " %10lu%c", size, mark); + } +@@ -5680,6 +5947,9 @@ static int run_aging(struct lruvec *lruvec, unsigned long seq, + { + DEFINE_MAX_SEQ(lruvec); + ++ if (seq < max_seq) ++ return 0; ++ + if (seq > max_seq) + return -EINVAL; + +diff --git a/mm/workingset.c b/mm/workingset.c +index 8412f48..a04d495 100644 +--- a/mm/workingset.c ++++ b/mm/workingset.c +@@ -188,6 +188,12 @@ + #define EVICTION_SHIFT_ANON (EVICTION_SHIFT + SWAP_COUNT_SHIFT) + #define EVICTION_MASK (~0UL >> EVICTION_SHIFT) + #define EVICTION_MASK_ANON (~0UL >> EVICTION_SHIFT_ANON) ++/* ++ * LRU refs uses LRU_REFS_WIDTH + 2 bits, the 2 bits being PG_workingset ++ * and PG_referenced. The lowest bit is recorded in the workingset field ++ * of the shadow entry (to reuse pack_shadow()). ++ */ ++#define LRU_REFS_BITS ((LRU_REFS_WIDTH + 2) - 1) + + /* + * Eviction timestamps need to be able to cover the full range of +@@ -242,13 +248,12 @@ static void *lru_gen_eviction(struct folio *folio) + int type = folio_is_file_lru(folio); + int delta = folio_nr_pages(folio); + int refs = folio_lru_refs(folio); +- bool workingset = folio_test_workingset(folio); +- int tier = lru_tier_from_refs(refs, workingset); ++ int tier = lru_tier_from_refs(refs); + struct mem_cgroup *memcg; + struct pglist_data *pgdat = folio_pgdat(folio); + unsigned short memcg_id; + +- BUILD_BUG_ON(LRU_GEN_WIDTH + LRU_REFS_WIDTH > ++ BUILD_BUG_ON(LRU_GEN_WIDTH + LRU_REFS_BITS > + BITS_PER_LONG - max(EVICTION_SHIFT, EVICTION_SHIFT_ANON)); + + rcu_read_lock(); +@@ -256,14 +261,14 @@ static void *lru_gen_eviction(struct folio *folio) + lruvec = mem_cgroup_lruvec(memcg, pgdat); + lrugen = &lruvec->lrugen; + min_seq = READ_ONCE(lrugen->min_seq[type]); +- token = (min_seq << LRU_REFS_WIDTH) | max(refs - 1, 0); ++ token = (min_seq << LRU_REFS_BITS) | refs >> 1; + + hist = lru_hist_from_seq(min_seq); + atomic_long_add(delta, &lrugen->evicted[hist][type][tier]); + memcg_id = mem_cgroup_private_id(memcg); + rcu_read_unlock(); + +- return pack_shadow(memcg_id, pgdat, token, workingset, type); ++ return pack_shadow(memcg_id, pgdat, token, refs & 1, type); + } + + /* +@@ -284,9 +289,9 @@ static bool lru_gen_test_recent(void *shadow, struct lruvec **lruvec, + *lruvec = mem_cgroup_lruvec(memcg, pgdat); + + max_seq = READ_ONCE((*lruvec)->lrugen.max_seq); +- max_seq &= (file ? EVICTION_MASK : EVICTION_MASK_ANON) >> LRU_REFS_WIDTH; ++ max_seq &= (file ? EVICTION_MASK : EVICTION_MASK_ANON) >> LRU_REFS_BITS; + +- return abs_diff(max_seq, *token >> LRU_REFS_WIDTH) < MAX_NR_GENS; ++ return abs_diff(max_seq, *token >> LRU_REFS_BITS) < MAX_NR_GENS; + } + + static void lru_gen_refault(struct folio *folio, void *shadow) +@@ -314,22 +319,26 @@ static void lru_gen_refault(struct folio *folio, void *shadow) + lrugen = &lruvec->lrugen; + + hist = lru_hist_from_seq(READ_ONCE(lrugen->min_seq[type])); +- refs = (token & (BIT(LRU_REFS_WIDTH) - 1)) + 1; +- tier = lru_tier_from_refs(refs, workingset); ++ refs = ((token & (BIT(LRU_REFS_BITS) - 1)) << 1) + workingset; ++ tier = lru_tier_from_refs(refs); + + atomic_long_add(delta, &lrugen->refaulted[hist][type][tier]); + +- if (workingset) { +- /* +- * see folio_add_lru(), where folio_set_active() is +- * called for workingset folios +- */ +- if (lru_gen_in_fault()) ++ /* ++ * Activate a fault-driven refault folio, which would have been ++ * promoted had it stayed in memory. ++ */ ++ if (refs >= LRU_REFS_REFERENCED) { ++ if (lru_gen_in_fault()) { ++ folio_set_active(folio); + mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta); +- folio_set_workingset(folio); ++ } ++ /* Refault is also promotion, cap the refs like folio_inc_lru_refs */ ++ __folio_set_lru_refs(folio, min(refs, LRU_REFS_PROTECTED)); ++ } ++ ++ if (refs >= LRU_REFS_WORKINGSET) + mod_lruvec_state(lruvec, WORKINGSET_RESTORE_BASE + type, delta); +- } else +- set_mask_bits(&folio->flags.f, LRU_REFS_MASK, (refs - 1UL) << LRU_REFS_PGOFF); + unlock: + rcu_read_unlock(); + } +diff --git a/mm/zswap.c b/mm/zswap.c +index e6e6377..9354ca1 100644 +--- a/mm/zswap.c ++++ b/mm/zswap.c +@@ -136,14 +136,25 @@ bool zswap_never_enabled(void) + * data structures + **********************************/ + +-struct crypto_acomp_ctx { +- struct crypto_acomp *acomp; ++struct zswap_acomp_req { + struct acomp_req *req; + struct crypto_wait wait; +- u8 *buffer; + struct mutex mutex; + }; + ++/* The compression mutex also protects the output buffer. */ ++struct zswap_comp_ctx { ++ struct zswap_acomp_req areq; ++ u8 *buffer; ++}; ++ ++/* Separate requests, so that decompression does not wait for compression. */ ++struct crypto_acomp_ctx { ++ struct crypto_acomp *acomp; ++ struct zswap_comp_ctx comp; ++ struct zswap_acomp_req decomp; /* unused with on-stack requests */ ++}; ++ + /* + * The lock ordering is zswap_tree.lock -> zswap_pool.lru_lock. + * The only case where lru_lock is not acquired while holding tree.lock is +@@ -247,14 +258,10 @@ static void acomp_ctx_free(struct crypto_acomp_ctx *acomp_ctx) + if (!acomp_ctx) + return; + +- /* +- * If there was an error in allocating @acomp_ctx->req, it +- * would be set to NULL. +- */ +- if (acomp_ctx->req) +- acomp_request_free(acomp_ctx->req); +- +- acomp_ctx->req = NULL; ++ acomp_request_free(acomp_ctx->comp.areq.req); ++ acomp_ctx->comp.areq.req = NULL; ++ acomp_request_free(acomp_ctx->decomp.req); ++ acomp_ctx->decomp.req = NULL; + + /* + * We have to handle both cases here: an error pointer return from +@@ -266,8 +273,8 @@ static void acomp_ctx_free(struct crypto_acomp_ctx *acomp_ctx) + + acomp_ctx->acomp = NULL; + +- kfree(acomp_ctx->buffer); +- acomp_ctx->buffer = NULL; ++ kfree(acomp_ctx->comp.buffer); ++ acomp_ctx->comp.buffer = NULL; + } + + static struct zswap_pool *zswap_pool_create(char *compressor) +@@ -782,6 +789,33 @@ static void zswap_entry_free(struct zswap_entry *entry) + /********************************* + * compressed storage functions + **********************************/ ++static void zswap_set_acomp_req_callback(struct acomp_req *req, ++ struct crypto_wait *wait) ++{ ++ /* ++ * if the backend of acomp is async zip, crypto_req_done() will wakeup ++ * crypto_wait_req(); if the backend of acomp is scomp, the callback ++ * won't be called, crypto_wait_req() will return without blocking. ++ */ ++ acomp_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG, ++ crypto_req_done, wait); ++} ++ ++static int zswap_acomp_req_init(struct zswap_acomp_req *areq, ++ struct crypto_acomp *acomp) ++{ ++ /* acomp_request_alloc() returns NULL in case of an error. */ ++ areq->req = acomp_request_alloc(acomp); ++ if (!areq->req) ++ return -ENOMEM; ++ ++ crypto_init_wait(&areq->wait); ++ zswap_set_acomp_req_callback(areq->req, &areq->wait); ++ ++ mutex_init(&areq->mutex); ++ return 0; ++} ++ + static int zswap_cpu_comp_prepare(unsigned int cpu, struct hlist_node *node) + { + struct zswap_pool *pool = hlist_entry(node, struct zswap_pool, node); +@@ -797,8 +831,8 @@ static int zswap_cpu_comp_prepare(unsigned int cpu, struct hlist_node *node) + return 0; + } + +- acomp_ctx->buffer = kmalloc_node(PAGE_SIZE, GFP_KERNEL, cpu_to_node(cpu)); +- if (!acomp_ctx->buffer) ++ acomp_ctx->comp.buffer = kmalloc_node(PAGE_SIZE, GFP_KERNEL, cpu_to_node(cpu)); ++ if (!acomp_ctx->comp.buffer) + return ret; + + /* +@@ -813,27 +847,21 @@ static int zswap_cpu_comp_prepare(unsigned int cpu, struct hlist_node *node) + goto fail; + } + +- /* acomp_request_alloc() returns NULL in case of an error. */ +- acomp_ctx->req = acomp_request_alloc(acomp_ctx->acomp); +- if (!acomp_ctx->req) { +- pr_err("could not alloc crypto acomp_request %s\n", +- pool->tfm_name); +- goto fail; +- } +- +- crypto_init_wait(&acomp_ctx->wait); ++ ret = zswap_acomp_req_init(&acomp_ctx->comp.areq, acomp_ctx->acomp); ++ if (ret) ++ goto req_fail; + +- /* +- * if the backend of acomp is async zip, crypto_req_done() will wakeup +- * crypto_wait_req(); if the backend of acomp is scomp, the callback +- * won't be called, crypto_wait_req() will return without blocking. +- */ +- acomp_request_set_callback(acomp_ctx->req, CRYPTO_TFM_REQ_MAY_BACKLOG, +- crypto_req_done, &acomp_ctx->wait); ++ /* Skip the per-CPU request when decompression can use the stack. */ ++ if (acomp_is_async(acomp_ctx->acomp)) { ++ ret = zswap_acomp_req_init(&acomp_ctx->decomp, acomp_ctx->acomp); ++ if (ret) ++ goto req_fail; ++ } + +- mutex_init(&acomp_ctx->mutex); + return 0; + ++req_fail: ++ pr_err("could not alloc crypto acomp_request %s\n", pool->tfm_name); + fail: + acomp_ctx_free(acomp_ctx); + return ret; +@@ -842,7 +870,7 @@ static int zswap_cpu_comp_prepare(unsigned int cpu, struct hlist_node *node) + static bool zswap_compress(struct page *page, struct zswap_entry *entry, + struct zswap_pool *pool) + { +- struct crypto_acomp_ctx *acomp_ctx; ++ struct zswap_comp_ctx *comp_ctx; + struct scatterlist input, output; + int comp_ret = 0, alloc_ret = 0; + unsigned int dlen = PAGE_SIZE; +@@ -851,15 +879,16 @@ static bool zswap_compress(struct page *page, struct zswap_entry *entry, + u8 *dst; + bool mapped = false; + +- acomp_ctx = raw_cpu_ptr(pool->acomp_ctx); +- mutex_lock(&acomp_ctx->mutex); ++ comp_ctx = &raw_cpu_ptr(pool->acomp_ctx)->comp; ++ mutex_lock(&comp_ctx->areq.mutex); + +- dst = acomp_ctx->buffer; ++ dst = comp_ctx->buffer; + sg_init_table(&input, 1); + sg_set_page(&input, page, PAGE_SIZE, 0); + + sg_init_one(&output, dst, PAGE_SIZE); +- acomp_request_set_params(acomp_ctx->req, &input, &output, PAGE_SIZE, dlen); ++ acomp_request_set_params(comp_ctx->areq.req, &input, &output, ++ PAGE_SIZE, dlen); + + /* + * it maybe looks a little bit silly that we send an asynchronous request, +@@ -871,10 +900,12 @@ static bool zswap_compress(struct page *page, struct zswap_entry *entry, + * existing method to send the second page before the first page is done + * in one thread doing zswap. + * but in different threads running on different cpu, we have different +- * acomp instance, so multiple threads can do (de)compression in parallel. ++ * acomp instance, and compression and decompression use separate ++ * requests, so multiple threads can do (de)compression in parallel. + */ +- comp_ret = crypto_wait_req(crypto_acomp_compress(acomp_ctx->req), &acomp_ctx->wait); +- dlen = acomp_ctx->req->dlen; ++ comp_ret = crypto_wait_req(crypto_acomp_compress(comp_ctx->areq.req), ++ &comp_ctx->areq.wait); ++ dlen = comp_ctx->areq.req->dlen; + + /* + * If a page cannot be compressed into a size smaller than PAGE_SIZE, +@@ -919,20 +950,18 @@ static bool zswap_compress(struct page *page, struct zswap_entry *entry, + else if (alloc_ret) + zswap_reject_alloc_fail++; + +- mutex_unlock(&acomp_ctx->mutex); ++ mutex_unlock(&comp_ctx->areq.mutex); + return comp_ret == 0 && alloc_ret == 0; + } + +-static bool zswap_decompress(struct zswap_entry *entry, struct folio *folio) ++static bool __zswap_decompress(struct zswap_entry *entry, ++ struct zswap_pool *pool, struct acomp_req *req, ++ struct crypto_wait *wait, struct folio *folio) + { +- struct zswap_pool *pool = entry->pool; + struct scatterlist input[2]; /* zsmalloc returns an SG list 1-2 entries */ + struct scatterlist output; +- struct crypto_acomp_ctx *acomp_ctx; + int ret = 0, dlen; + +- acomp_ctx = raw_cpu_ptr(pool->acomp_ctx); +- mutex_lock(&acomp_ctx->mutex); + zs_obj_read_sg_begin(pool->zs_pool, entry->handle, input, entry->length); + + /* zswap entries of length PAGE_SIZE are not compressed. */ +@@ -949,15 +978,13 @@ static bool zswap_decompress(struct zswap_entry *entry, struct folio *folio) + } else { + sg_init_table(&output, 1); + sg_set_folio(&output, folio, PAGE_SIZE, 0); +- acomp_request_set_params(acomp_ctx->req, input, &output, +- entry->length, PAGE_SIZE); +- ret = crypto_acomp_decompress(acomp_ctx->req); +- ret = crypto_wait_req(ret, &acomp_ctx->wait); +- dlen = acomp_ctx->req->dlen; ++ acomp_request_set_params(req, input, &output, entry->length, PAGE_SIZE); ++ ret = crypto_acomp_decompress(req); ++ ret = crypto_wait_req(ret, wait); ++ dlen = req->dlen; + } + + zs_obj_read_sg_end(pool->zs_pool, entry->handle); +- mutex_unlock(&acomp_ctx->mutex); + + if (!ret && dlen == PAGE_SIZE) + return true; +@@ -971,6 +998,32 @@ static bool zswap_decompress(struct zswap_entry *entry, struct folio *folio) + return false; + } + ++static bool zswap_decompress(struct zswap_entry *entry, struct folio *folio) ++{ ++ struct zswap_pool *pool = entry->pool; ++ struct crypto_acomp_ctx *acomp_ctx; ++ bool ret; ++ ++ acomp_ctx = raw_cpu_ptr(pool->acomp_ctx); ++ /* ++ * Use a private on-stack request when the transform supports it. ++ * Otherwise serialize decompression on the shared per-CPU request. ++ */ ++ if (!acomp_ctx->decomp.req) { ++ ACOMP_REQUEST_ON_STACK(req, acomp_ctx->acomp); ++ DECLARE_CRYPTO_WAIT(wait); ++ ++ zswap_set_acomp_req_callback(req, &wait); ++ return __zswap_decompress(entry, pool, req, &wait, folio); ++ } ++ ++ mutex_lock(&acomp_ctx->decomp.mutex); ++ ret = __zswap_decompress(entry, pool, acomp_ctx->decomp.req, ++ &acomp_ctx->decomp.wait, folio); ++ mutex_unlock(&acomp_ctx->decomp.mutex); ++ return ret; ++} ++ + /********************************* + * writeback code + **********************************/ +diff --git a/net/ipv4/Kconfig b/net/ipv4/Kconfig +index 301b476..b7476c5 100644 +--- a/net/ipv4/Kconfig ++++ b/net/ipv4/Kconfig +@@ -668,15 +668,33 @@ config TCP_CONG_BBR + default n + help + +- BBR (Bottleneck Bandwidth and RTT) TCP congestion control aims to +- maximize network utilization and minimize queues. It builds an explicit +- model of the bottleneck delivery rate and path round-trip propagation +- delay. It tolerates packet loss and delay unrelated to congestion. It +- can operate over LAN, WAN, cellular, wifi, or cable modem links. It can +- coexist with flows that use loss-based congestion control, and can +- operate with shallow buffers, deep buffers, bufferbloat, policers, or +- AQM schemes that do not provide a delay signal. It requires the fq +- ("Fair Queue") pacing packet scheduler. ++ BBR (Bottleneck Bandwidth and RTT) TCP congestion control aims to ++ maximize network utilization and minimize queues. It builds an explicit ++ model of the bottleneck delivery rate and path round-trip propagation ++ delay. It tolerates packet loss and delay unrelated to congestion. It ++ can operate over LAN, WAN, cellular, wifi, or cable modem links. It can ++ coexist with flows that use loss-based congestion control, and can ++ operate with shallow buffers, deep buffers, bufferbloat, policers, or ++ AQM schemes that do not provide a delay signal. It requires the fq ++ ("Fair Queue") pacing packet scheduler. ++ ++config TCP_CONG_BBR3 ++ tristate "BBR3 TCP" ++ default n ++ help ++ ++ BBR (Bottleneck Bandwidth and RTT) TCP congestion control is a ++ model-based congestion control algorithm that aims to maximize ++ network utilization, keep queues and retransmit rates low, and to be ++ able to coexist with Reno/CUBIC in common scenarios. It builds an ++ explicit model of the network path. It tolerates a targeted degree ++ of random packet loss and delay. It can operate over LAN, WAN, ++ cellular, wifi, or cable modem links, and can use shallow-threshold ++ ECN signals. It can coexist to some degree with flows that use ++ loss-based congestion control, and can operate with shallow buffers, ++ deep buffers, bufferbloat, policers, or AQM schemes that do not ++ provide a delay signal. It requires pacing, using either TCP internal ++ pacing or the fq ("Fair Queue") pacing packet scheduler. + + choice + prompt "Default TCP congestion control" +@@ -715,6 +733,9 @@ choice + config DEFAULT_BBR + bool "BBR" if TCP_CONG_BBR=y + ++ config DEFAULT_BBR3 ++ bool "BBR3" if TCP_CONG_BBR3=y ++ + config DEFAULT_RENO + bool "Reno" + endchoice +@@ -739,6 +760,7 @@ config DEFAULT_TCP_CONG + default "dctcp" if DEFAULT_DCTCP + default "cdg" if DEFAULT_CDG + default "bbr" if DEFAULT_BBR ++ default "bbr3" if DEFAULT_BBR3 + default "cubic" + + config TCP_AO +diff --git a/net/ipv4/Makefile b/net/ipv4/Makefile +index 06e21c2..2159821 100644 +--- a/net/ipv4/Makefile ++++ b/net/ipv4/Makefile +@@ -45,6 +45,7 @@ obj-$(CONFIG_INET_TCP_DIAG) += tcp_diag.o + obj-$(CONFIG_INET_UDP_DIAG) += udp_diag.o + obj-$(CONFIG_INET_RAW_DIAG) += raw_diag.o + obj-$(CONFIG_TCP_CONG_BBR) += tcp_bbr.o ++obj-$(CONFIG_TCP_CONG_BBR3) += tcp_bbr3.o + obj-$(CONFIG_TCP_CONG_BIC) += tcp_bic.o + obj-$(CONFIG_TCP_CONG_CDG) += tcp_cdg.o + obj-$(CONFIG_TCP_CONG_CUBIC) += tcp_cubic.o +diff --git a/net/ipv4/bpf_tcp_ca.c b/net/ipv4/bpf_tcp_ca.c +index 791e150..4f2c7bc 100644 +--- a/net/ipv4/bpf_tcp_ca.c ++++ b/net/ipv4/bpf_tcp_ca.c +@@ -284,7 +284,7 @@ static void bpf_tcp_ca_pkts_acked(struct sock *sk, const struct ack_sample *samp + { + } + +-static u32 bpf_tcp_ca_min_tso_segs(struct sock *sk) ++static u32 bpf_tcp_ca_tso_segs(struct sock *sk, unsigned int mss_now) + { + return 0; + } +@@ -320,7 +320,7 @@ static struct tcp_congestion_ops __bpf_ops_tcp_congestion_ops = { + .cwnd_event_tx_start = bpf_tcp_ca_cwnd_event_tx_start, + .in_ack_event = bpf_tcp_ca_in_ack_event, + .pkts_acked = bpf_tcp_ca_pkts_acked, +- .min_tso_segs = bpf_tcp_ca_min_tso_segs, ++ .tso_segs = bpf_tcp_ca_tso_segs, + .cong_control = bpf_tcp_ca_cong_control, + .undo_cwnd = bpf_tcp_ca_undo_cwnd, + .sndbuf_expand = bpf_tcp_ca_sndbuf_expand, +diff --git a/net/ipv4/tcp.c b/net/ipv4/tcp.c +index 87ef6d5..67e951b 100644 +--- a/net/ipv4/tcp.c ++++ b/net/ipv4/tcp.c +@@ -3484,6 +3484,7 @@ int tcp_disconnect(struct sock *sk, int flags) + tp->rx_opt.dsack = 0; + tp->rx_opt.num_sacks = 0; + tp->rcv_ooopack = 0; ++ tp->fast_ack_mode = 0; + + + /* Clean up fastopen related fields */ +@@ -4269,6 +4270,8 @@ void tcp_get_info(struct sock *sk, struct tcp_info *info) + info->tcpi_options |= TCPI_OPT_ECN; + if (tp->ecn_flags & TCP_ECN_SEEN) + info->tcpi_options |= TCPI_OPT_ECN_SEEN; ++ if (tp->ecn_flags & TCP_ECN_LOW) ++ info->tcpi_options |= TCPI_OPT_ECN_LOW; + if (tp->syn_data_acked) + info->tcpi_options |= TCPI_OPT_SYN_DATA; + if (tp->tcp_usec_ts) +diff --git a/net/ipv4/tcp_bbr.c b/net/ipv4/tcp_bbr.c +index 82378a2..2ab73e5 100644 +--- a/net/ipv4/tcp_bbr.c ++++ b/net/ipv4/tcp_bbr.c +@@ -302,6 +302,23 @@ __bpf_kfunc static u32 bbr_min_tso_segs(struct sock *sk) + return READ_ONCE(sk->sk_pacing_rate) < (bbr_min_tso_rate >> 3) ? 1 : 2; + } + ++__bpf_kfunc static u32 bbr_tso_segs(struct sock *sk, unsigned int mss_now) ++{ ++ unsigned long bytes; ++ u32 r; ++ ++ bytes = READ_ONCE(sk->sk_pacing_rate) >> READ_ONCE(sk->sk_pacing_shift); ++ ++ r = tcp_min_rtt(tcp_sk(sk)) >> ++ READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_tso_rtt_log); ++ if (r < BITS_PER_TYPE(sk->sk_gso_max_size)) ++ bytes += sk->sk_gso_max_size >> r; ++ ++ bytes = min_t(unsigned long, bytes, sk->sk_gso_max_size); ++ ++ return max_t(u32, bytes / mss_now, bbr_min_tso_segs(sk)); ++} ++ + static u32 bbr_tso_segs_goal(struct sock *sk) + { + struct tcp_sock *tp = tcp_sk(sk); +@@ -1151,7 +1168,7 @@ static struct tcp_congestion_ops tcp_bbr_cong_ops __read_mostly = { + .undo_cwnd = bbr_undo_cwnd, + .cwnd_event_tx_start = bbr_cwnd_event_tx_start, + .ssthresh = bbr_ssthresh, +- .min_tso_segs = bbr_min_tso_segs, ++ .tso_segs = bbr_tso_segs, + .get_info = bbr_get_info, + .set_state = bbr_set_state, + }; +diff --git a/net/ipv4/tcp_bbr3.c b/net/ipv4/tcp_bbr3.c +new file mode 100644 +index 0000000..0697a9c +--- /dev/null ++++ b/net/ipv4/tcp_bbr3.c +@@ -0,0 +1,2418 @@ ++// SPDX-License-Identifier: GPL-2.0 ++/* BBR (Bottleneck Bandwidth and RTT) congestion control ++ * ++ * BBR is a model-based congestion control algorithm that aims for low queues, ++ * low loss, and (bounded) Reno/CUBIC coexistence. To maintain a model of the ++ * network path, it uses measurements of bandwidth and RTT, as well as (if they ++ * occur) packet loss and/or shallow-threshold ECN signals. Note that although ++ * it can use ECN or loss signals explicitly, it does not require either; it ++ * can bound its in-flight data based on its estimate of the BDP. ++ * ++ * The model has both higher and lower bounds for the operating range: ++ * lo: bw_lo, inflight_lo: conservative short-term lower bound ++ * hi: bw_hi, inflight_hi: robust long-term upper bound ++ * The bandwidth-probing time scale is (a) extended dynamically based on ++ * estimated BDP to improve coexistence with Reno/CUBIC; (b) bounded by ++ * an interactive wall-clock time-scale to be more scalable and responsive ++ * than Reno and CUBIC. ++ * ++ * Here is a state transition diagram for BBR: ++ * ++ * | ++ * V ++ * +---> STARTUP ----+ ++ * | | | ++ * | V | ++ * | DRAIN ----+ ++ * | | | ++ * | V | ++ * +---> PROBE_BW ----+ ++ * | ^ | | ++ * | | | | ++ * | +----+ | ++ * | | ++ * +---- PROBE_RTT <--+ ++ * ++ * A BBR flow starts in STARTUP, and ramps up its sending rate quickly. ++ * When it estimates the pipe is full, it enters DRAIN to drain the queue. ++ * In steady state a BBR flow only uses PROBE_BW and PROBE_RTT. ++ * A long-lived BBR flow spends the vast majority of its time remaining ++ * (repeatedly) in PROBE_BW, fully probing and utilizing the pipe's bandwidth ++ * in a fair manner, with a small, bounded queue. *If* a flow has been ++ * continuously sending for the entire min_rtt window, and hasn't seen an RTT ++ * sample that matches or decreases its min_rtt estimate for 10 seconds, then ++ * it briefly enters PROBE_RTT to cut inflight to a minimum value to re-probe ++ * the path's two-way propagation delay (min_rtt). When exiting PROBE_RTT, if ++ * we estimated that we reached the full bw of the pipe then we enter PROBE_BW; ++ * otherwise we enter STARTUP to try to fill the pipe. ++ * ++ * BBR is described in detail in: ++ * "BBR: Congestion-Based Congestion Control", ++ * Neal Cardwell, Yuchung Cheng, C. Stephen Gunn, Soheil Hassas Yeganeh, ++ * Van Jacobson. ACM Queue, Vol. 14 No. 5, September-October 2016. ++ * ++ * There is a public e-mail list for discussing BBR development and testing: ++ * https://groups.google.com/forum/#!forum/bbr-dev ++ * ++ * NOTE: BBR might be used with the fq qdisc ("man tc-fq") with pacing enabled, ++ * otherwise TCP stack falls back to an internal pacing using one high ++ * resolution timer per TCP socket and may use more resources. ++ */ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++#include "tcp_dctcp.h" ++ ++#define BBR_VERSION 3 ++ ++#define bbr_param(sk,name) (bbr_ ## name) ++ ++/* Scale factor for rate in pkt/uSec unit to avoid truncation in bandwidth ++ * estimation. The rate unit ~= (1500 bytes / 1 usec / 2^24) ~= 715 bps. ++ * This handles bandwidths from 0.06pps (715bps) to 256Mpps (3Tbps) in a u32. ++ * Since the minimum window is >=4 packets, the lower bound isn't ++ * an issue. The upper bound isn't an issue with existing technologies. ++ */ ++#define BW_SCALE 24 ++#define BW_UNIT (1 << BW_SCALE) ++ ++#define BBR_SCALE 8 /* scaling factor for fractions in BBR (e.g. gains) */ ++#define BBR_UNIT (1 << BBR_SCALE) ++ ++/* BBR has the following modes for deciding how fast to send: */ ++enum bbr_mode { ++ BBR_STARTUP, /* ramp up sending rate rapidly to fill pipe */ ++ BBR_DRAIN, /* drain any queue created during startup */ ++ BBR_PROBE_BW, /* discover, share bw: pace around estimated bw */ ++ BBR_PROBE_RTT, /* cut inflight to min to probe min_rtt */ ++}; ++ ++/* How does the incoming ACK stream relate to our bandwidth probing? */ ++enum bbr_ack_phase { ++ BBR_ACKS_INIT, /* not probing; not getting probe feedback */ ++ BBR_ACKS_REFILLING, /* sending at est. bw to fill pipe */ ++ BBR_ACKS_PROBE_STARTING, /* inflight rising to probe bw */ ++ BBR_ACKS_PROBE_FEEDBACK, /* getting feedback from bw probing */ ++ BBR_ACKS_PROBE_STOPPING, /* stopped probing; still getting feedback */ ++}; ++ ++/* BBR congestion control block */ ++struct bbr { ++ u32 min_rtt_us; /* min RTT in min_rtt_win_sec window */ ++ u32 min_rtt_stamp; /* timestamp of min_rtt_us */ ++ u32 probe_rtt_done_stamp; /* end time for BBR_PROBE_RTT mode */ ++ u32 probe_rtt_min_us; /* min RTT in probe_rtt_win_ms win */ ++ u32 probe_rtt_min_stamp; /* timestamp of probe_rtt_min_us*/ ++ u32 next_rtt_delivered; /* scb->tx.delivered at end of round */ ++ u64 cycle_mstamp; /* time of this cycle phase start */ ++ u32 mode:2, /* current bbr_mode in state machine */ ++ prev_ca_state:3, /* CA state on previous ACK */ ++ round_start:1, /* start of packet-timed tx->ack round? */ ++ ce_state:1, /* If most recent data has CE bit set */ ++ bw_probe_up_rounds:5, /* cwnd-limited rounds in PROBE_UP */ ++ try_fast_path:1, /* can we take fast path? */ ++ idle_restart:1, /* restarting after idle? */ ++ probe_rtt_round_done:1, /* a BBR_PROBE_RTT round at 4 pkts? */ ++ init_cwnd:7, /* initial cwnd */ ++ unused_1:10; ++ u32 pacing_gain:10, /* current gain for setting pacing rate */ ++ cwnd_gain:10, /* current gain for setting cwnd */ ++ full_bw_reached:1, /* reached full bw in Startup? */ ++ full_bw_cnt:2, /* number of rounds without large bw gains */ ++ cycle_idx:2, /* current index in pacing_gain cycle array */ ++ has_seen_rtt:1, /* have we seen an RTT sample yet? */ ++ unused_2:6; ++ u32 prior_cwnd; /* prior cwnd upon entering loss recovery */ ++ u32 full_bw; /* recent bw, to estimate if pipe is full */ ++ ++ /* For tracking ACK aggregation: */ ++ u64 ack_epoch_mstamp; /* start of ACK sampling epoch */ ++ u16 extra_acked[2]; /* max excess data ACKed in epoch */ ++ u32 ack_epoch_acked:20, /* packets (S)ACKed in sampling epoch */ ++ extra_acked_win_rtts:5, /* age of extra_acked, in round trips */ ++ extra_acked_win_idx:1, /* current index in extra_acked array */ ++ /* BBR v3 state: */ ++ full_bw_now:1, /* recently reached full bw plateau? */ ++ startup_ecn_rounds:2, /* consecutive hi ECN STARTUP rounds */ ++ loss_in_cycle:1, /* packet loss in this cycle? */ ++ ecn_in_cycle:1, /* ECN in this cycle? */ ++ unused_3:1; ++ u32 loss_round_delivered; /* scb->tx.delivered ending loss round */ ++ u32 undo_bw_lo; /* bw_lo before latest losses */ ++ u32 undo_inflight_lo; /* inflight_lo before latest losses */ ++ u32 undo_inflight_hi; /* inflight_hi before latest losses */ ++ u32 bw_latest; /* max delivered bw in last round trip */ ++ u32 bw_lo; /* lower bound on sending bandwidth */ ++ u32 bw_hi[2]; /* max recent measured bw sample */ ++ u32 inflight_latest; /* max delivered data in last round trip */ ++ u32 inflight_lo; /* lower bound of inflight data range */ ++ u32 inflight_hi; /* upper bound of inflight data range */ ++ u32 bw_probe_up_cnt; /* packets delivered per inflight_hi incr */ ++ u32 bw_probe_up_acks; /* packets (S)ACKed since inflight_hi incr */ ++ u32 probe_wait_us; /* PROBE_DOWN until next clock-driven probe */ ++ u32 prior_rcv_nxt; /* tp->rcv_nxt when CE state last changed */ ++ u32 ecn_eligible:1, /* sender can use ECN (RTT, handshake)? */ ++ ecn_alpha:9, /* EWMA delivered_ce/delivered; 0..256 */ ++ bw_probe_samples:1, /* rate samples reflect bw probing? */ ++ prev_probe_too_high:1, /* did last PROBE_UP go too high? */ ++ stopped_risky_probe:1, /* last PROBE_UP stopped due to risk? */ ++ rounds_since_probe:8, /* packet-timed rounds since probed bw */ ++ loss_round_start:1, /* loss_round_delivered round trip? */ ++ loss_in_round:1, /* loss marked in this round trip? */ ++ ecn_in_round:1, /* ECN marked in this round trip? */ ++ ack_phase:3, /* bbr_ack_phase: meaning of ACKs */ ++ loss_events_in_round:4,/* losses in STARTUP round */ ++ initialized:1; /* has bbr_init() been called? */ ++ u32 alpha_last_delivered; /* tp->delivered at alpha update */ ++ u32 alpha_last_delivered_ce; /* tp->delivered_ce at alpha update */ ++ ++ u8 unused_4; /* to preserve alignment */ ++ struct tcp_plb_state plb; ++}; ++ ++struct bbr_context { ++ u32 sample_bw; ++}; ++ ++/* Window length of min_rtt filter (in sec): */ ++static const u32 bbr_min_rtt_win_sec = 10; ++/* Minimum time (in ms) spent at bbr_cwnd_min_target in BBR_PROBE_RTT mode: */ ++static const u32 bbr_probe_rtt_mode_ms = 200; ++/* Window length of probe_rtt_min_us filter (in ms), and consequently the ++ * typical interval between PROBE_RTT mode entries. The default is 5000ms. ++ * Note that bbr_probe_rtt_win_ms must be <= bbr_min_rtt_win_sec * MSEC_PER_SEC ++ */ ++static const u32 bbr_probe_rtt_win_ms = 5000; ++/* Proportion of cwnd to estimated BDP in PROBE_RTT, in units of BBR_UNIT: */ ++static const u32 bbr_probe_rtt_cwnd_gain = BBR_UNIT * 1 / 2; ++ ++/* Use min_rtt to help adapt TSO burst size, with smaller min_rtt resulting ++ * in bigger TSO bursts. We cut the RTT-based allowance in half ++ * for every 2^9 usec (aka 512 us) of RTT, so that the RTT-based allowance ++ * is below 1500 bytes after 6 * ~500 usec = 3ms. ++ */ ++static const u32 bbr_tso_rtt_shift = 9; ++ ++/* Pace at ~1% below estimated bw, on average, to reduce queue at bottleneck. ++ * In order to help drive the network toward lower queues and low latency while ++ * maintaining high utilization, the average pacing rate aims to be slightly ++ * lower than the estimated bandwidth. This is an important aspect of the ++ * design. ++ */ ++static const int bbr_pacing_margin_percent = 1; ++ ++/* We use a startup_pacing_gain of 4*ln(2) because it's the smallest value ++ * that will allow a smoothly increasing pacing rate that will double each RTT ++ * and send the same number of packets per RTT that an un-paced, slow-starting ++ * Reno or CUBIC flow would: ++ */ ++static const int bbr_startup_pacing_gain = BBR_UNIT * 277 / 100 + 1; ++/* The gain for deriving startup cwnd: */ ++static const int bbr_startup_cwnd_gain = BBR_UNIT * 2; ++/* The pacing gain in BBR_DRAIN is calculated to typically drain ++ * the queue created in BBR_STARTUP in a single round: ++ */ ++static const int bbr_drain_gain = BBR_UNIT * 1000 / 2885; ++/* The gain for deriving steady-state cwnd tolerates delayed/stretched ACKs: */ ++static const int bbr_cwnd_gain = BBR_UNIT * 2; ++/* The pacing_gain values for the PROBE_BW gain cycle, to discover/share bw: */ ++static const int bbr_pacing_gain[] = { ++ BBR_UNIT * 5 / 4, /* UP: probe for more available bw */ ++ BBR_UNIT * 91 / 100, /* DOWN: drain queue and/or yield bw */ ++ BBR_UNIT, /* CRUISE: try to use pipe w/ some headroom */ ++ BBR_UNIT, /* REFILL: refill pipe to estimated 100% */ ++}; ++enum bbr_pacing_gain_phase { ++ BBR_BW_PROBE_UP = 0, /* push up inflight to probe for bw/vol */ ++ BBR_BW_PROBE_DOWN = 1, /* drain excess inflight from the queue */ ++ BBR_BW_PROBE_CRUISE = 2, /* use pipe, w/ headroom in queue/pipe */ ++ BBR_BW_PROBE_REFILL = 3, /* refill the pipe again to 100% */ ++}; ++ ++/* Try to keep at least this many packets in flight, if things go smoothly. For ++ * smooth functioning, a sliding window protocol ACKing every other packet ++ * needs at least 4 packets in flight: ++ */ ++static const u32 bbr_cwnd_min_target = 4; ++ ++/* To estimate if BBR_STARTUP or BBR_BW_PROBE_UP has filled pipe... */ ++/* If bw has increased significantly (1.25x), there may be more bw available: */ ++static const u32 bbr_full_bw_thresh = BBR_UNIT * 5 / 4; ++/* But after 3 rounds w/o significant bw growth, estimate pipe is full: */ ++static const u32 bbr_full_bw_cnt = 3; ++ ++/* Gain factor for adding extra_acked to target cwnd: */ ++static const int bbr_extra_acked_gain = BBR_UNIT; ++/* Window length of extra_acked window. */ ++static const u32 bbr_extra_acked_win_rtts = 5; ++/* Max allowed val for ack_epoch_acked, after which sampling epoch is reset */ ++static const u32 bbr_ack_epoch_acked_reset_thresh = 1U << 20; ++/* Time period for clamping cwnd increment due to ack aggregation */ ++static const u32 bbr_extra_acked_max_us = 100 * 1000; ++ ++/* Flags to control BBR ECN-related behavior... */ ++ ++/* Ensure ACKs only ACK packets with consistent ECN CE status? */ ++static const bool bbr_precise_ece_ack = true; ++ ++/* Max RTT (in usec) at which to use sender-side ECN logic. ++ * Disabled when 0 (ECN allowed at any RTT). ++ */ ++static const u32 bbr_ecn_max_rtt_us = 5000; ++ ++/* On losses, scale down inflight and pacing rate by beta scaled by BBR_SCALE. ++ * No loss response when 0. ++ */ ++static const u32 bbr_beta = BBR_UNIT * 30 / 100; ++ ++/* Gain factor for ECN mark ratio samples, scaled by BBR_SCALE (1/16 = 6.25%) */ ++static const u32 bbr_ecn_alpha_gain = BBR_UNIT * 1 / 16; ++ ++/* The initial value for ecn_alpha; 1.0 allows a flow to respond quickly ++ * to congestion if the bottleneck is congested when the flow starts up. ++ */ ++static const u32 bbr_ecn_alpha_init = BBR_UNIT; ++ ++/* On ECN, cut inflight_lo to (1 - ecn_factor * ecn_alpha) scaled by BBR_SCALE. ++ * No ECN based bounding when 0. ++ */ ++static const u32 bbr_ecn_factor = BBR_UNIT * 1 / 3; /* 1/3 = 33% */ ++ ++/* Estimate bw probing has gone too far if CE ratio exceeds this threshold. ++ * Scaled by BBR_SCALE. Disabled when 0. ++ */ ++static const u32 bbr_ecn_thresh = BBR_UNIT * 1 / 2; /* 1/2 = 50% */ ++ ++/* If non-zero, if in a cycle with no losses but some ECN marks, after ECN ++ * clears then make the first round's increment to inflight_hi the following ++ * fraction of inflight_hi. ++ */ ++static const u32 bbr_ecn_reprobe_gain = BBR_UNIT * 1 / 2; ++ ++/* Estimate bw probing has gone too far if loss rate exceeds this level. */ ++static const u32 bbr_loss_thresh = BBR_UNIT * 2 / 100; /* 2% loss */ ++ ++/* Slow down for a packet loss recovered by TLP? */ ++static const bool bbr_loss_probe_recovery = true; ++ ++/* Exit STARTUP if number of loss marking events in a Recovery round is >= N, ++ * and loss rate is higher than bbr_loss_thresh. ++ * Disabled if 0. ++ */ ++static const u32 bbr_full_loss_cnt = 6; ++ ++/* Exit STARTUP if number of round trips with ECN mark rate above ecn_thresh ++ * meets this count. ++ */ ++static const u32 bbr_full_ecn_cnt = 2; ++ ++/* Fraction of unutilized headroom to try to leave in path upon high loss. */ ++static const u32 bbr_inflight_headroom = BBR_UNIT * 15 / 100; ++ ++/* How much do we increase cwnd_gain when probing for bandwidth in ++ * BBR_BW_PROBE_UP? This specifies the increment in units of ++ * BBR_UNIT/4. The default is 1, meaning 0.25. ++ * The min value is 0 (meaning 0.0); max is 3 (meaning 0.75). ++ */ ++static const u32 bbr_bw_probe_cwnd_gain = 1; ++ ++/* Max number of packet-timed rounds to wait before probing for bandwidth. If ++ * we want to tolerate 1% random loss per round, and not have this cut our ++ * inflight too much, we must probe for bw periodically on roughly this scale. ++ * If low, limits Reno/CUBIC coexistence; if high, limits loss tolerance. ++ * We aim to be fair with Reno/CUBIC up to a BDP of at least: ++ * BDP = 25Mbps * .030sec /(1514bytes) = 61.9 packets ++ */ ++static const u32 bbr_bw_probe_max_rounds = 63; ++ ++/* Max amount of randomness to inject in round counting for Reno-coexistence. ++ */ ++static const u32 bbr_bw_probe_rand_rounds = 2; ++ ++/* Use BBR-native probe time scale starting at this many usec. ++ * We aim to be fair with Reno/CUBIC up to an inter-loss time epoch of at least: ++ * BDP*RTT = 25Mbps * .030sec /(1514bytes) * 0.030sec = 1.9 secs ++ */ ++static const u32 bbr_bw_probe_base_us = 2 * USEC_PER_SEC; /* 2 secs */ ++ ++/* Use BBR-native probes spread over this many usec: */ ++static const u32 bbr_bw_probe_rand_us = 1 * USEC_PER_SEC; /* 1 secs */ ++ ++/* Use fast path if app-limited, no loss/ECN, and target cwnd was reached? */ ++static const bool bbr_fast_path = true; ++ ++/* Use fast ack mode? */ ++static const bool bbr_fast_ack_mode = true; ++ ++static u32 bbr_max_bw(const struct sock *sk); ++static u32 bbr_bw(const struct sock *sk); ++static void bbr_exit_probe_rtt(struct sock *sk); ++static void bbr_reset_congestion_signals(struct sock *sk); ++static void bbr_run_loss_probe_recovery(struct sock *sk); ++ ++static void bbr_check_probe_rtt_done(struct sock *sk); ++ ++/* This connection can use ECN if both endpoints have signaled ECN support in ++ * the handshake and the per-route settings indicated this is a ++ * shallow-threshold ECN environment, meaning both: ++ * (a) ECN CE marks indicate low-latency/shallow-threshold congestion, and ++ * (b) TCP endpoints provide precise ACKs that only ACK data segments ++ * with consistent ECN CE status ++ */ ++static bool bbr_can_use_ecn(const struct sock *sk) ++{ ++ const struct tcp_sock *tp = tcp_sk(sk); ++ ++ return tcp_ecn_mode_any(tp) && ++ (tcp_sk(sk)->ecn_flags & TCP_ECN_LOW); ++} ++ ++/* Do we estimate that STARTUP filled the pipe? */ ++static bool bbr_full_bw_reached(const struct sock *sk) ++{ ++ const struct bbr *bbr = inet_csk_ca(sk); ++ ++ return bbr->full_bw_reached; ++} ++ ++/* Return the windowed max recent bandwidth sample, in pkts/uS << BW_SCALE. */ ++static u32 bbr_max_bw(const struct sock *sk) ++{ ++ const struct bbr *bbr = inet_csk_ca(sk); ++ ++ return max(bbr->bw_hi[0], bbr->bw_hi[1]); ++} ++ ++/* Return the estimated bandwidth of the path, in pkts/uS << BW_SCALE. */ ++static u32 bbr_bw(const struct sock *sk) ++{ ++ const struct bbr *bbr = inet_csk_ca(sk); ++ ++ return min(bbr_max_bw(sk), bbr->bw_lo); ++} ++ ++/* Return maximum extra acked in past k-2k round trips, ++ * where k = bbr_extra_acked_win_rtts. ++ */ ++static u16 bbr_extra_acked(const struct sock *sk) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ return max(bbr->extra_acked[0], bbr->extra_acked[1]); ++} ++ ++/* Return rate in bytes per second, optionally with a gain. ++ * The order here is chosen carefully to avoid overflow of u64. This should ++ * work for input rates of up to 2.9Tbit/sec and gain of 2.89x. ++ */ ++static u64 bbr_rate_bytes_per_sec(struct sock *sk, u64 rate, int gain, ++ int margin) ++{ ++ unsigned int mss = tcp_sk(sk)->mss_cache; ++ ++ rate *= mss; ++ rate *= gain; ++ rate >>= BBR_SCALE; ++ rate *= USEC_PER_SEC / 100 * (100 - margin); ++ rate >>= BW_SCALE; ++ rate = max(rate, 1ULL); ++ return rate; ++} ++ ++static u64 bbr_bw_bytes_per_sec(struct sock *sk, u64 rate) ++{ ++ return bbr_rate_bytes_per_sec(sk, rate, BBR_UNIT, 0); ++} ++ ++/* Convert a BBR bw and gain factor to a pacing rate in bytes per second. */ ++static unsigned long bbr_bw_to_pacing_rate(struct sock *sk, u32 bw, int gain) ++{ ++ u64 rate = bw; ++ ++ rate = bbr_rate_bytes_per_sec(sk, rate, gain, ++ bbr_pacing_margin_percent); ++ rate = min_t(u64, rate, READ_ONCE(sk->sk_max_pacing_rate)); ++ return rate; ++} ++ ++/* Initialize pacing rate to: startup_pacing_gain * init_cwnd / RTT. */ ++static void bbr_init_pacing_rate_from_rtt(struct sock *sk) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ u64 bw; ++ u32 rtt_us; ++ ++ if (tp->srtt_us) { /* any RTT sample yet? */ ++ rtt_us = max(tp->srtt_us >> 3, 1U); ++ bbr->has_seen_rtt = 1; ++ } else { /* no RTT sample yet */ ++ rtt_us = USEC_PER_MSEC; /* use nominal default RTT */ ++ } ++ bw = (u64)tcp_snd_cwnd(tp) * BW_UNIT; ++ do_div(bw, rtt_us); ++ WRITE_ONCE(sk->sk_pacing_rate, ++ bbr_bw_to_pacing_rate(sk, bw, ++ bbr_param(sk, startup_pacing_gain))); ++} ++ ++/* Pace using current bw estimate and a gain factor. */ ++static void bbr_set_pacing_rate(struct sock *sk, u32 bw, int gain) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ unsigned long rate = bbr_bw_to_pacing_rate(sk, bw, gain); ++ ++ if (unlikely(!bbr->has_seen_rtt && tp->srtt_us)) ++ bbr_init_pacing_rate_from_rtt(sk); ++ if (bbr_full_bw_reached(sk) || rate > READ_ONCE(sk->sk_pacing_rate)) ++ WRITE_ONCE(sk->sk_pacing_rate, rate); ++} ++ ++/* Return the number of segments BBR would like in a TSO/GSO skb, given a ++ * particular max gso size as a constraint. TODO: make this simpler and more ++ * consistent by switching bbr to just call tcp_tso_autosize(). ++ */ ++static u32 bbr_tso_segs_generic(struct sock *sk, unsigned int mss_now, ++ u32 gso_max_size) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ u32 segs, r; ++ u64 bytes; ++ ++ /* Budget a TSO/GSO burst size allowance based on bw (pacing_rate). */ ++ bytes = READ_ONCE(sk->sk_pacing_rate) >> READ_ONCE(sk->sk_pacing_shift); ++ ++ /* Budget a TSO/GSO burst size allowance based on min_rtt. For every ++ * K = 2^tso_rtt_shift microseconds of min_rtt, halve the burst. ++ * The min_rtt-based burst allowance is: 64 KBytes / 2^(min_rtt/K) ++ */ ++ if (bbr_param(sk, tso_rtt_shift)) { ++ r = bbr->min_rtt_us >> bbr_param(sk, tso_rtt_shift); ++ if (r < BITS_PER_TYPE(u32)) /* prevent undefined behavior */ ++ bytes += GSO_LEGACY_MAX_SIZE >> r; ++ } ++ ++ bytes = min_t(u32, bytes, gso_max_size - 1 - MAX_TCP_HEADER); ++ segs = max_t(u32, bytes / mss_now, ++ sock_net(sk)->ipv4.sysctl_tcp_min_tso_segs); ++ return segs; ++} ++ ++/* Custom tcp_tso_autosize() for BBR, used at transmit time to cap skb size. */ ++__bpf_kfunc static u32 bbr_tso_segs(struct sock *sk, unsigned int mss_now) ++{ ++ return bbr_tso_segs_generic(sk, mss_now, sk->sk_gso_max_size); ++} ++ ++/* Like bbr_tso_segs(), using mss_cache, ignoring driver's sk_gso_max_size. */ ++static u32 bbr_tso_segs_goal(struct sock *sk) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ ++ return bbr_tso_segs_generic(sk, tp->mss_cache, GSO_LEGACY_MAX_SIZE); ++} ++ ++/* Save "last known good" cwnd so we can restore it after losses or PROBE_RTT */ ++static void bbr_save_cwnd(struct sock *sk) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ if (bbr->prev_ca_state < TCP_CA_Recovery && bbr->mode != BBR_PROBE_RTT) ++ bbr->prior_cwnd = tcp_snd_cwnd(tp); /* this cwnd is good enough */ ++ else /* loss recovery or BBR_PROBE_RTT have temporarily cut cwnd */ ++ bbr->prior_cwnd = max(bbr->prior_cwnd, tcp_snd_cwnd(tp)); ++} ++ ++__bpf_kfunc static void bbr_cwnd_event(struct sock *sk, enum tcp_ca_event event) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ if ((event == CA_EVENT_ECN_IS_CE || ++ event == CA_EVENT_ECN_NO_CE) && ++ bbr_can_use_ecn(sk) && ++ bbr_param(sk, precise_ece_ack)) { ++ u32 state = bbr->ce_state; ++ dctcp_ece_ack_update(sk, event, &bbr->prior_rcv_nxt, &state); ++ bbr->ce_state = state; ++ } else if (event == CA_EVENT_TLP_RECOVERY && ++ bbr_param(sk, loss_probe_recovery)) { ++ bbr_run_loss_probe_recovery(sk); ++ } ++} ++ ++__bpf_kfunc static void bbr_cwnd_event_tx_start(struct sock *sk) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ if (tp->app_limited) { ++ bbr->idle_restart = 1; ++ bbr->ack_epoch_mstamp = tp->tcp_mstamp; ++ bbr->ack_epoch_acked = 0; ++ /* Avoid pointless buffer overflows: pace at est. bw if we don't ++ * need more speed (we're restarting from idle and app-limited). ++ */ ++ if (bbr->mode == BBR_PROBE_BW) ++ bbr_set_pacing_rate(sk, bbr_bw(sk), BBR_UNIT); ++ else if (bbr->mode == BBR_PROBE_RTT) ++ bbr_check_probe_rtt_done(sk); ++ } ++} ++ ++/* Calculate bdp based on min RTT and the estimated bottleneck bandwidth: ++ * ++ * bdp = ceil(bw * min_rtt * gain) ++ * ++ * The key factor, gain, controls the amount of queue. While a small gain ++ * builds a smaller queue, it becomes more vulnerable to noise in RTT ++ * measurements (e.g., delayed ACKs or other ACK compression effects). This ++ * noise may cause BBR to under-estimate the rate. ++ */ ++static u32 bbr_bdp(struct sock *sk, u32 bw, int gain) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ u32 bdp; ++ u64 w; ++ ++ /* If we've never had a valid RTT sample, cap cwnd at the initial ++ * default. This should only happen when the connection is not using TCP ++ * timestamps and has retransmitted all of the SYN/SYNACK/data packets ++ * ACKed so far. In this case, an RTO can cut cwnd to 1, in which ++ * case we need to slow-start up toward something safe: initial cwnd. ++ */ ++ if (unlikely(bbr->min_rtt_us == ~0U)) /* no valid RTT samples yet? */ ++ return bbr->init_cwnd; /* be safe: cap at initial cwnd */ ++ ++ w = (u64)bw * bbr->min_rtt_us; ++ ++ /* Apply a gain to the given value, remove the BW_SCALE shift, and ++ * round the value up to avoid a negative feedback loop. ++ */ ++ bdp = (((w * gain) >> BBR_SCALE) + BW_UNIT - 1) / BW_UNIT; ++ ++ return bdp; ++} ++ ++/* To achieve full performance in high-speed paths, we budget enough cwnd to ++ * fit full-sized skbs in-flight on both end hosts to fully utilize the path: ++ * - one skb in sending host Qdisc, ++ * - one skb in sending host TSO/GSO engine ++ * - one skb being received by receiver host LRO/GRO/delayed-ACK engine ++ * Don't worry, at low rates this won't bloat cwnd because ++ * in such cases tso_segs_goal is small. The minimum cwnd is 4 packets, ++ * which allows 2 outstanding 2-packet sequences, to try to keep pipe ++ * full even with ACK-every-other-packet delayed ACKs. ++ */ ++static u32 bbr_quantization_budget(struct sock *sk, u32 cwnd) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ u32 tso_segs_goal; ++ ++ tso_segs_goal = 3 * bbr_tso_segs_goal(sk); ++ ++ /* Allow enough full-sized skbs in flight to utilize end systems. */ ++ cwnd = max_t(u32, cwnd, tso_segs_goal); ++ cwnd = max_t(u32, cwnd, bbr_param(sk, cwnd_min_target)); ++ /* Ensure gain cycling gets inflight above BDP even for small BDPs. */ ++ if (bbr->mode == BBR_PROBE_BW && bbr->cycle_idx == BBR_BW_PROBE_UP) ++ cwnd += 2; ++ ++ return cwnd; ++} ++ ++/* Find inflight based on min RTT and the estimated bottleneck bandwidth. */ ++static u32 bbr_inflight(struct sock *sk, u32 bw, int gain) ++{ ++ u32 inflight; ++ ++ inflight = bbr_bdp(sk, bw, gain); ++ inflight = bbr_quantization_budget(sk, inflight); ++ ++ return inflight; ++} ++ ++/* With pacing at lower layers, there's often less data "in the network" than ++ * "in flight". With TSQ and departure time pacing at lower layers (e.g. fq), ++ * we often have several skbs queued in the pacing layer with a pre-scheduled ++ * earliest departure time (EDT). BBR adapts its pacing rate based on the ++ * inflight level that it estimates has already been "baked in" by previous ++ * departure time decisions. We calculate a rough estimate of the number of our ++ * packets that might be in the network at the earliest departure time for the ++ * next skb scheduled: ++ * in_network_at_edt = inflight_at_edt - (EDT - now) * bw ++ * If we're increasing inflight, then we want to know if the transmit of the ++ * EDT skb will push inflight above the target, so inflight_at_edt includes ++ * bbr_tso_segs_goal() from the skb departing at EDT. If decreasing inflight, ++ * then estimate if inflight will sink too low just before the EDT transmit. ++ */ ++static u32 bbr_packets_in_net_at_edt(struct sock *sk, u32 inflight_now) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ u64 now_ns, edt_ns, interval_us; ++ u32 interval_delivered, inflight_at_edt; ++ ++ now_ns = tp->tcp_clock_cache; ++ edt_ns = max(tp->tcp_wstamp_ns, now_ns); ++ interval_us = div_u64(edt_ns - now_ns, NSEC_PER_USEC); ++ interval_delivered = (u64)bbr_bw(sk) * interval_us >> BW_SCALE; ++ inflight_at_edt = inflight_now; ++ if (bbr->pacing_gain > BBR_UNIT) /* increasing inflight */ ++ inflight_at_edt += bbr_tso_segs_goal(sk); /* include EDT skb */ ++ if (interval_delivered >= inflight_at_edt) ++ return 0; ++ return inflight_at_edt - interval_delivered; ++} ++ ++/* Find the cwnd increment based on estimate of ack aggregation */ ++static u32 bbr_ack_aggregation_cwnd(struct sock *sk) ++{ ++ u32 max_aggr_cwnd, aggr_cwnd = 0; ++ ++ if (bbr_param(sk, extra_acked_gain)) { ++ max_aggr_cwnd = ((u64)bbr_bw(sk) * bbr_extra_acked_max_us) ++ / BW_UNIT; ++ aggr_cwnd = (bbr_param(sk, extra_acked_gain) * bbr_extra_acked(sk)) ++ >> BBR_SCALE; ++ aggr_cwnd = min(aggr_cwnd, max_aggr_cwnd); ++ } ++ ++ return aggr_cwnd; ++} ++ ++/* Returns the cwnd for PROBE_RTT mode. */ ++static u32 bbr_probe_rtt_cwnd(struct sock *sk) ++{ ++ return max_t(u32, bbr_param(sk, cwnd_min_target), ++ bbr_bdp(sk, bbr_bw(sk), bbr_param(sk, probe_rtt_cwnd_gain))); ++} ++ ++/* Slow-start up toward target cwnd (if bw estimate is growing, or packet loss ++ * has drawn us down below target), or snap down to target if we're above it. ++ */ ++static void bbr_set_cwnd(struct sock *sk, const struct rate_sample *rs, ++ u32 acked, u32 bw, int gain, u32 cwnd, ++ struct bbr_context *ctx) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ u32 target_cwnd = 0; ++ ++ if (!acked) ++ goto done; /* no packet fully ACKed; just apply caps */ ++ ++ target_cwnd = bbr_bdp(sk, bw, gain); ++ ++ /* Increment the cwnd to account for excess ACKed data that seems ++ * due to aggregation (of data and/or ACKs) visible in the ACK stream. ++ */ ++ target_cwnd += bbr_ack_aggregation_cwnd(sk); ++ target_cwnd = bbr_quantization_budget(sk, target_cwnd); ++ ++ /* Update cwnd and enable fast path if cwnd reaches target_cwnd. */ ++ bbr->try_fast_path = 0; ++ if (bbr_full_bw_reached(sk)) { /* only cut cwnd if we filled the pipe */ ++ cwnd += acked; ++ if (cwnd >= target_cwnd) { ++ cwnd = target_cwnd; ++ bbr->try_fast_path = 1; ++ } ++ } else if (cwnd < target_cwnd || cwnd < 2 * bbr->init_cwnd) { ++ cwnd += acked; ++ } else { ++ bbr->try_fast_path = 1; ++ } ++ ++ cwnd = max_t(u32, cwnd, bbr_param(sk, cwnd_min_target)); ++done: ++ tcp_snd_cwnd_set(tp, min(cwnd, tp->snd_cwnd_clamp)); /* global cap */ ++ if (bbr->mode == BBR_PROBE_RTT) /* drain queue, refresh min_rtt */ ++ tcp_snd_cwnd_set(tp, min_t(u32, tcp_snd_cwnd(tp), ++ bbr_probe_rtt_cwnd(sk))); ++} ++ ++static void bbr_reset_startup_mode(struct sock *sk) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ bbr->mode = BBR_STARTUP; ++} ++ ++/* See if we have reached next round trip. Upon start of the new round, ++ * returns packets delivered since previous round start plus this ACK. ++ */ ++static u32 bbr_update_round_start(struct sock *sk, ++ const struct rate_sample *rs, struct bbr_context *ctx) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ u32 round_delivered = 0; ++ ++ bbr->round_start = 0; ++ ++ /* See if we've reached the next RTT */ ++ if (rs->interval_us > 0 && ++ !before(rs->prior_delivered, bbr->next_rtt_delivered)) { ++ round_delivered = tp->delivered - bbr->next_rtt_delivered; ++ bbr->next_rtt_delivered = tp->delivered; ++ bbr->round_start = 1; ++ } ++ return round_delivered; ++} ++ ++/* Calculate the bandwidth based on how fast packets are delivered */ ++static void bbr_calculate_bw_sample(struct sock *sk, ++ const struct rate_sample *rs, struct bbr_context *ctx) ++{ ++ u64 bw = 0; ++ ++ /* Divide delivered by the interval to find a (lower bound) bottleneck ++ * bandwidth sample. Delivered is in packets and interval_us in uS and ++ * ratio will be <<1 for most connections. So delivered is first scaled. ++ * Round up to allow growth at low rates, even with integer division. ++ */ ++ if (rs->interval_us > 0) { ++ if (WARN_ONCE(rs->delivered < 0, ++ "negative delivered: %d interval_us: %ld\n", ++ rs->delivered, rs->interval_us)) ++ return; ++ ++ bw = DIV_ROUND_UP_ULL((u64)rs->delivered * BW_UNIT, rs->interval_us); ++ } ++ ++ ctx->sample_bw = bw; ++} ++ ++/* Estimates the windowed max degree of ack aggregation. ++ * This is used to provision extra in-flight data to keep sending during ++ * inter-ACK silences. ++ * ++ * Degree of ack aggregation is estimated as extra data acked beyond expected. ++ * ++ * max_extra_acked = "maximum recent excess data ACKed beyond max_bw * interval" ++ * cwnd += max_extra_acked ++ * ++ * Max extra_acked is clamped by cwnd and bw * bbr_extra_acked_max_us (100 ms). ++ * Max filter is an approximate sliding window of 5-10 (packet timed) round ++ * trips for non-startup phase, and 1-2 round trips for startup. ++ */ ++static void bbr_update_ack_aggregation(struct sock *sk, ++ const struct rate_sample *rs) ++{ ++ u32 epoch_us, expected_acked, extra_acked; ++ struct bbr *bbr = inet_csk_ca(sk); ++ struct tcp_sock *tp = tcp_sk(sk); ++ u32 extra_acked_win_rtts_thresh = bbr_param(sk, extra_acked_win_rtts); ++ ++ if (!bbr_param(sk, extra_acked_gain) || rs->acked_sacked <= 0 || ++ rs->delivered < 0 || rs->interval_us <= 0) ++ return; ++ ++ if (bbr->round_start) { ++ bbr->extra_acked_win_rtts = min(0x1F, ++ bbr->extra_acked_win_rtts + 1); ++ if (!bbr_full_bw_reached(sk)) ++ extra_acked_win_rtts_thresh = 1; ++ if (bbr->extra_acked_win_rtts >= ++ extra_acked_win_rtts_thresh) { ++ bbr->extra_acked_win_rtts = 0; ++ bbr->extra_acked_win_idx = bbr->extra_acked_win_idx ? ++ 0 : 1; ++ bbr->extra_acked[bbr->extra_acked_win_idx] = 0; ++ } ++ } ++ ++ /* Compute how many packets we expected to be delivered over epoch. */ ++ epoch_us = tcp_stamp_us_delta(tp->delivered_mstamp, ++ bbr->ack_epoch_mstamp); ++ expected_acked = ((u64)bbr_bw(sk) * epoch_us) / BW_UNIT; ++ ++ /* Reset the aggregation epoch if ACK rate is below expected rate or ++ * significantly large no. of ack received since epoch (potentially ++ * quite old epoch). ++ */ ++ if (bbr->ack_epoch_acked <= expected_acked || ++ (bbr->ack_epoch_acked + rs->acked_sacked >= ++ bbr_ack_epoch_acked_reset_thresh)) { ++ bbr->ack_epoch_acked = 0; ++ bbr->ack_epoch_mstamp = tp->delivered_mstamp; ++ expected_acked = 0; ++ } ++ ++ /* Compute excess data delivered, beyond what was expected. */ ++ bbr->ack_epoch_acked = min_t(u32, 0xFFFFF, ++ bbr->ack_epoch_acked + rs->acked_sacked); ++ extra_acked = bbr->ack_epoch_acked - expected_acked; ++ extra_acked = min(extra_acked, tcp_snd_cwnd(tp)); ++ if (extra_acked > bbr->extra_acked[bbr->extra_acked_win_idx]) ++ bbr->extra_acked[bbr->extra_acked_win_idx] = extra_acked; ++} ++ ++static void bbr_check_probe_rtt_done(struct sock *sk) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ if (!(bbr->probe_rtt_done_stamp && ++ after(tcp_jiffies32, bbr->probe_rtt_done_stamp))) ++ return; ++ ++ bbr->probe_rtt_min_stamp = tcp_jiffies32; /* schedule next PROBE_RTT */ ++ tcp_snd_cwnd_set(tp, max(tcp_snd_cwnd(tp), bbr->prior_cwnd)); ++ bbr_exit_probe_rtt(sk); ++} ++ ++/* The goal of PROBE_RTT mode is to have BBR flows cooperatively and ++ * periodically drain the bottleneck queue, to converge to measure the true ++ * min_rtt (unloaded propagation delay). This allows the flows to keep queues ++ * small (reducing queuing delay and packet loss) and achieve fairness among ++ * BBR flows. ++ * ++ * The min_rtt filter window is 10 seconds. When the min_rtt estimate expires, ++ * we enter PROBE_RTT mode and cap the cwnd at bbr_cwnd_min_target=4 packets. ++ * After at least bbr_probe_rtt_mode_ms=200ms and at least one packet-timed ++ * round trip elapsed with that flight size <= 4, we leave PROBE_RTT mode and ++ * re-enter the previous mode. BBR uses 200ms to approximately bound the ++ * performance penalty of PROBE_RTT's cwnd capping to roughly 2% (200ms/10s). ++ * ++ * Note that flows need only pay 2% if they are busy sending over the last 10 ++ * seconds. Interactive applications (e.g., Web, RPCs, video chunks) often have ++ * natural silences or low-rate periods within 10 seconds where the rate is low ++ * enough for long enough to drain its queue in the bottleneck. We pick up ++ * these min RTT measurements opportunistically with our min_rtt filter. :-) ++ */ ++static void bbr_update_min_rtt(struct sock *sk, const struct rate_sample *rs) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ bool probe_rtt_expired, min_rtt_expired; ++ u32 expire; ++ ++ /* Track min RTT in probe_rtt_win_ms to time next PROBE_RTT state. */ ++ expire = bbr->probe_rtt_min_stamp + ++ msecs_to_jiffies(bbr_param(sk, probe_rtt_win_ms)); ++ probe_rtt_expired = after(tcp_jiffies32, expire); ++ if (rs->rtt_us >= 0 && ++ (rs->rtt_us < bbr->probe_rtt_min_us || ++ (probe_rtt_expired && !rs->is_ack_delayed))) { ++ bbr->probe_rtt_min_us = rs->rtt_us; ++ bbr->probe_rtt_min_stamp = tcp_jiffies32; ++ } ++ /* Track min RTT seen in the min_rtt_win_sec filter window: */ ++ expire = bbr->min_rtt_stamp + bbr_param(sk, min_rtt_win_sec) * HZ; ++ min_rtt_expired = after(tcp_jiffies32, expire); ++ if (bbr->probe_rtt_min_us <= bbr->min_rtt_us || ++ min_rtt_expired) { ++ bbr->min_rtt_us = bbr->probe_rtt_min_us; ++ bbr->min_rtt_stamp = bbr->probe_rtt_min_stamp; ++ } ++ ++ if (bbr_param(sk, probe_rtt_mode_ms) > 0 && probe_rtt_expired && ++ !bbr->idle_restart && bbr->mode != BBR_PROBE_RTT) { ++ bbr->mode = BBR_PROBE_RTT; /* dip, drain queue */ ++ bbr_save_cwnd(sk); /* note cwnd so we can restore it */ ++ bbr->probe_rtt_done_stamp = 0; ++ bbr->ack_phase = BBR_ACKS_PROBE_STOPPING; ++ bbr->next_rtt_delivered = tp->delivered; ++ } ++ ++ if (bbr->mode == BBR_PROBE_RTT) { ++ /* Ignore low rate samples during this mode. */ ++ tp->app_limited = ++ (tp->delivered + tcp_packets_in_flight(tp)) ? : 1; ++ /* Maintain min packets in flight for max(200 ms, 1 round). */ ++ if (!bbr->probe_rtt_done_stamp && ++ tcp_packets_in_flight(tp) <= bbr_probe_rtt_cwnd(sk)) { ++ bbr->probe_rtt_done_stamp = tcp_jiffies32 + ++ msecs_to_jiffies(bbr_param(sk, probe_rtt_mode_ms)); ++ bbr->probe_rtt_round_done = 0; ++ bbr->next_rtt_delivered = tp->delivered; ++ } else if (bbr->probe_rtt_done_stamp) { ++ if (bbr->round_start) ++ bbr->probe_rtt_round_done = 1; ++ if (bbr->probe_rtt_round_done) ++ bbr_check_probe_rtt_done(sk); ++ } ++ } ++ /* Restart after idle ends only once we process a new S/ACK for data */ ++ if (rs->delivered > 0) ++ bbr->idle_restart = 0; ++} ++ ++static void bbr_update_gains(struct sock *sk) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ switch (bbr->mode) { ++ case BBR_STARTUP: ++ bbr->pacing_gain = bbr_param(sk, startup_pacing_gain); ++ bbr->cwnd_gain = bbr_param(sk, startup_cwnd_gain); ++ break; ++ case BBR_DRAIN: ++ bbr->pacing_gain = bbr_param(sk, drain_gain); /* slow, to drain */ ++ bbr->cwnd_gain = bbr_param(sk, startup_cwnd_gain); /* keep cwnd */ ++ break; ++ case BBR_PROBE_BW: ++ bbr->pacing_gain = bbr_pacing_gain[bbr->cycle_idx]; ++ bbr->cwnd_gain = bbr_param(sk, cwnd_gain); ++ if (bbr_param(sk, bw_probe_cwnd_gain) && ++ bbr->cycle_idx == BBR_BW_PROBE_UP) ++ bbr->cwnd_gain += ++ BBR_UNIT * bbr_param(sk, bw_probe_cwnd_gain) / 4; ++ break; ++ case BBR_PROBE_RTT: ++ bbr->pacing_gain = BBR_UNIT; ++ bbr->cwnd_gain = BBR_UNIT; ++ break; ++ default: ++ WARN_ONCE(1, "BBR bad mode: %u\n", bbr->mode); ++ break; ++ } ++} ++ ++__bpf_kfunc static u32 bbr_sndbuf_expand(struct sock *sk) ++{ ++ /* Provision 3 * cwnd since BBR may slow-start even during recovery. */ ++ return 3; ++} ++ ++/* Incorporate a new bw sample into the current window of our max filter. */ ++static void bbr_take_max_bw_sample(struct sock *sk, u32 bw) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ bbr->bw_hi[1] = max(bw, bbr->bw_hi[1]); ++} ++ ++/* Keep max of last 1-2 cycles. Each PROBE_BW cycle, flip filter window. */ ++static void bbr_advance_max_bw_filter(struct sock *sk) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ if (!bbr->bw_hi[1]) ++ return; /* no samples in this window; remember old window */ ++ bbr->bw_hi[0] = bbr->bw_hi[1]; ++ bbr->bw_hi[1] = 0; ++} ++ ++/* Reset the estimator for reaching full bandwidth based on bw plateau. */ ++static void bbr_reset_full_bw(struct sock *sk) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ bbr->full_bw = 0; ++ bbr->full_bw_cnt = 0; ++ bbr->full_bw_now = 0; ++} ++ ++/* How much do we want in flight? Our BDP, unless congestion cut cwnd. */ ++static u32 bbr_target_inflight(struct sock *sk) ++{ ++ u32 bdp = bbr_inflight(sk, bbr_bw(sk), BBR_UNIT); ++ ++ return min(bdp, tcp_sk(sk)->snd_cwnd); ++} ++ ++static bool bbr_is_probing_bandwidth(struct sock *sk) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ return (bbr->mode == BBR_STARTUP) || ++ (bbr->mode == BBR_PROBE_BW && ++ (bbr->cycle_idx == BBR_BW_PROBE_REFILL || ++ bbr->cycle_idx == BBR_BW_PROBE_UP)); ++} ++ ++/* Has the given amount of time elapsed since we marked the phase start? */ ++static bool bbr_has_elapsed_in_phase(const struct sock *sk, u32 interval_us) ++{ ++ const struct tcp_sock *tp = tcp_sk(sk); ++ const struct bbr *bbr = inet_csk_ca(sk); ++ ++ return tcp_stamp_us_delta(tp->tcp_mstamp, ++ bbr->cycle_mstamp + interval_us) > 0; ++} ++ ++static void bbr_handle_queue_too_high_in_startup(struct sock *sk) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ u32 bdp; /* estimated BDP in packets, with quantization budget */ ++ ++ bbr->full_bw_reached = 1; ++ ++ bdp = bbr_inflight(sk, bbr_max_bw(sk), BBR_UNIT); ++ bbr->inflight_hi = max(bdp, bbr->inflight_latest); ++} ++ ++/* Exit STARTUP upon N consecutive rounds with ECN mark rate > ecn_thresh. */ ++static void bbr_check_ecn_too_high_in_startup(struct sock *sk, u32 ce_ratio) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ if (bbr_full_bw_reached(sk) || !bbr->ecn_eligible || ++ !bbr_param(sk, full_ecn_cnt) || !bbr_param(sk, ecn_thresh)) ++ return; ++ ++ if (ce_ratio >= bbr_param(sk, ecn_thresh)) ++ bbr->startup_ecn_rounds++; ++ else ++ bbr->startup_ecn_rounds = 0; ++ ++ if (bbr->startup_ecn_rounds >= bbr_param(sk, full_ecn_cnt)) { ++ bbr_handle_queue_too_high_in_startup(sk); ++ return; ++ } ++} ++ ++/* Updates ecn_alpha and returns ce_ratio. -1 if not available. */ ++static int bbr_update_ecn_alpha(struct sock *sk) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct net *net = sock_net(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ s32 delivered, delivered_ce; ++ u64 alpha, ce_ratio; ++ u32 gain; ++ bool want_ecn_alpha; ++ ++ /* See if we should use ECN sender logic for this connection. */ ++ if (!bbr->ecn_eligible && bbr_can_use_ecn(sk) && ++ !!bbr_param(sk, ecn_factor) && ++ (bbr->min_rtt_us <= bbr_ecn_max_rtt_us || ++ !bbr_ecn_max_rtt_us)) ++ bbr->ecn_eligible = 1; ++ ++ /* Skip updating alpha only if not ECN-eligible and PLB is disabled. */ ++ want_ecn_alpha = (bbr->ecn_eligible || ++ (bbr_can_use_ecn(sk) && ++ READ_ONCE(net->ipv4.sysctl_tcp_plb_enabled))); ++ if (!want_ecn_alpha) ++ return -1; ++ ++ delivered = tp->delivered - bbr->alpha_last_delivered; ++ delivered_ce = tp->delivered_ce - bbr->alpha_last_delivered_ce; ++ ++ if (delivered == 0 || /* avoid divide by zero */ ++ WARN_ON_ONCE(delivered < 0 || delivered_ce < 0)) /* backwards? */ ++ return -1; ++ ++ BUILD_BUG_ON(BBR_SCALE != TCP_PLB_SCALE); ++ ce_ratio = (u64)delivered_ce << BBR_SCALE; ++ do_div(ce_ratio, delivered); ++ ++ gain = bbr_param(sk, ecn_alpha_gain); ++ alpha = ((BBR_UNIT - gain) * bbr->ecn_alpha) >> BBR_SCALE; ++ alpha += (gain * ce_ratio) >> BBR_SCALE; ++ bbr->ecn_alpha = min_t(u32, alpha, BBR_UNIT); ++ ++ bbr->alpha_last_delivered = tp->delivered; ++ bbr->alpha_last_delivered_ce = tp->delivered_ce; ++ ++ bbr_check_ecn_too_high_in_startup(sk, ce_ratio); ++ return (int)ce_ratio; ++} ++ ++/* Protective Load Balancing (PLB). PLB rehashes outgoing data (to a new IPv6 ++ * flow label) if it encounters sustained congestion in the form of ECN marks. ++ */ ++static void bbr_plb(struct sock *sk, const struct rate_sample *rs, int ce_ratio) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ if (bbr->round_start && ce_ratio >= 0) ++ tcp_plb_update_state(sk, &bbr->plb, ce_ratio); ++ ++ tcp_plb_check_rehash(sk, &bbr->plb); ++} ++ ++/* Each round trip of BBR_BW_PROBE_UP, double volume of probing data. */ ++static void bbr_raise_inflight_hi_slope(struct sock *sk) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ u32 growth_this_round, cnt; ++ ++ /* Calculate "slope": packets S/Acked per inflight_hi increment. */ ++ growth_this_round = 1 << bbr->bw_probe_up_rounds; ++ bbr->bw_probe_up_rounds = min(bbr->bw_probe_up_rounds + 1, 30); ++ cnt = tcp_snd_cwnd(tp) / growth_this_round; ++ cnt = max(cnt, 1U); ++ bbr->bw_probe_up_cnt = cnt; ++} ++ ++/* In BBR_BW_PROBE_UP, not seeing high loss/ECN/queue, so raise inflight_hi. */ ++static void bbr_probe_inflight_hi_upward(struct sock *sk, ++ const struct rate_sample *rs) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ u32 delta; ++ ++ if (!tp->is_cwnd_limited || tcp_snd_cwnd(tp) < bbr->inflight_hi) ++ return; /* not fully using inflight_hi, so don't grow it */ ++ ++ /* For each bw_probe_up_cnt packets ACKed, increase inflight_hi by 1. */ ++ bbr->bw_probe_up_acks += rs->acked_sacked; ++ if (bbr->bw_probe_up_acks >= bbr->bw_probe_up_cnt) { ++ delta = bbr->bw_probe_up_acks / bbr->bw_probe_up_cnt; ++ bbr->bw_probe_up_acks -= delta * bbr->bw_probe_up_cnt; ++ bbr->inflight_hi += delta; ++ bbr->try_fast_path = 0; /* Need to update cwnd */ ++ } ++ ++ if (bbr->round_start) ++ bbr_raise_inflight_hi_slope(sk); ++} ++ ++/* Does loss/ECN rate for this sample say inflight is "too high"? ++ * This is used by both the bbr_check_loss_too_high_in_startup() function, ++ * and in PROBE_UP. ++ */ ++static bool bbr_is_inflight_too_high(const struct sock *sk, ++ const struct rate_sample *rs) ++{ ++ const struct bbr *bbr = inet_csk_ca(sk); ++ u32 loss_thresh, ecn_thresh; ++ ++ if (rs->lost > 0 && rs->tx_in_flight) { ++ loss_thresh = (u64)rs->tx_in_flight * bbr_param(sk, loss_thresh) >> ++ BBR_SCALE; ++ if (rs->lost > loss_thresh) { ++ return true; ++ } ++ } ++ ++ if (rs->delivered_ce > 0 && rs->delivered > 0 && ++ bbr->ecn_eligible && !!bbr_param(sk, ecn_thresh)) { ++ ecn_thresh = (u64)rs->delivered * bbr_param(sk, ecn_thresh) >> ++ BBR_SCALE; ++ if (rs->delivered_ce > ecn_thresh) { ++ return true; ++ } ++ } ++ ++ return false; ++} ++ ++/* Calculate the tx_in_flight level that corresponded to excessive loss. ++ * We find "lost_prefix" segs of the skb where loss rate went too high, ++ * by solving for "lost_prefix" in the following equation: ++ * lost / inflight >= loss_thresh ++ * (lost_prev + lost_prefix) / (inflight_prev + lost_prefix) >= loss_thresh ++ * Then we take that equation, convert it to fixed point, and ++ * round up to the nearest packet. ++ */ ++static u32 bbr_inflight_hi_from_lost_skb(const struct sock *sk, ++ const struct rate_sample *rs, ++ const struct sk_buff *skb) ++{ ++ const struct tcp_sock *tp = tcp_sk(sk); ++ u32 loss_thresh = bbr_param(sk, loss_thresh); ++ u32 pcount, divisor, inflight_hi; ++ s32 inflight_prev, lost_prev; ++ u64 loss_budget, lost_prefix; ++ ++ pcount = tcp_skb_pcount(skb); ++ ++ /* How much data was in flight before this skb? */ ++ inflight_prev = rs->tx_in_flight - pcount; ++ if (inflight_prev < 0) { ++ WARN_ONCE(tcp_skb_tx_in_flight_is_suspicious( ++ pcount, ++ TCP_SKB_CB(skb)->sacked, ++ rs->tx_in_flight), ++ "tx_in_flight: %u pcount: %u reneg: %u", ++ rs->tx_in_flight, pcount, tcp_sk(sk)->is_sack_reneg); ++ return ~0U; ++ } ++ ++ /* How much inflight data was marked lost before this skb? */ ++ lost_prev = rs->lost - pcount; ++ if (WARN_ONCE(lost_prev < 0, ++ "cwnd: %u ca: %d out: %u lost: %u pif: %u " ++ "tx_in_flight: %u tx.lost: %u tp->lost: %u rs->lost: %d " ++ "lost_prev: %d pcount: %d seq: %u end_seq: %u reneg: %u", ++ tcp_snd_cwnd(tp), inet_csk(sk)->icsk_ca_state, ++ tp->packets_out, tp->lost_out, tcp_packets_in_flight(tp), ++ rs->tx_in_flight, TCP_SKB_CB(skb)->tx.lost, tp->lost, ++ rs->lost, lost_prev, pcount, ++ TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq, ++ tp->is_sack_reneg)) ++ return ~0U; ++ ++ /* At what prefix of this lost skb did losss rate exceed loss_thresh? */ ++ loss_budget = (u64)inflight_prev * loss_thresh + BBR_UNIT - 1; ++ loss_budget >>= BBR_SCALE; ++ if (lost_prev >= loss_budget) { ++ lost_prefix = 0; /* previous losses crossed loss_thresh */ ++ } else { ++ lost_prefix = loss_budget - lost_prev; ++ lost_prefix <<= BBR_SCALE; ++ divisor = BBR_UNIT - loss_thresh; ++ if (WARN_ON_ONCE(!divisor)) /* loss_thresh is 8 bits */ ++ return ~0U; ++ do_div(lost_prefix, divisor); ++ } ++ ++ inflight_hi = inflight_prev + lost_prefix; ++ return inflight_hi; ++} ++ ++/* If loss/ECN rates during probing indicated we may have overfilled a ++ * buffer, return an operating point that tries to leave unutilized headroom in ++ * the path for other flows, for fairness convergence and lower RTTs and loss. ++ */ ++static u32 bbr_inflight_with_headroom(const struct sock *sk) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ u32 headroom, headroom_fraction; ++ ++ if (bbr->inflight_hi == ~0U) ++ return ~0U; ++ ++ headroom_fraction = bbr_param(sk, inflight_headroom); ++ headroom = ((u64)bbr->inflight_hi * headroom_fraction) >> BBR_SCALE; ++ headroom = max(headroom, 1U); ++ return max_t(s32, bbr->inflight_hi - headroom, ++ bbr_param(sk, cwnd_min_target)); ++} ++ ++/* Bound cwnd to a sensible level, based on our current probing state ++ * machine phase and model of a good inflight level (inflight_lo, inflight_hi). ++ */ ++static void bbr_bound_cwnd_for_inflight_model(struct sock *sk) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ u32 cap; ++ ++ /* tcp_rcv_synsent_state_process() currently calls tcp_ack() ++ * and thus cong_control() without first initializing us(!). ++ */ ++ if (!bbr->initialized) ++ return; ++ ++ cap = ~0U; ++ if (bbr->mode == BBR_PROBE_BW && ++ bbr->cycle_idx != BBR_BW_PROBE_CRUISE) { ++ /* Probe to see if more packets fit in the path. */ ++ cap = bbr->inflight_hi; ++ } else { ++ if (bbr->mode == BBR_PROBE_RTT || ++ (bbr->mode == BBR_PROBE_BW && ++ bbr->cycle_idx == BBR_BW_PROBE_CRUISE)) ++ cap = bbr_inflight_with_headroom(sk); ++ } ++ /* Adapt to any loss/ECN since our last bw probe. */ ++ cap = min(cap, bbr->inflight_lo); ++ ++ cap = max_t(u32, cap, bbr_param(sk, cwnd_min_target)); ++ tcp_snd_cwnd_set(tp, min(cap, tcp_snd_cwnd(tp))); ++} ++ ++/* How should we multiplicatively cut bw or inflight limits based on ECN? */ ++static u32 bbr_ecn_cut(struct sock *sk) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ return BBR_UNIT - ++ ((bbr->ecn_alpha * bbr_param(sk, ecn_factor)) >> BBR_SCALE); ++} ++ ++/* Init lower bounds if have not inited yet. */ ++static void bbr_init_lower_bounds(struct sock *sk, bool init_bw) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ if (init_bw && bbr->bw_lo == ~0U) ++ bbr->bw_lo = bbr_max_bw(sk); ++ if (bbr->inflight_lo == ~0U) ++ bbr->inflight_lo = tcp_snd_cwnd(tp); ++} ++ ++/* Reduce bw and inflight to (1 - beta). */ ++static void bbr_loss_lower_bounds(struct sock *sk, u32 *bw, u32 *inflight) ++{ ++ struct bbr* bbr = inet_csk_ca(sk); ++ u32 loss_cut = BBR_UNIT - bbr_param(sk, beta); ++ ++ *bw = max_t(u32, bbr->bw_latest, ++ (u64)bbr->bw_lo * loss_cut >> BBR_SCALE); ++ *inflight = max_t(u32, bbr->inflight_latest, ++ (u64)bbr->inflight_lo * loss_cut >> BBR_SCALE); ++} ++ ++/* Reduce inflight to (1 - alpha*ecn_factor). */ ++static void bbr_ecn_lower_bounds(struct sock *sk, u32 *inflight) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ u32 ecn_cut = bbr_ecn_cut(sk); ++ ++ *inflight = (u64)bbr->inflight_lo * ecn_cut >> BBR_SCALE; ++} ++ ++/* Estimate a short-term lower bound on the capacity available now, based ++ * on measurements of the current delivery process and recent history. When we ++ * are seeing loss/ECN at times when we are not probing bw, then conservatively ++ * move toward flow balance by multiplicatively cutting our short-term ++ * estimated safe rate and volume of data (bw_lo and inflight_lo). We use a ++ * multiplicative decrease in order to converge to a lower capacity in time ++ * logarithmic in the magnitude of the decrease. ++ * ++ * However, we do not cut our short-term estimates lower than the current rate ++ * and volume of delivered data from this round trip, since from the current ++ * delivery process we can estimate the measured capacity available now. ++ * ++ * Anything faster than that approach would knowingly risk high loss, which can ++ * cause low bw for Reno/CUBIC and high loss recovery latency for ++ * request/response flows using any congestion control. ++ */ ++static void bbr_adapt_lower_bounds(struct sock *sk, ++ const struct rate_sample *rs) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ u32 ecn_inflight_lo = ~0U; ++ ++ /* We only use lower-bound estimates when not probing bw. ++ * When probing we need to push inflight higher to probe bw. ++ */ ++ if (bbr_is_probing_bandwidth(sk)) ++ return; ++ ++ /* ECN response. */ ++ if (bbr->ecn_in_round && !!bbr_param(sk, ecn_factor)) { ++ bbr_init_lower_bounds(sk, false); ++ bbr_ecn_lower_bounds(sk, &ecn_inflight_lo); ++ } ++ ++ /* Loss response. */ ++ if (bbr->loss_in_round) { ++ bbr_init_lower_bounds(sk, true); ++ bbr_loss_lower_bounds(sk, &bbr->bw_lo, &bbr->inflight_lo); ++ } ++ ++ /* Adjust to the lower of the levels implied by loss/ECN. */ ++ bbr->inflight_lo = min(bbr->inflight_lo, ecn_inflight_lo); ++ bbr->bw_lo = max(1U, bbr->bw_lo); ++} ++ ++/* Reset any short-term lower-bound adaptation to congestion, so that we can ++ * push our inflight up. ++ */ ++static void bbr_reset_lower_bounds(struct sock *sk) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ bbr->bw_lo = ~0U; ++ bbr->inflight_lo = ~0U; ++} ++ ++/* After bw probing (STARTUP/PROBE_UP), reset signals before entering a state ++ * machine phase where we adapt our lower bound based on congestion signals. ++ */ ++static void bbr_reset_congestion_signals(struct sock *sk) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ bbr->loss_in_round = 0; ++ bbr->ecn_in_round = 0; ++ bbr->loss_in_cycle = 0; ++ bbr->ecn_in_cycle = 0; ++ bbr->bw_latest = 0; ++ bbr->inflight_latest = 0; ++} ++ ++static void bbr_exit_loss_recovery(struct sock *sk) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ tcp_snd_cwnd_set(tp, max(tcp_snd_cwnd(tp), bbr->prior_cwnd)); ++ bbr->try_fast_path = 0; /* bound cwnd using latest model */ ++} ++ ++/* Update rate and volume of delivered data from latest round trip. */ ++static void bbr_update_latest_delivery_signals( ++ struct sock *sk, const struct rate_sample *rs, struct bbr_context *ctx) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ bbr->loss_round_start = 0; ++ if (rs->interval_us <= 0 || !rs->acked_sacked) ++ return; /* Not a valid observation */ ++ ++ bbr->bw_latest = max_t(u32, bbr->bw_latest, ctx->sample_bw); ++ bbr->inflight_latest = max_t(u32, bbr->inflight_latest, rs->delivered); ++ ++ if (!before(rs->prior_delivered, bbr->loss_round_delivered)) { ++ bbr->loss_round_delivered = tp->delivered; ++ bbr->loss_round_start = 1; /* mark start of new round trip */ ++ } ++} ++ ++/* Once per round, reset filter for latest rate and volume of delivered data. */ ++static void bbr_advance_latest_delivery_signals( ++ struct sock *sk, const struct rate_sample *rs, struct bbr_context *ctx) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ /* If ACK matches a TLP retransmit, persist the filter. If we detect ++ * that a TLP retransmit plugged a tail loss, we'll want to remember ++ * how much data the path delivered before the tail loss. ++ */ ++ if (bbr->loss_round_start && !rs->is_acking_tlp_retrans_seq) { ++ bbr->bw_latest = ctx->sample_bw; ++ bbr->inflight_latest = rs->delivered; ++ } ++} ++ ++/* Update (most of) our congestion signals: track the recent rate and volume of ++ * delivered data, presence of loss, and EWMA degree of ECN marking. ++ */ ++static void bbr_update_congestion_signals( ++ struct sock *sk, const struct rate_sample *rs, struct bbr_context *ctx) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ u64 bw; ++ ++ if (rs->interval_us <= 0 || !rs->acked_sacked) ++ return; /* Not a valid observation */ ++ bw = ctx->sample_bw; ++ ++ if (!rs->is_app_limited || bw >= bbr_max_bw(sk)) ++ bbr_take_max_bw_sample(sk, bw); ++ ++ bbr->loss_in_round |= (rs->losses > 0); ++ ++ if (!bbr->loss_round_start) ++ return; /* skip the per-round-trip updates */ ++ /* Now do per-round-trip updates. */ ++ bbr_adapt_lower_bounds(sk, rs); ++ ++ bbr->loss_in_round = 0; ++ bbr->ecn_in_round = 0; ++} ++ ++/* Bandwidth probing can cause loss. To help coexistence with loss-based ++ * congestion control we spread out our probing in a Reno-conscious way. Due to ++ * the shape of the Reno sawtooth, the time required between loss epochs for an ++ * idealized Reno flow is a number of round trips that is the BDP of that ++ * flow. We count packet-timed round trips directly, since measured RTT can ++ * vary widely, and Reno is driven by packet-timed round trips. ++ */ ++static bool bbr_is_reno_coexistence_probe_time(struct sock *sk) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ u32 rounds; ++ ++ /* Random loss can shave some small percentage off of our inflight ++ * in each round. To survive this, flows need robust periodic probes. ++ */ ++ rounds = min_t(u32, bbr_param(sk, bw_probe_max_rounds), bbr_target_inflight(sk)); ++ return bbr->rounds_since_probe >= rounds; ++} ++ ++/* How long do we want to wait before probing for bandwidth (and risking ++ * loss)? We randomize the wait, for better mixing and fairness convergence. ++ * ++ * We bound the Reno-coexistence inter-bw-probe time to be 62-63 round trips. ++ * This is calculated to allow fairness with a 25Mbps, 30ms Reno flow, ++ * (eg 4K video to a broadband user): ++ * BDP = 25Mbps * .030sec /(1514bytes) = 61.9 packets ++ * ++ * We bound the BBR-native inter-bw-probe wall clock time to be: ++ * (a) higher than 2 sec: to try to avoid causing loss for a long enough time ++ * to allow Reno at 30ms to get 4K video bw, the inter-bw-probe time must ++ * be at least: 25Mbps * .030sec / (1514bytes) * 0.030sec = 1.9secs ++ * (b) lower than 3 sec: to ensure flows can start probing in a reasonable ++ * amount of time to discover unutilized bw on human-scale interactive ++ * time-scales (e.g. perhaps traffic from a web page download that we ++ * were competing with is now complete). ++ */ ++static void bbr_pick_probe_wait(struct sock *sk) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ /* Decide the random round-trip bound for wait until probe: */ ++ bbr->rounds_since_probe = ++ get_random_u32_below(bbr_param(sk, bw_probe_rand_rounds)); ++ /* Decide the random wall clock bound for wait until probe: */ ++ bbr->probe_wait_us = bbr_param(sk, bw_probe_base_us) + ++ get_random_u32_below(bbr_param(sk, bw_probe_rand_us)); ++} ++ ++static void bbr_set_cycle_idx(struct sock *sk, int cycle_idx) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ bbr->cycle_idx = cycle_idx; ++ /* New phase, so need to update cwnd and pacing rate. */ ++ bbr->try_fast_path = 0; ++} ++ ++/* Send at estimated bw to fill the pipe, but not queue. We need this phase ++ * before PROBE_UP, because as soon as we send faster than the available bw ++ * we will start building a queue, and if the buffer is shallow we can cause ++ * loss. If we do not fill the pipe before we cause this loss, our bw_hi and ++ * inflight_hi estimates will underestimate. ++ */ ++static void bbr_start_bw_probe_refill(struct sock *sk, u32 bw_probe_up_rounds) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ bbr_reset_lower_bounds(sk); ++ bbr->bw_probe_up_rounds = bw_probe_up_rounds; ++ bbr->bw_probe_up_acks = 0; ++ bbr->stopped_risky_probe = 0; ++ bbr->ack_phase = BBR_ACKS_REFILLING; ++ bbr->next_rtt_delivered = tp->delivered; ++ bbr_set_cycle_idx(sk, BBR_BW_PROBE_REFILL); ++} ++ ++/* Now probe max deliverable data rate and volume. */ ++static void bbr_start_bw_probe_up(struct sock *sk, struct bbr_context *ctx) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ bbr->ack_phase = BBR_ACKS_PROBE_STARTING; ++ bbr->next_rtt_delivered = tp->delivered; ++ bbr->cycle_mstamp = tp->tcp_mstamp; ++ bbr_reset_full_bw(sk); ++ bbr->full_bw = ctx->sample_bw; ++ bbr_set_cycle_idx(sk, BBR_BW_PROBE_UP); ++ bbr_raise_inflight_hi_slope(sk); ++} ++ ++/* Start a new PROBE_BW probing cycle of some wall clock length. Pick a wall ++ * clock time at which to probe beyond an inflight that we think to be ++ * safe. This will knowingly risk packet loss, so we want to do this rarely, to ++ * keep packet loss rates low. Also start a round-trip counter, to probe faster ++ * if we estimate a Reno flow at our BDP would probe faster. ++ */ ++static void bbr_start_bw_probe_down(struct sock *sk) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ bbr_reset_congestion_signals(sk); ++ bbr->bw_probe_up_cnt = ~0U; /* not growing inflight_hi any more */ ++ bbr_pick_probe_wait(sk); ++ bbr->cycle_mstamp = tp->tcp_mstamp; /* start wall clock */ ++ bbr->ack_phase = BBR_ACKS_PROBE_STOPPING; ++ bbr->next_rtt_delivered = tp->delivered; ++ bbr_set_cycle_idx(sk, BBR_BW_PROBE_DOWN); ++} ++ ++/* Cruise: maintain what we estimate to be a neutral, conservative ++ * operating point, without attempting to probe up for bandwidth or down for ++ * RTT, and only reducing inflight in response to loss/ECN signals. ++ */ ++static void bbr_start_bw_probe_cruise(struct sock *sk) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ if (bbr->inflight_lo != ~0U) ++ bbr->inflight_lo = min(bbr->inflight_lo, bbr->inflight_hi); ++ ++ bbr_set_cycle_idx(sk, BBR_BW_PROBE_CRUISE); ++} ++ ++/* Loss and/or ECN rate is too high while probing. ++ * Adapt (once per bw probe) by cutting inflight_hi and then restarting cycle. ++ */ ++static void bbr_handle_inflight_too_high(struct sock *sk, ++ const struct rate_sample *rs) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ const u32 beta = bbr_param(sk, beta); ++ ++ bbr->prev_probe_too_high = 1; ++ bbr->bw_probe_samples = 0; /* only react once per probe */ ++ /* If we are app-limited then we are not robustly ++ * probing the max volume of inflight data we think ++ * might be safe (analogous to how app-limited bw ++ * samples are not known to be robustly probing bw). ++ */ ++ if (!rs->is_app_limited) { ++ bbr->inflight_hi = max_t(u32, rs->tx_in_flight, ++ (u64)bbr_target_inflight(sk) * ++ (BBR_UNIT - beta) >> BBR_SCALE); ++ } ++ if (bbr->mode == BBR_PROBE_BW && bbr->cycle_idx == BBR_BW_PROBE_UP) ++ bbr_start_bw_probe_down(sk); ++} ++ ++/* If we're seeing bw and loss samples reflecting our bw probing, adapt ++ * using the signals we see. If loss or ECN mark rate gets too high, then adapt ++ * inflight_hi downward. If we're able to push inflight higher without such ++ * signals, push higher: adapt inflight_hi upward. ++ */ ++static bool bbr_adapt_upper_bounds(struct sock *sk, ++ const struct rate_sample *rs, ++ struct bbr_context *ctx) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ /* Track when we'll see bw/loss samples resulting from our bw probes. */ ++ if (bbr->ack_phase == BBR_ACKS_PROBE_STARTING && bbr->round_start) ++ bbr->ack_phase = BBR_ACKS_PROBE_FEEDBACK; ++ if (bbr->ack_phase == BBR_ACKS_PROBE_STOPPING && bbr->round_start) { ++ /* End of samples from bw probing phase. */ ++ bbr->bw_probe_samples = 0; ++ bbr->ack_phase = BBR_ACKS_INIT; ++ /* At this point in the cycle, our current bw sample is also ++ * our best recent chance at finding the highest available bw ++ * for this flow. So now is the best time to forget the bw ++ * samples from the previous cycle, by advancing the window. ++ */ ++ if (bbr->mode == BBR_PROBE_BW && !rs->is_app_limited) ++ bbr_advance_max_bw_filter(sk); ++ /* If we had an inflight_hi, then probed and pushed inflight all ++ * the way up to hit that inflight_hi without seeing any ++ * high loss/ECN in all the resulting ACKs from that probing, ++ * then probe up again, this time letting inflight persist at ++ * inflight_hi for a round trip, then accelerating beyond. ++ */ ++ if (bbr->mode == BBR_PROBE_BW && ++ bbr->stopped_risky_probe && !bbr->prev_probe_too_high) { ++ bbr_start_bw_probe_refill(sk, 0); ++ return true; /* yes, decided state transition */ ++ } ++ } ++ if (bbr_is_inflight_too_high(sk, rs)) { ++ if (bbr->bw_probe_samples) /* sample is from bw probing? */ ++ bbr_handle_inflight_too_high(sk, rs); ++ } else { ++ /* Loss/ECN rate is declared safe. Adjust upper bound upward. */ ++ ++ if (bbr->inflight_hi == ~0U) ++ return false; /* no excess queue signals yet */ ++ ++ /* To be resilient to random loss, we must raise bw/inflight_hi ++ * if we observe in any phase that a higher level is safe. ++ */ ++ if (rs->tx_in_flight > bbr->inflight_hi) { ++ bbr->inflight_hi = rs->tx_in_flight; ++ } ++ ++ if (bbr->mode == BBR_PROBE_BW && ++ bbr->cycle_idx == BBR_BW_PROBE_UP) ++ bbr_probe_inflight_hi_upward(sk, rs); ++ } ++ ++ return false; ++} ++ ++/* Check if it's time to probe for bandwidth now, and if so, kick it off. */ ++static bool bbr_check_time_to_probe_bw(struct sock *sk, ++ const struct rate_sample *rs) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ u32 n; ++ ++ /* If we seem to be at an operating point where we are not seeing loss ++ * but we are seeing ECN marks, then when the ECN marks cease we reprobe ++ * quickly (in case cross-traffic has ceased and freed up bw). ++ */ ++ if (bbr_param(sk, ecn_reprobe_gain) && bbr->ecn_eligible && ++ bbr->ecn_in_cycle && !bbr->loss_in_cycle && ++ inet_csk(sk)->icsk_ca_state == TCP_CA_Open) { ++ /* Calculate n so that when bbr_raise_inflight_hi_slope() ++ * computes growth_this_round as 2^n it will be roughly the ++ * desired volume of data (inflight_hi*ecn_reprobe_gain). ++ */ ++ n = ilog2((((u64)bbr->inflight_hi * ++ bbr_param(sk, ecn_reprobe_gain)) >> BBR_SCALE)); ++ bbr_start_bw_probe_refill(sk, n); ++ return true; ++ } ++ ++ if (bbr_has_elapsed_in_phase(sk, bbr->probe_wait_us) || ++ bbr_is_reno_coexistence_probe_time(sk)) { ++ bbr_start_bw_probe_refill(sk, 0); ++ return true; ++ } ++ return false; ++} ++ ++/* Is it time to transition from PROBE_DOWN to PROBE_CRUISE? */ ++static bool bbr_check_time_to_cruise(struct sock *sk, u32 inflight, u32 bw) ++{ ++ /* Always need to pull inflight down to leave headroom in queue. */ ++ if (inflight > bbr_inflight_with_headroom(sk)) ++ return false; ++ ++ return inflight <= bbr_inflight(sk, bw, BBR_UNIT); ++} ++ ++/* PROBE_BW state machine: cruise, refill, probe for bw, or drain? */ ++static void bbr_update_cycle_phase(struct sock *sk, ++ const struct rate_sample *rs, ++ struct bbr_context *ctx) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ bool is_bw_probe_done = false; ++ u32 inflight, bw; ++ ++ if (!bbr_full_bw_reached(sk)) ++ return; ++ ++ /* In DRAIN, PROBE_BW, or PROBE_RTT, adjust upper bounds. */ ++ if (bbr_adapt_upper_bounds(sk, rs, ctx)) ++ return; /* already decided state transition */ ++ ++ if (bbr->mode != BBR_PROBE_BW) ++ return; ++ ++ inflight = bbr_packets_in_net_at_edt(sk, rs->prior_in_flight); ++ bw = bbr_max_bw(sk); ++ ++ switch (bbr->cycle_idx) { ++ /* First we spend most of our time cruising with a pacing_gain of 1.0, ++ * which paces at the estimated bw, to try to fully use the pipe ++ * without building queue. If we encounter loss/ECN marks, we adapt ++ * by slowing down. ++ */ ++ case BBR_BW_PROBE_CRUISE: ++ if (bbr_check_time_to_probe_bw(sk, rs)) ++ return; /* already decided state transition */ ++ break; ++ ++ /* After cruising, when it's time to probe, we first "refill": we send ++ * at the estimated bw to fill the pipe, before probing higher and ++ * knowingly risking overflowing the bottleneck buffer (causing loss). ++ */ ++ case BBR_BW_PROBE_REFILL: ++ if (bbr->round_start) { ++ /* After one full round trip of sending in REFILL, we ++ * start to see bw samples reflecting our REFILL, which ++ * may be putting too much data in flight. ++ */ ++ bbr->bw_probe_samples = 1; ++ bbr_start_bw_probe_up(sk, ctx); ++ } ++ break; ++ ++ /* After we refill the pipe, we probe by using a pacing_gain > 1.0, to ++ * probe for bw. If we have not seen loss/ECN, we try to raise inflight ++ * to at least pacing_gain*BDP; note that this may take more than ++ * min_rtt if min_rtt is small (e.g. on a LAN). ++ * ++ * We terminate PROBE_UP bandwidth probing upon any of the following: ++ * ++ * (1) We've pushed inflight up to hit the inflight_hi target set in the ++ * most recent previous bw probe phase. Thus we want to start ++ * draining the queue immediately because it's very likely the most ++ * recently sent packets will fill the queue and cause drops. ++ * (2) If inflight_hi has not limited bandwidth growth recently, and ++ * yet delivered bandwidth has not increased much recently ++ * (bbr->full_bw_now). ++ * (3) Loss filter says loss rate is "too high". ++ * (4) ECN filter says ECN mark rate is "too high". ++ * ++ * (1) (2) checked here, (3) (4) checked in bbr_is_inflight_too_high() ++ */ ++ case BBR_BW_PROBE_UP: ++ if (bbr->prev_probe_too_high && ++ inflight >= bbr->inflight_hi) { ++ bbr->stopped_risky_probe = 1; ++ is_bw_probe_done = true; ++ } else { ++ if (tp->is_cwnd_limited && ++ tcp_snd_cwnd(tp) >= bbr->inflight_hi) { ++ /* inflight_hi is limiting bw growth */ ++ bbr_reset_full_bw(sk); ++ bbr->full_bw = ctx->sample_bw; ++ } else if (bbr->full_bw_now) { ++ /* Plateau in estimated bw. Pipe looks full. */ ++ is_bw_probe_done = true; ++ } ++ } ++ if (is_bw_probe_done) { ++ bbr->prev_probe_too_high = 0; /* no loss/ECN (yet) */ ++ bbr_start_bw_probe_down(sk); /* restart w/ down */ ++ } ++ break; ++ ++ /* After probing in PROBE_UP, we have usually accumulated some data in ++ * the bottleneck buffer (if bw probing didn't find more bw). We next ++ * enter PROBE_DOWN to try to drain any excess data from the queue. To ++ * do this, we use a pacing_gain < 1.0. We hold this pacing gain until ++ * our inflight is less then that target cruising point, which is the ++ * minimum of (a) the amount needed to leave headroom, and (b) the ++ * estimated BDP. Once inflight falls to match the target, we estimate ++ * the queue is drained; persisting would underutilize the pipe. ++ */ ++ case BBR_BW_PROBE_DOWN: ++ if (bbr_check_time_to_probe_bw(sk, rs)) ++ return; /* already decided state transition */ ++ if (bbr_check_time_to_cruise(sk, inflight, bw)) ++ bbr_start_bw_probe_cruise(sk); ++ break; ++ ++ default: ++ WARN_ONCE(1, "BBR invalid cycle index %u\n", bbr->cycle_idx); ++ } ++} ++ ++/* Exiting PROBE_RTT, so return to bandwidth probing in STARTUP or PROBE_BW. */ ++static void bbr_exit_probe_rtt(struct sock *sk) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ bbr_reset_lower_bounds(sk); ++ if (bbr_full_bw_reached(sk)) { ++ bbr->mode = BBR_PROBE_BW; ++ /* Raising inflight after PROBE_RTT may cause loss, so reset ++ * the PROBE_BW clock and schedule the next bandwidth probe for ++ * a friendly and randomized future point in time. ++ */ ++ bbr_start_bw_probe_down(sk); ++ /* Since we are exiting PROBE_RTT, we know inflight is ++ * below our estimated BDP, so it is reasonable to cruise. ++ */ ++ bbr_start_bw_probe_cruise(sk); ++ } else { ++ bbr->mode = BBR_STARTUP; ++ } ++} ++ ++/* Exit STARTUP based on loss rate > 1% and loss gaps in round >= N. Wait until ++ * the end of the round in recovery to get a good estimate of how many packets ++ * have been lost, and how many we need to drain with a low pacing rate. ++ */ ++static void bbr_check_loss_too_high_in_startup(struct sock *sk, ++ const struct rate_sample *rs) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ if (bbr_full_bw_reached(sk)) ++ return; ++ ++ /* For STARTUP exit, check the loss rate at the end of each round trip ++ * of Recovery episodes in STARTUP. We check the loss rate at the end ++ * of the round trip to filter out noisy/low loss and have a better ++ * sense of inflight (extent of loss), so we can drain more accurately. ++ */ ++ if (rs->losses && bbr->loss_events_in_round < 0xf) ++ bbr->loss_events_in_round++; /* update saturating counter */ ++ if (bbr_param(sk, full_loss_cnt) && bbr->loss_round_start && ++ inet_csk(sk)->icsk_ca_state == TCP_CA_Recovery && ++ bbr->loss_events_in_round >= bbr_param(sk, full_loss_cnt) && ++ bbr_is_inflight_too_high(sk, rs)) { ++ bbr_handle_queue_too_high_in_startup(sk); ++ return; ++ } ++ if (bbr->loss_round_start) ++ bbr->loss_events_in_round = 0; ++} ++ ++/* Estimate when the pipe is full, using the change in delivery rate: BBR ++ * estimates bw probing filled the pipe if the estimated bw hasn't changed by ++ * at least bbr_full_bw_thresh (25%) after bbr_full_bw_cnt (3) non-app-limited ++ * rounds. Why 3 rounds: 1: rwin autotuning grows the rwin, 2: we fill the ++ * higher rwin, 3: we get higher delivery rate samples. Or transient ++ * cross-traffic or radio noise can go away. CUBIC Hystart shares a similar ++ * design goal, but uses delay and inter-ACK spacing instead of bandwidth. ++ */ ++static void bbr_check_full_bw_reached(struct sock *sk, ++ const struct rate_sample *rs, ++ struct bbr_context *ctx) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ u32 bw_thresh, full_cnt, thresh; ++ ++ if (bbr->full_bw_now || rs->is_app_limited) ++ return; ++ ++ thresh = bbr_param(sk, full_bw_thresh); ++ full_cnt = bbr_param(sk, full_bw_cnt); ++ bw_thresh = (u64)bbr->full_bw * thresh >> BBR_SCALE; ++ if (ctx->sample_bw >= bw_thresh) { ++ bbr_reset_full_bw(sk); ++ bbr->full_bw = ctx->sample_bw; ++ return; ++ } ++ if (!bbr->round_start) ++ return; ++ ++bbr->full_bw_cnt; ++ bbr->full_bw_now = bbr->full_bw_cnt >= full_cnt; ++ bbr->full_bw_reached |= bbr->full_bw_now; ++} ++ ++/* If pipe is probably full, drain the queue and then enter steady-state. */ ++static void bbr_check_drain(struct sock *sk, const struct rate_sample *rs, ++ struct bbr_context *ctx) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ if (bbr->mode == BBR_STARTUP && bbr_full_bw_reached(sk)) { ++ bbr->mode = BBR_DRAIN; /* drain queue we created */ ++ /* Set ssthresh to export purely for monitoring, to signal ++ * completion of initial STARTUP by setting to a non- ++ * TCP_INFINITE_SSTHRESH value (ssthresh is not used by BBR). ++ */ ++ tcp_sk(sk)->snd_ssthresh = ++ bbr_inflight(sk, bbr_max_bw(sk), BBR_UNIT); ++ bbr_reset_congestion_signals(sk); ++ } /* fall through to check if in-flight is already small: */ ++ if (bbr->mode == BBR_DRAIN && ++ bbr_packets_in_net_at_edt(sk, tcp_packets_in_flight(tcp_sk(sk))) <= ++ bbr_inflight(sk, bbr_max_bw(sk), BBR_UNIT)) { ++ bbr->mode = BBR_PROBE_BW; ++ bbr_start_bw_probe_down(sk); ++ } ++} ++ ++static void bbr_update_model(struct sock *sk, const struct rate_sample *rs, ++ struct bbr_context *ctx) ++{ ++ bbr_update_congestion_signals(sk, rs, ctx); ++ bbr_update_ack_aggregation(sk, rs); ++ bbr_check_loss_too_high_in_startup(sk, rs); ++ bbr_check_full_bw_reached(sk, rs, ctx); ++ bbr_check_drain(sk, rs, ctx); ++ bbr_update_cycle_phase(sk, rs, ctx); ++ bbr_update_min_rtt(sk, rs); ++} ++ ++/* Fast path for app-limited case. ++ * ++ * On each ack, we execute bbr state machine, which primarily consists of: ++ * 1) update model based on new rate sample, and ++ * 2) update control based on updated model or state change. ++ * ++ * There are certain workload/scenarios, e.g. app-limited case, where ++ * either we can skip updating model or we can skip update of both model ++ * as well as control. This provides signifcant softirq cpu savings for ++ * processing incoming acks. ++ * ++ * In case of app-limited, if there is no congestion (loss/ecn) and ++ * if observed bw sample is less than current estimated bw, then we can ++ * skip some of the computation in bbr state processing: ++ * ++ * - if there is no rtt/mode/phase change: In this case, since all the ++ * parameters of the network model are constant, we can skip model ++ * as well control update. ++ * ++ * - else we can skip rest of the model update. But we still need to ++ * update the control to account for the new rtt/mode/phase. ++ * ++ * Returns whether we can take fast path or not. ++ */ ++static bool bbr_run_fast_path(struct sock *sk, bool *update_model, ++ const struct rate_sample *rs, struct bbr_context *ctx) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ u32 prev_min_rtt_us, prev_mode; ++ ++ if (bbr_param(sk, fast_path) && bbr->try_fast_path && ++ rs->is_app_limited && ctx->sample_bw < bbr_max_bw(sk) && ++ !bbr->loss_in_round && !bbr->ecn_in_round ) { ++ prev_mode = bbr->mode; ++ prev_min_rtt_us = bbr->min_rtt_us; ++ bbr_check_drain(sk, rs, ctx); ++ bbr_update_cycle_phase(sk, rs, ctx); ++ bbr_update_min_rtt(sk, rs); ++ ++ if (bbr->mode == prev_mode && ++ bbr->min_rtt_us == prev_min_rtt_us && ++ bbr->try_fast_path) { ++ return true; ++ } ++ ++ /* Skip model update, but control still needs to be updated */ ++ *update_model = false; ++ } ++ return false; ++} ++ ++__bpf_kfunc static void bbr_main(struct sock *sk, u32 ack, int flag, ++ const struct rate_sample *rs) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ struct bbr_context ctx = { 0 }; ++ bool update_model = true; ++ u32 bw, round_delivered; ++ int ce_ratio = -1; ++ ++ round_delivered = bbr_update_round_start(sk, rs, &ctx); ++ if (bbr->round_start) { ++ bbr->rounds_since_probe = ++ min_t(s32, bbr->rounds_since_probe + 1, 0xFF); ++ ce_ratio = bbr_update_ecn_alpha(sk); ++ } ++ bbr_plb(sk, rs, ce_ratio); ++ ++ bbr->ecn_in_round |= (bbr->ecn_eligible && rs->is_ece); ++ bbr_calculate_bw_sample(sk, rs, &ctx); ++ bbr_update_latest_delivery_signals(sk, rs, &ctx); ++ ++ if (bbr_run_fast_path(sk, &update_model, rs, &ctx)) ++ goto out; ++ ++ if (update_model) ++ bbr_update_model(sk, rs, &ctx); ++ ++ bbr_update_gains(sk); ++ bw = bbr_bw(sk); ++ bbr_set_pacing_rate(sk, bw, bbr->pacing_gain); ++ bbr_set_cwnd(sk, rs, rs->acked_sacked, bw, bbr->cwnd_gain, ++ tcp_snd_cwnd(tp), &ctx); ++ bbr_bound_cwnd_for_inflight_model(sk); ++ ++out: ++ bbr_advance_latest_delivery_signals(sk, rs, &ctx); ++ bbr->prev_ca_state = inet_csk(sk)->icsk_ca_state; ++ bbr->loss_in_cycle |= rs->lost > 0; ++ bbr->ecn_in_cycle |= rs->delivered_ce > 0; ++} ++ ++__bpf_kfunc static void bbr_init(struct sock *sk) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ bbr->initialized = 1; ++ ++ bbr->init_cwnd = min(0x7FU, tcp_snd_cwnd(tp)); ++ bbr->prior_cwnd = tp->prior_cwnd; ++ WRITE_ONCE(tp->snd_ssthresh, TCP_INFINITE_SSTHRESH); ++ bbr->next_rtt_delivered = tp->delivered; ++ bbr->prev_ca_state = TCP_CA_Open; ++ ++ bbr->probe_rtt_done_stamp = 0; ++ bbr->probe_rtt_round_done = 0; ++ bbr->probe_rtt_min_us = tcp_min_rtt(tp); ++ bbr->probe_rtt_min_stamp = tcp_jiffies32; ++ bbr->min_rtt_us = tcp_min_rtt(tp); ++ bbr->min_rtt_stamp = tcp_jiffies32; ++ ++ bbr->has_seen_rtt = 0; ++ bbr_init_pacing_rate_from_rtt(sk); ++ ++ bbr->round_start = 0; ++ bbr->idle_restart = 0; ++ bbr->full_bw_reached = 0; ++ bbr->full_bw = 0; ++ bbr->full_bw_cnt = 0; ++ bbr->cycle_mstamp = 0; ++ bbr->cycle_idx = 0; ++ ++ bbr_reset_startup_mode(sk); ++ ++ bbr->ack_epoch_mstamp = tp->tcp_mstamp; ++ bbr->ack_epoch_acked = 0; ++ bbr->extra_acked_win_rtts = 0; ++ bbr->extra_acked_win_idx = 0; ++ bbr->extra_acked[0] = 0; ++ bbr->extra_acked[1] = 0; ++ ++ bbr->ce_state = 0; ++ bbr->prior_rcv_nxt = tp->rcv_nxt; ++ bbr->try_fast_path = 0; ++ ++ cmpxchg(&sk->sk_pacing_status, SK_PACING_NONE, SK_PACING_NEEDED); ++ ++ /* Start sampling ECN mark rate after first full flight is ACKed: */ ++ bbr->loss_round_delivered = tp->delivered + 1; ++ bbr->loss_round_start = 0; ++ bbr->undo_bw_lo = 0; ++ bbr->undo_inflight_lo = 0; ++ bbr->undo_inflight_hi = 0; ++ bbr->loss_events_in_round = 0; ++ bbr->startup_ecn_rounds = 0; ++ bbr_reset_congestion_signals(sk); ++ bbr->bw_lo = ~0U; ++ bbr->bw_hi[0] = 0; ++ bbr->bw_hi[1] = 0; ++ bbr->inflight_lo = ~0U; ++ bbr->inflight_hi = ~0U; ++ bbr_reset_full_bw(sk); ++ bbr->bw_probe_up_cnt = ~0U; ++ bbr->bw_probe_up_acks = 0; ++ bbr->bw_probe_up_rounds = 0; ++ bbr->probe_wait_us = 0; ++ bbr->stopped_risky_probe = 0; ++ bbr->ack_phase = BBR_ACKS_INIT; ++ bbr->rounds_since_probe = 0; ++ bbr->bw_probe_samples = 0; ++ bbr->prev_probe_too_high = 0; ++ bbr->ecn_eligible = 0; ++ bbr->ecn_alpha = bbr_param(sk, ecn_alpha_init); ++ bbr->alpha_last_delivered = 0; ++ bbr->alpha_last_delivered_ce = 0; ++ bbr->plb.pause_until = 0; ++ ++ tp->fast_ack_mode = bbr_fast_ack_mode ? 1 : 0; ++ ++ if (bbr_can_use_ecn(sk)) ++ tp->ecn_flags |= TCP_ECN_ECT_PERMANENT; ++} ++ ++/* BBR marks the current round trip as a loss round. */ ++static void bbr_note_loss(struct sock *sk) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ /* Capture "current" data over the full round trip of loss, to ++ * have a better chance of observing the full capacity of the path. ++ */ ++ if (!bbr->loss_in_round) /* first loss in this round trip? */ ++ bbr->loss_round_delivered = tp->delivered; /* set round trip */ ++ bbr->loss_in_round = 1; ++ bbr->loss_in_cycle = 1; ++} ++ ++/* Core TCP stack informs us that the given skb was just marked lost. */ ++__bpf_kfunc static void bbr_skb_marked_lost(struct sock *sk, ++ const struct sk_buff *skb) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ struct tcp_skb_cb *scb = TCP_SKB_CB(skb); ++ struct rate_sample rs = {}; ++ ++ bbr_note_loss(sk); ++ ++ if (!bbr->bw_probe_samples) ++ return; /* not an skb sent while probing for bandwidth */ ++ if (unlikely(!scb->tx.delivered_mstamp)) ++ return; /* skb was SACKed, reneged, marked lost; ignore it */ ++ /* We are probing for bandwidth. Construct a rate sample that ++ * estimates what happened in the flight leading up to this lost skb, ++ * then see if the loss rate went too high, and if so at which packet. ++ */ ++ rs.tx_in_flight = scb->tx.in_flight; ++ rs.lost = tp->lost - scb->tx.lost; ++ rs.is_app_limited = scb->tx.is_app_limited; ++ if (bbr_is_inflight_too_high(sk, &rs)) { ++ rs.tx_in_flight = bbr_inflight_hi_from_lost_skb(sk, &rs, skb); ++ bbr_handle_inflight_too_high(sk, &rs); ++ } ++} ++ ++static void bbr_run_loss_probe_recovery(struct sock *sk) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ struct rate_sample rs = {0}; ++ ++ bbr_note_loss(sk); ++ ++ if (!bbr->bw_probe_samples) ++ return; /* not sent while probing for bandwidth */ ++ /* We are probing for bandwidth. Construct a rate sample that ++ * estimates what happened in the flight leading up to this ++ * loss, then see if the loss rate went too high. ++ */ ++ rs.lost = 1; /* TLP probe repaired loss of a single segment */ ++ rs.tx_in_flight = bbr->inflight_latest + rs.lost; ++ rs.is_app_limited = tp->tlp_orig_data_app_limited; ++ if (bbr_is_inflight_too_high(sk, &rs)) ++ bbr_handle_inflight_too_high(sk, &rs); ++} ++ ++/* Revert short-term model if current loss recovery event was spurious. */ ++__bpf_kfunc static u32 bbr_undo_cwnd(struct sock *sk) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ bbr_reset_full_bw(sk); /* spurious slow-down; reset full bw detector */ ++ bbr->loss_in_round = 0; ++ ++ /* Revert to cwnd and other state saved before loss episode. */ ++ bbr->bw_lo = max(bbr->bw_lo, bbr->undo_bw_lo); ++ bbr->inflight_lo = max(bbr->inflight_lo, bbr->undo_inflight_lo); ++ bbr->inflight_hi = max(bbr->inflight_hi, bbr->undo_inflight_hi); ++ bbr->try_fast_path = 0; /* take slow path to set proper cwnd, pacing */ ++ return bbr->prior_cwnd; ++} ++ ++/* Entering loss recovery, so save state for when we undo recovery. */ ++__bpf_kfunc static u32 bbr_ssthresh(struct sock *sk) ++{ ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ bbr_save_cwnd(sk); ++ /* For undo, save state that adapts based on loss signal. */ ++ bbr->undo_bw_lo = bbr->bw_lo; ++ bbr->undo_inflight_lo = bbr->inflight_lo; ++ bbr->undo_inflight_hi = bbr->inflight_hi; ++ return tcp_sk(sk)->snd_ssthresh; ++} ++ ++static enum tcp_bbr_phase bbr_get_phase(struct bbr *bbr) ++{ ++ switch (bbr->mode) { ++ case BBR_STARTUP: ++ return BBR_PHASE_STARTUP; ++ case BBR_DRAIN: ++ return BBR_PHASE_DRAIN; ++ case BBR_PROBE_BW: ++ break; ++ case BBR_PROBE_RTT: ++ return BBR_PHASE_PROBE_RTT; ++ default: ++ return BBR_PHASE_INVALID; ++ } ++ switch (bbr->cycle_idx) { ++ case BBR_BW_PROBE_UP: ++ return BBR_PHASE_PROBE_BW_UP; ++ case BBR_BW_PROBE_DOWN: ++ return BBR_PHASE_PROBE_BW_DOWN; ++ case BBR_BW_PROBE_CRUISE: ++ return BBR_PHASE_PROBE_BW_CRUISE; ++ case BBR_BW_PROBE_REFILL: ++ return BBR_PHASE_PROBE_BW_REFILL; ++ default: ++ return BBR_PHASE_INVALID; ++ } ++} ++ ++static size_t bbr_get_info(struct sock *sk, u32 ext, int *attr, ++ union tcp_cc_info *info) ++{ ++ if (ext & (1 << (INET_DIAG_BBRINFO - 1)) || ++ ext & (1 << (INET_DIAG_VEGASINFO - 1))) { ++ struct bbr *bbr = inet_csk_ca(sk); ++ u64 bw = bbr_bw_bytes_per_sec(sk, bbr_bw(sk)); ++ u64 bw_hi = bbr_bw_bytes_per_sec(sk, bbr_max_bw(sk)); ++ u64 bw_lo = bbr->bw_lo == ~0U ? ++ ~0ULL : bbr_bw_bytes_per_sec(sk, bbr->bw_lo); ++ struct tcp_bbr_info *bbr_info = &info->bbr; ++ ++ memset(bbr_info, 0, sizeof(*bbr_info)); ++ bbr_info->bbr_bw_lo = (u32)bw; ++ bbr_info->bbr_bw_hi = (u32)(bw >> 32); ++ bbr_info->bbr_min_rtt = bbr->min_rtt_us; ++ bbr_info->bbr_pacing_gain = bbr->pacing_gain; ++ bbr_info->bbr_cwnd_gain = bbr->cwnd_gain; ++ bbr_info->bbr_bw_hi_lsb = (u32)bw_hi; ++ bbr_info->bbr_bw_hi_msb = (u32)(bw_hi >> 32); ++ bbr_info->bbr_bw_lo_lsb = (u32)bw_lo; ++ bbr_info->bbr_bw_lo_msb = (u32)(bw_lo >> 32); ++ bbr_info->bbr_mode = bbr->mode; ++ bbr_info->bbr_phase = (__u8)bbr_get_phase(bbr); ++ bbr_info->bbr_version = (__u8)BBR_VERSION; ++ bbr_info->bbr_inflight_lo = bbr->inflight_lo; ++ bbr_info->bbr_inflight_hi = bbr->inflight_hi; ++ bbr_info->bbr_extra_acked = bbr_extra_acked(sk); ++ *attr = INET_DIAG_BBRINFO; ++ return sizeof(*bbr_info); ++ } ++ return 0; ++} ++ ++__bpf_kfunc static void bbr_set_state(struct sock *sk, u8 new_state) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ struct bbr *bbr = inet_csk_ca(sk); ++ ++ if (new_state == TCP_CA_Loss) { ++ ++ bbr->prev_ca_state = TCP_CA_Loss; ++ tcp_plb_update_state_upon_rto(sk, &bbr->plb); ++ /* The tcp_write_timeout() call to sk_rethink_txhash() likely ++ * repathed this flow, so re-learn the min network RTT on the ++ * new path: ++ */ ++ bbr_reset_full_bw(sk); ++ if (!bbr_is_probing_bandwidth(sk) && bbr->inflight_lo == ~0U) { ++ /* bbr_adapt_lower_bounds() needs cwnd before ++ * we suffered an RTO, to update inflight_lo: ++ */ ++ bbr->inflight_lo = ++ max(tcp_snd_cwnd(tp), bbr->prior_cwnd); ++ } ++ } else if (bbr->prev_ca_state == TCP_CA_Loss && ++ new_state != TCP_CA_Loss) { ++ bbr_exit_loss_recovery(sk); ++ } ++} ++ ++ ++static struct tcp_congestion_ops tcp_bbr_cong_ops __read_mostly = { ++ .flags = TCP_CONG_NON_RESTRICTED | TCP_CONG_WANTS_CE_EVENTS, ++ .name = "bbr3", ++ .owner = THIS_MODULE, ++ .init = bbr_init, ++ .cong_control = bbr_main, ++ .sndbuf_expand = bbr_sndbuf_expand, ++ .skb_marked_lost = bbr_skb_marked_lost, ++ .undo_cwnd = bbr_undo_cwnd, ++ .cwnd_event = bbr_cwnd_event, ++ .cwnd_event_tx_start = bbr_cwnd_event_tx_start, ++ .ssthresh = bbr_ssthresh, ++ .tso_segs = bbr_tso_segs, ++ .get_info = bbr_get_info, ++ .set_state = bbr_set_state, ++}; ++ ++BTF_KFUNCS_START(tcp_bbr_check_kfunc_ids) ++BTF_ID_FLAGS(func, bbr_init) ++BTF_ID_FLAGS(func, bbr_main) ++BTF_ID_FLAGS(func, bbr_sndbuf_expand) ++BTF_ID_FLAGS(func, bbr_skb_marked_lost) ++BTF_ID_FLAGS(func, bbr_undo_cwnd) ++BTF_ID_FLAGS(func, bbr_cwnd_event) ++BTF_ID_FLAGS(func, bbr_cwnd_event_tx_start) ++BTF_ID_FLAGS(func, bbr_ssthresh) ++BTF_ID_FLAGS(func, bbr_tso_segs) ++BTF_ID_FLAGS(func, bbr_set_state) ++BTF_KFUNCS_END(tcp_bbr_check_kfunc_ids) ++ ++static const struct btf_kfunc_id_set tcp_bbr_kfunc_set = { ++ .owner = THIS_MODULE, ++ .set = &tcp_bbr_check_kfunc_ids, ++}; ++ ++static int __init bbr_register(void) ++{ ++ int ret; ++ ++ BUILD_BUG_ON(sizeof(struct bbr) > ICSK_CA_PRIV_SIZE); ++ ++ ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, &tcp_bbr_kfunc_set); ++ if (ret < 0) ++ return ret; ++ return tcp_register_congestion_control(&tcp_bbr_cong_ops); ++} ++ ++static void __exit bbr_unregister(void) ++{ ++ tcp_unregister_congestion_control(&tcp_bbr_cong_ops); ++} ++ ++module_init(bbr_register); ++module_exit(bbr_unregister); ++ ++MODULE_AUTHOR("Van Jacobson "); ++MODULE_AUTHOR("Neal Cardwell "); ++MODULE_AUTHOR("Yuchung Cheng "); ++MODULE_AUTHOR("Soheil Hassas Yeganeh "); ++MODULE_AUTHOR("Priyaranjan Jha "); ++MODULE_AUTHOR("Yousuk Seung "); ++MODULE_AUTHOR("Kevin Yang "); ++MODULE_AUTHOR("Arjun Roy "); ++MODULE_AUTHOR("David Morley "); ++ ++MODULE_LICENSE("Dual BSD/GPL"); ++MODULE_DESCRIPTION("TCP BBR (Bottleneck Bandwidth and RTT)"); ++MODULE_VERSION(__stringify(BBR_VERSION)); +diff --git a/net/ipv4/tcp_cong.c b/net/ipv4/tcp_cong.c +index e3f462f..6fce9ac 100644 +--- a/net/ipv4/tcp_cong.c ++++ b/net/ipv4/tcp_cong.c +@@ -238,6 +238,7 @@ void tcp_init_congestion_control(struct sock *sk) + struct inet_connection_sock *icsk = inet_csk(sk); + + tcp_sk(sk)->prior_ssthresh = 0; ++ tcp_sk(sk)->fast_ack_mode = 0; + if (icsk->icsk_ca_ops->init) + icsk->icsk_ca_ops->init(sk); + if (tcp_ca_needs_ecn(sk)) +diff --git a/net/ipv4/tcp_input.c b/net/ipv4/tcp_input.c +index 3583867..969a6db 100644 +--- a/net/ipv4/tcp_input.c ++++ b/net/ipv4/tcp_input.c +@@ -358,7 +358,7 @@ static void tcp_data_ecn_check(struct sock *sk, const struct sk_buff *skb) + tcp_enter_quickack_mode(sk, 2); + break; + case INET_ECN_CE: +- if (tcp_ca_needs_ecn(sk)) ++ if (tcp_ca_wants_ce_events(sk)) + tcp_ca_event(sk, CA_EVENT_ECN_IS_CE); + + if (!(tp->ecn_flags & TCP_ECN_DEMAND_CWR) && +@@ -376,7 +376,7 @@ static void tcp_data_ecn_check(struct sock *sk, const struct sk_buff *skb) + tp->ecn_flags |= TCP_ECN_SEEN; + break; + default: +- if (tcp_ca_needs_ecn(sk)) ++ if (tcp_ca_wants_ce_events(sk)) + tcp_ca_event(sk, CA_EVENT_ECN_NO_CE); + if (!tcp_ecn_mode_rfc3168(tp)) + break; +@@ -1323,7 +1323,12 @@ static void tcp_verify_retransmit_hint(struct tcp_sock *tp, struct sk_buff *skb) + */ + static void tcp_notify_skb_loss_event(struct tcp_sock *tp, const struct sk_buff *skb) + { ++ struct sock *sk = (struct sock *)tp; ++ const struct tcp_congestion_ops *ca_ops = inet_csk(sk)->icsk_ca_ops; ++ + tp->lost += tcp_skb_pcount(skb); ++ if (ca_ops->skb_marked_lost) ++ ca_ops->skb_marked_lost(sk, skb); + } + + void tcp_mark_skb_lost(struct sock *sk, struct sk_buff *skb) +@@ -1751,6 +1756,7 @@ static void tcp_rate_gen(struct sock *sk, u32 delivered, u32 lost, + return; + } + rs->delivered = tp->delivered - rs->prior_delivered; ++ rs->lost = tp->lost - rs->prior_lost; + + rs->delivered_ce = tp->delivered_ce - rs->prior_delivered_ce; + /* delivered_ce occupies less than 32 bits in the skb control block */ +@@ -1762,7 +1768,7 @@ static void tcp_rate_gen(struct sock *sk, u32 delivered, u32 lost, + * longer phase. + */ + snd_us = rs->interval_us; /* send phase */ +- ack_us = tcp_stamp_us_delta(tp->tcp_mstamp, ++ ack_us = tcp_stamp32_us_delta(tp->tcp_mstamp, + rs->prior_mstamp); /* ack phase */ + rs->interval_us = max(snd_us, ack_us); + +@@ -1819,19 +1825,21 @@ static void tcp_rate_skb_delivered(struct sock *sk, struct sk_buff *skb, + if (!rs->prior_delivered || + tcp_skb_sent_after(tx_tstamp, tp->first_tx_mstamp, + scb->end_seq, rs->last_end_seq)) { ++ rs->prior_lost = scb->tx.lost; + rs->prior_delivered_ce = scb->tx.delivered_ce; + rs->prior_delivered = scb->tx.delivered; + rs->prior_mstamp = scb->tx.delivered_mstamp; + rs->is_app_limited = scb->tx.is_app_limited; + rs->is_retrans = scb->sacked & TCPCB_RETRANS; ++ rs->tx_in_flight = scb->tx.in_flight; + rs->last_end_seq = scb->end_seq; + + /* Record send time of most recently ACKed packet: */ + tp->first_tx_mstamp = tx_tstamp; + /* Find the duration of the "send phase" of this window: */ +- rs->interval_us = tcp_stamp_us_delta(tp->first_tx_mstamp, +- scb->tx.first_tx_mstamp); +- ++ rs->interval_us = tcp_stamp32_us_delta( ++ tp->first_tx_mstamp, ++ scb->tx.first_tx_mstamp); + } + /* Mark off the skb delivered once it's sacked to avoid being + * used again when it's cumulatively acked. For acked packets +@@ -1874,6 +1882,17 @@ static bool tcp_shifted_skb(struct sock *sk, struct sk_buff *prev, + WARN_ON_ONCE(tcp_skb_pcount(skb) < pcount); + tcp_skb_pcount_add(skb, -pcount); + ++ /* Adjust tx.in_flight as pcount is shifted from skb to prev. */ ++ if (WARN_ONCE(TCP_SKB_CB(skb)->tx.in_flight < pcount, ++ "prev in_flight: %u skb in_flight: %u pcount: %u", ++ TCP_SKB_CB(prev)->tx.in_flight, ++ TCP_SKB_CB(skb)->tx.in_flight, ++ pcount)) ++ TCP_SKB_CB(skb)->tx.in_flight = 0; ++ else ++ TCP_SKB_CB(skb)->tx.in_flight -= pcount; ++ TCP_SKB_CB(prev)->tx.in_flight += pcount; ++ + /* When we're adding to gso_segs == 1, gso_size will be zero, + * in theory this shouldn't be necessary but as long as DSACK + * code can come after this skb later on it's better to keep +@@ -4139,7 +4158,8 @@ static int tcp_replace_ts_recent(struct tcp_sock *tp, u32 seq) + /* This routine deals with acks during a TLP episode and ends an episode by + * resetting tlp_high_seq. Ref: TLP algorithm in RFC8985 + */ +-static void tcp_process_tlp_ack(struct sock *sk, u32 ack, int flag) ++static void tcp_process_tlp_ack(struct sock *sk, u32 ack, int flag, ++ struct rate_sample *rs) + { + struct tcp_sock *tp = tcp_sk(sk); + +@@ -4156,6 +4176,7 @@ static void tcp_process_tlp_ack(struct sock *sk, u32 ack, int flag) + /* ACK advances: there was a loss, so reduce cwnd. Reset + * tlp_high_seq in tcp_init_cwnd_reduction() + */ ++ tcp_ca_event(sk, CA_EVENT_TLP_RECOVERY); + tcp_init_cwnd_reduction(sk); + tcp_set_ca_state(sk, TCP_CA_CWR); + tcp_end_cwnd_reduction(sk); +@@ -4166,6 +4187,11 @@ static void tcp_process_tlp_ack(struct sock *sk, u32 ack, int flag) + FLAG_NOT_DUP | FLAG_DATA_SACKED))) { + /* Pure dupack: original and TLP probe arrived; no loss */ + tp->tlp_high_seq = 0; ++ } else { ++ /* This ACK matches a TLP retransmit. We cannot yet tell if ++ * this ACK is for the original or the TLP retransmit. ++ */ ++ rs->is_acking_tlp_retrans_seq = 1; + } + } + +@@ -4339,6 +4365,7 @@ static int tcp_ack(struct sock *sk, const struct sk_buff *skb, int flag) + + prior_fack = tcp_is_sack(tp) ? tcp_highest_sack_seq(tp) : tp->snd_una; + rs.prior_in_flight = tcp_packets_in_flight(tp); ++ tcp_rate_check_app_limited(sk); + + /* ts_recent update must be made after we are sure that the packet + * is in window. +@@ -4411,7 +4438,7 @@ static int tcp_ack(struct sock *sk, const struct sk_buff *skb, int flag) + tcp_in_ack_event(sk, flag); + + if (unlikely(tp->tlp_high_seq)) +- tcp_process_tlp_ack(sk, ack, flag); ++ tcp_process_tlp_ack(sk, ack, flag, &rs); + + if (tcp_ack_is_dubious(sk, flag)) { + if (!(flag & (FLAG_SND_UNA_ADVANCED | +@@ -4436,6 +4463,7 @@ static int tcp_ack(struct sock *sk, const struct sk_buff *skb, int flag) + + lost = tp->lost - lost; /* freshly marked lost */ + rs.is_ack_delayed = !!(flag & FLAG_ACK_MAYBE_DELAYED); ++ rs.is_ece = !!(flag & FLAG_ECE); + tcp_rate_gen(sk, delivered, lost, is_sack_reneg, sack_state.rate); + tcp_cong_control(sk, ack, delivered, flag, sack_state.rate); + tcp_xmit_recovery(sk, rexmit); +@@ -4461,7 +4489,7 @@ static int tcp_ack(struct sock *sk, const struct sk_buff *skb, int flag) + tcp_ack_probe(sk); + + if (unlikely(tp->tlp_high_seq)) +- tcp_process_tlp_ack(sk, ack, flag); ++ tcp_process_tlp_ack(sk, ack, flag, &rs); + return 1; + + old_ack: +@@ -6127,13 +6155,14 @@ static void __tcp_ack_snd_check(struct sock *sk, int ofo_possible) + + /* More than one full frame received... */ + if (((tp->rcv_nxt - tp->rcv_wup) > inet_csk(sk)->icsk_ack.rcv_mss && ++ (tp->fast_ack_mode == 1 || + /* ... and right edge of window advances far enough. + * (tcp_recvmsg() will send ACK otherwise). + * If application uses SO_RCVLOWAT, we want send ack now if + * we have not received enough bytes to satisfy the condition. + */ +- (tp->rcv_nxt - tp->copied_seq < sk->sk_rcvlowat || +- __tcp_select_window(sk) >= tp->rcv_wnd)) || ++ (tp->rcv_nxt - tp->copied_seq < sk->sk_rcvlowat || ++ __tcp_select_window(sk) >= tp->rcv_wnd))) || + /* We ACK each frame or... */ + tcp_in_quickack_mode(sk) || + /* Protocol state mandates a one-time immediate ACK */ +diff --git a/net/ipv4/tcp_minisocks.c b/net/ipv4/tcp_minisocks.c +index 0ddfd5a..72c2780 100644 +--- a/net/ipv4/tcp_minisocks.c ++++ b/net/ipv4/tcp_minisocks.c +@@ -500,6 +500,8 @@ void tcp_ca_openreq_child(struct sock *sk, const struct dst_entry *dst) + u32 ca_key = dst_metric(dst, RTAX_CC_ALGO); + bool ca_got_dst = false; + ++ tcp_set_ecn_low_from_dst(sk, dst); ++ + if (ca_key != TCP_CA_UNSPEC) { + const struct tcp_congestion_ops *ca; + +diff --git a/net/ipv4/tcp_output.c b/net/ipv4/tcp_output.c +index 9f47b66..7982197 100644 +--- a/net/ipv4/tcp_output.c ++++ b/net/ipv4/tcp_output.c +@@ -365,7 +365,8 @@ static void tcp_ecn_send(struct sock *sk, struct sk_buff *skb, + th->cwr = 1; + skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN; + } +- } else if (!tcp_ca_needs_ecn(sk)) { ++ } else if (!(tp->ecn_flags & TCP_ECN_ECT_PERMANENT) && ++ !tcp_ca_needs_ecn(sk)) { + /* ACK or retransmitted segment: clear ECT|CE */ + INET_ECN_dontxmit(sk); + } +@@ -1467,6 +1468,24 @@ static void tcp_update_skb_after_send(struct sock *sk, struct sk_buff *skb, + list_move_tail(&skb->tcp_tsorted_anchor, &tp->tsorted_sent_queue); + } + ++static void tcp_set_tx_in_flight(struct sock *sk, struct sk_buff *skb) ++{ ++ struct tcp_sock *tp = tcp_sk(sk); ++ u32 in_flight; ++ ++ /* Check, sanitize, and record packets in flight after skb was sent. */ ++ in_flight = tcp_packets_in_flight(tp) + tcp_skb_pcount(skb); ++ if (WARN_ONCE(in_flight > TCPCB_IN_FLIGHT_MAX, ++ "insane in_flight %u cc %s mss %u " ++ "cwnd %u pif %u %u %u %u\n", ++ in_flight, inet_csk(sk)->icsk_ca_ops->name, ++ tp->mss_cache, tp->snd_cwnd, ++ tp->packets_out, tp->retrans_out, ++ tp->sacked_out, tp->lost_out)) ++ in_flight = TCPCB_IN_FLIGHT_MAX; ++ TCP_SKB_CB(skb)->tx.in_flight = in_flight; ++} ++ + /* Snapshot the current delivery information in the skb, to generate + * a rate sample later when the skb is (s)acked in tcp_rate_skb_delivered(). + */ +@@ -1499,7 +1518,9 @@ static void tcp_rate_skb_sent(struct sock *sk, struct sk_buff *skb) + TCP_SKB_CB(skb)->tx.delivered_mstamp = tp->delivered_mstamp; + TCP_SKB_CB(skb)->tx.delivered = tp->delivered; + TCP_SKB_CB(skb)->tx.delivered_ce = tp->delivered_ce; ++ TCP_SKB_CB(skb)->tx.lost = tp->lost; + TCP_SKB_CB(skb)->tx.is_app_limited = tp->app_limited ? 1 : 0; ++ tcp_set_tx_in_flight(sk, skb); + } + + INDIRECT_CALLABLE_DECLARE(int ip_queue_xmit(struct sock *sk, struct sk_buff *skb, struct flowi *fl)); +@@ -1847,7 +1868,7 @@ int tcp_fragment(struct sock *sk, enum tcp_queue tcp_queue, + { + struct tcp_sock *tp = tcp_sk(sk); + struct sk_buff *buff; +- int old_factor; ++ int old_factor, inflight_prev; + long limit; + u16 flags; + int nlen; +@@ -1922,6 +1943,30 @@ int tcp_fragment(struct sock *sk, enum tcp_queue tcp_queue, + + if (diff) + tcp_adjust_pcount(sk, skb, diff); ++ ++ inflight_prev = TCP_SKB_CB(skb)->tx.in_flight - old_factor; ++ if (inflight_prev < 0) { ++ WARN_ONCE(tcp_skb_tx_in_flight_is_suspicious( ++ old_factor, ++ TCP_SKB_CB(skb)->sacked, ++ TCP_SKB_CB(skb)->tx.in_flight), ++ "inconsistent: tx.in_flight: %u " ++ "old_factor: %d mss: %u sacked: %u " ++ "1st pcount: %d 2nd pcount: %d " ++ "1st len: %u 2nd len: %u ", ++ TCP_SKB_CB(skb)->tx.in_flight, old_factor, ++ mss_now, TCP_SKB_CB(skb)->sacked, ++ tcp_skb_pcount(skb), tcp_skb_pcount(buff), ++ skb->len, buff->len); ++ inflight_prev = 0; ++ } ++ /* Set 1st tx.in_flight as if 1st were sent by itself: */ ++ TCP_SKB_CB(skb)->tx.in_flight = inflight_prev + ++ tcp_skb_pcount(skb); ++ /* Set 2nd tx.in_flight with new 1st and 2nd pcounts: */ ++ TCP_SKB_CB(buff)->tx.in_flight = inflight_prev + ++ tcp_skb_pcount(skb) + ++ tcp_skb_pcount(buff); + } + + /* Link BUFF into the send queue. */ +@@ -2276,13 +2321,12 @@ static u32 tcp_tso_autosize(const struct sock *sk, unsigned int mss_now, + static u32 tcp_tso_segs(struct sock *sk, unsigned int mss_now) + { + const struct tcp_congestion_ops *ca_ops = inet_csk(sk)->icsk_ca_ops; +- u32 min_tso, tso_segs; +- +- min_tso = ca_ops->min_tso_segs ? +- ca_ops->min_tso_segs(sk) : +- READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_min_tso_segs); ++ u32 tso_segs; + +- tso_segs = tcp_tso_autosize(sk, mss_now, min_tso); ++ tso_segs = ca_ops->tso_segs ? ++ ca_ops->tso_segs(sk, mss_now) : ++ tcp_tso_autosize(sk, mss_now, ++ sock_net(sk)->ipv4.sysctl_tcp_min_tso_segs); + return min_t(u32, tso_segs, sk->sk_gso_max_segs); + } + +@@ -3000,6 +3044,7 @@ static bool tcp_write_xmit(struct sock *sk, unsigned int mss_now, int nonagle, + skb_set_delivery_time(skb, tp->tcp_wstamp_ns, SKB_CLOCK_MONOTONIC); + list_move_tail(&skb->tcp_tsorted_anchor, &tp->tsorted_sent_queue); + tcp_init_tso_segs(skb, mss_now); ++ tcp_set_tx_in_flight(sk, skb); + goto repair; /* Skip network transmission */ + } + +@@ -3212,6 +3257,7 @@ void tcp_send_loss_probe(struct sock *sk) + if (WARN_ON(!skb || !tcp_skb_pcount(skb))) + goto rearm_timer; + ++ tp->tlp_orig_data_app_limited = TCP_SKB_CB(skb)->tx.is_app_limited; + if (__tcp_retransmit_skb(sk, skb, 1)) + goto rearm_timer; + +diff --git a/net/ipv4/tcp_timer.c b/net/ipv4/tcp_timer.c +index e56eae4..db33717 100644 +--- a/net/ipv4/tcp_timer.c ++++ b/net/ipv4/tcp_timer.c +@@ -708,6 +708,7 @@ void tcp_write_timer_handler(struct sock *sk) + tcp_timeout_expires(sk)); + return; + } ++ tcp_rate_check_app_limited(sk); + tcp_mstamp_refresh(tcp_sk(sk)); + event = icsk->icsk_pending; + +diff --git a/tools/testing/selftests/bpf/progs/tcp_ca_kfunc.c b/tools/testing/selftests/bpf/progs/tcp_ca_kfunc.c +index 0a3e9d3..4fb0a59 100644 +--- a/tools/testing/selftests/bpf/progs/tcp_ca_kfunc.c ++++ b/tools/testing/selftests/bpf/progs/tcp_ca_kfunc.c +@@ -8,6 +8,7 @@ extern void bbr_init(struct sock *sk) __ksym; + extern void bbr_main(struct sock *sk, u32 ack, int flag, const struct rate_sample *rs) __ksym; + extern u32 bbr_sndbuf_expand(struct sock *sk) __ksym; + extern u32 bbr_undo_cwnd(struct sock *sk) __ksym; ++extern void bbr_cwnd_event(struct sock *sk, enum tcp_ca_event event) __ksym; + extern void bbr_cwnd_event_tx_start(struct sock *sk) __ksym; + extern u32 bbr_ssthresh(struct sock *sk) __ksym; + extern u32 bbr_min_tso_segs(struct sock *sk) __ksym; +@@ -70,6 +71,7 @@ u32 BPF_PROG(undo_cwnd, struct sock *sk) + SEC("struct_ops") + void BPF_PROG(cwnd_event, struct sock *sk, enum tcp_ca_event event) + { ++ bbr_cwnd_event(sk, event); + dctcp_cwnd_event(sk, event); + } + diff --git a/releases/v7.3.5-zako1/patches/0002-sched-bore-7.0.0.patch b/releases/v7.3.5-zako1/patches/0002-sched-bore-7.0.0.patch new file mode 100644 index 0000000..4f47c2f --- /dev/null +++ b/releases/v7.3.5-zako1/patches/0002-sched-bore-7.0.0.patch @@ -0,0 +1,1409 @@ +From 8e0f25bdcc68fa437072260acc6b4347ece2a794 Mon Sep 17 00:00:00 2001 +From: Masahito S +Date: Sat, 19 Sep 2026 00:31:35 +0900 +Subject: [PATCH] sched-bore-7.0.0-rebased-for-7.3.5 + +Rebased onto v7.3.5 (linux-libre 7.3.5 + 0001-zen-7.3.5-zen1). Two conflict +sites were resolved by hand: + + * kernel/sched/fair.c: the CONFIG_SCHED_BORE base-slice definitions are + nested inside the existing CONFIG_ZEN_INTERACTIVE block, so BORE wins + when it is enabled and zen's 400000/700000 values are kept otherwise. + * kernel/sched/debug.c: base_slice_ns / min_base_slice_ns and the + tunable_scaling helper are placed inside zen's existing + #ifndef CONFIG_SCHED_ALT regions. + +Signed-off-by: Masahito S +--- + include/linux/sched.h | 29 +++ + include/linux/sched/bore.h | 64 ++++++ + init/Kconfig | 17 ++ + kernel/Kconfig.hz | 17 ++ + kernel/exit.c | 4 + + kernel/fork.c | 13 ++ + kernel/futex/waitwake.c | 11 + + kernel/sched/Makefile | 1 + + kernel/sched/bore.c | 530 +++++++++++++++++++++++++++++++++++++++++++ + kernel/sched/build_utility.c | 4 + + kernel/sched/core.c | 12 + + kernel/sched/debug.c | 61 +++++ + kernel/sched/fair.c | 188 ++++++++++++++- + kernel/sched/sched.h | 9 + + 14 files changed, 948 insertions(+), 12 deletions(-) + +diff --git a/include/linux/sched.h b/include/linux/sched.h +index 2d1fa5440..8a7bfc9a4 100644 +--- a/include/linux/sched.h ++++ b/include/linux/sched.h +@@ -832,6 +832,32 @@ struct task_ipi_mask { + struct task_ipi_mask { }; + #endif + ++#ifdef CONFIG_SCHED_BORE ++#define BORE_BC_TIMESTAMP_SHIFT 16 ++ ++struct bore_bc { ++ union { ++ struct { ++ u64 timestamp: 48; ++ u64 penalty: 16; ++ }; ++ u64 value; ++ }; ++}; ++ ++struct bore_ctx { ++ u64 burst_time; ++ u64 credit_sleep; ++ u16 prev_penalty; ++ u16 curr_penalty; ++ u16 penalty; ++ bool stop_update; ++ bool futex_waiting; ++ struct bore_bc subtree; ++ struct bore_bc group; ++}; ++#endif /* CONFIG_SCHED_BORE */ ++ + struct task_struct { + #ifdef CONFIG_THREAD_INFO_IN_TASK + /* +@@ -915,6 +941,9 @@ struct task_struct { + #ifdef CONFIG_SCHED_CLASS_EXT + struct sched_ext_entity scx; + #endif ++#ifdef CONFIG_SCHED_BORE ++ struct bore_ctx bore; ++#endif /* CONFIG_SCHED_BORE */ + const struct sched_class *sched_class; + + #ifdef CONFIG_SCHED_CORE +diff --git a/include/linux/sched/bore.h b/include/linux/sched/bore.h +new file mode 100644 +index 000000000..017207fb8 +--- /dev/null ++++ b/include/linux/sched/bore.h +@@ -0,0 +1,64 @@ ++#ifndef _KERNEL_SCHED_BORE_H ++#define _KERNEL_SCHED_BORE_H ++ ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#define SCHED_BORE_AUTHOR "Masahito Suzuki" ++#define SCHED_BORE_PROGNAME "BORE CPU Scheduler modification" ++ ++#define SCHED_BORE_VERSION "7.0.0" ++ ++extern u8 __read_mostly sched_bore; ++DECLARE_STATIC_KEY_TRUE(sched_bore_key); ++extern u8 __read_mostly sched_burst_inherit_type; ++extern u8 __read_mostly sched_burst_smoothness; ++extern u8 __read_mostly sched_burst_penalty_offset; ++extern uint __read_mostly sched_burst_penalty_scale; ++extern uint __read_mostly sched_burst_cache_lifetime; ++extern u8 __read_mostly sched_burst_protect_slice_lv; ++ ++extern uint __read_mostly sched_credit_cap_us; ++DECLARE_STATIC_KEY_FALSE(sched_credit_key); ++ ++extern void bore_note_sleep(struct task_struct *p, u64 now); ++extern u64 bore_credit_ns(struct task_struct *p); ++ ++DECLARE_STATIC_KEY_TRUE(sched_burst_protect_slice_cond_key); ++DECLARE_STATIC_KEY_FALSE(sched_burst_protect_slice_prefer_key); ++ ++static inline u8 bore_score(struct task_struct *p) ++{ return p->bore.penalty >> 8; } ++ ++extern u8 effective_prio_bore(struct task_struct *p); ++extern void update_curr_bore(struct task_struct *p, u64 delta_exec); ++extern void restart_burst_bore(struct task_struct *p); ++extern void restart_burst_rescale_deadline_bore(struct task_struct *p); ++extern void task_fork_bore(struct task_struct *p, struct task_struct *parent, ++ u64 clone_flags, u64 now); ++extern void sched_init_bore(void); ++extern void reset_task_bore(struct task_struct *p); ++ ++extern int sched_bore_update_handler(const struct ctl_table *table, ++ int write, void __user *buffer, size_t *lenp, loff_t *ppos); ++extern int sched_burst_inherit_type_update_handler(const struct ctl_table *table, ++ int write, void __user *buffer, size_t *lenp, loff_t *ppos); ++extern int sched_burst_protect_slice_lv_update_handler(const struct ctl_table *table, ++ int write, void __user *buffer, size_t *lenp, loff_t *ppos); ++extern int sched_credit_cap_us_update_handler(const struct ctl_table *table, ++ int write, void __user *buffer, size_t *lenp, loff_t *ppos); ++ ++/* ++ * v7.3 split the old reweight_entity() into reweight_entity() (raw se->load ++ * plus PELT) and reweight_eevdf() (the flattened EEVDF se->h_load carried on ++ * the root cfs_rq). reweight_task_fair() is the single entry point that keeps ++ * both halves consistent, so BORE drives that instead. ++ */ ++extern void reweight_task_fair(struct rq *rq, struct task_struct *p, ++ const struct load_weight *lw); ++ ++#endif /* _KERNEL_SCHED_BORE_H */ +diff --git a/init/Kconfig b/init/Kconfig +index 0f0ca9497..968ef263c 100644 +--- a/init/Kconfig ++++ b/init/Kconfig +@@ -1600,6 +1600,23 @@ config CHECKPOINT_RESTORE + + If unsure, say N here. + ++config SCHED_BORE ++ bool "Burst-Oriented Response Enhancer" ++ default y ++ help ++ In Desktop and Mobile computing, one might prefer interactive ++ tasks to keep responsive no matter what they run in the background. ++ ++ Enabling this kernel feature modifies the scheduler to discriminate ++ tasks by their burst time (runtime since it last went sleeping or ++ yielding state) and prioritize those that run less bursty. ++ Such tasks usually include window compositor, widgets backend, ++ terminal emulator, video playback, games and so on. ++ With a little impact to scheduling fairness, it may improve ++ responsiveness especially under heavy background workload. ++ ++ If unsure, say Y here. ++ + config SCHED_AUTOGROUP + bool "Automatic process group scheduling" + depends on !SCHED_ALT +diff --git a/kernel/Kconfig.hz b/kernel/Kconfig.hz +index ce1435cb0..9eee2005e 100644 +--- a/kernel/Kconfig.hz ++++ b/kernel/Kconfig.hz +@@ -57,3 +57,20 @@ config HZ + + config SCHED_HRTICK + def_bool HIGH_RES_TIMERS ++ ++config MIN_BASE_SLICE_NS ++ int "Default value for min_base_slice_ns" ++ default 2000000 ++ help ++ The BORE Scheduler automatically calculates the optimal base ++ slice for the configured HZ using the following equation: ++ ++ base_slice_ns = ++ 1000000000/HZ * DIV_ROUNDUP(min_base_slice_ns, 1000000000/HZ) ++ ++ This option sets the default lower bound limit of the base slice ++ to prevent the loss of task throughput due to overscheduling. ++ ++ Setting this value too high can cause the system to boot with ++ an unnecessarily large base slice, resulting in high scheduling ++ latency and poor system responsiveness. +diff --git a/kernel/exit.c b/kernel/exit.c +index 263b422f0..7cc1a36e3 100644 +--- a/kernel/exit.c ++++ b/kernel/exit.c +@@ -146,7 +146,11 @@ static void __unhash_process(struct release_task_post *post, struct task_struct + detach_pid(post->pids, p, PIDTYPE_SID); + + list_del_rcu(&p->tasks); ++#ifdef CONFIG_SCHED_BORE ++ list_del_rcu(&p->sibling); ++#else /* !CONFIG_SCHED_BORE */ + list_del_init(&p->sibling); ++#endif /* CONFIG_SCHED_BORE */ + __this_cpu_dec(process_counts); + } + list_del_rcu(&p->thread_node); +diff --git a/kernel/fork.c b/kernel/fork.c +index 9566b9977..088903782 100644 +--- a/kernel/fork.c ++++ b/kernel/fork.c +@@ -120,6 +120,10 @@ + /* For dup_mmap(). */ + #include "../mm/internal.h" + ++#ifdef CONFIG_SCHED_BORE ++#include ++#endif /* CONFIG_SCHED_BORE */ ++ + #include + + #define CREATE_TRACE_POINTS +@@ -2489,6 +2493,11 @@ __latent_entropy struct task_struct *copy_process( + p->start_time = ktime_get_ns(); + p->start_boottime = ktime_get_boottime_ns(); + ++#ifdef CONFIG_SCHED_BORE ++ if (likely(p->pid)) ++ task_fork_bore(p, current, clone_flags, p->start_time); ++#endif /* CONFIG_SCHED_BORE */ ++ + /* + * Make it visible to the rest of the system, but dont wake it up yet. + * Need tasklist lock for parent etc handling! +@@ -2574,7 +2583,11 @@ __latent_entropy struct task_struct *copy_process( + p->real_parent->signal->is_child_subreaper; + if (clone_flags & CLONE_AUTOREAP) + p->signal->autoreap = 1; ++#ifdef CONFIG_SCHED_BORE ++ list_add_tail_rcu(&p->sibling, &p->real_parent->children); ++#else /* !CONFIG_SCHED_BORE */ + list_add_tail(&p->sibling, &p->real_parent->children); ++#endif /* CONFIG_SCHED_BORE */ + list_add_tail_rcu(&p->tasks, &init_task.tasks); + attach_pid(p, PIDTYPE_TGID); + attach_pid(p, PIDTYPE_PGID); +diff --git a/kernel/futex/waitwake.c b/kernel/futex/waitwake.c +index d4483d15d..7fa31c8d7 100644 +--- a/kernel/futex/waitwake.c ++++ b/kernel/futex/waitwake.c +@@ -4,6 +4,9 @@ + #include + #include + #include ++#ifdef CONFIG_SCHED_BORE ++#include ++#endif /* CONFIG_SCHED_BORE */ + + #include "futex.h" + +@@ -384,7 +387,15 @@ void futex_do_wait(struct futex_q *q, struct hrtimer_sleeper *timeout) + * is no timeout, or if it has yet to expire. + */ + if (!timeout || timeout->task) ++#ifdef CONFIG_SCHED_BORE ++ { ++ current->bore.futex_waiting = true; ++#endif /* CONFIG_SCHED_BORE */ + schedule(); ++#ifdef CONFIG_SCHED_BORE ++ current->bore.futex_waiting = false; ++ } ++#endif /* CONFIG_SCHED_BORE */ + } + __set_current_state(TASK_RUNNING); + } +diff --git a/kernel/sched/Makefile b/kernel/sched/Makefile +index 0c1f4f030..b127506f4 100644 +--- a/kernel/sched/Makefile ++++ b/kernel/sched/Makefile +@@ -46,3 +46,4 @@ obj-y += fair.o + endif + obj-y += build_policy.o + obj-y += build_utility.o ++obj-$(CONFIG_SCHED_BORE) += bore.o +diff --git a/kernel/sched/bore.c b/kernel/sched/bore.c +new file mode 100644 +index 000000000..1a3952271 +--- /dev/null ++++ b/kernel/sched/bore.c +@@ -0,0 +1,530 @@ ++/* ++ * Burst-Oriented Response Enhancer (BORE) CPU Scheduler ++ * Copyright (C) 2021-2025 Masahito Suzuki ++ */ ++#include ++#include ++#include ++#include "sched.h" ++ ++#ifdef CONFIG_SCHED_BORE ++DEFINE_STATIC_KEY_TRUE(sched_bore_key); ++u8 __read_mostly sched_bore = 1; ++u8 __read_mostly sched_burst_inherit_type = 2; ++u8 __read_mostly sched_burst_protect_slice_lv = 1; ++u8 __read_mostly sched_burst_smoothness = 1; ++u8 __read_mostly sched_burst_penalty_offset = 24; ++uint __read_mostly sched_burst_penalty_scale = 1536; ++uint __read_mostly sched_burst_cache_lifetime = 75000000; ++ ++uint __read_mostly sched_credit_cap_us = 16000; ++ ++static int __maybe_unused maxval_prio = 39; ++static int __maybe_unused maxval_6_bits = 63; ++static int __maybe_unused maxval_8_bits = 255; ++static int __maybe_unused maxval_12_bits = 4095; ++static int __maybe_unused maxval_16_bits = 65535; ++static int __maybe_unused maxval_1_million = 1000000; ++ ++#define MAX_BURST_PENALTY ((40U << 8) - 1) ++#define BURST_CACHE_SAMPLE_LIMIT 63 ++#define BURST_CACHE_SCAN_LIMIT (BURST_CACHE_SAMPLE_LIMIT * 2) ++ ++static u32 bore_reciprocal_lut[BURST_CACHE_SAMPLE_LIMIT + 1]; ++ ++DEFINE_STATIC_KEY_TRUE(sched_burst_inherit_key); ++DEFINE_STATIC_KEY_TRUE(sched_burst_ancestor_key); ++DEFINE_STATIC_KEY_TRUE (sched_burst_protect_slice_cond_key); ++DEFINE_STATIC_KEY_FALSE(sched_burst_protect_slice_prefer_key); ++DEFINE_STATIC_KEY_FALSE(sched_credit_key); ++ ++static inline u32 log2p1_u64_u32fp(u64 v, u8 fp) { ++ if (unlikely(!v)) return 0; ++ int clz = __builtin_clzll(v); ++ int exponent = 64 - clz; ++ u32 mantissa = (u32)((v << clz) << 1 >> (64 - fp)); ++ return exponent << fp | mantissa; ++} ++ ++void bore_note_sleep(struct task_struct *p, u64 now) ++{ ++ p->bore.credit_sleep = now; ++} ++ ++u64 bore_credit_ns(struct task_struct *p) ++{ ++ u64 cap = (u64)sched_credit_cap_us * 1000ULL; ++ u64 slept = 0, credit = 0; ++ ++ if (p->bore.credit_sleep) { ++ slept = rq_clock(task_rq(p)) - p->bore.credit_sleep; ++ if ((s64)slept > 0) { ++ p->bore.credit_sleep = 0; ++ credit = slept < cap ? slept : cap; ++ } else { ++ slept = 0; ++ } ++ } ++ ++ return credit; ++} ++ ++static inline u32 calc_burst_penalty(u64 burst_time) { ++ u32 greed = log2p1_u64_u32fp(burst_time, 8), ++ tolerance = sched_burst_penalty_offset << 8; ++ s32 diff = (s32)(greed - tolerance); ++ u32 penalty = diff & ~(diff >> 31); ++ u32 scaled_penalty = penalty * sched_burst_penalty_scale >> 10; ++ s32 overflow = scaled_penalty - MAX_BURST_PENALTY; ++ return scaled_penalty - (overflow & ~(overflow >> 31)); ++} ++ ++static inline u64 rescale_slice(u64 delta, u8 old_prio, u8 new_prio) { ++ u64 unscaled, rescaled; ++ unscaled = mul_u64_u32_shr(delta , sched_prio_to_weight[old_prio], 10); ++ rescaled = mul_u64_u32_shr(unscaled, sched_prio_to_wmult [new_prio], 22); ++ return rescaled; ++} ++ ++static inline u32 binary_smooth(u32 new, u32 old) { ++ u32 is_growing = (new > old); ++ u32 increment = (new - old) * is_growing; ++ u32 shift = sched_burst_smoothness; ++ u32 smoothed = old + ((increment + (1U << shift) - 1) >> shift); ++ return (new & ~(-is_growing)) | (smoothed & (-is_growing)); ++} ++ ++static void reweight_task_by_prio(struct task_struct *p, int prio) { ++ if (task_has_idle_policy(p)) return; ++ ++ struct sched_entity *se = &p->se; ++ struct load_weight lw = { ++ .weight = scale_load(sched_prio_to_weight[prio]), ++ .inv_weight = sched_prio_to_wmult[prio], ++ }; ++ ++ if (se->on_rq) { ++ /* ++ * reweight_task_fair() commits the current task's runtime via ++ * update_curr_fair() first; stop_update keeps that from ++ * re-entering the burst accounting we are in the middle of. ++ */ ++ p->bore.stop_update = true; ++ reweight_task_fair(task_rq(p), p, &lw); ++ p->bore.stop_update = false; ++ } else { ++ se->load.weight = lw.weight; ++ se->load.inv_weight = lw.inv_weight; ++ } ++} ++ ++u8 effective_prio_bore(struct task_struct *p) { ++ int prio = p->static_prio - MAX_RT_PRIO; ++ if (static_branch_likely(&sched_bore_key)) ++ prio += bore_score(p); ++ prio &= ~(prio >> 31); ++ s32 diff = prio - maxval_prio; ++ prio -= (diff & ~(diff >> 31)); ++ return (u8)prio; ++} ++ ++static void update_penalty(struct task_struct *p) { ++ struct bore_ctx *ctx = &p->bore; ++ ++ u8 prev_prio = effective_prio_bore(p); ++ ++ s32 diff = (s32)ctx->curr_penalty - (s32)ctx->prev_penalty; ++ u16 max_val = ctx->curr_penalty - (diff & (diff >> 31)); ++ u32 is_kthread = !!(p->flags & PF_KTHREAD); ++ ctx->penalty = max_val & -(s32)(!is_kthread); ++ ++ u8 new_prio = effective_prio_bore(p); ++ if (new_prio != prev_prio) ++ reweight_task_by_prio(p, new_prio); ++} ++ ++void update_curr_bore(struct task_struct *p, u64 delta_exec) { ++ struct bore_ctx *ctx = &p->bore; ++ if (ctx->stop_update) return; ++ ++ ctx->burst_time += delta_exec; ++ u32 curr_penalty = ctx->curr_penalty = calc_burst_penalty(ctx->burst_time); ++ ++ if (curr_penalty <= ctx->prev_penalty) return; ++ update_penalty(p); ++} ++ ++void restart_burst_bore(struct task_struct *p) { ++ struct bore_ctx *ctx = &p->bore; ++ u32 new_penalty = binary_smooth(ctx->curr_penalty, ctx->prev_penalty); ++ ctx->prev_penalty = new_penalty; ++ ctx->curr_penalty = 0; ++ ctx->burst_time = 0; ++ update_penalty(p); ++} ++ ++void restart_burst_rescale_deadline_bore(struct task_struct *p) { ++ struct sched_entity *se = &p->se; ++ s64 vscaled, vremain = se->deadline - se->vruntime; ++ ++ u8 old_prio = effective_prio_bore(p); ++ restart_burst_bore(p); ++ u8 new_prio = effective_prio_bore(p); ++ ++ if (old_prio > new_prio) { ++ vscaled = rescale_slice(abs(vremain), old_prio, new_prio); ++ if (unlikely(vremain < 0)) ++ vscaled = -vscaled; ++ se->deadline = se->vruntime + vscaled; ++ } ++} ++ ++static inline bool task_is_bore_eligible(struct task_struct *p) ++{return p && p->sched_class == &fair_sched_class && !p->exit_state;} ++ ++#ifndef for_each_child_task ++#define for_each_child_task(p, t) \ ++ list_for_each_entry_rcu(t, &(p)->children, sibling) ++#endif ++ ++static inline u32 count_children_upto2(struct task_struct *p) { ++ struct list_head *head = &p->children; ++ struct list_head *first = READ_ONCE(head->next); ++ struct list_head *second = READ_ONCE(first->next); ++ return (first != head) + (second != head); ++} ++ ++static inline bool burst_cache_expired(struct bore_bc *bc, u64 now) { ++ struct bore_bc bc_val = { .value = READ_ONCE(bc->value) }; ++ u64 timestamp = (u64)bc_val.timestamp << BORE_BC_TIMESTAMP_SHIFT; ++ return now - timestamp > (u64)sched_burst_cache_lifetime; ++} ++ ++static void update_burst_cache(struct bore_bc *bc, ++ struct task_struct *p, u32 count, u32 total, u64 now) { ++ u32 average = (count == 1) ? total : ++ (u32)(((u64)total * bore_reciprocal_lut[count]) >> 32); ++ ++ struct bore_bc new_bc = { ++ .penalty = max(average, p->bore.penalty), ++ .timestamp = now >> BORE_BC_TIMESTAMP_SHIFT ++ }; ++ WRITE_ONCE(bc->value, new_bc.value); ++} ++ ++static u32 inherit_from_parent(struct task_struct *parent, ++ u64 clone_flags, u64 now) { ++ struct bore_bc bc_val; ++ ++ if (clone_flags & CLONE_PARENT) ++ parent = rcu_dereference(parent->real_parent); ++ ++ struct bore_bc *bc = &parent->bore.subtree; ++ ++ if (burst_cache_expired(bc, now)) { ++ struct task_struct *child; ++ u32 count = 0, total = 0, scan_count = 0; ++ for_each_child_task(parent, child) { ++ if (count >= BURST_CACHE_SAMPLE_LIMIT) break; ++ if (scan_count++ >= BURST_CACHE_SCAN_LIMIT) break; ++ ++ if (!task_is_bore_eligible(child)) continue; ++ count++; ++ total += child->bore.penalty; ++ } ++ ++ update_burst_cache(bc, parent, count, total, now); ++ } ++ ++ bc_val.value = READ_ONCE(bc->value); ++ return (u32)bc_val.penalty; ++} ++ ++static u32 inherit_from_ancestor_hub(struct task_struct *parent, ++ u64 clone_flags, u64 now) { ++ struct bore_bc bc_val; ++ struct task_struct *ancestor = parent; ++ u32 sole_child_count = 0; ++ ++ if (clone_flags & CLONE_PARENT) { ++ ancestor = rcu_dereference(ancestor->real_parent); ++ sole_child_count = 1; ++ } ++ ++ for (struct task_struct *next; ++ (next = rcu_dereference(ancestor->real_parent)) != ancestor && ++ count_children_upto2(ancestor) <= sole_child_count; ++ ancestor = next, sole_child_count = 1) {} ++ ++ struct bore_bc *bc = &ancestor->bore.subtree; ++ ++ if (burst_cache_expired(bc, now)) { ++ struct task_struct *direct_child; ++ u32 count = 0, total = 0, scan_count = 0; ++ for_each_child_task(ancestor, direct_child) { ++ if (count >= BURST_CACHE_SAMPLE_LIMIT) break; ++ if (scan_count++ >= BURST_CACHE_SCAN_LIMIT) break; ++ ++ struct task_struct *descendant = direct_child; ++ while (count_children_upto2(descendant) == 1) { ++ struct task_struct *next_descendant = ++ list_first_or_null_rcu(&descendant->children, ++ struct task_struct, sibling); ++ if (!next_descendant) break; ++ descendant = next_descendant; ++ } ++ ++ if (!task_is_bore_eligible(descendant)) continue; ++ count++; ++ total += descendant->bore.penalty; ++ } ++ ++ update_burst_cache(bc, ancestor, count, total, now); ++ } ++ ++ bc_val.value = READ_ONCE(bc->value); ++ return (u32)bc_val.penalty; ++} ++ ++static u32 inherit_from_thread_group(struct task_struct *p, u64 now) { ++ struct bore_bc bc_val; ++ struct task_struct *leader = p->group_leader; ++ struct bore_bc *bc = &leader->bore.group; ++ ++ if (burst_cache_expired(bc, now)) { ++ struct task_struct *sibling; ++ u32 count = 0, total = 0, scan_count = 0; ++ ++ for_each_thread(leader, sibling) { ++ if (count >= BURST_CACHE_SAMPLE_LIMIT) break; ++ if (scan_count++ >= BURST_CACHE_SCAN_LIMIT) break; ++ ++ if (!task_is_bore_eligible(sibling)) continue; ++ count++; ++ total += sibling->bore.penalty; ++ } ++ ++ update_burst_cache(bc, leader, count, total, now); ++ } ++ ++ bc_val.value = READ_ONCE(bc->value); ++ return (u32)bc_val.penalty; ++} ++ ++void task_fork_bore(struct task_struct *p, ++ struct task_struct *parent, u64 clone_flags, u64 now) { ++ if (!static_branch_likely(&sched_bore_key) || !task_is_bore_eligible(p)) return; ++ ++ rcu_read_lock(); ++ struct bore_ctx *ctx = &p->bore; ++ u32 inherited_penalty; ++ if (clone_flags & CLONE_THREAD) ++ inherited_penalty = inherit_from_thread_group(parent, now); ++ else if (static_branch_likely(&sched_burst_inherit_key)) ++ inherited_penalty = static_branch_likely(&sched_burst_ancestor_key)? ++ inherit_from_ancestor_hub(parent, clone_flags, now): ++ inherit_from_parent(parent, clone_flags, now); ++ else ++ inherited_penalty = 0; ++ ++ if (ctx->prev_penalty < inherited_penalty) ++ ctx->prev_penalty = inherited_penalty; ++ ctx->curr_penalty = 0; ++ ctx->burst_time = 0; ++ ctx->stop_update = false; ++ ctx->futex_waiting = false; ++ update_penalty(p); ++ rcu_read_unlock(); ++} ++ ++void reset_task_bore(struct task_struct *p) ++{ memset(&p->bore, 0, sizeof(struct bore_ctx)); } ++ ++static void update_inherit_type(void) { ++ switch(sched_burst_inherit_type) { ++ case 1: ++ static_branch_enable(&sched_burst_inherit_key); ++ static_branch_disable(&sched_burst_ancestor_key); ++ break; ++ case 2: ++ static_branch_enable(&sched_burst_inherit_key); ++ static_branch_enable(&sched_burst_ancestor_key); ++ break; ++ default: ++ static_branch_disable(&sched_burst_inherit_key); ++ break; ++ } ++} ++ ++void __init sched_init_bore(void) { ++ printk(KERN_INFO "%s %s by %s\n", ++ SCHED_BORE_PROGNAME, SCHED_BORE_VERSION, SCHED_BORE_AUTHOR); ++ ++ for (int i = 1; i <= BURST_CACHE_SAMPLE_LIMIT; i++) ++ bore_reciprocal_lut[i] = (u32)div64_u64(0xffffffffULL + i, i); ++ ++ reset_task_bore(&init_task); ++ update_inherit_type(); ++ ++ if (sched_credit_cap_us) ++ static_branch_enable(&sched_credit_key); ++} ++ ++static void readjust_all_task_weights(void) { ++ struct task_struct *task; ++ struct rq *rq; ++ struct rq_flags rf; ++ ++ scoped_guard(write_lock_irq, &tasklist_lock) ++ for_each_process(task) { ++ if (!task_is_bore_eligible(task)) continue; ++ rq = task_rq_lock(task, &rf); ++ update_rq_clock(rq); ++ reweight_task_by_prio(task, effective_prio_bore(task)); ++ task_rq_unlock(rq, task, &rf); ++ } ++} ++ ++int sched_bore_update_handler(const struct ctl_table *table, ++ int write, void __user *buffer, size_t *lenp, loff_t *ppos) { ++ int ret = proc_dou8vec_minmax(table, write, buffer, lenp, ppos); ++ if (ret || !write) ++ return ret; ++ ++ if (sched_bore) ++ static_branch_enable(&sched_bore_key); ++ else ++ static_branch_disable(&sched_bore_key); ++ ++ readjust_all_task_weights(); ++ ++ return 0; ++} ++ ++int sched_burst_inherit_type_update_handler(const struct ctl_table *table, ++ int write, void __user *buffer, size_t *lenp, loff_t *ppos) { ++ int ret = proc_dou8vec_minmax(table, write, buffer, lenp, ppos); ++ if (ret || !write) ++ return ret; ++ ++ update_inherit_type(); ++ ++ return 0; ++} ++ ++int sched_burst_protect_slice_lv_update_handler(const struct ctl_table *table, ++ int write, void __user *buffer, size_t *lenp, loff_t *ppos) { ++ int ret = proc_dou8vec_minmax(table, write, buffer, lenp, ppos); ++ if (ret || !write) ++ return ret; ++ ++ if (sched_burst_protect_slice_lv == 1 || ++ sched_burst_protect_slice_lv == 2) ++ static_branch_enable(&sched_burst_protect_slice_cond_key); ++ else ++ static_branch_disable(&sched_burst_protect_slice_cond_key); ++ ++ if (sched_burst_protect_slice_lv >= 2) ++ static_branch_enable(&sched_burst_protect_slice_prefer_key); ++ else ++ static_branch_disable(&sched_burst_protect_slice_prefer_key); ++ ++ return 0; ++} ++ ++int sched_credit_cap_us_update_handler(const struct ctl_table *table, ++ int write, void __user *buffer, size_t *lenp, loff_t *ppos) { ++ int ret = proc_douintvec_minmax(table, write, buffer, lenp, ppos); ++ if (ret || !write) ++ return ret; ++ ++ if (sched_credit_cap_us) ++ static_branch_enable(&sched_credit_key); ++ else ++ static_branch_disable(&sched_credit_key); ++ ++ return 0; ++} ++ ++#ifdef CONFIG_SYSCTL ++static struct ctl_table sched_bore_sysctls[] = { ++ { ++ .procname = "sched_bore", ++ .data = &sched_bore, ++ .maxlen = sizeof(u8), ++ .mode = 0644, ++ .proc_handler = sched_bore_update_handler, ++ .extra1 = SYSCTL_ZERO, ++ .extra2 = SYSCTL_ONE, ++ }, ++ { ++ .procname = "sched_burst_inherit_type", ++ .data = &sched_burst_inherit_type, ++ .maxlen = sizeof(u8), ++ .mode = 0644, ++ .proc_handler = sched_burst_inherit_type_update_handler, ++ .extra1 = SYSCTL_ZERO, ++ .extra2 = SYSCTL_TWO, ++ }, ++ { ++ .procname = "sched_burst_smoothness", ++ .data = &sched_burst_smoothness, ++ .maxlen = sizeof(u8), ++ .mode = 0644, ++ .proc_handler = proc_dou8vec_minmax, ++ .extra1 = SYSCTL_ZERO, ++ .extra2 = SYSCTL_THREE, ++ }, ++ { ++ .procname = "sched_burst_penalty_offset", ++ .data = &sched_burst_penalty_offset, ++ .maxlen = sizeof(u8), ++ .mode = 0644, ++ .proc_handler = proc_dou8vec_minmax, ++ .extra1 = SYSCTL_ZERO, ++ .extra2 = &maxval_6_bits, ++ }, ++ { ++ .procname = "sched_burst_penalty_scale", ++ .data = &sched_burst_penalty_scale, ++ .maxlen = sizeof(uint), ++ .mode = 0644, ++ .proc_handler = proc_douintvec_minmax, ++ .extra1 = SYSCTL_ZERO, ++ .extra2 = &maxval_12_bits, ++ }, ++ { ++ .procname = "sched_burst_cache_lifetime", ++ .data = &sched_burst_cache_lifetime, ++ .maxlen = sizeof(uint), ++ .mode = 0644, ++ .proc_handler = proc_douintvec, ++ }, ++ { ++ .procname = "sched_burst_protect_slice_lv", ++ .data = &sched_burst_protect_slice_lv, ++ .maxlen = sizeof(u8), ++ .mode = 0644, ++ .proc_handler = sched_burst_protect_slice_lv_update_handler, ++ .extra1 = SYSCTL_ZERO, ++ .extra2 = SYSCTL_THREE, ++ }, ++ { ++ .procname = "sched_credit_cap_us", ++ .data = &sched_credit_cap_us, ++ .maxlen = sizeof(uint), ++ .mode = 0644, ++ .proc_handler = sched_credit_cap_us_update_handler, ++ .extra1 = SYSCTL_ZERO, ++ .extra2 = &maxval_1_million, ++ }, ++}; ++ ++static int __init sched_bore_sysctl_init(void) { ++ register_sysctl_init("kernel", sched_bore_sysctls); ++ return 0; ++} ++late_initcall(sched_bore_sysctl_init); ++ ++#endif // CONFIG_SYSCTL ++#endif /* CONFIG_SCHED_BORE */ +diff --git a/kernel/sched/build_utility.c b/kernel/sched/build_utility.c +index a64bf71a6..6a20c28c0 100644 +--- a/kernel/sched/build_utility.c ++++ b/kernel/sched/build_utility.c +@@ -54,6 +54,10 @@ + #include "stats.h" + #include "autogroup.h" + ++#ifdef CONFIG_SCHED_BORE ++#include ++#endif /* CONFIG_SCHED_BORE */ ++ + #include "clock.c" + + #ifdef CONFIG_SCHED_ALT +diff --git a/kernel/sched/core.c b/kernel/sched/core.c +index 484913595..a8613f0b7 100644 +--- a/kernel/sched/core.c ++++ b/kernel/sched/core.c +@@ -99,6 +99,10 @@ + #include "../smpboot.h" + #include "../locking/mutex.h" + ++#ifdef CONFIG_SCHED_BORE ++#include ++#endif /* CONFIG_SCHED_BORE */ ++ + EXPORT_TRACEPOINT_SYMBOL_GPL(ipi_send_cpu); + EXPORT_TRACEPOINT_SYMBOL_GPL(ipi_send_cpumask); + +@@ -1533,7 +1537,11 @@ int tg_nop(struct task_group *tg, void *data) + + void set_load_weight(struct task_struct *p, bool update_load) + { ++#ifdef CONFIG_SCHED_BORE ++ int prio = effective_prio_bore(p); ++#else /* !CONFIG_SCHED_BORE */ + int prio = p->static_prio - MAX_RT_PRIO; ++#endif /* CONFIG_SCHED_BORE */ + struct load_weight lw; + + if (task_has_idle_policy(p)) { +@@ -8993,6 +9001,10 @@ void __init sched_init(void) + BUG_ON(!sched_class_above(&ext_sched_class, &idle_sched_class)); + #endif + ++#ifdef CONFIG_SCHED_BORE ++ sched_init_bore(); ++#endif /* CONFIG_SCHED_BORE */ ++ + wait_bit_init(); + + #ifdef CONFIG_FAIR_GROUP_SCHED +diff --git a/kernel/sched/debug.c b/kernel/sched/debug.c +index 70b7c3425..61776527a 100644 +--- a/kernel/sched/debug.c ++++ b/kernel/sched/debug.c +@@ -171,6 +171,53 @@ static const struct file_operations sched_feat_fops = { + .release = single_release, + }; + ++#ifdef CONFIG_SCHED_BORE ++#define DEFINE_SYSCTL_SCHED_FUNC(name, update_func) \ ++static ssize_t sched_##name##_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *ppos) \ ++{ \ ++ char buf[16]; \ ++ unsigned int value; \ ++\ ++ if (cnt > 15) \ ++ cnt = 15; \ ++\ ++ if (copy_from_user(&buf, ubuf, cnt)) \ ++ return -EFAULT; \ ++ buf[cnt] = '\0'; \ ++\ ++ if (kstrtouint(buf, 10, &value)) \ ++ return -EINVAL; \ ++\ ++ sysctl_sched_##name = value; \ ++ sched_update_##update_func(); \ ++\ ++ *ppos += cnt; \ ++ return cnt; \ ++} \ ++\ ++static int sched_##name##_show(struct seq_file *m, void *v) \ ++{ \ ++ seq_printf(m, "%d\n", sysctl_sched_##name); \ ++ return 0; \ ++} \ ++\ ++static int sched_##name##_open(struct inode *inode, struct file *filp) \ ++{ \ ++ return single_open(filp, sched_##name##_show, NULL); \ ++} \ ++\ ++static const struct file_operations sched_##name##_fops = { \ ++ .open = sched_##name##_open, \ ++ .write = sched_##name##_write, \ ++ .read = seq_read, \ ++ .llseek = seq_lseek, \ ++ .release = single_release, \ ++}; ++ ++DEFINE_SYSCTL_SCHED_FUNC(min_base_slice, min_base_slice) ++ ++#undef DEFINE_SYSCTL_SCHED_FUNC ++#else /* !CONFIG_SCHED_BORE */ + static ssize_t sched_scaling_write(struct file *filp, const char __user *ubuf, + size_t cnt, loff_t *ppos) + { +@@ -210,6 +257,7 @@ static const struct file_operations sched_scaling_fops = { + .llseek = seq_lseek, + .release = single_release, + }; ++#endif /* CONFIG_SCHED_BORE */ + + #ifdef CONFIG_SCHED_CACHE + static ssize_t +@@ -731,13 +779,20 @@ static __init int sched_init_debug(void) + debugfs_create_file("preempt", 0644, debugfs_sched, NULL, &sched_dynamic_fops); + #endif + ++#ifdef CONFIG_SCHED_BORE ++ debugfs_create_file("min_base_slice_ns", 0644, debugfs_sched, NULL, &sched_min_base_slice_fops); ++ debugfs_create_u32("base_slice_ns", 0444, debugfs_sched, &sysctl_sched_base_slice); ++#else /* !CONFIG_SCHED_BORE */ + debugfs_create_u32("base_slice_ns", 0644, debugfs_sched, &sysctl_sched_base_slice); ++#endif /* CONFIG_SCHED_BORE */ + + #ifndef CONFIG_SCHED_ALT + debugfs_create_u32("latency_warn_ms", 0644, debugfs_sched, &sysctl_resched_latency_warn_ms); + debugfs_create_u32("latency_warn_once", 0644, debugfs_sched, &sysctl_resched_latency_warn_once); + ++#if !defined(CONFIG_SCHED_BORE) + debugfs_create_file("tunable_scaling", 0644, debugfs_sched, NULL, &sched_scaling_fops); ++#endif /* CONFIG_SCHED_BORE */ + debugfs_create_u32("migration_cost_ns", 0644, debugfs_sched, &sysctl_sched_migration_cost); + debugfs_create_u32("nr_migrate", 0644, debugfs_sched, &sysctl_sched_nr_migrate); + +@@ -1008,6 +1063,9 @@ print_task(struct seq_file *m, struct rq *rq, struct task_struct *p) + SPLIT_NS(schedstat_val_or_zero(p->stats.sum_sleep_runtime)), + SPLIT_NS(schedstat_val_or_zero(p->stats.sum_block_runtime))); + ++#ifdef CONFIG_SCHED_BORE ++ SEQ_printf(m, " %2d", bore_score(p)); ++#endif /* CONFIG_SCHED_BORE */ + #ifdef CONFIG_NUMA_BALANCING + SEQ_printf(m, " %d %d", task_node(p), task_numa_group_id(p)); + #endif +@@ -1497,6 +1555,9 @@ void proc_sched_show_task(struct task_struct *p, struct pid_namespace *ns, + __PS("nr_involuntary_switches", p->nivcsw); + + P(se.load.weight); ++#ifdef CONFIG_SCHED_BORE ++ __PS("bore.score", bore_score(p)); ++#endif /* CONFIG_SCHED_BORE */ + P(se.avg.load_sum); + P(se.avg.runnable_sum); + P(se.avg.util_sum); +diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c +index 532c0de5b..c8e019cfe 100644 +--- a/kernel/sched/fair.c ++++ b/kernel/sched/fair.c +@@ -61,6 +61,10 @@ + #include "stats.h" + #include "autogroup.h" + ++#ifdef CONFIG_SCHED_BORE ++#include ++#endif /* CONFIG_SCHED_BORE */ ++ + /* + * The initial- and re-scaling of tunables is configurable + * +@@ -70,9 +74,14 @@ + * SCHED_TUNABLESCALING_LOG - scaled logarithmically, *1+ilog(ncpus) + * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus + * +- * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus)) ++ * BORE : default SCHED_TUNABLESCALING_NONE = *1 constant ++ * EEVDF: default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus)) + */ ++#ifdef CONFIG_SCHED_BORE ++unsigned int sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_NONE; ++#else /* !CONFIG_SCHED_BORE */ + unsigned int sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG; ++#endif /* CONFIG_SCHED_BORE */ + + /* + * Default base time slice (request size r_i) for SCHED_NORMAL/SCHED_BATCH: +@@ -80,15 +89,23 @@ unsigned int sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG; + * Under EEVDF this is the request size used to compute the virtual + * deadline; see update_deadline(). + * +- * (default: 0.70 msec * (1 + ilog(ncpus)), units: nanoseconds) ++ * BORE : base_slice = minimum multiple of nsecs_per_tick >= min_base_slice ++ * (default min_base_slice = 2000000 constant, units: nanoseconds) ++ * EEVDF: default 0.70 msec * (1 + ilog(ncpus)), units: nanoseconds + */ ++#ifdef CONFIG_SCHED_BORE ++static const unsigned int nsecs_per_tick = 1000000000ULL / HZ; ++unsigned int sysctl_sched_min_base_slice = CONFIG_MIN_BASE_SLICE_NS; ++__read_mostly uint sysctl_sched_base_slice = nsecs_per_tick; ++#else /* !CONFIG_SCHED_BORE */ + #ifdef CONFIG_ZEN_INTERACTIVE + unsigned int sysctl_sched_base_slice = 400000ULL; + static unsigned int normalized_sysctl_sched_base_slice = 400000ULL; + #else + unsigned int sysctl_sched_base_slice = 700000ULL; + static unsigned int normalized_sysctl_sched_base_slice = 700000ULL; +-#endif ++#endif /* CONFIG_ZEN_INTERACTIVE */ ++#endif /* CONFIG_SCHED_BORE */ + + #ifdef CONFIG_ZEN_INTERACTIVE + __read_mostly unsigned int sysctl_sched_migration_cost = 300000UL; +@@ -208,6 +225,13 @@ static inline void update_load_set(struct load_weight *lw, unsigned long w) + * + * This idea comes from the SD scheduler of Con Kolivas: + */ ++#ifdef CONFIG_SCHED_BORE ++static void update_sysctl(void) { ++ sysctl_sched_base_slice = nsecs_per_tick * ++ max(1UL, DIV_ROUND_UP(sysctl_sched_min_base_slice, nsecs_per_tick)); ++} ++void sched_update_min_base_slice(void) { update_sysctl(); } ++#else /* !CONFIG_SCHED_BORE */ + static unsigned int get_update_sysctl_factor(void) + { + unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8); +@@ -238,6 +262,7 @@ static void update_sysctl(void) + SET_SYSCTL(sched_base_slice); + #undef SET_SYSCTL + } ++#endif /* CONFIG_SCHED_BORE */ + + void __init sched_init_granularity(void) + { +@@ -1140,7 +1165,11 @@ struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq) + */ + static inline void set_protect_slice(struct cfs_rq *cfs_rq, struct sched_entity *se) + { ++#ifdef CONFIG_SCHED_BORE ++ u64 slice = sysctl_sched_base_slice; ++#else /* CONFIG_SCHED_BORE */ + u64 slice = normalized_sysctl_sched_base_slice; ++#endif /* CONFIG_SCHED_BORE */ + u64 vprot = se->deadline; + + if (sched_feat(RUN_TO_PARITY)) +@@ -1224,8 +1253,17 @@ static struct sched_entity *pick_eevdf(struct cfs_rq *cfs_rq, bool protect) + if (curr && (!curr->on_rq || !entity_eligible(cfs_rq, curr))) + curr = NULL; + +- if (curr && protect && protect_slice(curr)) +- return curr; ++ if (curr && protect && protect_slice(curr)) { ++#ifdef CONFIG_SCHED_BORE ++ if (static_branch_likely(&sched_bore_key)) { ++ if ((static_branch_likely(&sched_burst_protect_slice_cond_key) || ++ static_branch_unlikely(&sched_burst_protect_slice_prefer_key)) && ++ (!entity_is_task(curr) || !task_of(curr)->bore.futex_waiting)) ++ return curr; ++ } else ++#endif /* CONFIG_SCHED_BORE */ ++ return curr; ++ } + + /* Pick the leftmost entity if it's eligible */ + if (se && entity_eligible(cfs_rq, se)) { +@@ -1281,6 +1319,7 @@ struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq) + /************************************************************** + * Scheduling class statistics methods: + */ ++#if !defined(CONFIG_SCHED_BORE) + int sched_update_scaling(void) + { + unsigned int factor = get_update_sysctl_factor(); +@@ -1292,6 +1331,7 @@ int sched_update_scaling(void) + + return 0; + } ++#endif /* CONFIG_SCHED_BORE */ + + static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se); + +@@ -2222,6 +2262,41 @@ static void pref_llc_running_dec(struct rq *rq, struct task_struct *p) {} + + #endif /* CONFIG_SCHED_CACHE */ + ++#ifdef CONFIG_SCHED_BORE ++static inline bool do_preempt_weight(struct cfs_rq *cfs_rq, ++ struct sched_entity *pse, struct sched_entity *se) ++{ ++ /* ++ * Companion to the PREEMPT_SHORT path: where that lets a shorter-slice ++ * waker cancel current's slice protection, this lets a heavier (under ++ * BORE: more interactive) waker do so. No RUN_TO_PARITY gate -- in 7.0 ++ * the slice protection (vprot) exists regardless of RUN_TO_PARITY, so ++ * the weight bypass must apply either way. ++ */ ++ if (!static_branch_likely(&sched_bore_key)) ++ return false; ++ ++ if (!static_branch_likely(&sched_burst_protect_slice_cond_key)) ++ return false; ++ ++ if (static_branch_unlikely(&sched_burst_protect_slice_prefer_key) ++ ? (pse->load.weight <= se->load.weight) ++ : (pse->load.weight < se->load.weight)) ++ return false; ++ ++ if (!entity_eligible(cfs_rq, pse)) ++ return false; ++ ++ if (entity_before(pse, se)) ++ return true; ++ ++ if (!entity_eligible(cfs_rq, se)) ++ return true; ++ ++ return false; ++} ++#endif /* CONFIG_SCHED_BORE */ ++ + /* + * Used by other classes to account runtime. + */ +@@ -2263,6 +2338,10 @@ static void update_curr(struct cfs_rq *cfs_rq) + curr->vruntime += calc_delta_fair(delta_exec, curr); + resched = update_deadline(cfs_rq, curr); + ++#ifdef CONFIG_SCHED_BORE ++ update_curr_bore(task_of(curr), delta_exec); ++#endif /* CONFIG_SCHED_BORE */ ++ + /* + * If the fair_server is active, we need to account for the + * fair_server time whether or not the task is running on +@@ -5016,8 +5095,22 @@ unsigned long __calc_prop_weight(struct cfs_rq *cfs_rq, struct sched_entity *se, + return max(weight, MIN_SHARES); + } + ++#ifdef CONFIG_SCHED_BORE ++/* ++ * BORE re-weights a task from its burst penalty and lives in a separate ++ * translation unit (kernel/sched/bore.c), so this must be globally visible. ++ * ++ * Note: in 7.2 BORE poked the old reweight_entity() directly. 7.3 split that ++ * into reweight_entity() (raw se->load + PELT) and reweight_eevdf() (the ++ * flattened EEVDF h_load on the root cfs_rq); reweight_task_fair() is the one ++ * entry point that performs both halves consistently. ++ */ ++void reweight_task_fair(struct rq *rq, struct task_struct *p, ++ const struct load_weight *lw) ++#else /* !CONFIG_SCHED_BORE */ + static void reweight_task_fair(struct rq *rq, struct task_struct *p, + const struct load_weight *lw) ++#endif /* CONFIG_SCHED_BORE */ + { + struct sched_entity *se = &p->se; + unsigned long weight = NICE_0_LOAD; +@@ -6398,14 +6491,13 @@ void __setparam_fair(struct task_struct *p, const struct sched_attr *attr) + static void + place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) + { +- u64 vslice, vruntime = avg_vruntime(cfs_rq); ++ u64 vslice = 0, vruntime = avg_vruntime(cfs_rq); + unsigned int nr_queued = cfs_rq->h_nr_queued; + bool update_zero = false; + s64 lag = 0; + + if (!se->custom_slice) + se->slice = sysctl_sched_base_slice; +- vslice = calc_delta_fair(se->slice, se); + + if (flags & ENQUEUE_QUEUED) + nr_queued -= 1; +@@ -6528,7 +6620,18 @@ place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) + se->rel_deadline = 0; + return; + } +- ++#ifdef CONFIG_SCHED_BORE ++ if (static_branch_likely(&sched_bore_key) && ++ entity_is_task(se) && ++ task_of(se)->bore.futex_waiting) ++ goto vslice_found; ++#endif /* !CONFIG_SCHED_BORE */ ++ vslice = calc_delta_fair(se->slice, se); ++#ifdef CONFIG_SCHED_BORE ++ if (static_branch_likely(&sched_bore_key)) ++ vslice >>= !!(flags & (ENQUEUE_INITIAL | ENQUEUE_WAKEUP)); ++ else ++#endif /* CONFIG_SCHED_BORE */ + /* + * When joining the competition; the existing tasks will be, + * on average, halfway through their slice, as such start tasks +@@ -6537,10 +6640,24 @@ place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) + if (sched_feat(PLACE_DEADLINE_INITIAL) && (flags & ENQUEUE_INITIAL)) + vslice /= 2; + ++#ifdef CONFIG_SCHED_BORE ++vslice_found: ++#endif /* CONFIG_SCHED_BORE */ + /* + * EEVDF: vd_i = ve_i + r_i/w_i + */ + se->deadline = se->vruntime + vslice; ++ ++#ifdef CONFIG_SCHED_BORE ++ if (static_branch_likely(&sched_bore_key) && ++ static_branch_unlikely(&sched_credit_key) && ++ entity_is_task(se) && (flags & ENQUEUE_WAKEUP)) { ++ u64 credit = bore_credit_ns(task_of(se)); ++ ++ if (credit && se->deadline > credit) ++ se->deadline -= credit; ++ } ++#endif /* CONFIG_SCHED_BORE */ + } + + static void check_enqueue_throttle(struct cfs_rq *cfs_rq); +@@ -8148,7 +8265,7 @@ static int choose_idle_cpu(int cpu, struct task_struct *p) + } + + static void +-requeue_delayed_entity(struct cfs_rq *cfs_rq, struct sched_entity *se) ++requeue_delayed_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) + { + /* + * se->sched_delayed should imply: se->on_rq == 1. +@@ -8162,7 +8279,13 @@ requeue_delayed_entity(struct cfs_rq *cfs_rq, struct sched_entity *se) + cfs_rq->h_nr_queued--; + if (se != cfs_rq->curr) + __dequeue_entity(cfs_rq, se); +- place_entity(cfs_rq, se, 0); ++#ifdef CONFIG_SCHED_BORE ++ if (static_branch_likely(&sched_bore_key)) ++ flags |= ENQUEUE_WAKEUP; ++ else ++#endif /* CONFIG_SCHED_BORE */ ++ flags = 0; ++ place_entity(cfs_rq, se, flags); + if (se != cfs_rq->curr) + __enqueue_entity(cfs_rq, se); + cfs_rq->h_nr_queued++; +@@ -8250,7 +8373,7 @@ enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags) + update_curr_eevdf(cfs_rq); + + if (flags & ENQUEUE_DELAYED) { +- requeue_delayed_entity(cfs_rq, se); ++ requeue_delayed_entity(cfs_rq, se, flags); + return; + } + +@@ -8270,7 +8393,7 @@ enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags) + place_entity(cfs_rq, se, flags); + + if (se->on_rq && se->sched_delayed) +- requeue_delayed_entity(cfs_rq, se); ++ requeue_delayed_entity(cfs_rq, se, flags); + + weight = enqueue_hierarchy(p, flags); + +@@ -8440,6 +8563,23 @@ static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags) + if (!p->se.sched_delayed) + util_est_dequeue(&rq->cfs, p); + ++#ifdef CONFIG_SCHED_BORE ++ /* ++ * Commit the outstanding runtime of @p before folding the burst into ++ * the smoothed penalty, while @p is still queued (restart_burst_bore() ++ * reweights it). 7.3 flattened the EEVDF tree: the running task entity ++ * is tracked by rq->cfs.curr, and update_curr_eevdf() redirects to the ++ * cfs_rq that actually owns it, so use those rather than the old ++ * cfs_rq_of(&p->se)->curr. ++ */ ++ if (flags & DEQUEUE_SLEEP) { ++ if (rq->cfs.curr == &p->se) ++ update_curr_eevdf(&rq->cfs); ++ bore_note_sleep(p, rq_clock(rq)); ++ restart_burst_bore(p); ++ } ++#endif /* CONFIG_SCHED_BORE */ ++ + if (!__dequeue_task(rq, p, flags)) + return false; + +@@ -10230,6 +10370,18 @@ static void wakeup_preempt_fair(struct rq *rq, struct task_struct *p, int wake_f + goto pick; + } + ++#ifdef CONFIG_SCHED_BORE ++ /* ++ * Likewise, if @p is heavier than current (under BORE: more ++ * interactive), per kernel.sched_burst_protect_slice_lv, override ++ * current's slice protection to allow preemption. ++ */ ++ if (do_preempt_weight(cfs_rq, pse, se)) { ++ preempt_action = PREEMPT_WAKEUP_SHORT; ++ goto pick; ++ } ++#endif ++ + /* + * Ignore wakee preemption on WF_FORK as it is less likely that + * there is shared data as exec often follow fork. +@@ -10399,16 +10551,25 @@ static void yield_task_fair(struct rq *rq) + /* + * Are we the only task in the tree? + */ ++#if !defined(CONFIG_SCHED_BORE) + if (unlikely(rq->nr_running == 1)) + return; + + clear_buddies(cfs_rq, se); ++#endif /* CONFIG_SCHED_BORE */ + + update_rq_clock(rq); + /* + * Update run-time statistics of the 'current'. + */ + update_curr_eevdf(cfs_rq); ++#ifdef CONFIG_SCHED_BORE ++ restart_burst_rescale_deadline_bore(curr); ++ if (unlikely(rq->nr_running == 1)) ++ return; ++ ++ clear_buddies(cfs_rq, se); ++#endif /* CONFIG_SCHED_BORE */ + /* + * Tell update_rq_clock() that we've just updated, + * so we don't do microscopic update in schedule() +@@ -15536,6 +15697,9 @@ static void switched_to_fair(struct rq *rq, struct task_struct *p) + WARN_ON_ONCE(p->se.sched_delayed); + + attach_task_cfs_rq(p); ++#ifdef CONFIG_SCHED_BORE ++ reset_task_bore(p); ++#endif /* CONFIG_SCHED_BORE */ + + set_task_max_allowed_capacity(p); + +diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h +index 11f5b47aa..4f77a09b2 100644 +--- a/kernel/sched/sched.h ++++ b/kernel/sched/sched.h +@@ -2305,7 +2305,11 @@ extern int group_balance_cpu(struct sched_group *sg); + extern void update_sched_domain_debugfs(void); + extern void dirty_sched_domain_sysctl(int cpu); + ++#ifdef CONFIG_SCHED_BORE ++extern void sched_update_min_base_slice(void); ++#else /* !CONFIG_SCHED_BORE */ + extern int sched_update_scaling(void); ++#endif /* CONFIG_SCHED_BORE */ + + static inline const struct cpumask *task_user_cpus(struct task_struct *p) + { +@@ -3151,7 +3155,12 @@ static inline void attach_one_task(struct rq *rq, struct task_struct *p) + extern __read_mostly unsigned int sysctl_sched_nr_migrate; + extern __read_mostly unsigned int sysctl_sched_migration_cost; + ++#ifdef CONFIG_SCHED_BORE ++extern unsigned int sysctl_sched_min_base_slice; ++extern __read_mostly uint sysctl_sched_base_slice; ++#else /* !CONFIG_SCHED_BORE */ + extern unsigned int sysctl_sched_base_slice; ++#endif /* CONFIG_SCHED_BORE */ + + extern int sysctl_resched_latency_warn_ms; + extern int sysctl_resched_latency_warn_once; +-- +2.34.1 diff --git a/releases/v7.3.5-zako1/series b/releases/v7.3.5-zako1/series new file mode 100644 index 0000000..ca57082 --- /dev/null +++ b/releases/v7.3.5-zako1/series @@ -0,0 +1,2 @@ +patches/0001-zen-7.3.5-zen1.patch +patches/0002-sched-bore-7.0.0.patch diff --git a/releases/v7.3.5-zako1/sources b/releases/v7.3.5-zako1/sources new file mode 100644 index 0000000..5877627 --- /dev/null +++ b/releases/v7.3.5-zako1/sources @@ -0,0 +1,5 @@ +tarball linux-libre-7.3.5-gnu.tar.xz +url https://www.linux-libre.fsfla.org/pub/linux-libre/releases/7.3.5-gnu/ +sha256 00f30f9cc4328a4b0a8d8a71349f9dc9fabed762f0a27993160e319377ef5753 +zen v7.3.5-zen1 +bore 7.0.0 diff --git a/series/7.3.5 b/series/7.3.5 deleted file mode 100644 index d681b18..0000000 --- a/series/7.3.5 +++ /dev/null @@ -1,2 +0,0 @@ -patches/7.3.5/0001-zen-7.3.5-zen1.patch -patches/7.3.5/0002-sched-bore-7.0.0.patch diff --git a/sources/7.3.5 b/sources/7.3.5 deleted file mode 100644 index 41fc518..0000000 --- a/sources/7.3.5 +++ /dev/null @@ -1,3 +0,0 @@ -tarball linux-libre-7.3.5-gnu.tar.xz -url https://www.linux-libre.fsfla.org/pub/linux-libre/releases/7.3.5-gnu/ -sha256 00f30f9cc4328a4b0a8d8a71349f9dc9fabed762f0a27993160e319377ef5753 -- cgit v1.3