
The BUG: sleeping function called from invalid context warning from the pr/legacy console printing thread caught kernel developers off guard on CONFIG_PREEMPT_RT=y builds during the Linux v6.19 cycle. Although the stack trace points directly to console_conditional_schedule() in kernel/printk/printk.c, the underlying fault is an architectural mismatch: a global flag (console_may_schedule) set when taking console_lock() leaks into a virtual terminal driver callback (vt_console_print()) that holds a spinlock_t (printing_lock). This article traces the exact execution path in the Linux kernel source, explains why the bug surfaced in v6.19 despite pr/legacy arriving in v6.12, and details the upstream fix merged for Linux v7.0.
Suppose you boot a Linux v6.19 kernel configured with CONFIG_PREEMPT_RT=y and CONFIG_DEBUG_ATOMIC_SLEEP=y and an active framebuffer console (fbcon via vt). When heavy printk() output causes the virtual terminal to scroll, the kernel log emits a BUG: sleeping function called from invalid context warning (a WARN-level diagnostic rather than a fatal panic unless panic_on_warn is enabled):
BUG: sleeping function called from invalid context at kernel/printk/printk.c:3377in_atomic(): 0, irqs_disabled(): 0, non_block: 0, pid: 142, name: pr/legacypreempt_count: 0, expected: 0RCU nest depth: 1, expected: 0locks held by pr/legacy/142:#0: ... (console_lock), at: legacy_kthread_func+...#1: ... (console_srcu), at: console_flush_one_record+...#2: ... (printing_lock), at: vt_console_print+...#3: ... (rcu_read_lock), at: rt_spin_trylock+...Call Trace:dump_stack_lvl__might_resched.coldconsole_conditional_schedulefbcon_redrawfbcon_scrollcon_scrolllfvt_console_printconsole_flush_one_recordlegacy_kthread_funckthreadret_from_fork
(Illustrative trace matching Linux v6.19 CONFIG_PREEMPT_RT + CONFIG_PROVE_LOCKING; exact addresses, lockdep wait-type tags, and line numbers such as kernel/printk/printk.c:3377 in v6.19 vs. 3431 in pre-release development trees vary by build.)
Look closely at the diagnostic header before reading the stack frames:
name: pr/legacy: The task is the dedicated legacy console printing kernel thread (kthread_run(legacy_kthread_func, NULL, "pr/legacy")).preempt_count: 0, expected: 0: Preemption is not disabled (PREEMPT_LOCK_OFFSET is 0 under CONFIG_PREEMPT_RT).RCU nest depth: 1, expected: 0: This is the trigger. cond_resched() expands to __might_resched(__FILE__, __LINE__, 0) followed by _cond_resched(). Even though vt_console_print() acquired printing_lock with spin_trylock() rather than disabling preemption, rt_spin_trylock() on PREEMPT_RT calls rcu_read_lock() (raising RCU nest depth to 1) and migrate_disable(). Calling cond_resched() with an active RCU read-side critical section violates __might_resched()’s resched_offsets_ok(0) check and rcu_sleep_check().In Linux v6.12, commit 5f53ca3ff83b4 (“printk: Implement legacy printer kthread for PREEMPT_RT”) introduced a dedicated kernel thread (pr/legacy) running legacy_kthread_func() whenever force_legacy_kthread() evaluates to true. In kernel/printk/internal.h, that macro is enabled solely for CONFIG_PREEMPT_RT:
// kernel/printk/internal.h#ifdef CONFIG_PREEMPT_RT# define force_legacy_kthread() (true)#else# define force_legacy_kthread() (false)#endif
Why did the warning not appear immediately in v6.12 through v6.18? Because in v6.12-v6.18, legacy_kthread_func() flushed records via __console_flush_and_unlock():
// kernel/printk/printk.c (v6.12 - v6.18)static int legacy_kthread_func(void *unused){for (;;) {wait_event_interruptible(legacy_wait, legacy_kthread_should_wakeup());if (kthread_should_stop())break;console_lock();__console_flush_and_unlock();}return 0;}
Inside __console_flush_and_unlock(), the kernel saved do_cond_resched = console_may_schedule; into a local variable and cleared console_may_schedule = 0; before calling console_flush_all():
// kernel/printk/printk.cstatic void __console_flush_and_unlock(void){bool do_cond_resched;bool handover;bool flushed;u64 next_seq;do_cond_resched = console_may_schedule;do {console_may_schedule = 0;flushed = console_flush_all(do_cond_resched, &next_seq, &handover);if (!handover)__console_unlock();if (!flushed)break;} while (prb_read_valid(prb, next_seq, NULL) && console_trylock());}
Because console_may_schedule was reset to 0 prior to invoking any console driver’s write() callback, console_conditional_schedule() stayed silent.
In Linux v6.19 (commit 1bc9a28f076f, “printk: Use console_flush_one_record for legacy printer kthread”), legacy_kthread_func() was refactored to drop console_lock between individual records rather than holding it across an entire backlog flush (which had caused severe console_lock contention during boot, such as delaying filp_open() in console_on_rootfs()):
// kernel/printk/printk.c (v6.19)static int legacy_kthread_func(void *unused){bool try_again;wait_for_event:wait_event_interruptible(legacy_wait, legacy_kthread_should_wakeup());do {bool handover = false;u64 next_seq = 0;if (kthread_should_stop())return 0;console_lock();console_flush_one_record(true, &next_seq, &handover, &try_again);if (!handover)__console_unlock();} while (try_again);goto wait_for_event;}
console_lock() acquires the global binary semaphore console_sem (annotated for lockdep under console_lock_dep_map, named "console_lock"), sets console_locked = 1, and sets console_may_schedule = 1:
// kernel/printk/printk.cvoid console_lock(void){might_sleep();while (panic_on_other_cpu())msleep(1000);down_console_sem();console_locked = 1;console_may_schedule = 1;}
Unlike console_unlock() (which calls __console_flush_and_unlock()), the v6.19 legacy_kthread_func() path called console_flush_one_record() and __console_unlock() directly without ever clearing console_may_schedule. Furthermore, inside console_emit_next_record(), when force_legacy_kthread() && !panic_in_progress() is true, con->write() runs directly in preemptible task context (pr/legacy) rather than with local IRQs disabled via printk_safe_enter_irqsave(), while console_may_schedule remains 1 throughout vt_console_print().
On non-PREEMPT_RT kernels (force_legacy_kthread() == false), printk() either acquires console_trylock() (which sets console_may_schedule = 0) or flushes through console_unlock() and __console_flush_and_unlock(), which always clears console_may_schedule = 0 before calling con->write().
spinlock_t in vt_console_print() and Indirect Scrollingvt_console_print() in drivers/tty/vt/vt.c guards against concurrent oops output using a local spinlock_t named printing_lock. Notice that vt_console_print() does not call console_conditional_schedule() directly; instead, newline processing (lf()) triggers con_scroll(), which calls vc->vc_sw->con_scroll() (fbcon_scroll()), which invokes fbcon_redraw() (or fbcon_redraw_move() / fbcon_redraw_blit()):
// drivers/tty/vt/vt.cstatic DEFINE_SPINLOCK(printing_lock);static void vt_console_print(struct console *co, const char *b, unsigned count){.../* this protects against concurrent oops only */if (!spin_trylock(&printing_lock))return;...if (c != ASCII_CAR_RET)lf(vc); /* -> con_scroll() -> fbcon_scroll() -> fbcon_redraw*()-> console_conditional_schedule() */...quit:spin_unlock(&printing_lock);}
When fbcon_redraw*() reaches console_conditional_schedule():
// kernel/printk/printk.cvoid __sched console_conditional_schedule(void){if (console_may_schedule)cond_resched();}
Look at why this breaks on CONFIG_PREEMPT_RT=y even though PREEMPT_RT selects CONFIG_PREEMPTION:
include/linux/sched.h, cond_resched() is a macro that always calls __might_resched(__FILE__, __LINE__, 0) before calling _cond_resched() (which compiles to a no-op return 0; when CONFIG_PREEMPTION=y and !CONFIG_PREEMPT_DYNAMIC).kernel/locking/spinlock_rt.c, spin_trylock(&printing_lock) resolves to rt_spin_trylock(), which calls __rt_spin_trylock(). That helper acquires the underlying rt_mutex_base (without blocking, since it is a trylock) and then explicitly calls rcu_read_lock() and migrate_disable().console_may_schedule is 1, console_conditional_schedule() invokes cond_resched(), and __might_resched() (together with rcu_sleep_check()) detects rcu_preempt_depth() == 1 when 0 is expected, emitting the warning.console_may_schedule only describes how console_sem was acquired, not what locks downstream console callbacks have taken while rendering.
+----------------------------------------------------------------------+| PREEMPT_RT LEGACY CONSOLE FLUSH FLOW (v6.19) |+----------------------------------------------------------------------+| || printk() || | || v || wake_up_interruptible(&legacy_wait) ---> legacy_kthread_func() || | [pr/legacy kthread] || v || console_lock() || (down_console_sem(), || sets console_may_schedule=1)|| | || v || console_flush_one_record() || (acquires console_srcu) || | || v || console_emit_next_record() || (task context: console_may_sched || is STILL 1) || | || v || vt_console_print() [vt.c] || spin_trylock(&printing_lock) || (rt_spin_trylock: rcu_read_lock() || + migrate_disable()) || | || v || lf() -> con_scroll() || -> fbcon_scroll() || -> fbcon_redraw*() [fbcon.c] || | || v || console_conditional_schedule() || if (console_may_schedule) || cond_resched() || | || v || +-------------------------------+ || | __might_resched() WARNING: | || | BUG: sleeping function called | || | from invalid context | || | RCU nest depth: 1, expected:0 | || +-------------------------------+ || |+----------------------------------------------------------------------+
The call trace crosses three distinct subsystems:
legacy_kthread_func(), console_flush_one_record(), console_lock)vt) (vt_console_print(), printing_lock, lf(), con_scroll())fbcon) (fbcon_scroll(), fbcon_redraw())Because the warning only points to the check site (console_conditional_schedule()), it is easy to blame the wrong layer. During the January 2026 mailing list discussion, Petr Mladek initially explored dropping spin_trylock(&printing_lock) in vt_console_print(), before Sebastian Andrzej Siewior demonstrated that console_conditional_schedule() itself had become obsolete dead weight. As Siewior explained in the upstream fix commit message:
“vt_console_print() acquires a spinlock_t which does not allow a voluntary schedule. There is no need to fb_scroll() to schedule since console_flush_one_record() attempts to schedule after each line. !PREEMPT_RT is not affected because the legacy printing thread is only enabled on PREEMPT_RT builds.”
console_conditional_schedule() dates back to Linux v2.4.9.11. In that architecture:
console_unlock() flushed consoles in v2.6.38-rc3 and earlier, interrupts remained disabled across the console loop, so console output could not yield inside console_unlock(). Long TTY operations (do_con_write()) and scrolling redraws (fbcon) used console_conditional_schedule() to yield when console_lock() had been acquired in a schedulable process context.8d91f8b15361d (“printk: do cond_resched() between lines while outputting to consoles”) updated console_unlock() to save console_may_schedule into a local variable, clear the global console_may_schedule = 0 before calling console drivers, and run cond_resched() cleanly between records outside driver spinlocks.CONFIG_PREEMPTION=y is active (including CONFIG_PREEMPT_RT) and !CONFIG_PREEMPT_DYNAMIC, _cond_resched() is a no-op anyway — console_conditional_schedule() only affected PREEMPT_NONE and PREEMPT_VOLUNTARY builds (or dynamic preemption), while __might_resched() inside cond_resched() stayed active whenever CONFIG_DEBUG_ATOMIC_SLEEP=y was enabled.Thus console_conditional_schedule() had already been rendered redundant on the printk path a decade earlier; commit 1bc9a28f076f in v6.19 merely exposed the latent bug by skipping __console_flush_and_unlock() and leaving console_may_schedule = 1 across vt_console_print().
console_conditional_schedule() EntirelyRather than patching console_may_schedule or removing printing_lock, the clean upstream fix removes console_conditional_schedule() altogether. In v6.19+, legacy_kthread_func() and console_flush_one_record() already handle scheduling cleanly outside driver locks:
// kernel/printk/printk.c (v6.19+)do {bool handover = false;u64 next_seq = 0;if (kthread_should_stop())return 0;console_lock();console_flush_one_record(true, &next_seq, &handover, &try_again);// Inside console_flush_one_record(), after console_emit_next_record()// returns and printing_lock is already released:// if (do_cond_resched) cond_resched();if (!handover)__console_unlock();} while (try_again);
Because legacy_kthread_func() drops and reacquires console_lock (__console_unlock() / console_lock()) around each record in preemptible task context — and console_flush_one_record() calls cond_resched() (when do_cond_resched is true) outside vt_console_print()’s printing_lock for non-preemptible or dynamic-preemption kernels — calling console_conditional_schedule() inside fbcon_redraw*() or do_con_write() is completely unnecessary.
8e9bf8b9e8c0)Commit 8e9bf8b9e8c0 (“printk, vt, fbcon: Remove console_conditional_schedule()”, authored by Sebastian Andrzej Siewior) deletes the helper, its declaration/export, and all seven call sites:
--- a/drivers/tty/vt/vt.c+++ b/drivers/tty/vt/vt.c@@ -3230,7 +3230,6 @@ static int do_con_write(struct tty_struct *tty, const u8 *buf, int count)goto rescan_last_byte;}con_flush(vc, &draw);- console_conditional_schedule();notify_update(vc);return n;--- a/drivers/video/fbdev/core/fbcon.c+++ b/drivers/video/fbdev/core/fbcon.c@@ -1704,13 +1700,11 @@ static void fbcon_redraw(struct vc_data *vc, int line, int count, int offset)}}scr_writew(c, d);- console_conditional_schedule();s++;d++;} while (s < le);if (s > start)fbcon_putcs(vc, start, s - start, line, x);- console_conditional_schedule();if (offset > 0)line++;else {... (4 additional call sites removed identically in fbcon_redraw_move() and fbcon_redraw_blit())--- a/include/linux/console.h+++ b/include/linux/console.h@@ -697,7 +697,6 @@ extern int unregister_console(struct console *);extern void console_lock(void);extern int console_trylock(void);extern void console_unlock(void);-extern void console_conditional_schedule(void);extern void console_unblank(void);--- a/kernel/printk/printk.c+++ b/kernel/printk/printk.c@@ -3416,22 +3416,6 @@ void console_unlock(void)}EXPORT_SYMBOL(console_unlock);-/**- * console_conditional_schedule - yield the CPU if required- *- * If the console code is currently allowed to sleep, and- * if this CPU should yield the CPU to another task, do- * so here.- *- * Must be called within console_lock();.- */-void __sched console_conditional_schedule(void)-{- if (console_may_schedule)- cond_resched();-}-EXPORT_SYMBOL(console_conditional_schedule);-void console_unblank(void){
Specifically, the patch removes:
EXPORT_SYMBOL(console_conditional_schedule) in kernel/printk/printk.cinclude/linux/console.hdrivers/tty/vt/vt.c inside do_con_write()drivers/video/fbdev/core/fbcon.c (2 in fbcon_redraw_move(), 2 in fbcon_redraw_blit(), and 2 in fbcon_redraw())Build and boot with the RT debug options enabled, ensure a virtual terminal framebuffer console is active (console=tty0 on fbcon), and force heavy scrolling via printk() or /dev/kmsg:
# 1. Verify debug options in the active kernel config{ zcat /proc/config.gz 2>/dev/null || cat "/boot/config-$(uname -r)"; } \| grep -E 'CONFIG_(PREEMPT_RT|DEBUG_ATOMIC_SLEEP|PROVE_LOCKING)='# Expected:# CONFIG_PREEMPT_RT=y# CONFIG_DEBUG_ATOMIC_SLEEP=y# 2. Ensure console loglevel displays messages on the active VT/fbcon (test environment only)dmesg -n 8# 3. Generate kernel log bursts to scroll the active VT/fbcon displayfor i in $(seq 1 200); doprintf "<4>fbcon scroll stress test line %d\n" "$i" > /dev/kmsgdone# 4. Inspect kernel log for atomic-sleep warningsdmesg | grep -Ei 'sleeping function|might_resched|console_conditional_schedule'
Before fix (v6.19 with 1bc9a28f076f): BUG: sleeping function called from invalid context fires when vt_console_print() scrolls via fbcon_redraw*().
After fix (v7.0+ or patched v6.19): No warning appears during scrolling.
| Kernel Series | pr/legacy Present? | console_may_schedule Leak? | Fix Status |
|---|---|---|---|
| v7.0+ | Yes (CONFIG_PREEMPT_RT=y) | No | Fixed in v7.0-rc1 (8e9bf8b9e8c0) |
| v6.19 | Yes (CONFIG_PREEMPT_RT=y) | Yes (1bc9a28f076f) | Apply 8e9bf8b9e8c0 if unpatched |
| v6.12 - v6.18 | Yes (CONFIG_PREEMPT_RT=y, 5f53ca3ff83b4) | No (__console_flush_and_unlock() clears it) | Not triggered unless 1bc9a28f076f is backported |
| v6.6 LTS and older | No mainline pr/legacy | N/A | Not affected in mainline |
If you maintain a vendor or downstream kernel tree, do not rely on a nonexistent Kconfig option to check exposure. Instead, inspect the source directly:
# Check if your tree has both legacy_kthread_func calling console_flush_one_record# AND console_conditional_schedule() still present:grep -rn "console_conditional_schedule" kernel/printk/ drivers/tty/vt/ drivers/video/fbdev/ include/linux/grep -rn -A 25 "legacy_kthread_func" kernel/printk/printk.c
If legacy_kthread_func() invokes console_flush_one_record() directly (bypassing __console_flush_and_unlock()) while console_conditional_schedule() is still present, backport commit 8e9bf8b9e8c0. Note that other CONFIG_PREEMPT_RT atomic-sleep fixes in stable changelogs — such as commit cddc76b16516 in v6.6.70 (mm/kmemleak) or commit 799c8f0b9f3f in v7.2.9 (accel/ivpu) — address unrelated driver/subsystem locking bugs, not console_conditional_schedule().
Understanding how spinlock_t interacts with RCU and __might_resched() on PREEMPT_RT explains both why this warning fired and why preempt_count remained 0.
spin_trylock()On non-PREEMPT_RT builds:
spin_trylock(&lock) -> raw_spin_trylock() -> disables preemption (PREEMPT_LOCK_OFFSET)spin_unlock(&lock) -> raw_spin_unlock() -> enables preemption
On PREEMPT_RT builds (kernel/locking/spinlock_rt.c):
spin_trylock(&lock) -> rt_spin_trylock() -> acquires rt_mutex_base,calls rcu_read_lock() + migrate_disable()(PREEMPT_LOCK_OFFSET is 0; task stays preemptible)spin_unlock(&lock) -> rt_spin_unlock() -> calls migrate_enable() + rcu_read_unlock(),releases rt_mutex_base
Because PREEMPT_RT leaves preemption enabled while holding a spinlock_t, the RT lock wrapper explicitly calls migrate_disable() (so per-CPU assumptions hold while preempted) and rcu_read_lock() (preserving non-RT spinlock protection against RCU grace periods). Consequently, calling cond_resched() while holding spinlock_t violates the rule against voluntary scheduling inside an RCU read-side critical section.
| Lock Type | Non-RT Implementation | PREEMPT_RT Implementation | Can Sleep on Acquisition on RT? |
|---|---|---|---|
spinlock_t | raw_spinlock_t | rt_mutex_base-based (rt_spin_lock) | Yes (PI-aware; calls rcu_read_lock() + migrate_disable()) |
rwlock_t | Spinning reader/writer lock | rwbase_rt (rt_mutex_base-based) | Yes (PI for writers, not readers) |
mutex | Standard kernel mutex | rt_mutex_base-based mutex | Yes (always) |
semaphore | Counting semaphore | Counting semaphore (unchanged; no PI) | Yes (always) |
raw_spinlock_t | Spinning lock | Spinning lock | No (disables preemption; _irq/_irqsave also disable local IRQs) |
Ensure the test kernel has RT atomic-sleep and lockdep validation enabled:
CONFIG_PREEMPT_RT=yCONFIG_DEBUG_ATOMIC_SLEEP=yCONFIG_PROVE_LOCKING=y
Keep CONFIG_PROVE_LOCKING=y, CONFIG_DEBUG_LOCKDEP, and CONFIG_LOCK_STAT restricted to debug and CI kernels. Lockdep and lock statistics add substantial runtime overhead and are not intended for production real-time latency measurement or deployment builds.
If a warning arrives as raw hexadecimal addresses, resolve exact file paths and line numbers using the kernel’s helper script against the matching vmlinux debug image:
./scripts/decode_stacktrace.sh vmlinux < console-warning.log
While removing console_conditional_schedule() eliminates a locking-context violation rather than changing lock contention directly, always re-baseline RT scheduling latency on a non-debug (CONFIG_PROVE_LOCKING=n) kernel using cyclictest under representative console load:
# Run cyclictest on the target hardware (adjust priority/interval to your workload)cyclictest --mlockall --smp --priority=80 --interval=1000 --duration=60s \--histfile=latency.hist &# Generate representative console traffic concurrently, then evaluate# observed Min/Avg/Max wakeup latency against your system's real-time budget.
Evaluate observed Max latency against your system’s actual deadline budget and hardware platform rather than relying on an arbitrary universal microsecond threshold.
Before deleting or auditing any cond_resched() or might_sleep() call, verify every caller across all build configurations:
grep -rn "console_conditional_schedule\|cond_resched" \kernel/printk/ drivers/tty/vt/ drivers/video/fbdev/
console_lock() Instead of the Global Flagconsole_lock() (down_console_sem()) legitimately sets console_may_schedule = 1 because pr/legacy is a normal kernel thread running in process context. The bug is not that pr/legacy holds console_lock(), nor that console_lock() can sleep — it is that console_conditional_schedule() reads a global flag set at console_lock() time without knowing that vt_console_print() later acquired printing_lock.
PREEMPT_RTOn non-PREEMPT_RT kernels, force_legacy_kthread() is false, so pr/legacy never runs and the v6.19 regression is completely hidden. Always run CI boot and console-scrolling stress tests with CONFIG_PREEMPT_RT=y and CONFIG_DEBUG_ATOMIC_SLEEP=y.
cond_resched() with if (!in_atomic())Adding if (!in_atomic()) around cond_resched() would not even catch this case on PREEMPT_RT: because PREEMPT_LOCK_OFFSET is 0, preempt_count() and in_atomic() remain 0 while holding printing_lock! Moreover, kernel guidelines explicitly warn against using in_atomic() in driver code to decide whether sleeping is safe. Deleting obsolete conditional-scheduling hooks is the right fix.
PREEMPT_RT locking changes.spinlock_t, raw_spinlock_t, rwlock_t, mutex, and semaphore semantics under PREEMPT_RT.legacy_kthread_func() to console_flush_one_record().pr/legacy thread.cond_resched() between console records.PREEMPT_RT atomic-sleep fixes in drivers (accel/ivpu) and mm/kmemleak (cddc76b16516).The console_conditional_schedule() warning on PREEMPT_RT stems from a stale legacy scheduling helper (v2.4.9.11) colliding with Linux v6.19’s pr/legacy kthread refactor (1bc9a28f076f). Because legacy_kthread_func() called console_lock() (setting console_may_schedule = 1) and then console_flush_one_record() directly without clearing console_may_schedule, vt_console_print() entered fbcon_redraw*() while holding printing_lock (spinlock_t) with console_may_schedule still set. On PREEMPT_RT, rt_spin_trylock() enters an RCU read-side critical section (rcu_read_lock()), causing cond_resched() (and its __might_resched() check) to emit BUG: sleeping function called from invalid context (RCU nest depth: 1, expected: 0).
The upstream fix is complete removal: Linux commit 8e9bf8b9e8c0 (v7.0-rc1) deletes console_conditional_schedule(), its header declaration and symbol export, and all seven call sites across do_con_write() in vt.c and fbcon_redraw*() in fbcon.c, leaving per-record scheduling to console_flush_one_record() and legacy_kthread_func().
Quick Links
Legal Stuff





