| 0/0 |
2026/11/03 15:10 |
flow |
patching |
8h53m
Results: map[AckedBy:[] Fixes:map[AuthorEmail:ming.lei@redhat.com AuthorName:Ming Lei Hash:f6661b1d0525f3764596a1b65eeed9e75aecafa7 Title:block: track queue dying state automatically for modeling queue freeze lockdep] KernelBranch:master KernelCommit:6628e7d4c6b25c8d18f1345e3a20d21829aae7e4 KernelRepo:git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git PatchDescription:block: snapshot lock mask to fix queue freeze lockdep race
A race between queue freeze/unfreeze operations and concurrent queue death
or draining can cause lockdep to report a lock held when returning to user
space:
================================================
WARNING: lock held when returning to user space!
...
task is leaving the kernel with locks still held!
locks held:
(&q->q_usage_counter(queue)){+.+.}-{0:0}, at: elevator_change+0x194/0x480
block/elevator.c:668
The lockdep tracking for queue freeze and unfreeze previously stored
mq_freeze_queue_dying and mq_freeze_disk_dead directly in struct
request_queue. These fields were initialized under q->mq_freeze_lock on the
outermost freeze (when !q->mq_freeze_depth). During unfreeze,
__blk_mq_unfreeze_queue() decremented q->mq_freeze_depth to 0, cleared
q->mq_freeze_owner, and released q->mq_freeze_lock. Only after releasing
the mutex did blk_mq_unfreeze_queue_nomemrestore() call
blk_unfreeze_release_lock(q), which inspected q->mq_freeze_queue_dying and
q->mq_freeze_disk_dead without holding q->mq_freeze_lock.
If another thread concurrently initiates queue draining or marks the queue
dying (such as during device destruction via blk_mark_disk_dead()), it sets
QUEUE_FLAG_DYING and calls __blk_freeze_queue_start(). Because
q->mq_freeze_depth has already dropped to 0 and q->mq_freeze_lock is
unlocked, the second thread acquires q->mq_freeze_lock, sees depth 0, and
overwrites q->mq_freeze_queue_dying with true. When the unfreezing thread
subsequently executes blk_unfreeze_release_lock(), it observes
q->mq_freeze_queue_dying as true, skips releasing q->q_lockdep_map, and
exits back to user space with the lockdep map still held.
Additionally, blk_queue_start_drain() unconditionally passed current as the
freeze owner to __blk_freeze_queue_start(). Because draining a dying queue
is permanent and does not release lockdep maps, tracking freeze ownership
on dying queues can corrupt owner tracking if called in contexts that
already hold an outer freeze.
Fix these issues by replacing the mutable per-queue boolean flags with a
snapshotted lock mask returned by value. Define BLK_FREEZE_LOCK_IO and
BLK_FREEZE_LOCK_QUEUE bit flags and store unsigned int mq_freeze_lock_mask
in struct request_queue. In blk_freeze_set_owner() and
blk_unfreeze_check_owner(), compute and retrieve the lock mask while
holding q->mq_freeze_lock, returning it by value from
__blk_freeze_queue_start() and __blk_mq_unfreeze_queue(). Pass the lock
mask by value to blk_freeze_acquire_lock() and blk_unfreeze_release_lock(),
avoiding unlocked reads of mutable request_queue fields after dropping
q->mq_freeze_lock. In blk_queue_start_drain(), pass NULL as owner to
__blk_freeze_queue_start() when blk_queue_dying(q) is true, preventing
permanent dying drains from claiming freeze ownership. Finally, propagate
and consume the lock mask in __blk_mark_disk_dead() and __del_gendisk(). PatchDiff:diff --git a/block/blk-core.c b/block/blk-core.c
index 8836c7028..fc3ab62e8 100644
--- a/block/blk-core.c
+++ b/block/blk-core.c
@@ -324,20 +324,21 @@ void blk_put_queue(struct request_queue *q)
}
EXPORT_SYMBOL(blk_put_queue);
-bool blk_queue_start_drain(struct request_queue *q)
+unsigned int blk_queue_start_drain(struct request_queue *q)
{
/*
* When queue DYING flag is set, we need to block new req
* entering queue, so we call blk_freeze_queue_start() to
* prevent I/O from crossing blk_queue_enter().
*/
- bool freeze = __blk_freeze_queue_start(q, current);
+ unsigned int lock_mask = __blk_freeze_queue_start(q,
+ blk_queue_dying(q) ? NULL : current);
if (queue_is_mq(q))
blk_mq_wake_waiters(q);
/* Make blk_queue_enter() reexamine the DYING flag. */
wake_up_all(&q->mq_freeze_wq);
- return freeze;
+ return lock_mask;
}
/**
diff --git a/block/blk-mq.c b/block/blk-mq.c
index d9ab295be..3f64a59e5 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -113,60 +113,64 @@ void blk_mq_in_driver_rw(struct block_device *part, unsigned int inflight[2])
}
#ifdef CONFIG_LOCKDEP
-static bool blk_freeze_set_owner(struct request_queue *q,
- struct task_struct *owner)
+static unsigned int blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
{
+ unsigned int lock_mask = 0;
+
if (!owner)
- return false;
+ return 0;
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
- q->mq_freeze_disk_dead = !q->disk ||
- test_bit(GD_DEAD, &q->disk->state) ||
- !blk_queue_registered(q);
- q->mq_freeze_queue_dying = blk_queue_dying(q);
- return true;
+ if (q->disk && !test_bit(GD_DEAD, &q->disk->state) &&
+ blk_queue_registered(q))
+ lock_mask |= BLK_FREEZE_LOCK_IO;
+ if (!blk_queue_dying(q))
+ lock_mask |= BLK_FREEZE_LOCK_QUEUE;
+ q->mq_freeze_lock_mask = lock_mask;
+ return lock_mask;
}
if (owner == q->mq_freeze_owner)
q->mq_freeze_owner_depth += 1;
- return false;
+ return 0;
}
/* verify the last unfreeze in owner context */
-static bool blk_unfreeze_check_owner(struct request_queue *q)
+static unsigned int blk_unfreeze_check_owner(struct request_queue *q)
{
if (q->mq_freeze_owner != current)
- return false;
+ return 0;
if (--q->mq_freeze_owner_depth == 0) {
q->mq_freeze_owner = NULL;
- return true;
+ return q->mq_freeze_lock_mask;
}
- return false;
+ return 0;
}
#else
-static bool blk_freeze_set_owner(struct request_queue *q,
- struct task_struct *owner)
+static unsigned int blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
{
- return false;
+ return 0;
}
-static bool blk_unfreeze_check_owner(struct request_queue *q)
+static unsigned int blk_unfreeze_check_owner(struct request_queue *q)
{
- return false;
+ return 0;
}
#endif
-bool __blk_freeze_queue_start(struct request_queue *q,
- struct task_struct *owner)
+unsigned int __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner)
{
- bool freeze;
+ unsigned int lock_mask;
mutex_lock(&q->mq_freeze_lock);
- freeze = blk_freeze_set_owner(q, owner);
+ lock_mask = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
@@ -176,13 +180,14 @@ bool __blk_freeze_queue_start(struct request_queue *q,
mutex_unlock(&q->mq_freeze_lock);
}
- return freeze;
+ return lock_mask;
}
void blk_freeze_queue_start(struct request_queue *q)
{
- if (__blk_freeze_queue_start(q, current))
- blk_freeze_acquire_lock(q);
+ unsigned int lock_mask = __blk_freeze_queue_start(q, current);
+
+ blk_freeze_acquire_lock(q, lock_mask);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -208,9 +213,9 @@ void blk_mq_freeze_queue_nomemsave(struct request_queue *q)
}
EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_nomemsave);
-bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
+unsigned int __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
- bool unfreeze;
+ unsigned int lock_mask;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
@@ -221,16 +226,17 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
}
- unfreeze = blk_unfreeze_check_owner(q);
+ lock_mask = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
- return unfreeze;
+ return lock_mask;
}
void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
{
- if (__blk_mq_unfreeze_queue(q, false))
- blk_unfreeze_release_lock(q);
+ unsigned int lock_mask = __blk_mq_unfreeze_queue(q, false);
+
+ blk_unfreeze_release_lock(q, lock_mask);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_nomemrestore);
diff --git a/block/blk.h b/block/blk.h
index ed2172472..2c4d5ee7d 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -55,10 +55,11 @@ const char *blk_status_to_tag(blk_status_t status);
blk_status_t tag_to_blk_status(const char *tag);
enum req_op str_to_blk_op(const char *op);
-bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
-bool blk_queue_start_drain(struct request_queue *q);
-bool __blk_freeze_queue_start(struct request_queue *q,
- struct task_struct *owner);
+unsigned int __blk_mq_unfreeze_queue(struct request_queue *q,
+ bool force_atomic);
+unsigned int blk_queue_start_drain(struct request_queue *q);
+unsigned int __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner);
int __bio_queue_enter(struct request_queue *q, struct bio *bio);
void submit_bio_noacct_nocheck(struct bio *bio, bool split);
int bio_submit_or_kill(struct bio *bio, unsigned int flags);
@@ -777,27 +778,36 @@ blk_status_t bio_integrity_verify(struct bio *bio,
void blk_integrity_prepare(struct request *rq);
void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
+enum {
+ BLK_FREEZE_LOCK_IO = (1 << 0),
+ BLK_FREEZE_LOCK_QUEUE = (1 << 1),
+};
+
#ifdef CONFIG_LOCKDEP
-static inline void blk_freeze_acquire_lock(struct request_queue *q)
+static inline void blk_freeze_acquire_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
- if (!q->mq_freeze_disk_dead)
+ if (lock_mask & BLK_FREEZE_LOCK_IO)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
- if (!q->mq_freeze_queue_dying)
+ if (lock_mask & BLK_FREEZE_LOCK_QUEUE)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q)
+static inline void blk_unfreeze_release_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
- if (!q->mq_freeze_queue_dying)
+ if (lock_mask & BLK_FREEZE_LOCK_QUEUE)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
- if (!q->mq_freeze_disk_dead)
+ if (lock_mask & BLK_FREEZE_LOCK_IO)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
#else
-static inline void blk_freeze_acquire_lock(struct request_queue *q)
+static inline void blk_freeze_acquire_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q)
+static inline void blk_unfreeze_release_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
}
#endif
diff --git a/block/genhd.c b/block/genhd.c
index 10ca8b4d6..e73349b74 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -657,13 +657,13 @@ static void blk_report_disk_dead(struct gendisk *disk, bool surprise)
rcu_read_unlock();
}
-static bool __blk_mark_disk_dead(struct gendisk *disk)
+static unsigned int __blk_mark_disk_dead(struct gendisk *disk)
{
/*
* Fail any new I/O.
*/
if (test_and_set_bit(GD_DEAD, &disk->state))
- return false;
+ return 0;
if (test_bit(GD_OWNS_QUEUE, &disk->state))
blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
@@ -699,7 +699,7 @@ static void __del_gendisk(struct gendisk *disk)
struct request_queue *q = disk->queue;
struct block_device *part;
unsigned long idx;
- bool start_drain;
+ unsigned int lock_mask;
might_sleep();
@@ -727,9 +727,8 @@ static void __del_gendisk(struct gendisk *disk)
* Drop all partitions now that the disk is marked dead.
*/
mutex_lock(&disk->open_mutex);
- start_drain = __blk_mark_disk_dead(disk);
- if (start_drain)
- blk_freeze_acquire_lock(q);
+ lock_mask = __blk_mark_disk_dead(disk);
+ blk_freeze_acquire_lock(q, lock_mask);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
@@ -777,8 +776,7 @@ static void __del_gendisk(struct gendisk *disk)
else if (queue_is_mq(q))
blk_mq_exit_queue(q);
- if (start_drain)
- blk_unfreeze_release_lock(q);
+ blk_unfreeze_release_lock(q, lock_mask);
}
static void disable_elv_switch(struct request_queue *q)
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 0c2010230..32a8e93c4 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -637,11 +637,10 @@ struct request_queue {
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
/*
- * Records disk & queue state in current context, used in unfreeze
+ * Records lockdep locks acquired in owner context, used in unfreeze
* queue
*/
- bool mq_freeze_disk_dead;
- bool mq_freeze_queue_dying;
+ unsigned int mq_freeze_lock_mask;
#endif
wait_queue_head_t mq_freeze_wq;
/*
Recipients:[map[Email:axboe@kernel.dk Name:Jens Axboe To:true] map[Email:linux-block@vger.kernel.org Name: To:true] map[Email:linux-kernel@vger.kernel.org Name: To:false] map[Email:ming.lei@redhat.com Name:Ming Lei To:true]] ReportedBy:[] ReviewedBy:[] SuggestedBy:[] TestedBy:[]]
|
| 1/1 |
2026/11/03 15:10 |
action |
base-commit-picker |
0m
Results: map[KernelBranch:master KernelCommit:6628e7d4c6b25c8d18f1345e3a20d21829aae7e4 KernelRepo:git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git]
|
| 2/1 |
2026/11/03 15:11 |
action |
syz-repro-to-c-repro |
0m
Results: map[SimplifiedCRepro:// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <endian.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
uint64_t r[3] = {0xffffffffffffffff, 0xffffffffffffffff, 0x0};
int main(void)
{
syscall(__NR_mmap, /*addr=*/0x1ffffffff000ul, /*len=*/0x1000, /*prot=*/0ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
syscall(__NR_mmap, /*addr=*/0x200000000000ul, /*len=*/0x1000000, /*prot=PROT_WRITE|PROT_READ|PROT_EXEC*/7ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
syscall(__NR_mmap, /*addr=*/0x200001000000ul, /*len=*/0x1000, /*prot=*/0ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
const char* reason;
(void)reason;
intptr_t res = 0;
if (write(1, "executing program\n", sizeof("executing program\n") - 1)) {}
// openat$dm_control arguments: [
// fd: const = 0xffffffffffffff9c (8 bytes)
// file: ptr[in, buffer] {
// buffer: {2f 64 65 76 2f 6d 61 70 70 65 72 2f 63 6f 6e 74 72 6f 6c 00} (length 0x14)
// }
// flags: open_flags = 0x2 (4 bytes)
// mode: const = 0x0 (2 bytes)
// ]
// returns fd_dm_ctl
memcpy((void*)0x2000000009c0, "/dev/mapper/control\000", 20);
res = syscall(__NR_openat, /*fd=*/0xffffffffffffff9cul, /*file=*/0x2000000009c0ul, /*flags=O_RDWR*/2, /*mode=*/0);
if (res != -1)
r[0] = res;
// openat$dm_control arguments: [
// fd: const = 0xffffffffffffff9c (8 bytes)
// file: ptr[in, buffer] {
// buffer: {2f 64 65 76 2f 6d 61 70 70 65 72 2f 63 6f 6e 74 72 6f 6c 00} (length 0x14)
// }
// flags: open_flags = 0x2 (4 bytes)
// mode: const = 0x0 (2 bytes)
// ]
// returns fd_dm_ctl
memcpy((void*)0x200000000200, "/dev/mapper/control\000", 20);
res = syscall(__NR_openat, /*fd=*/0xffffffffffffff9cul, /*file=*/0x200000000200ul, /*flags=O_RDWR*/2, /*mode=*/0);
if (res != -1)
r[1] = res;
// ioctl$DM_DEV_CREATE arguments: [
// fd: fd_dm_ctl (resource)
// cmd: const = 0xc138fd03 (4 bytes)
// arg: ptr[inout, dm_ioctl_t[dm_id_create, void, const[0, int32], const[0, int32]]] {
// dm_ioctl_t[dm_id_create, void, const[0, int32], const[0, int32]] {
// version_major: const = 0x4 (4 bytes)
// version_minor: const = 0x0 (4 bytes)
// version_patch: const = 0x0 (4 bytes)
// data_size: bytesize = 0x138 (4 bytes)
// data_start: offsetof = 0x138 (4 bytes)
// target_count: const = 0x0 (4 bytes)
// open_count: const = 0x0 (4 bytes)
// flags: dm_ioctl_flags = 0xc01 (4 bytes)
// event_nr: const = 0x0 (4 bytes)
// padding: const = 0x0 (4 bytes)
// id: dm_id_create {
// dev: dm_dev_number (resource)
// name: dm_dev_name {
// prefix: buffer: {73 79 7a} (length 0x3)
// proc: proc = 0x0 (1 bytes)
// slot: buffer: {32 00} (length 0x2)
// pad = 0x0 (122 bytes)
// }
// uuid: union dm_dev_uuid_opt {
// none: const = 0x0 (1 bytes)
// }
// }
// data: buffer: {} (length 0x0)
// }
// }
// ]
*(uint32_t*)0x200000000240 = 4;
*(uint32_t*)0x200000000244 = 0;
*(uint32_t*)0x200000000248 = 0;
*(uint32_t*)0x20000000024c = 0x138;
*(uint32_t*)0x200000000250 = 0x138;
*(uint32_t*)0x200000000254 = 0;
*(uint32_t*)0x200000000258 = 0;
*(uint32_t*)0x20000000025c = 0xc01;
*(uint32_t*)0x200000000260 = 0;
*(uint32_t*)0x200000000264 = 0;
memcpy((void*)0x200000000270, "syz", 3);
*(uint8_t*)0x200000000273 = 0x61;
memcpy((void*)0x200000000274, "2\000", 2);
*(uint8_t*)0x2000000002f0 = 0;
res = syscall(__NR_ioctl, /*fd=*/r[1], /*cmd=*/0xc138fd03, /*arg=*/0x200000000240ul);
if (res != -1)
r[2] = *(uint64_t*)0x200000000268;
// ioctl$DM_TABLE_LOAD arguments: [
// fd: fd_dm_ctl (resource)
// cmd: const = 0xc138fd09 (4 bytes)
// arg: ptr[inout, dm_ioctl_t[dm_id_lookup, array[dm_target, 1], len[data, int32], const[0, int32]]] {
// dm_ioctl_t[dm_id_lookup, array[dm_target, 1], len[data, int32], const[0, int32]] {
// version_major: const = 0x4 (4 bytes)
// version_minor: const = 0x32 (4 bytes)
// version_patch: const = 0x0 (4 bytes)
// data_size: bytesize = 0x1b0 (4 bytes)
// data_start: offsetof = 0x138 (4 bytes)
// target_count: len = 0x1 (4 bytes)
// open_count: const = 0x0 (4 bytes)
// flags: dm_ioctl_flags = 0x24400 (4 bytes)
// event_nr: const = 0x0 (4 bytes)
// padding: const = 0x0 (4 bytes)
// id: union dm_id_lookup {
// by_dev: dm_id_by_dev {
// dev: dm_dev_number (resource)
// pad = 0x0 (264 bytes)
// }
// }
// data: array[dm_target] {
// union dm_target {
// multipath: dm_target_spec_t[dm_target_multipath, dm_multipath_params] {
// sector_start: const = 0x0 (8 bytes)
// length: dm_lengths = 0x54d0 (8 bytes)
// status: const = 0x0 (4 bytes)
// next: bytesize = 0x78 (4 bytes)
// target_type: buffer: {6d 75 6c 74 69 70 61 74 68 00 00 00 00 00 00 00} (length 0x10)
// params: dm_multipath_params {
// feat: buffer: {31 20 72 65 74 61 69 6e 5f 61 74 74 61 63 68 65 64 5f 68 77 5f 68 61 6e 64 6c 65 72} (length 0x1c)
// sp0: const = 0x20 (1 bytes)
// hwh: buffer: {31 20 72 64 61 63} (length 0x6)
// sp1: const = 0x20 (1 bytes)
// ngrp: len = 0x0 (20 bytes)
// sp2: const = 0x20 (1 bytes)
// init: int8 = 0x0 (20 bytes)
// groups: array[dm_mpath_group] {
// }
// }
// z: const = 0x0 (1 bytes)
// }
// }
// }
// }
// }
// ]
*(uint32_t*)0x200000000380 = 4;
*(uint32_t*)0x200000000384 = 0x32;
*(uint32_t*)0x200000000388 = 0;
*(uint32_t*)0x20000000038c = 0x1b0;
*(uint32_t*)0x200000000390 = 0x138;
*(uint32_t*)0x200000000394 = 1;
*(uint32_t*)0x200000000398 = 0;
*(uint32_t*)0x20000000039c = 0x24400;
*(uint32_t*)0x2000000003a0 = 0;
*(uint32_t*)0x2000000003a4 = 0;
*(uint64_t*)0x2000000003a8 = r[2];
*(uint64_t*)0x2000000004b8 = 0;
*(uint64_t*)0x2000000004c0 = 0x54d0;
*(uint32_t*)0x2000000004c8 = 0;
*(uint32_t*)0x2000000004cc = 0x78;
memcpy((void*)0x2000000004d0, "multipath\000\000\000\000\000\000\000", 16);
memcpy((void*)0x2000000004e0, "1 retain_attached_hw_handler", 28);
*(uint8_t*)0x2000000004fc = 0x20;
memcpy((void*)0x2000000004fd, "1 rdac", 6);
*(uint8_t*)0x200000000503 = 0x20;
sprintf((char*)0x200000000504, "%020llu", (long long)0);
*(uint8_t*)0x200000000518 = 0x20;
sprintf((char*)0x200000000519, "%020llu", (long long)0);
*(uint8_t*)0x20000000052d = 0;
syscall(__NR_ioctl, /*fd=*/r[1], /*cmd=*/0xc138fd09, /*arg=*/0x200000000380ul);
// ioctl$DM_DEV_REMOVE arguments: [
// fd: fd_dm_ctl (resource)
// cmd: const = 0xc138fd04 (4 bytes)
// arg: ptr[inout, dm_ioctl_t[dm_id_lookup, void, const[0, int32], const[0, int32]]] {
// dm_ioctl_t[dm_id_lookup, void, const[0, int32], const[0, int32]] {
// version_major: const = 0x4 (4 bytes)
// version_minor: const = 0x0 (4 bytes)
// version_patch: const = 0x0 (4 bytes)
// data_size: bytesize = 0x138 (4 bytes)
// data_start: offsetof = 0x138 (4 bytes)
// target_count: const = 0x0 (4 bytes)
// open_count: const = 0x0 (4 bytes)
// flags: dm_ioctl_flags = 0x9a4ee504b98d1bf2 (4 bytes)
// event_nr: const = 0x0 (4 bytes)
// padding: const = 0x0 (4 bytes)
// id: union dm_id_lookup {
// by_dev: dm_id_by_dev {
// dev: dm_dev_number (resource)
// pad = 0x0 (264 bytes)
// }
// }
// data: buffer: {} (length 0x0)
// }
// }
// ]
*(uint32_t*)0x200000000540 = 4;
*(uint32_t*)0x200000000544 = 0;
*(uint32_t*)0x200000000548 = 0;
*(uint32_t*)0x20000000054c = 0x138;
*(uint32_t*)0x200000000550 = 0x138;
*(uint32_t*)0x200000000554 = 0;
*(uint32_t*)0x200000000558 = 0;
*(uint32_t*)0x20000000055c = 0xb98d1bf2;
*(uint32_t*)0x200000000560 = 0;
*(uint32_t*)0x200000000564 = 0;
*(uint64_t*)0x200000000568 = r[2];
syscall(__NR_ioctl, /*fd=*/r[0], /*cmd=*/0xc138fd04, /*arg=*/0x200000000540ul);
return 0;
}
]
|
| 3/1 |
2026/11/03 15:11 |
action |
kernel-checkouter |
0m
Results: map[KernelSrc:/app/workdir/cache/src/3613a638dc7fae26deb3e7e05aeccc393739c861/data]
|
| 4/1 |
2026/11/03 15:11 |
action |
kernel-builder |
0m
Results: map[KernelObj:/app/workdir/cache/build/04c788ce8e84a06f43bc3cccc28106bb617bc671/data]
|
| 5/1 |
2026/11/03 15:11 |
action |
crash-reproducer |
0m
Results: map[OtherCrashReports:[======================================================
WARNING: possible circular locking dependency detected
syzkaller #1 Not tainted
------------------------------------------------------
syz.3.1506/11612 is trying to acquire lock:
ffff888037901b48 (&q->debugfs_mutex){+.+.}-{4:4}, at: blk_debugfs_lock_nomemsave block/blk.h:814 [inline]
ffff888037901b48 (&q->debugfs_mutex){+.+.}-{4:4}, at: blk_debugfs_lock block/blk.h:828 [inline]
ffff888037901b48 (&q->debugfs_mutex){+.+.}-{4:4}, at: wbt_init_enable_default+0x146/0x220 block/blk-wbt.c:794
but task is already holding lock:
ffff888037901300 (&q->q_usage_counter(io)#99){++++}-{0:0}, at: blk_mq_freeze_queue include/linux/blk-mq.h:959 [inline]
ffff888037901300 (&q->q_usage_counter(io)#99){++++}-{0:0}, at: rq_qos_add+0x15b/0x370 block/blk-rq-qos.c:341
which lock already depends on the new lock.
the existing dependency chain (in reverse order) is:
-> #3 (&q->q_usage_counter(io)#99){++++}-{0:0}:
blk_alloc_queue+0x544/0x690 block/blk-core.c:505
__blk_alloc_disk+0xe3/0x1d0 block/genhd.c:1527
alloc_dev drivers/md/dm.c:2349 [inline]
dm_create+0x476/0xf70 drivers/md/dm.c:2563
dev_create+0x1f7/0x400 drivers/md/dm-ioctl.c:977
ctl_ioctl drivers/md/dm-ioctl.c:2221 [inline]
dm_ctl_ioctl+0x9ec/0xe10 drivers/md/dm-ioctl.c:2243
vfs_ioctl fs/ioctl.c:51 [inline]
__do_sys_ioctl fs/ioctl.c:597 [inline]
__se_sys_ioctl+0xfc/0x170 fs/ioctl.c:583
do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline]
do_syscall_64+0x166/0x520 arch/x86/entry/syscall_64.c:84
entry_SYSCALL_64_after_hwframe+0x77/0x7f
-> #2 (fs_reclaim){+.+.}-{0:0}:
__fs_reclaim_acquire mm/page_alloc.c:4360 [inline]
fs_reclaim_acquire+0x71/0x100 mm/page_alloc.c:4374
might_alloc include/linux/sched/mm.h:316 [inline]
slab_pre_alloc_hook mm/slub.c:4673 [inline]
slab_alloc_node mm/slub.c:5011 [inline]
kmem_cache_alloc_lru_noprof+0x65/0x5f0 mm/slub.c:5066
__d_alloc+0x37/0x820 fs/dcache.c:1945
d_alloc+0x4b/0x190 fs/dcache.c:2031
lookup_one_qstr_excl+0xd8/0x360 fs/namei.c:1812
__start_dirop fs/namei.c:2926 [inline]
start_dirop+0x5c/0x90 fs/namei.c:2948
simple_start_creating+0xcc/0x110 fs/libfs.c:2310
debugfs_start_creating+0xca/0x1b0 fs/debugfs/inode.c:397
debugfs_create_dir+0x24/0x350 fs/debugfs/inode.c:575
regulator_init+0x6c/0x110 drivers/regulator/core.c:6787
do_one_initcall+0x250/0x870 init/main.c:1419
do_initcall_level+0x10a/0x1a0 init/main.c:1481
do_initcalls+0x59/0xa0 init/main.c:1497
kernel_init_freeable+0x29d/0x3e0 init/main.c:1732
kernel_init+0x22/0x1d0 init/main.c:1622
ret_from_fork+0x514/0xb70 arch/x86/kernel/process.c:158
ret_from_fork_asm+0x1a/0x30 arch/x86/entry/entry_64.S:245
-> #1 (&sb->s_type->i_mutex_key#3/1){+.+.}-{4:4}:
down_write_nested+0x98/0x200 kernel/locking/rwsem.c:1757
inode_lock_nested include/linux/fs.h:1071 [inline]
__start_dirop fs/namei.c:2924 [inline]
start_dirop+0x4f/0x90 fs/namei.c:2948
simple_start_creating+0xcc/0x110 fs/libfs.c:2310
debugfs_start_creating+0xca/0x1b0 fs/debugfs/inode.c:397
debugfs_create_dir+0x24/0x350 fs/debugfs/inode.c:575
blk_register_queue+0x189/0x4f0 block/blk-sysfs.c:968
__add_disk+0x6b8/0xdb0 block/genhd.c:531
add_disk_fwnode+0x143/0x3a0 block/genhd.c:604
add_disk include/linux/blkdev.h:801 [inline]
brd_alloc+0x5a9/0x7c0 drivers/block/brd.c:340
brd_init+0xc1/0x120 drivers/block/brd.c:420
do_one_initcall+0x250/0x870 init/main.c:1419
do_initcall_level+0x10a/0x1a0 init/main.c:1481
do_initcalls+0x59/0xa0 init/main.c:1497
kernel_init_freeable+0x29d/0x3e0 init/main.c:1732
kernel_init+0x22/0x1d0 init/main.c:1622
ret_from_fork+0x514/0xb70 arch/x86/kernel/process.c:158
ret_from_fork_asm+0x1a/0x30 arch/x86/entry/entry_64.S:245
-> #0 (&q->debugfs_mutex){+.+.}-{4:4}:
check_prev_add kernel/locking/lockdep.c:3209 [inline]
check_prevs_add kernel/locking/lockdep.c:3328 [inline]
validate_chain kernel/locking/lockdep.c:3952 [inline]
__lock_acquire+0x164c/0x2de0 kernel/locking/lockdep.c:5288
lock_acquire+0x115/0x350 kernel/locking/lockdep.c:5942
__mutex_lock_common kernel/locking/mutex.c:646 [inline]
__mutex_lock+0x197/0x15a0 kernel/locking/mutex.c:821
blk_debugfs_lock_nomemsave block/blk.h:814 [inline]
blk_debugfs_lock block/blk.h:828 [inline]
wbt_init_enable_default+0x146/0x220 block/blk-wbt.c:794
blk_register_queue+0x420/0x4f0 block/blk-sysfs.c:995
__add_disk+0x6b8/0xdb0 block/genhd.c:531
add_disk_fwnode+0x100/0x3a0 block/genhd.c:600
add_disk include/linux/blkdev.h:801 [inline]
dm_setup_md_queue+0x23d/0x4f0 drivers/md/dm.c:2632
table_load+0x4fd/0x8a0 drivers/md/dm-ioctl.c:1661
ctl_ioctl drivers/md/dm-ioctl.c:2221 [inline]
dm_ctl_ioctl+0x9ec/0xe10 drivers/md/dm-ioctl.c:2243
vfs_ioctl fs/ioctl.c:51 [inline]
__do_sys_ioctl fs/ioctl.c:597 [inline]
__se_sys_ioctl+0xfc/0x170 fs/ioctl.c:583
do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline]
do_syscall_64+0x166/0x520 arch/x86/entry/syscall_64.c:84
entry_SYSCALL_64_after_hwframe+0x77/0x7f
other info that might help us debug this:
Chain exists of:
&q->debugfs_mutex --> fs_reclaim --> &q->q_usage_counter(io)#99
Possible unsafe locking scenario:
CPU0 CPU1
---- ----
lock(&q->q_usage_counter(io)#99);
lock(fs_reclaim);
lock(&q->q_usage_counter(io)#99);
lock(&q->debugfs_mutex);
*** DEADLOCK ***
locks held by syz.3.1506/11612: 6, last CPU#0:
#0: ffff888024281190 (&md->type_lock){+.+.}-{4:4}, at: table_load+0x1dd/0x8a0 drivers/md/dm-ioctl.c:1644
#1: ffff8880242810e8 (&md->table_devices_lock){+.+.}-{4:4}, at: dm_setup_md_queue+0x20b/0x4f0 drivers/md/dm.c:2631
#2: ffff888079eac1c0 (&set->update_nr_hwq_lock){++++}-{4:4}, at: add_disk_fwnode+0xea/0x3a0 block/genhd.c:599
#3: ffff8880379018b0 (&q->sysfs_lock){+.+.}-{4:4}, at: blk_register_queue+0x10d/0x4f0 block/blk-sysfs.c:965
#4: ffff888037901300 (&q->q_usage_counter(io)#99){++++}-{0:0}, at: blk_mq_freeze_queue include/linux/blk-mq.h:959 [inline]
#4: ffff888037901300 (&q->q_usage_counter(io)#99){++++}-{0:0}, at: rq_qos_add+0x15b/0x370 block/blk-rq-qos.c:341
#5: ffff888037901338 (&q->q_usage_counter(queue)#53){+.+.}-{0:0}, at: blk_mq_freeze_queue include/linux/blk-mq.h:959 [inline]
#5: ffff888037901338 (&q->q_usage_counter(queue)#53){+.+.}-{0:0}, at: rq_qos_add+0x15b/0x370 block/blk-rq-qos.c:341
stack backtrace:
CPU: 0 UID: 0 PID: 11612 Comm: syz.3.1506 Not tainted syzkaller #1 PREEMPT(full)
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 10/15/2026
Call Trace:
<TASK>
dump_stack_lvl+0xe8/0x150 lib/dump_stack.c:120
print_circular_bug+0x2e2/0x300 kernel/locking/lockdep.c:2087
check_noncircular+0x12f/0x150 kernel/locking/lockdep.c:2219
check_prev_add kernel/locking/lockdep.c:3209 [inline]
check_prevs_add kernel/locking/lockdep.c:3328 [inline]
validate_chain kernel/locking/lockdep.c:3952 [inline]
__lock_acquire+0x164c/0x2de0 kernel/locking/lockdep.c:5288
lock_acquire+0x115/0x350 kernel/locking/lockdep.c:5942
__mutex_lock_common kernel/locking/mutex.c:646 [inline]
__mutex_lock+0x197/0x15a0 kernel/locking/mutex.c:821
blk_debugfs_lock_nomemsave block/blk.h:814 [inline]
blk_debugfs_lock block/blk.h:828 [inline]
wbt_init_enable_default+0x146/0x220 block/blk-wbt.c:794
blk_register_queue+0x420/0x4f0 block/blk-sysfs.c:995
__add_disk+0x6b8/0xdb0 block/genhd.c:531
add_disk_fwnode+0x100/0x3a0 block/genhd.c:600
add_disk include/linux/blkdev.h:801 [inline]
dm_setup_md_queue+0x23d/0x4f0 drivers/md/dm.c:2632
table_load+0x4fd/0x8a0 drivers/md/dm-ioctl.c:1661
ctl_ioctl drivers/md/dm-ioctl.c:2221 [inline]
dm_ctl_ioctl+0x9ec/0xe10 drivers/md/dm-ioctl.c:2243
vfs_ioctl fs/ioctl.c:51 [inline]
__do_sys_ioctl fs/ioctl.c:597 [inline]
__se_sys_ioctl+0xfc/0x170 fs/ioctl.c:583
do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline]
do_syscall_64+0x166/0x520 arch/x86/entry/syscall_64.c:84
entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7fb32d19fb19
Code: ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 e8 ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007fb32e00b028 EFLAGS: 00000246 ORIG_RAX: 0000000000000010
RAX: ffffffffffffffda RBX: 00007fb32d425fa0 RCX: 00007fb32d19fb19
RDX: 0000200000000380 RSI: 00000000c138fd09 RDI: 0000000000000004
RBP: 00007fb32d237b70 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000
R13: 00007fb32d426038 R14: 00007fb32d425fa0 R15: 00007ffd09e4dbf8
</TASK>
device-mapper: ioctl: device has been removed from the dev hash table.
] ReproducedBugTitle:WARNING: lock held when returning to user space in elevator_change ReproducedCrashReport:device-mapper: ioctl: device has been removed from the dev hash table.
================================================
WARNING: lock held when returning to user space!
syzkaller #1 Not tainted
------------------------------------------------
syz.3.1525/11804 is leaving the kernel with locks still held!
locks held by syz.3.1525/11804: 1, last CPU#0:
#0: ffff88805abdd468 (&q->q_usage_counter(queue)#52){+.+.}-{0:0}, at: blk_mq_freeze_queue include/linux/blk-mq.h:959 [inline]
#0: ffff88805abdd468 (&q->q_usage_counter(queue)#52){+.+.}-{0:0}, at: elevator_change+0x194/0x480 block/elevator.c:668
ReproducedFaultInjection:]
|
| 6/1 |
2026/11/03 15:11 |
action |
codesearch-prepare |
0m
Results: map[Index:codesearch-index]
|
| 7/1 |
2026/11/03 15:11 |
agent |
debugger |
26m
Model:
Instruction:
You are an experienced Linux kernel developer tasked with debugging a kernel crash root cause.
You need to provide a detailed explanation of the root cause for another developer to be
able to write a fix for the bug based on your explanation. Include all relevant details
into the response: function/struct/field/etc names, code snippets, line numbers,
macro/enum values, etc.
Don't make assumptions about the kernel source code (it may be different from what you assume it is).
Extensively use the provided code access tools (codesearch-*, git-*, grepper, etc)
to examine the actual source code, and confirm any assumptions.
Prefer calling several tools at the same time to save round-trips.
Prompt:
The crash is:
device-mapper: ioctl: device has been removed from the dev hash table.
================================================
WARNING: lock held when returning to user space!
syzkaller #1 Not tainted
------------------------------------------------
syz.3.1525/11804 is leaving the kernel with locks still held!
locks held by syz.3.1525/11804: 1, last CPU#0:
#0: ffff88805abdd468 (&q->q_usage_counter(queue)#52){+.+.}-{0:0}, at: blk_mq_freeze_queue include/linux/blk-mq.h:959 [inline]
#0: ffff88805abdd468 (&q->q_usage_counter(queue)#52){+.+.}-{0:0}, at: elevator_change+0x194/0x480 block/elevator.c:668
The following C code is a draft of the vulnerable syscall sequence. Keep in mind that
it may lack the precise threading, sandboxing, and some arguments of a working reproducer:
// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <endian.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
uint64_t r[3] = {0xffffffffffffffff, 0xffffffffffffffff, 0x0};
int main(void)
{
syscall(__NR_mmap, /*addr=*/0x1ffffffff000ul, /*len=*/0x1000, /*prot=*/0ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
syscall(__NR_mmap, /*addr=*/0x200000000000ul, /*len=*/0x1000000, /*prot=PROT_WRITE|PROT_READ|PROT_EXEC*/7ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
syscall(__NR_mmap, /*addr=*/0x200001000000ul, /*len=*/0x1000, /*prot=*/0ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
const char* reason;
(void)reason;
intptr_t res = 0;
if (write(1, "executing program\n", sizeof("executing program\n") - 1)) {}
// openat$dm_control arguments: [
// fd: const = 0xffffffffffffff9c (8 bytes)
// file: ptr[in, buffer] {
// buffer: {2f 64 65 76 2f 6d 61 70 70 65 72 2f 63 6f 6e 74 72 6f 6c 00} (length 0x14)
// }
// flags: open_flags = 0x2 (4 bytes)
// mode: const = 0x0 (2 bytes)
// ]
// returns fd_dm_ctl
memcpy((void*)0x2000000009c0, "/dev/mapper/control\000", 20);
res = syscall(__NR_openat, /*fd=*/0xffffffffffffff9cul, /*file=*/0x2000000009c0ul, /*flags=O_RDWR*/2, /*mode=*/0);
if (res != -1)
r[0] = res;
// openat$dm_control arguments: [
// fd: const = 0xffffffffffffff9c (8 bytes)
// file: ptr[in, buffer] {
// buffer: {2f 64 65 76 2f 6d 61 70 70 65 72 2f 63 6f 6e 74 72 6f 6c 00} (length 0x14)
// }
// flags: open_flags = 0x2 (4 bytes)
// mode: const = 0x0 (2 bytes)
// ]
// returns fd_dm_ctl
memcpy((void*)0x200000000200, "/dev/mapper/control\000", 20);
res = syscall(__NR_openat, /*fd=*/0xffffffffffffff9cul, /*file=*/0x200000000200ul, /*flags=O_RDWR*/2, /*mode=*/0);
if (res != -1)
r[1] = res;
// ioctl$DM_DEV_CREATE arguments: [
// fd: fd_dm_ctl (resource)
// cmd: const = 0xc138fd03 (4 bytes)
// arg: ptr[inout, dm_ioctl_t[dm_id_create, void, const[0, int32], const[0, int32]]] {
// dm_ioctl_t[dm_id_create, void, const[0, int32], const[0, int32]] {
// version_major: const = 0x4 (4 bytes)
// version_minor: const = 0x0 (4 bytes)
// version_patch: const = 0x0 (4 bytes)
// data_size: bytesize = 0x138 (4 bytes)
// data_start: offsetof = 0x138 (4 bytes)
// target_count: const = 0x0 (4 bytes)
// open_count: const = 0x0 (4 bytes)
// flags: dm_ioctl_flags = 0xc01 (4 bytes)
// event_nr: const = 0x0 (4 bytes)
// padding: const = 0x0 (4 bytes)
// id: dm_id_create {
// dev: dm_dev_number (resource)
// name: dm_dev_name {
// prefix: buffer: {73 79 7a} (length 0x3)
// proc: proc = 0x0 (1 bytes)
// slot: buffer: {32 00} (length 0x2)
// pad = 0x0 (122 bytes)
// }
// uuid: union dm_dev_uuid_opt {
// none: const = 0x0 (1 bytes)
// }
// }
// data: buffer: {} (length 0x0)
// }
// }
// ]
*(uint32_t*)0x200000000240 = 4;
*(uint32_t*)0x200000000244 = 0;
*(uint32_t*)0x200000000248 = 0;
*(uint32_t*)0x20000000024c = 0x138;
*(uint32_t*)0x200000000250 = 0x138;
*(uint32_t*)0x200000000254 = 0;
*(uint32_t*)0x200000000258 = 0;
*(uint32_t*)0x20000000025c = 0xc01;
*(uint32_t*)0x200000000260 = 0;
*(uint32_t*)0x200000000264 = 0;
memcpy((void*)0x200000000270, "syz", 3);
*(uint8_t*)0x200000000273 = 0x61;
memcpy((void*)0x200000000274, "2\000", 2);
*(uint8_t*)0x2000000002f0 = 0;
res = syscall(__NR_ioctl, /*fd=*/r[1], /*cmd=*/0xc138fd03, /*arg=*/0x200000000240ul);
if (res != -1)
r[2] = *(uint64_t*)0x200000000268;
// ioctl$DM_TABLE_LOAD arguments: [
// fd: fd_dm_ctl (resource)
// cmd: const = 0xc138fd09 (4 bytes)
// arg: ptr[inout, dm_ioctl_t[dm_id_lookup, array[dm_target, 1], len[data, int32], const[0, int32]]] {
// dm_ioctl_t[dm_id_lookup, array[dm_target, 1], len[data, int32], const[0, int32]] {
// version_major: const = 0x4 (4 bytes)
// version_minor: const = 0x32 (4 bytes)
// version_patch: const = 0x0 (4 bytes)
// data_size: bytesize = 0x1b0 (4 bytes)
// data_start: offsetof = 0x138 (4 bytes)
// target_count: len = 0x1 (4 bytes)
// open_count: const = 0x0 (4 bytes)
// flags: dm_ioctl_flags = 0x24400 (4 bytes)
// event_nr: const = 0x0 (4 bytes)
// padding: const = 0x0 (4 bytes)
// id: union dm_id_lookup {
// by_dev: dm_id_by_dev {
// dev: dm_dev_number (resource)
// pad = 0x0 (264 bytes)
// }
// }
// data: array[dm_target] {
// union dm_target {
// multipath: dm_target_spec_t[dm_target_multipath, dm_multipath_params] {
// sector_start: const = 0x0 (8 bytes)
// length: dm_lengths = 0x54d0 (8 bytes)
// status: const = 0x0 (4 bytes)
// next: bytesize = 0x78 (4 bytes)
// target_type: buffer: {6d 75 6c 74 69 70 61 74 68 00 00 00 00 00 00 00} (length 0x10)
// params: dm_multipath_params {
// feat: buffer: {31 20 72 65 74 61 69 6e 5f 61 74 74 61 63 68 65 64 5f 68 77 5f 68 61 6e 64 6c 65 72} (length 0x1c)
// sp0: const = 0x20 (1 bytes)
// hwh: buffer: {31 20 72 64 61 63} (length 0x6)
// sp1: const = 0x20 (1 bytes)
// ngrp: len = 0x0 (20 bytes)
// sp2: const = 0x20 (1 bytes)
// init: int8 = 0x0 (20 bytes)
// groups: array[dm_mpath_group] {
// }
// }
// z: const = 0x0 (1 bytes)
// }
// }
// }
// }
// }
// ]
*(uint32_t*)0x200000000380 = 4;
*(uint32_t*)0x200000000384 = 0x32;
*(uint32_t*)0x200000000388 = 0;
*(uint32_t*)0x20000000038c = 0x1b0;
*(uint32_t*)0x200000000390 = 0x138;
*(uint32_t*)0x200000000394 = 1;
*(uint32_t*)0x200000000398 = 0;
*(uint32_t*)0x20000000039c = 0x24400;
*(uint32_t*)0x2000000003a0 = 0;
*(uint32_t*)0x2000000003a4 = 0;
*(uint64_t*)0x2000000003a8 = r[2];
*(uint64_t*)0x2000000004b8 = 0;
*(uint64_t*)0x2000000004c0 = 0x54d0;
*(uint32_t*)0x2000000004c8 = 0;
*(uint32_t*)0x2000000004cc = 0x78;
memcpy((void*)0x2000000004d0, "multipath\000\000\000\000\000\000\000", 16);
memcpy((void*)0x2000000004e0, "1 retain_attached_hw_handler", 28);
*(uint8_t*)0x2000000004fc = 0x20;
memcpy((void*)0x2000000004fd, "1 rdac", 6);
*(uint8_t*)0x200000000503 = 0x20;
sprintf((char*)0x200000000504, "%020llu", (long long)0);
*(uint8_t*)0x200000000518 = 0x20;
sprintf((char*)0x200000000519, "%020llu", (long long)0);
*(uint8_t*)0x20000000052d = 0;
syscall(__NR_ioctl, /*fd=*/r[1], /*cmd=*/0xc138fd09, /*arg=*/0x200000000380ul);
// ioctl$DM_DEV_REMOVE arguments: [
// fd: fd_dm_ctl (resource)
// cmd: const = 0xc138fd04 (4 bytes)
// arg: ptr[inout, dm_ioctl_t[dm_id_lookup, void, const[0, int32], const[0, int32]]] {
// dm_ioctl_t[dm_id_lookup, void, const[0, int32], const[0, int32]] {
// version_major: const = 0x4 (4 bytes)
// version_minor: const = 0x0 (4 bytes)
// version_patch: const = 0x0 (4 bytes)
// data_size: bytesize = 0x138 (4 bytes)
// data_start: offsetof = 0x138 (4 bytes)
// target_count: const = 0x0 (4 bytes)
// open_count: const = 0x0 (4 bytes)
// flags: dm_ioctl_flags = 0x9a4ee504b98d1bf2 (4 bytes)
// event_nr: const = 0x0 (4 bytes)
// padding: const = 0x0 (4 bytes)
// id: union dm_id_lookup {
// by_dev: dm_id_by_dev {
// dev: dm_dev_number (resource)
// pad = 0x0 (264 bytes)
// }
// }
// data: buffer: {} (length 0x0)
// }
// }
// ]
*(uint32_t*)0x200000000540 = 4;
*(uint32_t*)0x200000000544 = 0;
*(uint32_t*)0x200000000548 = 0;
*(uint32_t*)0x20000000054c = 0x138;
*(uint32_t*)0x200000000550 = 0x138;
*(uint32_t*)0x200000000554 = 0;
*(uint32_t*)0x200000000558 = 0;
*(uint32_t*)0x20000000055c = 0xb98d1bf2;
*(uint32_t*)0x200000000560 = 0;
*(uint32_t*)0x200000000564 = 0;
*(uint64_t*)0x200000000568 = r[2];
syscall(__NR_ioctl, /*fd=*/r[0], /*cmd=*/0xc138fd04, /*arg=*/0x200000000540ul);
return 0;
}
Reply: ### Root Cause Analysis
#### Summary
The `WARNING: lock held when returning to user space!` for `&q->q_usage_counter(queue)` (which is the lockdep map `q->q_lockdep_map` acquired at `elevator_change+0x194/0x480`, `block/elevator.c:668`) is caused by a race condition between:
1. **`DM_TABLE_LOAD` (`table_load`)** initializing and registering the request-based DM queue/gendisk (`dm_setup_md_queue()` -> `add_disk()` -> `blk_register_queue()` -> `elevator_set_default()` -> `elevator_change()`), and
2. **`DM_DEV_REMOVE` (`dev_remove`)** concurrently destroying the same DM device (`dm_destroy()` -> `__dm_destroy()` -> `blk_mark_disk_dead()`), which marks the queue dying and starts draining/freezing the queue.
Specifically, in the block layer's queue-freeze lockdep tracking (`block/blk-mq.c` and `block/blk.h`), the flags `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead` are stored as per-`request_queue` fields protected by `q->mq_freeze_lock` when `q->mq_freeze_depth == 0`, **but `blk_unfreeze_release_lock(q)` reads them outside `q->mq_freeze_lock` after `q->mq_freeze_depth` has already been decremented to `0`**. When `blk_mark_disk_dead()` races with `blk_mq_unfreeze_queue()`, `q->mq_freeze_queue_dying` is overwritten from `false` to `true` before `blk_unfreeze_release_lock(q)` runs, causing `blk_unfreeze_release_lock(q)` to skip releasing `q->q_lockdep_map`.
---
#### Detailed Mechanism
##### 1. Lockdep modeling of `blk_mq_freeze_queue()` / `blk_mq_unfreeze_queue()`
In `block/blk-core.c:500`, `q->q_lockdep_map` is initialized with the name `"&q->q_usage_counter(queue)"`:
```c
lockdep_init_map(&q->q_lockdep_map, "&q->q_usage_counter(queue)",
&q->q_lock_cls_key, 0);
```
In `block/blk-mq.c`, when a task freezes a queue via `blk_mq_freeze_queue(q)` -> `blk_freeze_queue_start(q)`:
```c
static bool blk_freeze_set_owner(struct request_queue *q,
struct task_struct *owner)
{
if (!owner)
return false;
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
q->mq_freeze_disk_dead = !q->disk ||
test_bit(GD_DEAD, &q->disk->state) ||
!blk_queue_registered(q);
q->mq_freeze_queue_dying = blk_queue_dying(q);
return true;
}
if (owner == q->mq_freeze_owner)
q->mq_freeze_owner_depth += 1;
return false;
}
```
```c
bool __blk_freeze_queue_start(struct request_queue *q,
struct task_struct *owner)
{
bool freeze;
mutex_lock(&q->mq_freeze_lock);
freeze = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
if (queue_is_mq(q))
blk_mq_run_hw_queues(q, false);
} else {
mutex_unlock(&q->mq_freeze_lock);
}
return freeze;
}
void blk_freeze_queue_start(struct request_queue *q)
{
if (__blk_freeze_queue_start(q, current))
blk_freeze_acquire_lock(q);
}
```
And in `block/blk.h:715-728`:
```c
static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
if (!q->mq_freeze_queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
```
When the owner task unfreezes the queue via `blk_mq_unfreeze_queue(q, memflags)` -> `blk_mq_unfreeze_queue_nomemrestore(q)` (`block/blk-mq.c:211-235`):
```c
bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
bool unfreeze;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
q->q_usage_counter.data->force_atomic = true;
q->mq_freeze_depth--;
WARN_ON_ONCE(q->mq_freeze_depth < 0);
if (!q->mq_freeze_depth) {
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
}
unfreeze = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
return unfreeze;
}
void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
{
if (__blk_mq_unfreeze_queue(q, false))
blk_unfreeze_release_lock(q);
}
```
Notice the bug here:
1. Inside `__blk_mq_unfreeze_queue()`, `q->mq_freeze_depth` is decremented to `0` and `q->mq_freeze_owner` is cleared to `NULL`, and then `mutex_unlock(&q->mq_freeze_lock)` is called.
2. Only **after** `q->mq_freeze_lock` is released does `blk_mq_unfreeze_queue_nomemrestore()` call `blk_unfreeze_release_lock(q)`, which inspects `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead`.
3. Because `q->mq_freeze_depth` is already `0` and `q->mq_freeze_lock` is unlocked, another thread calling `__blk_freeze_queue_start()` can immediately acquire `q->mq_freeze_lock`, see `!q->mq_freeze_depth`, and overwrite `q->mq_freeze_queue_dying` (and `q->mq_freeze_disk_dead`) in `blk_freeze_set_owner()`.
##### 2. How Device Mapper triggers this race
In the reproducer:
1. `ioctl(DM_DEV_CREATE)` creates a DM device `md` (`md->type == DM_TYPE_NONE`, with `md->disk` allocated via `blk_alloc_disk()`).
2. **Thread 1 (`syz.3.1525/11804`)** calls `ioctl(DM_TABLE_LOAD)` (`table_load()` in `drivers/md/dm-ioctl.c:1622`) with a request-based `"multipath"` target:
- `find_device(param)` looks up `md` under `_hash_lock`, increments `md->holders` (`dm_get(md)`), and drops `_hash_lock`.
- `populate_table()` parses the `"multipath"` target, setting the table type to `DM_TYPE_REQUEST_BASED`.
- Since `dm_get_md_type(md) == DM_TYPE_NONE`, `table_load()` calls `dm_setup_md_queue(md, t)` (`drivers/md/dm.c:2606`):
- `dm_mq_init_request_queue(md, t)` initializes `md->queue` as a `blk-mq` queue.
- `add_disk(md->disk)` -> `device_add_disk()` -> `add_disk_fwnode()` -> `__add_disk()` -> `blk_register_queue(md->disk)` (`block/blk-sysfs.c:991`):
```c
if (queue_is_mq(q))
elevator_set_default(q);
```
- `elevator_set_default(q)` calls `elevator_change(q, &ctx)` (`block/elevator.c:653`).
3. Concurrently, **Thread 2** calls `ioctl(DM_DEV_REMOVE)` (`dev_remove()` in `drivers/md/dm-ioctl.c:1063`):
- Under `_hash_lock`, `dm_lock_for_deletion(md, ...)` succeeds because it only checks `dm_open_count(md)` (`0`), **not** `md->holders`.
- `__hash_remove(hc)` removes `hc` from the hash table and clears `md->interface_ptr` (`dm_set_mdptr(md, NULL)`).
- `dev_remove()` drops `_hash_lock`, calls `dm_put(md)`, and calls `dm_destroy(md)` -> `__dm_destroy(md, true)` (`drivers/md/dm.c:2726`):
```c
blk_mark_disk_dead(md->disk);
...
if (wait)
while (atomic_read(&md->holders))
fsleep(1000);
```
- Notice that `__dm_destroy()` calls `blk_mark_disk_dead(md->disk)` **before** waiting for `md->holders` to drop to `0`.
##### 3. Exact Race Sequence
1. **Thread 1 (`table_load`)** enters `elevator_change()` (`block/elevator.c:668`):
```c
memflags = blk_mq_freeze_queue(q);
```
- `q->mq_freeze_depth` is `0`.
- `blk_freeze_set_owner(q, Thread_1)` sets:
- `q->mq_freeze_owner = Thread_1`
- `q->mq_freeze_owner_depth = 1`
- `q->mq_freeze_disk_dead = true` (since `QUEUE_FLAG_REGISTERED` is not set yet)
- `q->mq_freeze_queue_dying = false` (since `QUEUE_FLAG_DYING` is not set yet)
- `q->mq_freeze_depth` becomes `1`.
- `blk_freeze_acquire_lock(q)` sees `!q->mq_freeze_queue_dying == true` and calls:
```c
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
```
2. **Thread 1 (`table_load`)** finishes `elevator_switch()` and calls `blk_mq_unfreeze_queue(q, memflags)` at `block/elevator.c:683`:
- Inside `__blk_mq_unfreeze_queue(q, false)` (`block/blk-mq.c:211`):
- `q->mq_freeze_depth` is decremented from `1` to `0`.
- `blk_unfreeze_check_owner(q)` decrements `q->mq_freeze_owner_depth` to `0`, sets `q->mq_freeze_owner = NULL`, and returns `true`.
- `mutex_unlock(&q->mq_freeze_lock)` unlocks `q->mq_freeze_lock`.
3. **Thread 2 (`dev_remove`)** executes `blk_mark_disk_dead(md->disk)` (`block/genhd.c:689`):
```c
void blk_mark_disk_dead(struct gendisk *disk)
{
blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
__blk_mark_disk_dead(disk);
blk_report_disk_dead(disk, true);
}
```
- `blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue)` sets `QUEUE_FLAG_DYING` on `q`.
- `__blk_mark_disk_dead(disk)` calls `blk_queue_start_drain(disk->queue)` -> `__blk_freeze_queue_start(q, Thread_2)`.
- Right after Thread 1 unlocks `q->mq_freeze_lock` in step 2 (e.g., when woken from `q->mq_freeze_lock` wait_list during `mutex_unlock`), Thread 2 acquires `q->mq_freeze_lock`.
- Because `q->mq_freeze_depth` is `0`, `blk_freeze_set_owner(q, Thread_2)` runs and sets:
```c
q->mq_freeze_queue_dying = blk_queue_dying(q); /* true! */
```
4. **Thread 1 (`table_load`)** now executes `blk_unfreeze_release_lock(q)` (`block/blk-mq.c:233` -> `block/blk.h:722`):
```c
static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
```
Because `q->mq_freeze_queue_dying` was overwritten with `true` by Thread 2 in step 3, `!q->mq_freeze_queue_dying` evaluates to `false`, and **`rwsem_release(&q->q_lockdep_map, _RET_IP_)` is skipped**.
5. **Thread 1 (`table_load`)** finishes `dm_setup_md_queue()`, acquires `_hash_lock` in `table_load()` (`drivers/md/dm-ioctl.c:1678`), sees `hc = dm_get_mdptr(md)` is `NULL`, logs:
```
device-mapper: ioctl: device has been removed from the dev hash table.
```
cleans up `t`, drops `md->holders` (`dm_put(md)`), and returns `-ENXIO` to user space with `q->q_lockdep_map` (`&q->q_usage_counter(queue)`) still held in lockdep, triggering the warning.
---
#### How to Fix
1. **In the block layer (`block/blk-mq.c`, `block/blk.h`, `block/genhd.c`)**:
`blk_freeze_acquire_lock(q)` and `blk_unfreeze_release_lock(q)` must not read mutable per-queue `q->mq_freeze_queue_dying` / `q->mq_freeze_disk_dead` fields outside `q->mq_freeze_lock` after `q->mq_freeze_depth` has dropped to `0` (where another task starting a new freeze can overwrite them). Either:
- Perform the lockdep release (`blk_unfreeze_release_lock(q)`) / state consumption under `q->mq_freeze_lock` before `q->mq_freeze_depth` is decremented / unlocked (or pass the saved `disk_dead` and `queue_dying` booleans out of `__blk_mq_unfreeze_queue()` by value while still holding `q->mq_freeze_lock`), and similarly pass/snapshot them under `q->mq_freeze_lock` in `__blk_freeze_queue_start()`.
2. **In Device Mapper (`drivers/md/dm.c`)**:
In `__dm_destroy()`, `blk_mark_disk_dead(md->disk)` should not be called while another thread holds `md->holders` and may still be in `dm_setup_md_queue()` / `add_disk(md->disk)` initializing and registering the disk/queue (i.e., wait for `atomic_read(&md->holders)` or serialize against `md->type_lock` before marking the disk dead).
|
| 8/2 |
2026/11/03 15:11 |
llm |
debugger |
0m
Model:
Tokens:
input: 8403
output: 96
thoughts: 395
Thoughts: **Analyzing a Device Mapper Crash**
Okay, let's dive into this crash report and the reproducer. The error message, "device-mapper: ioctl: device has been removed from the dev hash table," immediately grabs my attention. It's coupled with a lock held warning, "WARNING: lock held when returning to user space!" which is never a good sign, especially when dealing with the kernel's block layer. The crash occurs in `syz.3.1525/11804`, and it seems like the process is exiting the kernel with a lock held on the queue usage counter within the block layer, specifically at the `elevator_change` function.
Looking at the reproducer, we see a pretty standard sequence: a device mapper device is created using `ioctl$DM_DEV_CREATE`, then a table is loaded with a `multipath` target via `ioctl$DM_TABLE_LOAD`, and finally, the device is removed with `ioctl$DM_DEV_REMOVE`. The timing here is probably key. The critical message, "device has been removed from the dev hash table," precedes the warning, suggesting something is going wrong during the removal process.
My immediate next step is to examine the source code. I need to understand what's happening within `elevator_change` in `block/elevator.c`. I'll also need to investigate the device-mapper's ioctl handling in `drivers/md/` to see exactly what operations are taking place during device creation, table loading, and removal. I'll need to locate where that "device has been removed..." message is printed to understand how that removal is happening. I'll reach for `codesearch-definition-source`, `grepper`, and probably `read-file` to get a handle on all of the involved sources. The goal is to pinpoint the exact code path where the lock is being held and why the device is being removed at the wrong time, leading to this conflict.
|
| 9/2 |
2026/11/03 15:11 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/elevator.c Name:elevator_change]
Results: map[SourceCode: 650: /*
651: * Switch this queue to the given IO scheduler.
652: */
653: static int elevator_change(struct request_queue *q, struct elv_change_ctx *ctx)
654: {
655: unsigned int memflags;
656: struct blk_mq_tag_set *set = q->tag_set;
657: int ret = 0;
658:
659: lockdep_assert_held(&set->update_nr_hwq_lock);
660:
661: if (strncmp(ctx->name, "none", 4)) {
662: ret = blk_mq_alloc_sched_res(q, ctx->type, &ctx->res,
663: set->nr_hw_queues);
664: if (ret)
665: return ret;
666: }
667:
668: memflags = blk_mq_freeze_queue(q);
669: /*
670: * May be called before adding disk, when there isn't any FS I/O,
671: * so freezing queue plus canceling dispatch work is enough to
672: * drain any dispatch activities originated from passthrough
673: * requests, then no need to quiesce queue which may add long boot
674: * latency, especially when lots of disks are involved.
675: *
676: * Disk isn't added yet, so verifying queue lock only manually.
677: */
678: blk_mq_cancel_work_sync(q);
679: mutex_lock(&q->elevator_lock);
680: if (!(q->elevator && elevator_match(q->elevator->type, ctx->name)))
681: ret = elevator_switch(q, ctx);
682: mutex_unlock(&q->elevator_lock);
683: blk_mq_unfreeze_queue(q, memflags);
684: if (!ret)
685: ret = elevator_change_done(q, ctx);
686:
687: /*
688: * Free sched resource if it's allocated but we couldn't switch elevator.
689: */
690: if (!ctx->new)
691: blk_mq_free_sched_res(&ctx->res, ctx->type, set);
692:
693: return ret;
694: }
SourceFile:block/elevator.c]
|
| 10/2 |
2026/11/03 15:11 |
tool |
grepper |
0m
Args: map[Expression:device has been removed from the dev hash table PathPrefixes:[drivers/md/]]
Results: map[Output:drivers/md/dm-ioctl.c=875=static struct dm_table *dm_get_inactive_table(struct mapped_device *md, int *srcu_idx)
--
drivers/md/dm-ioctl.c-885- if (!hc) {
drivers/md/dm-ioctl.c:886: DMERR("device has been removed from the dev hash table.");
drivers/md/dm-ioctl.c-887- goto out;
--
drivers/md/dm-ioctl.c=1626=static int table_load(struct file *filp, struct dm_ioctl *param, size_t param_size)
--
drivers/md/dm-ioctl.c-1679- if (!hc) {
drivers/md/dm-ioctl.c:1680: DMERR("device has been removed from the dev hash table.");
drivers/md/dm-ioctl.c-1681- up_write(&_hash_lock);
]
|
| 11/2 |
2026/11/03 15:11 |
tool |
codesearch-find-references |
0m
Args: map[Name:elevator_change]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:elevator_set_default SourceFile:block/elevator.c SourceLine:754] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:elevator_set_none SourceFile:block/elevator.c SourceLine:769] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:elv_iosched_store SourceFile:block/elevator.c SourceLine:826]] TruncatedOutput:false]
|
| 12/2 |
2026/11/03 15:11 |
llm |
debugger |
0m
Model:
Tokens:
input: 10033
output: 152
thoughts: 204
Thoughts: Okay, here's my breakdown of what's going through my mind as I analyze this:
**Investigating a Potential Block Layer Concurrency Issue**
Alright, the code's pointed me towards `elevator_change` in `block/elevator.c`. Immediately, I'm zeroing in on lines 668 and 683, the freezing and unfreezing of the block queue `q` using `blk_mq_freeze_queue` and `blk_mq_unfreeze_queue`. The concern is, *why* is `q->q_usage_counter` still being held after `elevator_change` completes? That shouldn't be happening. We're supposed to be in a consistent state post freeze/unfreeze cycle.
My next step is to look at how `elevator_change`, and related functions like `elevator_set_default`, `elevator_set_none`, `blk_mq_freeze_queue`, `blk_mq_unfreeze_queue`, and functions that might call these functions such as `table_load` and `dev_remove`, handle this usage counter. I need to understand how these functions interact and if the usage counter is properly accounted for. I'm thinking of where the queue is touched by these functions.
To get a handle on this, I'm going to deeply read the `block/elevator.c` file, specifically around that 650-850 line range to see the surrounding context. Also, since there are mentions of `table_load` and `dev_remove`, I need to cross-reference with related files. `drivers/md/dm-ioctl.c` will likely be important for those functions. Finally, I'll review `drivers/md/dm.c` for some context as well. I'm looking for where the queue is touched, where locking is happening, and if usage counts are incremented and decremented properly.
|
| 13/2 |
2026/11/03 15:11 |
tool |
read-file |
0m
Args: map[File:block/elevator.c FirstLine:600 LineCount:100]
Results: map[Contents: 600: pr_warn("elv: switch to \"%s\" failed, falling back to \"none\"\n",
601: new_e->elevator_name);
602: }
603:
604: if (new_e)
605: elevator_put(new_e);
606: return ret;
607: }
608:
609: static void elv_exit_and_release(struct elv_change_ctx *ctx,
610: struct request_queue *q)
611: {
612: struct elevator_queue *e;
613: unsigned memflags;
614:
615: memflags = blk_mq_freeze_queue(q);
616: mutex_lock(&q->elevator_lock);
617: e = q->elevator;
618: elevator_exit(q);
619: mutex_unlock(&q->elevator_lock);
620: blk_mq_unfreeze_queue(q, memflags);
621: if (e) {
622: blk_mq_free_sched_res(&ctx->res, ctx->type, q->tag_set);
623: kobject_put(&e->kobj);
624: }
625: }
626:
627: static int elevator_change_done(struct request_queue *q,
628: struct elv_change_ctx *ctx)
629: {
630: int ret = 0;
631:
632: if (ctx->old) {
633: struct elevator_resources res = {
634: .et = ctx->old->et,
635: .data = ctx->old->elevator_data
636: };
637:
638: elv_unregister_queue(q, ctx->old);
639: blk_mq_free_sched_res(&res, ctx->old->type, q->tag_set);
640: kobject_put(&ctx->old->kobj);
641: }
642: if (ctx->new) {
643: ret = elv_register_queue(q, ctx->new, !ctx->no_uevent);
644: if (ret)
645: elv_exit_and_release(ctx, q);
646: }
647: return ret;
648: }
649:
650: /*
651: * Switch this queue to the given IO scheduler.
652: */
653: static int elevator_change(struct request_queue *q, struct elv_change_ctx *ctx)
654: {
655: unsigned int memflags;
656: struct blk_mq_tag_set *set = q->tag_set;
657: int ret = 0;
658:
659: lockdep_assert_held(&set->update_nr_hwq_lock);
660:
661: if (strncmp(ctx->name, "none", 4)) {
662: ret = blk_mq_alloc_sched_res(q, ctx->type, &ctx->res,
663: set->nr_hw_queues);
664: if (ret)
665: return ret;
666: }
667:
668: memflags = blk_mq_freeze_queue(q);
669: /*
670: * May be called before adding disk, when there isn't any FS I/O,
671: * so freezing queue plus canceling dispatch work is enough to
672: * drain any dispatch activities originated from passthrough
673: * requests, then no need to quiesce queue which may add long boot
674: * latency, especially when lots of disks are involved.
675: *
676: * Disk isn't added yet, so verifying queue lock only manually.
677: */
678: blk_mq_cancel_work_sync(q);
679: mutex_lock(&q->elevator_lock);
680: if (!(q->elevator && elevator_match(q->elevator->type, ctx->name)))
681: ret = elevator_switch(q, ctx);
682: mutex_unlock(&q->elevator_lock);
683: blk_mq_unfreeze_queue(q, memflags);
684: if (!ret)
685: ret = elevator_change_done(q, ctx);
686:
687: /*
688: * Free sched resource if it's allocated but we couldn't switch elevator.
689: */
690: if (!ctx->new)
691: blk_mq_free_sched_res(&ctx->res, ctx->type, set);
692:
693: return ret;
694: }
695:
696: /*
697: * The I/O scheduler depends on the number of hardware queues, this forces a
698: * reattachment when nr_hw_queues changes.
699: */
]
|
| 14/2 |
2026/11/03 15:11 |
tool |
read-file |
0m
Args: map[File:block/elevator.c FirstLine:700 LineCount:100]
Results: map[Contents: 700: void elv_update_nr_hw_queues(struct request_queue *q,
701: struct elv_change_ctx *ctx)
702: {
703: struct blk_mq_tag_set *set = q->tag_set;
704: int ret = -ENODEV;
705:
706: WARN_ON_ONCE(q->mq_freeze_depth == 0);
707:
708: if (ctx->type && !blk_queue_dying(q) && blk_queue_registered(q)) {
709: mutex_lock(&q->elevator_lock);
710: /* force to reattach elevator after nr_hw_queue is updated */
711: ret = elevator_switch(q, ctx);
712: mutex_unlock(&q->elevator_lock);
713: }
714: blk_mq_unfreeze_queue_nomemrestore(q);
715: if (!ret)
716: WARN_ON_ONCE(elevator_change_done(q, ctx));
717:
718: /*
719: * Free sched resource if it's allocated but we couldn't switch elevator.
720: */
721: if (!ctx->new)
722: blk_mq_free_sched_res(&ctx->res, ctx->type, set);
723: }
724:
725: /*
726: * Use the default elevator settings. If the chosen elevator initialization
727: * fails, fall back to the "none" elevator (no elevator).
728: */
729: void elevator_set_default(struct request_queue *q)
730: {
731: struct elv_change_ctx ctx = {
732: .name = "mq-deadline",
733: .no_uevent = true,
734: };
735: int err;
736:
737: /* now we allow to switch elevator */
738: blk_queue_flag_clear(QUEUE_FLAG_NO_ELV_SWITCH, q);
739:
740: if (q->tag_set->flags & BLK_MQ_F_NO_SCHED_BY_DEFAULT)
741: return;
742:
743: /*
744: * For single queue devices, default to using mq-deadline. If we
745: * have multiple queues or mq-deadline is not available, default
746: * to "none".
747: */
748: ctx.type = elevator_find_get(ctx.name);
749: if (!ctx.type)
750: return;
751:
752: if ((q->nr_hw_queues == 1 ||
753: blk_mq_is_shared_tags(q->tag_set->flags))) {
754: err = elevator_change(q, &ctx);
755: if (err < 0)
756: pr_warn("\"%s\" elevator initialization, failed %d, falling back to \"none\"\n",
757: ctx.name, err);
758: }
759: elevator_put(ctx.type);
760: }
761:
762: void elevator_set_none(struct request_queue *q)
763: {
764: struct elv_change_ctx ctx = {
765: .name = "none",
766: };
767: int err;
768:
769: err = elevator_change(q, &ctx);
770: if (err < 0)
771: pr_warn("%s: set none elevator failed %d\n", __func__, err);
772: }
773:
774: static void elv_iosched_load_module(const char *elevator_name)
775: {
776: struct elevator_type *found;
777:
778: spin_lock(&elv_list_lock);
779: found = __elevator_find(elevator_name);
780: spin_unlock(&elv_list_lock);
781:
782: if (!found)
783: request_module("%s-iosched", elevator_name);
784: }
785:
786: ssize_t elv_iosched_store(struct gendisk *disk, const char *buf,
787: size_t count)
788: {
789: char elevator_name[ELV_NAME_MAX];
790: struct elv_change_ctx ctx = {};
791: int ret;
792: struct request_queue *q = disk->queue;
793: struct blk_mq_tag_set *set = q->tag_set;
794:
795: /* Make sure queue is not in the middle of being removed */
796: if (!blk_queue_registered(q))
797: return -ENOENT;
798:
799: /*
]
|
| 15/2 |
2026/11/03 15:11 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/md/dm-ioctl.c Name:table_load]
Results: map[SourceCode:1626: static int table_load(struct file *filp, struct dm_ioctl *param, size_t param_size)
1627: {
1628: int r, srcu_idx;
1629: struct hash_cell *hc;
1630: struct dm_table *t, *old_map = NULL;
1631: struct mapped_device *md;
1632: struct target_type *immutable_target_type;
1633: struct dm_ima_context *ima_context = NULL;
1634:
1635: md = find_device(param);
1636: if (!md)
1637: return -ENXIO;
1638:
1639: r = dm_table_create(&t, get_mode(param), param->target_count, md);
1640: if (r)
1641: goto err;
1642:
1643: /* Protect md->type and md->queue against concurrent table loads. */
1644: dm_lock_md_type(md);
1645: r = populate_table(t, param, param_size);
1646: if (r)
1647: goto err_unlock_md_type;
1648:
1649: immutable_target_type = dm_get_immutable_target_type(md);
1650: if (immutable_target_type &&
1651: (immutable_target_type != dm_table_get_immutable_target_type(t)) &&
1652: !dm_table_get_wildcard_target(t)) {
1653: DMERR("can't replace immutable target type %s",
1654: immutable_target_type->name);
1655: r = -EINVAL;
1656: goto err_unlock_md_type;
1657: }
1658:
1659: if (dm_get_md_type(md) == DM_TYPE_NONE) {
1660: /* setup md->queue to reflect md's type (may block) */
1661: r = dm_setup_md_queue(md, t);
1662: if (r) {
1663: DMERR("unable to set up device queue for new table.");
1664: goto err_unlock_md_type;
1665: }
1666: } else if (!is_valid_type(dm_get_md_type(md), dm_table_get_type(t))) {
1667: DMERR("can't change device type (old=%u vs new=%u) after initial table load.",
1668: dm_get_md_type(md), dm_table_get_type(t));
1669: r = -EINVAL;
1670: goto err_unlock_md_type;
1671: }
1672:
1673: dm_unlock_md_type(md);
1674:
1675: dm_ima_alloc_context(&ima_context, false);
1676: /* stage inactive table */
1677: down_write(&_hash_lock);
1678: hc = dm_get_mdptr(md);
1679: if (!hc) {
1680: DMERR("device has been removed from the dev hash table.");
1681: up_write(&_hash_lock);
1682: dm_ima_free_context(ima_context);
1683: r = -ENXIO;
1684: goto err_destroy_table;
1685: }
1686:
1687: if (hc->new_map)
1688: old_map = hc->new_map;
1689: hc->new_map = t;
1690: dm_ima_init_context(hc, ima_context, false);
1691: /* Make sure new_map doesn't get freed before we measure it*/
1692: dm_get_live_table(md, &srcu_idx);
1693: up_write(&_hash_lock);
1694:
1695: dm_ima_measure_on_table_load(t, ima_context);
1696: dm_ima_free_context(ima_context);
1697: dm_put_live_table(md, srcu_idx);
1698:
1699: param->flags |= DM_INACTIVE_PRESENT_FLAG;
1700: __dev_status(md, param);
1701:
1702: if (old_map) {
1703: dm_sync_table(md);
1704: dm_table_destroy(old_map);
1705: }
1706:
1707: dm_put(md);
1708:
1709: return 0;
1710:
1711: err_unlock_md_type:
1712: dm_unlock_md_type(md);
1713: err_destroy_table:
1714: dm_table_destroy(t);
1715: err:
1716: dm_put(md);
1717:
1718: return r;
1719: }
SourceFile:drivers/md/dm-ioctl.c]
|
| 16/2 |
2026/11/03 15:11 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/md/dm-ioctl.c Name:dev_remove]
Results: map[SourceCode:1063: static int dev_remove(struct file *filp, struct dm_ioctl *param, size_t param_size)
1064: {
1065: struct hash_cell *hc;
1066: struct mapped_device *md;
1067: int r;
1068: struct dm_table *t;
1069: struct dm_ima_context *ima_context = NULL;
1070: unsigned int ima_idx;
1071:
1072: dm_ima_alloc_context(&ima_context, true);
1073: down_write(&_hash_lock);
1074: hc = __find_device_hash_cell(param);
1075:
1076: if (!hc) {
1077: DMDEBUG_LIMIT("device doesn't appear to be in the dev hash table.");
1078: up_write(&_hash_lock);
1079: dm_ima_free_context(ima_context);
1080: return -ENXIO;
1081: }
1082:
1083: md = hc->md;
1084:
1085: /*
1086: * Ensure the device is not open and nothing further can open it.
1087: */
1088: r = dm_lock_for_deletion(md, !!(param->flags & DM_DEFERRED_REMOVE), false);
1089: if (r) {
1090: if (r == -EBUSY && param->flags & DM_DEFERRED_REMOVE) {
1091: up_write(&_hash_lock);
1092: dm_put(md);
1093: dm_ima_free_context(ima_context);
1094: return 0;
1095: }
1096: DMDEBUG_LIMIT("unable to remove open device %s", hc->name);
1097: up_write(&_hash_lock);
1098: dm_put(md);
1099: dm_ima_free_context(ima_context);
1100: return r;
1101: }
1102:
1103: ima_idx = dm_ima_init_context(hc, ima_context, true);
1104: t = __hash_remove(hc);
1105: up_write(&_hash_lock);
1106:
1107: if (t) {
1108: dm_sync_table(md);
1109: dm_table_destroy(t);
1110: }
1111:
1112: param->flags &= ~DM_DEFERRED_REMOVE;
1113:
1114: dm_ima_measure_on_device_remove(md, false, ima_context, ima_idx);
1115: dm_ima_free_context(ima_context);
1116:
1117: if (!dm_kobject_uevent(md, KOBJ_REMOVE, param->event_nr, false))
1118: param->flags |= DM_UEVENT_GENERATED_FLAG;
1119:
1120: dm_put(md);
1121: dm_destroy(md);
1122: return 0;
1123: }
SourceFile:drivers/md/dm-ioctl.c]
|
| 17/2 |
2026/11/03 15:11 |
llm |
debugger |
0m
Model:
Tokens:
input: 15755
output: 211
thoughts: 127
Thoughts: Okay, here's my take on those functions and their implications:
**Deep Dive into Device Mapper and Block Layer Interactions**
Alright, my initial focus lands squarely on `table_load` and `dev_remove`. These are key, and I know I need to quickly determine how they interact with the device mapper framework. My mind immediately jumps to the critical supporting functions around queue management, so let's check `dm_setup_md_queue`, `dm_destroy`, `blk_mq_freeze_queue`, and `blk_mq_unfreeze_queue`. These are all red flags as potential sources of either concurrency problems or unexpected states during device removal and table updates. Of course, `del_gendisk` and `blk_unregister_queue` are on the list as integral components of the teardown process for a device mapper target.
I need to understand the complete picture, so I'll need the precise definitions, along with the calling contexts, for the functions involved, *specifically* the ones dealing with queue manipulation. I need to see the implementation details for `dm_setup_md_queue`, `dm_destroy`, `blk_mq_freeze_queue`, `blk_mq_unfreeze_queue`, `elevator_set_default`, and `elevator_set_none`. I need to fully grok how these are set up, torn down, and how they interact with each other. I'll need the call graphs to understand the control flow, because an issue here could manifest as anything from data corruption to deadlock. My goal is to determine if all the pieces of the puzzle are properly synchronized.
|
| 18/2 |
2026/11/03 15:11 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/md/dm.c Name:dm_setup_md_queue]
Results: map[SourceCode:2597: /*
2598: * Setup the DM device's queue based on md's type
2599: */
2600: int dm_setup_md_queue(struct mapped_device *md, struct dm_table *t)
2601: {
2602: enum dm_queue_mode type = dm_table_get_type(t);
2603: struct queue_limits limits;
2604: struct table_device *td;
2605: int r;
2606:
2607: WARN_ON_ONCE(type == DM_TYPE_NONE);
2608:
2609: if (type == DM_TYPE_REQUEST_BASED) {
2610: md->disk->fops = &dm_rq_blk_dops;
2611: r = dm_mq_init_request_queue(md, t);
2612: if (r) {
2613: DMERR("Cannot initialize queue for request-based dm mapped device");
2614: return r;
2615: }
2616: }
2617:
2618: r = dm_calculate_queue_limits(t, &limits);
2619: if (r) {
2620: DMERR("Cannot calculate initial queue limits");
2621: return r;
2622: }
2623: r = dm_table_set_restrictions(t, md->queue, &limits);
2624: if (r)
2625: return r;
2626:
2627: /*
2628: * Hold lock to make sure add_disk() and del_gendisk() won't concurrent
2629: * with open_table_device() and close_table_device().
2630: */
2631: mutex_lock(&md->table_devices_lock);
2632: r = add_disk(md->disk);
2633: if (r) {
2634: mutex_unlock(&md->table_devices_lock);
2635: return r;
2636: }
2637:
2638: /*
2639: * Register the holder relationship for devices added before the disk
2640: * was live.
2641: */
2642: list_for_each_entry(td, &md->table_devices, list) {
2643: r = bd_link_disk_holder(td->dm_dev.bdev, md->disk);
2644: if (r)
2645: goto out_undo_holders;
2646: }
2647: mutex_unlock(&md->table_devices_lock);
2648:
2649: r = dm_sysfs_init(md);
2650: if (r)
2651: goto lock_out_undo_holders;
2652:
2653: md->type = type;
2654:
2655: return 0;
2656:
2657: lock_out_undo_holders:
2658: mutex_lock(&md->table_devices_lock);
2659: out_undo_holders:
2660: list_for_each_entry_continue_reverse(td, &md->table_devices, list)
2661: bd_unlink_disk_holder(td->dm_dev.bdev, md->disk);
2662: del_gendisk(md->disk);
2663: mutex_unlock(&md->table_devices_lock);
2664: return r;
2665: }
SourceFile:drivers/md/dm.c]
|
| 19/2 |
2026/11/03 15:11 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/md/dm.c Name:dm_destroy]
Results: map[SourceCode:2773: void dm_destroy(struct mapped_device *md)
2774: {
2775: __dm_destroy(md, true);
2776: }
SourceFile:drivers/md/dm.c]
|
| 20/2 |
2026/11/03 15:11 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/blk-mq.c Name:blk_mq_freeze_queue]
Results: map[SourceCode: 954: static inline unsigned int __must_check
955: blk_mq_freeze_queue(struct request_queue *q)
956: {
957: unsigned int memflags = memalloc_noio_save();
958:
959: blk_mq_freeze_queue_nomemsave(q);
960: return memflags;
961: }
SourceFile:include/linux/blk-mq.h]
|
| 21/2 |
2026/11/03 15:11 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/blk-mq.c Name:blk_mq_unfreeze_queue]
Results: map[SourceCode: 962: static inline void
963: blk_mq_unfreeze_queue(struct request_queue *q, unsigned int memflags)
964: {
965: blk_mq_unfreeze_queue_nomemrestore(q);
966: memalloc_noio_restore(memflags);
967: }
SourceFile:include/linux/blk-mq.h]
|
| 22/2 |
2026/11/03 15:11 |
tool |
codesearch-find-references |
0m
Args: map[Name:elevator_set_default]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_register_queue SourceFile:block/blk-sysfs.c SourceLine:992]] TruncatedOutput:false]
|
| 23/2 |
2026/11/03 15:11 |
tool |
codesearch-find-references |
0m
Args: map[Name:elevator_set_none]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_mq_elv_switch_none SourceFile:block/blk-mq.c SourceLine:5160] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_unregister_queue SourceFile:block/blk-sysfs.c SourceLine:1073]] TruncatedOutput:false]
|
| 24/2 |
2026/11/03 15:11 |
llm |
debugger |
0m
Model:
Tokens:
input: 17686
output: 252
thoughts: 61
Thoughts: Here's my summary, as though I'm thinking through this process:
**Reviewing Key Block Layer Operations**
Okay, so I need to get a handle on the lifecycle and state management of these block queues and their interactions. Let me quickly go through the core functions that I think are going to be critical to understanding whatβs happening. I should check `__dm_destroy`, since that's likely the final cleanup function. It's crucial to understand how things are properly de-allocated to avoid resource leaks or dangling pointers. Then, I'll move on to `dm_mq_init_request_queue`, as it's the initialization, so I should be able to map how the queue is setup. I need to be sure that I am looking at the `blk-mq` setup. After initialization, I have to ensure I have a good grasp of the freeze and unfreeze capabilities. So, letβs look closely at `blk_mq_freeze_queue_nomemsave` and `blk_mq_unfreeze_queue_nomemrestore`. That'll tell me how the I/O flow is temporarily halted and resumed. These routines are critical when handling resource-constrained scenarios or during device reconfiguration, so I need to see how the state transitions are handled here. And finally, I must be sure to look at the `blk_register_queue` and `blk_unregister_queue` calls for queue registration/deregistration. Thatβs probably the entry and exit points for these block devices within the system. These calls are going to be key to understanding how the block devices come online and go offline, and how the kernel tracks them.
|
| 25/2 |
2026/11/03 15:11 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/md/dm.c Name:__dm_destroy]
Results: map[SourceCode:2726: static void __dm_destroy(struct mapped_device *md, bool wait)
2727: {
2728: struct dm_table *map;
2729: int srcu_idx;
2730:
2731: might_sleep();
2732:
2733: spin_lock(&_minor_lock);
2734: idr_replace(&_minor_idr, MINOR_ALLOCED, MINOR(disk_devt(dm_disk(md))));
2735: set_bit(DMF_FREEING, &md->flags);
2736: spin_unlock(&_minor_lock);
2737:
2738: blk_mark_disk_dead(md->disk);
2739:
2740: /*
2741: * Take suspend_lock so that presuspend and postsuspend methods
2742: * do not race with internal suspend.
2743: */
2744: mutex_lock(&md->suspend_lock);
2745: map = dm_get_live_table(md, &srcu_idx);
2746: if (!dm_suspended_md(md)) {
2747: dm_table_presuspend_targets(map);
2748: set_bit(DMF_SUSPENDED, &md->flags);
2749: set_bit(DMF_POST_SUSPENDING, &md->flags);
2750: dm_table_postsuspend_targets(map);
2751: }
2752: /* dm_put_live_table must be before fsleep, otherwise deadlock is possible */
2753: dm_put_live_table(md, srcu_idx);
2754: mutex_unlock(&md->suspend_lock);
2755:
2756: /*
2757: * Rare, but there may be I/O requests still going to complete,
2758: * for example. Wait for all references to disappear.
2759: * No one should increment the reference count of the mapped_device,
2760: * after the mapped_device state becomes DMF_FREEING.
2761: */
2762: if (wait)
2763: while (atomic_read(&md->holders))
2764: fsleep(1000);
2765: else if (atomic_read(&md->holders))
2766: DMWARN("%s: Forcibly removing mapped_device still in use! (%d users)",
2767: dm_device_name(md), atomic_read(&md->holders));
2768:
2769: dm_table_destroy(__unbind(md));
2770: free_dev(md);
2771: }
SourceFile:drivers/md/dm.c]
|
| 26/2 |
2026/11/03 15:11 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/md/dm-rq.c Name:dm_mq_init_request_queue]
Results: map[SourceCode: 545: int dm_mq_init_request_queue(struct mapped_device *md, struct dm_table *t)
546: {
547: struct dm_target *immutable_tgt;
548: int err;
549:
550: md->tag_set = kzalloc_node(sizeof(struct blk_mq_tag_set), GFP_KERNEL, md->numa_node_id);
551: if (!md->tag_set)
552: return -ENOMEM;
553:
554: md->tag_set->ops = &dm_mq_ops;
555: md->tag_set->queue_depth = dm_get_blk_mq_queue_depth();
556: md->tag_set->numa_node = md->numa_node_id;
557: md->tag_set->flags = BLK_MQ_F_STACKING;
558: md->tag_set->nr_hw_queues = dm_get_blk_mq_nr_hw_queues();
559: md->tag_set->driver_data = md;
560:
561: md->tag_set->cmd_size = sizeof(struct dm_rq_target_io);
562: immutable_tgt = dm_table_get_immutable_target(t);
563: if (immutable_tgt && immutable_tgt->per_io_data_size) {
564: /* any target-specific per-io data is immediately after the tio */
565: md->tag_set->cmd_size += immutable_tgt->per_io_data_size;
566: md->init_tio_pdu = true;
567: }
568:
569: err = blk_mq_alloc_tag_set(md->tag_set);
570: if (err)
571: goto out_kfree_tag_set;
572:
573: err = blk_mq_init_allocated_queue(md->tag_set, md->queue);
574: if (err)
575: goto out_tag_set;
576: return 0;
577:
578: out_tag_set:
579: blk_mq_free_tag_set(md->tag_set);
580: out_kfree_tag_set:
581: kfree(md->tag_set);
582: md->tag_set = NULL;
583:
584: return err;
585: }
SourceFile:drivers/md/dm-rq.c]
|
| 27/2 |
2026/11/03 15:11 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/blk-mq.c Name:blk_mq_freeze_queue_nomemsave]
Results: map[SourceCode: 204: void blk_mq_freeze_queue_nomemsave(struct request_queue *q)
205: {
206: blk_freeze_queue_start(q);
207: blk_mq_freeze_queue_wait(q);
208: }
SourceFile:block/blk-mq.c]
|
| 28/2 |
2026/11/03 15:11 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/blk-mq.c Name:blk_mq_unfreeze_queue_nomemrestore]
Results: map[SourceCode: 230: void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
231: {
232: if (__blk_mq_unfreeze_queue(q, false))
233: blk_unfreeze_release_lock(q);
234: }
SourceFile:block/blk-mq.c]
|
| 29/2 |
2026/11/03 15:11 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/blk-sysfs.c Name:blk_register_queue]
Results: map[SourceCode: 946: /**
947: * blk_register_queue - register a block layer queue with sysfs
948: * @disk: Disk of which the request queue should be registered with sysfs.
949: */
950: int blk_register_queue(struct gendisk *disk)
951: {
952: struct request_queue *q = disk->queue;
953: unsigned int memflags;
954: int ret;
955:
956: ret = kobject_add(&disk->queue_kobj, &disk_to_dev(disk)->kobj, "queue");
957: if (ret < 0)
958: return ret;
959:
960: if (queue_is_mq(q)) {
961: ret = blk_mq_sysfs_register(disk);
962: if (ret)
963: goto out_del_queue_kobj;
964: }
965: mutex_lock(&q->sysfs_lock);
966:
967: memflags = blk_debugfs_lock(q);
968: q->debugfs_dir = debugfs_create_dir(disk->disk_name, blk_debugfs_root);
969: if (IS_ENABLED(CONFIG_BLK_ERROR_INJECTION))
970: blk_error_injection_init(disk);
971: if (queue_is_mq(q))
972: blk_mq_debugfs_register(q);
973: blk_debugfs_unlock(q, memflags);
974:
975: /*
976: * For blk-mq rotational zoned devices, default to using QD=1
977: * writes. For non-mq rotational zoned devices, the device driver can
978: * set an appropriate default.
979: */
980: if (queue_is_mq(q) && blk_queue_rot(q) && blk_queue_is_zoned(q))
981: blk_queue_flag_set(QUEUE_FLAG_ZONED_QD1_WRITES, q);
982:
983: ret = disk_register_independent_access_ranges(disk);
984: if (ret)
985: goto out_debugfs_remove;
986:
987: ret = blk_crypto_sysfs_register(disk);
988: if (ret)
989: goto out_unregister_ia_ranges;
990:
991: if (queue_is_mq(q))
992: elevator_set_default(q);
993:
994: blk_queue_flag_set(QUEUE_FLAG_REGISTERED, q);
995: wbt_init_enable_default(disk);
996:
997: /* Now everything is ready and send out KOBJ_ADD uevent */
998: kobject_uevent(&disk->queue_kobj, KOBJ_ADD);
999: if (q->elevator)
1000: kobject_uevent(&q->elevator->kobj, KOBJ_ADD);
1001: mutex_unlock(&q->sysfs_lock);
1002:
1003: /*
1004: * SCSI probing may synchronously create and destroy a lot of
1005: * request_queues for non-existent devices. Shutting down a fully
1006: * functional queue takes measureable wallclock time as RCU grace
1007: * periods are involved. To avoid excessive latency in these
1008: * cases, a request_queue starts out in a degraded mode which is
1009: * faster to shut down and is made fully functional here as
1010: * request_queues for non-existent devices never get registered.
1011: */
1012: blk_queue_flag_set(QUEUE_FLAG_INIT_DONE, q);
1013: percpu_ref_switch_to_percpu(&q->q_usage_counter);
1014:
1015: return ret;
1016:
1017: out_unregister_ia_ranges:
1018: disk_unregister_independent_access_ranges(disk);
1019: out_debugfs_remove:
1020: blk_debugfs_remove(disk);
1021: mutex_unlock(&q->sysfs_lock);
1022: if (queue_is_mq(q))
1023: blk_mq_sysfs_unregister(disk);
1024: out_del_queue_kobj:
1025: kobject_del(&disk->queue_kobj);
1026: return ret;
1027: }
SourceFile:block/blk-sysfs.c]
|
| 30/2 |
2026/11/03 15:11 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/blk-sysfs.c Name:blk_unregister_queue]
Results: map[SourceCode:1029: /**
1030: * blk_unregister_queue - counterpart of blk_register_queue()
1031: * @disk: Disk of which the request queue should be unregistered from sysfs.
1032: *
1033: * Note: the caller is responsible for guaranteeing that this function is called
1034: * after blk_register_queue() has finished.
1035: */
1036: void blk_unregister_queue(struct gendisk *disk)
1037: {
1038: struct request_queue *q = disk->queue;
1039:
1040: if (WARN_ON(!q))
1041: return;
1042:
1043: /* Return early if disk->queue was never registered. */
1044: if (!blk_queue_registered(q))
1045: return;
1046:
1047: /*
1048: * Since sysfs_remove_dir() prevents adding new directory entries
1049: * before removal of existing entries starts, protect against
1050: * concurrent elv_iosched_store() calls.
1051: */
1052: mutex_lock(&q->sysfs_lock);
1053: blk_queue_flag_clear(QUEUE_FLAG_REGISTERED, q);
1054: mutex_unlock(&q->sysfs_lock);
1055:
1056: /*
1057: * Remove the sysfs attributes before unregistering the queue data
1058: * structures that can be modified through sysfs.
1059: */
1060: if (queue_is_mq(q))
1061: blk_mq_sysfs_unregister(disk);
1062: blk_crypto_sysfs_unregister(disk);
1063:
1064: mutex_lock(&q->sysfs_lock);
1065: disk_unregister_independent_access_ranges(disk);
1066: mutex_unlock(&q->sysfs_lock);
1067:
1068: /* Now that we've deleted all child objects, we can delete the queue. */
1069: kobject_uevent(&disk->queue_kobj, KOBJ_REMOVE);
1070: kobject_del(&disk->queue_kobj);
1071:
1072: if (queue_is_mq(q))
1073: elevator_set_none(q);
1074:
1075: blk_debugfs_remove(disk);
1076: }
SourceFile:block/blk-sysfs.c]
|
| 31/2 |
2026/11/03 15:11 |
llm |
debugger |
0m
Model:
Tokens:
input: 21821
output: 202
thoughts: 133
Thoughts: Here's my thought process, as requested:
**Deconstructing a Potential Data Loss Scenario**
Wait a second! My internal alarms are going off. Those function names β `table_load`, `dev_remove`, `__dm_destroy`, `blk_mark_disk_dead`, `blk_freeze_queue_start`, and `blk_mq_unfreeze_queue_nomemrestore` β they're screaming "disk failure" and "queue management" at me. This smells like a potential data loss or corruption scenario related to block device handling, and quite possibly even device mapper interactions. I need to dig deeper, and fast.
Right, time to get specific. I need to understand the control flow and potential race conditions. I'm going to focus on how `blk_mark_disk_dead`, `blk_freeze_queue_start`, `__blk_mq_unfreeze_queue`, `blk_unfreeze_release_lock`, and `free_dev` interact, because these are all involved in handling devices that are failing. I'll need to examine the implementation of these functions within the context of `drivers/md/dm.c`, `block/blk-mq.c`, and `block/genhd.c`. Those locations will give me critical information about how device mapper devices are handled, and how the block layer interacts with them during a disk failure. Let's see if these functions are properly synchronized, and if all the error paths are clearly defined. I'm looking for a potential vulnerability in how the queues are frozen and unfrozen, and how data integrity is assured during a failure.
|
| 32/2 |
2026/11/03 15:11 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/genhd.c Name:blk_mark_disk_dead]
Results: map[SourceCode: 682: /**
683: * blk_mark_disk_dead - mark a disk as dead
684: * @disk: disk to mark as dead
685: *
686: * Mark as disk as dead (e.g. surprise removed) and don't accept any new I/O
687: * to this disk.
688: */
689: void blk_mark_disk_dead(struct gendisk *disk)
690: {
691: blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
692: __blk_mark_disk_dead(disk);
693: blk_report_disk_dead(disk, true);
694: }
SourceFile:block/genhd.c]
|
| 33/2 |
2026/11/03 15:11 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/blk-mq.c Name:blk_freeze_queue_start]
Results: map[SourceCode: 182: void blk_freeze_queue_start(struct request_queue *q)
183: {
184: if (__blk_freeze_queue_start(q, current))
185: blk_freeze_acquire_lock(q);
186: }
SourceFile:block/blk-mq.c]
|
| 34/2 |
2026/11/03 15:11 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/blk-mq.c Name:__blk_mq_unfreeze_queue]
Results: map[SourceCode: 211: bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
212: {
213: bool unfreeze;
214:
215: mutex_lock(&q->mq_freeze_lock);
216: if (force_atomic)
217: q->q_usage_counter.data->force_atomic = true;
218: q->mq_freeze_depth--;
219: WARN_ON_ONCE(q->mq_freeze_depth < 0);
220: if (!q->mq_freeze_depth) {
221: percpu_ref_resurrect(&q->q_usage_counter);
222: wake_up_all(&q->mq_freeze_wq);
223: }
224: unfreeze = blk_unfreeze_check_owner(q);
225: mutex_unlock(&q->mq_freeze_lock);
226:
227: return unfreeze;
228: }
SourceFile:block/blk-mq.c]
|
| 35/2 |
2026/11/03 15:11 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/blk-mq.c Name:blk_unfreeze_release_lock]
Results: map[SourceCode: 789: static inline void blk_unfreeze_release_lock(struct request_queue *q)
790: {
791: if (!q->mq_freeze_queue_dying)
792: rwsem_release(&q->q_lockdep_map, _RET_IP_);
793: if (!q->mq_freeze_disk_dead)
794: rwsem_release(&q->io_lockdep_map, _RET_IP_);
795: }
SourceFile:block/blk.h]
|
| 36/2 |
2026/11/03 15:11 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/md/dm.c Name:free_dev]
Results: map[SourceCode:2424: static void free_dev(struct mapped_device *md)
2425: {
2426: int minor = MINOR(disk_devt(md->disk));
2427:
2428: unlock_fs(md);
2429:
2430: cleanup_mapped_device(md);
2431:
2432: WARN_ON_ONCE(!list_empty(&md->table_devices));
2433: dm_stats_cleanup(&md->stats);
2434: free_minor(minor);
2435:
2436: module_put(THIS_MODULE);
2437: kvfree(md);
2438: }
SourceFile:drivers/md/dm.c]
|
| 37/2 |
2026/11/03 15:11 |
llm |
debugger |
0m
Model:
Tokens:
input: 23218
output: 77
thoughts: 198
Thoughts: **Analyzing `blk_unfreeze_release_lock` and Associated Code**
Okay, wait a minute. Something's nagging at me about `blk_unfreeze_release_lock` in `block/blk.h`. I need to take a closer look at that function. Specifically, lines 789 through 795:
static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
This screams potential race conditions or lock management issues. Why are there two `rwsem_release` calls, conditional on `mq_freeze_queue_dying` and `mq_freeze_disk_dead`? What are the implications if *either* of those conditions are met? I need to understand the logic behind these flags. I also have to see how these flags are set and reset.
I need to expand my search to see the code around line 789 in `block/blk.h` and the surrounding code, in addition to line 180 in `block/blk-mq.c`. Specifically, I need to understand how these locks, `q_lockdep_map` and `io_lockdep_map`, are being acquired and released and under what circumstances they are released when the block queue is unfreezing. I'm going to dig into the surrounding code to grasp the bigger picture β what the queue is doing when it's being "frozen" and "unfrozen" in this context.
|
| 38/2 |
2026/11/03 15:11 |
tool |
read-file |
0m
Args: map[File:block/blk.h FirstLine:730 LineCount:80]
Results: map[Contents: 730: }
731:
732: static inline int req_ref_read(struct request *req)
733: {
734: return atomic_read(&req->ref);
735: }
736:
737: static inline u64 blk_time_get_ns(void)
738: {
739: struct blk_plug *plug = current->plug;
740: u64 now;
741:
742: if (!plug || !in_task())
743: return ktime_get_ns();
744:
745: /*
746: * 0 could very well be a valid time, but rather than flag "this is
747: * a valid timestamp" separately, just accept that we'll do an extra
748: * ktime_get_ns() if we just happen to get 0 as the current time.
749: *
750: * cur_ktime can be zeroed by pre-emption the moment PF_BLOCK_TS is set.
751: */
752: now = READ_ONCE(plug->cur_ktime);
753: if (!now) {
754: now = ktime_get_ns();
755: WRITE_ONCE(plug->cur_ktime, now);
756: /* Ensure PF_BLOCK_TS is set after cur_ktime. */
757: barrier();
758: current->flags |= PF_BLOCK_TS;
759: }
760: return now;
761: }
762:
763: static inline ktime_t blk_time_get(void)
764: {
765: return ns_to_ktime(blk_time_get_ns());
766: }
767:
768: void bdev_release(struct file *bdev_file);
769: int bdev_open(struct block_device *bdev, blk_mode_t mode, void *holder,
770: const struct blk_holder_ops *hops, struct file *bdev_file);
771: int bdev_permission(dev_t dev, blk_mode_t mode, void *holder);
772:
773: void bio_integrity_generate(struct bio *bio);
774: blk_status_t bio_integrity_verify(struct bio *bio,
775: struct bvec_iter *saved_iter);
776:
777: void blk_integrity_prepare(struct request *rq);
778: void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
779:
780: #ifdef CONFIG_LOCKDEP
781: static inline void blk_freeze_acquire_lock(struct request_queue *q)
782: {
783: if (!q->mq_freeze_disk_dead)
784: rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
785: if (!q->mq_freeze_queue_dying)
786: rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
787: }
788:
789: static inline void blk_unfreeze_release_lock(struct request_queue *q)
790: {
791: if (!q->mq_freeze_queue_dying)
792: rwsem_release(&q->q_lockdep_map, _RET_IP_);
793: if (!q->mq_freeze_disk_dead)
794: rwsem_release(&q->io_lockdep_map, _RET_IP_);
795: }
796: #else
797: static inline void blk_freeze_acquire_lock(struct request_queue *q)
798: {
799: }
800: static inline void blk_unfreeze_release_lock(struct request_queue *q)
801: {
802: }
803: #endif
804:
805: /*
806: * debugfs directory and file creation can trigger fs reclaim, which can enter
807: * back into the block layer request_queue. This can cause deadlock if the
808: * queue is frozen. Use NOIO context together with debugfs_mutex to prevent fs
809: * reclaim from triggering block I/O.
]
|
| 39/2 |
2026/11/03 15:11 |
tool |
read-file |
0m
Args: map[File:block/blk-mq.c FirstLine:140 LineCount:110]
Results: map[Contents: 140: if (q->mq_freeze_owner != current)
141: return false;
142: if (--q->mq_freeze_owner_depth == 0) {
143: q->mq_freeze_owner = NULL;
144: return true;
145: }
146: return false;
147: }
148:
149: #else
150:
151: static bool blk_freeze_set_owner(struct request_queue *q,
152: struct task_struct *owner)
153: {
154: return false;
155: }
156:
157: static bool blk_unfreeze_check_owner(struct request_queue *q)
158: {
159: return false;
160: }
161: #endif
162:
163: bool __blk_freeze_queue_start(struct request_queue *q,
164: struct task_struct *owner)
165: {
166: bool freeze;
167:
168: mutex_lock(&q->mq_freeze_lock);
169: freeze = blk_freeze_set_owner(q, owner);
170: if (++q->mq_freeze_depth == 1) {
171: percpu_ref_kill(&q->q_usage_counter);
172: mutex_unlock(&q->mq_freeze_lock);
173: if (queue_is_mq(q))
174: blk_mq_run_hw_queues(q, false);
175: } else {
176: mutex_unlock(&q->mq_freeze_lock);
177: }
178:
179: return freeze;
180: }
181:
182: void blk_freeze_queue_start(struct request_queue *q)
183: {
184: if (__blk_freeze_queue_start(q, current))
185: blk_freeze_acquire_lock(q);
186: }
187: EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
188:
189: void blk_mq_freeze_queue_wait(struct request_queue *q)
190: {
191: wait_event(q->mq_freeze_wq, percpu_ref_is_zero(&q->q_usage_counter));
192: }
193: EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait);
194:
195: int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
196: unsigned long timeout)
197: {
198: return wait_event_timeout(q->mq_freeze_wq,
199: percpu_ref_is_zero(&q->q_usage_counter),
200: timeout);
201: }
202: EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait_timeout);
203:
204: void blk_mq_freeze_queue_nomemsave(struct request_queue *q)
205: {
206: blk_freeze_queue_start(q);
207: blk_mq_freeze_queue_wait(q);
208: }
209: EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_nomemsave);
210:
211: bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
212: {
213: bool unfreeze;
214:
215: mutex_lock(&q->mq_freeze_lock);
216: if (force_atomic)
217: q->q_usage_counter.data->force_atomic = true;
218: q->mq_freeze_depth--;
219: WARN_ON_ONCE(q->mq_freeze_depth < 0);
220: if (!q->mq_freeze_depth) {
221: percpu_ref_resurrect(&q->q_usage_counter);
222: wake_up_all(&q->mq_freeze_wq);
223: }
224: unfreeze = blk_unfreeze_check_owner(q);
225: mutex_unlock(&q->mq_freeze_lock);
226:
227: return unfreeze;
228: }
229:
230: void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
231: {
232: if (__blk_mq_unfreeze_queue(q, false))
233: blk_unfreeze_release_lock(q);
234: }
235: EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_nomemrestore);
236:
237: /*
238: * non_owner variant of blk_freeze_queue_start
239: *
]
|
| 40/2 |
2026/11/03 15:11 |
llm |
debugger |
0m
Model:
Tokens:
input: 26236
output: 103
thoughts: 110
Thoughts: Here's my analysis of the provided text, rendered as a first-person expert summary:
**Digging into the Block Layer's Death Throes**
Okay, hold on a second. I need to dive into the block layer, specifically `block/blk-mq.c`. I'm seeing a cluster of activity around lines 90-165, and the names `mq_freeze_queue_dying` and `mq_freeze_disk_dead` are just screaming "resource management during shutdown/error." This smells like crucial code for handling I/O queue transitions when things are going south, like a disk failure or a process that will soon die.
Let me take a closer look at the surrounding code (lines 80-160) for context. I'll need to understand the control flow. I need to find the definition of `struct request_queue::mq_freeze_queue_dying` and `struct request_queue::mq_freeze_disk_dead`, which is what I'll need to do via `codesearch-find-references`. I expect these to be either function pointers or maybe flags within the `request_queue` structure. Given the names, they likely relate to mechanisms for gracefully halting I/O operations and preventing data corruption. I have to see how these elements relate to the rest of the dying process.
I need to understand what state changes they imply, and how they relate to the underlying hardware and the rest of the kernel. This is important stuff. I need to understand how queues are frozen. I'll come back to this and keep digging!
|
| 41/2 |
2026/11/03 15:11 |
tool |
read-file |
0m
Args: map[File:block/blk-mq.c FirstLine:80 LineCount:70]
Results: map[Contents: 80: static void blk_mq_hctx_clear_pending(struct blk_mq_hw_ctx *hctx,
81: struct blk_mq_ctx *ctx)
82: {
83: const int bit = ctx->index_hw[hctx->type];
84:
85: sbitmap_clear_bit(&hctx->ctx_map, bit);
86: }
87:
88: struct mq_inflight {
89: struct block_device *part;
90: unsigned int inflight[2];
91: };
92:
93: static bool blk_mq_check_in_driver(struct request *rq, void *priv)
94: {
95: struct mq_inflight *mi = priv;
96:
97: if (rq->rq_flags & RQF_IO_STAT &&
98: (!bdev_is_partition(mi->part) || rq->part == mi->part) &&
99: blk_mq_rq_state(rq) == MQ_RQ_IN_FLIGHT)
100: mi->inflight[rq_data_dir(rq)]++;
101:
102: return true;
103: }
104:
105: void blk_mq_in_driver_rw(struct block_device *part, unsigned int inflight[2])
106: {
107: struct mq_inflight mi = { .part = part };
108:
109: blk_mq_queue_tag_busy_iter(bdev_get_queue(part), blk_mq_check_in_driver,
110: &mi);
111: inflight[READ] = mi.inflight[READ];
112: inflight[WRITE] = mi.inflight[WRITE];
113: }
114:
115: #ifdef CONFIG_LOCKDEP
116: static bool blk_freeze_set_owner(struct request_queue *q,
117: struct task_struct *owner)
118: {
119: if (!owner)
120: return false;
121:
122: if (!q->mq_freeze_depth) {
123: q->mq_freeze_owner = owner;
124: q->mq_freeze_owner_depth = 1;
125: q->mq_freeze_disk_dead = !q->disk ||
126: test_bit(GD_DEAD, &q->disk->state) ||
127: !blk_queue_registered(q);
128: q->mq_freeze_queue_dying = blk_queue_dying(q);
129: return true;
130: }
131:
132: if (owner == q->mq_freeze_owner)
133: q->mq_freeze_owner_depth += 1;
134: return false;
135: }
136:
137: /* verify the last unfreeze in owner context */
138: static bool blk_unfreeze_check_owner(struct request_queue *q)
139: {
140: if (q->mq_freeze_owner != current)
141: return false;
142: if (--q->mq_freeze_owner_depth == 0) {
143: q->mq_freeze_owner = NULL;
144: return true;
145: }
146: return false;
147: }
148:
149: #else
]
|
| 42/2 |
2026/11/03 15:11 |
tool |
codesearch-find-references |
0m
Args: map[Name:request_queue::mq_freeze_queue_dying]
Results: map[References:[map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:blk_freeze_acquire_lock SourceFile:block/blk.h SourceLine:785] map[ReferenceKind:writes ReferencingEntityKind:function ReferencingEntityName:blk_freeze_set_owner SourceFile:block/blk-mq.c SourceLine:128] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:blk_unfreeze_release_lock SourceFile:block/blk.h SourceLine:791]] TruncatedOutput:false]
|
| 43/2 |
2026/11/03 15:11 |
tool |
codesearch-find-references |
0m
Args: map[Name:request_queue::mq_freeze_disk_dead]
Results: map[References:[map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:blk_freeze_acquire_lock SourceFile:block/blk.h SourceLine:783] map[ReferenceKind:writes ReferencingEntityKind:function ReferencingEntityName:blk_freeze_set_owner SourceFile:block/blk-mq.c SourceLine:125] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:blk_unfreeze_release_lock SourceFile:block/blk.h SourceLine:793]] TruncatedOutput:false]
|
| 44/2 |
2026/11/03 15:11 |
llm |
debugger |
0m
Model:
Tokens:
input: 27828
output: 93
thoughts: 112
Thoughts: **Investigating a Lock Deprivation Mystery**
Hold on a minute! This doesn't make sense. Why is `&q->q_usage_counter(queue)#52`, specifically the `q_lockdep_map` within it, still being held *after* `elevator_change`? That shouldn't be happening. Something's clearly gone wrong.
Okay, let's step back and figure this out. The first thing I need to know is the nature of `&q->q_usage_counter(queue)`. What exactly *is* that thing? Let's trace back from there.
My next step: I'll need to figure out where the `q_lockdep_map`, and also `io_lockdep_map`, are even initialized, and what are the possible usages of `q_usage_counter`. Time to break out the greps. I'll search the codebase for `q_lockdep_map`, `io_lockdep_map`, and `q_usage_counter` to understand how these lock dependencies are set up, and where the counter is used, to see if I can find the source of this problem.
|
| 45/2 |
2026/11/03 15:12 |
tool |
grepper |
0m
Args: map[Expression:q_lockdep_map|io_lockdep_map|q_usage_counter\( PathPrefixes:[block/ include/linux/blk]]
Results: map[Output:block/blk-core.c=348=int blk_queue_enter(struct request_queue *q, blk_mq_req_flags_t flags)
--
block/blk-core.c-371-
block/blk-core.c:372: rwsem_acquire_read(&q->q_lockdep_map, 0, 0, _RET_IP_);
block/blk-core.c:373: rwsem_release(&q->q_lockdep_map, _RET_IP_);
block/blk-core.c-374- return 0;
--
block/blk-core.c=377=int __bio_queue_enter(struct request_queue *q, struct bio *bio)
--
block/blk-core.c-404-
block/blk-core.c:405: rwsem_acquire_read(&q->io_lockdep_map, 0, 0, _RET_IP_);
block/blk-core.c:406: rwsem_release(&q->io_lockdep_map, _RET_IP_);
block/blk-core.c-407- return 0;
--
block/blk-core.c=437=struct request_queue *blk_alloc_queue(struct queue_limits *lim, int node_id)
--
block/blk-core.c-497- lockdep_register_key(&q->q_lock_cls_key);
block/blk-core.c:498: lockdep_init_map(&q->io_lockdep_map, "&q->q_usage_counter(io)",
block/blk-core.c-499- &q->io_lock_cls_key, 0);
block/blk-core.c:500: lockdep_init_map(&q->q_lockdep_map, "&q->q_usage_counter(queue)",
block/blk-core.c-501- &q->q_lock_cls_key, 0);
--
block/blk-core.c-504- fs_reclaim_acquire(GFP_KERNEL);
block/blk-core.c:505: rwsem_acquire_read(&q->io_lockdep_map, 0, 0, _RET_IP_);
block/blk-core.c:506: rwsem_release(&q->io_lockdep_map, _RET_IP_);
block/blk-core.c-507- fs_reclaim_release(GFP_KERNEL);
--
block/blk.h=90=static inline int bio_queue_enter(struct bio *bio)
--
block/blk.h-94- if (blk_try_enter_queue(q, false)) {
block/blk.h:95: rwsem_acquire_read(&q->io_lockdep_map, 0, 0, _RET_IP_);
block/blk.h:96: rwsem_release(&q->io_lockdep_map, _RET_IP_);
block/blk.h-97- return 0;
--
block/blk.h=781=static inline void blk_freeze_acquire_lock(struct request_queue *q)
--
block/blk.h-783- if (!q->mq_freeze_disk_dead)
block/blk.h:784: rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
block/blk.h-785- if (!q->mq_freeze_queue_dying)
block/blk.h:786: rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
block/blk.h-787-}
--
block/blk.h=789=static inline void blk_unfreeze_release_lock(struct request_queue *q)
--
block/blk.h-791- if (!q->mq_freeze_queue_dying)
block/blk.h:792: rwsem_release(&q->q_lockdep_map, _RET_IP_);
block/blk.h-793- if (!q->mq_freeze_disk_dead)
block/blk.h:794: rwsem_release(&q->io_lockdep_map, _RET_IP_);
block/blk.h-795-}
]
|
| 46/2 |
2026/11/03 15:12 |
tool |
read-file |
0m
Args: map[File:block/blk-mq.c FirstLine:230 LineCount:60]
Results: map[Contents: 230: void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
231: {
232: if (__blk_mq_unfreeze_queue(q, false))
233: blk_unfreeze_release_lock(q);
234: }
235: EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_nomemrestore);
236:
237: /*
238: * non_owner variant of blk_freeze_queue_start
239: *
240: * Unlike blk_freeze_queue_start, the queue doesn't need to be unfrozen
241: * by the same task. This is fragile and should not be used if at all
242: * possible.
243: */
244: void blk_freeze_queue_start_non_owner(struct request_queue *q)
245: {
246: __blk_freeze_queue_start(q, NULL);
247: }
248: EXPORT_SYMBOL_GPL(blk_freeze_queue_start_non_owner);
249:
250: /* non_owner variant of blk_mq_unfreeze_queue */
251: void blk_mq_unfreeze_queue_non_owner(struct request_queue *q)
252: {
253: __blk_mq_unfreeze_queue(q, false);
254: }
255: EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_non_owner);
256:
257: /*
258: * FIXME: replace the scsi_internal_device_*block_nowait() calls in the
259: * mpt3sas driver such that this function can be removed.
260: */
261: void blk_mq_quiesce_queue_nowait(struct request_queue *q)
262: {
263: unsigned long flags;
264:
265: spin_lock_irqsave(&q->queue_lock, flags);
266: if (!q->quiesce_depth++)
267: blk_queue_flag_set(QUEUE_FLAG_QUIESCED, q);
268: spin_unlock_irqrestore(&q->queue_lock, flags);
269: }
270: EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue_nowait);
271:
272: /**
273: * blk_mq_wait_quiesce_done() - wait until in-progress quiesce is done
274: * @set: tag_set to wait on
275: *
276: * Note: it is driver's responsibility for making sure that quiesce has
277: * been started on or more of the request_queues of the tag_set. This
278: * function only waits for the quiesce on those request_queues that had
279: * the quiesce flag set using blk_mq_quiesce_queue_nowait.
280: */
281: void blk_mq_wait_quiesce_done(struct blk_mq_tag_set *set)
282: {
283: if (set->flags & BLK_MQ_F_BLOCKING)
284: synchronize_srcu(set->srcu);
285: else
286: synchronize_rcu();
287: }
288: EXPORT_SYMBOL_GPL(blk_mq_wait_quiesce_done);
289:
]
|
| 47/2 |
2026/11/03 15:12 |
llm |
debugger |
0m
Model:
Tokens:
input: 30138
output: 118
thoughts: 153
Thoughts: Okay, here's my assessment of the situation:
**Deep Dive into Block Layer Freezing**
Wait a second, this requires a much closer look! I need to really understand the interplay here. Let's meticulously trace the execution paths of `blk_freeze_set_owner`, `blk_freeze_acquire_lock`, `blk_unfreeze_check_owner`, and `blk_unfreeze_release_lock`. That's the core set of functions involved in this freezing and unfreezing mechanism. But that's not enough; I have to map out the call graph. I need to know *exactly* who is calling `blk_freeze_queue_start`, `blk_freeze_queue_start_non_owner`, and `blk_mq_freeze_queue`.
Furthermore, I have to be exhaustive, I can't leave anything to chance. To achieve a complete understanding, I have to find *every* caller of the underlying freezing functions. Let's find every instance where `__blk_freeze_queue_start`, `blk_freeze_queue_start_non_owner`, `blk_mq_freeze_queue`, and `blk_mq_freeze_queue_nomemsave` are invoked. That's the only way to get a full picture.
|
| 48/2 |
2026/11/03 15:12 |
tool |
codesearch-find-references |
0m
Args: map[Name:blk_freeze_queue_start_non_owner]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:nvme_start_freeze SourceFile:drivers/nvme/host/core.c SourceLine:5418] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__UNIQUE_ID_addressable_blk_freeze_queue_start_non_owner_1308 SourceFile:block/blk-mq.c SourceLine:248] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__gendwarfksyms_ptr_blk_freeze_queue_start_non_owner SourceFile:block/blk-mq.c SourceLine:248] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__gendwarfksyms_ptr_blk_freeze_queue_start_non_owner SourceFile:block/blk-mq.c SourceLine:248]] TruncatedOutput:false]
|
| 49/2 |
2026/11/03 15:12 |
tool |
codesearch-find-references |
0m
Args: map[Name:__blk_freeze_queue_start]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_freeze_queue_start SourceFile:block/blk-mq.c SourceLine:184] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_freeze_queue_start_non_owner SourceFile:block/blk-mq.c SourceLine:246] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_queue_start_drain SourceFile:block/blk-core.c SourceLine:334]] TruncatedOutput:false]
|
| 50/2 |
2026/11/03 15:12 |
tool |
codesearch-find-references |
0m
Args: map[Name:blk_freeze_acquire_lock]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__del_gendisk SourceFile:block/genhd.c SourceLine:732] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_freeze_queue_start SourceFile:block/blk-mq.c SourceLine:185]] TruncatedOutput:false]
|
| 51/2 |
2026/11/03 15:12 |
tool |
codesearch-find-references |
0m
Args: map[Name:blk_unfreeze_release_lock]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__del_gendisk SourceFile:block/genhd.c SourceLine:781] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_mq_unfreeze_queue_nomemrestore SourceFile:block/blk-mq.c SourceLine:233]] TruncatedOutput:false]
|
| 52/2 |
2026/11/03 15:12 |
llm |
debugger |
0m
Model:
Tokens:
input: 31131
output: 78
thoughts: 134
Thoughts: Here's my analysis:
**A Flash of Insight: Block Layer Concurrency Concerns**
Hold on, something just clicked! I was reviewing the code and those function calls jumped out at me. Specifically, I see mentions of `__blk_freeze_queue_start`, `blk_freeze_acquire_lock`, and `blk_unfreeze_release_lock`. That's a strong indicator of concurrency control related to block device queue management. My immediate thought is to trace the flow.
First, `blk_queue_start_drain` in `block/blk-core.c:334` seems like a critical starting point. Then, I noticed calls to those functions in the `__del_gendisk` function, which appears in both `block/genhd.c:732` and `781`. That's interesting, as it is likely handling the removal of a disk, which might require freezing the queue to ensure data integrity.
My next step is clear: I need to deeply understand the context around these calls. I'm going to read `block/blk-core.c` around line 334 and `block/genhd.c` around lines 650-800 to fully grasp the locking and unlocking semantics. This should give me a solid understanding of how the block layer handles potentially conflicting operations during queue draining and disk deletion. I anticipate some interesting synchronization mechanisms to ensure data consistency.
|
| 53/2 |
2026/11/03 15:12 |
tool |
read-file |
0m
Args: map[File:block/blk-core.c FirstLine:310 LineCount:50]
Results: map[Contents: 310: call_rcu(&q->rcu_head, blk_free_queue_rcu);
311: }
312:
313: /**
314: * blk_put_queue - decrement the request_queue refcount
315: * @q: the request_queue structure to decrement the refcount for
316: *
317: * Decrements the refcount of the request_queue and free it when the refcount
318: * reaches 0.
319: */
320: void blk_put_queue(struct request_queue *q)
321: {
322: if (refcount_dec_and_test(&q->refs))
323: blk_free_queue(q);
324: }
325: EXPORT_SYMBOL(blk_put_queue);
326:
327: bool blk_queue_start_drain(struct request_queue *q)
328: {
329: /*
330: * When queue DYING flag is set, we need to block new req
331: * entering queue, so we call blk_freeze_queue_start() to
332: * prevent I/O from crossing blk_queue_enter().
333: */
334: bool freeze = __blk_freeze_queue_start(q, current);
335: if (queue_is_mq(q))
336: blk_mq_wake_waiters(q);
337: /* Make blk_queue_enter() reexamine the DYING flag. */
338: wake_up_all(&q->mq_freeze_wq);
339:
340: return freeze;
341: }
342:
343: /**
344: * blk_queue_enter() - try to increase q->q_usage_counter
345: * @q: request queue pointer
346: * @flags: BLK_MQ_REQ_NOWAIT and/or BLK_MQ_REQ_PM
347: */
348: int blk_queue_enter(struct request_queue *q, blk_mq_req_flags_t flags)
349: {
350: const bool pm = flags & BLK_MQ_REQ_PM;
351:
352: while (!blk_try_enter_queue(q, pm)) {
353: if (flags & BLK_MQ_REQ_NOWAIT)
354: return -EAGAIN;
355:
356: /*
357: * read pair of barrier in blk_freeze_queue_start(), we need to
358: * order reading __PERCPU_REF_DEAD flag of .q_usage_counter and
359: * reading .mq_freeze_depth or queue dying flag, otherwise the
]
|
| 54/2 |
2026/11/03 15:12 |
tool |
read-file |
0m
Args: map[File:block/genhd.c FirstLine:660 LineCount:140]
Results: map[Contents: 660: static bool __blk_mark_disk_dead(struct gendisk *disk)
661: {
662: /*
663: * Fail any new I/O.
664: */
665: if (test_and_set_bit(GD_DEAD, &disk->state))
666: return false;
667:
668: if (test_bit(GD_OWNS_QUEUE, &disk->state))
669: blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
670:
671: /*
672: * Stop buffered writers from dirtying pages that can't be written out.
673: */
674: set_capacity(disk, 0);
675:
676: /*
677: * Prevent new I/O from crossing bio_queue_enter().
678: */
679: return blk_queue_start_drain(disk->queue);
680: }
681:
682: /**
683: * blk_mark_disk_dead - mark a disk as dead
684: * @disk: disk to mark as dead
685: *
686: * Mark as disk as dead (e.g. surprise removed) and don't accept any new I/O
687: * to this disk.
688: */
689: void blk_mark_disk_dead(struct gendisk *disk)
690: {
691: blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
692: __blk_mark_disk_dead(disk);
693: blk_report_disk_dead(disk, true);
694: }
695: EXPORT_SYMBOL_GPL(blk_mark_disk_dead);
696:
697: static void __del_gendisk(struct gendisk *disk)
698: {
699: struct request_queue *q = disk->queue;
700: struct block_device *part;
701: unsigned long idx;
702: bool start_drain;
703:
704: might_sleep();
705:
706: if (WARN_ON_ONCE(!disk_live(disk) && !(disk->flags & GENHD_FL_HIDDEN)))
707: return;
708:
709: disk_del_events(disk);
710:
711: /*
712: * Prevent new openers by unlinked the bdev inode.
713: */
714: mutex_lock(&disk->open_mutex);
715: xa_for_each(&disk->part_tbl, idx, part)
716: bdev_unhash(part);
717: mutex_unlock(&disk->open_mutex);
718:
719: /*
720: * Tell the file system to write back all dirty data and shut down if
721: * it hasn't been notified earlier.
722: */
723: if (!test_bit(GD_DEAD, &disk->state))
724: blk_report_disk_dead(disk, false);
725:
726: /*
727: * Drop all partitions now that the disk is marked dead.
728: */
729: mutex_lock(&disk->open_mutex);
730: start_drain = __blk_mark_disk_dead(disk);
731: if (start_drain)
732: blk_freeze_acquire_lock(q);
733: xa_for_each_start(&disk->part_tbl, idx, part, 1)
734: drop_partition(part);
735: mutex_unlock(&disk->open_mutex);
736:
737: if (!(disk->flags & GENHD_FL_HIDDEN)) {
738: sysfs_remove_link(&disk_to_dev(disk)->kobj, "bdi");
739:
740: /*
741: * Unregister bdi before releasing device numbers (as they can
742: * get reused and we'd get clashes in sysfs).
743: */
744: bdi_unregister(disk->bdi);
745: }
746:
747: blk_unregister_queue(disk);
748:
749: kobject_put(disk->part0->bd_holder_dir);
750: kobject_put(disk->slave_dir);
751: disk->slave_dir = NULL;
752:
753: part_stat_set_all(disk->part0, 0);
754: disk->part0->bd_stamp = 0;
755: sysfs_remove_link(block_depr, dev_name(disk_to_dev(disk)));
756: pm_runtime_set_memalloc_noio(disk_to_dev(disk), false);
757: device_del(disk_to_dev(disk));
758:
759: blk_mq_freeze_queue_wait(q);
]
|
| 55/2 |
2026/11/03 15:12 |
llm |
debugger |
0m
Model:
Tokens:
input: 33634
output: 40
thoughts: 59
Thoughts: Okay, here we go...
**Deep Dive Alert: Potential Disk Death and Elevator Interaction**
Oh. My. God! I'm staring at this code and my brain is firing on all cylinders! The interaction between `blk_mark_disk_dead`, `__del_gendisk`, and `elevator_change` is screaming for attention. I need to understand this dance and how it handles disk failure scenarios. The potential ramifications here are significant, especially if this is related to a storage subsystem I'm familiar with.
I'm immediately jumping to `block/genhd.c`, specifically lines 755 through 820. That section is practically begging for a thorough review. I need to see how these functions interact in this critical part of the disk handling process. I need to understand this to determine if the logic is safe and performant, or if I should raise a red flag.
|
| 56/2 |
2026/11/03 15:12 |
tool |
read-file |
0m
Args: map[File:block/genhd.c FirstLine:755 LineCount:70]
Results: map[Contents: 755: sysfs_remove_link(block_depr, dev_name(disk_to_dev(disk)));
756: pm_runtime_set_memalloc_noio(disk_to_dev(disk), false);
757: device_del(disk_to_dev(disk));
758:
759: blk_mq_freeze_queue_wait(q);
760:
761: blk_throtl_cancel_bios(disk);
762:
763: blk_sync_queue(q);
764: blk_flush_integrity();
765:
766: if (queue_is_mq(q))
767: blk_mq_cancel_work_sync(q);
768:
769: rq_qos_exit(q);
770:
771: /*
772: * If the disk does not own the queue, allow using passthrough requests
773: * again. Else leave the queue frozen to fail all I/O.
774: */
775: if (!test_bit(GD_OWNS_QUEUE, &disk->state))
776: __blk_mq_unfreeze_queue(q, true);
777: else if (queue_is_mq(q))
778: blk_mq_exit_queue(q);
779:
780: if (start_drain)
781: blk_unfreeze_release_lock(q);
782: }
783:
784: static void disable_elv_switch(struct request_queue *q)
785: {
786: struct blk_mq_tag_set *set = q->tag_set;
787: WARN_ON_ONCE(!queue_is_mq(q));
788:
789: down_write(&set->update_nr_hwq_lock);
790: blk_queue_flag_set(QUEUE_FLAG_NO_ELV_SWITCH, q);
791: up_write(&set->update_nr_hwq_lock);
792: }
793:
794: /**
795: * del_gendisk - remove the gendisk
796: * @disk: the struct gendisk to remove
797: *
798: * Removes the gendisk and all its associated resources. This deletes the
799: * partitions associated with the gendisk, and unregisters the associated
800: * request_queue.
801: *
802: * This is the counter to the respective device_add_disk() call.
803: *
804: * The final removal of the struct gendisk happens when its refcount reaches 0
805: * with put_disk(), which should be called after del_gendisk(), if
806: * device_add_disk() was used.
807: *
808: * Drivers exist which depend on the release of the gendisk to be synchronous,
809: * it should not be deferred.
810: *
811: * Context: can sleep
812: */
813: void del_gendisk(struct gendisk *disk)
814: {
815: struct blk_mq_tag_set *set;
816: unsigned int memflags;
817:
818: if (!queue_is_mq(disk->queue)) {
819: __del_gendisk(disk);
820: } else {
821: set = disk->queue->tag_set;
822:
823: disable_elv_switch(disk->queue);
824:
]
|
| 57/2 |
2026/11/03 15:12 |
llm |
debugger |
0m
Model:
Tokens:
input: 34788
output: 77
thoughts: 66
Thoughts: Okay, let me break this down.
**Initial Assessment: Two Critical Points!**
Wait a minute, hold on! This is important. My initial read flagged something significant, something that warrants immediate and detailed scrutiny. I'm going to carefully isolate and verify both of those points.
First, I need to thoroughly re-examine the context of `del_gendisk` and `device_add_disk`, particularly within the `block/genhd.c` file. I need to refresh my understanding of their interaction before I can make a judgement. This warrants a more in-depth code dive.
|
| 58/2 |
2026/11/03 15:12 |
tool |
read-file |
0m
Args: map[File:block/genhd.c FirstLine:820 LineCount:50]
Results: map[Contents: 820: } else {
821: set = disk->queue->tag_set;
822:
823: disable_elv_switch(disk->queue);
824:
825: memflags = memalloc_noio_save();
826: down_read(&set->update_nr_hwq_lock);
827: __del_gendisk(disk);
828: up_read(&set->update_nr_hwq_lock);
829: memalloc_noio_restore(memflags);
830: }
831: }
832: EXPORT_SYMBOL(del_gendisk);
833:
834: /**
835: * invalidate_disk - invalidate the disk
836: * @disk: the struct gendisk to invalidate
837: *
838: * A helper to invalidates the disk. It will clean the disk's associated
839: * buffer/page caches and reset its internal states so that the disk
840: * can be reused by the drivers.
841: *
842: * Context: can sleep
843: */
844: void invalidate_disk(struct gendisk *disk)
845: {
846: struct block_device *bdev = disk->part0;
847:
848: invalidate_bdev(bdev);
849: bdev->bd_mapping->wb_err = 0;
850: set_capacity(disk, 0);
851: }
852: EXPORT_SYMBOL(invalidate_disk);
853:
854: /* sysfs access to bad-blocks list. */
855: static ssize_t disk_badblocks_show(struct device *dev,
856: struct device_attribute *attr,
857: char *page)
858: {
859: struct gendisk *disk = dev_to_disk(dev);
860:
861: if (!disk->bb)
862: return sysfs_emit(page, "\n");
863:
864: return badblocks_show(disk->bb, page, 0);
865: }
866:
867: static ssize_t disk_badblocks_store(struct device *dev,
868: struct device_attribute *attr,
869: const char *page, size_t len)
]
|
| 59/2 |
2026/11/03 15:12 |
tool |
read-file |
0m
Args: map[File:block/genhd.c FirstLine:450 LineCount:150]
Results: map[Contents: 450: /*
451: * We do not support partitions with zoned block devices, so do not try
452: * to scan the partitions table.
453: */
454: if (blk_queue_is_zoned(disk->queue))
455: disk->flags |= GENHD_FL_NO_PART;
456:
457: /*
458: * If the driver provides an explicit major number it also must provide
459: * the number of minors numbers supported, and those will be used to
460: * setup the gendisk.
461: * Otherwise just allocate the device numbers for both the whole device
462: * and all partitions from the extended dev_t space.
463: */
464: ret = -EINVAL;
465: if (disk->major) {
466: if (WARN_ON(!disk->minors))
467: goto out;
468:
469: if (disk->minors > DISK_MAX_PARTS) {
470: pr_err("block: can't allocate more than %d partitions\n",
471: DISK_MAX_PARTS);
472: disk->minors = DISK_MAX_PARTS;
473: }
474: if (disk->first_minor > MINORMASK ||
475: disk->minors > MINORMASK + 1 ||
476: disk->first_minor + disk->minors > MINORMASK + 1)
477: goto out;
478: } else {
479: if (WARN_ON(disk->minors))
480: goto out;
481:
482: ret = blk_alloc_ext_minor();
483: if (ret < 0)
484: goto out;
485: disk->major = BLOCK_EXT_MAJOR;
486: disk->first_minor = ret;
487: }
488:
489: /* delay uevents, until we scanned partition table */
490: dev_set_uevent_suppress(ddev, 1);
491:
492: ddev->parent = parent;
493: ddev->groups = groups;
494: dev_set_name(ddev, "%s", disk->disk_name);
495: if (fwnode)
496: device_set_node(ddev, fwnode);
497: if (!(disk->flags & GENHD_FL_HIDDEN))
498: ddev->devt = MKDEV(disk->major, disk->first_minor);
499: ret = device_add(ddev);
500: if (ret)
501: goto out_free_ext_minor;
502:
503: ret = disk_alloc_events(disk);
504: if (ret)
505: goto out_device_del;
506:
507: ret = sysfs_create_link(block_depr, &ddev->kobj,
508: kobject_name(&ddev->kobj));
509: if (ret)
510: goto out_device_del;
511:
512: /*
513: * avoid probable deadlock caused by allocating memory with
514: * GFP_KERNEL in runtime_resume callback of its all ancestor
515: * devices
516: */
517: pm_runtime_set_memalloc_noio(ddev, true);
518:
519: disk->part0->bd_holder_dir =
520: kobject_create_and_add("holders", &ddev->kobj);
521: if (!disk->part0->bd_holder_dir) {
522: ret = -ENOMEM;
523: goto out_del_block_link;
524: }
525: disk->slave_dir = kobject_create_and_add("slaves", &ddev->kobj);
526: if (!disk->slave_dir) {
527: ret = -ENOMEM;
528: goto out_put_holder_dir;
529: }
530:
531: ret = blk_register_queue(disk);
532: if (ret)
533: goto out_put_slave_dir;
534:
535: if (!(disk->flags & GENHD_FL_HIDDEN)) {
536: ret = bdi_register(disk->bdi, "%u:%u",
537: disk->major, disk->first_minor);
538: if (ret)
539: goto out_unregister_queue;
540: bdi_set_owner(disk->bdi, ddev);
541: ret = sysfs_create_link(&ddev->kobj,
542: &disk->bdi->dev->kobj, "bdi");
543: if (ret)
544: goto out_unregister_bdi;
545: } else {
546: /*
547: * Even if the block_device for a hidden gendisk is not
548: * registered, it needs to have a valid bd_dev so that the
549: * freeing of the dynamic major works.
]
|
| 60/2 |
2026/11/03 15:12 |
llm |
debugger |
0m
Model:
Tokens:
input: 37169
output: 44
thoughts: 1448
Thoughts: **Analyzing a Device Mapper Crash: A Deep Dive**
Okay, so here's what's running through my head as I dissect this crash report. First, I need to understand the context. I'm looking at `blk_mark_disk_dead` in `block/genhd.c`. This function is important because it's responsible for handling a disk becoming unusable, which is what I'm suspecting has happened. It sets a flag, stops I/O, and drains the queue. This is crucial for avoiding data corruption.
But something went wrong. The crash report indicates a "lock held when returning to user space!" Specifically, the `q->q_usage_counter` lock is being held by thread `syz.3.1525/11804` at `elevator_change+0x194/0x480`. This is bad, *very* bad. A lock must always be released before returning to userspace; otherwise, things are very unstable.
The crash happened within device mapper with concurrent `table_load` (DM_TABLE_LOAD) and `dev_remove` (DM_DEV_REMOVE) calls. I see that these are triggered by two file descriptors for `/dev/mapper/control`. `table_load` is running on a request-based target (like `multipath`). This sounds like a race condition, so let's check the code:
In the crash, one thread is executing `table_load`. What are the steps?
1. It calls `find_device` to get a reference to `md` (increasing the holder count).
2. Then, it acquires the `md` lock with `dm_lock_md_type(md)`.
3. Next, `populate_table` parses the `multipath` target and sets its type to `DM_TYPE_REQUEST_BASED`.
4. If `dm_get_md_type(md)` is `DM_TYPE_NONE`, it calls `dm_setup_md_queue(md, t)`.
5. Within `dm_setup_md_queue`, for `DM_TYPE_REQUEST_BASED` targets, `dm_mq_init_request_queue` initializes the request queue and calls `add_disk(md->disk)`.
6. Finally, `add_disk` calls `device_add_disk`, which calls `blk_register_queue`.
7. `blk_register_queue` then calls `elevator_set_default(q)` and *finally*, `elevator_change(q, &ctx)`.
Okay, while all that is going on, another thread `dev_remove` is also running, and it's trying to remove the device. This is where I need to focus:
1. `dev_remove` acquires `_hash_lock`.
2. It calls `__find_device_hash_cell`.
3. It then gets a pointer `md` using `hc->md`.
4. And *then* calls `dm_lock_for_deletion(md...)`.
This is *critical*, so I must know: What is the check in `dm_lock_for_deletion`? It's time to check the code in `drivers/md/dm.c`. I suspect the race is there. The `elevator_change` from thread A might be colliding with whatever `dm_lock_for_deletion` is doing on thread B.
|
| 61/2 |
2026/11/03 15:12 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/md/dm.c Name:dm_lock_for_deletion]
Results: map[SourceCode: 362: /*
363: * Guarantees nothing is using the device before it's deleted.
364: */
365: int dm_lock_for_deletion(struct mapped_device *md, bool mark_deferred, bool only_deferred)
366: {
367: int r = 0;
368:
369: spin_lock(&_minor_lock);
370:
371: if (dm_open_count(md)) {
372: r = -EBUSY;
373: if (mark_deferred)
374: set_bit(DMF_DEFERRED_REMOVE, &md->flags);
375: } else if (only_deferred && !test_bit(DMF_DEFERRED_REMOVE, &md->flags))
376: r = -EEXIST;
377: else
378: set_bit(DMF_DELETING, &md->flags);
379:
380: spin_unlock(&_minor_lock);
381:
382: return r;
383: }
SourceFile:drivers/md/dm.c]
|
| 62/2 |
2026/11/03 15:12 |
llm |
debugger |
0m
Model:
Tokens:
input: 39004
output: 78
thoughts: 5578
Thoughts: **Analyzing a Device Mapper Concurrency Bug**
Okay, here's the situation as I understand it. I'm looking at a concurrency issue within the Device Mapper (DM) framework, specifically focusing on a crash report from a syzkaller fuzzing run. The core of the problem appears to be a race condition between device removal and device table loading, leading to a lock being held when returning to user space, which is a big no-no.
The initial thought is that `dm_lock_for_deletion` is too simplistic, only checking `dm_open_count(md)` and not the more important `md->holders`. This means there's a window where a device can be considered safe for deletion even if references still exist. Following the execution path, `dev_remove` calls `dm_destroy`, which eventually calls `blk_mark_disk_dead(md->disk)`. It seems that the key lies within `blk_mark_disk_dead(md->disk)` and its interaction with the block layer's queue management.
`blk_mark_disk_dead` sets the `QUEUE_FLAG_DYING` flag on the queue and calls `blk_queue_start_drain`. It seems that `blk_queue_start_drain` calls `blk_freeze_queue_start` to prevent I/O from crossing `blk_queue_enter()`. Crucially, this involves `blk_freeze_acquire_lock`, which acquires `q->q_lockdep_map` (a read-write semaphore) within the `elevator_change` function. The crash log indicates that a syzkaller thread (syz.3.1525/11804) holds this `q->q_lockdep_map` at `elevator_change+0x194/0x480`.
The core concern here is that `blk_mark_disk_dead` can potentially interfere with the `elevator_change` operation. The key question is whether the `q->q_lockdep_map` acquired at `elevator_change` will be released properly. It appears that `elevator_change` is called from `blk_register_queue` through `elevator_set_default` during `add_disk(md->disk)` in `table_load`. This suggests that the issue is likely due to an interaction between the table loading process and the device removal.
The code flow analysis indicates a critical point is within `blk_freeze_queue_start`, `blk_freeze_acquire_lock` and the interaction between these calls in Thread A, and `blk_mark_disk_dead` called in Thread B. The lock acquisition depends on certain flags within the request queue; specifically, `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying`. The interaction of these two flags will cause acquisition of the `q->q_lockdep_map`.
The reproducer shows a `DM_TABLE_LOAD` followed by a `DM_DEV_REMOVE`. A critical insight comes from the crash log message "device has been removed from the dev hash table." when trying to load the table. It indicates a race - `dev_remove` happens while `table_load` is in progress. The key steps are:
1. In `table_load`, `dm_setup_md_queue(md, t)` is called. This initializes the block-mq queue.
2. `add_disk(md->disk)` registers the disk and queue (via `blk_register_queue` which calls `elevator_change`).
3. While `table_load` is in progress, the other thread calls `dev_remove`, which calls `dm_destroy` and then `blk_mark_disk_dead(md->disk)`.
This seems to happen before line 1677 in `table_load`.
A core question is whether `blk_mark_disk_dead` is called _before_ or during `add_disk`. The `syz.3.1525/11804` process holds the lock `&q->q_usage_counter(queue)` which seems to imply that the block device has already been created, but perhaps `add_disk` is interrupted by `dev_remove` and the unfreezing isn't done correctly.
If Thread B calls `blk_mark_disk_dead` before the queue is fully initialized by `add_disk`, `q->mq_freeze_disk_dead` would be `true` and thus `q->q_lockdep_map` is not acquired, and the crash should not happen.
The critical path to the crash involves `blk_freeze_queue_start` followed by `blk_freeze_acquire_
|
| 63/2 |
2026/11/03 15:12 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/md/dm.c Name:alloc_dev]
Results: map[SourceCode:2298: /*
2299: * Allocate and initialise a blank device with a given minor.
2300: */
2301: static struct mapped_device *alloc_dev(int minor)
2302: {
2303: int r, numa_node_id = dm_get_numa_node();
2304: struct dax_device *dax_dev;
2305: struct mapped_device *md;
2306: void *old_md;
2307:
2308: md = kvzalloc_node(sizeof(*md), GFP_KERNEL, numa_node_id);
2309: if (!md) {
2310: DMERR("unable to allocate device, out of memory.");
2311: return NULL;
2312: }
2313:
2314: if (!try_module_get(THIS_MODULE))
2315: goto bad_module_get;
2316:
2317: /* get a minor number for the dev */
2318: if (minor == DM_ANY_MINOR)
2319: r = next_free_minor(&minor);
2320: else
2321: r = specific_minor(minor);
2322: if (r < 0)
2323: goto bad_minor;
2324:
2325: r = init_srcu_struct(&md->io_barrier);
2326: if (r < 0)
2327: goto bad_io_barrier;
2328:
2329: md->numa_node_id = numa_node_id;
2330: md->init_tio_pdu = false;
2331: md->type = DM_TYPE_NONE;
2332: mutex_init(&md->suspend_lock);
2333: mutex_init(&md->type_lock);
2334: mutex_init(&md->table_devices_lock);
2335: spin_lock_init(&md->deferred_lock);
2336: atomic_set(&md->holders, 1);
2337: atomic_set(&md->open_count, 0);
2338: atomic_set(&md->event_nr, 0);
2339: atomic_set(&md->uevent_seq, 0);
2340: INIT_LIST_HEAD(&md->uevent_list);
2341: INIT_LIST_HEAD(&md->table_devices);
2342: spin_lock_init(&md->uevent_lock);
2343:
2344: /*
2345: * default to bio-based until DM table is loaded and md->type
2346: * established. If request-based table is loaded: blk-mq will
2347: * override accordingly.
2348: */
2349: md->disk = blk_alloc_disk(NULL, md->numa_node_id);
2350: if (IS_ERR(md->disk)) {
2351: md->disk = NULL;
2352: goto bad;
2353: }
2354: md->queue = md->disk->queue;
2355:
2356: init_waitqueue_head(&md->wait);
2357: INIT_WORK(&md->work, dm_wq_work);
2358: INIT_WORK(&md->requeue_work, dm_wq_requeue_work);
2359: init_waitqueue_head(&md->eventq);
2360: init_completion(&md->kobj_holder.completion);
2361:
2362: md->requeue_list = NULL;
2363: md->swap_bios = get_swap_bios();
2364: sema_init(&md->swap_bios_semaphore, md->swap_bios);
2365: mutex_init(&md->swap_bios_lock);
2366:
2367: md->disk->major = _major;
2368: md->disk->first_minor = minor;
2369: md->disk->minors = 1;
2370: md->disk->flags |= GENHD_FL_NO_PART;
2371: md->disk->fops = &dm_blk_dops;
2372: md->disk->private_data = md;
2373: sprintf(md->disk->disk_name, "dm-%d", minor);
2374:
2375: dax_dev = alloc_dax(md, &dm_dax_ops);
2376: if (IS_ERR(dax_dev)) {
2377: if (PTR_ERR(dax_dev) != -EOPNOTSUPP)
2378: goto bad;
2379: } else {
2380: set_dax_nocache(dax_dev);
2381: set_dax_nomc(dax_dev);
2382: md->dax_dev = dax_dev;
2383: if (dax_add_host(dax_dev, md->disk))
2384: goto bad;
2385: }
2386:
2387: format_dev_t(md->name, MKDEV(_major, minor));
2388:
2389: md->wq = alloc_workqueue("kdmflush/%s", WQ_MEM_RECLAIM | WQ_PERCPU, 0,
2390: md->name);
2391: if (!md->wq)
2392: goto bad;
2393:
2394: md->pending_io = alloc_percpu(unsigned long);
2395: if (!md->pending_io)
2396: goto bad;
2397:
2398: r = dm_stats_init(&md->stats);
2399: if (r < 0)
2400: goto bad;
2401:
2402: /* Populate the mapping, nobody knows we exist yet */
2403: spin_lock(&_minor_lock);
2404: old_md = idr_replace(&_minor_idr, md, minor);
2405: spin_unlock(&_minor_lock);
2406:
2407: BUG_ON(old_md != MINOR_ALLOCED);
2408:
2409: return md;
2410:
2411: bad:
2412: cleanup_mapped_device(md);
2413: bad_io_barrier:
2414: free_minor(minor);
2415: bad_minor:
2416: module_put(THIS_MODULE);
2417: bad_module_get:
2418: kvfree(md);
2419: return NULL;
2420: }
SourceFile:drivers/md/dm.c]
|
| 64/2 |
2026/11/03 15:12 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/md/dm.c Name:cleanup_mapped_device]
Results: map[SourceCode:2245: static void cleanup_mapped_device(struct mapped_device *md)
2246: {
2247: if (md->wq)
2248: destroy_workqueue(md->wq);
2249: dm_free_md_mempools(md->mempools);
2250:
2251: if (md->dax_dev) {
2252: dax_remove_host(md->disk);
2253: kill_dax(md->dax_dev);
2254: put_dax(md->dax_dev);
2255: md->dax_dev = NULL;
2256: }
2257:
2258: if (md->disk) {
2259: spin_lock(&_minor_lock);
2260: md->disk->private_data = NULL;
2261: spin_unlock(&_minor_lock);
2262: if (dm_get_md_type(md) != DM_TYPE_NONE) {
2263: struct table_device *td;
2264:
2265: dm_sysfs_exit(md);
2266: list_for_each_entry(td, &md->table_devices, list) {
2267: bd_unlink_disk_holder(td->dm_dev.bdev,
2268: md->disk);
2269: }
2270:
2271: /*
2272: * Hold lock to make sure del_gendisk() won't concurrent
2273: * with open/close_table_device().
2274: */
2275: mutex_lock(&md->table_devices_lock);
2276: del_gendisk(md->disk);
2277: mutex_unlock(&md->table_devices_lock);
2278: }
2279: dm_queue_destroy_crypto_profile(md->queue);
2280: put_disk(md->disk);
2281: }
2282:
2283: if (md->pending_io) {
2284: free_percpu(md->pending_io);
2285: md->pending_io = NULL;
2286: }
2287:
2288: cleanup_srcu_struct(&md->io_barrier);
2289:
2290: mutex_destroy(&md->suspend_lock);
2291: mutex_destroy(&md->type_lock);
2292: mutex_destroy(&md->table_devices_lock);
2293: mutex_destroy(&md->swap_bios_lock);
2294:
2295: dm_mq_cleanup_mapped_device(md);
2296: }
SourceFile:drivers/md/dm.c]
|
| 65/2 |
2026/11/03 15:12 |
llm |
debugger |
0m
Model:
Tokens:
input: 47351
output: 91
thoughts: 107
Thoughts: Okay, here's the breakdown of my thought process:
**Diving Deep into the Disk Management Code**
Hold on a second! I need to quickly compare `blk_mark_disk_dead`, `__del_gendisk`, and `elevator_change`. There's something potentially interconnected here that needs closer scrutiny. Before I get too far down that rabbit hole, I should pause and take a look at the git history. Let's start with a focused investigation into the relevant files β `block/genhd.c`, `block/blk-mq.c`, `block/blk.h`, and `block/elevator.c`. The changes over time in these files might illuminate the relationships between these functions and the broader block layer architecture. Now I should make sure I run a `git log` specifically on `block/blk-mq.c`, `block/genhd.c` and `block/blk.h` files to check the changes made.
|
| 66/2 |
2026/11/03 15:12 |
tool |
git-log |
0m
Args: map[Count:20 PathPrefix:block/blk-mq.c]
Results: map[Output:4fcc499ea9bc blk-mq: set up a queue under tag_list_lock
89a2381482d8 blk-mq: exit the hctxs of a queue under tag_list_lock
71ec3c7d6db8 blk-mq: quiesce a queue that joins a quiesced tag set
0db9f8968a89 blk-mq: don't forget a timer the driver has restarted
9531230ee1fc blk-mq: don't bring back flags of a completed request
620cfc7a6642 blk-mq: keep sharing tags fairly after a queue update
24974185999f blk-mq: don't trust the cookie in blk_mq_poll()
afc1de47a7ab blk-mq: clear stale inactive flag on hctx reuse
5f702d4bd61b blk-mq: drop the tag_set argument from blk_mq_free_rq_map/tags
e1c51edd6a57 blk-mq: share one tags_srcu instance across all tag sets
20d808694e40 block: fix indention for dma-buf checks
d88e44f43e93 block: introduce dma map backed bio type
e0f2224433b1 block: drop the cached plug time when blk_add_rq_to_plug() flushes
9d2c70986bb7 blk-mq: allow cached requests to be used for flush operations
ab6c756f28c7 blk-mq: set RQF_USE_SCHED when the operation is known
1207dbb91c11 blk-mq: add missing call to srcu_barrier() in blk_mq_free_tag_set()
30e542a36228 blk-mq: bound blk_hctx_poll() to one jiffy
5bdb8ec58b54 block: propagate in_flight to whole disk on partition I/O
b7f40ab50190 block: export passthrough stats enabled
a7d8eaee7faf block: add a bio_endio_status helper
]
|
| 67/2 |
2026/11/03 15:12 |
tool |
git-log |
0m
Args: map[Count:20 PathPrefix:block/genhd.c]
Results: map[Output:3f9c7a108c0e block: flag zoned disks with GENHD_FL_NO_PART
7e9a46004b47 block: set QUEUE_FLAG_DYING unconditionally in blk_mark_disk_dead()
26cb8ebbfaf7 block: stop the timeout timer when releasing a never added disk
181bb9c9eae4 block: remove redundant GD_NEED_PART_SCAN in add_disk_final()
3dd63dba8f9c block: avoid potential deadlock on zone revalidation failure
e8dcf2d142bd block: add configurable error injection
bf4afc53b77a Convert 'alloc_obj' family to use the new default GFP_KERNEL argument
69050f8d6d07 treewide: Replace kmalloc with kmalloc_obj for non-scalar types
a74de0c3663c block: Remove references to __device_add_disk()
3179a5f7f86b block: rate-limit capacity change info log
343dc5423bfe block: fix kobject double initialization in add_disk
c007062188d8 block: fix false warning in bdev_count_inflight_rw()
f2987c5816bd block: export API to get the number of bdev inflight IO
6b6c3a97abde block: clean up blk_mq_in_flight_rw()
f5482ee5edb9 block: WARN if bdev inflight counter is negative
5b8f19aee474 block: reuse part_in_flight_rw for part_in_flight
78c271344b6f block: move wbt_enable_default() out of queue freezing from sched ->exit()
21eed794ab4b block: add new helper for disabling elevator switch when deleting disk
1e44bedbc921 block: unifying elevator change
98e68f67020c block: prevent adding/deleting disk during updating nr_hw_queues
]
|
| 68/2 |
2026/11/03 15:12 |
tool |
git-log |
0m
Args: map[Count:20 PathPrefix:block/elevator.c]
Results: map[Output:4ff58d6bc9dd block: serialize elevator changes for the same queue using a writer lock
ce8ee8583ed8 block: use trylock to avoid lockdep circular dependency in sysfs
f98afe4f31bb blk-mq: add a new queue sysfs attribute async_depth
9869d3a6fed3 block: fix race between wbt_enable_default and IO submission
0315476e78c0 block: use {alloc|free}_sched data methods
04728ce90966 block: move elevator tags into struct elevator_resources
232143b60538 block: unify elevator tags and type xarrays into struct elv_change_ctx
6293e336f6d7 blk-mq-sched: add new parameter nr_requests in blk_mq_alloc_sched_tags()
04225d13aef1 block: fix potential deadlock while running nr_hw_queue update
f5a6604f7a44 block: fix lockdep warning caused by lock dependency in elv_iosched_store
49811586be37 block: move elevator queue allocation logic into blk_mq_init_sched
5989bfe6ac6b block: restore two stage elevator switch while running nr_hw_queue update
1966554b2e82 block: fix module reference leak in mq-deadline I/O scheduler
532b9e11b854 block: fix elv_update_nr_hw_queues() to reattach elevator
78c271344b6f block: move wbt_enable_default() out of queue freezing from sched ->exit()
559dc11143eb block: move elv_register[unregister]_queue out of elevator_lock
21eed794ab4b block: add new helper for disabling elevator switch when deleting disk
5c3d858cdc57 block: fail to show/store elevator sysfs attribute if elevator is dying
e25ee50dfab9 block: remove elevator queue's type check in elv_attr_show/store()
a3dc6279c2d5 block: pass elevator_queue to elv_register_queue & unregister_queue
]
|
| 69/2 |
2026/11/03 15:12 |
llm |
debugger |
0m
Model:
Tokens:
input: 49152
output: 103
thoughts: 90
Thoughts: Okay, here's my take on those thoughts, framed for my expert perspective:
**Debugging a Potentially Deadly Disk Issue**
Wait a second! Something just clicked. I need to take a closer look at a specific commit: `7e9a46004b47`. Why? Because the commit message itself β "block: set QUEUE_FLAG_DYING unconditionally in blk_mark_disk_dead()" β is screaming potential problems. Unconditionally marking a queue as dyingβ¦ that sounds like it could have some pretty significant, and potentially unexpected, consequences for the block layer. This could be where the rubber meets the road.
My immediate next step is to dive right into the code for that commit. I'm going to carefully inspect the changes introduced by `7e9a46004b47` to understand exactly how `QUEUE_FLAG_DYING` is being set and what implications that has for the overall system. I need to see the context.
Beyond that, I also need to get a handle on the history of this piece of the kernel, specifically, I'm going to use `git blame` on `blk_freeze_set_owner`. This will help me understand how this code evolved, who's been working on it, and what their intentions were. That's a good first step to help understand the scope of impact and if other pieces of code are affected by this commit. The combination of these two examinations should point me in the right direction.
|
| 70/2 |
2026/11/03 15:12 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 7e9a46004b471eaf69b082c473d865316a4158e0
Author: θ‘θΏε€ <hulianqin@vivo.com>
Date: Wed Aug 12 11:59:04 2026 +0000
block: set QUEUE_FLAG_DYING unconditionally in blk_mark_disk_dead()
Disks created via blk_mq_alloc_disk_for_queue() (e.g. SCSI SD disks)
do not have GD_OWNS_QUEUE set. Currently __blk_mark_disk_dead() only
sets QUEUE_FLAG_DYING when GD_OWNS_QUEUE is set, so for such disks
blk_queue_enter() and __bio_queue_enter() cannot detect the dying
state via blk_queue_dying() and remain blocked waiting for I/O that
will never complete after surprise removal.
blk_mark_disk_dead() is the explicit "surprise removal" API -- the
caller has already decided the disk is dead. Setting QUEUE_FLAG_DYING
unconditionally here is appropriate: any in-flight I/O from other
threads should get -ENODEV immediately from blk_queue_enter()
regardless of GD_OWNS_QUEUE ownership.
For disks that already have GD_OWNS_QUEUE set, __blk_mark_disk_dead()
will set the flag again which is harmless.
Fixes: 6f8191fdf41d ("block: simplify disk shutdown")
Cc: stable@vger.kernel.org
Signed-off-by: Lianqin Hu <hulianqin@vivo.com>
Reviewed-by: Christoph Hellwig <hch@lst.de>
Link: https://patch.msgid.link/PUZPR06MB62247E82E66A3ED46CC3E6C7D2DC2@PUZPR06MB6224.apcprd06.prod.outlook.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/genhd.c b/block/genhd.c
index df2c3c69b467..7b089e2d52c4 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -681,6 +681,7 @@ static bool __blk_mark_disk_dead(struct gendisk *disk)
*/
void blk_mark_disk_dead(struct gendisk *disk)
{
+ blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
__blk_mark_disk_dead(disk);
blk_report_disk_dead(disk, true);
}
]
|
| 71/2 |
2026/11/03 15:12 |
tool |
git-blame |
0m
Args: map[End:150 File:block/blk-mq.c Start:115]
Results: map[Output:6a78699838a0d 115) #ifdef CONFIG_LOCKDEP
6a78699838a0d 116) static bool blk_freeze_set_owner(struct request_queue *q,
6a78699838a0d 117) struct task_struct *owner)
43a5e4e21964a 118) {
6a78699838a0d 119) if (!owner)
6a78699838a0d 120) return false;
6a78699838a0d 121)
6a78699838a0d 122) if (!q->mq_freeze_depth) {
6a78699838a0d 123) q->mq_freeze_owner = owner;
6a78699838a0d 124) q->mq_freeze_owner_depth = 1;
6f491a8d4b92d 125) q->mq_freeze_disk_dead = !q->disk ||
6f491a8d4b92d 126) test_bit(GD_DEAD, &q->disk->state) ||
6f491a8d4b92d 127) !blk_queue_registered(q);
f6661b1d0525f 128) q->mq_freeze_queue_dying = blk_queue_dying(q);
6a78699838a0d 129) return true;
6a78699838a0d 130) }
6a78699838a0d 131)
6a78699838a0d 132) if (owner == q->mq_freeze_owner)
6a78699838a0d 133) q->mq_freeze_owner_depth += 1;
6a78699838a0d 134) return false;
6a78699838a0d 135) }
6a78699838a0d 136)
6a78699838a0d 137) /* verify the last unfreeze in owner context */
6a78699838a0d 138) static bool blk_unfreeze_check_owner(struct request_queue *q)
6a78699838a0d 139) {
6a78699838a0d 140) if (q->mq_freeze_owner != current)
6a78699838a0d 141) return false;
6a78699838a0d 142) if (--q->mq_freeze_owner_depth == 0) {
6a78699838a0d 143) q->mq_freeze_owner = NULL;
6a78699838a0d 144) return true;
6a78699838a0d 145) }
6a78699838a0d 146) return false;
6a78699838a0d 147) }
6a78699838a0d 148)
6a78699838a0d 149) #else
6a78699838a0d 150)
]
|
| 72/2 |
2026/11/03 15:12 |
tool |
git-blame |
0m
Args: map[End:800 File:block/blk.h Start:780]
Results: map[Output:6f491a8d4b92d 780) #ifdef CONFIG_LOCKDEP
f6661b1d0525f 781) static inline void blk_freeze_acquire_lock(struct request_queue *q)
f1be1788a32e8 782) {
6f491a8d4b92d 783) if (!q->mq_freeze_disk_dead)
f1be1788a32e8 784) rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
f6661b1d0525f 785) if (!q->mq_freeze_queue_dying)
f1be1788a32e8 786) rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
f1be1788a32e8 787) }
f1be1788a32e8 788)
f6661b1d0525f 789) static inline void blk_unfreeze_release_lock(struct request_queue *q)
f1be1788a32e8 790) {
f6661b1d0525f 791) if (!q->mq_freeze_queue_dying)
f1be1788a32e8 792) rwsem_release(&q->q_lockdep_map, _RET_IP_);
6f491a8d4b92d 793) if (!q->mq_freeze_disk_dead)
f1be1788a32e8 794) rwsem_release(&q->io_lockdep_map, _RET_IP_);
f1be1788a32e8 795) }
6f491a8d4b92d 796) #else
f6661b1d0525f 797) static inline void blk_freeze_acquire_lock(struct request_queue *q)
6f491a8d4b92d 798) {
6f491a8d4b92d 799) }
f6661b1d0525f 800) static inline void blk_unfreeze_release_lock(struct request_queue *q)
]
|
| 73/2 |
2026/11/03 15:12 |
llm |
debugger |
0m
Model:
Tokens:
input: 51702
output: 123
thoughts: 65
Thoughts: Here's the summary, tailored for an expert audience:
**Commit Analysis Kickoff**
Okay, time to dive in. I need to get a clear picture of recent changes, so let's start by scrutinizing commits `f6661b1d0525f`, `6f491a8d4b92d`, `6a78699838a0d`, and `f1be1788a32e8`. I'll be looking for potential impact across the system, any architectural shifts, and of course, any code quality implications. I'll probably start with a `git diff` for a quick overview before drilling down into the details of the changed files. I'm expecting some specific patterns to emerge based on their commit messages, and I need to be prepared to identify and understand them quickly. Let's get to work.
|
| 74/2 |
2026/11/03 15:12 |
tool |
git-show |
0m
Args: map[Commit:f6661b1d0525f]
Results: map[Output:commit f6661b1d0525f3764596a1b65eeed9e75aecafa7
Author: Ming Lei <ming.lei@redhat.com>
Date: Wed Nov 27 21:51:30 2024 +0800
block: track queue dying state automatically for modeling queue freeze lockdep
Now we only verify the outmost freeze & unfreeze in current context in case
that !q->mq_freeze_depth, so it is reliable to save queue lying state when
we want to lock the freeze queue since the state is one per-task variable
now.
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241127135133.3952153-5-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 0c6a319fb936..fca2ec64a06b 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -134,6 +134,7 @@ static bool blk_freeze_set_owner(struct request_queue *q,
q->mq_freeze_disk_dead = !q->disk ||
test_bit(GD_DEAD, &q->disk->state) ||
!blk_queue_registered(q);
+ q->mq_freeze_queue_dying = blk_queue_dying(q);
return true;
}
@@ -190,7 +191,7 @@ bool __blk_freeze_queue_start(struct request_queue *q,
void blk_freeze_queue_start(struct request_queue *q)
{
if (__blk_freeze_queue_start(q, current))
- blk_freeze_acquire_lock(q, false);
+ blk_freeze_acquire_lock(q);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -238,7 +239,7 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
void blk_mq_unfreeze_queue(struct request_queue *q)
{
if (__blk_mq_unfreeze_queue(q, false))
- blk_unfreeze_release_lock(q, false);
+ blk_unfreeze_release_lock(q);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
diff --git a/block/blk.h b/block/blk.h
index 8708168d50e4..cbf6a676ffe9 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -721,26 +721,26 @@ void blk_integrity_prepare(struct request *rq);
void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
#ifdef CONFIG_LOCKDEP
-static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
- if (!queue_dying)
+ if (!q->mq_freeze_queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
- if (!queue_dying)
+ if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
#else
-static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
}
#endif
diff --git a/block/genhd.c b/block/genhd.c
index 59ac299909b3..5678194b6b1a 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -661,7 +661,7 @@ void del_gendisk(struct gendisk *disk)
struct request_queue *q = disk->queue;
struct block_device *part;
unsigned long idx;
- bool start_drain, queue_dying;
+ bool start_drain;
might_sleep();
@@ -690,9 +690,8 @@ void del_gendisk(struct gendisk *disk)
*/
mutex_lock(&disk->open_mutex);
start_drain = __blk_mark_disk_dead(disk);
- queue_dying = blk_queue_dying(q);
if (start_drain)
- blk_freeze_acquire_lock(q, queue_dying);
+ blk_freeze_acquire_lock(q);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
@@ -748,7 +747,7 @@ void del_gendisk(struct gendisk *disk)
blk_mq_exit_queue(q);
if (start_drain)
- blk_unfreeze_release_lock(q, queue_dying);
+ blk_unfreeze_release_lock(q);
}
EXPORT_SYMBOL(del_gendisk);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 522cf8eef66c..5d40af2ef971 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -581,8 +581,12 @@ struct request_queue {
#ifdef CONFIG_LOCKDEP
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
- /* Records disk state in current context, used in unfreeze queue */
+ /*
+ * Records disk & queue state in current context, used in unfreeze
+ * queue
+ */
bool mq_freeze_disk_dead;
+ bool mq_freeze_queue_dying;
#endif
wait_queue_head_t mq_freeze_wq;
/*
]
|
| 75/2 |
2026/11/03 15:12 |
tool |
git-show |
0m
Args: map[Commit:6f491a8d4b92d]
Results: map[Output:commit 6f491a8d4b92d1a840fd9209cba783c84437d0b7
Author: Ming Lei <ming.lei@redhat.com>
Date: Wed Nov 27 21:51:28 2024 +0800
block: track disk DEAD state automatically for modeling queue freeze lockdep
Now we only verify the outmost freeze & unfreeze in current context in case
that !q->mq_freeze_depth, so it is reliable to save disk DEAD state when
we want to lock the freeze queue since the state is one per-task variable
now.
Doing this way can kill lots of false positive when freeze queue is
called before adding disk[1].
[1] https://lore.kernel.org/linux-block/6741f6b2.050a0220.1cc393.0017.GAE@google.com/
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241127135133.3952153-3-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 60f457f62913..0c6a319fb936 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -131,6 +131,9 @@ static bool blk_freeze_set_owner(struct request_queue *q,
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
+ q->mq_freeze_disk_dead = !q->disk ||
+ test_bit(GD_DEAD, &q->disk->state) ||
+ !blk_queue_registered(q);
return true;
}
@@ -187,7 +190,7 @@ bool __blk_freeze_queue_start(struct request_queue *q,
void blk_freeze_queue_start(struct request_queue *q)
{
if (__blk_freeze_queue_start(q, current))
- blk_freeze_acquire_lock(q, false, false);
+ blk_freeze_acquire_lock(q, false);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -235,7 +238,7 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
void blk_mq_unfreeze_queue(struct request_queue *q)
{
if (__blk_mq_unfreeze_queue(q, false))
- blk_unfreeze_release_lock(q, false, false);
+ blk_unfreeze_release_lock(q, false);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
diff --git a/block/blk.h b/block/blk.h
index 2c26abf505b8..8708168d50e4 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -720,22 +720,29 @@ void blk_integrity_verify(struct bio *bio);
void blk_integrity_prepare(struct request *rq);
void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
-static inline void blk_freeze_acquire_lock(struct request_queue *q, bool
- disk_dead, bool queue_dying)
+#ifdef CONFIG_LOCKDEP
+static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
{
- if (!disk_dead)
+ if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
if (!queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q, bool
- disk_dead, bool queue_dying)
+static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
{
if (!queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
- if (!disk_dead)
+ if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
+#else
+static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
+{
+}
+static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
+{
+}
+#endif
#endif /* BLK_INTERNAL_H */
diff --git a/block/elevator.c b/block/elevator.c
index 7c3ba80e5ff4..ca0a74369f1c 100644
--- a/block/elevator.c
+++ b/block/elevator.c
@@ -602,14 +602,14 @@ void elevator_init_mq(struct request_queue *q)
* Disk isn't added yet, so verifying queue lock only manually.
*/
blk_freeze_queue_start_non_owner(q);
- blk_freeze_acquire_lock(q, true, false);
+ blk_freeze_acquire_lock(q, false);
blk_mq_freeze_queue_wait(q);
blk_mq_cancel_work_sync(q);
err = blk_mq_init_sched(q, e);
- blk_unfreeze_release_lock(q, true, false);
+ blk_unfreeze_release_lock(q, false);
blk_mq_unfreeze_queue_non_owner(q);
if (err) {
diff --git a/block/genhd.c b/block/genhd.c
index 79230c109fca..59ac299909b3 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -692,7 +692,7 @@ void del_gendisk(struct gendisk *disk)
start_drain = __blk_mark_disk_dead(disk);
queue_dying = blk_queue_dying(q);
if (start_drain)
- blk_freeze_acquire_lock(q, true, queue_dying);
+ blk_freeze_acquire_lock(q, queue_dying);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
@@ -748,7 +748,7 @@ void del_gendisk(struct gendisk *disk)
blk_mq_exit_queue(q);
if (start_drain)
- blk_unfreeze_release_lock(q, true, queue_dying);
+ blk_unfreeze_release_lock(q, queue_dying);
}
EXPORT_SYMBOL(del_gendisk);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 378d3a1a22fc..522cf8eef66c 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -581,6 +581,8 @@ struct request_queue {
#ifdef CONFIG_LOCKDEP
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
+ /* Records disk state in current context, used in unfreeze queue */
+ bool mq_freeze_disk_dead;
#endif
wait_queue_head_t mq_freeze_wq;
/*
]
|
| 76/2 |
2026/11/03 15:12 |
tool |
git-show |
0m
Args: map[Commit:6a78699838a0d]
Results: map[Output:commit 6a78699838a0ddeed3620ddf50c1521f1fe1e811
Author: Ming Lei <ming.lei@redhat.com>
Date: Thu Oct 31 21:37:19 2024 +0800
block: always verify unfreeze lock on the owner task
commit f1be1788a32e ("block: model freeze & enter queue as lock for
supporting lockdep") tries to apply lockdep for verifying freeze &
unfreeze. However, the verification is only done the outmost freeze and
unfreeze. This way is actually not correct because q->mq_freeze_depth
still may drop to zero on other task instead of the freeze owner task.
Fix this issue by always verifying the last unfreeze lock on the owner
task context, and make sure both the outmost freeze & unfreeze are
verified in the current task.
Fixes: f1be1788a32e ("block: model freeze & enter queue as lock for supporting lockdep")
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241031133723.303835-4-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-core.c b/block/blk-core.c
index 09d10bb95fda..4f791a3114a1 100644
--- a/block/blk-core.c
+++ b/block/blk-core.c
@@ -287,7 +287,7 @@ bool blk_queue_start_drain(struct request_queue *q)
* entering queue, so we call blk_freeze_queue_start() to
* prevent I/O from crossing blk_queue_enter().
*/
- bool freeze = __blk_freeze_queue_start(q);
+ bool freeze = __blk_freeze_queue_start(q, current);
if (queue_is_mq(q))
blk_mq_wake_waiters(q);
/* Make blk_queue_enter() reexamine the DYING flag. */
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 5f4496220432..5e240a4b6be0 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -120,20 +120,66 @@ void blk_mq_in_flight_rw(struct request_queue *q, struct block_device *part,
inflight[1] = mi.inflight[1];
}
-bool __blk_freeze_queue_start(struct request_queue *q)
+#ifdef CONFIG_LOCKDEP
+static bool blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
{
- int freeze;
+ if (!owner)
+ return false;
+
+ if (!q->mq_freeze_depth) {
+ q->mq_freeze_owner = owner;
+ q->mq_freeze_owner_depth = 1;
+ return true;
+ }
+
+ if (owner == q->mq_freeze_owner)
+ q->mq_freeze_owner_depth += 1;
+ return false;
+}
+
+/* verify the last unfreeze in owner context */
+static bool blk_unfreeze_check_owner(struct request_queue *q)
+{
+ if (!q->mq_freeze_owner)
+ return false;
+ if (q->mq_freeze_owner != current)
+ return false;
+ if (--q->mq_freeze_owner_depth == 0) {
+ q->mq_freeze_owner = NULL;
+ return true;
+ }
+ return false;
+}
+
+#else
+
+static bool blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
+{
+ return false;
+}
+
+static bool blk_unfreeze_check_owner(struct request_queue *q)
+{
+ return false;
+}
+#endif
+
+bool __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner)
+{
+ bool freeze;
mutex_lock(&q->mq_freeze_lock);
+ freeze = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
if (queue_is_mq(q))
blk_mq_run_hw_queues(q, false);
- freeze = true;
} else {
mutex_unlock(&q->mq_freeze_lock);
- freeze = false;
}
return freeze;
@@ -141,7 +187,7 @@ bool __blk_freeze_queue_start(struct request_queue *q)
void blk_freeze_queue_start(struct request_queue *q)
{
- if (__blk_freeze_queue_start(q))
+ if (__blk_freeze_queue_start(q, current))
blk_freeze_acquire_lock(q, false, false);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -170,7 +216,7 @@ EXPORT_SYMBOL_GPL(blk_mq_freeze_queue);
bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
- int unfreeze = false;
+ bool unfreeze;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
@@ -180,8 +226,8 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
if (!q->mq_freeze_depth) {
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
- unfreeze = true;
}
+ unfreeze = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
return unfreeze;
@@ -203,7 +249,7 @@ EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
*/
void blk_freeze_queue_start_non_owner(struct request_queue *q)
{
- __blk_freeze_queue_start(q);
+ __blk_freeze_queue_start(q, NULL);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start_non_owner);
diff --git a/block/blk.h b/block/blk.h
index ac48b79cbf80..57fc035620d6 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -37,7 +37,8 @@ void blk_free_flush_queue(struct blk_flush_queue *q);
bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
bool blk_queue_start_drain(struct request_queue *q);
-bool __blk_freeze_queue_start(struct request_queue *q);
+bool __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner);
int __bio_queue_enter(struct request_queue *q, struct bio *bio);
void submit_bio_noacct_nocheck(struct bio *bio);
void bio_await_chain(struct bio *bio);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 93551772c1d6..1b51a7c92e9b 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -575,6 +575,10 @@ struct request_queue {
struct throtl_data *td;
#endif
struct rcu_head rcu_head;
+#ifdef CONFIG_LOCKDEP
+ struct task_struct *mq_freeze_owner;
+ int mq_freeze_owner_depth;
+#endif
wait_queue_head_t mq_freeze_wq;
/*
* Protect concurrent access to q_usage_counter by
]
|
| 77/2 |
2026/11/03 15:12 |
tool |
git-show |
0m
Args: map[Commit:f1be1788a32e8]
Results: map[Output:commit f1be1788a32e8fa63416ad4518bbd1a85a825c9d
Author: Ming Lei <ming.lei@redhat.com>
Date: Fri Oct 25 08:37:20 2024 +0800
block: model freeze & enter queue as lock for supporting lockdep
Recently we got several deadlock report[1][2][3] caused by
blk_mq_freeze_queue and blk_enter_queue().
Turns out the two are just like acquiring read/write lock, so model them
as read/write lock for supporting lockdep:
1) model q->q_usage_counter as two locks(io and queue lock)
- queue lock covers sync with blk_enter_queue()
- io lock covers sync with bio_enter_queue()
2) make the lockdep class/key as per-queue:
- different subsystem has very different lock use pattern, shared lock
class causes false positive easily
- freeze_queue degrades to no lock in case that disk state becomes DEAD
because bio_enter_queue() won't be blocked any more
- freeze_queue degrades to no lock in case that request queue becomes dying
because blk_enter_queue() won't be blocked any more
3) model blk_mq_freeze_queue() as acquire_exclusive & try_lock
- it is exclusive lock, so dependency with blk_enter_queue() is covered
- it is trylock because blk_mq_freeze_queue() are allowed to run
concurrently
4) model blk_enter_queue() & bio_enter_queue() as acquire_read()
- nested blk_enter_queue() are allowed
- dependency with blk_mq_freeze_queue() is covered
- blk_queue_exit() is often called from other contexts(such as irq), and
it can't be annotated as lock_release(), so simply do it in
blk_enter_queue(), this way still covered cases as many as possible
With lockdep support, such kind of reports may be reported asap and
needn't wait until the real deadlock is triggered.
For example, lockdep report can be triggered in the report[3] with this
patch applied.
[1] occasional block layer hang when setting 'echo noop > /sys/block/sda/queue/scheduler'
https://bugzilla.kernel.org/show_bug.cgi?id=219166
[2] del_gendisk() vs blk_queue_enter() race condition
https://lore.kernel.org/linux-block/20241003085610.GK11458@google.com/
[3] queue_freeze & queue_enter deadlock in scsi
https://lore.kernel.org/linux-block/ZxG38G9BuFdBpBHZ@fedora/T/#u
Reviewed-by: Christoph Hellwig <hch@lst.de>
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241025003722.3630252-4-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-core.c b/block/blk-core.c
index bc5e8c5eaac9..09d10bb95fda 100644
--- a/block/blk-core.c
+++ b/block/blk-core.c
@@ -261,6 +261,8 @@ static void blk_free_queue(struct request_queue *q)
blk_mq_release(q);
ida_free(&blk_queue_ida, q->id);
+ lockdep_unregister_key(&q->io_lock_cls_key);
+ lockdep_unregister_key(&q->q_lock_cls_key);
call_rcu(&q->rcu_head, blk_free_queue_rcu);
}
@@ -278,18 +280,20 @@ void blk_put_queue(struct request_queue *q)
}
EXPORT_SYMBOL(blk_put_queue);
-void blk_queue_start_drain(struct request_queue *q)
+bool blk_queue_start_drain(struct request_queue *q)
{
/*
* When queue DYING flag is set, we need to block new req
* entering queue, so we call blk_freeze_queue_start() to
* prevent I/O from crossing blk_queue_enter().
*/
- blk_freeze_queue_start(q);
+ bool freeze = __blk_freeze_queue_start(q);
if (queue_is_mq(q))
blk_mq_wake_waiters(q);
/* Make blk_queue_enter() reexamine the DYING flag. */
wake_up_all(&q->mq_freeze_wq);
+
+ return freeze;
}
/**
@@ -321,6 +325,8 @@ int blk_queue_enter(struct request_queue *q, blk_mq_req_flags_t flags)
return -ENODEV;
}
+ rwsem_acquire_read(&q->q_lockdep_map, 0, 0, _RET_IP_);
+ rwsem_release(&q->q_lockdep_map, _RET_IP_);
return 0;
}
@@ -352,6 +358,8 @@ int __bio_queue_enter(struct request_queue *q, struct bio *bio)
goto dead;
}
+ rwsem_acquire_read(&q->io_lockdep_map, 0, 0, _RET_IP_);
+ rwsem_release(&q->io_lockdep_map, _RET_IP_);
return 0;
dead:
bio_io_error(bio);
@@ -441,6 +449,12 @@ struct request_queue *blk_alloc_queue(struct queue_limits *lim, int node_id)
PERCPU_REF_INIT_ATOMIC, GFP_KERNEL);
if (error)
goto fail_stats;
+ lockdep_register_key(&q->io_lock_cls_key);
+ lockdep_register_key(&q->q_lock_cls_key);
+ lockdep_init_map(&q->io_lockdep_map, "&q->q_usage_counter(io)",
+ &q->io_lock_cls_key, 0);
+ lockdep_init_map(&q->q_lockdep_map, "&q->q_usage_counter(queue)",
+ &q->q_lock_cls_key, 0);
q->nr_requests = BLKDEV_DEFAULT_RQ;
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 770276815507..4ae7eb335fbd 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -120,17 +120,29 @@ void blk_mq_in_flight_rw(struct request_queue *q, struct block_device *part,
inflight[1] = mi.inflight[1];
}
-void blk_freeze_queue_start(struct request_queue *q)
+bool __blk_freeze_queue_start(struct request_queue *q)
{
+ int freeze;
+
mutex_lock(&q->mq_freeze_lock);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
if (queue_is_mq(q))
blk_mq_run_hw_queues(q, false);
+ freeze = true;
} else {
mutex_unlock(&q->mq_freeze_lock);
+ freeze = false;
}
+
+ return freeze;
+}
+
+void blk_freeze_queue_start(struct request_queue *q)
+{
+ if (__blk_freeze_queue_start(q))
+ blk_freeze_acquire_lock(q, false, false);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -176,8 +188,10 @@ void blk_mq_freeze_queue(struct request_queue *q)
}
EXPORT_SYMBOL_GPL(blk_mq_freeze_queue);
-void __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
+bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
+ int unfreeze = false;
+
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
q->q_usage_counter.data->force_atomic = true;
@@ -186,13 +200,17 @@ void __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
if (!q->mq_freeze_depth) {
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
+ unfreeze = true;
}
mutex_unlock(&q->mq_freeze_lock);
+
+ return unfreeze;
}
void blk_mq_unfreeze_queue(struct request_queue *q)
{
- __blk_mq_unfreeze_queue(q, false);
+ if (__blk_mq_unfreeze_queue(q, false))
+ blk_unfreeze_release_lock(q, false, false);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
@@ -205,7 +223,7 @@ EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
*/
void blk_freeze_queue_start_non_owner(struct request_queue *q)
{
- blk_freeze_queue_start(q);
+ __blk_freeze_queue_start(q);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start_non_owner);
diff --git a/block/blk.h b/block/blk.h
index 8fddaf6eae49..63d5df0dc29c 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -4,6 +4,7 @@
#include <linux/bio-integrity.h>
#include <linux/blk-crypto.h>
+#include <linux/lockdep.h>
#include <linux/memblock.h> /* for max_pfn/max_low_pfn */
#include <linux/sched/sysctl.h>
#include <linux/timekeeping.h>
@@ -35,8 +36,9 @@ struct blk_flush_queue *blk_alloc_flush_queue(int node, int cmd_size,
void blk_free_flush_queue(struct blk_flush_queue *q);
void blk_freeze_queue(struct request_queue *q);
-void __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
-void blk_queue_start_drain(struct request_queue *q);
+bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
+bool blk_queue_start_drain(struct request_queue *q);
+bool __blk_freeze_queue_start(struct request_queue *q);
int __bio_queue_enter(struct request_queue *q, struct bio *bio);
void submit_bio_noacct_nocheck(struct bio *bio);
void bio_await_chain(struct bio *bio);
@@ -69,8 +71,11 @@ static inline int bio_queue_enter(struct bio *bio)
{
struct request_queue *q = bdev_get_queue(bio->bi_bdev);
- if (blk_try_enter_queue(q, false))
+ if (blk_try_enter_queue(q, false)) {
+ rwsem_acquire_read(&q->io_lockdep_map, 0, 0, _RET_IP_);
+ rwsem_release(&q->io_lockdep_map, _RET_IP_);
return 0;
+ }
return __bio_queue_enter(q, bio);
}
@@ -724,4 +729,22 @@ void blk_integrity_verify(struct bio *bio);
void blk_integrity_prepare(struct request *rq);
void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
+static inline void blk_freeze_acquire_lock(struct request_queue *q, bool
+ disk_dead, bool queue_dying)
+{
+ if (!disk_dead)
+ rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
+ if (!queue_dying)
+ rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
+}
+
+static inline void blk_unfreeze_release_lock(struct request_queue *q, bool
+ disk_dead, bool queue_dying)
+{
+ if (!queue_dying)
+ rwsem_release(&q->q_lockdep_map, _RET_IP_);
+ if (!disk_dead)
+ rwsem_release(&q->io_lockdep_map, _RET_IP_);
+}
+
#endif /* BLK_INTERNAL_H */
diff --git a/block/genhd.c b/block/genhd.c
index bc30eee7ab16..dfee66146bd1 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -601,13 +601,13 @@ static void blk_report_disk_dead(struct gendisk *disk, bool surprise)
rcu_read_unlock();
}
-static void __blk_mark_disk_dead(struct gendisk *disk)
+static bool __blk_mark_disk_dead(struct gendisk *disk)
{
/*
* Fail any new I/O.
*/
if (test_and_set_bit(GD_DEAD, &disk->state))
- return;
+ return false;
if (test_bit(GD_OWNS_QUEUE, &disk->state))
blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
@@ -620,7 +620,7 @@ static void __blk_mark_disk_dead(struct gendisk *disk)
/*
* Prevent new I/O from crossing bio_queue_enter().
*/
- blk_queue_start_drain(disk->queue);
+ return blk_queue_start_drain(disk->queue);
}
/**
@@ -661,6 +661,7 @@ void del_gendisk(struct gendisk *disk)
struct request_queue *q = disk->queue;
struct block_device *part;
unsigned long idx;
+ bool start_drain, queue_dying;
might_sleep();
@@ -688,7 +689,10 @@ void del_gendisk(struct gendisk *disk)
* Drop all partitions now that the disk is marked dead.
*/
mutex_lock(&disk->open_mutex);
- __blk_mark_disk_dead(disk);
+ start_drain = __blk_mark_disk_dead(disk);
+ queue_dying = blk_queue_dying(q);
+ if (start_drain)
+ blk_freeze_acquire_lock(q, true, queue_dying);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
@@ -745,6 +749,9 @@ void del_gendisk(struct gendisk *disk)
if (queue_is_mq(q))
blk_mq_exit_queue(q);
}
+
+ if (start_drain)
+ blk_unfreeze_release_lock(q, true, queue_dying);
}
EXPORT_SYMBOL(del_gendisk);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 55bec14fe55f..d0a52ed05e60 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -25,6 +25,7 @@
#include <linux/uuid.h>
#include <linux/xarray.h>
#include <linux/file.h>
+#include <linux/lockdep.h>
struct module;
struct request_queue;
@@ -474,6 +475,11 @@ struct request_queue {
struct xarray hctx_table;
struct percpu_ref q_usage_counter;
+ struct lock_class_key io_lock_cls_key;
+ struct lockdep_map io_lockdep_map;
+
+ struct lock_class_key q_lock_cls_key;
+ struct lockdep_map q_lockdep_map;
struct request *last_merge;
]
|
| 78/2 |
2026/11/03 15:12 |
llm |
debugger |
0m
Model:
Tokens:
input: 62615
output: 38
thoughts: 1775
Thoughts: **Deep Dive into Block Layer Queue Freezing**
Okay, BINGO! I think I'm onto something. Let's dig into this. I need to understand the interaction between `blk_mark_disk_dead` and the queue freezing mechanisms, specifically when we compare this to `__del_gendisk` and how `blk_freeze_set_owner` plays into all this. Let's trace it through. The key question is, what happens when `blk_mark_disk_dead` is called when the `q->mq_freeze_depth` is zero?
So, first, `blk_mark_disk_dead` calls `__blk_mark_disk_dead`. This, in turn, calls `blk_queue_start_drain`. `blk_queue_start_drain` then calls `__blk_freeze_queue_start`. Let's see what *that* function does.
Inside `__blk_freeze_queue_start`, if `q->mq_freeze_depth` is zero, `blk_freeze_set_owner(q, current)` is run. This sets the `q->mq_freeze_owner` to the current task, `q->mq_freeze_owner_depth` to 1, and also sets `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying` to `true`. Crucially, this function returns `true`, and then the depth is incremented.
Here's the problem: `blk_mark_disk_dead` *ignores* the return value of `__blk_mark_disk_dead`. The queue is permanently drained, but, because `blk_queue_start_drain` does not call `blk_freeze_acquire_lock` (because `blk_mark_disk_dead` doesn't call `blk_freeze_acquire_lock`, which isn't used), the queue remains frozen, and the freeze owner, depth, and other associated flags are left in place and unchanged.
Now, let's consider `elevator_change`. Why did `elevator_change` acquire the queue's usage counter? And then, what would happen?
If `q->mq_freeze_depth` was already 1 before `elevator_change`, then in the call to `blk_freeze_set_owner` inside `elevator_change`, the depth would be checked. Therefore, that must mean that `q->mq_freeze_depth` was 0 when `elevator_change` called `blk_mq_freeze_queue(q)`.
If `q->mq_freeze_depth` was 0, then, at `elevator_change:668`:
`memflags = blk_mq_freeze_queue(q)`:
- `q->mq_freeze_depth` was 0!
- `blk_freeze_set_owner(q, current)` returned `true`!
- `q->mq_freeze_owner = current` (the current syz task)
- `q->mq_freeze_owner_depth = 1`
- `q->mq_freeze_queue_dying` was `false` (because `blk_freeze_acquire_lock` DID acquire the queue usage counter)
- `++q->mq_freeze_depth` became 1!
- `blk_freeze_acquire_lock(q)` called `rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_)`!
Okay, so the depth is 1, a lock has been acquired and an owner set. Now, the question is, why does `blk_mq_unfreeze_queue(q, memflags)` at `elevator_change:683` *not* release the lock `q->q_lockdep_map`?!
Let's carefully examine the code within `elevator_change`, between the calls to `blk_mq_freeze_queue` and `blk_mq_unfreeze_queue`:
In `elevator_change` from lines 668 to 683, between `blk_mq_freeze_queue(q)` and `blk_mq_unfreeze_queue(q, memflags)`, there are these calls:
- `blk_mq_cancel_work_sync(q)`
- `elevator_switch(q, ctx)`
I need to look at `elevator_switch` to see if *it* is involved!
|
| 79/2 |
2026/11/03 15:12 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/elevator.c Name:elevator_switch]
Results: map[SourceCode: 556: /*
557: * Switch to new_e io scheduler.
558: *
559: * If switching fails, we are most likely running out of memory and not able
560: * to restore the old io scheduler, so leaving the io scheduler being none.
561: */
562: static int elevator_switch(struct request_queue *q, struct elv_change_ctx *ctx)
563: {
564: struct elevator_type *new_e = NULL;
565: int ret = 0;
566:
567: WARN_ON_ONCE(q->mq_freeze_depth == 0);
568: lockdep_assert_held(&q->elevator_lock);
569:
570: if (strncmp(ctx->name, "none", 4)) {
571: new_e = elevator_find_get(ctx->name);
572: if (!new_e)
573: return -EINVAL;
574: }
575:
576: blk_mq_quiesce_queue(q);
577:
578: if (q->elevator) {
579: ctx->old = q->elevator;
580: elevator_exit(q);
581: }
582:
583: if (new_e) {
584: ret = blk_mq_init_sched(q, new_e, &ctx->res);
585: if (ret)
586: goto out_unfreeze;
587: ctx->new = q->elevator;
588: } else {
589: blk_queue_flag_clear(QUEUE_FLAG_SQ_SCHED, q);
590: q->elevator = NULL;
591: q->nr_requests = q->tag_set->queue_depth;
592: q->async_depth = q->tag_set->queue_depth;
593: }
594: blk_add_trace_msg(q, "elv switch: %s", ctx->name);
595:
596: out_unfreeze:
597: blk_mq_unquiesce_queue(q);
598:
599: if (ret) {
600: pr_warn("elv: switch to \"%s\" failed, falling back to \"none\"\n",
601: new_e->elevator_name);
602: }
603:
604: if (new_e)
605: elevator_put(new_e);
606: return ret;
607: }
SourceFile:block/elevator.c]
|
| 80/2 |
2026/11/03 15:12 |
llm |
debugger |
0m
Model:
Tokens:
input: 65211
output: 158
thoughts: 13186
Thoughts: **Analyzing a Race Condition in the Block Layer**
Okay, here's how I see this, as an expert in this area. I'm focusing on a race condition within the block layer, specifically within the `elevator_change` function and its interaction with queue freezing/unfreezing mechanisms. This analysis relies heavily on the call stacks provided, the lockdep output, and the potential interactions between threads.
My concern stems from a potential mismatch between acquiring and releasing a critical lock, `q->q_lockdep_map`, which controls queue usage. The core issue lies in the sequence within `elevator_change`:
1. We call `blk_mq_freeze_queue(q)` (at line 668), which acquires the `q->q_lockdep_map`.
2. Some other operations happen (including calls to `blk_mq_cancel_work_sync(q)`, locking the elevator, potential elevator switching, etc.).
3. We call `blk_mq_unfreeze_queue(q, memflags)` (at line 683), which should release the `q->q_lockdep_map`.
The key question is why the lock is *held* on return to user space and the kernel reports a lock leak.
I initially looked at the internals of `blk_mq_freeze_queue` and `blk_mq_unfreeze_queue`. It's clear that these functions use `blk_freeze_acquire_lock` and `blk_unfreeze_release_lock`, which involve `rwsem_acquire` and `rwsem_release` on `q->q_lockdep_map`. I meticulously traced the execution paths and found that if `blk_freeze_acquire_lock(q)` is called, `blk_freeze_set_owner` must return true, and that, in turn, depends on the `q->mq_freeze_depth` being initially 0 and `q->mq_freeze_queue_dying` being false. I confirmed these things.
After tracing the entire flow, the most important revelation is that `blk_mark_disk_dead` runs concurrently with `elevator_change`. It sets `q->mq_freeze_queue_dying = true` which causes a race. Specifically, `blk_mark_disk_dead` can be called while `elevator_change` is in flight. If Thread 1 is running `elevator_change` with `q->mq_freeze_queue_dying = false`, another thread, Thread 2, calls `blk_mark_disk_dead` which sets `q->mq_freeze_queue_dying = true`, and then Thread 1 *won't* release the lock when `blk_unfreeze_release_lock` is called because, as `q->mq_freeze_queue_dying = true` and that is a condition to not release the lock.
Specifically, in `blk_unfreeze_queue` we look at the value of `q->mq_freeze_queue_dying`. If it's true, we skip the `rwsem_release(&q->q_lockdep_map)` which is why the kernel returns to userspace with the lock held. This race is possible because Thread 1 is in `elevator_change` and Thread 2 calls `blk_mark_disk_dead`. Thread 2 calls `blk_mark_disk_dead` (when `del_gendisk` calls `blk_unregister_queue`), and `blk_mark_disk_dead` *sets* `q->mq_freeze_queue_dying = true` **before** the other thread unfreezes the queue.
This scenario explains the lockdep report and the held lock on return to user space.
|
| 81/2 |
2026/11/03 15:12 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/elevator.c Name:elevator_exit]
Results: map[SourceCode: 152: static void elevator_exit(struct request_queue *q)
153: {
154: struct elevator_queue *e = q->elevator;
155:
156: lockdep_assert_held(&q->elevator_lock);
157:
158: ioc_clear_queue(q);
159:
160: mutex_lock(&e->sysfs_lock);
161: blk_mq_exit_sched(q, e);
162: mutex_unlock(&e->sysfs_lock);
163: }
SourceFile:block/elevator.c]
|
| 82/2 |
2026/11/03 15:12 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/blk-mq-sched.c Name:blk_mq_init_sched]
Results: map[SourceCode: 613: /* caller must have a reference to @e, will grab another one if successful */
614: int blk_mq_init_sched(struct request_queue *q, struct elevator_type *e,
615: struct elevator_resources *res)
616: {
617: unsigned int flags = q->tag_set->flags;
618: struct elevator_tags *et = res->et;
619: struct blk_mq_hw_ctx *hctx;
620: struct elevator_queue *eq;
621: unsigned long i;
622: int ret;
623:
624: eq = elevator_alloc(q, e, res);
625: if (!eq)
626: return -ENOMEM;
627:
628: q->nr_requests = et->nr_requests;
629:
630: if (blk_mq_is_shared_tags(flags)) {
631: /* Shared tags are stored at index 0 in @et->tags. */
632: q->sched_shared_tags = et->tags[0];
633: blk_mq_tag_update_sched_shared_tags(q, et->nr_requests);
634: }
635:
636: queue_for_each_hw_ctx(q, hctx, i) {
637: if (blk_mq_is_shared_tags(flags))
638: hctx->sched_tags = q->sched_shared_tags;
639: else
640: hctx->sched_tags = et->tags[i];
641: }
642:
643: ret = e->ops.init_sched(q, eq);
644: if (ret)
645: goto out;
646:
647: queue_for_each_hw_ctx(q, hctx, i) {
648: if (e->ops.init_hctx) {
649: ret = e->ops.init_hctx(hctx, i);
650: if (ret) {
651: blk_mq_exit_sched(q, eq);
652: kobject_put(&eq->kobj);
653: return ret;
654: }
655: }
656: }
657: return 0;
658:
659: out:
660: blk_mq_sched_tags_teardown(q, flags);
661: kobject_put(&eq->kobj);
662: q->elevator = NULL;
663: return ret;
664: }
SourceFile:block/blk-mq-sched.c]
|
| 83/2 |
2026/11/03 15:12 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/elevator.c Name:elv_register_queue]
Results: map[SourceCode: 457: static int elv_register_queue(struct request_queue *q,
458: struct elevator_queue *e,
459: bool uevent)
460: {
461: int error;
462:
463: error = kobject_add(&e->kobj, &q->disk->queue_kobj, "iosched");
464: if (!error) {
465: const struct elv_fs_entry *attr = e->type->elevator_attrs;
466: if (attr) {
467: while (attr->attr.name) {
468: if (sysfs_create_file(&e->kobj, &attr->attr))
469: break;
470: attr++;
471: }
472: }
473: if (uevent)
474: kobject_uevent(&e->kobj, KOBJ_ADD);
475:
476: /*
477: * Sched is initialized, it is ready to export it via
478: * debugfs
479: */
480: blk_mq_sched_reg_debugfs(q);
481: set_bit(ELEVATOR_FLAG_REGISTERED, &e->flags);
482: }
483: return error;
484: }
SourceFile:block/elevator.c]
|
| 84/2 |
2026/11/03 15:12 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/blk-wbt.c Name:wbt_init_enable_default]
Results: map[SourceCode: 775: void wbt_init_enable_default(struct gendisk *disk)
776: {
777: struct request_queue *q = disk->queue;
778: struct rq_wb *rwb;
779: unsigned int memflags;
780:
781: if (!__wbt_enable_default(disk))
782: return;
783:
784: rwb = wbt_alloc();
785: if (!rwb)
786: return;
787:
788: if (wbt_init(disk, rwb)) {
789: pr_warn("%s: failed to enable wbt\n", disk->disk_name);
790: wbt_free(rwb);
791: return;
792: }
793:
794: memflags = blk_debugfs_lock(q);
795: blk_mq_debugfs_register_rq_qos(q);
796: blk_debugfs_unlock(q, memflags);
797: }
SourceFile:block/blk-wbt.c]
|
| 85/2 |
2026/11/03 15:12 |
llm |
debugger |
0m
Model:
Tokens:
input: 80326
output: 93
thoughts: 2054
Thoughts: **The Race to the Death: A Deep Dive into the DM and Blk Layers**
Okay, hold on a second, I need to really think this through. I'm looking at this reproducer, specifically `syz.3.1525/11804`, and it's got me stumped. Can this single task really be responsible for both removing a device *and* trying to load a table onto it? That doesn't make logical sense. If the device is removed *before* the table load, the `find_device` function should fail, right? But what if the remove operation was deferred? Let me look at that `ioctl$DM_DEV_REMOVE` again... Yep, it includes a `DM_DEFERRED_REMOVE` flag!
But, back to the problem: the `table_load` operation is printing that the device has already been removed. I have to trace through that `table_load` function in `dm-ioctl.c`. I can see that `find_device` is successful, but then, later on, when it tries to get the device pointer with `dm_get_mdptr`, it's returning `NULL`. How could that possibly happen in a single thread? `find_device` can't find it, but it does get removed from the hash table after the device is found in a single thread. The only explanation is that *another* thread must be removing it from the hash table *between* the `find_device` and `dm_get_mdptr` calls!
Okay, let's back up and follow the breadcrumbs from the removal side. I'm going to trace through the `dev_remove` function. This is in the same `dm-ioctl.c` file. The other thread (the remove thread) acquires the hash lock, finds the device, removes it from the hash, and then... *ah ha!* It calls `blk_mark_disk_dead(md->disk)` *after* removing from the hash!
This is where the lightbulb goes off. This `blk_mark_disk_dead` call is the key! This `blk_mark_disk_dead` has to be happening in Thread 2, and what's Thread 1 doing right now? Thread 1 is calling `elevator_change`. I need to understand what this `blk_mark_disk_dead` call does. I need to know how it changes the state of the block queue. It sets `QUEUE_FLAG_DYING` and calls `__blk_mark_disk_dead`. The thread also calls `blk_freeze_queue_start` and `blk_mq_unfreeze_queue_nomemrestore`.
Wait a minute, I have to be sure... I need to look for any other places where `q->mq_freeze_queue_dying` or the related fields are being accessed. Let's do a *thorough* search of the entire kernel to make sure that these are the *only* places where this queue state is modified. This is going to be important to understand this race condition.
|
| 86/2 |
2026/11/03 15:12 |
tool |
codesearch-find-references |
0m
Args: map[Name:request_queue::mq_freeze_owner]
Results: map[References:[map[ReferenceKind:writes ReferencingEntityKind:function ReferencingEntityName:blk_freeze_set_owner SourceFile:block/blk-mq.c SourceLine:123] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:blk_freeze_set_owner SourceFile:block/blk-mq.c SourceLine:132] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:blk_unfreeze_check_owner SourceFile:block/blk-mq.c SourceLine:140] map[ReferenceKind:writes ReferencingEntityKind:function ReferencingEntityName:blk_unfreeze_check_owner SourceFile:block/blk-mq.c SourceLine:143]] TruncatedOutput:false]
|
| 87/2 |
2026/11/03 15:12 |
tool |
codesearch-find-references |
0m
Args: map[Name:request_queue::mq_freeze_owner_depth]
Results: map[References:[map[ReferenceKind:writes ReferencingEntityKind:function ReferencingEntityName:blk_freeze_set_owner SourceFile:block/blk-mq.c SourceLine:124] map[ReferenceKind:writes ReferencingEntityKind:function ReferencingEntityName:blk_freeze_set_owner SourceFile:block/blk-mq.c SourceLine:133] map[ReferenceKind:takes-address-of ReferencingEntityKind:function ReferencingEntityName:blk_unfreeze_check_owner SourceFile:block/blk-mq.c SourceLine:142]] TruncatedOutput:false]
|
| 88/2 |
2026/11/03 15:12 |
tool |
codesearch-find-references |
0m
Args: map[Name:request_queue::mq_freeze_depth]
Results: map[References:[map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:__bio_queue_enter SourceFile:block/blk-core.c SourceLine:397] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:__bio_queue_enter SourceFile:block/blk-core.c SourceLine:397] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:__bio_queue_enter SourceFile:block/blk-core.c SourceLine:397] map[ReferenceKind:takes-address-of ReferencingEntityKind:function ReferencingEntityName:__blk_freeze_queue_start SourceFile:block/blk-mq.c SourceLine:170] map[ReferenceKind:takes-address-of ReferencingEntityKind:function ReferencingEntityName:__blk_mq_unfreeze_queue SourceFile:block/blk-mq.c SourceLine:218] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:__blk_mq_unfreeze_queue SourceFile:block/blk-mq.c SourceLine:219] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:__blk_mq_unfreeze_queue SourceFile:block/blk-mq.c SourceLine:220] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:blk_freeze_set_owner SourceFile:block/blk-mq.c SourceLine:122] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:blk_queue_enter SourceFile:block/blk-core.c SourceLine:364] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:blk_queue_enter SourceFile:block/blk-core.c SourceLine:364] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:blk_queue_enter SourceFile:block/blk-core.c SourceLine:364] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:elevator_switch SourceFile:block/elevator.c SourceLine:567] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:elv_update_nr_hw_queues SourceFile:block/elevator.c SourceLine:706] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:loop_update_dio SourceFile:drivers/block/loop.c SourceLine:204]] TruncatedOutput:false]
|
| 89/2 |
2026/11/03 15:12 |
llm |
debugger |
0m
Model:
Tokens:
input: 83621
output: 65
thoughts: 82
Thoughts: Okay, let's see. Here's a summary as if I'm processing those thought cues:
**Digging into the Message Queue Code - Potential Concurrency Bottlenecks!**
Wait a second! My mind is immediately drawn to a series of *very* specific identifiers. I'm seeing a cluster of mentions related to freezing message queue operations: `mq_freeze_owner`, `mq_freeze_owner_depth`, `mq_freeze_depth`, `mq_freeze_queue_dying`, and `mq_freeze_disk_dead`. This screams to me that there are intricate locking mechanisms in place around the handling of message queue lifecycles, and specifically around instances where queues might be in a state of transition β dying, or dealing with disk I/O issues, which suggests a careful dance between concurrent processes.
This immediately triggers a mental investigation of all uses of these freeze-related variables, I want to see how these are used to control access to the data structures. They imply careful locking, and I need to figure out how that locking is done.
Now, I need to check out references to `q_lockdep_map` and `q_lock_cls_key`. These are classic hints of lock dependency analysis. The presence of these suggests that a lockdep tool is being used to attempt to detect potential deadlock scenarios. This is critical. Are these lockdep hints being used properly? Are we seeing false positives or, worse, missing actual deadlocks? This warrants a *thorough* inspection. My brain is now mapping out a plan to use the source code, and potentially a debugger, to follow the data flow and understand how these locks are acquired and released within the message queue subsystem. I want to see if the freeze logic interacts properly with these lockdep features.
|
| 90/2 |
2026/11/03 15:12 |
tool |
codesearch-find-references |
0m
Args: map[Name:request_queue::q_lockdep_map]
Results: map[References:[map[ReferenceKind:takes-address-of ReferencingEntityKind:function ReferencingEntityName:blk_alloc_queue SourceFile:block/blk-core.c SourceLine:500] map[ReferenceKind:takes-address-of ReferencingEntityKind:function ReferencingEntityName:blk_freeze_acquire_lock SourceFile:block/blk.h SourceLine:786] map[ReferenceKind:takes-address-of ReferencingEntityKind:function ReferencingEntityName:blk_queue_enter SourceFile:block/blk-core.c SourceLine:372] map[ReferenceKind:takes-address-of ReferencingEntityKind:function ReferencingEntityName:blk_queue_enter SourceFile:block/blk-core.c SourceLine:373] map[ReferenceKind:takes-address-of ReferencingEntityKind:function ReferencingEntityName:blk_unfreeze_release_lock SourceFile:block/blk.h SourceLine:792]] TruncatedOutput:false]
|
| 91/2 |
2026/11/03 15:12 |
tool |
codesearch-find-references |
0m
Args: map[Name:request_queue::q_lock_cls_key]
Results: map[References:[map[ReferenceKind:takes-address-of ReferencingEntityKind:function ReferencingEntityName:blk_alloc_queue SourceFile:block/blk-core.c SourceLine:497] map[ReferenceKind:takes-address-of ReferencingEntityKind:function ReferencingEntityName:blk_alloc_queue SourceFile:block/blk-core.c SourceLine:501] map[ReferenceKind:takes-address-of ReferencingEntityKind:function ReferencingEntityName:blk_free_queue SourceFile:block/blk-core.c SourceLine:309]] TruncatedOutput:false]
|
| 92/2 |
2026/11/03 15:12 |
llm |
debugger |
0m
Model:
Tokens:
input: 84241
output: 33
thoughts: 7766
Thoughts: **Analyzing a Persistent Lockdep Issue in the Block Layer**
Okay, so I've meticulously traced the code paths related to the `mq_freeze` mechanism within the block layer, specifically focusing on the `q->mq_freeze_depth`, `q->mq_freeze_owner`, `q->mq_freeze_owner_depth`, `q->mq_freeze_queue_dying`, `q->mq_freeze_disk_dead`, and importantly, `q->q_lockdep_map` fields. My goal is to pinpoint a scenario that leads to a lock being held when returning to userspace, a clear lockdep violation. I've exhaustively identified all locations where these variables are modified and, by extension, where `q->q_lockdep_map` is acquired and released.
My analysis centers on a call to `elevator_change`, where a task `T1` calls `blk_mq_freeze_queue(q)` and then later `blk_mq_unfreeze_queue(q, memflags)`. I've broken down this call into its constituent parts, `__blk_freeze_queue_start`, `blk_freeze_acquire_lock`, `__blk_mq_unfreeze_queue`, and `blk_unfreeze_release_lock`, meticulously tracking the values of the key variables in question. I am especially concerned with whether the `q->q_lockdep_map` is properly released.
I've established that at the point `blk_freeze_acquire_lock` is called, `q->mq_freeze_queue_dying` is `false`, and therefore the lock is acquired. The critical point is that I *know* the lock *was* acquired because lockdep recorded it. This is evident by checking the stack trace in lockdep. However, despite the lock being acquired during `elevator_change`, I've observed that the release of the lock is not occurring in a later call. I've verified that the code should have called `rwsem_release`, but it didn't.
The core of the issue hinges on `q->mq_freeze_queue_dying`. I know that if the release is skipped, `q->mq_freeze_queue_dying` must have been true when `blk_unfreeze_release_lock(q)` ran. `q->mq_freeze_queue_dying` is initialized in `blk_freeze_set_owner`, which *can* only occur when the `q->mq_freeze_depth` is zero. I can then deduce the only way this could occur is for another thread `T2` calls `blk_mark_disk_dead` which will call `blk_freeze_queue_start`. If Thread 2 called `blk_mark_disk_dead` BEFORE `elevator_change`, Thread 1 would NOT call `blk_freeze_acquire_lock(q)` at `elevator_change:668`!
I've determined that *the same* thread must have called both `blk_mark_disk_dead` and `elevator_change` for this to occur.
|
| 93/2 |
2026/11/03 15:12 |
tool |
codesearch-find-references |
0m
Args: map[Name:__blk_mq_unfreeze_queue]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__del_gendisk SourceFile:block/genhd.c SourceLine:776] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_mq_unfreeze_queue_nomemrestore SourceFile:block/blk-mq.c SourceLine:232] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_mq_unfreeze_queue_non_owner SourceFile:block/blk-mq.c SourceLine:253]] TruncatedOutput:false]
|
| 94/2 |
2026/11/03 15:12 |
llm |
debugger |
0m
Model:
Tokens:
input: 92224
output: 83
thoughts: 8524
Thoughts: **A Deep Dive into a Potential Race Condition in the Block Layer**
Okay, so I've been tracing through this crash report, and it looks like we have a really tricky race condition on our hands. The core issue seems to be around the `__blk_mq_unfreeze_queue` function and, more specifically, how the `q->mq_freeze_queue_dying` flag gets clobbered in a multi-threaded scenario. It's like we're having a classic read-modify-write problem, and the lock isn't helping us.
First off, I've got to understand who's calling `__blk_mq_unfreeze_queue`. Looks like it's primarily being called from `__del_gendisk`, `blk_mq_unfreeze_queue_nomemrestore`, and `blk_mq_unfreeze_queue_non_owner`. No immediate red flags there, but it's good to know the call sites. My immediate concern is `q->mq_freeze_queue_dying` and how that's getting set. I've got to know where it's being written in the kernel!
Digging deeper, I see it's written in `blk_freeze_set_owner`. This function is setting several freeze-related flags, and the critical one here is `q->mq_freeze_queue_dying = blk_queue_dying(q)`. Now, this is starting to smell like a problem. I need to go through what is happening when unfreezing, specifically with `blk_mq_unfreeze_queue_nomemrestore` and how it interacts with the owner-setting.
Here's the setup: Thread 1, let's call it the "elevator" thread, is in the `elevator_change` function and holds `q->mq_freeze_lock`. In `__blk_mq_unfreeze_queue`, it decrements `q->mq_freeze_depth` and then calls `blk_unfreeze_check_owner(q)`. At this point, `q->mq_freeze_depth` is `0`. `unfreeze` returns `true`, and it releases the lock.
Meanwhile, Thread 2, the "destroy" thread, is off doing its own thing, and it ends up calling `blk_mark_disk_dead`. This sets the `QUEUE_FLAG_DYING` flag on the queue which in turn calls `blk_queue_start_drain` and ultimately `__blk_freeze_queue_start`. Now this is where it gets interesting... The race.
If the destroy thread acquires `q->mq_freeze_lock` *after* elevator has just unlocked it, or if it can acquire the lock after thread 1 has begun the unlock process, then it sets:
* `q->mq_freeze_owner` to Thread 2
* `q->mq_freeze_owner_depth` to 1
* `q->mq_freeze_queue_dying` to `true` (because `blk_queue_dying(q)` will return true due to the `QUEUE_FLAG_DYING` flag.)
Then, back in the elevator thread, which just *finished* `__blk_mq_unfreeze_queue` has no idea, and when it tries to release locks at `blk_unfreeze_release_lock`, it ends up *not* releasing the `q->q_lockdep_map` resource because `q->mq_freeze_queue_dying` is now set to `true`. This causes the crash, which tells us that the lock wasn't properly released!
However, the real puzzle is: Why would the elevator thread get preempted or delayed at the critical point of `mutex_unlock(&q->mq_freeze_lock)`?
Now, looking at the crash report that said that Thread 2 was possibly spinning. Let me trace `mutex_unlock` on an instance where a thread is waiting.
The theory I have is that the destroy thread can run and get the `q->mq_freeze_queue_dying` flag set to `true` and the elevator thread fails to detect this at the point where it releases the locks. My mind has been completely blown. I need to make sure I am tracing correctly.
This leads to the question of why the acquire/release of `blk_freeze_acquire_lock(q)` and `blk_unfreeze_release_lock(q)` are *outside* of `q->mq_freeze_lock`. I need to review `blk-mq.c` to see how the depth setting works, but the depth count will either be 0 or 1. If we freeze a queue, it increments `
|
| 95/2 |
2026/11/03 15:12 |
tool |
read-file |
0m
Args: map[File:block/genhd.c FirstLine:530 LineCount:100]
Results: map[Contents: 530:
531: ret = blk_register_queue(disk);
532: if (ret)
533: goto out_put_slave_dir;
534:
535: if (!(disk->flags & GENHD_FL_HIDDEN)) {
536: ret = bdi_register(disk->bdi, "%u:%u",
537: disk->major, disk->first_minor);
538: if (ret)
539: goto out_unregister_queue;
540: bdi_set_owner(disk->bdi, ddev);
541: ret = sysfs_create_link(&ddev->kobj,
542: &disk->bdi->dev->kobj, "bdi");
543: if (ret)
544: goto out_unregister_bdi;
545: } else {
546: /*
547: * Even if the block_device for a hidden gendisk is not
548: * registered, it needs to have a valid bd_dev so that the
549: * freeing of the dynamic major works.
550: */
551: disk->part0->bd_dev = MKDEV(disk->major, disk->first_minor);
552: }
553: return 0;
554:
555: out_unregister_bdi:
556: if (!(disk->flags & GENHD_FL_HIDDEN))
557: bdi_unregister(disk->bdi);
558: out_unregister_queue:
559: blk_unregister_queue(disk);
560: rq_qos_exit(disk->queue);
561: out_put_slave_dir:
562: kobject_put(disk->slave_dir);
563: disk->slave_dir = NULL;
564: out_put_holder_dir:
565: kobject_put(disk->part0->bd_holder_dir);
566: out_del_block_link:
567: sysfs_remove_link(block_depr, dev_name(ddev));
568: pm_runtime_set_memalloc_noio(ddev, false);
569: out_device_del:
570: device_del(ddev);
571: out_free_ext_minor:
572: if (disk->major == BLOCK_EXT_MAJOR)
573: blk_free_ext_minor(disk->first_minor);
574: out:
575: return ret;
576: }
577:
578: /**
579: * add_disk_fwnode - add disk information to kernel list with fwnode
580: * @parent: parent device for the disk
581: * @disk: per-device partitioning information
582: * @groups: Additional per-device sysfs groups
583: * @fwnode: attached disk fwnode
584: *
585: * This function registers the partitioning information in @disk
586: * with the kernel. Also attach a fwnode to the disk device.
587: */
588: int __must_check add_disk_fwnode(struct device *parent, struct gendisk *disk,
589: const struct attribute_group **groups,
590: struct fwnode_handle *fwnode)
591: {
592: struct blk_mq_tag_set *set;
593: unsigned int memflags;
594: int ret;
595:
596: if (queue_is_mq(disk->queue)) {
597: set = disk->queue->tag_set;
598: memflags = memalloc_noio_save();
599: down_read(&set->update_nr_hwq_lock);
600: ret = __add_disk(parent, disk, groups, fwnode);
601: up_read(&set->update_nr_hwq_lock);
602: memalloc_noio_restore(memflags);
603: } else {
604: ret = __add_disk(parent, disk, groups, fwnode);
605: }
606:
607: /*
608: * add_disk_final() needn't to read `nr_hw_queues`, so move it out
609: * of read lock `set->update_nr_hwq_lock` for avoiding unnecessary
610: * lock dependency on `disk->open_mutex` from scanning partition.
611: */
612: if (!ret)
613: add_disk_final(disk);
614: return ret;
615: }
616: EXPORT_SYMBOL_GPL(add_disk_fwnode);
617:
618: /**
619: * device_add_disk - add disk information to kernel list
620: * @parent: parent device for the disk
621: * @disk: per-device partitioning information
622: * @groups: Additional per-device sysfs groups
623: *
624: * This function registers the partitioning information in @disk
625: * with the kernel.
626: */
627: int __must_check device_add_disk(struct device *parent, struct gendisk *disk,
628: const struct attribute_group **groups)
629: {
]
|
| 96/2 |
2026/11/03 15:12 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/md/dm-sysfs.c Name:dm_sysfs_init]
Results: map[SourceCode: 125: /*
126: * Initialize kobj
127: * because nobody using md yet, no need to call explicit dm_get/put
128: */
129: int dm_sysfs_init(struct mapped_device *md)
130: {
131: return kobject_init_and_add(dm_kobject(md), &dm_ktype,
132: &disk_to_dev(dm_disk(md))->kobj,
133: "%s", "dm");
134: }
SourceFile:drivers/md/dm-sysfs.c]
|
| 97/2 |
2026/11/03 15:12 |
llm |
debugger |
0m
Model:
Tokens:
input: 102589
output: 46
thoughts: 298
Thoughts: **My Analysis of the Device Mapper Queue Initialization**
Wait a second! This doesn't seem quite right. Wait a second! Let me retrace my steps and dissect this more carefully.
Let's start by scrutinizing the `dm_setup_md_queue` function. Specifically, I'm focusing on lines 2609-2611. If the type is `DM_TYPE_REQUEST_BASED`, then `md->disk->fops` is set to `&dm_rq_blk_dops`, and then `dm_mq_init_request_queue(md, t)` is called. Okay, that seems standard.
But what *exactly* happens before `dm_setup_md_queue` is invoked, when `alloc_dev` is called? I need to understand the state of the queue at that point. I'll check `alloc_dev`: Lines 2349-2354 are key. I see that `md->disk = blk_alloc_disk(NULL, md->numa_node_id);` followed by `md->queue = md->disk->queue;` occur. That's where it all begins.
Now, at this point in `alloc_dev`, `md->queue` is *definitely* *not* a blk-mq queue, right? It's freshly allocated. So `q->tag_set` should be NULL at that point.
The million-dollar question is: *when* does `md->queue` transition into a blk-mq queue? The answer, I believe, lies within `dm_mq_init_request_queue`. I'll delve into the code here. It appears that `blk_mq_init_allocated_queue(md->tag_set, md->queue)` is the crucial call. This is the lynchpin.
Okay, let's now look at `blk_mq_init_allocated_queue` in `block/blk-mq.c`. That's where the magic happens. I should be able to deduce the exact initialization process from there. Time to dive into the code.
|
| 98/2 |
2026/11/03 15:12 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/blk-mq.c Name:blk_mq_init_allocated_queue]
Results: map[SourceCode:4661: int blk_mq_init_allocated_queue(struct blk_mq_tag_set *set,
4662: struct request_queue *q)
4663: {
4664: unsigned int memflags;
4665:
4666: /* mark the queue as mq asap */
4667: q->mq_ops = set->ops;
4668:
4669: /*
4670: * ->tag_set has to be setup before initialize hctx, which cpuphp
4671: * handler needs it for checking queue mapping
4672: */
4673: q->tag_set = set;
4674:
4675: if (blk_mq_alloc_ctxs(q))
4676: goto err_exit;
4677:
4678: /* init q->mq_kobj and sw queues' kobjects */
4679: blk_mq_sysfs_init(q);
4680:
4681: INIT_LIST_HEAD(&q->unused_hctx_list);
4682: spin_lock_init(&q->unused_hctx_lock);
4683:
4684: /*
4685: * Keep blk_mq_update_nr_hw_queues() away until the queue is on
4686: * set->tag_list: it changes the number of hardware queues, the tags and
4687: * the maps, and blk_mq_map_swqueue() allocates and frees tags of the set.
4688: * An update can be part of the error handling of a driver, so it must
4689: * not have to wait for somebody who waits for I/O.
4690: */
4691: memflags = memalloc_noio_save();
4692: mutex_lock(&set->tag_list_lock);
4693:
4694: blk_mq_realloc_hw_ctxs(set, q);
4695: if (!q->nr_hw_queues)
4696: goto err_hctxs;
4697:
4698: INIT_WORK(&q->timeout_work, blk_mq_timeout_work);
4699: blk_queue_rq_timeout(q, set->timeout ? set->timeout : 30 * HZ);
4700:
4701: q->queue_flags |= QUEUE_FLAG_MQ_DEFAULT;
4702:
4703: INIT_DELAYED_WORK(&q->requeue_work, blk_mq_requeue_work);
4704: INIT_LIST_HEAD(&q->flush_list);
4705: INIT_LIST_HEAD(&q->requeue_list);
4706: spin_lock_init(&q->requeue_lock);
4707:
4708: q->nr_requests = set->queue_depth;
4709: q->async_depth = set->queue_depth;
4710:
4711: blk_mq_init_cpu_queues(q, set->nr_hw_queues);
4712: blk_mq_map_swqueue(q);
4713: blk_mq_add_queue_tag_set(set, q);
4714:
4715: mutex_unlock(&set->tag_list_lock);
4716: memalloc_noio_restore(memflags);
4717: return 0;
4718:
4719: err_hctxs:
4720: mutex_unlock(&set->tag_list_lock);
4721: memalloc_noio_restore(memflags);
4722: blk_mq_release(q);
4723: err_exit:
4724: q->mq_ops = NULL;
4725: return -ENOMEM;
4726: }
SourceFile:block/blk-mq.c]
|
| 99/2 |
2026/11/03 15:12 |
llm |
debugger |
1m
Model:
Tokens:
input: 104011
output: 89
thoughts: 144
Thoughts: Okay, here's my take on those thoughts, as if they were my own:
**Immediate Alarm Bells and a Quick Code Dive**
OH. MY. GOD. I just spotted something in line 4701 of `blk_mq_init_allocated_queue`, specifically the assignment: `q->queue_flags |= QUEUE_FLAG_MQ_DEFAULT;`. Wait, that's a `|=`! My spidey-sense is tingling. That's a bit of a flags field, which is often used as a set, rather than a single value and it often indicates some important things about how a queue is operating.
Now I need to quickly determine whether the queue state is locked or unlocked, especially given the `MQ_DEFAULT` flag. Does anything *else* in this sequence potentially modify those flags? Are there any other calls to `blk_mq_init_allocated_queue`, `blk_mq_map_swqueue`, or `blk_mq_add_queue_tag_set` that could potentially freeze or unfreeze the queue? Time to immediately investigate `blk_mq_map_swqueue` and `blk_mq_add_queue_tag_set`. I need to ensure I fully understand the potential implications of this flag manipulation.
|
| 100/2 |
2026/11/03 15:14 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/blk-mq.c Name:blk_mq_map_swqueue]
Results: map[SourceCode:4191: static void blk_mq_map_swqueue(struct request_queue *q)
4192: {
4193: unsigned int j, hctx_idx;
4194: unsigned long i;
4195: struct blk_mq_hw_ctx *hctx;
4196: struct blk_mq_ctx *ctx;
4197: struct blk_mq_tag_set *set = q->tag_set;
4198:
4199: queue_for_each_hw_ctx(q, hctx, i) {
4200: cpumask_clear(hctx->cpumask);
4201: hctx->nr_ctx = 0;
4202: hctx->dispatch_from = NULL;
4203: }
4204:
4205: /*
4206: * Map software to hardware queues.
4207: *
4208: * If the cpu isn't present, the cpu is mapped to first hctx.
4209: */
4210: for_each_possible_cpu(i) {
4211:
4212: ctx = per_cpu_ptr(q->queue_ctx, i);
4213: for (j = 0; j < set->nr_maps; j++) {
4214: if (!set->map[j].nr_queues) {
4215: ctx->hctxs[j] = blk_mq_map_queue_type(q,
4216: HCTX_TYPE_DEFAULT, i);
4217: continue;
4218: }
4219: hctx_idx = set->map[j].mq_map[i];
4220: /* unmapped hw queue can be remapped after CPU topo changed */
4221: if (!set->tags[hctx_idx] &&
4222: !__blk_mq_alloc_map_and_rqs(set, hctx_idx)) {
4223: /*
4224: * If tags initialization fail for some hctx,
4225: * that hctx won't be brought online. In this
4226: * case, remap the current ctx to hctx[0] which
4227: * is guaranteed to always have tags allocated
4228: */
4229: set->map[j].mq_map[i] = 0;
4230: }
4231:
4232: hctx = blk_mq_map_queue_type(q, j, i);
4233: ctx->hctxs[j] = hctx;
4234: /*
4235: * If the CPU is already set in the mask, then we've
4236: * mapped this one already. This can happen if
4237: * devices share queues across queue maps.
4238: */
4239: if (cpumask_test_cpu(i, hctx->cpumask))
4240: continue;
4241:
4242: cpumask_set_cpu(i, hctx->cpumask);
4243: hctx->type = j;
4244: ctx->index_hw[hctx->type] = hctx->nr_ctx;
4245: hctx->ctxs[hctx->nr_ctx++] = ctx;
4246:
4247: /*
4248: * If the nr_ctx type overflows, we have exceeded the
4249: * amount of sw queues we can support.
4250: */
4251: BUG_ON(!hctx->nr_ctx);
4252: }
4253:
4254: for (; j < HCTX_MAX_TYPES; j++)
4255: ctx->hctxs[j] = blk_mq_map_queue_type(q,
4256: HCTX_TYPE_DEFAULT, i);
4257: }
4258:
4259: queue_for_each_hw_ctx(q, hctx, i) {
4260: int cpu;
4261:
4262: /*
4263: * If no software queues are mapped to this hardware queue,
4264: * disable it and free the request entries.
4265: */
4266: if (!hctx->nr_ctx) {
4267: /* Never unmap queue 0. We need it as a
4268: * fallback in case of a new remap fails
4269: * allocation
4270: */
4271: if (i)
4272: __blk_mq_free_map_and_rqs(set, i);
4273:
4274: hctx->tags = NULL;
4275: continue;
4276: }
4277:
4278: hctx->tags = set->tags[i];
4279: WARN_ON(!hctx->tags);
4280:
4281: /*
4282: * Set the map size to the number of mapped software queues.
4283: * This is more accurate and more efficient than looping
4284: * over all possibly mapped software queues.
4285: */
4286: sbitmap_resize(&hctx->ctx_map, hctx->nr_ctx);
4287:
4288: /*
4289: * Rule out isolated CPUs from hctx->cpumask to avoid
4290: * running block kworker on isolated CPUs.
4291: * FIXME: cpuset should propagate further changes to isolated CPUs
4292: * here.
4293: */
4294: rcu_read_lock();
4295: for_each_cpu(cpu, hctx->cpumask) {
4296: if (cpu_is_isolated(cpu))
4297: cpumask_clear_cpu(cpu, hctx->cpumask);
4298: }
4299: rcu_read_unlock();
4300:
4301: /*
4302: * Initialize batch roundrobin counts
4303: */
4304: hctx->next_cpu = blk_mq_first_mapped_cpu(hctx);
4305: hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
4306: }
4307: }
SourceFile:block/blk-mq.c]
|
| 101/2 |
2026/11/03 15:14 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/blk-mq.c Name:blk_mq_add_queue_tag_set]
Results: map[SourceCode:4358: static void blk_mq_add_queue_tag_set(struct blk_mq_tag_set *set,
4359: struct request_queue *q)
4360: {
4361: unsigned int i;
4362:
4363: lockdep_assert_held(&set->tag_list_lock);
4364:
4365: /*
4366: * Check to see if we're transitioning to shared (from 1 to 2 queues).
4367: */
4368: if (!list_empty(&set->tag_list) &&
4369: !(set->flags & BLK_MQ_F_TAG_QUEUE_SHARED)) {
4370: set->flags |= BLK_MQ_F_TAG_QUEUE_SHARED;
4371: /* update existing queue */
4372: blk_mq_update_tag_set_shared(set, true);
4373: }
4374: if (set->flags & BLK_MQ_F_TAG_QUEUE_SHARED)
4375: queue_set_hctx_shared(q, true);
4376:
4377: /*
4378: * A queue that joins a quiesced tag set is quiesced like the others,
4379: * and blk_mq_unquiesce_tagset() finds what it is going to undo.
4380: */
4381: spin_lock(&set->quiesce_lock);
4382: list_add_tail_rcu(&q->tag_set_list, &set->tag_list);
4383: if (!blk_queue_skip_tagset_quiesce(q)) {
4384: for (i = 0; i < set->quiesce_depth; i++)
4385: blk_mq_quiesce_queue_nowait(q);
4386: }
4387: spin_unlock(&set->quiesce_lock);
4388: }
SourceFile:block/blk-mq.c]
|
| 102/2 |
2026/11/03 15:14 |
llm |
debugger |
0m
Model:
Tokens:
input: 106589
output: 46
thoughts: 51
Thoughts: Okay, let's dive into this code.
**Diving into Queue Limits and Restrictions in dm-table.c**
Alright, I'm going to take a look at how this all works. I need to understand how the queue limits are calculated and how they interact with the table's restrictions in the Device Mapper module. My focus is on the functions `dm_calculate_queue_limits(t, &limits)` and `dm_table_set_restrictions(t, md->queue, &limits)`. I want to see exactly how `dm-table.c` handles these. I need to understand how these pieces fit together to manage the flow of I/O requests through the device mapper. I'm looking for the subtle nuances of how these calculations and settings impact overall performance and resource usage. Knowing this is critical to performance tuning.
|
| 103/2 |
2026/11/03 15:14 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/md/dm-table.c Name:dm_table_set_restrictions]
Results: map[SourceCode:2024: /*
2025: * This function will be skipped by noflush reloads of immutable request
2026: * based devices (dm-mpath).
2027: */
2028: int dm_table_set_restrictions(struct dm_table *t, struct request_queue *q,
2029: struct queue_limits *limits)
2030: {
2031: int r;
2032: struct queue_limits old_limits;
2033:
2034: if (!dm_table_supports_nowait(t))
2035: limits->features &= ~BLK_FEAT_NOWAIT;
2036:
2037: /*
2038: * The current polling implementation does not support request based
2039: * stacking.
2040: */
2041: if (!__table_type_bio_based(t->type))
2042: limits->features &= ~BLK_FEAT_POLL;
2043:
2044: if (!dm_table_supports_discards(t)) {
2045: limits->max_hw_discard_sectors = 0;
2046: limits->discard_granularity = 0;
2047: limits->discard_alignment = 0;
2048: }
2049:
2050: if (!dm_table_supports_write_zeroes(t)) {
2051: limits->max_write_zeroes_sectors = 0;
2052: limits->max_hw_wzeroes_unmap_sectors = 0;
2053: }
2054:
2055: if (!dm_table_supports_secure_erase(t))
2056: limits->max_secure_erase_sectors = 0;
2057:
2058: if (dm_table_supports_flush(t))
2059: limits->features |= BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA;
2060:
2061: if (dm_table_supports_dax(t, device_not_dax_capable))
2062: limits->features |= BLK_FEAT_DAX;
2063: else
2064: limits->features &= ~BLK_FEAT_DAX;
2065:
2066: /* For a zoned table, setup the zone related queue attributes. */
2067: if (IS_ENABLED(CONFIG_BLK_DEV_ZONED)) {
2068: if (limits->features & BLK_FEAT_ZONED) {
2069: r = dm_set_zones_restrictions(t, q, limits);
2070: if (r)
2071: return r;
2072: } else if (dm_has_zone_plugs(t->md)) {
2073: DMWARN("%s: device has zone write plug resources. "
2074: "Cannot switch to non-zoned table.",
2075: dm_device_name(t->md));
2076: return -EINVAL;
2077: }
2078: }
2079:
2080: if (dm_table_supports_atomic_writes(t))
2081: limits->features |= BLK_FEAT_ATOMIC_WRITES;
2082:
2083: old_limits = queue_limits_start_update(q);
2084: r = queue_limits_commit_update(q, limits);
2085: if (r)
2086: return r;
2087:
2088: /*
2089: * Now that the limits are set, check the zones mapped by the table
2090: * and setup the resources for zone append emulation if necessary.
2091: */
2092: if (IS_ENABLED(CONFIG_BLK_DEV_ZONED) &&
2093: (limits->features & BLK_FEAT_ZONED)) {
2094: r = dm_revalidate_zones(t, q);
2095: if (r) {
2096: queue_limits_set(q, &old_limits);
2097: return r;
2098: }
2099: }
2100:
2101: if (IS_ENABLED(CONFIG_BLK_DEV_ZONED))
2102: dm_finalize_zone_settings(t, limits);
2103:
2104: if (dm_table_supports_dax(t, device_not_dax_synchronous_capable))
2105: set_dax_synchronous(t->md->dax_dev);
2106:
2107: if (dm_table_any_dev_attr(t, device_dax_write_cache_enabled, NULL))
2108: dax_write_cache(t->md->dax_dev, true);
2109:
2110: dm_update_crypto_profile(q, t);
2111: return 0;
2112: }
SourceFile:drivers/md/dm-table.c]
|
| 104/2 |
2026/11/03 15:14 |
llm |
debugger |
0m
Model:
Tokens:
input: 108092
output: 80
thoughts: 2941
Thoughts: **A Deep Dive into a Data Mapper Conundrum**
Alright, let's break this down. We have two threads duking it out: one loading a table (`table_load`) and the other removing a device (`dev_remove`). My first thought is to meticulously trace the interactions. Thread 1, the `table_load` thread, creates the device, and then calls `dm_table_create`. This bumps up the holder count. We get to `dm_setup_md_queue`, which sets up the request queue, essentially prepping the device. At this point, we're setting up the `blk-mq` queue. This looks important. Specifically, the call to `elevator_change` looks important because we see a `blk_mq_freeze_queue` followed by a `blk_mq_unfreeze_queue`.
Now, we shift our focus to Thread 2. This is where things get interesting. `dev_remove` comes along and tries to delete the device by calling `blk_mark_disk_dead`. The core question becomes: what happens if Thread 2's marking the disk as dead *before* Thread 1 has fully set up the queue, specifically before `blk_mq_init_request_queue` is done? Looking at `blk_mq_init_allocated_queue`, we see the setting of the `QUEUE_FLAG_MQ_DEFAULT` flag. Now we have to trace what `blk_mark_disk_dead` does. It sets `QUEUE_FLAG_DYING` and calls `__blk_mark_disk_dead`. Inside that function, we get `blk_queue_start_drain`, which calls `__blk_freeze_queue_start`. But in Thread 1 we call `blk_mq_freeze_queue` *before* `blk_mark_disk_dead` in Thread 2.
We need to consider what would happen if `dm_setup_md_queue` failed, calling `del_gendisk` in Thread 1. This could be a possibility, but looking through the code, we wouldn't see the crash log we have. Looking at where we are getting the crash log, we are seeing the message: `device-mapper: ioctl: device has been removed from the dev hash table.` This tells me that `dm_setup_md_queue(md, t)` succeeded. Thread 1 calls `dm_put(md)`. If there were a race that was not possible, we would see `goto err_destroy_table;` in the `table_load` function. When we have the message, we see we call `dm_table_destroy(t)` and `dm_put(md)`. We need to examine these closely. This is the root of the problem.
|
| 105/2 |
2026/11/03 15:15 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/md/dm-table.c Name:dm_table_destroy]
Results: map[SourceCode: 182: void dm_table_destroy(struct dm_table *t)
183: {
184: if (!t)
185: return;
186:
187: /* free the indexes */
188: if (t->depth >= 2)
189: kvfree(t->index[t->depth - 2]);
190:
191: /* free the targets */
192: for (unsigned int i = 0; i < t->num_targets; i++) {
193: struct dm_target *ti = dm_table_get_target(t, i);
194:
195: if (ti->type->dtr)
196: ti->type->dtr(ti);
197:
198: dm_put_target_type(ti->type);
199: }
200:
201: kvfree(t->highs);
202:
203: /* free the device list */
204: free_devices(&t->devices, t->md);
205:
206: dm_free_md_mempools(t->mempools);
207:
208: dm_table_destroy_crypto_profile(t);
209:
210: kfree(t);
211: }
SourceFile:drivers/md/dm-table.c]
|
| 106/2 |
2026/11/03 15:15 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/md/dm.c Name:dm_put]
Results: map[SourceCode:2783: void dm_put(struct mapped_device *md)
2784: {
2785: atomic_dec(&md->holders);
2786: }
SourceFile:drivers/md/dm.c]
|
| 107/2 |
2026/11/03 15:15 |
llm |
debugger |
0m
Model:
Tokens:
input: 111625
output: 44
thoughts: 3008
Thoughts: **Race Condition Analysis in Device Mapper's Elevator Subsystem**
Okay, here's what I'm seeing. This is pretty subtle, but potentially nasty. The key is understanding how the elevator (queue) is handled in the Device Mapper context, and where the potential for a race condition lies.
First, I observe that neither `dm_table_destroy` nor `dm_put` directly interact with the queue (`md->queue` or `elevator_change`), which is the first clue. This implies that the queue manipulation happens *elsewhere*.
In the case of `table_load` (Thread 1), the chain of calls goes `table_load` -> `dm_setup_md_queue` -> `add_disk` -> `device_add_disk` -> `add_disk_fwnode` -> `__add_disk` -> `blk_register_queue` -> `elevator_set_default` -> `elevator_change`. *This* is where the elevator settings are being adjusted for the new device. Crucially, the same thread can be executing `dev_remove`, so we must check for a race.
It seems `dev_remove` (Thread 2) can also execute at the same time and does not have the same chain of calls to the elevator. It calls `__hash_remove`, which unlinks the device. Then `dm_destroy` is called, and `blk_mark_disk_dead(md->disk)` is called, which is where things get interesting.
I'm focusing in on what happens when these two threads interact. Here's a timeline of a race:
1. Thread 1 (`table_load`) is running and calls `find_device(param)` and now `md->holders` becomes 1.
2. Thread 2 (`dev_remove`) runs, removes the device.
Now it's time to check what happens while Thread 1 is in `elevator_change`, and, Thread 2 calls `blk_mark_disk_dead(md->disk)`.
* Thread 1 is in `elevator_change`. It calls `blk_mq_freeze_queue(q)`. This increments `q->mq_freeze_depth` and makes `q->mq_freeze_owner = Thread_1`, and then acquires the `q->q_lockdep_map`. The queue is now effectively frozen.
* Thread 2 (inside `blk_mark_disk_dead`) sets `QUEUE_FLAG_DYING` on `q`, and calls `blk_queue_start_drain`. This calls `__blk_freeze_queue_start`, but `q->mq_freeze_depth` is already at 1 from the first thread. `blk_freeze_set_owner` returns false. The depth is incremented to 2.
* Thread 1 continues. `blk_mq_unfreeze_queue(q)` gets called. `q->mq_freeze_depth` becomes 1. `blk_unfreeze_check_owner` returns true, meaning it releases ownership and sets the owner to `NULL`.
At this point, *`q->mq_freeze_depth` is 1*, even though `q->mq_freeze_owner` is `NULL`.
When Thread 2 wakes up from its `fsleep` and calls `elevator_set_none(q)` -> `elevator_change`, `q->mq_freeze_depth` is 1! It won't acquire the lock because the depth is not 0. Thread 2 would call `elevator_change`, but the queue is still frozen at a depth of 1!
The problem is the acquire/release of `q->q_lockdep_map` within the `elevator_change` calls, especially when the queue is in a state of flux due to the two threads.
**Here's the critical question:** What happens to the `lockdep_unregister_key(&q->q_lock_cls_key)` in `blk_free_queue` if a task is *still holding* the `&q->q_lockdep_map`? *That's where the potential corruption is.* This is where I'll dig into the `lockdep_unregister_key` function and see what it does under contention. I need to understand if this unregistering can happen safely while a lock is still held. This is where the root cause lies.
|
| 108/2 |
2026/11/03 15:15 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/locking/lockdep.c Name:lockdep_unregister_key]
Results: map[SourceCode:6671: /*
6672: * Unregister a dynamically allocated key.
6673: *
6674: * Unlike lockdep_register_key(), a search is always done to find a matching
6675: * key irrespective of debug_locks to avoid potential invalid access to freed
6676: * memory in lock_class entry.
6677: */
6678: void lockdep_unregister_key(struct lock_class_key *key)
6679: {
6680: struct hlist_head *hash_head = keyhashentry(key);
6681: struct lock_class_key *k;
6682: struct pending_free *pf;
6683: unsigned long flags;
6684: bool found = false;
6685: bool need_callback = false;
6686:
6687: might_sleep();
6688:
6689: if (WARN_ON_ONCE(static_obj(key)))
6690: return;
6691:
6692: raw_local_irq_save(flags);
6693: lockdep_lock();
6694:
6695: hlist_for_each_entry_rcu(k, hash_head, hash_entry) {
6696: if (k == key) {
6697: hlist_del_rcu(&k->hash_entry);
6698: found = true;
6699: break;
6700: }
6701: }
6702: WARN_ON_ONCE(!found && debug_locks);
6703: if (found) {
6704: pf = get_pending_free();
6705: __lockdep_free_key_range(pf, key, 1);
6706: need_callback = prepare_call_rcu_zapped(pf);
6707: nr_dynamic_keys--;
6708: }
6709: lockdep_unlock();
6710: raw_local_irq_restore(flags);
6711:
6712: if (need_callback)
6713: call_rcu(&delayed_free.rcu_head, free_zapped_rcu);
6714:
6715: /*
6716: * Wait until is_dynamic_key() has finished accessing k->hash_entry.
6717: *
6718: * Some operations like __qdisc_destroy() will call this in a debug
6719: * kernel, and the network traffic is disabled while waiting, hence
6720: * the delay of the wait matters in debugging cases. Currently use a
6721: * synchronize_rcu_expedited() to speed up the wait at the cost of
6722: * system IPIs. TODO: Replace RCU with hazptr for this.
6723: */
6724: synchronize_rcu_expedited();
6725: }
SourceFile:kernel/locking/lockdep.c]
|
| 109/2 |
2026/11/03 15:15 |
llm |
debugger |
1m
Model:
Tokens:
input: 115517
output: 78
thoughts: 2773
Thoughts: **Analysis of a Device Mapper Concurrency Issue**
Okay, let's break this down. It seems we have a race condition in the device mapper, specifically tied to the interaction between device loading (`table_load`) and device removal (`dev_remove`). My initial thinking was centered on how the `blk_free_queue` and `__lockdep_free_key_range` are handled, given the timing of `put_disk` and the `fsleep` in `__dm_destroy`. I was concerned about a potential use-after-free scenario.
The crucial observation hinges on the `fsleep(1000)` call within `__dm_destroy`, specifically inside the `while (atomic_read(&md->holders))` loop. This means the `dev_remove` thread can be *sleeping* after `blk_mark_disk_dead` is called, allowing the `table_load` thread to continue executing.
Let me outline the sequence that's making this so interesting:
1. `__dm_destroy` (from `dev_remove`) calls `blk_mark_disk_dead(md->disk)`.
2. `__dm_destroy` then enters a `while` loop that sleeps (via `fsleep(1000)`) until the device's `holders` count reaches zero.
3. Simultaneously, `table_load` (in another thread) prints a "device has been removed" message, destroys the table, decrements the device's holder count (`dm_put(md)`), and *returns to user space*. Crucially, this is all happening *before* the `dev_remove` thread exits its sleep loop.
This timing reveals that when `table_load` calls `dm_put(md)`, the `del_gendisk(md->disk)` has *not* been called yet by `dev_remove`. This is verified, because I examined the timing of when this happens. `dev_remove` has not completed and is still sleeping during this.
The key thread involved in the crash, the `table_load` thread, executed `elevator_change` only once, which is inside `dm_setup_md_queue` -> `add_disk(md->disk)` -> `blk_register_queue` -> `elevator_set_default(q)` -> `elevator_change(q, &ctx)`.
I verified that the holder count is greater than or equal to 1 in `table_load` until `dm_put(md)` (the very last thing before returning from the `table_load` function), and that `del_gendisk(md->disk)` is not called until *after* `fsleep(1000)` in `__dm_destroy`. So it's absolutely true that no operation happens in `dev_remove` touching the disk and queue until after the loop in `dev_remove` is sleeping.
I re-examined the code in `dev_remove` and `__dm_destroy` to confirm that `blk_mark_disk_dead(md->disk)` is the *only* operation that touches `md->disk` or `md->queue` before `fsleep(1000)`.
What about `table_load`? I confirmed that the only places that `table_load` touches the disk and queue are: in `dm_setup_md_queue` and the subsequent calls I mentioned above: `elevator_change`.
Therefore, the critical sequence is this:
* Thread 1 (`table_load`): Runs `elevator_change(q, &ctx)`.
* Thread 2 (`dev_remove`): Runs `blk_mark_disk_dead(md->disk)` *before* `table_load` is complete.
Now, let's look at those two functions in detail. `elevator_change(q, &ctx)` calls `blk_mq_freeze_queue(q)` and `blk_mq_cancel_work_sync(q)`. At this point, I think, I need to understand whether this is a blocking operation or not, and whether that has an impact on the calls from `__dm_destroy`. Looking into the call to `blk_mark_disk_dead`, it sets the `QUEUE_FLAG_DYING` flag and calls `blk_queue_start_drain`. Specifically, `blk_queue_start_drain` and `blk_mark_disk_dead` are the functions that should be investigated to find the source of the crash. I'll need to review if `blk_mark_disk_dead` has an effect that overlaps with any changes that `elevator_change` is making.
|
| 110/2 |
2026/11/03 15:17 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/genhd.c Name:set_capacity]
Results: map[SourceCode: 59: void set_capacity(struct gendisk *disk, sector_t sectors)
60: {
61: if (sectors > BLK_DEV_MAX_SECTORS) {
62: pr_warn_once("%s: truncate capacity from %lld to %lld\n",
63: disk->disk_name, sectors,
64: BLK_DEV_MAX_SECTORS);
65: sectors = BLK_DEV_MAX_SECTORS;
66: }
67:
68: bdev_set_nr_sectors(disk->part0, sectors);
69: }
SourceFile:block/genhd.c]
|
| 111/2 |
2026/11/03 15:17 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/genhd.c Name:blk_report_disk_dead]
Results: map[SourceCode: 634: static void blk_report_disk_dead(struct gendisk *disk, bool surprise)
635: {
636: struct block_device *bdev;
637: unsigned long idx;
638:
639: /*
640: * On surprise disk removal, bdev_mark_dead() may call into file
641: * systems below. Make it clear that we're expecting to not hold
642: * disk->open_mutex.
643: */
644: lockdep_assert_not_held(&disk->open_mutex);
645:
646: rcu_read_lock();
647: xa_for_each(&disk->part_tbl, idx, bdev) {
648: if (!kobject_get_unless_zero(&bdev->bd_device.kobj))
649: continue;
650: rcu_read_unlock();
651:
652: bdev_mark_dead(bdev, surprise);
653:
654: put_device(&bdev->bd_device);
655: rcu_read_lock();
656: }
657: rcu_read_unlock();
658: }
SourceFile:block/genhd.c]
|
| 112/2 |
2026/11/03 15:17 |
llm |
debugger |
0m
Model:
Tokens:
input: 118953
output: 42
thoughts: 31
Thoughts: Okay, let's dive into this. Here's my thought process on dissecting `bdev_mark_dead(bdev, surprise)`:
**Dissecting `bdev_mark_dead` - The First Checkpoint**
Right, let's not just assume what this function *does*. Instead, I need to see *how* it does it. I'm going to pull up the source code for `bdev_mark_dead(bdev, surprise)` right now. Need to understand the exact implementation before making any assumptions about the implications for the system. What signals are being sent, what data structures are being modified, are there any calls to other key functions in the block device layer? It is imperative to know the details!
|
| 113/2 |
2026/11/03 15:17 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/bdev.c Name:bdev_mark_dead]
Results: map[SourceCode:1300: /**
1301: * bdev_mark_dead - mark a block device as dead
1302: * @bdev: block device to operate on
1303: * @surprise: indicate a surprise removal
1304: *
1305: * Tell the file system that this devices or media is dead. If @surprise is set
1306: * to %true the device or media is already gone, if not we are preparing for an
1307: * orderly removal.
1308: *
1309: * This calls into the file system, which then typicall syncs out all dirty data
1310: * and writes back inodes and then invalidates any cached data in the inodes on
1311: * the file system. In addition we also invalidate the block device mapping.
1312: */
1313: void bdev_mark_dead(struct block_device *bdev, bool surprise)
1314: {
1315: mutex_lock(&bdev->bd_holder_lock);
1316: if (bdev->bd_holder_ops && bdev->bd_holder_ops->mark_dead)
1317: bdev->bd_holder_ops->mark_dead(bdev, surprise);
1318: else {
1319: mutex_unlock(&bdev->bd_holder_lock);
1320: /*
1321: * On surprise removal the device is already gone; syncing is
1322: * futile and can hang forever waiting on I/O that will never
1323: * complete. Match fs_bdev_mark_dead(), which also skips it.
1324: */
1325: if (!surprise)
1326: sync_blockdev(bdev);
1327: }
1328:
1329: invalidate_bdev(bdev);
1330: }
SourceFile:block/bdev.c]
|
| 114/2 |
2026/11/03 15:17 |
llm |
debugger |
0m
Model:
Tokens:
input: 119566
output: 71
thoughts: 86
Thoughts: Here's my thought process, as it stands:
**Digging into that pesky Queue Update**
Okay, hold on a second. I was so focused on the `add_disk` function, but I just noticed `queue_limits_commit_update(q, limits)` right before it in `dm_table_set_restrictions`, which is itself called in `dm_setup_md_queue`. I need to circle back and fully understand this call! Could this be where the queue is potentially frozen? It seems like a likely spot.
Right, I'm going to dive straight into `queue_limits_commit_update` and see exactly what it's doing. Let's see if it's the culprit. Does it actually have the potential to block or quiesce the queue? I need to verify that before proceeding.
|
| 115/2 |
2026/11/03 15:17 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/blk-settings.c Name:queue_limits_commit_update]
Results: map[SourceCode: 542: /**
543: * queue_limits_commit_update - commit an atomic update of queue limits
544: * @q: queue to update
545: * @lim: limits to apply
546: *
547: * Apply the limits in @lim that were obtained from queue_limits_start_update()
548: * and updated by the caller to @q. The caller must have frozen the queue or
549: * ensure that there are no outstanding I/Os by other means.
550: *
551: * Returns 0 if successful, else a negative error code.
552: */
553: int queue_limits_commit_update(struct request_queue *q,
554: struct queue_limits *lim)
555: {
556: int error;
557:
558: lockdep_assert_held(&q->limits_lock);
559:
560: error = blk_validate_limits(lim);
561: if (error)
562: goto out_unlock;
563:
564: #ifdef CONFIG_BLK_INLINE_ENCRYPTION
565: if (q->crypto_profile && lim->integrity.tag_size) {
566: pr_warn("blk-integrity: Integrity and hardware inline encryption are not supported together.\n");
567: error = -EINVAL;
568: goto out_unlock;
569: }
570: #endif
571:
572: q->limits = *lim;
573: if (q->disk)
574: blk_apply_bdi_limits(q->disk->bdi, lim);
575: out_unlock:
576: mutex_unlock(&q->limits_lock);
577: return error;
578: }
SourceFile:block/blk-settings.c]
|
| 116/2 |
2026/11/03 15:17 |
tool |
codesearch-find-references |
0m
Args: map[Name:blk_mq_freeze_queue]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:aoedev_downdev SourceFile:drivers/block/aoe/aoedev.c SourceLine:240] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_mq_update_tag_set_shared SourceFile:block/blk-mq.c SourceLine:4337] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_throtl_init SourceFile:block/blk-throttle.c SourceLine:1333] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blkcg_activate_policy SourceFile:block/blk-cgroup.c SourceLine:1628] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blkcg_deactivate_policy SourceFile:block/blk-cgroup.c SourceLine:1733] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blkiolatency_enable_work_fn SourceFile:block/blk-iolatency.c SourceLine:749] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:del_mtd_blktrans_dev SourceFile:drivers/mtd/mtd_blkdevs.c SourceLine:429] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:disk_revalidate_zone_resources SourceFile:block/blk-zoned.c SourceLine:2234] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:elevator_change SourceFile:block/elevator.c SourceLine:668] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:elv_exit_and_release SourceFile:block/elevator.c SourceLine:615] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:ioc_cost_model_write SourceFile:block/blk-iocost.c SourceLine:3605] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:ioc_qos_write SourceFile:block/blk-iocost.c SourceLine:3392] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:loop_set_block_size SourceFile:drivers/block/loop.c SourceLine:1400] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:loop_set_dio SourceFile:drivers/block/loop.c SourceLine:1354] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:loop_set_status SourceFile:drivers/block/loop.c SourceLine:1166] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:nvme_update_ns_info SourceFile:drivers/nvme/host/core.c SourceLine:2588] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:nvme_update_ns_info_block SourceFile:drivers/nvme/host/core.c SourceLine:2451] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:nvme_update_ns_info_generic SourceFile:drivers/nvme/host/core.c SourceLine:2246] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:queue_async_depth_store SourceFile:block/blk-sysfs.c SourceLine:162] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:queue_limits_commit_update_frozen SourceFile:block/blk-settings.c SourceLine:598] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:queue_requests_store SourceFile:block/blk-sysfs.c SourceLine:123] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:queue_zoned_qd1_writes_store SourceFile:block/blk-sysfs.c SourceLine:412] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:rq_qos_add SourceFile:block/blk-rq-qos.c SourceLine:341] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:rq_qos_del SourceFile:block/blk-rq-qos.c SourceLine:364] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:scsi_device_quiesce SourceFile:drivers/scsi/scsi_lib.c SourceLine:2874] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:scsi_realloc_sdev_budget_map SourceFile:drivers/scsi/scsi_scan.c SourceLine:245] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:ublk_lock_buf_tree SourceFile:drivers/block/ublk_drv.c SourceLine:5508] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:virtblk_freeze_priv SourceFile:drivers/block/virtio_blk.c SourceLine:1598] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:wbt_set_lat SourceFile:block/blk-wbt.c SourceLine:1009]] TruncatedOutput:false]
|
| 117/2 |
2026/11/03 15:17 |
llm |
debugger |
0m
Model:
Tokens:
input: 121846
output: 82
thoughts: 123
Thoughts: **Investigating the Queue Freeze**
Wait a second! Something just clicked. I was looking at those mentions of `blk_mq_freeze_queue`, and then I saw it: `rq_qos_add` in `block/blk-rq-qos.c:341` is one of the callers! But where *else* is `rq_qos_add` being called? I need to trace this back.
Alright, let's back up a step. I know `wbt_init` gets called in `blk_register_queue` right after `elevator_set_default(q)` β and that's critical in understanding how block layer settings get initialized. I'm going to examine the code path of `wbt_init`, and then I *must* cross-reference it with the code in `rq_qos_add`. I need to figure out where the connection is.
|
| 118/2 |
2026/11/03 15:17 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/blk-wbt.c Name:wbt_init]
Results: map[SourceCode: 960: static int wbt_init(struct gendisk *disk, struct rq_wb *rwb)
961: {
962: struct request_queue *q = disk->queue;
963: int ret;
964: int i;
965:
966: for (i = 0; i < WBT_NUM_RWQ; i++)
967: rq_wait_init(&rwb->rq_wait[i]);
968:
969: rwb->last_comp = rwb->last_issue = jiffies;
970: rwb->win_nsec = RWB_WINDOW_NSEC;
971: rwb->enable_state = WBT_STATE_ON_DEFAULT;
972: rwb->rq_depth.default_depth = RWB_DEF_DEPTH;
973: rwb->min_lat_nsec = wbt_default_latency_nsec(q);
974: rwb->rq_depth.queue_depth = blk_queue_depth(q);
975: wbt_update_limits(rwb);
976:
977: /*
978: * Assign rwb and add the stats callback.
979: */
980: mutex_lock(&q->rq_qos_mutex);
981: ret = rq_qos_add(&rwb->rqos, disk, RQ_QOS_WBT, &wbt_rqos_ops);
982: mutex_unlock(&q->rq_qos_mutex);
983: if (ret)
984: return ret;
985:
986: blk_stat_add_callback(q, rwb->cb);
987: return 0;
988: }
SourceFile:block/blk-wbt.c]
|
| 119/2 |
2026/11/03 15:17 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/blk-rq-qos.c Name:rq_qos_add]
Results: map[SourceCode: 325: int rq_qos_add(struct rq_qos *rqos, struct gendisk *disk, enum rq_qos_id id,
326: const struct rq_qos_ops *ops)
327: {
328: struct request_queue *q = disk->queue;
329: unsigned int memflags;
330:
331: lockdep_assert_held(&q->rq_qos_mutex);
332:
333: rqos->disk = disk;
334: rqos->id = id;
335: rqos->ops = ops;
336:
337: /*
338: * No IO can be in-flight when adding rqos, so freeze queue, which
339: * is fine since we only support rq_qos for blk-mq queue.
340: */
341: memflags = blk_mq_freeze_queue(q);
342:
343: if (rq_qos_id(q, rqos->id))
344: goto ebusy;
345: rqos->next = q->rq_qos;
346: q->rq_qos = rqos;
347: blk_queue_flag_set(QUEUE_FLAG_QOS_ENABLED, q);
348:
349: blk_mq_unfreeze_queue(q, memflags);
350: return 0;
351: ebusy:
352: blk_mq_unfreeze_queue(q, memflags);
353: return -EBUSY;
354: }
SourceFile:block/blk-rq-qos.c]
|
| 120/2 |
2026/11/03 15:17 |
llm |
debugger |
0m
Model:
Tokens:
input: 123062
output: 76
thoughts: 1989
Thoughts: **Deeper Dive into Block Queue Freezing and Unfreezing**
Okay, hold on a second, I need to really think this through. I'm looking at `blk_register_queue` in `block/blk-sysfs.c`. It's registering a queue, and there are a few things that immediately jump out. First, if it's an MQ queue, `elevator_set_default` is called. Then, the `QUEUE_FLAG_REGISTERED` flag is set, and `wbt_init_enable_default(disk)` is called. I need to figure out what that `wbt_init_enable_default` function is doing. Why would that even be necessary? I'm already seeing lockdep reports indicating potential issues with lock acquisition and release, particularly around the `q_usage_counter`.
My initial thought was that I had identified a problem with `q->mq_freeze_queue_dying` being exclusively written to by `blk_freeze_set_owner`. However, I need to re-examine the interactions between `blk_freeze_set_owner`, `blk_freeze_acquire_lock`, `blk_unfreeze_check_owner`, and `blk_unfreeze_release_lock`.
Specifically, I'm focusing on the freezing and unfreezing of the queue, and what locks are acquired and released. I need to understand the logic in `blk_freeze_queue_start` and `blk_mq_unfreeze_queue_nomemrestore`. I'm going through the code to trace how `q->mq_freeze_depth` is handled. The `percpu_ref_kill` and `percpu_ref_resurrect` calls look important, as does the wake up to `q->mq_freeze_wq`. I'm starting to understand how the freezing mechanism works. I must know the roles of `io_lockdep_map` and `q_lockdep_map`.
Now, I'm going through the call chain from `elevator_change`. It calls `blk_mq_freeze_queue` which I know can be problematic. Then, it calls a number of other functions like `blk_mq_cancel_work_sync` and `elevator_switch`. Crucially, it unfreezes the queue with `blk_mq_unfreeze_queue`. My question is, given this sequence of events in `elevator_change` and the subsequent call to `elevator_set_default`, what happens *after* `elevator_change` returns and `blk_register_queue` is called? The code in `blk_register_queue` sets the queue registered, then calls `wbt_init_enable_default` and sends out a uevent. The `QUEUE_FLAG_INIT_DONE` is set. After that, I see a call to `percpu_ref_switch_to_percpu`.
Okay, I need to see what's happening *after* `blk_register_queue` returns. The code I am looking at then calls `__add_disk` and `add_disk_final` in `block/genhd.c` which I will investigate next. I need to see how the system is re-initialized after an elevator switch. The question is: what is the order of these operations and what are the implications on any state variables or locks? I am confident I will find the source of the issue.
|
| 121/2 |
2026/11/03 15:18 |
tool |
read-file |
0m
Args: map[File:block/genhd.c FirstLine:380 LineCount:90]
Results: map[Contents: 380: ret = bd_prepare_to_claim(disk->part0, disk_scan_partitions,
381: NULL);
382: if (ret)
383: return ret;
384: }
385:
386: set_bit(GD_NEED_PART_SCAN, &disk->state);
387: file = bdev_file_open_by_dev(disk_devt(disk), mode & ~BLK_OPEN_EXCL,
388: NULL, NULL);
389: if (IS_ERR(file))
390: ret = PTR_ERR(file);
391: else
392: fput(file);
393:
394: /*
395: * If blkdev_get_by_dev() failed early, GD_NEED_PART_SCAN is still set,
396: * and this will cause that re-assemble partitioned raid device will
397: * creat partition for underlying disk.
398: */
399: clear_bit(GD_NEED_PART_SCAN, &disk->state);
400: if (!(mode & BLK_OPEN_EXCL))
401: bd_abort_claiming(disk->part0, disk_scan_partitions);
402: return ret;
403: }
404:
405: static void add_disk_final(struct gendisk *disk)
406: {
407: struct device *ddev = disk_to_dev(disk);
408:
409: if (!(disk->flags & GENHD_FL_HIDDEN)) {
410: bdev_add(disk->part0, ddev->devt);
411: if (get_capacity(disk))
412: disk_scan_partitions(disk, BLK_OPEN_READ);
413:
414: /*
415: * Announce the disk and partitions after all partitions are
416: * created. (for hidden disks uevents remain suppressed forever)
417: */
418: dev_set_uevent_suppress(ddev, 0);
419: disk_uevent(disk, KOBJ_ADD);
420: }
421:
422: blk_apply_bdi_limits(disk->bdi, &disk->queue->limits);
423: disk_add_events(disk);
424: set_bit(GD_ADDED, &disk->state);
425: }
426:
427: static int __add_disk(struct device *parent, struct gendisk *disk,
428: const struct attribute_group **groups,
429: struct fwnode_handle *fwnode)
430:
431: {
432: struct device *ddev = disk_to_dev(disk);
433: int ret;
434:
435: if (WARN_ON_ONCE(bdev_nr_sectors(disk->part0) > BLK_DEV_MAX_SECTORS))
436: return -EINVAL;
437:
438: if (queue_is_mq(disk->queue)) {
439: /*
440: * ->submit_bio and ->poll_bio are bypassed for blk-mq drivers.
441: */
442: if (disk->fops->submit_bio || disk->fops->poll_bio)
443: return -EINVAL;
444: } else {
445: if (!disk->fops->submit_bio)
446: return -EINVAL;
447: bdev_set_flag(disk->part0, BD_HAS_SUBMIT_BIO);
448: }
449:
450: /*
451: * We do not support partitions with zoned block devices, so do not try
452: * to scan the partitions table.
453: */
454: if (blk_queue_is_zoned(disk->queue))
455: disk->flags |= GENHD_FL_NO_PART;
456:
457: /*
458: * If the driver provides an explicit major number it also must provide
459: * the number of minors numbers supported, and those will be used to
460: * setup the gendisk.
461: * Otherwise just allocate the device numbers for both the whole device
462: * and all partitions from the extended dev_t space.
463: */
464: ret = -EINVAL;
465: if (disk->major) {
466: if (WARN_ON(!disk->minors))
467: goto out;
468:
469: if (disk->minors > DISK_MAX_PARTS) {
]
|
| 122/2 |
2026/11/03 15:18 |
tool |
read-file |
0m
Args: map[File:block/genhd.c FirstLine:530 LineCount:50]
Results: map[Contents: 530:
531: ret = blk_register_queue(disk);
532: if (ret)
533: goto out_put_slave_dir;
534:
535: if (!(disk->flags & GENHD_FL_HIDDEN)) {
536: ret = bdi_register(disk->bdi, "%u:%u",
537: disk->major, disk->first_minor);
538: if (ret)
539: goto out_unregister_queue;
540: bdi_set_owner(disk->bdi, ddev);
541: ret = sysfs_create_link(&ddev->kobj,
542: &disk->bdi->dev->kobj, "bdi");
543: if (ret)
544: goto out_unregister_bdi;
545: } else {
546: /*
547: * Even if the block_device for a hidden gendisk is not
548: * registered, it needs to have a valid bd_dev so that the
549: * freeing of the dynamic major works.
550: */
551: disk->part0->bd_dev = MKDEV(disk->major, disk->first_minor);
552: }
553: return 0;
554:
555: out_unregister_bdi:
556: if (!(disk->flags & GENHD_FL_HIDDEN))
557: bdi_unregister(disk->bdi);
558: out_unregister_queue:
559: blk_unregister_queue(disk);
560: rq_qos_exit(disk->queue);
561: out_put_slave_dir:
562: kobject_put(disk->slave_dir);
563: disk->slave_dir = NULL;
564: out_put_holder_dir:
565: kobject_put(disk->part0->bd_holder_dir);
566: out_del_block_link:
567: sysfs_remove_link(block_depr, dev_name(ddev));
568: pm_runtime_set_memalloc_noio(ddev, false);
569: out_device_del:
570: device_del(ddev);
571: out_free_ext_minor:
572: if (disk->major == BLOCK_EXT_MAJOR)
573: blk_free_ext_minor(disk->first_minor);
574: out:
575: return ret;
576: }
577:
578: /**
579: * add_disk_fwnode - add disk information to kernel list with fwnode
]
|
| 123/2 |
2026/11/03 15:18 |
llm |
debugger |
1m
Model:
Tokens:
input: 127280
output: 77
thoughts: 9758
Thoughts: **A Deep Dive into a Kernel Lock Deprivation Bug**
Okay, so I'm staring at this crash log, and something's clearly gone sideways in the device-mapper code. It's screaming about a lock held when returning to user space, specifically within `elevator_change`. My expert intuition immediately flags a potential race condition involving the request queue freeze mechanism.
The log tells me that `syz.3.1525/11804` is the culprit, and it seems to have a freeze lock held, specifically at `elevator_change` called by the `blk_mq_freeze_queue` function.
I have to carefully analyze what happened. Was this thread related to the `table_load` operation, or the `dev_remove` operation?
I've got a hunch, so let's start with a thorough check of the `dev_remove` path first and re-trace my assumptions. `dev_remove` calls `blk_mark_disk_dead`, which then calls `__blk_freeze_queue_start`. This function increments `q->mq_freeze_depth` and sets `q->mq_freeze_owner`. This appears to be critical.
If `syz.3.1525/11804` is running `dev_remove` and Thread 1 is in `elevator_change`, then we have a potential race!
I've got a scenario where Thread 1 (during `table_load`) might be freezing a queue using `blk_mq_freeze_queue` inside `elevator_change`, and Thread 2 (`dev_remove`) might try to mark the disk as dead. The issue is that the code isn't robust if a queue is frozen during disk removal.
I carefully examined this scenario with `q->mq_freeze_depth`. The goal is to track the owner and depth of queue freezes. The problem is when `blk_mark_disk_dead` is called and `q->mq_freeze_depth` is already at 1. `elevator_change` tries to call `blk_mq_freeze_queue`, but this is where the race happens. There's a subtle interaction happening where the `queue_dying` and the `queue_freeze` flags get out of sync.
Specifically, I have to ensure the `q->q_lockdep_map` is properly released. The analysis reveals an issue in the design of the queue freeze/unfreeze functions. The `blk_freeze_set_owner` function is only executed under `q->mq_freeze_lock`, but `blk_unfreeze_release_lock` is executed *after* the lock is released! That means a race condition where `q->mq_freeze_queue_dying` can be set after `q->mq_freeze_lock` has been released. The second thread can modify the flag and cause `blk_unfreeze_release_lock` not to release the lock!
I need to confirm if `elevator_change` can ever have `q->mq_freeze_queue_dying` set to false.
I have to consider what this crash report means. The critical point is that `rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_)` *was* executed, implying the initial freeze was successful. The problem is that it wasn't released!
The code path shows that `elevator_change`, specifically `blk_mq_freeze_queue` is acquiring a lock and not releasing it. It seems that this must be the `elevator_change` in `add_disk`, and *not* from the `del_gendisk` operation as a result of the crash.
I now focus back on the execution of the freezing and unfreezing of the queue in `table_load`.
I'm now zeroing in on a race condition between the device removal path and the queue registration and unregistration path, and carefully tracing the function calls between `blk_freeze_queue_start` and `blk_mq_unfreeze_queue_nomemrestore`. I now have to check for when `q->mq_freeze_queue_dying` would become `true`.
I check the commit by Ming Lei, where they tried to track queue dying state, and I see a flaw in the assumption that the `q->mq_freeze_*` values are safe to read/write without the lock. They're not. They're only safe if the code holding the `q->mq_freeze_lock` also *releases* the queue dying flag.
I can confirm that the `q->mq_freeze_depth` variable is set correctly: if Thread 2 calls `mutex_lock(&q->mq_freeze_lock)` after the lock is released,
|
| 124/2 |
2026/11/03 15:20 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/locking/mutex.c Name:mutex_unlock]
Results: map[SourceCode: 560: /**
561: * mutex_unlock - release the mutex
562: * @lock: the mutex to be released
563: *
564: * Unlock a mutex that has been locked by this task previously.
565: *
566: * This function must not be used in interrupt context. Unlocking
567: * of a not locked mutex is not allowed.
568: *
569: * The caller must ensure that the mutex stays alive until this function has
570: * returned - mutex_unlock() can NOT directly be used to release an object such
571: * that another concurrent task can free it.
572: * Mutexes are different from spinlocks & refcounts in this aspect.
573: *
574: * This function is similar to (but not equivalent to) up().
575: */
576: void __sched mutex_unlock(struct mutex *lock)
577: {
578: #ifndef CONFIG_DEBUG_LOCK_ALLOC
579: if (__mutex_unlock_fast(lock))
580: return;
581: #endif
582: __mutex_unlock_slowpath(lock, _RET_IP_);
583: }
SourceFile:kernel/locking/mutex.c]
|
| 125/2 |
2026/11/03 15:20 |
tool |
read-file |
0m
Args: map[File:kernel/locking/mutex.c FirstLine:530 LineCount:60]
Results: map[Contents: 530:
531: fail:
532: /*
533: * If we fell out of the spin path because of need_resched(),
534: * reschedule now, before we try-lock the mutex. This avoids getting
535: * scheduled out right after we obtained the mutex.
536: */
537: if (need_resched()) {
538: /*
539: * We _should_ have TASK_RUNNING here, but just in case
540: * we do not, make it so, otherwise we might get stuck.
541: */
542: __set_current_state(TASK_RUNNING);
543: schedule_preempt_disabled();
544: }
545:
546: return false;
547: }
548: #else
549: static __always_inline bool
550: mutex_optimistic_spin(struct mutex *lock, struct ww_acquire_ctx *ww_ctx,
551: struct mutex_waiter *waiter)
552: {
553: return false;
554: }
555: #endif
556:
557: static noinline void __sched __mutex_unlock_slowpath(struct mutex *lock, unsigned long ip)
558: __releases(lock);
559:
560: /**
561: * mutex_unlock - release the mutex
562: * @lock: the mutex to be released
563: *
564: * Unlock a mutex that has been locked by this task previously.
565: *
566: * This function must not be used in interrupt context. Unlocking
567: * of a not locked mutex is not allowed.
568: *
569: * The caller must ensure that the mutex stays alive until this function has
570: * returned - mutex_unlock() can NOT directly be used to release an object such
571: * that another concurrent task can free it.
572: * Mutexes are different from spinlocks & refcounts in this aspect.
573: *
574: * This function is similar to (but not equivalent to) up().
575: */
576: void __sched mutex_unlock(struct mutex *lock)
577: {
578: #ifndef CONFIG_DEBUG_LOCK_ALLOC
579: if (__mutex_unlock_fast(lock))
580: return;
581: #endif
582: __mutex_unlock_slowpath(lock, _RET_IP_);
583: }
584: EXPORT_SYMBOL(mutex_unlock);
585:
586: /**
587: * ww_mutex_unlock - release the w/w mutex
588: * @lock: the mutex to be released
589: *
]
|
| 126/2 |
2026/11/03 15:20 |
llm |
debugger-compressor |
12m
Model:
Reply: ### 1. Approaches Tried and Their Results
1. **Initial Crash Analysis**:
- Analyzed lockdep warning: `WARNING: lock held when returning to user space!`, lock held: `&q->q_usage_counter(queue)#52` at `elevator_change+0x194/0x480 block/elevator.c:668` (`memflags = blk_mq_freeze_queue(q);`).
- Context message: `device-mapper: ioctl: device has been removed from the dev hash table.` at `drivers/md/dm-ioctl.c:1680` (in `table_load`) or `886` (`dm_get_inactive_table`).
- Syzkaller reproducer executes:
- `openat("/dev/mapper/control")` -> `fd0`, `fd1`
- `ioctl(DM_DEV_CREATE, name="syza2")`
- `ioctl(DM_TABLE_LOAD, target="multipath ...")`
- `ioctl(DM_DEV_REMOVE, flags=..., dev=...)`
2. **Source Inspection of `elevator_change` and `blk-mq` freeze/unfreeze logic**:
- `elevator_change()` (`block/elevator.c:653`):
- Line 668: `memflags = blk_mq_freeze_queue(q);`
- Line 683: `blk_mq_unfreeze_queue(q, memflags);`
- Notice: the lock held is NOT a mutex, but the lockdep annotation map `&q->q_lockdep_map`, named `"&q->q_usage_counter(queue)"`.
- In `block/blk-core.c:500`: `lockdep_init_map(&q->q_lockdep_map, "&q->q_usage_counter(queue)", &q->q_lock_cls_key, 0);`.
3. **Tracing lockdep acquire/release semantics in `blk-mq`**:
- In `block/blk.h`:
```c
static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
if (!q->mq_freeze_queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
```
- In `block/blk-mq.c`:
- `blk_freeze_set_owner()` (called when `!q->mq_freeze_depth`):
```c
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
q->mq_freeze_disk_dead = !q->disk ||
test_bit(GD_DEAD, &q->disk->state) ||
!blk_queue_registered(q);
q->mq_freeze_queue_dying = blk_queue_dying(q);
```
- `blk_unfreeze_check_owner()` checks owner task and decrements depth. If zero, clears owner.
- `__blk_mq_unfreeze_queue(q, false)` calls `blk_unfreeze_check_owner(q)`. If true, `blk_mq_unfreeze_queue` calls `blk_unfreeze_release_lock(q)`.
4. **Git history analysis of `blk_freeze_*` and queue dying states**:
- Identified recent commits:
- `f1be1788a32e`: "block: model freeze & enter queue as lock for supporting lockdep"
- `6a78699838a0`: "block: always verify unfreeze lock on the owner task"
- `6f491a8d4b92`: "block: track disk DEAD state automatically for modeling queue freeze lockdep"
- `f6661b1d0525`: "block: track queue dying state automatically for modeling queue freeze lockdep"
- `7e9a46004b47`: "block: set QUEUE_FLAG_DYING unconditionally in blk_mark_disk_dead()"
5. **Investigation of DM lifecycle (`table_load` vs `dev_remove`)**:
- `DM_DEV_CREATE`: allocates `mapped_device` (type `DM_TYPE_NONE`, disk allocated with bio-based queue).
- `DM_TABLE_LOAD` with multipath:
- `dm_get_md_type(md) == DM_TYPE_NONE` -> calls `dm_setup_md_queue(md, t)`.
- `dm_setup_md_queue()` initializes request-based queue (`dm_mq_init_request_queue`), sets limits, then calls `add_disk(md->disk)`.
- `add_disk()` -> `device_add_disk()` -> `__add_disk()` -> `blk_register_queue(disk)`:
- In `blk_register_queue()`:
```c
if (queue_is_mq(q))
elevator_set_default(q);
```
- `elevator_set_default()` calls `elevator_change(q, &ctx)` to set "mq-deadline".
- In `elevator_change()`: calls `blk_mq_freeze_queue(q)` and later `blk_mq_unfreeze_queue(q, memflags)`.
- Concurrently, `DM_DEV_REMOVE`:
- Checks `dm_lock_for_deletion()`. (Note: `holders` is not checked here, only `dm_open_count(md)`!).
- Removes hash cell: `t = __hash_remove(hc);`.
- Calls `dm_put(md); dm_destroy(md);`.
- `__dm_destroy()` calls `blk_mark_disk_dead(md->disk);` and later `free_dev(md)` -> `cleanup_mapped_device(md)` -> `del_gendisk(md->disk);`.
---
### 2. Verified Facts
1. **Lock in Question**:
- The reported held lock `&q->q_usage_counter(queue)#52` is NOT an actual mutex or semaphore that was forgotten in kernel data structures, but the lockdep map `q->q_lockdep_map` acquired via `rwsem_acquire(&q->q_lockdep_map, ...)` in `blk_freeze_acquire_lock(q)`.
2. **Lockdep State Condition in `blk_unfreeze_release_lock()`**:
- `blk_freeze_acquire_lock()` acquires `&q->q_lockdep_map` IF AND ONLY IF `!q->mq_freeze_queue_dying`.
- `blk_unfreeze_release_lock()` releases `&q->q_lockdep_map` IF AND ONLY IF `!q->mq_freeze_queue_dying`.
3. **`mq_freeze_queue_dying` and `mq_freeze_disk_dead` are stored in `struct request_queue`**:
- Both are stored as fields on `struct request_queue` (`q->mq_freeze_queue_dying`, `q->mq_freeze_disk_dead`) rather than local variables on the task struct or stack!
- They are initialized in `blk_freeze_set_owner()` under `&q->mq_freeze_lock` when `!q->mq_freeze_depth`:
```c
q->mq_freeze_disk_dead = !q->disk || test_bit(GD_DEAD, &q->disk->state) || !blk_queue_registered(q);
q->mq_freeze_queue_dying = blk_queue_dying(q);
```
4. **How the Lock Leak Happens**:
- Thread A (running `table_load` -> `add_disk` -> `blk_register_queue` -> `elevator_set_default` -> `elevator_change`):
1. Calls `blk_mq_freeze_queue(q)`:
- `q->mq_freeze_depth` is 0.
- `blk_freeze_set_owner(q, current)` runs: `q->mq_freeze_owner = current; q->mq_freeze_queue_dying = false;`.
- `blk_freeze_acquire_lock(q)` runs: because `!q->mq_freeze_queue_dying` is true, `rwsem_acquire(&q->q_lockdep_map)` is called.
2. Thread A is running `elevator_change()` (quiescing, switching sched, etc.).
- Meanwhile, Thread B (or concurrent removal operation) runs `blk_mark_disk_dead()` or something similar on the queue, or modifies queue state:
- Wait, how can `q->mq_freeze_queue_dying` change while Thread A is frozen?
- Or what if Thread B calls `blk_freeze_queue_start()` or `blk_mark_disk_dead()`?
- Let's check the exact mechanism where `q->mq_freeze_queue_dying` gets corrupted or where freeze depth / owner behaves unexpectedly.
---
### 3. Active Hypotheses & Lines of Investigation
#### Hypothesis 1: `q->mq_freeze_queue_dying` is overwritten or mutated between freeze and unfreeze
- Notice: `q->mq_freeze_queue_dying` is a field in `struct request_queue`.
- Does another thread call `blk_freeze_set_owner()`?
- `blk_freeze_set_owner(q, owner)`:
```c
if (!q->mq_freeze_depth) { ... }
if (owner == q->mq_freeze_owner)
q->mq_freeze_owner_depth += 1;
return false;
```
If `q->mq_freeze_depth > 0`, it does NOT touch `q->mq_freeze_queue_dying`.
- Wait! What if `blk_queue_start_drain()` or something else modifies it? No, nobody writes `q->mq_freeze_queue_dying` except `blk_freeze_set_owner()`.
- Wait! Could `q->mq_freeze_queue_dying` NOT be overwritten, but rather `blk_unfreeze_check_owner()` returns false?
- In `__blk_mq_unfreeze_queue`:
```c
unfreeze = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
return unfreeze;
```
If `unfreeze` is false, `blk_unfreeze_release_lock()` is NEVER CALLED!
Why would `blk_unfreeze_check_owner(q)` return false?
```c
static bool blk_unfreeze_check_owner(struct request_queue *q)
{
if (q->mq_freeze_owner != current)
return false;
if (--q->mq_freeze_owner_depth == 0) {
q->mq_freeze_owner = NULL;
return true;
}
return false;
}
```
`elevator_change` froze the queue once. Depth was 1. If nobody else touched it, `unfreeze` should be true.
#### Hypothesis 2: A nested freeze/unfreeze inside `elevator_change` or nested helper clobbers or mismatched freeze
- Check all freeze/unfreeze calls during `elevator_change`:
- `elevator_change`:
- `memflags = blk_mq_freeze_queue(q);` (freeze depth 1)
- `blk_mq_cancel_work_sync(q);`
- `mutex_lock(&q->elevator_lock);`
- `elevator_switch(q, ctx);`:
- `blk_mq_quiesce_queue(q);`
- `blk_mq_unquiesce_queue(q);`
- `mutex_unlock(&q->elevator_lock);`
- `blk_mq_unfreeze_queue(q, memflags);` (unfreeze depth drops to 0)
- `if (!ret) ret = elevator_change_done(q, ctx);`:
- `if (ctx->new) ret = elv_register_queue(q, ctx->new, ...);`
- `if (ret) elv_exit_and_release(ctx, q);`:
- In `elv_exit_and_release`:
- `memflags = blk_mq_freeze_queue(q);`
- `elv_exit(...)`
- `blk_mq_unfreeze_queue(q, memflags);`
- Wait! Did `elevator_switch` or something else call freeze?
- Wait, what about `elevator_match`?
In `elevator_change`:
```c
if (!(q->elevator && elevator_match(q->elevator->type, ctx->name)))
ret = elevator_switch(q, ctx);
```
#### Hypothesis 3: The call to `elevator_change` is during `del_gendisk` or `blk_unregister_queue`!
- LOOK AT THE CALL TRACE:
Where is `elevator_change` called?
References to `elevator_change`:
1. `elevator_set_default(q)` -> from `blk_register_queue()` line 992
2. `elevator_set_none(q)` -> from `blk_unregister_queue()` line 1073!
Wait! Look at `blk_unregister_queue()`:
```c
void blk_unregister_queue(struct gendisk *disk)
{
...
if (queue_is_mq(q))
elevator_set_none(q);
...
}
```
`elevator_set_none()` calls:
```c
void elevator_set_none(struct request_queue *q)
{
struct elv_change_ctx ctx = {
.name = "none",
};
err = elevator_change(q, &ctx);
...
}
```
Look at the warning line in the prompt:
```
syz.3.1525/11804 is leaving the kernel with locks still held!
locks held by syz.3.1525/11804: 1, last CPU#0:
#0: ffff88805abdd468 (&q->q_usage_counter(queue)#52){+.+.}-{0:0}, at: blk_mq_freeze_queue include/linux/blk-mq.h:959 [inline]
#0: ffff88805abdd468 (&q->q_usage_counter(queue)#52){+.+.}-{0:0}, at: elevator_change+0x194/0x480 block/elevator.c:668
```
Wait! The process exiting the syscall and leaving the kernel with lock held is `syz.3.1525/11804`!
And what syscall was `syz.3.1525/11804` running?
In the reproducer:
```c
syscall(__NR_ioctl, /*fd=*/r[1], /*cmd=*/DM_TABLE_LOAD, ...);
syscall(__NR_ioctl, /*fd=*/r[0], /*cmd=*/DM_DEV_REMOVE, ...);
```
Wait! In `del_gendisk()` (`block/genhd.c`):
Let's look at `del_gendisk()`:
```c
void del_gendisk(struct gendisk *disk)
{
...
set = disk->queue->tag_set;
disable_elv_switch(disk->queue);
memflags = memalloc_noio_save();
down_read(&set->update_nr_hwq_lock);
__del_gendisk(disk);
up_read(&set->update_nr_hwq_lock);
memalloc_noio_restore(memflags);
}
```
AND inside `__del_gendisk(disk)`:
```c
static void __del_gendisk(struct gendisk *disk)
{
...
mutex_lock(&disk->open_mutex);
start_drain = __blk_mark_disk_dead(disk);
if (start_drain)
blk_freeze_acquire_lock(q);
...
mutex_unlock(&disk->open_mutex);
...
blk_unregister_queue(disk);
```
LOOK AT THAT!
In `__del_gendisk`:
1. `start_drain = __blk_mark_disk_dead(disk);`
`__blk_mark_disk_dead(disk)` calls `blk_queue_start_drain(disk->queue)`.
`blk_queue_start_drain` calls `__blk_freeze_queue_start(q, current)`.
`__blk_freeze_queue_start(q, current)` calls:
```c
freeze = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
...
```
`q->mq_freeze_depth` becomes 1!
`q->mq_freeze_owner` becomes `current`!
`q->mq_freeze_owner_depth` becomes 1!
`q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying` are recorded!
Then in `__del_gendisk`:
```c
if (start_drain)
blk_freeze_acquire_lock(q);
```
Locks are acquired (or not, depending on flags).
2. Then later in `__del_gendisk`:
`blk_unregister_queue(disk);`
3. `blk_unregister_queue(disk)` calls:
`elevator_set_none(q);`
4. `elevator_set_none(q)` calls:
`elevator_change(q, &ctx);`
5. In `elevator_change()`:
Line 668: `memflags = blk_mq_freeze_queue(q);`
WHAT DOES `blk_mq_freeze_queue(q)` DO?
It calls `blk_freeze_queue_start(q)`!
And what does `blk_freeze_queue_start(q)` do?
```c
void blk_freeze_queue_start(struct request_queue *q)
{
if (__blk_freeze_queue_start(q, current))
blk_freeze_acquire_lock(q);
}
```
What does `__blk_freeze_queue_start(q, current)` do?!
```c
mutex_lock(&q->mq_freeze_lock);
freeze = blk_freeze_set_owner(q, owner);
```
AND WHAT DOES `blk_freeze_set_owner(q, owner)` DO WHEN `q->mq_freeze_depth > 0` AND `owner == q->mq_freeze_owner`???
```c
if (owner == q->mq_freeze_owner)
q->mq_freeze_owner_depth += 1;
return false;
```
IT RETURNS `false`!
So `freeze` is FALSE!
So `blk_freeze_acquire_lock(q)` is NOT called in `blk_freeze_queue_start(q)`!
Wait... but the lockdep report says:
`lock held ... at: blk_mq_freeze_queue ... at elevator_change+0x194`!
Why does lockdep say it WAS acquired at `elevator_change`?!
BECAUSE `elevator_change` WAS the one that called `blk_freeze_acquire_lock`!
Why? Why would `blk_freeze_set_owner` return TRUE in `elevator_change`?!
When `q->mq_freeze_depth == 0`!
#### Hypothesis 4: Look closely at when `blk_register_queue` is called vs `del_gendisk`
- Why does `dm_setup_md_queue()` call `add_disk()`?
- And why does `del_gendisk()` happen in `cleanup_mapped_device()`?
- Could `del_gendisk` and `table_load` race? Or could `table_load` fail?
- What does the reproducer actually do?
Let's check the reproducer again:
```c
// 1. open control fd 0 and fd 1
// 2. DM_DEV_CREATE: creates "syza2"
// 3. DM_TABLE_LOAD:
// target: multipath, 1 retain_attached_hw_handler, 1 rdac, 0 groups
// 4. DM_DEV_REMOVE:
// removes the device
```
- Wait! Look at `DM_TABLE_LOAD` in the reproducer:
Target params: `"1 retain_attached_hw_handler 1 rdac 0 0"`.
Does `populate_table` succeed or fail?
Wait! Notice the DM message in the crash report:
`device-mapper: ioctl: device has been removed from the dev hash table.`
WHERE does that message come from?
Look at `drivers/md/dm-ioctl.c`:
```c
static int table_load(...) {
...
if (dm_get_md_type(md) == DM_TYPE_NONE) {
/* setup md->queue to reflect md's type (may block) */
r = dm_setup_md_queue(md, t);
if (r) {
DMERR("unable to set up device queue for new table.");
goto err_unlock_md_type;
}
}
dm_unlock_md_type(md);
...
down_write(&_hash_lock);
hc = dm_get_mdptr(md);
if (!hc) {
DMERR("device has been removed from the dev hash table.");
up_write(&_hash_lock);
dm_ima_free_context(ima_context);
r = -ENXIO;
goto err_destroy_table;
}
...
}
```
`table_load()` reached line 1680:
`DMERR("device has been removed from the dev hash table.");`!
`hc` was NULL!
Because `dev_remove` ALREADY removed `hc` from `_hash_lock` while `table_load` was running!
And then `dev_remove` called:
`dm_destroy(md)`!
---
### 4. Critical Code Paths and Snippets
- **`drivers/md/dm.c` - `__dm_destroy()`**:
```c
blk_mark_disk_dead(md->disk);
...
free_dev(md); // calls cleanup_mapped_device(md) -> del_gendisk(md->disk)
```
- **`block/genhd.c` - `blk_mark_disk_dead()`**:
```c
void blk_mark_disk_dead(struct gendisk *disk)
{
blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
__blk_mark_disk_dead(disk);
blk_report_disk_dead(disk, true);
}
```
- **`block/genhd.c` - `__blk_mark_disk_dead()`**:
```c
static bool __blk_mark_disk_dead(struct gendisk *disk)
{
if (test_and_set_bit(GD_DEAD, &disk->state))
return false;
if (test_bit(GD_OWNS_QUEUE, &disk->state))
blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
set_capacity(disk, 0);
return blk_queue_start_drain(disk->queue);
}
```
- **`block/blk-mq.c` - `blk_freeze_set_owner()`**:
```c
static bool blk_freeze_set_owner(struct request_queue *q, struct task_struct *owner)
{
if (!owner) return false;
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
q->mq_freeze_disk_dead = !q->disk ||
test_bit(GD_DEAD, &q->disk->state) ||
!blk_queue_registered(q);
q->mq_freeze_queue_dying = blk_queue_dying(q);
return true;
}
if (owner == q->mq_freeze_owner)
q->mq_freeze_owner_depth += 1;
return false;
}
```
- **`block/blk.h` - `blk_freeze_acquire_lock()` & `blk_unfreeze_release_lock()`**:
```c
static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
if (!q->mq_freeze_queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
```
---
### 5. Watch Out / Potential Reasoning Pitfalls
- Do NOT confuse the runtime lock with lockdep annotation: `q->q_lockdep_map` is a fake rwsem map used strictly for lockdep verification of `q_usage_counter`.
- Note how `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead` are per-queue fields, NOT per-task or local to the freeze caller!
- Consider what happens if `blk_mark_disk_dead()` sets `QUEUE_FLAG_DYING` while or after `elevator_change()` is executing, or if `elevator_set_default()` in `add_disk()` races with `del_gendisk()`.
- Notice `del_gendisk()` acquires `down_read(&set->update_nr_hwq_lock)`.
Meanwhile, `elevator_change()` has `lockdep_assert_held(&set->update_nr_hwq_lock)`.
In `add_disk_fwnode()`:
`down_read(&set->update_nr_hwq_lock); __add_disk(...); up_read(...);`.
Both `add_disk` and `del_gendisk` take `update_nr_hwq_lock` with `down_read`! So they do NOT exclude each other via `update_nr_hwq_lock`!
---
### 6. Next Steps
1. **Examine the exact race between `table_load` and `dev_remove`**:
- Trace how `table_load` (calling `dm_setup_md_queue` -> `add_disk`) executes concurrently with `dev_remove` (calling `dm_destroy` -> `blk_mark_disk_dead` / `del_gendisk`).
- Specifically check:
- Does Thread 1 do `blk_mq_freeze_queue` in `elevator_change`, where `blk_queue_dying(q)` was `false` at freeze time?
- Then Thread 2 (or same thread in error unwind) calls `blk_queue_flag_set(QUEUE_FLAG_DYING, q)`?
- Wait: does `q->mq_freeze_queue_dying` change, OR does `blk_freeze_set_owner` get called again, OR does something else happen?
- What if `QUEUE_FLAG_DYING` is set in `blk_mark_disk_dead()`, but where did `q->mq_freeze_queue_dying` get set?
2. **Examine `elevator_set_none()` in `del_gendisk()`**:
- Could `elevator_change` be called from `elevator_set_none` in `del_gendisk` while `QUEUE_FLAG_DYING` was ALREADY set?
- Wait! If `QUEUE_FLAG_DYING` was already set, `blk_queue_dying(q)` is `true`!
- If `blk_queue_dying(q)` is `true`, then `blk_freeze_set_owner()` sets `q->mq_freeze_queue_dying = true`, so `blk_freeze_acquire_lock()` does NOT acquire `q_lockdep_map`!
- BUT the crash log shows `q_lockdep_map` WAS acquired at `elevator_change` line 668!
- This proves that when `elevator_change` called `blk_freeze_acquire_lock`, `q->mq_freeze_queue_dying` was FALSE!
- How did it NOT get released at line 683? Or was it never released because something panicked, or did `q->mq_freeze_queue_dying` become TRUE before unfreeze?
3. **Check the exact mechanism of lock leak**:
- Check where `q->mq_freeze_queue_dying` or `q->mq_freeze_owner` is modified while queue is frozen.
- Check if `disable_elv_switch` or `QUEUE_FLAG_NO_ELV_SWITCH` interacts with `elevator_set_default` or `elevator_change`.
- Read `block/elevator.c` error handling paths in `elevator_change` to see if there is an early return or unbalanced unfreeze.
Tokens:
input: 77175
output: 7296
thoughts: 0
|
| 127/2 |
2026/11/03 15:33 |
llm |
debugger |
0m
Model:
Tokens:
input: 51441
output: 40
thoughts: 1936
Thoughts: **Race Condition Analysis in Block Device Freezing/Unfreezing**
Okay, let's break this down. My initial thought is triggered by the potential for preemption within `__mutex_unlock_slowpath`, specifically how `wake_up_q` could immediately yield control to another thread (`Thread 2`) *before* the original thread (`Thread 1`) finishes unlocking. This seems problematic with `mq_freeze_lock` and queue operations.
My first scenario involves `Thread 2` trying to acquire `q->mq_freeze_lock` while `Thread 1` holds it in either `__blk_freeze_queue_start` or `__blk_mq_unfreeze_queue`. If `Thread 2` blocks, waits, then `Thread 1` unlocks, the immediate wakeup within the `__mutex_unlock_slowpath` could lead to `Thread 2` running *immediately*. This scenario is particularly worrying because `Thread 2` could set `q->mq_freeze_queue_dying = true` using `blk_freeze_set_owner` *before* `Thread 1` resumes from the unlock operation and potentially skips a critical `q_lockdep_map` release in `blk_unfreeze_release_lock`.
I'm now also considering a second, related scenario: if `Thread 2` does *not* block, are there other ways the `q->mq_freeze_queue_dying` or `q_lockdep_map` state can be corrupted? I'm focusing on `__blk_freeze_queue_start`.
Examining `blk_freeze_queue_start` in `block/blk-mq.c`, I notice a pattern of locking, setting freeze-related state (including `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying` if dying flag is set), unlocking, running potentially long-running or preemption-prone actions, and only *then* acquiring the lock with `blk_freeze_acquire_lock`. `blk_mq_unfreeze_queue_nomemrestore` follows a similar pattern. This non-atomic operation could definitely be problematic, especially with preemptible kernel.
I'm now focusing on a specific race: What if `Thread 2` (`dev_remove`, which calls `blk_mark_disk_dead`) runs *before* `Thread 1` (a `table_load` path)? Specifically, what happens if `blk_mark_disk_dead` runs first, meaning a call to `__blk_freeze_queue_start`?
If `Thread 2` runs `blk_mark_disk_dead` *before* `elevator_change` from `Thread 1`, then `q->mq_freeze_depth` becomes 1. This would cause a problem: if the depth is 1, then the later `blk_mq_freeze_queue(q)` call from `Thread 1` (in `elevator_change`) now does not acquire the freeze lock and sets the disk into an inconsistent state.
Wait! There's also another interesting point: `blk_mark_disk_dead` actually *calls* `__blk_freeze_queue_start`. This is confusing because the `blk_mark_disk_dead` path, the disk is being destroyed/removed. Why are we "freezing" the queue here during teardown, especially if the subsequent calls to unfreeze might not happen? This seems like a potential double free or a race on `q->mq_freeze_lock`. I need to review what calls are made to `blk_freeze_acquire_lock` and `blk_unfreeze_release_lock` from the perspective of how a device is being removed!
Okay, I need to investigate where `blk_freeze_acquire_lock` and `blk_unfreeze_release_lock` are paired in `__del_gendisk` to better understand the correct locking and unlocking behaviour in the device teardown path. The race looks like it may involve `__del_gendisk`!
|
| 128/2 |
2026/11/03 15:33 |
tool |
read-file |
0m
Args: map[File:block/genhd.c FirstLine:720 LineCount:75]
Results: map[Contents: 720: * Tell the file system to write back all dirty data and shut down if
721: * it hasn't been notified earlier.
722: */
723: if (!test_bit(GD_DEAD, &disk->state))
724: blk_report_disk_dead(disk, false);
725:
726: /*
727: * Drop all partitions now that the disk is marked dead.
728: */
729: mutex_lock(&disk->open_mutex);
730: start_drain = __blk_mark_disk_dead(disk);
731: if (start_drain)
732: blk_freeze_acquire_lock(q);
733: xa_for_each_start(&disk->part_tbl, idx, part, 1)
734: drop_partition(part);
735: mutex_unlock(&disk->open_mutex);
736:
737: if (!(disk->flags & GENHD_FL_HIDDEN)) {
738: sysfs_remove_link(&disk_to_dev(disk)->kobj, "bdi");
739:
740: /*
741: * Unregister bdi before releasing device numbers (as they can
742: * get reused and we'd get clashes in sysfs).
743: */
744: bdi_unregister(disk->bdi);
745: }
746:
747: blk_unregister_queue(disk);
748:
749: kobject_put(disk->part0->bd_holder_dir);
750: kobject_put(disk->slave_dir);
751: disk->slave_dir = NULL;
752:
753: part_stat_set_all(disk->part0, 0);
754: disk->part0->bd_stamp = 0;
755: sysfs_remove_link(block_depr, dev_name(disk_to_dev(disk)));
756: pm_runtime_set_memalloc_noio(disk_to_dev(disk), false);
757: device_del(disk_to_dev(disk));
758:
759: blk_mq_freeze_queue_wait(q);
760:
761: blk_throtl_cancel_bios(disk);
762:
763: blk_sync_queue(q);
764: blk_flush_integrity();
765:
766: if (queue_is_mq(q))
767: blk_mq_cancel_work_sync(q);
768:
769: rq_qos_exit(q);
770:
771: /*
772: * If the disk does not own the queue, allow using passthrough requests
773: * again. Else leave the queue frozen to fail all I/O.
774: */
775: if (!test_bit(GD_OWNS_QUEUE, &disk->state))
776: __blk_mq_unfreeze_queue(q, true);
777: else if (queue_is_mq(q))
778: blk_mq_exit_queue(q);
779:
780: if (start_drain)
781: blk_unfreeze_release_lock(q);
782: }
783:
784: static void disable_elv_switch(struct request_queue *q)
785: {
786: struct blk_mq_tag_set *set = q->tag_set;
787: WARN_ON_ONCE(!queue_is_mq(q));
788:
789: down_write(&set->update_nr_hwq_lock);
790: blk_queue_flag_set(QUEUE_FLAG_NO_ELV_SWITCH, q);
791: up_write(&set->update_nr_hwq_lock);
792: }
793:
794: /**
]
|
| 129/2 |
2026/11/03 15:33 |
llm |
debugger |
0m
Model:
Tokens:
input: 54578
output: 29
thoughts: 98
Thoughts: Okay, here's the summary, tailored for an expert audience, in the first person:
**Investigating a Potential Issue in the Block Layer**
Wait a second! My internal radar is pinging. I need to zoom in on something. Specifically, I need to compare how `__del_gendisk` interacts with `blk_mark_disk_dead`. This smells like a subtle timing issue or a potential race condition and I need to be sure I'm following the correct execution path.
Hold on, let's broaden the search a bit. I should really check if there's been any chatter about `blk_mark_disk_dead`, `mq_freeze_queue_dying`, or `blk_unfreeze_release_lock` on LKML, or in the git history. We know how these pieces work together, let's make sure we've caught all potential issues. I'll need to see if any recent commits touch these areas directly or indirectly.
Alright, time to crack open `git-log` on `block/`. Let's see if we can find any recent commits that might shed some light on the issue. This could be a refactor, a bug fix, or even a new feature that could have unintended consequences. Let's see if we can find any recent commits that touch these areas directly or indirectly. It's time to dig into the recent changes and see what we can find.
|
| 130/2 |
2026/11/03 15:34 |
tool |
git-log |
0m
Args: map[Count:30 PathPrefix:block/]
Results: map[Output:c8c53d669d4e blk-crypto: fix NULL deref and UAF in __blk_crypto_evict_key()
aa977f5d9674 block: fix kernel-doc warnings in blk-map.c and blk-mq-dma.c
0150554a3f38 blk-iocost: publish hweights as one atomic value
c810ee88cdab blk-iocost: abort weight transfer on invalid donation weights
10b249e9b05e blk-mq: free the bitmaps of tags in the SRCU callback
6c55f9431724 block: partitions/mac: compute the sectors in 64 bits
4fcc499ea9bc blk-mq: set up a queue under tag_list_lock
89a2381482d8 blk-mq: exit the hctxs of a queue under tag_list_lock
71ec3c7d6db8 blk-mq: quiesce a queue that joins a quiesced tag set
035236c9e135 blk-mq-dma: initialize the dma state for P2P, too
0db9f8968a89 blk-mq: don't forget a timer the driver has restarted
9531230ee1fc blk-mq: don't bring back flags of a completed request
620cfc7a6642 blk-mq: keep sharing tags fairly after a queue update
24974185999f blk-mq: don't trust the cookie in blk_mq_poll()
67c43ceaa29e block: don't lose the status of a failed flush request
cebb1c2331c2 block: fix use-after-free of the disk in sync_bdevs()
045cbfc369f5 block: don't enter reclaim under rq_qos_mutex
ac81a07a0bd5 blk-throttle: make blkio.reset_stats reset I/O counts
587edb931fdd blk-throttle: pass the I/O counts of a dead group on
020f61242d6e blk-iolatency: flush enable_work after going offline
4def096314cf blk-cgroup: don't free a blkg with its punt work queued
e335b853d919 blk-cgroup: fix root io.stat byte counts on 32-bit
7d96874ba80b blk-throttle: don't truncate the cgroup v1 iops limits
05ce1df37567 blk-iocost: free struct ioc after a grace period
0e1daaf9b20d blk-cgroup: keep the old blkg while reassociating a bio
21b88cc8bafc block: fix recursive i_rwsem locking in blkdev_write_iter()
82e72ea18d0a block: advance iterator after copy-in for SG_DXFER_TO_FROM_DEV
9a6cb1da4f3b scsi: handle out-of-range SG_SET_TIMEOUT values
c84de57efe88 super: convert to plain hashtable
bcbd808652e1 block: reject dma-bufs larger than 4GiB
]
|
| 131/2 |
2026/11/03 15:34 |
llm |
debugger |
0m
Model:
Tokens:
input: 55516
output: 91
thoughts: 90
Thoughts: Okay, let's dive into this code.
**Investigating Recent Block Layer Commit Behavior**
Alright, time to refresh my memory and pinpoint the potential causes for that observed behavior. First, I need to check the `git-show` output for the commits that seem most relevant. Specifically, I want to review commit `7e9a46004b47`, which appears to unconditionally set `QUEUE_FLAG_DYING` in `blk_mark_disk_dead()`. That sounds like a key candidate, and I want to see exactly *how* that was changed. I'll also be reviewing commit `6a78699838a0`, which has to do with always verifying the unfreeze lock on the owner task. That could relate. Finally, I need to quickly examine `6f491a8d4b92` as well, just to make sure I don't miss any obvious, related changes in that area, as well. Let's start with those.
|
| 132/2 |
2026/11/03 15:34 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 7e9a46004b471eaf69b082c473d865316a4158e0
Author: θ‘θΏε€ <hulianqin@vivo.com>
Date: Wed Aug 12 11:59:04 2026 +0000
block: set QUEUE_FLAG_DYING unconditionally in blk_mark_disk_dead()
Disks created via blk_mq_alloc_disk_for_queue() (e.g. SCSI SD disks)
do not have GD_OWNS_QUEUE set. Currently __blk_mark_disk_dead() only
sets QUEUE_FLAG_DYING when GD_OWNS_QUEUE is set, so for such disks
blk_queue_enter() and __bio_queue_enter() cannot detect the dying
state via blk_queue_dying() and remain blocked waiting for I/O that
will never complete after surprise removal.
blk_mark_disk_dead() is the explicit "surprise removal" API -- the
caller has already decided the disk is dead. Setting QUEUE_FLAG_DYING
unconditionally here is appropriate: any in-flight I/O from other
threads should get -ENODEV immediately from blk_queue_enter()
regardless of GD_OWNS_QUEUE ownership.
For disks that already have GD_OWNS_QUEUE set, __blk_mark_disk_dead()
will set the flag again which is harmless.
Fixes: 6f8191fdf41d ("block: simplify disk shutdown")
Cc: stable@vger.kernel.org
Signed-off-by: Lianqin Hu <hulianqin@vivo.com>
Reviewed-by: Christoph Hellwig <hch@lst.de>
Link: https://patch.msgid.link/PUZPR06MB62247E82E66A3ED46CC3E6C7D2DC2@PUZPR06MB6224.apcprd06.prod.outlook.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/genhd.c b/block/genhd.c
index df2c3c69b467..7b089e2d52c4 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -681,6 +681,7 @@ static bool __blk_mark_disk_dead(struct gendisk *disk)
*/
void blk_mark_disk_dead(struct gendisk *disk)
{
+ blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
__blk_mark_disk_dead(disk);
blk_report_disk_dead(disk, true);
}
]
|
| 133/2 |
2026/11/03 15:34 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 6a78699838a0ddeed3620ddf50c1521f1fe1e811
Author: Ming Lei <ming.lei@redhat.com>
Date: Thu Oct 31 21:37:19 2024 +0800
block: always verify unfreeze lock on the owner task
commit f1be1788a32e ("block: model freeze & enter queue as lock for
supporting lockdep") tries to apply lockdep for verifying freeze &
unfreeze. However, the verification is only done the outmost freeze and
unfreeze. This way is actually not correct because q->mq_freeze_depth
still may drop to zero on other task instead of the freeze owner task.
Fix this issue by always verifying the last unfreeze lock on the owner
task context, and make sure both the outmost freeze & unfreeze are
verified in the current task.
Fixes: f1be1788a32e ("block: model freeze & enter queue as lock for supporting lockdep")
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241031133723.303835-4-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-core.c b/block/blk-core.c
index 09d10bb95fda..4f791a3114a1 100644
--- a/block/blk-core.c
+++ b/block/blk-core.c
@@ -287,7 +287,7 @@ bool blk_queue_start_drain(struct request_queue *q)
* entering queue, so we call blk_freeze_queue_start() to
* prevent I/O from crossing blk_queue_enter().
*/
- bool freeze = __blk_freeze_queue_start(q);
+ bool freeze = __blk_freeze_queue_start(q, current);
if (queue_is_mq(q))
blk_mq_wake_waiters(q);
/* Make blk_queue_enter() reexamine the DYING flag. */
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 5f4496220432..5e240a4b6be0 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -120,20 +120,66 @@ void blk_mq_in_flight_rw(struct request_queue *q, struct block_device *part,
inflight[1] = mi.inflight[1];
}
-bool __blk_freeze_queue_start(struct request_queue *q)
+#ifdef CONFIG_LOCKDEP
+static bool blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
{
- int freeze;
+ if (!owner)
+ return false;
+
+ if (!q->mq_freeze_depth) {
+ q->mq_freeze_owner = owner;
+ q->mq_freeze_owner_depth = 1;
+ return true;
+ }
+
+ if (owner == q->mq_freeze_owner)
+ q->mq_freeze_owner_depth += 1;
+ return false;
+}
+
+/* verify the last unfreeze in owner context */
+static bool blk_unfreeze_check_owner(struct request_queue *q)
+{
+ if (!q->mq_freeze_owner)
+ return false;
+ if (q->mq_freeze_owner != current)
+ return false;
+ if (--q->mq_freeze_owner_depth == 0) {
+ q->mq_freeze_owner = NULL;
+ return true;
+ }
+ return false;
+}
+
+#else
+
+static bool blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
+{
+ return false;
+}
+
+static bool blk_unfreeze_check_owner(struct request_queue *q)
+{
+ return false;
+}
+#endif
+
+bool __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner)
+{
+ bool freeze;
mutex_lock(&q->mq_freeze_lock);
+ freeze = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
if (queue_is_mq(q))
blk_mq_run_hw_queues(q, false);
- freeze = true;
} else {
mutex_unlock(&q->mq_freeze_lock);
- freeze = false;
}
return freeze;
@@ -141,7 +187,7 @@ bool __blk_freeze_queue_start(struct request_queue *q)
void blk_freeze_queue_start(struct request_queue *q)
{
- if (__blk_freeze_queue_start(q))
+ if (__blk_freeze_queue_start(q, current))
blk_freeze_acquire_lock(q, false, false);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -170,7 +216,7 @@ EXPORT_SYMBOL_GPL(blk_mq_freeze_queue);
bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
- int unfreeze = false;
+ bool unfreeze;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
@@ -180,8 +226,8 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
if (!q->mq_freeze_depth) {
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
- unfreeze = true;
}
+ unfreeze = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
return unfreeze;
@@ -203,7 +249,7 @@ EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
*/
void blk_freeze_queue_start_non_owner(struct request_queue *q)
{
- __blk_freeze_queue_start(q);
+ __blk_freeze_queue_start(q, NULL);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start_non_owner);
diff --git a/block/blk.h b/block/blk.h
index ac48b79cbf80..57fc035620d6 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -37,7 +37,8 @@ void blk_free_flush_queue(struct blk_flush_queue *q);
bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
bool blk_queue_start_drain(struct request_queue *q);
-bool __blk_freeze_queue_start(struct request_queue *q);
+bool __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner);
int __bio_queue_enter(struct request_queue *q, struct bio *bio);
void submit_bio_noacct_nocheck(struct bio *bio);
void bio_await_chain(struct bio *bio);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 93551772c1d6..1b51a7c92e9b 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -575,6 +575,10 @@ struct request_queue {
struct throtl_data *td;
#endif
struct rcu_head rcu_head;
+#ifdef CONFIG_LOCKDEP
+ struct task_struct *mq_freeze_owner;
+ int mq_freeze_owner_depth;
+#endif
wait_queue_head_t mq_freeze_wq;
/*
* Protect concurrent access to q_usage_counter by
]
|
| 134/2 |
2026/11/03 15:34 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 6f491a8d4b92d1a840fd9209cba783c84437d0b7
Author: Ming Lei <ming.lei@redhat.com>
Date: Wed Nov 27 21:51:28 2024 +0800
block: track disk DEAD state automatically for modeling queue freeze lockdep
Now we only verify the outmost freeze & unfreeze in current context in case
that !q->mq_freeze_depth, so it is reliable to save disk DEAD state when
we want to lock the freeze queue since the state is one per-task variable
now.
Doing this way can kill lots of false positive when freeze queue is
called before adding disk[1].
[1] https://lore.kernel.org/linux-block/6741f6b2.050a0220.1cc393.0017.GAE@google.com/
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241127135133.3952153-3-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 60f457f62913..0c6a319fb936 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -131,6 +131,9 @@ static bool blk_freeze_set_owner(struct request_queue *q,
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
+ q->mq_freeze_disk_dead = !q->disk ||
+ test_bit(GD_DEAD, &q->disk->state) ||
+ !blk_queue_registered(q);
return true;
}
@@ -187,7 +190,7 @@ bool __blk_freeze_queue_start(struct request_queue *q,
void blk_freeze_queue_start(struct request_queue *q)
{
if (__blk_freeze_queue_start(q, current))
- blk_freeze_acquire_lock(q, false, false);
+ blk_freeze_acquire_lock(q, false);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -235,7 +238,7 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
void blk_mq_unfreeze_queue(struct request_queue *q)
{
if (__blk_mq_unfreeze_queue(q, false))
- blk_unfreeze_release_lock(q, false, false);
+ blk_unfreeze_release_lock(q, false);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
diff --git a/block/blk.h b/block/blk.h
index 2c26abf505b8..8708168d50e4 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -720,22 +720,29 @@ void blk_integrity_verify(struct bio *bio);
void blk_integrity_prepare(struct request *rq);
void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
-static inline void blk_freeze_acquire_lock(struct request_queue *q, bool
- disk_dead, bool queue_dying)
+#ifdef CONFIG_LOCKDEP
+static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
{
- if (!disk_dead)
+ if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
if (!queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q, bool
- disk_dead, bool queue_dying)
+static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
{
if (!queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
- if (!disk_dead)
+ if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
+#else
+static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
+{
+}
+static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
+{
+}
+#endif
#endif /* BLK_INTERNAL_H */
diff --git a/block/elevator.c b/block/elevator.c
index 7c3ba80e5ff4..ca0a74369f1c 100644
--- a/block/elevator.c
+++ b/block/elevator.c
@@ -602,14 +602,14 @@ void elevator_init_mq(struct request_queue *q)
* Disk isn't added yet, so verifying queue lock only manually.
*/
blk_freeze_queue_start_non_owner(q);
- blk_freeze_acquire_lock(q, true, false);
+ blk_freeze_acquire_lock(q, false);
blk_mq_freeze_queue_wait(q);
blk_mq_cancel_work_sync(q);
err = blk_mq_init_sched(q, e);
- blk_unfreeze_release_lock(q, true, false);
+ blk_unfreeze_release_lock(q, false);
blk_mq_unfreeze_queue_non_owner(q);
if (err) {
diff --git a/block/genhd.c b/block/genhd.c
index 79230c109fca..59ac299909b3 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -692,7 +692,7 @@ void del_gendisk(struct gendisk *disk)
start_drain = __blk_mark_disk_dead(disk);
queue_dying = blk_queue_dying(q);
if (start_drain)
- blk_freeze_acquire_lock(q, true, queue_dying);
+ blk_freeze_acquire_lock(q, queue_dying);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
@@ -748,7 +748,7 @@ void del_gendisk(struct gendisk *disk)
blk_mq_exit_queue(q);
if (start_drain)
- blk_unfreeze_release_lock(q, true, queue_dying);
+ blk_unfreeze_release_lock(q, queue_dying);
}
EXPORT_SYMBOL(del_gendisk);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 378d3a1a22fc..522cf8eef66c 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -581,6 +581,8 @@ struct request_queue {
#ifdef CONFIG_LOCKDEP
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
+ /* Records disk state in current context, used in unfreeze queue */
+ bool mq_freeze_disk_dead;
#endif
wait_queue_head_t mq_freeze_wq;
/*
]
|
| 135/2 |
2026/11/03 15:34 |
llm |
debugger |
1m
Model:
Tokens:
input: 60764
output: 77
thoughts: 986
Thoughts: **Analyzing Block Device Death and Queue Freezing**
Okay, hold on a second. I need to dig into this code. Looking at commits `6a78699838a0`, `6f491a8d4b92`, and `f6661b1d0525` is critical. Specifically, the change in `block/blk-core.c` where `__blk_freeze_queue_start` now takes `current` as an argument is interesting. I also need to focus on how `blk_mark_disk_dead` in `block/genhd.c` functions. I need to grasp how the flags interact.
I see that `blk_mark_disk_dead` calls `__blk_mark_disk_dead`. The latter sets the `GD_DEAD` bit, sets capacity to zero and starts a drain on the request queue. This seems straightforward. But wait, why are `blk_mark_disk_dead` and `__del_gendisk` operating differently on the queue?
In `__del_gendisk`, the code calls `blk_freeze_acquire_lock` and `blk_unfreeze_release_lock` after `__blk_mark_disk_dead`, which is what I'm expecting. However, in `blk_mark_disk_dead`, it calls `__blk_mark_disk_dead` but *ignores* the return value, thus *never* calling those freeze functions. That's a huge difference!
Aha! I think I see it. When `blk_mark_disk_dead` is called and `GD_OWNS_QUEUE` is set (or unconditionally after `7e9a46004b47`), both `QUEUE_FLAG_DYING` and `GD_DEAD` are set before `blk_queue_start_drain`. So, in `blk_mark_disk_dead`, `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying` are true. So, in that case, `blk_freeze_acquire_lock(q)` *would* be a no-op anyway! This explains the difference in behavior.
However, that means I still need to understand the implications of `blk_freeze_set_owner`, `blk_freeze_acquire_lock`, `blk_unfreeze_check_owner`, and `blk_unfreeze_release_lock`. I need to review *all* of those function in `block/blk-mq.c` and `block/blk.h` to fully grasp the memory restore behaviour. I'm going to look at lines 115-245 of `block/blk-mq.c` and lines 730-765 of `block/blk.h`. Okay, let's see what's going on with the queue freezing, the owner setup, and unfreezing in detail. This needs to be understood completely, because this potentially affects how we are handling dying queues.
|
| 136/2 |
2026/11/03 15:35 |
tool |
read-file |
0m
Args: map[File:block/blk-mq.c FirstLine:115 LineCount:130]
Results: map[Contents: 115: #ifdef CONFIG_LOCKDEP
116: static bool blk_freeze_set_owner(struct request_queue *q,
117: struct task_struct *owner)
118: {
119: if (!owner)
120: return false;
121:
122: if (!q->mq_freeze_depth) {
123: q->mq_freeze_owner = owner;
124: q->mq_freeze_owner_depth = 1;
125: q->mq_freeze_disk_dead = !q->disk ||
126: test_bit(GD_DEAD, &q->disk->state) ||
127: !blk_queue_registered(q);
128: q->mq_freeze_queue_dying = blk_queue_dying(q);
129: return true;
130: }
131:
132: if (owner == q->mq_freeze_owner)
133: q->mq_freeze_owner_depth += 1;
134: return false;
135: }
136:
137: /* verify the last unfreeze in owner context */
138: static bool blk_unfreeze_check_owner(struct request_queue *q)
139: {
140: if (q->mq_freeze_owner != current)
141: return false;
142: if (--q->mq_freeze_owner_depth == 0) {
143: q->mq_freeze_owner = NULL;
144: return true;
145: }
146: return false;
147: }
148:
149: #else
150:
151: static bool blk_freeze_set_owner(struct request_queue *q,
152: struct task_struct *owner)
153: {
154: return false;
155: }
156:
157: static bool blk_unfreeze_check_owner(struct request_queue *q)
158: {
159: return false;
160: }
161: #endif
162:
163: bool __blk_freeze_queue_start(struct request_queue *q,
164: struct task_struct *owner)
165: {
166: bool freeze;
167:
168: mutex_lock(&q->mq_freeze_lock);
169: freeze = blk_freeze_set_owner(q, owner);
170: if (++q->mq_freeze_depth == 1) {
171: percpu_ref_kill(&q->q_usage_counter);
172: mutex_unlock(&q->mq_freeze_lock);
173: if (queue_is_mq(q))
174: blk_mq_run_hw_queues(q, false);
175: } else {
176: mutex_unlock(&q->mq_freeze_lock);
177: }
178:
179: return freeze;
180: }
181:
182: void blk_freeze_queue_start(struct request_queue *q)
183: {
184: if (__blk_freeze_queue_start(q, current))
185: blk_freeze_acquire_lock(q);
186: }
187: EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
188:
189: void blk_mq_freeze_queue_wait(struct request_queue *q)
190: {
191: wait_event(q->mq_freeze_wq, percpu_ref_is_zero(&q->q_usage_counter));
192: }
193: EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait);
194:
195: int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
196: unsigned long timeout)
197: {
198: return wait_event_timeout(q->mq_freeze_wq,
199: percpu_ref_is_zero(&q->q_usage_counter),
200: timeout);
201: }
202: EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait_timeout);
203:
204: void blk_mq_freeze_queue_nomemsave(struct request_queue *q)
205: {
206: blk_freeze_queue_start(q);
207: blk_mq_freeze_queue_wait(q);
208: }
209: EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_nomemsave);
210:
211: bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
212: {
213: bool unfreeze;
214:
]
|
| 137/2 |
2026/11/03 15:35 |
tool |
read-file |
0m
Args: map[File:block/blk.h FirstLine:730 LineCount:35]
Results: map[Contents: 730: }
731:
732: static inline int req_ref_read(struct request *req)
733: {
734: return atomic_read(&req->ref);
735: }
736:
737: static inline u64 blk_time_get_ns(void)
738: {
739: struct blk_plug *plug = current->plug;
740: u64 now;
741:
742: if (!plug || !in_task())
743: return ktime_get_ns();
744:
745: /*
746: * 0 could very well be a valid time, but rather than flag "this is
747: * a valid timestamp" separately, just accept that we'll do an extra
748: * ktime_get_ns() if we just happen to get 0 as the current time.
749: *
750: * cur_ktime can be zeroed by pre-emption the moment PF_BLOCK_TS is set.
751: */
752: now = READ_ONCE(plug->cur_ktime);
753: if (!now) {
754: now = ktime_get_ns();
755: WRITE_ONCE(plug->cur_ktime, now);
756: /* Ensure PF_BLOCK_TS is set after cur_ktime. */
757: barrier();
758: current->flags |= PF_BLOCK_TS;
759: }
760: return now;
761: }
762:
763: static inline ktime_t blk_time_get(void)
764: {
]
|
| 138/2 |
2026/11/03 15:35 |
llm |
debugger |
0m
Model:
Tokens:
input: 63779
output: 48
thoughts: 3040
Thoughts: **A Deep Dive into Device Mapper and Queue Freezing**
Okay, let's break this down. My initial focus was on the interaction between `blk_mark_disk_dead`, `__blk_mark_disk_dead`, and `blk_queue_start_drain`. I needed to understand their precise roles, especially regarding queue freezing and unfreezing. I had initially made an assumption about when `blk_freeze_acquire_lock` was called, which proved to be incorrect and warranted a thorough re-evaluation. The core question is, what does `blk_mark_disk_dead` *really* do, specifically in relation to queue state transitions? I started by dissecting the code.
I focused on the sequence of calls: `blk_mark_disk_dead` calls `__blk_mark_disk_dead`, which in turn calls `blk_queue_start_drain`. I needed to trace the path and what happens to the queue within `blk_queue_start_drain`. Specifically, the critical part of `blk_queue_start_drain` includes `__blk_freeze_queue_start`, and the use of `q->mq_freeze_depth`.
Then, I was faced with an intriguing question: what happens if the order of execution is reversed? Specifically, I had to analyze what occurs when `blk_mark_disk_dead` (Thread B, representing a `DM_DEV_REMOVE` operation) is called *before* the `elevator_change` function (Thread A, representing a `DM_TABLE_LOAD` operation). This exposed the core race condition. What happens when two threads are concurrently accessing and modifying the queue?
I considered a specific scenario where the `DM_TABLE_LOAD` and `DM_DEV_REMOVE` ioctls were running in different threads. The key was realizing that, based on the output, they were indeed running in separate threads. I am calling these threads A and B. I had to carefully trace the execution path of each thread, considering how their operations would interleave, particularly around `blk_mark_disk_dead` and `elevator_change`. The `q->mq_freeze_depth` became the critical piece of data.
I then went through a very detailed tracing of what occurs during each scenario. The initial scenario, with `elevator_change` running first, highlights that Thread B, calling `blk_mark_disk_dead`, can effectively push `q->mq_freeze_depth` to 2. Then, Thread A's `elevator_change` has a different behavior with the `mq_freeze_depth` at 2.
Next, I reversed the order of execution, to see what happens when the `DM_DEV_REMOVE` (Thread B) is initiated *before* the `DM_TABLE_LOAD` (Thread A) reaches the crucial point of `elevator_change`. This scenario proved even more interesting, because the `QUEUE_FLAG_DYING` flag gets set *before* Thread A can act, and I am still not clear on *when* or *if* this flag can be cleared or overwritten. The question of flag manipulation by multiple threads in this context is critical.
And finally, my investigation continues with checking where the `queue_flags` of the queue are modified.
|
| 139/2 |
2026/11/03 15:36 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/md/dm-rq.c Name:dm_mq_init_request_queue]
Results: map[SourceCode: 545: int dm_mq_init_request_queue(struct mapped_device *md, struct dm_table *t)
546: {
547: struct dm_target *immutable_tgt;
548: int err;
549:
550: md->tag_set = kzalloc_node(sizeof(struct blk_mq_tag_set), GFP_KERNEL, md->numa_node_id);
551: if (!md->tag_set)
552: return -ENOMEM;
553:
554: md->tag_set->ops = &dm_mq_ops;
555: md->tag_set->queue_depth = dm_get_blk_mq_queue_depth();
556: md->tag_set->numa_node = md->numa_node_id;
557: md->tag_set->flags = BLK_MQ_F_STACKING;
558: md->tag_set->nr_hw_queues = dm_get_blk_mq_nr_hw_queues();
559: md->tag_set->driver_data = md;
560:
561: md->tag_set->cmd_size = sizeof(struct dm_rq_target_io);
562: immutable_tgt = dm_table_get_immutable_target(t);
563: if (immutable_tgt && immutable_tgt->per_io_data_size) {
564: /* any target-specific per-io data is immediately after the tio */
565: md->tag_set->cmd_size += immutable_tgt->per_io_data_size;
566: md->init_tio_pdu = true;
567: }
568:
569: err = blk_mq_alloc_tag_set(md->tag_set);
570: if (err)
571: goto out_kfree_tag_set;
572:
573: err = blk_mq_init_allocated_queue(md->tag_set, md->queue);
574: if (err)
575: goto out_tag_set;
576: return 0;
577:
578: out_tag_set:
579: blk_mq_free_tag_set(md->tag_set);
580: out_kfree_tag_set:
581: kfree(md->tag_set);
582: md->tag_set = NULL;
583:
584: return err;
585: }
SourceFile:drivers/md/dm-rq.c]
|
| 140/2 |
2026/11/03 15:36 |
llm |
debugger |
1m
Model:
Tokens:
input: 67611
output: 4038
thoughts: 5254
Thoughts: **Root Cause Analysis: Device Mapper and Block Layer Concurrency Issue**
Okay, here's what I've figured out. There's a race condition between device removal (`dev_remove`) and device table loading (`table_load`) in the Device Mapper (DM) that's leading to a lockdep issue and a subsequent crash. The crux of the problem lies in how the block layer's queue freezing and unfreezing mechanisms interact with DM's device lifecycle, specifically with how the `QUEUE_FLAG_DYING` flag is set and how `q_lockdep_map` is managed.
First, let's look at what is happening during `table_load`, specifically at `elevator_change`. The `table_load` function acquires a reference to the `mapped_device` (`md`), increments `md->holders`, and subsequently grabs the `md->type_lock`, which it holds while initializing the queue. The crash shows `table_load` acquires `q->q_lockdep_map` at `block/elevator.c:668` which corresponds to `blk_mq_freeze_queue(q)` in `elevator_change`.
Meanwhile, `dev_remove` calls `blk_mark_disk_dead(md->disk)`. The `blk_mark_disk_dead()` function sets the `QUEUE_FLAG_DYING` flag on the request queue (`q`). Then `blk_mark_disk_dead` calls `blk_queue_start_drain(disk->queue)` which calls `__blk_freeze_queue_start(q, Thread B)`.
Here's where the race begins:
1. **Race 1**: `table_load` calls `blk_mq_freeze_queue(q)` during `elevator_change`. Inside the `__blk_freeze_queue_start`, `q->mq_freeze_depth` is incremented. However, there's a window where `dev_remove` can preempt and call `blk_mark_disk_dead` setting `QUEUE_FLAG_DYING`.
2. **Race 2**: During the call to `blk_mq_freeze_queue(q)` the code obtains `q->q_lockdep_map`. However, `blk_unfreeze_release_lock(q)` is called *outside* of the `q->mq_freeze_lock`. This is a bug because we can overwrite the `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead` variables within the `q->mq_freeze_lock`.
3. Because `q->mq_freeze_queue_dying` can be set concurrently, `blk_unfreeze_release_lock(q)` may release the lockdep map that was not originally acquired.
The core vulnerability is this: `table_load` holds a reference via `md->holders`, and is initializing the queue (in a state that assumes the disk is "alive"), while `dev_remove` *concurrently* calls `blk_mark_disk_dead`, which sets `QUEUE_FLAG_DYING` and then calls `blk_freeze_queue_start()`. This setting of `QUEUE_FLAG_DYING` effectively marks the disk as dead while `table_load` is still in the middle of initialization and has an active reference to the disk!
What happens is that the incorrect `q->mq_freeze_queue_dying` or `q->mq_freeze_disk_dead` values end up being read when `blk_unfreeze_release_lock(q)` is called. This leads to the leaked lock because the `q_lockdep_map` is not released.
The lockdep output clearly pinpoints the location (`block/elevator.c:668`) where the lock was acquired. It wasn't a matter of what `wbt_init_enable_default` did; the lock was acquired at `blk_mq_freeze_queue` within the `elevator_change` function. This is the source of the problem.
The key is that the DM's `dev_remove` function is racing against queue initialization in `table_load` because of how `blk_mark_disk_dead` is called and how the `q->mq_freeze_lock` and lockdep maps are managed. The non-atomic read-modify-write on `q->queue_flags` on the queue flags further exacerbates the issue by introducing a window of vulnerability during queue initialization, specifically at the line `q->queue_flags |= QUEUE_FLAG_MQ_DEFAULT;`
In summary: the race condition between device removal and table loading, coupled with the block layer's freezing mechanism and lock management, results in a situation where a lock is acquired and never
|
| 141/1 |
2026/11/03 15:38 |
agent |
history-explorer |
5h06m
Model:
Instruction:
You are an experienced Linux kernel developer researching prior art for fixing a kernel bug.
You are given a bug explanation. This explanation details the root cause of the bug resulting
from debugging, but does not provide the final fix strategy. Your goal is to explore how
similar bugs were fixed in the past in the same subsystem or files.
CRITICAL: Do NOT attempt to debug the issue further or write a patch for it yourself.
Your ONLY objective is to research and provide the necessary historical context.
Use the git-log tool with the Since parameter set to "3 years" to focus on recent history.
Search for commits that address issues with similar root causes (e.g. similar missing locks,
incorrect refcounting, or similar error path bugs) in the affected files.
Your final reply must summarize your findings: what idioms, locking rules, or common patterns
should be followed when writing a fix for this bug based on how previous similar bugs were addressed.
If you find no relevant past fixes, clearly state that.
Don't make assumptions about the kernel source code (it may be different from what you assume it is).
Extensively use the provided code access tools (codesearch-*, git-*, grepper, etc)
to examine the actual source code, and confirm any assumptions.
Prefer calling several tools at the same time to save round-trips.
Prompt:
The crash is:
device-mapper: ioctl: device has been removed from the dev hash table.
================================================
WARNING: lock held when returning to user space!
syzkaller #1 Not tainted
------------------------------------------------
syz.3.1525/11804 is leaving the kernel with locks still held!
locks held by syz.3.1525/11804: 1, last CPU#0:
#0: ffff88805abdd468 (&q->q_usage_counter(queue)#52){+.+.}-{0:0}, at: blk_mq_freeze_queue include/linux/blk-mq.h:959 [inline]
#0: ffff88805abdd468 (&q->q_usage_counter(queue)#52){+.+.}-{0:0}, at: elevator_change+0x194/0x480 block/elevator.c:668
The explanation of the root cause of the bug is:
### Root Cause Analysis
#### Summary
The `WARNING: lock held when returning to user space!` for `&q->q_usage_counter(queue)` (which is the lockdep map `q->q_lockdep_map` acquired at `elevator_change+0x194/0x480`, `block/elevator.c:668`) is caused by a race condition between:
1. **`DM_TABLE_LOAD` (`table_load`)** initializing and registering the request-based DM queue/gendisk (`dm_setup_md_queue()` -> `add_disk()` -> `blk_register_queue()` -> `elevator_set_default()` -> `elevator_change()`), and
2. **`DM_DEV_REMOVE` (`dev_remove`)** concurrently destroying the same DM device (`dm_destroy()` -> `__dm_destroy()` -> `blk_mark_disk_dead()`), which marks the queue dying and starts draining/freezing the queue.
Specifically, in the block layer's queue-freeze lockdep tracking (`block/blk-mq.c` and `block/blk.h`), the flags `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead` are stored as per-`request_queue` fields protected by `q->mq_freeze_lock` when `q->mq_freeze_depth == 0`, **but `blk_unfreeze_release_lock(q)` reads them outside `q->mq_freeze_lock` after `q->mq_freeze_depth` has already been decremented to `0`**. When `blk_mark_disk_dead()` races with `blk_mq_unfreeze_queue()`, `q->mq_freeze_queue_dying` is overwritten from `false` to `true` before `blk_unfreeze_release_lock(q)` runs, causing `blk_unfreeze_release_lock(q)` to skip releasing `q->q_lockdep_map`.
---
#### Detailed Mechanism
##### 1. Lockdep modeling of `blk_mq_freeze_queue()` / `blk_mq_unfreeze_queue()`
In `block/blk-core.c:500`, `q->q_lockdep_map` is initialized with the name `"&q->q_usage_counter(queue)"`:
```c
lockdep_init_map(&q->q_lockdep_map, "&q->q_usage_counter(queue)",
&q->q_lock_cls_key, 0);
```
In `block/blk-mq.c`, when a task freezes a queue via `blk_mq_freeze_queue(q)` -> `blk_freeze_queue_start(q)`:
```c
static bool blk_freeze_set_owner(struct request_queue *q,
struct task_struct *owner)
{
if (!owner)
return false;
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
q->mq_freeze_disk_dead = !q->disk ||
test_bit(GD_DEAD, &q->disk->state) ||
!blk_queue_registered(q);
q->mq_freeze_queue_dying = blk_queue_dying(q);
return true;
}
if (owner == q->mq_freeze_owner)
q->mq_freeze_owner_depth += 1;
return false;
}
```
```c
bool __blk_freeze_queue_start(struct request_queue *q,
struct task_struct *owner)
{
bool freeze;
mutex_lock(&q->mq_freeze_lock);
freeze = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
if (queue_is_mq(q))
blk_mq_run_hw_queues(q, false);
} else {
mutex_unlock(&q->mq_freeze_lock);
}
return freeze;
}
void blk_freeze_queue_start(struct request_queue *q)
{
if (__blk_freeze_queue_start(q, current))
blk_freeze_acquire_lock(q);
}
```
And in `block/blk.h:715-728`:
```c
static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
if (!q->mq_freeze_queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
```
When the owner task unfreezes the queue via `blk_mq_unfreeze_queue(q, memflags)` -> `blk_mq_unfreeze_queue_nomemrestore(q)` (`block/blk-mq.c:211-235`):
```c
bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
bool unfreeze;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
q->q_usage_counter.data->force_atomic = true;
q->mq_freeze_depth--;
WARN_ON_ONCE(q->mq_freeze_depth < 0);
if (!q->mq_freeze_depth) {
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
}
unfreeze = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
return unfreeze;
}
void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
{
if (__blk_mq_unfreeze_queue(q, false))
blk_unfreeze_release_lock(q);
}
```
Notice the bug here:
1. Inside `__blk_mq_unfreeze_queue()`, `q->mq_freeze_depth` is decremented to `0` and `q->mq_freeze_owner` is cleared to `NULL`, and then `mutex_unlock(&q->mq_freeze_lock)` is called.
2. Only **after** `q->mq_freeze_lock` is released does `blk_mq_unfreeze_queue_nomemrestore()` call `blk_unfreeze_release_lock(q)`, which inspects `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead`.
3. Because `q->mq_freeze_depth` is already `0` and `q->mq_freeze_lock` is unlocked, another thread calling `__blk_freeze_queue_start()` can immediately acquire `q->mq_freeze_lock`, see `!q->mq_freeze_depth`, and overwrite `q->mq_freeze_queue_dying` (and `q->mq_freeze_disk_dead`) in `blk_freeze_set_owner()`.
##### 2. How Device Mapper triggers this race
In the reproducer:
1. `ioctl(DM_DEV_CREATE)` creates a DM device `md` (`md->type == DM_TYPE_NONE`, with `md->disk` allocated via `blk_alloc_disk()`).
2. **Thread 1 (`syz.3.1525/11804`)** calls `ioctl(DM_TABLE_LOAD)` (`table_load()` in `drivers/md/dm-ioctl.c:1622`) with a request-based `"multipath"` target:
- `find_device(param)` looks up `md` under `_hash_lock`, increments `md->holders` (`dm_get(md)`), and drops `_hash_lock`.
- `populate_table()` parses the `"multipath"` target, setting the table type to `DM_TYPE_REQUEST_BASED`.
- Since `dm_get_md_type(md) == DM_TYPE_NONE`, `table_load()` calls `dm_setup_md_queue(md, t)` (`drivers/md/dm.c:2606`):
- `dm_mq_init_request_queue(md, t)` initializes `md->queue` as a `blk-mq` queue.
- `add_disk(md->disk)` -> `device_add_disk()` -> `add_disk_fwnode()` -> `__add_disk()` -> `blk_register_queue(md->disk)` (`block/blk-sysfs.c:991`):
```c
if (queue_is_mq(q))
elevator_set_default(q);
```
- `elevator_set_default(q)` calls `elevator_change(q, &ctx)` (`block/elevator.c:653`).
3. Concurrently, **Thread 2** calls `ioctl(DM_DEV_REMOVE)` (`dev_remove()` in `drivers/md/dm-ioctl.c:1063`):
- Under `_hash_lock`, `dm_lock_for_deletion(md, ...)` succeeds because it only checks `dm_open_count(md)` (`0`), **not** `md->holders`.
- `__hash_remove(hc)` removes `hc` from the hash table and clears `md->interface_ptr` (`dm_set_mdptr(md, NULL)`).
- `dev_remove()` drops `_hash_lock`, calls `dm_put(md)`, and calls `dm_destroy(md)` -> `__dm_destroy(md, true)` (`drivers/md/dm.c:2726`):
```c
blk_mark_disk_dead(md->disk);
...
if (wait)
while (atomic_read(&md->holders))
fsleep(1000);
```
- Notice that `__dm_destroy()` calls `blk_mark_disk_dead(md->disk)` **before** waiting for `md->holders` to drop to `0`.
##### 3. Exact Race Sequence
1. **Thread 1 (`table_load`)** enters `elevator_change()` (`block/elevator.c:668`):
```c
memflags = blk_mq_freeze_queue(q);
```
- `q->mq_freeze_depth` is `0`.
- `blk_freeze_set_owner(q, Thread_1)` sets:
- `q->mq_freeze_owner = Thread_1`
- `q->mq_freeze_owner_depth = 1`
- `q->mq_freeze_disk_dead = true` (since `QUEUE_FLAG_REGISTERED` is not set yet)
- `q->mq_freeze_queue_dying = false` (since `QUEUE_FLAG_DYING` is not set yet)
- `q->mq_freeze_depth` becomes `1`.
- `blk_freeze_acquire_lock(q)` sees `!q->mq_freeze_queue_dying == true` and calls:
```c
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
```
2. **Thread 1 (`table_load`)** finishes `elevator_switch()` and calls `blk_mq_unfreeze_queue(q, memflags)` at `block/elevator.c:683`:
- Inside `__blk_mq_unfreeze_queue(q, false)` (`block/blk-mq.c:211`):
- `q->mq_freeze_depth` is decremented from `1` to `0`.
- `blk_unfreeze_check_owner(q)` decrements `q->mq_freeze_owner_depth` to `0`, sets `q->mq_freeze_owner = NULL`, and returns `true`.
- `mutex_unlock(&q->mq_freeze_lock)` unlocks `q->mq_freeze_lock`.
3. **Thread 2 (`dev_remove`)** executes `blk_mark_disk_dead(md->disk)` (`block/genhd.c:689`):
```c
void blk_mark_disk_dead(struct gendisk *disk)
{
blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
__blk_mark_disk_dead(disk);
blk_report_disk_dead(disk, true);
}
```
- `blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue)` sets `QUEUE_FLAG_DYING` on `q`.
- `__blk_mark_disk_dead(disk)` calls `blk_queue_start_drain(disk->queue)` -> `__blk_freeze_queue_start(q, Thread_2)`.
- Right after Thread 1 unlocks `q->mq_freeze_lock` in step 2 (e.g., when woken from `q->mq_freeze_lock` wait_list during `mutex_unlock`), Thread 2 acquires `q->mq_freeze_lock`.
- Because `q->mq_freeze_depth` is `0`, `blk_freeze_set_owner(q, Thread_2)` runs and sets:
```c
q->mq_freeze_queue_dying = blk_queue_dying(q); /* true! */
```
4. **Thread 1 (`table_load`)** now executes `blk_unfreeze_release_lock(q)` (`block/blk-mq.c:233` -> `block/blk.h:722`):
```c
static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
```
Because `q->mq_freeze_queue_dying` was overwritten with `true` by Thread 2 in step 3, `!q->mq_freeze_queue_dying` evaluates to `false`, and **`rwsem_release(&q->q_lockdep_map, _RET_IP_)` is skipped**.
5. **Thread 1 (`table_load`)** finishes `dm_setup_md_queue()`, acquires `_hash_lock` in `table_load()` (`drivers/md/dm-ioctl.c:1678`), sees `hc = dm_get_mdptr(md)` is `NULL`, logs:
```
device-mapper: ioctl: device has been removed from the dev hash table.
```
cleans up `t`, drops `md->holders` (`dm_put(md)`), and returns `-ENXIO` to user space with `q->q_lockdep_map` (`&q->q_usage_counter(queue)`) still held in lockdep, triggering the warning.
---
#### How to Fix
1. **In the block layer (`block/blk-mq.c`, `block/blk.h`, `block/genhd.c`)**:
`blk_freeze_acquire_lock(q)` and `blk_unfreeze_release_lock(q)` must not read mutable per-queue `q->mq_freeze_queue_dying` / `q->mq_freeze_disk_dead` fields outside `q->mq_freeze_lock` after `q->mq_freeze_depth` has dropped to `0` (where another task starting a new freeze can overwrite them). Either:
- Perform the lockdep release (`blk_unfreeze_release_lock(q)`) / state consumption under `q->mq_freeze_lock` before `q->mq_freeze_depth` is decremented / unlocked (or pass the saved `disk_dead` and `queue_dying` booleans out of `__blk_mq_unfreeze_queue()` by value while still holding `q->mq_freeze_lock`), and similarly pass/snapshot them under `q->mq_freeze_lock` in `__blk_freeze_queue_start()`.
2. **In Device Mapper (`drivers/md/dm.c`)**:
In `__dm_destroy()`, `blk_mark_disk_dead(md->disk)` should not be called while another thread holds `md->holders` and may still be in `dm_setup_md_queue()` / `add_disk(md->disk)` initializing and registering the disk/queue (i.e., wait for `atomic_read(&md->holders)` or serialize against `md->type_lock` before marking the disk dead).
Reply: Based on research into the commit history of the **Block Layer** and **Device Mapper** subsystems over the past 3 years (and relevant foundational commits), here is the historical context, prior art, and subsystem idioms for addressing this bug.
---
### 1. Block Layer: Queue Freeze Lockdep Tracking (`block/blk-mq.c`, `block/blk.h`)
#### Historical Context and Evolution
The queue freeze and unfreeze lockdep tracking was introduced and refined across several recent commits:
* **`f1be1788a32e` ("block: model freeze & enter queue as lock for supporting lockdep")**:
Initially modeled queue freeze/unfreeze using lockdep (`q->q_lockdep_map` and `q->io_lockdep_map`). Originally, `blk_freeze_acquire_lock()` and `blk_unfreeze_release_lock()` took explicit boolean parameters (`disk_dead`, `queue_dying`) passed down the call stack or stored as local variables.
* **`6a78699838a0` ("block: always verify unfreeze lock on the owner task")**:
Addressed an issue where freeze depth could drop across different tasks. It established the rule that lockdep verification must only occur on the **freeze owner task context** by tracking `q->mq_freeze_owner` and `q->mq_freeze_owner_depth` under `q->mq_freeze_lock`. `blk_freeze_set_owner()` only assigns ownership on outermost freeze (`!q->mq_freeze_depth`), and `blk_unfreeze_check_owner()` only authorizes releasing the lockdep map on the outermost unfreeze when `mq_freeze_owner_depth` drops to 0.
* **`6f491a8d4b92` ("block: track disk DEAD state automatically for modeling queue freeze lockdep")** and **`f6661b1d0525` ("block: track queue dying state automatically for modeling queue freeze lockdep")**:
Eliminated the boolean parameters to make lockdep tracking automatic. Under `q->mq_freeze_lock`, `blk_freeze_set_owner()` records `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying` on `struct request_queue`. The commit log noted that *"the state is one per-task variable now"*.
**However**, storing these booleans directly in `struct request_queue` without snapshotting them or protecting their read in `blk_unfreeze_release_lock()` broke this per-task guarantee: `blk_unfreeze_release_lock(q)` reads `q->mq_freeze_queue_dying` **outside** `q->mq_freeze_lock` after `q->mq_freeze_depth` has already been decremented to 0.
#### Idioms and Locking Patterns from Prior Art
1. **Never read per-queue mutable lockdep state outside `q->mq_freeze_lock` once `mq_freeze_depth == 0`**:
Any fields in `struct request_queue` conditioned on `!q->mq_freeze_depth` can immediately be overwritten by another task starting a new freeze (e.g. `__blk_freeze_queue_start()` called via `blk_mark_disk_dead()` or `blk_queue_start_drain()`) the instant `q->mq_freeze_lock` is dropped in `__blk_mq_unfreeze_queue()`.
2. **Snapshot state under the lock or perform the lockdep release before releasing the lock**:
* *Passing by value / snapshotting*: Similar to the pattern in `f1be1788a32e`, when a task needs to remember the state captured at freeze time, that state must either be snapshotted under `q->mq_freeze_lock` into local stack variables before unlocking (e.g., returned by `blk_unfreeze_check_owner()` / `__blk_mq_unfreeze_queue()`), or
* *Lockdep release under `q->mq_freeze_lock`*: Releasing a lockdep map (`rwsem_release()` / `lock_release()`) simply removes the held lock from the task's held-lock list and does not establish new lock dependency edges, so state consumption and release under `q->mq_freeze_lock` before depth drops to 0 avoids the race window entirely.
---
### 2. Device Mapper: Device Removal vs Table Load Synchronization (`drivers/md/dm.c`, `drivers/md/dm-ioctl.c`)
#### Historical Context and Evolution
The race occurs because `table_load()` is setting up the request-based queue (`dm_setup_md_queue()` -> `add_disk()` -> `elevator_change()`) while `dev_remove()` concurrently calls `dm_destroy()` -> `__dm_destroy()` -> `blk_mark_disk_dead()`:
* **`3f77316de0ec` ("dm: separate device deletion from dm_put")**:
Separated mapped device deletion from reference counting. It established the convention that `__dm_destroy()` must wait for all in-flight references held on the mapped device via `while (atomic_read(&md->holders)) fsleep(1000);`.
* **`3b785fbcf81c` ("dm: mark request_queue dead before destroying the DM device")** and **`7a5428dcb790` ("block: fix surprise removal for drivers calling blk_set_queue_dying")**:
Replaced direct queue flag setting with `blk_mark_disk_dead(md->disk)` at the top of `__dm_destroy()`. This was intended to reject new I/O during removal, but placed the call **before** `__dm_destroy()` waits for `atomic_read(&md->holders)`.
* **`00c4fc3b1f59` ("dm ioctl: increase granularity of type_lock when loading table")**:
Recognized that `md->type` and `md->queue` setup must be serialized, introducing `dm_lock_md_type()` / `md->type_lock` during `table_load()` around `dm_setup_md_queue()`. However, `__dm_destroy()` does not acquire or synchronize against `md->type_lock`.
* **`44b43ec132f1` ("dm: fix resume-vs-remove race")**:
Fixed a race where an ioctl (`dm_resume`) raced with `__dm_destroy()`. The pattern used was explicitly checking device removal flags (`test_bit(DMF_FREEING, &md->flags)`) under the appropriate lock (`suspend_lock`) to reject operations on devices undergoing destruction.
* **`c50abeb38026` ("dm ioctl: forbid messages to devices being deleted")** and **`abdc568b0540` ("dm: prevent access to md being deleted")**:
Prevented operations on devices being deleted by checking `dm_deleting_md(md)` (which tests `DMF_DELETING`, set in `dm_lock_for_deletion()`) under `_minor_lock`.
#### Idioms and Locking Patterns from Prior Art
1. **Do not mark a disk dead before in-flight device holders finish setup**:
In `__dm_destroy()`, calling `blk_mark_disk_dead(md->disk)` while `atomic_read(&md->holders) > 0` allows `blk_mark_disk_dead()` to race with concurrent operations (such as `table_load()`) that hold `md->holders` and are still in the middle of disk registration or queue setup (`dm_setup_md_queue()` / `add_disk()`). In DM's lifecycle model, disk teardown actions should follow the drainage of active holders.
2. **Check deletion flags (`DMF_DELETING` / `DMF_FREEING`) before mutating queue/device state**:
As demonstrated in `44b43ec132f1` and `c50abeb38026`, ioctls modifying device state must check `dm_deleting_md(md)` or `DMF_FREEING` to abort cleanly (returning `-ENXIO`) before performing heavy setup like initializing request queues or adding disks.
3. **Serialize queue type initialization against device destruction**:
`table_load()` uses `md->type_lock` to serialize queue setup. Ensuring that `__dm_destroy()` synchronizes with `md->type_lock` prevents tearing down or marking a queue dying while `dm_setup_md_queue()` is configuring it.
|
| 142/2 |
2026/11/03 15:38 |
llm |
history-explorer |
4m
Model:
Tokens:
input: 8230
output: 215
thoughts: 713
Thoughts: **Kernel Bug Research: Historical Context**
Okay, let's get down to business. My task is crystal clear: I'm a seasoned Linux kernel developer, and I need to dig into the past to find prior art for fixing a kernel bug, focusing on the historical solutions within the same subsystems and files. The bug's root cause is provided, but I'm *not* to debug or patch the issue myself. My goal is strictly to research and extract relevant context.
The prompt outlines a solid methodology. I'll be using `git-log` primarily, with a `Since: "3 years"` filter to keep my focus on recent changes. I need to be searching for commits that address issues with similar root causes within the block and DM subsystems. I'll be examining: `block/blk-mq.c`, `block/blk.h`, `block/genhd.c`, and `drivers/md/dm.c`. Specifically, my initial search will revolve around these symbols and functions: `blk_freeze_set_owner`, `blk_freeze_acquire_lock` / `blk_unfreeze_release_lock`, `__blk_mq_unfreeze_queue` / `blk_mq_unfreeze_queue_nomemrestore`, `mq_freeze_queue_dying`, `mq_freeze_disk_dead`, `blk_mark_disk_dead`, DM's `__dm_destroy`, `dm_setup_md_queue`, `md->holders`, and `md->type_lock`.
I'll be looking for commits that:
* Modified `mq_freeze_queue_dying`, `mq_freeze_disk_dead`, `blk_freeze_set_owner`, `blk_freeze_acquire_lock`, `blk_unfreeze_release_lock` (to understand their initial introduction and subsequent fixes).
* Address lockdep tracking in queue freeze/unfreeze mechanisms.
* Handled races between `blk_mark_disk_dead`, queue cleanup/destruction, and queue operations / disk add.
* Dealt with races in device-mapper's `dm_destroy`, `table_load`, `holders`, `type_lock`, and `blk_mark_disk_dead`.
I'll be using the provided code access tools extensively, and I won't make any assumptions about the code. I intend to use several tools concurrently to increase efficiency, as I'm sure every engineer does! The key here is not just to find commits, but to *understand* the reasoning behind them, the problems they were trying to solve, and the patterns that emerged. This process of discovery is the real work and will lead to an optimal fix strategy.
|
| 143/2 |
2026/11/03 15:42 |
tool |
git-log |
4m
Args: map[CodeRegexp:mq_freeze_queue_dying Count:10 Since:3 years]
Results: map[Output:f6661b1d0525 block: track queue dying state automatically for modeling queue freeze lockdep
]
|
| 144/2 |
2026/11/03 15:47 |
tool |
git-log |
4m
Args: map[CodeRegexp:blk_freeze_acquire_lock Count:10 Since:3 years]
Results: map[Output:f6661b1d0525 block: track queue dying state automatically for modeling queue freeze lockdep
b9d4eee7e04b block: don't verify queue freeze manually in elevator_init_mq()
6f491a8d4b92 block: track disk DEAD state automatically for modeling queue freeze lockdep
357e1b7f730b block: don't verify IO lock for freeze/unfreeze in elevator_init_mq()
f1be1788a32e block: model freeze & enter queue as lock for supporting lockdep
]
|
| 145/2 |
2026/11/03 15:51 |
tool |
grepper |
0m
Args: map[Expression:mq_freeze_queue_dying PathPrefixes:[block/]]
Results: map[Output:block/blk-mq.c=116=static bool blk_freeze_set_owner(struct request_queue *q,
--
block/blk-mq.c-127- !blk_queue_registered(q);
block/blk-mq.c:128: q->mq_freeze_queue_dying = blk_queue_dying(q);
block/blk-mq.c-129- return true;
--
block/blk.h=781=static inline void blk_freeze_acquire_lock(struct request_queue *q)
--
block/blk.h-784- rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
block/blk.h:785: if (!q->mq_freeze_queue_dying)
block/blk.h-786- rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
--
block/blk.h=789=static inline void blk_unfreeze_release_lock(struct request_queue *q)
block/blk.h-790-{
block/blk.h:791: if (!q->mq_freeze_queue_dying)
block/blk.h-792- rwsem_release(&q->q_lockdep_map, _RET_IP_);
]
|
| 146/2 |
2026/11/03 15:51 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/blk-mq.c Name:blk_freeze_set_owner]
Results: map[SourceCode: 116: static bool blk_freeze_set_owner(struct request_queue *q,
117: struct task_struct *owner)
118: {
119: if (!owner)
120: return false;
121:
122: if (!q->mq_freeze_depth) {
123: q->mq_freeze_owner = owner;
124: q->mq_freeze_owner_depth = 1;
125: q->mq_freeze_disk_dead = !q->disk ||
126: test_bit(GD_DEAD, &q->disk->state) ||
127: !blk_queue_registered(q);
128: q->mq_freeze_queue_dying = blk_queue_dying(q);
129: return true;
130: }
131:
132: if (owner == q->mq_freeze_owner)
133: q->mq_freeze_owner_depth += 1;
134: return false;
135: }
SourceFile:block/blk-mq.c]
|
| 147/2 |
2026/11/03 15:51 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/blk.h Name:blk_freeze_acquire_lock]
Results: map[SourceCode: 781: static inline void blk_freeze_acquire_lock(struct request_queue *q)
782: {
783: if (!q->mq_freeze_disk_dead)
784: rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
785: if (!q->mq_freeze_queue_dying)
786: rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
787: }
SourceFile:block/blk.h]
|
| 148/2 |
2026/11/03 15:51 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/blk.h Name:blk_unfreeze_release_lock]
Results: map[SourceCode: 789: static inline void blk_unfreeze_release_lock(struct request_queue *q)
790: {
791: if (!q->mq_freeze_queue_dying)
792: rwsem_release(&q->q_lockdep_map, _RET_IP_);
793: if (!q->mq_freeze_disk_dead)
794: rwsem_release(&q->io_lockdep_map, _RET_IP_);
795: }
SourceFile:block/blk.h]
|
| 149/2 |
2026/11/03 15:51 |
llm |
history-explorer |
9m
Model:
Tokens:
input: 10933
output: 54
thoughts: 182
Thoughts: Okay, let's dive into these commits. My initial impression is that we're dealing with some refinements in block device modeling, specifically around queue freezing and its interaction with lockdep. The commit messages give me a decent starting point.
**Diving Deep into the Block Layer Commit Refinements**
First, I need to see the implementation details to fully grasp the rationale behind these changes. Let's start by using `git show` on each commit.
* `f6661b1d0525 block: track queue dying state automatically for modeling queue freeze lockdep`: Interesting, tracking the "dying" state automatically suggests a shift towards more proactive error detection within the queuing mechanisms. This probably helps with lockdep analysis by providing earlier signals related to the queue life-cycle.
* `6f491a8d4b92 block: track disk DEAD state automatically for modeling queue freeze lockdep`: Following that, automatically tracking the `DEAD` state would likely be crucial for ensuring lockdep correctness. We're probably aiming to model potential scenarios in which freezing or unfreezing operations are impossible and avoid introducing race conditions.
* `f1be1788a32e block: model freeze & enter queue as lock for supporting lockdep`: This one is the most significant. Explicitly modeling freeze/enter operations as locks is a fundamental change. It moves this critical aspect of queue management under lockdep's scrutiny, allowing us to catch potential deadlocks and other concurrency issues related to queue operations. We're effectively adding a new lock class here, probably based on how the freeze operation actually functions with the queue.
* `b9d4eee7e04b block: don't verify queue freeze manually in elevator_init_mq()`: Removing manual verification in `elevator_init_mq()` indicates a move toward a more automated approach, leveraging the lockdep framework for checking and handling these cases automatically. This is a good move to reduce redundancy.
* `357e1b7f730b block: don't verify IO lock for freeze/unfreeze in elevator_init_mq()`: Similar to the previous commit, this simplification likely reduces unnecessary checks in the initialization process and aligns the design more consistently with the lockdep-driven model.
I expect that by reading the code itself, I should be able to confirm my suspicions and see how each step affects the overall block layer design and its interactions with lockdep. I need to look for any potential side effects or areas requiring special attention.
|
| 150/2 |
2026/11/03 16:01 |
tool |
git-show |
0m
Args:
Results: map[Output:commit f6661b1d0525f3764596a1b65eeed9e75aecafa7
Author: Ming Lei <ming.lei@redhat.com>
Date: Wed Nov 27 21:51:30 2024 +0800
block: track queue dying state automatically for modeling queue freeze lockdep
Now we only verify the outmost freeze & unfreeze in current context in case
that !q->mq_freeze_depth, so it is reliable to save queue lying state when
we want to lock the freeze queue since the state is one per-task variable
now.
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241127135133.3952153-5-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 0c6a319fb936..fca2ec64a06b 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -134,6 +134,7 @@ static bool blk_freeze_set_owner(struct request_queue *q,
q->mq_freeze_disk_dead = !q->disk ||
test_bit(GD_DEAD, &q->disk->state) ||
!blk_queue_registered(q);
+ q->mq_freeze_queue_dying = blk_queue_dying(q);
return true;
}
@@ -190,7 +191,7 @@ bool __blk_freeze_queue_start(struct request_queue *q,
void blk_freeze_queue_start(struct request_queue *q)
{
if (__blk_freeze_queue_start(q, current))
- blk_freeze_acquire_lock(q, false);
+ blk_freeze_acquire_lock(q);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -238,7 +239,7 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
void blk_mq_unfreeze_queue(struct request_queue *q)
{
if (__blk_mq_unfreeze_queue(q, false))
- blk_unfreeze_release_lock(q, false);
+ blk_unfreeze_release_lock(q);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
diff --git a/block/blk.h b/block/blk.h
index 8708168d50e4..cbf6a676ffe9 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -721,26 +721,26 @@ void blk_integrity_prepare(struct request *rq);
void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
#ifdef CONFIG_LOCKDEP
-static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
- if (!queue_dying)
+ if (!q->mq_freeze_queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
- if (!queue_dying)
+ if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
#else
-static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
}
#endif
diff --git a/block/genhd.c b/block/genhd.c
index 59ac299909b3..5678194b6b1a 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -661,7 +661,7 @@ void del_gendisk(struct gendisk *disk)
struct request_queue *q = disk->queue;
struct block_device *part;
unsigned long idx;
- bool start_drain, queue_dying;
+ bool start_drain;
might_sleep();
@@ -690,9 +690,8 @@ void del_gendisk(struct gendisk *disk)
*/
mutex_lock(&disk->open_mutex);
start_drain = __blk_mark_disk_dead(disk);
- queue_dying = blk_queue_dying(q);
if (start_drain)
- blk_freeze_acquire_lock(q, queue_dying);
+ blk_freeze_acquire_lock(q);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
@@ -748,7 +747,7 @@ void del_gendisk(struct gendisk *disk)
blk_mq_exit_queue(q);
if (start_drain)
- blk_unfreeze_release_lock(q, queue_dying);
+ blk_unfreeze_release_lock(q);
}
EXPORT_SYMBOL(del_gendisk);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 522cf8eef66c..5d40af2ef971 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -581,8 +581,12 @@ struct request_queue {
#ifdef CONFIG_LOCKDEP
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
- /* Records disk state in current context, used in unfreeze queue */
+ /*
+ * Records disk & queue state in current context, used in unfreeze
+ * queue
+ */
bool mq_freeze_disk_dead;
+ bool mq_freeze_queue_dying;
#endif
wait_queue_head_t mq_freeze_wq;
/*
]
|
| 151/2 |
2026/11/03 16:01 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 6f491a8d4b92d1a840fd9209cba783c84437d0b7
Author: Ming Lei <ming.lei@redhat.com>
Date: Wed Nov 27 21:51:28 2024 +0800
block: track disk DEAD state automatically for modeling queue freeze lockdep
Now we only verify the outmost freeze & unfreeze in current context in case
that !q->mq_freeze_depth, so it is reliable to save disk DEAD state when
we want to lock the freeze queue since the state is one per-task variable
now.
Doing this way can kill lots of false positive when freeze queue is
called before adding disk[1].
[1] https://lore.kernel.org/linux-block/6741f6b2.050a0220.1cc393.0017.GAE@google.com/
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241127135133.3952153-3-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 60f457f62913..0c6a319fb936 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -131,6 +131,9 @@ static bool blk_freeze_set_owner(struct request_queue *q,
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
+ q->mq_freeze_disk_dead = !q->disk ||
+ test_bit(GD_DEAD, &q->disk->state) ||
+ !blk_queue_registered(q);
return true;
}
@@ -187,7 +190,7 @@ bool __blk_freeze_queue_start(struct request_queue *q,
void blk_freeze_queue_start(struct request_queue *q)
{
if (__blk_freeze_queue_start(q, current))
- blk_freeze_acquire_lock(q, false, false);
+ blk_freeze_acquire_lock(q, false);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -235,7 +238,7 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
void blk_mq_unfreeze_queue(struct request_queue *q)
{
if (__blk_mq_unfreeze_queue(q, false))
- blk_unfreeze_release_lock(q, false, false);
+ blk_unfreeze_release_lock(q, false);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
diff --git a/block/blk.h b/block/blk.h
index 2c26abf505b8..8708168d50e4 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -720,22 +720,29 @@ void blk_integrity_verify(struct bio *bio);
void blk_integrity_prepare(struct request *rq);
void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
-static inline void blk_freeze_acquire_lock(struct request_queue *q, bool
- disk_dead, bool queue_dying)
+#ifdef CONFIG_LOCKDEP
+static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
{
- if (!disk_dead)
+ if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
if (!queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q, bool
- disk_dead, bool queue_dying)
+static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
{
if (!queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
- if (!disk_dead)
+ if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
+#else
+static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
+{
+}
+static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
+{
+}
+#endif
#endif /* BLK_INTERNAL_H */
diff --git a/block/elevator.c b/block/elevator.c
index 7c3ba80e5ff4..ca0a74369f1c 100644
--- a/block/elevator.c
+++ b/block/elevator.c
@@ -602,14 +602,14 @@ void elevator_init_mq(struct request_queue *q)
* Disk isn't added yet, so verifying queue lock only manually.
*/
blk_freeze_queue_start_non_owner(q);
- blk_freeze_acquire_lock(q, true, false);
+ blk_freeze_acquire_lock(q, false);
blk_mq_freeze_queue_wait(q);
blk_mq_cancel_work_sync(q);
err = blk_mq_init_sched(q, e);
- blk_unfreeze_release_lock(q, true, false);
+ blk_unfreeze_release_lock(q, false);
blk_mq_unfreeze_queue_non_owner(q);
if (err) {
diff --git a/block/genhd.c b/block/genhd.c
index 79230c109fca..59ac299909b3 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -692,7 +692,7 @@ void del_gendisk(struct gendisk *disk)
start_drain = __blk_mark_disk_dead(disk);
queue_dying = blk_queue_dying(q);
if (start_drain)
- blk_freeze_acquire_lock(q, true, queue_dying);
+ blk_freeze_acquire_lock(q, queue_dying);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
@@ -748,7 +748,7 @@ void del_gendisk(struct gendisk *disk)
blk_mq_exit_queue(q);
if (start_drain)
- blk_unfreeze_release_lock(q, true, queue_dying);
+ blk_unfreeze_release_lock(q, queue_dying);
}
EXPORT_SYMBOL(del_gendisk);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 378d3a1a22fc..522cf8eef66c 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -581,6 +581,8 @@ struct request_queue {
#ifdef CONFIG_LOCKDEP
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
+ /* Records disk state in current context, used in unfreeze queue */
+ bool mq_freeze_disk_dead;
#endif
wait_queue_head_t mq_freeze_wq;
/*
]
|
| 152/2 |
2026/11/03 16:01 |
llm |
history-explorer |
6m
Model:
Tokens:
input: 15752
output: 51
thoughts: 85
Thoughts: Okay, let's dive into this. Here's how I'm thinking about it:
**Analyzing Recent Kernel Block Layer Activity**
Right, so I need to get a handle on what's been happening recently in the kernel's block layer. Specifically, I want to take a close look at a few specific commits: `f1be1788a32e`, `b9d4eee7e04b`, and `357e1b7f730b`. Those might be key to whatever issue or improvement I'm tracking. They should give me a good jumping-off point.
Beyond those specific commits, I'm also going to expand my search to see what's changed more broadly in a few crucial files. I'm focusing on `block/blk-mq.c`, `block/genhd.c`, and `drivers/md/dm.c`. These are core components for block I/O, general hard disk definitions, and device mapper. Analyzing recent changes here should help me understand any systemic shifts or potential regressions that may have come up in the area. I anticipate that recent changes in these files will provide context for what the key commits were attempting to address.
|
| 153/2 |
2026/11/03 16:08 |
tool |
git-show |
0m
Args:
Results: map[Output:commit f1be1788a32e8fa63416ad4518bbd1a85a825c9d
Author: Ming Lei <ming.lei@redhat.com>
Date: Fri Oct 25 08:37:20 2024 +0800
block: model freeze & enter queue as lock for supporting lockdep
Recently we got several deadlock report[1][2][3] caused by
blk_mq_freeze_queue and blk_enter_queue().
Turns out the two are just like acquiring read/write lock, so model them
as read/write lock for supporting lockdep:
1) model q->q_usage_counter as two locks(io and queue lock)
- queue lock covers sync with blk_enter_queue()
- io lock covers sync with bio_enter_queue()
2) make the lockdep class/key as per-queue:
- different subsystem has very different lock use pattern, shared lock
class causes false positive easily
- freeze_queue degrades to no lock in case that disk state becomes DEAD
because bio_enter_queue() won't be blocked any more
- freeze_queue degrades to no lock in case that request queue becomes dying
because blk_enter_queue() won't be blocked any more
3) model blk_mq_freeze_queue() as acquire_exclusive & try_lock
- it is exclusive lock, so dependency with blk_enter_queue() is covered
- it is trylock because blk_mq_freeze_queue() are allowed to run
concurrently
4) model blk_enter_queue() & bio_enter_queue() as acquire_read()
- nested blk_enter_queue() are allowed
- dependency with blk_mq_freeze_queue() is covered
- blk_queue_exit() is often called from other contexts(such as irq), and
it can't be annotated as lock_release(), so simply do it in
blk_enter_queue(), this way still covered cases as many as possible
With lockdep support, such kind of reports may be reported asap and
needn't wait until the real deadlock is triggered.
For example, lockdep report can be triggered in the report[3] with this
patch applied.
[1] occasional block layer hang when setting 'echo noop > /sys/block/sda/queue/scheduler'
https://bugzilla.kernel.org/show_bug.cgi?id=219166
[2] del_gendisk() vs blk_queue_enter() race condition
https://lore.kernel.org/linux-block/20241003085610.GK11458@google.com/
[3] queue_freeze & queue_enter deadlock in scsi
https://lore.kernel.org/linux-block/ZxG38G9BuFdBpBHZ@fedora/T/#u
Reviewed-by: Christoph Hellwig <hch@lst.de>
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241025003722.3630252-4-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-core.c b/block/blk-core.c
index bc5e8c5eaac9..09d10bb95fda 100644
--- a/block/blk-core.c
+++ b/block/blk-core.c
@@ -261,6 +261,8 @@ static void blk_free_queue(struct request_queue *q)
blk_mq_release(q);
ida_free(&blk_queue_ida, q->id);
+ lockdep_unregister_key(&q->io_lock_cls_key);
+ lockdep_unregister_key(&q->q_lock_cls_key);
call_rcu(&q->rcu_head, blk_free_queue_rcu);
}
@@ -278,18 +280,20 @@ void blk_put_queue(struct request_queue *q)
}
EXPORT_SYMBOL(blk_put_queue);
-void blk_queue_start_drain(struct request_queue *q)
+bool blk_queue_start_drain(struct request_queue *q)
{
/*
* When queue DYING flag is set, we need to block new req
* entering queue, so we call blk_freeze_queue_start() to
* prevent I/O from crossing blk_queue_enter().
*/
- blk_freeze_queue_start(q);
+ bool freeze = __blk_freeze_queue_start(q);
if (queue_is_mq(q))
blk_mq_wake_waiters(q);
/* Make blk_queue_enter() reexamine the DYING flag. */
wake_up_all(&q->mq_freeze_wq);
+
+ return freeze;
}
/**
@@ -321,6 +325,8 @@ int blk_queue_enter(struct request_queue *q, blk_mq_req_flags_t flags)
return -ENODEV;
}
+ rwsem_acquire_read(&q->q_lockdep_map, 0, 0, _RET_IP_);
+ rwsem_release(&q->q_lockdep_map, _RET_IP_);
return 0;
}
@@ -352,6 +358,8 @@ int __bio_queue_enter(struct request_queue *q, struct bio *bio)
goto dead;
}
+ rwsem_acquire_read(&q->io_lockdep_map, 0, 0, _RET_IP_);
+ rwsem_release(&q->io_lockdep_map, _RET_IP_);
return 0;
dead:
bio_io_error(bio);
@@ -441,6 +449,12 @@ struct request_queue *blk_alloc_queue(struct queue_limits *lim, int node_id)
PERCPU_REF_INIT_ATOMIC, GFP_KERNEL);
if (error)
goto fail_stats;
+ lockdep_register_key(&q->io_lock_cls_key);
+ lockdep_register_key(&q->q_lock_cls_key);
+ lockdep_init_map(&q->io_lockdep_map, "&q->q_usage_counter(io)",
+ &q->io_lock_cls_key, 0);
+ lockdep_init_map(&q->q_lockdep_map, "&q->q_usage_counter(queue)",
+ &q->q_lock_cls_key, 0);
q->nr_requests = BLKDEV_DEFAULT_RQ;
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 770276815507..4ae7eb335fbd 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -120,17 +120,29 @@ void blk_mq_in_flight_rw(struct request_queue *q, struct block_device *part,
inflight[1] = mi.inflight[1];
}
-void blk_freeze_queue_start(struct request_queue *q)
+bool __blk_freeze_queue_start(struct request_queue *q)
{
+ int freeze;
+
mutex_lock(&q->mq_freeze_lock);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
if (queue_is_mq(q))
blk_mq_run_hw_queues(q, false);
+ freeze = true;
} else {
mutex_unlock(&q->mq_freeze_lock);
+ freeze = false;
}
+
+ return freeze;
+}
+
+void blk_freeze_queue_start(struct request_queue *q)
+{
+ if (__blk_freeze_queue_start(q))
+ blk_freeze_acquire_lock(q, false, false);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -176,8 +188,10 @@ void blk_mq_freeze_queue(struct request_queue *q)
}
EXPORT_SYMBOL_GPL(blk_mq_freeze_queue);
-void __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
+bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
+ int unfreeze = false;
+
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
q->q_usage_counter.data->force_atomic = true;
@@ -186,13 +200,17 @@ void __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
if (!q->mq_freeze_depth) {
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
+ unfreeze = true;
}
mutex_unlock(&q->mq_freeze_lock);
+
+ return unfreeze;
}
void blk_mq_unfreeze_queue(struct request_queue *q)
{
- __blk_mq_unfreeze_queue(q, false);
+ if (__blk_mq_unfreeze_queue(q, false))
+ blk_unfreeze_release_lock(q, false, false);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
@@ -205,7 +223,7 @@ EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
*/
void blk_freeze_queue_start_non_owner(struct request_queue *q)
{
- blk_freeze_queue_start(q);
+ __blk_freeze_queue_start(q);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start_non_owner);
diff --git a/block/blk.h b/block/blk.h
index 8fddaf6eae49..63d5df0dc29c 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -4,6 +4,7 @@
#include <linux/bio-integrity.h>
#include <linux/blk-crypto.h>
+#include <linux/lockdep.h>
#include <linux/memblock.h> /* for max_pfn/max_low_pfn */
#include <linux/sched/sysctl.h>
#include <linux/timekeeping.h>
@@ -35,8 +36,9 @@ struct blk_flush_queue *blk_alloc_flush_queue(int node, int cmd_size,
void blk_free_flush_queue(struct blk_flush_queue *q);
void blk_freeze_queue(struct request_queue *q);
-void __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
-void blk_queue_start_drain(struct request_queue *q);
+bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
+bool blk_queue_start_drain(struct request_queue *q);
+bool __blk_freeze_queue_start(struct request_queue *q);
int __bio_queue_enter(struct request_queue *q, struct bio *bio);
void submit_bio_noacct_nocheck(struct bio *bio);
void bio_await_chain(struct bio *bio);
@@ -69,8 +71,11 @@ static inline int bio_queue_enter(struct bio *bio)
{
struct request_queue *q = bdev_get_queue(bio->bi_bdev);
- if (blk_try_enter_queue(q, false))
+ if (blk_try_enter_queue(q, false)) {
+ rwsem_acquire_read(&q->io_lockdep_map, 0, 0, _RET_IP_);
+ rwsem_release(&q->io_lockdep_map, _RET_IP_);
return 0;
+ }
return __bio_queue_enter(q, bio);
}
@@ -724,4 +729,22 @@ void blk_integrity_verify(struct bio *bio);
void blk_integrity_prepare(struct request *rq);
void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
+static inline void blk_freeze_acquire_lock(struct request_queue *q, bool
+ disk_dead, bool queue_dying)
+{
+ if (!disk_dead)
+ rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
+ if (!queue_dying)
+ rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
+}
+
+static inline void blk_unfreeze_release_lock(struct request_queue *q, bool
+ disk_dead, bool queue_dying)
+{
+ if (!queue_dying)
+ rwsem_release(&q->q_lockdep_map, _RET_IP_);
+ if (!disk_dead)
+ rwsem_release(&q->io_lockdep_map, _RET_IP_);
+}
+
#endif /* BLK_INTERNAL_H */
diff --git a/block/genhd.c b/block/genhd.c
index bc30eee7ab16..dfee66146bd1 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -601,13 +601,13 @@ static void blk_report_disk_dead(struct gendisk *disk, bool surprise)
rcu_read_unlock();
}
-static void __blk_mark_disk_dead(struct gendisk *disk)
+static bool __blk_mark_disk_dead(struct gendisk *disk)
{
/*
* Fail any new I/O.
*/
if (test_and_set_bit(GD_DEAD, &disk->state))
- return;
+ return false;
if (test_bit(GD_OWNS_QUEUE, &disk->state))
blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
@@ -620,7 +620,7 @@ static void __blk_mark_disk_dead(struct gendisk *disk)
/*
* Prevent new I/O from crossing bio_queue_enter().
*/
- blk_queue_start_drain(disk->queue);
+ return blk_queue_start_drain(disk->queue);
}
/**
@@ -661,6 +661,7 @@ void del_gendisk(struct gendisk *disk)
struct request_queue *q = disk->queue;
struct block_device *part;
unsigned long idx;
+ bool start_drain, queue_dying;
might_sleep();
@@ -688,7 +689,10 @@ void del_gendisk(struct gendisk *disk)
* Drop all partitions now that the disk is marked dead.
*/
mutex_lock(&disk->open_mutex);
- __blk_mark_disk_dead(disk);
+ start_drain = __blk_mark_disk_dead(disk);
+ queue_dying = blk_queue_dying(q);
+ if (start_drain)
+ blk_freeze_acquire_lock(q, true, queue_dying);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
@@ -745,6 +749,9 @@ void del_gendisk(struct gendisk *disk)
if (queue_is_mq(q))
blk_mq_exit_queue(q);
}
+
+ if (start_drain)
+ blk_unfreeze_release_lock(q, true, queue_dying);
}
EXPORT_SYMBOL(del_gendisk);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 55bec14fe55f..d0a52ed05e60 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -25,6 +25,7 @@
#include <linux/uuid.h>
#include <linux/xarray.h>
#include <linux/file.h>
+#include <linux/lockdep.h>
struct module;
struct request_queue;
@@ -474,6 +475,11 @@ struct request_queue {
struct xarray hctx_table;
struct percpu_ref q_usage_counter;
+ struct lock_class_key io_lock_cls_key;
+ struct lockdep_map io_lockdep_map;
+
+ struct lock_class_key q_lock_cls_key;
+ struct lockdep_map q_lockdep_map;
struct request *last_merge;
]
|
| 154/2 |
2026/11/03 16:08 |
tool |
git-show |
0m
Args:
Results: map[Output:commit b9d4eee7e04b9cfb0b4bcd748fe6b3ec517171d9
Author: Ming Lei <ming.lei@redhat.com>
Date: Wed Nov 27 21:51:29 2024 +0800
block: don't verify queue freeze manually in elevator_init_mq()
Now blk_freeze_queue_start() can track disk state automatically, and
it isn't necessary to verify queue freeze manually in elevator_init_mq()
any more.
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241127135133.3952153-4-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/elevator.c b/block/elevator.c
index ca0a74369f1c..a26b96662620 100644
--- a/block/elevator.c
+++ b/block/elevator.c
@@ -601,16 +601,13 @@ void elevator_init_mq(struct request_queue *q)
*
* Disk isn't added yet, so verifying queue lock only manually.
*/
- blk_freeze_queue_start_non_owner(q);
- blk_freeze_acquire_lock(q, false);
- blk_mq_freeze_queue_wait(q);
+ blk_mq_freeze_queue(q);
blk_mq_cancel_work_sync(q);
err = blk_mq_init_sched(q, e);
- blk_unfreeze_release_lock(q, false);
- blk_mq_unfreeze_queue_non_owner(q);
+ blk_mq_unfreeze_queue(q);
if (err) {
pr_warn("\"%s\" elevator initialization failed, "
]
|
| 155/2 |
2026/11/03 16:08 |
llm |
history-explorer |
3m
Model:
Tokens:
input: 21253
output: 34
thoughts: 52
Thoughts: Here's my take on the thought process:
**Diving into Freeze Owner Commits**
Okay, so I need to understand the evolution of these freeze owner mechanisms. My instinct is to go straight to the source. Let's see... I should start by exploring the commit history related to `mq_freeze_owner` and `blk_freeze_set_owner`. I'm thinking a `git log` should give me a good overview of the changes, the motivations behind them, and how these functions have evolved over time. I'll start with those specific functions to get a focused picture. That should give me a good historical context.
|
| 156/2 |
2026/11/03 16:12 |
tool |
git-log |
4m
Args: map[CodeRegexp:mq_freeze_owner Count:10 Since:3 years]
Results: map[Output:aff09dc1fd3a block: remove unnecessary check in blk_unfreeze_check_owner()
6a78699838a0 block: always verify unfreeze lock on the owner task
]
|
| 157/2 |
2026/11/03 16:17 |
llm |
history-explorer |
4m
Model:
Tokens:
input: 21536
output: 50
thoughts: 29
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:
**Initial Assessment: Code Snippet Examination**
Alright, let's dive into these two identifiers: `6a78699838a0` and `aff09dc1fd3a`. My first instinct, given the hexadecimal format, is that we're dealing with either memory addresses, cryptographic hashes, or potentially some form of unique identifiers within a larger system. Without more context, it's impossible to pinpoint their exact meaning, but the format itself suggests a few strong possibilities. I'll need to consider the environment these are found in to narrow down their purpose. I immediately start mentally cataloging which contexts this form of identifier might appear, and which would be most relevant, given my past experience. It's likely one of these.
|
| 158/2 |
2026/11/03 16:21 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 6a78699838a0ddeed3620ddf50c1521f1fe1e811
Author: Ming Lei <ming.lei@redhat.com>
Date: Thu Oct 31 21:37:19 2024 +0800
block: always verify unfreeze lock on the owner task
commit f1be1788a32e ("block: model freeze & enter queue as lock for
supporting lockdep") tries to apply lockdep for verifying freeze &
unfreeze. However, the verification is only done the outmost freeze and
unfreeze. This way is actually not correct because q->mq_freeze_depth
still may drop to zero on other task instead of the freeze owner task.
Fix this issue by always verifying the last unfreeze lock on the owner
task context, and make sure both the outmost freeze & unfreeze are
verified in the current task.
Fixes: f1be1788a32e ("block: model freeze & enter queue as lock for supporting lockdep")
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241031133723.303835-4-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-core.c b/block/blk-core.c
index 09d10bb95fda..4f791a3114a1 100644
--- a/block/blk-core.c
+++ b/block/blk-core.c
@@ -287,7 +287,7 @@ bool blk_queue_start_drain(struct request_queue *q)
* entering queue, so we call blk_freeze_queue_start() to
* prevent I/O from crossing blk_queue_enter().
*/
- bool freeze = __blk_freeze_queue_start(q);
+ bool freeze = __blk_freeze_queue_start(q, current);
if (queue_is_mq(q))
blk_mq_wake_waiters(q);
/* Make blk_queue_enter() reexamine the DYING flag. */
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 5f4496220432..5e240a4b6be0 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -120,20 +120,66 @@ void blk_mq_in_flight_rw(struct request_queue *q, struct block_device *part,
inflight[1] = mi.inflight[1];
}
-bool __blk_freeze_queue_start(struct request_queue *q)
+#ifdef CONFIG_LOCKDEP
+static bool blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
{
- int freeze;
+ if (!owner)
+ return false;
+
+ if (!q->mq_freeze_depth) {
+ q->mq_freeze_owner = owner;
+ q->mq_freeze_owner_depth = 1;
+ return true;
+ }
+
+ if (owner == q->mq_freeze_owner)
+ q->mq_freeze_owner_depth += 1;
+ return false;
+}
+
+/* verify the last unfreeze in owner context */
+static bool blk_unfreeze_check_owner(struct request_queue *q)
+{
+ if (!q->mq_freeze_owner)
+ return false;
+ if (q->mq_freeze_owner != current)
+ return false;
+ if (--q->mq_freeze_owner_depth == 0) {
+ q->mq_freeze_owner = NULL;
+ return true;
+ }
+ return false;
+}
+
+#else
+
+static bool blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
+{
+ return false;
+}
+
+static bool blk_unfreeze_check_owner(struct request_queue *q)
+{
+ return false;
+}
+#endif
+
+bool __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner)
+{
+ bool freeze;
mutex_lock(&q->mq_freeze_lock);
+ freeze = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
if (queue_is_mq(q))
blk_mq_run_hw_queues(q, false);
- freeze = true;
} else {
mutex_unlock(&q->mq_freeze_lock);
- freeze = false;
}
return freeze;
@@ -141,7 +187,7 @@ bool __blk_freeze_queue_start(struct request_queue *q)
void blk_freeze_queue_start(struct request_queue *q)
{
- if (__blk_freeze_queue_start(q))
+ if (__blk_freeze_queue_start(q, current))
blk_freeze_acquire_lock(q, false, false);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -170,7 +216,7 @@ EXPORT_SYMBOL_GPL(blk_mq_freeze_queue);
bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
- int unfreeze = false;
+ bool unfreeze;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
@@ -180,8 +226,8 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
if (!q->mq_freeze_depth) {
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
- unfreeze = true;
}
+ unfreeze = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
return unfreeze;
@@ -203,7 +249,7 @@ EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
*/
void blk_freeze_queue_start_non_owner(struct request_queue *q)
{
- __blk_freeze_queue_start(q);
+ __blk_freeze_queue_start(q, NULL);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start_non_owner);
diff --git a/block/blk.h b/block/blk.h
index ac48b79cbf80..57fc035620d6 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -37,7 +37,8 @@ void blk_free_flush_queue(struct blk_flush_queue *q);
bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
bool blk_queue_start_drain(struct request_queue *q);
-bool __blk_freeze_queue_start(struct request_queue *q);
+bool __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner);
int __bio_queue_enter(struct request_queue *q, struct bio *bio);
void submit_bio_noacct_nocheck(struct bio *bio);
void bio_await_chain(struct bio *bio);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 93551772c1d6..1b51a7c92e9b 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -575,6 +575,10 @@ struct request_queue {
struct throtl_data *td;
#endif
struct rcu_head rcu_head;
+#ifdef CONFIG_LOCKDEP
+ struct task_struct *mq_freeze_owner;
+ int mq_freeze_owner_depth;
+#endif
wait_queue_head_t mq_freeze_wq;
/*
* Protect concurrent access to q_usage_counter by
]
|
| 159/2 |
2026/11/03 16:21 |
tool |
git-show |
0m
Args:
Results: map[Output:commit aff09dc1fd3a165289011ab23cc3b46978ec741c
Author: Ming Lei <ming.lei@redhat.com>
Date: Wed Nov 27 21:51:27 2024 +0800
block: remove unnecessary check in blk_unfreeze_check_owner()
The following check of 'q->mq_freeze_owner != current' covers the
previous one, so remove the unnecessary check.
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241127135133.3952153-2-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 8ac19d4ae3c0..60f457f62913 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -142,8 +142,6 @@ static bool blk_freeze_set_owner(struct request_queue *q,
/* verify the last unfreeze in owner context */
static bool blk_unfreeze_check_owner(struct request_queue *q)
{
- if (!q->mq_freeze_owner)
- return false;
if (q->mq_freeze_owner != current)
return false;
if (--q->mq_freeze_owner_depth == 0) {
]
|
| 160/2 |
2026/11/03 16:21 |
llm |
history-explorer |
3m
Model:
Tokens:
input: 24482
output: 35
thoughts: 146
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience:
**Recent Block Layer Activity: Ming Lei's Contributions**
Right, let's take a quick look at this. Commits `f1be1788a32e`, `6a78699838a0`, `6f491a8d4b92`, and `f6661b1d0525`βall from October/November 2024, if I'm reading this correctlyβwere all tagged by Ming Lei. Interesting. I'm going to quickly check for even more recent activity in the core block layer files: `block/blk-mq.c`, `block/blk.h`, and `block/genhd.c`. It's worth digging into any potential refactoring or new feature additions he's been working on.
Let's start by running a `git log` on `block/blk-mq.c`. I'll specify a time frame β a year should give me a good overview, maybe six months to start and then adjust as necessary. This'll help me understand the flow of changes and see what Ming has been up to specifically in that area. I expect to get some interesting output here.
|
| 161/2 |
2026/11/03 16:25 |
tool |
git-log |
0m
Args: map[Count:30 PathPrefix:block/blk-mq.c Since:1 year]
Results: map[Output:4fcc499ea9bc blk-mq: set up a queue under tag_list_lock
89a2381482d8 blk-mq: exit the hctxs of a queue under tag_list_lock
71ec3c7d6db8 blk-mq: quiesce a queue that joins a quiesced tag set
0db9f8968a89 blk-mq: don't forget a timer the driver has restarted
9531230ee1fc blk-mq: don't bring back flags of a completed request
620cfc7a6642 blk-mq: keep sharing tags fairly after a queue update
24974185999f blk-mq: don't trust the cookie in blk_mq_poll()
afc1de47a7ab blk-mq: clear stale inactive flag on hctx reuse
5f702d4bd61b blk-mq: drop the tag_set argument from blk_mq_free_rq_map/tags
e1c51edd6a57 blk-mq: share one tags_srcu instance across all tag sets
20d808694e40 block: fix indention for dma-buf checks
d88e44f43e93 block: introduce dma map backed bio type
e0f2224433b1 block: drop the cached plug time when blk_add_rq_to_plug() flushes
9d2c70986bb7 blk-mq: allow cached requests to be used for flush operations
ab6c756f28c7 blk-mq: set RQF_USE_SCHED when the operation is known
1207dbb91c11 blk-mq: add missing call to srcu_barrier() in blk_mq_free_tag_set()
30e542a36228 blk-mq: bound blk_hctx_poll() to one jiffy
5bdb8ec58b54 block: propagate in_flight to whole disk on partition I/O
b7f40ab50190 block: export passthrough stats enabled
a7d8eaee7faf block: add a bio_endio_status helper
b051bb6bf0a2 blk-mq: reinsert cached request to the list
dc278e9bf2b9 blk-mq: pop cached request if it is usable
2c6e6a18a37b block: recompute nr_integrity_segments in blk_insert_cloned_request
daa6c79858e9 block: clear BIO_QOS flags in blk_steal_bios()
b2c45ced591e block: move bio queue-transition flag fixups into blk_steal_bios()
7ea25eaad5ae block: factor out a bio_integrity_action helper
539d1b47e935 block: break pcpu_alloc_mutex dependency on freeze_lock
bf4afc53b77a Convert 'alloc_obj' family to use the new default GFP_KERNEL argument
69050f8d6d07 treewide: Replace kmalloc with kmalloc_obj for non-scalar types
f98afe4f31bb blk-mq: add a new queue sysfs attribute async_depth
]
|
| 162/2 |
2026/11/03 16:25 |
llm |
history-explorer |
2m
Model:
Tokens:
input: 25765
output: 33
thoughts: 37
Thoughts: Here's my take on those thoughts:
**Analyzing Block Layer History in the Linux Kernel**
Okay, so I need to dig into the recent changes impacting the block layer. To get a handle on what's been happening, I'm thinking I should start by querying the `git-log` history. Specifically, I'll focus on a few key files. I want to zero in on any changes touching `block/blk.h` since it's the core header for the block layer's interfaces. Then, to get a sense of the implementation details, I'll check `block/genhd.c` which, if I recall correctly, handles generic disk operations, and `block/blk-core.c` which likely contains a lot of the core structures and management code. By examining the commit history for those files, I should get a pretty good overview of recent modifications and potential regressions. This should allow me to formulate some hypotheses about current performance or stability issues. This will narrow my scope.
|
| 163/2 |
2026/11/03 16:27 |
tool |
git-log |
0m
Args: map[Count:30 PathPrefix:block/blk.h Since:1 year]
Results: map[Output:9531230ee1fc blk-mq: don't bring back flags of a completed request
0687c9c346ac block: fail zone management operations to read-only and offline zones
b539aeacf8cc block: rename bi_bvec_done
691b052139c9 block: fix race in blk_time_get_ns() returning 0
3dd63dba8f9c block: avoid potential deadlock on zone revalidation failure
9b0c3673c885 block: check bio split for unaligned bvec
d39a63ead381 block: add a str_to_blk_op helper
ce351560b714 block: add a "tag" for block status codes
5bdb8ec58b54 block: propagate in_flight to whole disk on partition I/O
131f14125a18 block/blk-mq-debugfs: Improve lock context annotations
82aaa55a3162 block: unexport blk_status_to_str
41c665aae2b5 block: relax pgmap check in bio_add_page for compatible zone device pages
13920e4b7b78 block: add pgmap check to biovec_phys_mergeable
92c3737a2473 block: add a bio_submit_or_kill helper
fed406f3c1c2 block: mark bvec_{alloc,free} static
3f00626832a9 block: prepare generation / verification helpers for fs usage
dfe48ea17973 blk-mq: use NOIO context to prevent deadlock during debugfs creation
ee81212f74a5 block: decouple secure erase size limit from discard size limit
301f5356521e block: remove bio_release_page
f7ba87dfa8e4 block: account for bi_bvec_done in bio_may_need_split()
ee623c892aa5 block: use bvec iterator helper for bio_may_need_split()
232143b60538 block: unify elevator tags and type xarrays into struct elv_change_ctx
efae226c2ef1 block: handle zone management operations completions
]
|
| 164/2 |
2026/11/03 16:27 |
llm |
history-explorer |
6m
Model:
Tokens:
input: 26620
output: 43
thoughts: 27
Thoughts: Here's my take on those thoughts:
**Analyzing Block Layer Concurrency Issues**
Okay, so I need to get a handle on potential concurrency problems within the block layer. My initial thought is to zero in on specific keywords that often signal lock-related issues or system hangs. Given the block layer's critical role and the potential for complex interactions, I'll search commit messages to narrow down the problem set. I'll focus on the keywords "lockdep" β that should flag any lock dependency problems explicitly mentioned in the code changes β and "freeze", since unexpected system halts are a likely consequence of lock contention. I'll concentrate my search on the `block/` directory, naturally, since that's where the core block layer code resides. And to keep the scope reasonable, I'll limit the search to the past three years. This gives me a manageable window into recent developments and any ongoing issues. Let's see what this search yields.
|
| 165/2 |
2026/11/03 16:33 |
tool |
git-log |
0m
Args: map[Count:30 MessageRegexps:[freeze lockdep] PathPrefix:block/ Since:3 years]
Results: map[Output:3dd63dba8f9c block: avoid potential deadlock on zone revalidation failure
539d1b47e935 block: break pcpu_alloc_mutex dependency on freeze_lock
d4c3ef56a161 block: define alloc_sched_data and free_sched_data methods for kyber
61019afdf6ac block: introduce alloc_sched_data and free_sched_data elevator methods
5d726c4dbeed blk-cgroup: fix possible deadlock while configuring policy
370ac285f23a block: avoid cpu_hotplug_lock depedency on freeze_lock
2d82f3bd8910 blk-mq: fix lockdep warning in __blk_mq_update_nr_hw_queues
04225d13aef1 block: fix potential deadlock while running nr_hw_queue update
f5a6604f7a44 block: fix lockdep warning caused by lock dependency in elv_iosched_store
2d8951aee844 block: unfreeze queue if realloc tag set fails during nr_hw_queues update
7ed7fa561c35 block: move hctx cpuhp add/del out of queue freezing
01b91bf14f6d block: don't grab elevator lock during queue initialization
9730763f4756 block: correct locking order for protecting blk-wbt parameters
ffa1e7ada456 block: Make request_queue lockdep splats show up earlier
1bf70d08cc3b block: introduce a dedicated lock for protecting queue elevator updates
f6661b1d0525 block: track queue dying state automatically for modeling queue freeze lockdep
6f491a8d4b92 block: track disk DEAD state automatically for modeling queue freeze lockdep
be26ba96421a block: Fix potential deadlock while freezing queue and acquiring sysfs_lock
0b83c86b444a block: Prevent potential deadlock in blk_revalidate_disk_zones()
357e1b7f730b block: don't verify IO lock for freeze/unfreeze in elevator_init_mq()
6a78699838a0 block: always verify unfreeze lock on the owner task
f1be1788a32e block: model freeze & enter queue as lock for supporting lockdep
8acdd0e7bfad blk-mq: add non_owner variant of start_freeze/unfreeze queue APIs
]
|
| 166/2 |
2026/11/03 16:33 |
llm |
history-explorer |
2m
Model:
Tokens:
input: 27513
output: 23
thoughts: 17
Thoughts: Okay, here's my summary, presented as a stream of thought:
**Checking That Hash**
Alright, time to dig in. Given the context of what I'm working on β let's assume itβs a security analysis or debugging process β I've got a hash, `8acdd0e7bfad`, that needs immediate scrutiny. It's a quick, instinctual move, a reflex really. I need to understand what this represents, where it came from, and what, if anything, itβs connected to. The presence of this hash suggests a specific artifact or a point of interest, and I can't leave it unverified. I need to cross-reference it with any relevant databases, logs, or analysis tools I have at my disposal. Is it a file hash? An API key? A network identifier? I have a feeling that this will lead me down a rabbit hole. Let's get to it!
|
| 167/2 |
2026/11/03 16:36 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 8acdd0e7bfadda6b5103f2960d293581954454ed
Author: Ming Lei <ming.lei@redhat.com>
Date: Fri Oct 25 08:37:18 2024 +0800
blk-mq: add non_owner variant of start_freeze/unfreeze queue APIs
Add non_owner variant of start_freeze/unfreeze queue APIs, so that the
caller knows that what they are doing, and we can skip lockdep support
for non_owner variant in per-call level.
Prepare for supporting lockdep for freezing/unfreezing queue.
Reviewed-by: Christoph Hellwig <hch@lst.de>
Suggested-by: Christoph Hellwig <hch@lst.de>
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241025003722.3630252-2-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-mq.c b/block/blk-mq.c
index aae9a112c913..770276815507 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -196,6 +196,26 @@ void blk_mq_unfreeze_queue(struct request_queue *q)
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
+/*
+ * non_owner variant of blk_freeze_queue_start
+ *
+ * Unlike blk_freeze_queue_start, the queue doesn't need to be unfrozen
+ * by the same task. This is fragile and should not be used if at all
+ * possible.
+ */
+void blk_freeze_queue_start_non_owner(struct request_queue *q)
+{
+ blk_freeze_queue_start(q);
+}
+EXPORT_SYMBOL_GPL(blk_freeze_queue_start_non_owner);
+
+/* non_owner variant of blk_mq_unfreeze_queue */
+void blk_mq_unfreeze_queue_non_owner(struct request_queue *q)
+{
+ __blk_mq_unfreeze_queue(q, false);
+}
+EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_non_owner);
+
/*
* FIXME: replace the scsi_internal_device_*block_nowait() calls in the
* mpt3sas driver such that this function can be removed.
diff --git a/include/linux/blk-mq.h b/include/linux/blk-mq.h
index 59e9adf815a4..2035fad3131f 100644
--- a/include/linux/blk-mq.h
+++ b/include/linux/blk-mq.h
@@ -919,6 +919,8 @@ void blk_freeze_queue_start(struct request_queue *q);
void blk_mq_freeze_queue_wait(struct request_queue *q);
int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
unsigned long timeout);
+void blk_mq_unfreeze_queue_non_owner(struct request_queue *q);
+void blk_freeze_queue_start_non_owner(struct request_queue *q);
void blk_mq_map_queues(struct blk_mq_queue_map *qmap);
void blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set, int nr_hw_queues);
]
|
| 168/2 |
2026/11/03 16:36 |
llm |
history-explorer |
2m
Model:
Tokens:
input: 28727
output: 36
thoughts: 110
Thoughts: Okay, here's my analysis of those specific functions and search terms related to device mapper and block device management.
**Delving into Device Mapper Internals**
I need to get a deeper understanding of how the device mapper's core functions interact. My initial focus is on `drivers/md/dm.c` and `drivers/md/dm-ioctl.c`, specifically dissecting the roles of `table_load`, `dev_remove`, `__dm_destroy`, and `dm_setup_md_queue`. These are critical for understanding the lifecycle of a device mapper device, from creation and table loading, to device removal and queue management. I need to grasp how the device table is loaded, how devices are cleaned up, and what steps are taken to handle the block I/O queue during these operations. I suspect there are intricate interactions between these functions, and I want to identify potential bottlenecks or areas prone to race conditions.
To get the full picture, I'm going to leverage `git-log` within the `drivers/md/` directory. I'm going to search for commits that touch upon related functions and concepts, such as `blk_mark_disk_dead`, `del_gendisk`, `holders`, `dm_destroy`, and `dm_setup_md_queue`. These are all signifiers of how the block device and its gendisk are managed, destroyed, and that there are potentially multiple users of a device (the "holders" concept). By reviewing the commit history, I can likely track the evolution of these functions, see the motivations behind design decisions, and identify potential bugs or performance optimizations that were addressed over time. This will give me context, and hopefully shed light on potential issues and limitations.
|
| 169/2 |
2026/11/03 16:39 |
tool |
git-log |
0m
Args: map[Count:20 MessageRegexps:[blk_mark_disk_dead] Since:3 years]
Results: map[Output:085bb18a0b91 scsi: sd: Mark the disk dead if runtime resume fails in sd_remove()
61b6d1df1d62 xen-blkfront: Fix IO race during unplug
7e9a46004b47 block: set QUEUE_FLAG_DYING unconditionally in blk_mark_disk_dead()
69139a62a918 erofs: open via dedicated fs bdev helpers
49f06cff50a4 block: skip sync_blockdev() on surprise removal in bdev_mark_dead()
a471977780cc rbd: unfreeze queue after marking disk as dead
7e04da2dc701 block: fix deadlock between sd_remove & sd_release
]
|
| 170/2 |
2026/11/03 16:39 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 29437
output: 27
thoughts: 45
Thoughts: Here's my analysis of that commit, thinking through it like an expert:
**Investigating a Critical Block Layer Change**
Okay, so I see a commit touching `blk_mark_disk_dead()` and specifically, the unconditional setting of `QUEUE_FLAG_DYING`. My initial reaction is, that's potentially significant. `QUEUE_FLAG_DYING` is a pretty strong signal within the block layer β it usually means the device or queue is on its way out. Unconditionally setting it in this function warrants a closer look because that could have far-reaching implications. I need to understand the reasoning behind this change.
Now, let's dive into the commit itself and understand the context. What's the rationale provided? Are there any related bug reports or discussions referenced? Is there any risk of regressions or unexpected behavior? Iβm immediately considering how this affects error handling, resource management, and potentially even device failover strategies. I am thinking about race conditions that this could introduce.
What are the implications for various block layer components? How does this interact with I/O schedulers, multipath drivers, and RAID implementations? Specifically, I'm now thinking about how this plays into situations where a disk might be declared 'dead' but not physically removed or power cycled. This is an important detail!
This commit could represent a significant change in how the block layer handles device failure scenarios. I need to assess whether this is an improvement, a potential source of problems, or simply a necessary refactoring. I'll need to carefully review the surrounding code to grasp the intent and the potential impact of this change. Let's dig in and see what the details are!
|
| 171/2 |
2026/11/03 16:39 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 7e9a46004b471eaf69b082c473d865316a4158e0
Author: θ‘θΏε€ <hulianqin@vivo.com>
Date: Wed Aug 12 11:59:04 2026 +0000
block: set QUEUE_FLAG_DYING unconditionally in blk_mark_disk_dead()
Disks created via blk_mq_alloc_disk_for_queue() (e.g. SCSI SD disks)
do not have GD_OWNS_QUEUE set. Currently __blk_mark_disk_dead() only
sets QUEUE_FLAG_DYING when GD_OWNS_QUEUE is set, so for such disks
blk_queue_enter() and __bio_queue_enter() cannot detect the dying
state via blk_queue_dying() and remain blocked waiting for I/O that
will never complete after surprise removal.
blk_mark_disk_dead() is the explicit "surprise removal" API -- the
caller has already decided the disk is dead. Setting QUEUE_FLAG_DYING
unconditionally here is appropriate: any in-flight I/O from other
threads should get -ENODEV immediately from blk_queue_enter()
regardless of GD_OWNS_QUEUE ownership.
For disks that already have GD_OWNS_QUEUE set, __blk_mark_disk_dead()
will set the flag again which is harmless.
Fixes: 6f8191fdf41d ("block: simplify disk shutdown")
Cc: stable@vger.kernel.org
Signed-off-by: Lianqin Hu <hulianqin@vivo.com>
Reviewed-by: Christoph Hellwig <hch@lst.de>
Link: https://patch.msgid.link/PUZPR06MB62247E82E66A3ED46CC3E6C7D2DC2@PUZPR06MB6224.apcprd06.prod.outlook.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/genhd.c b/block/genhd.c
index df2c3c69b467..7b089e2d52c4 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -681,6 +681,7 @@ static bool __blk_mark_disk_dead(struct gendisk *disk)
*/
void blk_mark_disk_dead(struct gendisk *disk)
{
+ blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
__blk_mark_disk_dead(disk);
blk_report_disk_dead(disk, true);
}
]
|
| 172/2 |
2026/11/03 16:39 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 30578
output: 44
thoughts: 39
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:
**Investigating Potential Resource Leakage in the Device Mapper Code**
Alright, I'm diving into this Device Mapper issue. I need to get a handle on what might be going wrong with resource destruction. My thinking is to target `drivers/md/dm.c` specifically, given its central role in Device Mapper core functionality. I'm going to leverage `git-log` to uncover the commit history. The key is to look for commits that have touched the `__dm_destroy`, `dm_destroy` functions, or anything related to "holders." The "holders" keyword usually means that a reference is maintained when the object is destroyed. This sounds like an area where we can have potential memory issues if we are not careful about cleaning up those references. This approach will allow me to track the evolution of these critical destruction paths and see if any recent changes might have introduced a regression or simply highlight where the biggest changes have happened. The goal here is to identify potential sources of leakage, dangling pointers, or other memory management problems related to device destruction, and see if there are any related changes that may give us a clue.
|
| 173/2 |
2026/11/03 16:40 |
tool |
git-log |
0m
Args: map[Count:20 MessageRegexps:[dm_destroy|holders] PathPrefix:drivers/md/ Since:3 years]
Results:
|
| 174/2 |
2026/11/03 16:40 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 30932
output: 40
thoughts: 33
Thoughts: Okay, here's my take on those thoughts, framed as a first-person expert summary:
**Digging into dm.c with git-log**
Right, let's get down to brass tacks. I need to understand the evolution of this code, specifically around `drivers/md/dm.c`. I don't want to get bogged down in commit messages just yet, so I'll start with a straightforward `git-log` search. No fancy regex for message content, just a pure chronological view of changes to that specific file. That should give me a solid baseline, a clear history.
Alternatively, since I'm trying to see which parts of code are important, I could use CodeRegexp on that git-log to focus on the lines that contain the word "holders", since these may indicate the parts of code that hold references to something. I'll need to figure out the right combination of arguments for `git-log` to get me the results I need. I'm thinking I'll need to use some combination of `--` to separate the file path.
|
| 175/2 |
2026/11/03 16:40 |
tool |
git-log |
0m
Args: map[CodeRegexp:holders Count:10 PathPrefix:drivers/md/ Since:3 years]
Results: map[Output:5380c7f6335c dm: fix race when loading and unloading a table
cfaf07fae7a2 dm vdo: add hash locks and hash zones
79535a7881c0 dm vdo: add data_vio, the request object which services incoming bios
]
|
| 176/2 |
2026/11/03 16:40 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 31320
output: 27
thoughts: 35
Thoughts: Okay, here's my interpretation of that request, formatted as requested:
**Examining a Recent Database Commit**
Right, let's see. My attention is drawn to commit `5380c7f6335c dm: fix race when loading and unloading a table`. Hmm, a race condition? Interesting. Specifically, in the data management layer, and centered around loading and unloading tables. That immediately flags a potential area of concern. Race conditions in data management are notoriously tricky and can lead to all sorts of nasty data corruption or unexpected behavior β things like data loss, incorrect query results, or even system crashes. So, a fix here is definitely worth a closer look. Let's delve in and see what the specifics of this "race" were, and how they addressed the issue. Time to analyze the code changes.
|
| 177/2 |
2026/11/03 16:40 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 5380c7f6335cc6d77eb77d065105e81155c4d9d3
Author: Mikulas Patocka <mpatocka@redhat.com>
Date: Mon Jul 27 22:27:07 2026 +0200
dm: fix race when loading and unloading a table
If the userspace calls two concurrent table load ioctls and one of them
succeeds and the other fails, there is a race condition because
dm_setup_md_queue walks &md->table_devices without any lock. If the walk
races with dm_table_destroy -> free_devices -> dm_put_table_device, there
is access to invalid memory.
Fix this race by extending the lock over the list walk.
Signed-off-by: Mikulas Patocka <mpatocka@redhat.com>
Cc: stable@vger.kernel.org
diff --git a/drivers/md/dm.c b/drivers/md/dm.c
index e907fe278c72..eb9e32995b79 100644
--- a/drivers/md/dm.c
+++ b/drivers/md/dm.c
@@ -2630,9 +2630,10 @@ int dm_setup_md_queue(struct mapped_device *md, struct dm_table *t)
*/
mutex_lock(&md->table_devices_lock);
r = add_disk(md->disk);
- mutex_unlock(&md->table_devices_lock);
- if (r)
+ if (r) {
+ mutex_unlock(&md->table_devices_lock);
return r;
+ }
/*
* Register the holder relationship for devices added before the disk
@@ -2643,18 +2644,21 @@ int dm_setup_md_queue(struct mapped_device *md, struct dm_table *t)
if (r)
goto out_undo_holders;
}
+ mutex_unlock(&md->table_devices_lock);
r = dm_sysfs_init(md);
if (r)
- goto out_undo_holders;
+ goto lock_out_undo_holders;
md->type = type;
+
return 0;
+lock_out_undo_holders:
+ mutex_lock(&md->table_devices_lock);
out_undo_holders:
list_for_each_entry_continue_reverse(td, &md->table_devices, list)
bd_unlink_disk_holder(td->dm_dev.bdev, md->disk);
- mutex_lock(&md->table_devices_lock);
del_gendisk(md->disk);
mutex_unlock(&md->table_devices_lock);
return r;
]
|
| 178/2 |
2026/11/03 16:40 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 32314
output: 43
thoughts: 69
Thoughts: Here's my summary, as if I were thinking it:
**Digging into DM's __dm_destroy Calls**
Okay, so that `5380c7f6335c` commit was specifically dealing with those `bd_link_disk_holder` things β focusing on block device holders as they exist in sysfs and such, rather than the `md->holders` that we all know and love. Now, I need to figure out the broader context. What other commits are also messing around with `__dm_destroy` within that `drivers/md/dm.c` file? Time to track down the callers and understand the potential interactions. I'm especially interested in looking at the commits that touch that function and see what the wider implications are for block devices.
|
| 179/2 |
2026/11/03 16:40 |
tool |
git-log |
0m
Args: map[CodeRegexp:__dm_destroy Count:10 PathPrefix:drivers/md/ Since:3 years]
Results:
|
| 180/2 |
2026/11/03 16:40 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 32607
output: 40
thoughts: 23
Thoughts: Here's my thought process, as it stands:
**Checking the Historical Footprints of `__dm_destroy`**
Okay, so I need to dig into the history of the `__dm_destroy` symbol. My initial thought is to leverage `SymbolName` and `SourcePath` to effectively track down the changes to this particular function. It's the most efficient way to pinpoint when and where modifications were made, and who was responsible, or what changes caused its implementation. This will help me contextualize the current state of the function.
|
| 181/2 |
2026/11/03 16:40 |
tool |
git-log |
0m
Args: map[Since:3 years SourcePath:drivers/md/dm.c SymbolName:__dm_destroy]
Results:
|
| 182/2 |
2026/11/03 16:40 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 32798
output: 32
thoughts: 59
Thoughts: Okay, let's see... the symbol search came up empty, which makes me think `__dm_destroy` might not have been touched recently, or perhaps the symbol search itself is failing. Let's dig deeper. I'm going to quickly check `drivers/md/dm.c` with `git blame` for the `__dm_destroy` function. That'll immediately tell me the last modification date and hopefully shed some light on whether it's the right place to be looking. I'm betting that'll give us the answer.
|
| 183/2 |
2026/11/03 16:40 |
tool |
grepper |
0m
Args: map[Expression:__dm_destroy PathPrefixes:[drivers/md/dm.c]]
Results: map[Output:drivers/md/dm.c=2724=EXPORT_SYMBOL_GPL(dm_device_name);
drivers/md/dm.c-2725-
drivers/md/dm.c:2726:static void __dm_destroy(struct mapped_device *md, bool wait)
drivers/md/dm.c-2727-{
--
drivers/md/dm.c=2773=void dm_destroy(struct mapped_device *md)
drivers/md/dm.c-2774-{
drivers/md/dm.c:2775: __dm_destroy(md, true);
drivers/md/dm.c-2776-}
--
drivers/md/dm.c=2778=void dm_destroy_immediate(struct mapped_device *md)
drivers/md/dm.c-2779-{
drivers/md/dm.c:2780: __dm_destroy(md, false);
drivers/md/dm.c-2781-}
]
|
| 184/2 |
2026/11/03 16:40 |
llm |
history-explorer |
3m
Model:
Tokens:
input: 33266
output: 36
thoughts: 31
Thoughts: Okay, let's dive into this. I need to understand the `__dm_destroy` function within the device mapper code. Specifically, I'll be looking at the implementation in `drivers/md/dm.c` around line 2726. I expect this to be the core of how a device mapper device is torn down. I'm hoping to get a clear picture of the cleanup process: how resources are released, any potential issues that might arise during destruction, and any important considerations for error handling. Let's see what the code reveals. I anticipate seeing things like freeing allocated memory, detaching from underlying devices or targets, and potentially notifying other subsystems. This is the lynchpin of device mapper's lifecycle, so understanding it is crucial.
|
| 185/2 |
2026/11/03 16:44 |
tool |
read-file |
0m
Args: map[File:drivers/md/dm.c FirstLine:2725 LineCount:60]
Results: map[Contents:2725:
2726: static void __dm_destroy(struct mapped_device *md, bool wait)
2727: {
2728: struct dm_table *map;
2729: int srcu_idx;
2730:
2731: might_sleep();
2732:
2733: spin_lock(&_minor_lock);
2734: idr_replace(&_minor_idr, MINOR_ALLOCED, MINOR(disk_devt(dm_disk(md))));
2735: set_bit(DMF_FREEING, &md->flags);
2736: spin_unlock(&_minor_lock);
2737:
2738: blk_mark_disk_dead(md->disk);
2739:
2740: /*
2741: * Take suspend_lock so that presuspend and postsuspend methods
2742: * do not race with internal suspend.
2743: */
2744: mutex_lock(&md->suspend_lock);
2745: map = dm_get_live_table(md, &srcu_idx);
2746: if (!dm_suspended_md(md)) {
2747: dm_table_presuspend_targets(map);
2748: set_bit(DMF_SUSPENDED, &md->flags);
2749: set_bit(DMF_POST_SUSPENDING, &md->flags);
2750: dm_table_postsuspend_targets(map);
2751: }
2752: /* dm_put_live_table must be before fsleep, otherwise deadlock is possible */
2753: dm_put_live_table(md, srcu_idx);
2754: mutex_unlock(&md->suspend_lock);
2755:
2756: /*
2757: * Rare, but there may be I/O requests still going to complete,
2758: * for example. Wait for all references to disappear.
2759: * No one should increment the reference count of the mapped_device,
2760: * after the mapped_device state becomes DMF_FREEING.
2761: */
2762: if (wait)
2763: while (atomic_read(&md->holders))
2764: fsleep(1000);
2765: else if (atomic_read(&md->holders))
2766: DMWARN("%s: Forcibly removing mapped_device still in use! (%d users)",
2767: dm_device_name(md), atomic_read(&md->holders));
2768:
2769: dm_table_destroy(__unbind(md));
2770: free_dev(md);
2771: }
2772:
2773: void dm_destroy(struct mapped_device *md)
2774: {
2775: __dm_destroy(md, true);
2776: }
2777:
2778: void dm_destroy_immediate(struct mapped_device *md)
2779: {
2780: __dm_destroy(md, false);
2781: }
2782:
2783: void dm_put(struct mapped_device *md)
2784: {
]
|
| 186/2 |
2026/11/03 16:44 |
llm |
history-explorer |
4m
Model:
Tokens:
input: 34409
output: 37
thoughts: 28
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:
**Investigating a Suspect Code Segment**
Alright, so the first thing I'm thinking is, "Let's dig into that `dm.c` file again, specifically lines 2730 through 2770 in the `drivers/md/` directory." I need to understand the history of that particular chunk of code. I'm assuming that it has a bug. My immediate thought is to use `git blame` on those lines. This will tell me who wrote them, when they were written, and hopefully give me some context through commit messages to understand the purpose and rationale behind the code. I can then figure out if my hypothesis is correct or if my initial understanding is wrong.
|
| 187/2 |
2026/11/03 16:49 |
tool |
git-blame |
0m
Args: map[End:2770 File:drivers/md/dm.c Start:2730]
Results: map[Output:^1da177e4c3f4 2730)
3f77316de0ec0 2731) might_sleep();
fba9f90e568e1 2732)
63a4f065ece61 2733) spin_lock(&_minor_lock);
3f77316de0ec0 2734) idr_replace(&_minor_idr, MINOR_ALLOCED, MINOR(disk_devt(dm_disk(md))));
3f77316de0ec0 2735) set_bit(DMF_FREEING, &md->flags);
3f77316de0ec0 2736) spin_unlock(&_minor_lock);
3b785fbcf81c3 2737)
7a5428dcb7902 2738) blk_mark_disk_dead(md->disk);
3f77316de0ec0 2739)
ab7c7bb6f4ab9 2740) /*
ab7c7bb6f4ab9 2741) * Take suspend_lock so that presuspend and postsuspend methods
ab7c7bb6f4ab9 2742) * do not race with internal suspend.
ab7c7bb6f4ab9 2743) */
ab7c7bb6f4ab9 2744) mutex_lock(&md->suspend_lock);
2a708cff93f18 2745) map = dm_get_live_table(md, &srcu_idx);
3f77316de0ec0 2746) if (!dm_suspended_md(md)) {
3f77316de0ec0 2747) dm_table_presuspend_targets(map);
adc0daad366b6 2748) set_bit(DMF_SUSPENDED, &md->flags);
5df96f2b9f58a 2749) set_bit(DMF_POST_SUSPENDING, &md->flags);
3f77316de0ec0 2750) dm_table_postsuspend_targets(map);
^1da177e4c3f4 2751) }
238d991f054a5 2752) /* dm_put_live_table must be before fsleep, otherwise deadlock is possible */
83d5e5b0af907 2753) dm_put_live_table(md, srcu_idx);
2a708cff93f18 2754) mutex_unlock(&md->suspend_lock);
83d5e5b0af907 2755)
3f77316de0ec0 2756) /*
3f77316de0ec0 2757) * Rare, but there may be I/O requests still going to complete,
3f77316de0ec0 2758) * for example. Wait for all references to disappear.
3f77316de0ec0 2759) * No one should increment the reference count of the mapped_device,
3f77316de0ec0 2760) * after the mapped_device state becomes DMF_FREEING.
3f77316de0ec0 2761) */
3f77316de0ec0 2762) if (wait)
3f77316de0ec0 2763) while (atomic_read(&md->holders))
238d991f054a5 2764) fsleep(1000);
3f77316de0ec0 2765) else if (atomic_read(&md->holders))
3f77316de0ec0 2766) DMWARN("%s: Forcibly removing mapped_device still in use! (%d users)",
3f77316de0ec0 2767) dm_device_name(md), atomic_read(&md->holders));
3f77316de0ec0 2768)
3f77316de0ec0 2769) dm_table_destroy(__unbind(md));
3f77316de0ec0 2770) free_dev(md);
]
|
| 188/2 |
2026/11/03 16:49 |
llm |
history-explorer |
3m
Model:
Tokens:
input: 35871
output: 27
thoughts: 20
Thoughts: Okay, here's my interpretation of what's going through my mind, delivered as requested:
**Diving into Commit 7a5428dcb7902**
Alright, let's get down to brass tacks. I'm pulling up commit `7a5428dcb7902`. Given my understanding of the codebase and the usual patterns in our workflow, my mind is already starting to spin. I'm probably looking for a specific area, perhaps a bug fix, a new feature implementation, or maybe even a refactor. Judging by the commit hash I can see the author, maybe I'll get some clues from their past commits to understand this better. I'm anticipating the potential impact this commit has on the wider system and I'm ready to evaluate its quality.
|
| 189/2 |
2026/11/03 16:53 |
tool |
git-show |
0m
Args: map[Commit:7a5428dcb7902]
Results: map[Output:commit 7a5428dcb7902700b830e912feee4e845df7c019
Author: Christoph Hellwig <hch@lst.de>
Date: Thu Feb 17 08:52:31 2022 +0100
block: fix surprise removal for drivers calling blk_set_queue_dying
Various block drivers call blk_set_queue_dying to mark a disk as dead due
to surprise removal events, but since commit 8e141f9eb803 that doesn't
work given that the GD_DEAD flag needs to be set to stop I/O.
Replace the driver calls to blk_set_queue_dying with a new (and properly
documented) blk_mark_disk_dead API, and fold blk_set_queue_dying into the
only remaining caller.
Fixes: 8e141f9eb803 ("block: drain file system I/O on del_gendisk")
Reported-by: Markus BlΓΆchl <markus.bloechl@ipetronik.com>
Signed-off-by: Christoph Hellwig <hch@lst.de>
Reviewed-by: Sagi Grimberg <sagi@grimberg.me>
Link: https://lore.kernel.org/r/20220217075231.1140-1-hch@lst.de
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-core.c b/block/blk-core.c
index d93e3bb9a769..1039515c99d6 100644
--- a/block/blk-core.c
+++ b/block/blk-core.c
@@ -284,13 +284,6 @@ void blk_queue_start_drain(struct request_queue *q)
wake_up_all(&q->mq_freeze_wq);
}
-void blk_set_queue_dying(struct request_queue *q)
-{
- blk_queue_flag_set(QUEUE_FLAG_DYING, q);
- blk_queue_start_drain(q);
-}
-EXPORT_SYMBOL_GPL(blk_set_queue_dying);
-
/**
* blk_cleanup_queue - shutdown a request queue
* @q: request queue to shutdown
@@ -308,7 +301,8 @@ void blk_cleanup_queue(struct request_queue *q)
WARN_ON_ONCE(blk_queue_registered(q));
/* mark @q DYING, no new request or merges will be allowed afterwards */
- blk_set_queue_dying(q);
+ blk_queue_flag_set(QUEUE_FLAG_DYING, q);
+ blk_queue_start_drain(q);
blk_queue_flag_set(QUEUE_FLAG_NOMERGES, q);
blk_queue_flag_set(QUEUE_FLAG_NOXMERGES, q);
diff --git a/block/genhd.c b/block/genhd.c
index 626c8406f21a..9eca1f7d35c9 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -548,6 +548,20 @@ int __must_check device_add_disk(struct device *parent, struct gendisk *disk,
}
EXPORT_SYMBOL(device_add_disk);
+/**
+ * blk_mark_disk_dead - mark a disk as dead
+ * @disk: disk to mark as dead
+ *
+ * Mark as disk as dead (e.g. surprise removed) and don't accept any new I/O
+ * to this disk.
+ */
+void blk_mark_disk_dead(struct gendisk *disk)
+{
+ set_bit(GD_DEAD, &disk->state);
+ blk_queue_start_drain(disk->queue);
+}
+EXPORT_SYMBOL_GPL(blk_mark_disk_dead);
+
/**
* del_gendisk - remove the gendisk
* @disk: the struct gendisk to remove
diff --git a/drivers/block/mtip32xx/mtip32xx.c b/drivers/block/mtip32xx/mtip32xx.c
index e6005c232328..2b588b62cbbb 100644
--- a/drivers/block/mtip32xx/mtip32xx.c
+++ b/drivers/block/mtip32xx/mtip32xx.c
@@ -4112,7 +4112,7 @@ static void mtip_pci_remove(struct pci_dev *pdev)
"Completion workers still active!\n");
}
- blk_set_queue_dying(dd->queue);
+ blk_mark_disk_dead(dd->disk);
set_bit(MTIP_DDF_REMOVE_PENDING_BIT, &dd->dd_flag);
/* Clean up the block layer. */
diff --git a/drivers/block/rbd.c b/drivers/block/rbd.c
index 4203cdab8abf..b844432bad20 100644
--- a/drivers/block/rbd.c
+++ b/drivers/block/rbd.c
@@ -7185,7 +7185,7 @@ static ssize_t do_rbd_remove(struct bus_type *bus,
* IO to complete/fail.
*/
blk_mq_freeze_queue(rbd_dev->disk->queue);
- blk_set_queue_dying(rbd_dev->disk->queue);
+ blk_mark_disk_dead(rbd_dev->disk);
}
del_gendisk(rbd_dev->disk);
diff --git a/drivers/block/xen-blkfront.c b/drivers/block/xen-blkfront.c
index ccd0dd0c6b83..ca71a0585333 100644
--- a/drivers/block/xen-blkfront.c
+++ b/drivers/block/xen-blkfront.c
@@ -2126,7 +2126,7 @@ static void blkfront_closing(struct blkfront_info *info)
/* No more blkif_request(). */
blk_mq_stop_hw_queues(info->rq);
- blk_set_queue_dying(info->rq);
+ blk_mark_disk_dead(info->gd);
set_capacity(info->gd, 0);
for_each_rinfo(info, rinfo, i) {
diff --git a/drivers/md/dm.c b/drivers/md/dm.c
index dcbd6d201619..997ace47bbd5 100644
--- a/drivers/md/dm.c
+++ b/drivers/md/dm.c
@@ -2077,7 +2077,7 @@ static void __dm_destroy(struct mapped_device *md, bool wait)
set_bit(DMF_FREEING, &md->flags);
spin_unlock(&_minor_lock);
- blk_set_queue_dying(md->queue);
+ blk_mark_disk_dead(md->disk);
/*
* Take suspend_lock so that presuspend and postsuspend methods
diff --git a/drivers/nvme/host/core.c b/drivers/nvme/host/core.c
index 79005ea1a33e..469f23186159 100644
--- a/drivers/nvme/host/core.c
+++ b/drivers/nvme/host/core.c
@@ -4574,7 +4574,7 @@ static void nvme_set_queue_dying(struct nvme_ns *ns)
if (test_and_set_bit(NVME_NS_DEAD, &ns->flags))
return;
- blk_set_queue_dying(ns->queue);
+ blk_mark_disk_dead(ns->disk);
nvme_start_ns_queue(ns);
set_capacity_and_notify(ns->disk, 0);
diff --git a/drivers/nvme/host/multipath.c b/drivers/nvme/host/multipath.c
index f8bf6606eb2f..ff775235534c 100644
--- a/drivers/nvme/host/multipath.c
+++ b/drivers/nvme/host/multipath.c
@@ -848,7 +848,7 @@ void nvme_mpath_remove_disk(struct nvme_ns_head *head)
{
if (!head->disk)
return;
- blk_set_queue_dying(head->disk->queue);
+ blk_mark_disk_dead(head->disk);
/* make sure all pending bios are cleaned up */
kblockd_schedule_work(&head->requeue_work);
flush_work(&head->requeue_work);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index f35aea98bc35..16b47035e4b0 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -748,7 +748,8 @@ extern bool blk_queue_can_use_dma_map_merging(struct request_queue *q,
bool __must_check blk_get_queue(struct request_queue *);
extern void blk_put_queue(struct request_queue *);
-extern void blk_set_queue_dying(struct request_queue *);
+
+void blk_mark_disk_dead(struct gendisk *disk);
#ifdef CONFIG_BLOCK
/*
]
|
| 190/2 |
2026/11/03 16:53 |
llm |
history-explorer |
3m
Model:
Tokens:
input: 38690
output: 25
thoughts: 1380
Thoughts: **Analyzing the Queue Freeze Lock and Related Context**
Alright, let's dive into this block layer code, specifically around the queue freeze mechanism and its interaction with lockdep. I need to be clear on what's going on here, especially given the history.
I'm starting by examining the commits `f6661b1d0525`, `6f491a8d4b92`, and `f1be1788a32e`. It appears these commits introduce and refine the handling of freeze/unfreeze operations for request queues, particularly concerning lockdep analysis. Initially, `blk_freeze_acquire_lock` and `blk_unfreeze_release_lock` were added to manage the locking when freezing and unfreezing a queue. These were introduced in conjunction with the concepts of `disk_dead` and `queue_dying`, which, if I understand correctly, are related to the state of the disk and queue respectively, for the purposes of lockdep.
The key change I'm tracking is in `f6661b1d0525` and `6f491a8d4b92`. The commit messages, as I understand them, are trying to assert that they are tracking the state "per-task". But, that's where things get interesting, because the code seems to indicate otherwise. My reading of the code reveals that the `mq_freeze_disk_dead` and `mq_freeze_queue_dying` flags are stored directly within the `struct request_queue`, not within `struct task_struct`, as the commit message suggests. Specifically, these flags are set within the `blk_freeze_set_owner` function, and are used when acquiring the lock to handle the `disk_dead` and `queue_dying` states of the queue.
When a freeze is started, `blk_freeze_set_owner` sets the `mq_freeze_owner` to the current task and increments `mq_freeze_owner_depth`. When unfreezing, `blk_unfreeze_check_owner` confirms the current task is the owner and decrements the depth. If the depth goes to zero, the owner is cleared. This is not per-task, rather, it seems that there is a single owner *for the request queue*.
I need to confirm all the users of `blk_freeze_acquire_lock` and `blk_unfreeze_release_lock` now, and trace them, because there seems to be a disconnect between the code's implementation and the commit message's description. There may be some critical implications to this that need to be addressed in how lockdep is being modeled here. The handling of those dead states within the freeze-unfreeze mechanism needs to be carefully scrutinized in context. I'm going to look at other call sites to see if this mismatch between the intended and actual variable scope is causing or has the potential to cause any issues with the lockdep analysis.
|
| 191/2 |
2026/11/03 16:56 |
tool |
grepper |
0m
Args: map[Expression:blk_(un)?freeze_(acquire|release)_lock]
Results: map[Output:block/blk-mq.c=182=void blk_freeze_queue_start(struct request_queue *q)
--
block/blk-mq.c-184- if (__blk_freeze_queue_start(q, current))
block/blk-mq.c:185: blk_freeze_acquire_lock(q);
block/blk-mq.c-186-}
--
block/blk-mq.c=230=void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
--
block/blk-mq.c-232- if (__blk_mq_unfreeze_queue(q, false))
block/blk-mq.c:233: blk_unfreeze_release_lock(q);
block/blk-mq.c-234-}
--
block/blk.h=778=void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
--
block/blk.h-780-#ifdef CONFIG_LOCKDEP
block/blk.h:781:static inline void blk_freeze_acquire_lock(struct request_queue *q)
block/blk.h-782-{
--
block/blk.h-788-
block/blk.h:789:static inline void blk_unfreeze_release_lock(struct request_queue *q)
block/blk.h-790-{
--
block/blk.h-796-#else
block/blk.h:797:static inline void blk_freeze_acquire_lock(struct request_queue *q)
block/blk.h-798-{
block/blk.h-799-}
block/blk.h:800:static inline void blk_unfreeze_release_lock(struct request_queue *q)
block/blk.h-801-{
--
block/genhd.c=697=static void __del_gendisk(struct gendisk *disk)
--
block/genhd.c-731- if (start_drain)
block/genhd.c:732: blk_freeze_acquire_lock(q);
block/genhd.c-733- xa_for_each_start(&disk->part_tbl, idx, part, 1)
--
block/genhd.c-780- if (start_drain)
block/genhd.c:781: blk_unfreeze_release_lock(q);
block/genhd.c-782-}
]
|
| 192/2 |
2026/11/03 16:56 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 41364
output: 36
thoughts: 72
Thoughts: Here's my summary, as though I'm thinking through this process:
**Diving into Block Device Freezing in blk-mq.c**
Okay, time to get a grip on how this block device freezing mechanism works in the context of `blk-mq`. I'm starting by zeroing in on those crucial functions: `__blk_freeze_queue_start`, `blk_mq_freeze_queue`, and related definitions. I need to understand the control flow here, so I'm heading directly to the source. Let's start with a focused read of lines 110 through 250 of `block/blk-mq.c`. That should give me a good initial picture of the core logic and any related data structures involved in initiating and managing the queue freezing process. Hopefully this will make it clearer how this fits into the overall `blk-mq` architecture.
|
| 193/2 |
2026/11/03 16:57 |
tool |
read-file |
0m
Args: map[File:block/blk-mq.c FirstLine:115 LineCount:100]
Results: map[Contents: 115: #ifdef CONFIG_LOCKDEP
116: static bool blk_freeze_set_owner(struct request_queue *q,
117: struct task_struct *owner)
118: {
119: if (!owner)
120: return false;
121:
122: if (!q->mq_freeze_depth) {
123: q->mq_freeze_owner = owner;
124: q->mq_freeze_owner_depth = 1;
125: q->mq_freeze_disk_dead = !q->disk ||
126: test_bit(GD_DEAD, &q->disk->state) ||
127: !blk_queue_registered(q);
128: q->mq_freeze_queue_dying = blk_queue_dying(q);
129: return true;
130: }
131:
132: if (owner == q->mq_freeze_owner)
133: q->mq_freeze_owner_depth += 1;
134: return false;
135: }
136:
137: /* verify the last unfreeze in owner context */
138: static bool blk_unfreeze_check_owner(struct request_queue *q)
139: {
140: if (q->mq_freeze_owner != current)
141: return false;
142: if (--q->mq_freeze_owner_depth == 0) {
143: q->mq_freeze_owner = NULL;
144: return true;
145: }
146: return false;
147: }
148:
149: #else
150:
151: static bool blk_freeze_set_owner(struct request_queue *q,
152: struct task_struct *owner)
153: {
154: return false;
155: }
156:
157: static bool blk_unfreeze_check_owner(struct request_queue *q)
158: {
159: return false;
160: }
161: #endif
162:
163: bool __blk_freeze_queue_start(struct request_queue *q,
164: struct task_struct *owner)
165: {
166: bool freeze;
167:
168: mutex_lock(&q->mq_freeze_lock);
169: freeze = blk_freeze_set_owner(q, owner);
170: if (++q->mq_freeze_depth == 1) {
171: percpu_ref_kill(&q->q_usage_counter);
172: mutex_unlock(&q->mq_freeze_lock);
173: if (queue_is_mq(q))
174: blk_mq_run_hw_queues(q, false);
175: } else {
176: mutex_unlock(&q->mq_freeze_lock);
177: }
178:
179: return freeze;
180: }
181:
182: void blk_freeze_queue_start(struct request_queue *q)
183: {
184: if (__blk_freeze_queue_start(q, current))
185: blk_freeze_acquire_lock(q);
186: }
187: EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
188:
189: void blk_mq_freeze_queue_wait(struct request_queue *q)
190: {
191: wait_event(q->mq_freeze_wq, percpu_ref_is_zero(&q->q_usage_counter));
192: }
193: EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait);
194:
195: int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
196: unsigned long timeout)
197: {
198: return wait_event_timeout(q->mq_freeze_wq,
199: percpu_ref_is_zero(&q->q_usage_counter),
200: timeout);
201: }
202: EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait_timeout);
203:
204: void blk_mq_freeze_queue_nomemsave(struct request_queue *q)
205: {
206: blk_freeze_queue_start(q);
207: blk_mq_freeze_queue_wait(q);
208: }
209: EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_nomemsave);
210:
211: bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
212: {
213: bool unfreeze;
214:
]
|
| 194/2 |
2026/11/03 16:57 |
llm |
history-explorer |
3m
Model:
Tokens:
input: 43118
output: 35
thoughts: 24
Thoughts: Okay, here's my interpretation of what's going through my mind as I approach this code section, tailored for an expert audience:
**Analyzing blk-mq.c: Lines 212-270**
Alright, let's dive into this specific section of `blk-mq.c`, lines 212 to 270. Immediately, I'm going to start with a goal: understand the flow, the conditional logic, and the core data structures touched within this block. Knowing the context of `blk-mq.c` is important; I suspect this is handling a core aspect of the multiqueue block layer, likely submission, completion, or perhaps some form of request queuing or dispatching, and I'm ready to figure out the specifics.
I'll be looking for key function calls here; I'm expecting calls to related functions in this area, like ones involving request allocation (`blk_mq_alloc_request`), submission (`blk_mq_submit_request`), completion (`blk_mq_complete_request`), or perhaps even something related to interrupt handling. I'll need to see how the code handles error paths or edge cases, maybe there are special considerations for handling I/O errors or timeouts.
I'm ready to quickly scan the code for common patterns: spinlocks, mutexes, atomic operations, any of those primitives I already know are critical for concurrency in the block layer, given the multiqueue architecture. I'll be alert for any subtle data races or locking issues. I also expect to find a lot of `struct blk_mq_hw_ctx` and `struct blk_mq_queue_data` references; these are the core data structures in the multiqueue world, so seeing how they're used will give me a huge amount of insight. If I see a lot of bitwise operations or pointer arithmetic, I'll be immediately be thinking about optimizations and memory layout. Finally, I'll be mentally parsing the control flow, ready to trace exactly where a request will flow when submitted, how it's handled, and where it ultimately ends up after completion. Let's see what we've got!
|
| 195/2 |
2026/11/03 17:00 |
tool |
read-file |
0m
Args: map[File:block/blk-mq.c FirstLine:212 LineCount:60]
Results: map[Contents: 212: {
213: bool unfreeze;
214:
215: mutex_lock(&q->mq_freeze_lock);
216: if (force_atomic)
217: q->q_usage_counter.data->force_atomic = true;
218: q->mq_freeze_depth--;
219: WARN_ON_ONCE(q->mq_freeze_depth < 0);
220: if (!q->mq_freeze_depth) {
221: percpu_ref_resurrect(&q->q_usage_counter);
222: wake_up_all(&q->mq_freeze_wq);
223: }
224: unfreeze = blk_unfreeze_check_owner(q);
225: mutex_unlock(&q->mq_freeze_lock);
226:
227: return unfreeze;
228: }
229:
230: void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
231: {
232: if (__blk_mq_unfreeze_queue(q, false))
233: blk_unfreeze_release_lock(q);
234: }
235: EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_nomemrestore);
236:
237: /*
238: * non_owner variant of blk_freeze_queue_start
239: *
240: * Unlike blk_freeze_queue_start, the queue doesn't need to be unfrozen
241: * by the same task. This is fragile and should not be used if at all
242: * possible.
243: */
244: void blk_freeze_queue_start_non_owner(struct request_queue *q)
245: {
246: __blk_freeze_queue_start(q, NULL);
247: }
248: EXPORT_SYMBOL_GPL(blk_freeze_queue_start_non_owner);
249:
250: /* non_owner variant of blk_mq_unfreeze_queue */
251: void blk_mq_unfreeze_queue_non_owner(struct request_queue *q)
252: {
253: __blk_mq_unfreeze_queue(q, false);
254: }
255: EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_non_owner);
256:
257: /*
258: * FIXME: replace the scsi_internal_device_*block_nowait() calls in the
259: * mpt3sas driver such that this function can be removed.
260: */
261: void blk_mq_quiesce_queue_nowait(struct request_queue *q)
262: {
263: unsigned long flags;
264:
265: spin_lock_irqsave(&q->queue_lock, flags);
266: if (!q->quiesce_depth++)
267: blk_queue_flag_set(QUEUE_FLAG_QUIESCED, q);
268: spin_unlock_irqrestore(&q->queue_lock, flags);
269: }
270: EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue_nowait);
271:
]
|
| 196/2 |
2026/11/03 17:01 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 44613
output: 39
thoughts: 41
Thoughts: Okay, let's dive into this. Here's my take on those thoughts, as if they're my own:
**Investigating Block Layer Queue Freezing**
Right, let's see... I need to understand how the block layer's queue freezing mechanisms work. Specifically, I'm thinking about how `blk_mq_freeze_queue` and `blk_mq_unfreeze_queue` are implemented. I'm going to jump into `include/linux/blk-mq.h` to see the definitions. Knowing those is key to understanding how we can pause and resume I/O. I'm particularly interested in the intricacies of how this interacts with the multi-queue architecture. Knowing this will give me a solid base on which to reason about the implications of suspending and resuming the block device.
|
| 197/2 |
2026/11/03 17:02 |
tool |
grepper |
0m
Args: map[Expression:blk_mq_(un)?freeze_queue PathPrefixes:[include/linux/blk-mq.h]]
Results: map[Output:include/linux/blk-mq.h=951=void blk_mq_tagset_wait_completed_request(struct blk_mq_tag_set *tagset);
include/linux/blk-mq.h:952:void blk_mq_freeze_queue_nomemsave(struct request_queue *q);
include/linux/blk-mq.h:953:void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q);
include/linux/blk-mq.h-954-static inline unsigned int __must_check
include/linux/blk-mq.h:955:blk_mq_freeze_queue(struct request_queue *q)
include/linux/blk-mq.h-956-{
--
include/linux/blk-mq.h-958-
include/linux/blk-mq.h:959: blk_mq_freeze_queue_nomemsave(q);
include/linux/blk-mq.h-960- return memflags;
--
include/linux/blk-mq.h=962=static inline void
include/linux/blk-mq.h:963:blk_mq_unfreeze_queue(struct request_queue *q, unsigned int memflags)
include/linux/blk-mq.h-964-{
include/linux/blk-mq.h:965: blk_mq_unfreeze_queue_nomemrestore(q);
include/linux/blk-mq.h-966- memalloc_noio_restore(memflags);
--
include/linux/blk-mq.h=968=void blk_freeze_queue_start(struct request_queue *q);
include/linux/blk-mq.h:969:void blk_mq_freeze_queue_wait(struct request_queue *q);
include/linux/blk-mq.h:970:int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
include/linux/blk-mq.h-971- unsigned long timeout);
include/linux/blk-mq.h:972:void blk_mq_unfreeze_queue_non_owner(struct request_queue *q);
include/linux/blk-mq.h-973-void blk_freeze_queue_start_non_owner(struct request_queue *q);
]
|
| 198/2 |
2026/11/03 17:02 |
llm |
history-explorer |
4m
Model:
Tokens:
input: 45455
output: 38
thoughts: 67
Thoughts: Here's my analysis of what you're asking me to think about, presented as if it were my own thought process:
**Diving into Block Device Shutdown: `blk_queue_start_drain` and Disk Deletion**
Okay, so we're talking about the critical path of shutting down a block device, and the interesting bit is how we ensure that no further I/O gets issued to a device we're about to mark as dead or remove. My focus is going to be on the interplay between `blk_queue_start_drain`, found in `block/blk-core.c`, and the actions triggered by `del_gendisk` and `blk_mark_disk_dead`. The core concern is atomicity β we need a reliable mechanism to prevent any new I/O requests from sneaking in *after* we've initiated the device removal process.
First up, let's dissect `blk_queue_start_drain` in `block/blk-core.c`. This function is the key to halting I/O, so I want to know exactly how it works. I need to understand its mechanics regarding the internal state of the request queue and how it affects the flow of requests. Are we using a simple "drain" flag? Does it employ any sophisticated mechanisms like a counting semaphore or a more complex synchronization primitive? I need to get the precise details of that function. Then I'll be looking to understand the interplay between the "drain" action and `del_gendisk` / `blk_mark_disk_dead`. I expect there's some carefully crafted logic to make sure that the I/O queue is truly empty and all active requests are completed before we unregister or mark the disk as dead. I'm going to follow the logic through those functions, especially around the transitions in and out of the "drain" state. I need to be sure that the locking is correct to protect against race conditions and that there are no gaps where new requests could be introduced, leading to data corruption or crashes.
|
| 199/2 |
2026/11/03 17:06 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/blk-core.c Name:blk_queue_start_drain]
Results: map[SourceCode: 327: bool blk_queue_start_drain(struct request_queue *q)
328: {
329: /*
330: * When queue DYING flag is set, we need to block new req
331: * entering queue, so we call blk_freeze_queue_start() to
332: * prevent I/O from crossing blk_queue_enter().
333: */
334: bool freeze = __blk_freeze_queue_start(q, current);
335: if (queue_is_mq(q))
336: blk_mq_wake_waiters(q);
337: /* Make blk_queue_enter() reexamine the DYING flag. */
338: wake_up_all(&q->mq_freeze_wq);
339:
340: return freeze;
341: }
SourceFile:block/blk-core.c]
|
| 200/2 |
2026/11/03 17:06 |
llm |
history-explorer |
3m
Model:
Tokens:
input: 46259
output: 37
thoughts: 35
Thoughts: Here's a summary of my thought process:
**Diving into Block Device Handling**
Okay, so I'm thinking about how the kernel handles a disk going dead, and I'm really curious about how it marks the device as unusable. Let's delve into the `block/genhd.c` file. I need to understand the mechanics here, so I'm going to focus on those functions that handle the marking of a device as 'dead'. Specifically, I'm going to examine `__blk_mark_disk_dead` and `blk_mark_disk_dead`. The differences between those functions are likely subtle, so this will be an exercise in understanding the subtleties of error handling.
|
| 201/2 |
2026/11/03 17:09 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/genhd.c Name:blk_mark_disk_dead]
Results: map[SourceCode: 682: /**
683: * blk_mark_disk_dead - mark a disk as dead
684: * @disk: disk to mark as dead
685: *
686: * Mark as disk as dead (e.g. surprise removed) and don't accept any new I/O
687: * to this disk.
688: */
689: void blk_mark_disk_dead(struct gendisk *disk)
690: {
691: blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
692: __blk_mark_disk_dead(disk);
693: blk_report_disk_dead(disk, true);
694: }
SourceFile:block/genhd.c]
|
| 202/2 |
2026/11/03 17:09 |
llm |
history-explorer |
8m
Model:
Tokens:
input: 46716
output: 38
thoughts: 14
Thoughts: Okay, here's my interpretation of what's going on, framed as my own thoughts, assuming I'm already deep in the weeds of kernel disk I/O, and you, the user, are right there with me:
**Diving into `__blk_mark_disk_dead`**
Alright, let's get into this `__blk_mark_disk_dead` function. I see this function as the kernel's way of formally declaring a disk as, well, *dead*. This isn't just a casual "oops, looks like that drive has a hiccup" kind of thing. This is the point of no return, the nuclear option for a failing disk. This function is called when a disk has demonstrably failed and the system can't trust it anymore. I'm thinking, "what are the implications of marking a disk as dead?" We are talking about data integrity first and foremost.
Now, I need to understand what this function actually *does*. It's likely updating some crucial data structures within the kernel. It would be checking if it can still operate the disk and set some flag somewhere to indicate its death, like a death certificate for the disk. It's probably setting a flag on the `disk` structure, maybe in a field like `disk->flags`, to indicate this terminal state. The filesystem layer, and any other process that is responsible for communication with the disk would look for this flag and know not to interact with it.
I bet it also takes some actions to prevent further operations on that disk. This could involve, invalidating the I/O queues associated with the dead disk, or perhaps immediately starting to issue the I/O requests that are sitting on the queue to other disks, which in a modern storage environment, could be a mirror. It would stop the block layer from queuing further requests, and could potentially kick off any error handling or failover procedures. I'm wondering if it also initiates the logging of a specific error message to the system log, something very explicit like "Disk /dev/sdX marked dead, data integrity compromised."
I bet there's error reporting at play too. It would be interesting to see if any statistics are updated at this point. For example, counters for disk failures, errors, or possibly other counters that point to the cause of the issue.
Ultimately, this is about damage control. Marking a disk as dead isn't a *solution*; it's a *response*. It's a kernel's way of saying, "We can't rely on this device anymore, and we need to minimize the damage to the rest of the system and prevent data corruption." It's a crucial step in maintaining overall system stability and data integrity when dealing with a hardware failure.
|
| 203/2 |
2026/11/03 17:18 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/genhd.c Name:__blk_mark_disk_dead]
Results: map[SourceCode: 660: static bool __blk_mark_disk_dead(struct gendisk *disk)
661: {
662: /*
663: * Fail any new I/O.
664: */
665: if (test_and_set_bit(GD_DEAD, &disk->state))
666: return false;
667:
668: if (test_bit(GD_OWNS_QUEUE, &disk->state))
669: blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
670:
671: /*
672: * Stop buffered writers from dirtying pages that can't be written out.
673: */
674: set_capacity(disk, 0);
675:
676: /*
677: * Prevent new I/O from crossing bio_queue_enter().
678: */
679: return blk_queue_start_drain(disk->queue);
680: }
SourceFile:block/genhd.c]
|
| 204/2 |
2026/11/03 17:18 |
llm |
history-explorer |
4m
Model:
Tokens:
input: 47667
output: 37
thoughts: 1671
Thoughts: **Analysis of Potential Lockdep Issues in Block Layer Queue Freezing**
Okay, let's break this down. My initial thought process is centered around how `blk_mark_disk_dead` interacts with the block queue freezing/unfreezing mechanisms, and how it relates to lockdep.
First, I see that `blk_mark_disk_dead` calls `__blk_mark_disk_dead`, which eventually calls `blk_queue_start_drain` and, crucially, `__blk_freeze_queue_start`. I immediately notice something: `blk_mark_disk_dead` *doesn't* acquire a lock using `blk_freeze_acquire_lock()`. However, `__blk_freeze_queue_start` *does* call `blk_freeze_set_owner()`, and this sets up the freeze! If `q->mq_freeze_depth` is initially zero, then the calling thread becomes the owner and the depth gets bumped, along with flags. More importantly, I now see that `blk_mark_disk_dead` never unfreezes the queue. It permanently starts the draining process by incrementing the depth.
Then I look at `del_gendisk`. I see that it checks to see if the disk has been marked dead. If so, it acquires the lock *after* the dead mark, and releases it *after* the partition work. Ok, I understand. *Here* is where the lock acquisition and release *should* have happened if `start_drain` returns true.
The issue then crystallizes: `blk_mark_disk_dead` *doesn't* return any value, so it is impossible to protect the lockdep lock in the same way. The fact that the return value from `__blk_mark_disk_dead(disk)` is ignored is a red flag. It is simply starting a permanent drain, and it doesn't care.
Then I delve into the freezing/unfreezing calls. Let's look at `__blk_mq_unfreeze_queue`. It decrements `q->mq_freeze_depth`, and, if depth hits zero, wakes up any waiters. Okay, standard unfreeze. `blk_mq_unfreeze_queue_nomemrestore` calls `__blk_mq_unfreeze_queue` and *then* does the release, if necessary.
The core problem, now, is revealed with a multi-threaded scenario. Iβm thinking about a scenario where thread 1 calls `elevator_change` which calls `blk_mq_freeze_queue`. The queue is frozen, `q->mq_freeze_depth` is incremented to 1, and the lock is acquired. Later, thread 1 calls `blk_mq_unfreeze_queue`, decrements the depth, and releases the lock. Seems fine.
But now, before thread 1 can actually release the lock, thread 2 calls `blk_mark_disk_dead`. Thread 2 calls `__blk_freeze_queue_start`. Thread 2 acquires `q->mq_freeze_lock`. Since the depth is 0, thread 2 sets `q->mq_freeze_owner` to itself, increments the depth, and sets `q->mq_freeze_queue_dying = true` which is what sets the critical flag, and then it unlocks.
Now Thread 1 calls `blk_unfreeze_release_lock(q)`. It checks `q->mq_freeze_queue_dying`. Thread 2 has set that to true! The result? Thread 1 *doesn't* release the acquired lock! We have a potential lockdep violation here.
So the problem is that `blk_mark_disk_dead` permanently freezes the queue and updates the flags *without* acquiring the lock, and without having been called with the lock, so it does not participate in proper locking protocol. The unfreezing code will never think the lock is "free", because `q->mq_freeze_queue_dying` is set.
I need to now go back and check other commits, and search the git history. Let's see if there have been any commits touching `blk-mq.c` or `blk.h` with the terms `freeze` or `lockdep` to see if this has been addressed, or if any related bugs have already been found. Time to run a `git log` with CodeRegexp!
|
| 205/2 |
2026/11/03 17:22 |
tool |
git-log |
4m
Args: map[CodeRegexp:blk_unfreeze_check_owner Count:10 Since:3 years]
Results: map[Output:6a78699838a0 block: always verify unfreeze lock on the owner task
]
|
| 206/2 |
2026/11/03 17:27 |
llm |
history-explorer |
4m
Model:
Tokens:
input: 50355
output: 33
thoughts: 214
Thoughts: Okay, let me think this through. As an expert in this area, my initial concern is about potential lock contention issues related to `blk_unfreeze_release_lock` and `blk_freeze_acquire_lock`. I need to ensure the changes are safe in the broader context of the block layer.
**Investigating Potential Lock Contention**
My primary objective is to review recent commits that might interact with the aforementioned lock mechanisms. Let's see...I've got a preliminary list of relevant commits:
* `f6661b1d0525`: This commit is interesting because it introduces automatic tracking of queue dying state. This hints at changes related to lock dependency modeling.
* `b9d4eee7e04b`: This one removes the manual verification of queue freeze. Could be related.
* `6f491a8d4b92`: Similar to the first, it automatically tracks the disk DEAD state. Again, probably lockdep related.
* `357e1b7f730b`: This one avoids IO lock verification for the freeze/unfreeze operations within elevator\_init\_mq().
* `f1be1788a32e`: This one models freeze operations as a lock, which is important for supporting lockdep.
Based on this, my next step is a targeted search. I need to be absolutely certain that no recent commits introduce scenarios where a lock is held when returning to user space. That's a classic source of problems. I'll search for commits within the last three years, using regular expressions such as `lock held when returning to user space` or simply `lock held` to catch potential regressions. This will give me a better understanding of the wider landscape.
|
| 207/2 |
2026/11/03 17:31 |
tool |
git-log |
0m
Args: map[Count:20 MessageRegexps:[lock held when returning] Since:3 years]
Results: map[Output:d42032c0fe3c mm/hugetlb: don't clear the resv_map of a VMA whose lock is held
17a4fde81d3a afs: Fix merge preference rule failure condition
9b234a97b10c rtnetlink: fix rtnl_dump_ifinfo() error path
]
|
| 208/2 |
2026/11/03 17:31 |
llm |
history-explorer |
4m
Model:
Tokens:
input: 51077
output: 41
thoughts: 35
Thoughts: Okay, here's my interpretation of those thoughts, presented as a first-person expert summary:
**Analyzing Block Layer Concurrency and Usage**
Alright, let's dive in. I need to get a handle on the current state of lock usage and resource management within the block layer. My initial focus will be on identifying relevant commit messages. Specifically, I'm going to search through the commit history for mentions of the legacy `q_lockdep_map` and `io_lockdep_map` lockdep maps. These structures are key for understanding how we're enforcing locking rules around the request queue. They're part of the older locking strategy, so finding commits that touch them would provide a good baseline for changes. Also, I'll be looking for any references to `q_usage_counter`. This would indicate where the block layer tracks usage of request queues. These counters are often closely tied to resource management and could expose interesting interactions with locking that I need to be aware of. Looking for these terms will give me a quick scan of significant code changes related to these core locking strategies in the block layer, and provide direction to recent design decisions.
|
| 209/2 |
2026/11/03 17:36 |
tool |
git-log |
0m
Args: map[Count:20 MessageRegexps:[lockdep_map] PathPrefix:block/ Since:3 years]
Results: map[Output:ffa1e7ada456 block: Make request_queue lockdep splats show up earlier
357e1b7f730b block: don't verify IO lock for freeze/unfreeze in elevator_init_mq()
]
|
| 210/2 |
2026/11/03 17:36 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 51461
output: 50
thoughts: 30
Thoughts: Okay, here's my interpretation of what's going on, formatted as you requested:
**Analyzing Commits `ffa1e7ada456` and `357e1b7f730b`**
Alright, let's dive in. I need to get a handle on the changes introduced by commits `ffa1e7ada456` and `357e1b7f730b`. My initial thought process is to quickly parse these two commits and understand their scope and how they relate to the existing code base. I'll need to use my expertise to quickly identify any potential conflicts or areas of risk by examining the file diffs. I'm especially interested in the core modules that I manage because I will need to understand if these commits would have any side-effects on the systems that I am responsible for. Iβll be looking for changes in data structures, algorithms, dependencies, or anything that could impact performance, security, or stability. I'll likely mentally construct a dependency graph if needed. Furthermore, I'll be looking at the commit messages themselves; any context the developers provided is invaluable. The goal is to rapidly determine the impact of these changes, prioritize further review if necessary, and ensure a smooth integration or maintainability. I will also be looking to see if these commits are related to existing issues.
|
| 211/2 |
2026/11/03 17:37 |
tool |
git-show |
0m
Args:
Results: map[Output:commit ffa1e7ada456087c2402b37cd6b2863ced29aff0
Author: Thomas HellstrΓΆm <thomas.hellstrom@linux.intel.com>
Date: Tue Mar 18 10:55:48 2025 +0100
block: Make request_queue lockdep splats show up earlier
In recent kernels, there are lockdep splats around the
struct request_queue::io_lockdep_map, similar to [1], but they
typically don't show up until reclaim with writeback happens.
Having multiple kernel versions released with a known risc of kernel
deadlock during reclaim writeback should IMHO be addressed and
backported to -stable with the highest priority.
In order to have these lockdep splats show up earlier,
preferrably during system initialization, prime the
struct request_queue::io_lockdep_map as GFP_KERNEL reclaim-
tainted. This will instead lead to lockdep splats looking similar
to [2], but without the need for reclaim + writeback
happening.
[1]:
[ 189.762244] ======================================================
[ 189.762432] WARNING: possible circular locking dependency detected
[ 189.762441] 6.14.0-rc6-xe+ #6 Tainted: G U
[ 189.762450] ------------------------------------------------------
[ 189.762459] kswapd0/119 is trying to acquire lock:
[ 189.762467] ffff888110ceb710 (&q->q_usage_counter(io)#26){++++}-{0:0}, at: __submit_bio+0x76/0x230
[ 189.762485]
but task is already holding lock:
[ 189.762494] ffffffff834c97c0 (fs_reclaim){+.+.}-{0:0}, at: balance_pgdat+0xbe/0xb00
[ 189.762507]
which lock already depends on the new lock.
[ 189.762519]
the existing dependency chain (in reverse order) is:
[ 189.762529]
-> #2 (fs_reclaim){+.+.}-{0:0}:
[ 189.762540] fs_reclaim_acquire+0xc5/0x100
[ 189.762548] kmem_cache_alloc_lru_noprof+0x4a/0x480
[ 189.762558] alloc_inode+0xaa/0xe0
[ 189.762566] iget_locked+0x157/0x330
[ 189.762573] kernfs_get_inode+0x1b/0x110
[ 189.762582] kernfs_get_tree+0x1b0/0x2e0
[ 189.762590] sysfs_get_tree+0x1f/0x60
[ 189.762597] vfs_get_tree+0x2a/0xf0
[ 189.762605] path_mount+0x4cd/0xc00
[ 189.762613] __x64_sys_mount+0x119/0x150
[ 189.762621] x64_sys_call+0x14f2/0x2310
[ 189.762630] do_syscall_64+0x91/0x180
[ 189.762637] entry_SYSCALL_64_after_hwframe+0x76/0x7e
[ 189.762647]
-> #1 (&root->kernfs_rwsem){++++}-{3:3}:
[ 189.762659] down_write+0x3e/0xf0
[ 189.762667] kernfs_remove+0x32/0x60
[ 189.762676] sysfs_remove_dir+0x4f/0x60
[ 189.762685] __kobject_del+0x33/0xa0
[ 189.762709] kobject_del+0x13/0x30
[ 189.762716] elv_unregister_queue+0x52/0x80
[ 189.762725] elevator_switch+0x68/0x360
[ 189.762733] elv_iosched_store+0x14b/0x1b0
[ 189.762756] queue_attr_store+0x181/0x1e0
[ 189.762765] sysfs_kf_write+0x49/0x80
[ 189.762773] kernfs_fop_write_iter+0x17d/0x250
[ 189.762781] vfs_write+0x281/0x540
[ 189.762790] ksys_write+0x72/0xf0
[ 189.762798] __x64_sys_write+0x19/0x30
[ 189.762807] x64_sys_call+0x2a3/0x2310
[ 189.762815] do_syscall_64+0x91/0x180
[ 189.762823] entry_SYSCALL_64_after_hwframe+0x76/0x7e
[ 189.762833]
-> #0 (&q->q_usage_counter(io)#26){++++}-{0:0}:
[ 189.762845] __lock_acquire+0x1525/0x2760
[ 189.762854] lock_acquire+0xca/0x310
[ 189.762861] blk_mq_submit_bio+0x8a2/0xba0
[ 189.762870] __submit_bio+0x76/0x230
[ 189.762878] submit_bio_noacct_nocheck+0x323/0x430
[ 189.762888] submit_bio_noacct+0x2cc/0x620
[ 189.762896] submit_bio+0x38/0x110
[ 189.762904] __swap_writepage+0xf5/0x380
[ 189.762912] swap_writepage+0x3c7/0x600
[ 189.762920] shmem_writepage+0x3da/0x4f0
[ 189.762929] pageout+0x13f/0x310
[ 189.762937] shrink_folio_list+0x61c/0xf60
[ 189.763261] evict_folios+0x378/0xcd0
[ 189.763584] try_to_shrink_lruvec+0x1b0/0x360
[ 189.763946] shrink_one+0x10e/0x200
[ 189.764266] shrink_node+0xc02/0x1490
[ 189.764586] balance_pgdat+0x563/0xb00
[ 189.764934] kswapd+0x1e8/0x430
[ 189.765249] kthread+0x10b/0x260
[ 189.765559] ret_from_fork+0x44/0x70
[ 189.765889] ret_from_fork_asm+0x1a/0x30
[ 189.766198]
other info that might help us debug this:
[ 189.767089] Chain exists of:
&q->q_usage_counter(io)#26 --> &root->kernfs_rwsem --> fs_reclaim
[ 189.767971] Possible unsafe locking scenario:
[ 189.768555] CPU0 CPU1
[ 189.768849] ---- ----
[ 189.769136] lock(fs_reclaim);
[ 189.769421] lock(&root->kernfs_rwsem);
[ 189.769714] lock(fs_reclaim);
[ 189.770016] rlock(&q->q_usage_counter(io)#26);
[ 189.770305]
*** DEADLOCK ***
[ 189.771167] 1 lock held by kswapd0/119:
[ 189.771453] #0: ffffffff834c97c0 (fs_reclaim){+.+.}-{0:0}, at: balance_pgdat+0xbe/0xb00
[ 189.771770]
stack backtrace:
[ 189.772351] CPU: 4 UID: 0 PID: 119 Comm: kswapd0 Tainted: G U 6.14.0-rc6-xe+ #6
[ 189.772353] Tainted: [U]=USER
[ 189.772354] Hardware name: ASUS System Product Name/PRIME B560M-A AC, BIOS 2001 02/01/2023
[ 189.772354] Call Trace:
[ 189.772355] <TASK>
[ 189.772356] dump_stack_lvl+0x6e/0xa0
[ 189.772359] dump_stack+0x10/0x18
[ 189.772360] print_circular_bug.cold+0x17a/0x1b7
[ 189.772363] check_noncircular+0x13a/0x150
[ 189.772365] ? __pfx_stack_trace_consume_entry+0x10/0x10
[ 189.772368] __lock_acquire+0x1525/0x2760
[ 189.772368] ? ret_from_fork_asm+0x1a/0x30
[ 189.772371] lock_acquire+0xca/0x310
[ 189.772372] ? __submit_bio+0x76/0x230
[ 189.772375] ? lock_release+0xd5/0x2c0
[ 189.772376] blk_mq_submit_bio+0x8a2/0xba0
[ 189.772378] ? __submit_bio+0x76/0x230
[ 189.772380] __submit_bio+0x76/0x230
[ 189.772382] ? trace_hardirqs_on+0x1e/0xe0
[ 189.772384] submit_bio_noacct_nocheck+0x323/0x430
[ 189.772386] ? submit_bio_noacct_nocheck+0x323/0x430
[ 189.772387] ? __might_sleep+0x58/0xa0
[ 189.772390] submit_bio_noacct+0x2cc/0x620
[ 189.772391] ? count_memcg_events+0x68/0x90
[ 189.772393] submit_bio+0x38/0x110
[ 189.772395] __swap_writepage+0xf5/0x380
[ 189.772396] swap_writepage+0x3c7/0x600
[ 189.772397] shmem_writepage+0x3da/0x4f0
[ 189.772401] pageout+0x13f/0x310
[ 189.772406] shrink_folio_list+0x61c/0xf60
[ 189.772409] ? isolate_folios+0xe80/0x16b0
[ 189.772410] ? mark_held_locks+0x46/0x90
[ 189.772412] evict_folios+0x378/0xcd0
[ 189.772414] ? evict_folios+0x34a/0xcd0
[ 189.772415] ? lock_is_held_type+0xa3/0x130
[ 189.772417] try_to_shrink_lruvec+0x1b0/0x360
[ 189.772420] shrink_one+0x10e/0x200
[ 189.772421] shrink_node+0xc02/0x1490
[ 189.772423] ? shrink_node+0xa08/0x1490
[ 189.772424] ? shrink_node+0xbd8/0x1490
[ 189.772425] ? mem_cgroup_iter+0x366/0x480
[ 189.772427] balance_pgdat+0x563/0xb00
[ 189.772428] ? balance_pgdat+0x563/0xb00
[ 189.772430] ? trace_hardirqs_on+0x1e/0xe0
[ 189.772431] ? finish_task_switch.isra.0+0xcb/0x330
[ 189.772433] ? __switch_to_asm+0x33/0x70
[ 189.772437] kswapd+0x1e8/0x430
[ 189.772438] ? __pfx_autoremove_wake_function+0x10/0x10
[ 189.772440] ? __pfx_kswapd+0x10/0x10
[ 189.772441] kthread+0x10b/0x260
[ 189.772443] ? __pfx_kthread+0x10/0x10
[ 189.772444] ret_from_fork+0x44/0x70
[ 189.772446] ? __pfx_kthread+0x10/0x10
[ 189.772447] ret_from_fork_asm+0x1a/0x30
[ 189.772450] </TASK>
[2]:
[ 8.760253] ======================================================
[ 8.760254] WARNING: possible circular locking dependency detected
[ 8.760255] 6.14.0-rc6-xe+ #7 Tainted: G U
[ 8.760256] ------------------------------------------------------
[ 8.760257] (udev-worker)/674 is trying to acquire lock:
[ 8.760259] ffff888100e39148 (&root->kernfs_rwsem){++++}-{3:3}, at: kernfs_remove+0x32/0x60
[ 8.760265]
but task is already holding lock:
[ 8.760266] ffff888110dc7680 (&q->q_usage_counter(io)#27){++++}-{0:0}, at: blk_mq_freeze_queue_nomemsave+0x12/0x30
[ 8.760272]
which lock already depends on the new lock.
[ 8.760272]
the existing dependency chain (in reverse order) is:
[ 8.760273]
-> #2 (&q->q_usage_counter(io)#27){++++}-{0:0}:
[ 8.760276] blk_alloc_queue+0x30a/0x350
[ 8.760279] blk_mq_alloc_queue+0x6b/0xe0
[ 8.760281] scsi_alloc_sdev+0x276/0x3c0
[ 8.760284] scsi_probe_and_add_lun+0x22a/0x440
[ 8.760286] __scsi_scan_target+0x109/0x230
[ 8.760288] scsi_scan_channel+0x65/0xc0
[ 8.760290] scsi_scan_host_selected+0xff/0x140
[ 8.760292] do_scsi_scan_host+0xa7/0xc0
[ 8.760293] do_scan_async+0x1c/0x160
[ 8.760295] async_run_entry_fn+0x32/0x150
[ 8.760299] process_one_work+0x224/0x5f0
[ 8.760302] worker_thread+0x1d4/0x3e0
[ 8.760304] kthread+0x10b/0x260
[ 8.760306] ret_from_fork+0x44/0x70
[ 8.760309] ret_from_fork_asm+0x1a/0x30
[ 8.760312]
-> #1 (fs_reclaim){+.+.}-{0:0}:
[ 8.760315] fs_reclaim_acquire+0xc5/0x100
[ 8.760317] kmem_cache_alloc_lru_noprof+0x4a/0x480
[ 8.760319] alloc_inode+0xaa/0xe0
[ 8.760322] iget_locked+0x157/0x330
[ 8.760323] kernfs_get_inode+0x1b/0x110
[ 8.760325] kernfs_get_tree+0x1b0/0x2e0
[ 8.760327] sysfs_get_tree+0x1f/0x60
[ 8.760329] vfs_get_tree+0x2a/0xf0
[ 8.760332] path_mount+0x4cd/0xc00
[ 8.760334] __x64_sys_mount+0x119/0x150
[ 8.760336] x64_sys_call+0x14f2/0x2310
[ 8.760338] do_syscall_64+0x91/0x180
[ 8.760340] entry_SYSCALL_64_after_hwframe+0x76/0x7e
[ 8.760342]
-> #0 (&root->kernfs_rwsem){++++}-{3:3}:
[ 8.760345] __lock_acquire+0x1525/0x2760
[ 8.760347] lock_acquire+0xca/0x310
[ 8.760348] down_write+0x3e/0xf0
[ 8.760350] kernfs_remove+0x32/0x60
[ 8.760351] sysfs_remove_dir+0x4f/0x60
[ 8.760353] __kobject_del+0x33/0xa0
[ 8.760355] kobject_del+0x13/0x30
[ 8.760356] elv_unregister_queue+0x52/0x80
[ 8.760358] elevator_switch+0x68/0x360
[ 8.760360] elv_iosched_store+0x14b/0x1b0
[ 8.760362] queue_attr_store+0x181/0x1e0
[ 8.760364] sysfs_kf_write+0x49/0x80
[ 8.760366] kernfs_fop_write_iter+0x17d/0x250
[ 8.760367] vfs_write+0x281/0x540
[ 8.760370] ksys_write+0x72/0xf0
[ 8.760372] __x64_sys_write+0x19/0x30
[ 8.760374] x64_sys_call+0x2a3/0x2310
[ 8.760376] do_syscall_64+0x91/0x180
[ 8.760377] entry_SYSCALL_64_after_hwframe+0x76/0x7e
[ 8.760380]
other info that might help us debug this:
[ 8.760380] Chain exists of:
&root->kernfs_rwsem --> fs_reclaim --> &q->q_usage_counter(io)#27
[ 8.760384] Possible unsafe locking scenario:
[ 8.760384] CPU0 CPU1
[ 8.760385] ---- ----
[ 8.760385] lock(&q->q_usage_counter(io)#27);
[ 8.760387] lock(fs_reclaim);
[ 8.760388] lock(&q->q_usage_counter(io)#27);
[ 8.760390] lock(&root->kernfs_rwsem);
[ 8.760391]
*** DEADLOCK ***
[ 8.760391] 6 locks held by (udev-worker)/674:
[ 8.760392] #0: ffff8881209ac420 (sb_writers#4){.+.+}-{0:0}, at: ksys_write+0x72/0xf0
[ 8.760398] #1: ffff88810c80f488 (&of->mutex#2){+.+.}-{3:3}, at: kernfs_fop_write_iter+0x136/0x250
[ 8.760402] #2: ffff888125d1d330 (kn->active#101){.+.+}-{0:0}, at: kernfs_fop_write_iter+0x13f/0x250
[ 8.760406] #3: ffff888110dc7bb0 (&q->sysfs_lock){+.+.}-{3:3}, at: queue_attr_store+0x148/0x1e0
[ 8.760411] #4: ffff888110dc7680 (&q->q_usage_counter(io)#27){++++}-{0:0}, at: blk_mq_freeze_queue_nomemsave+0x12/0x30
[ 8.760416] #5: ffff888110dc76b8 (&q->q_usage_counter(queue)#27){++++}-{0:0}, at: blk_mq_freeze_queue_nomemsave+0x12/0x30
[ 8.760421]
stack backtrace:
[ 8.760422] CPU: 7 UID: 0 PID: 674 Comm: (udev-worker) Tainted: G U 6.14.0-rc6-xe+ #7
[ 8.760424] Tainted: [U]=USER
[ 8.760425] Hardware name: ASUS System Product Name/PRIME B560M-A AC, BIOS 2001 02/01/2023
[ 8.760426] Call Trace:
[ 8.760427] <TASK>
[ 8.760428] dump_stack_lvl+0x6e/0xa0
[ 8.760431] dump_stack+0x10/0x18
[ 8.760433] print_circular_bug.cold+0x17a/0x1b7
[ 8.760437] check_noncircular+0x13a/0x150
[ 8.760441] ? save_trace+0x54/0x360
[ 8.760445] __lock_acquire+0x1525/0x2760
[ 8.760446] ? irqentry_exit+0x3a/0xb0
[ 8.760448] ? sysvec_apic_timer_interrupt+0x57/0xc0
[ 8.760452] lock_acquire+0xca/0x310
[ 8.760453] ? kernfs_remove+0x32/0x60
[ 8.760457] down_write+0x3e/0xf0
[ 8.760459] ? kernfs_remove+0x32/0x60
[ 8.760460] kernfs_remove+0x32/0x60
[ 8.760462] sysfs_remove_dir+0x4f/0x60
[ 8.760464] __kobject_del+0x33/0xa0
[ 8.760466] kobject_del+0x13/0x30
[ 8.760467] elv_unregister_queue+0x52/0x80
[ 8.760470] elevator_switch+0x68/0x360
[ 8.760472] elv_iosched_store+0x14b/0x1b0
[ 8.760475] queue_attr_store+0x181/0x1e0
[ 8.760479] ? lock_acquire+0xca/0x310
[ 8.760480] ? kernfs_fop_write_iter+0x13f/0x250
[ 8.760482] ? lock_is_held_type+0xa3/0x130
[ 8.760485] sysfs_kf_write+0x49/0x80
[ 8.760487] kernfs_fop_write_iter+0x17d/0x250
[ 8.760489] vfs_write+0x281/0x540
[ 8.760494] ksys_write+0x72/0xf0
[ 8.760497] __x64_sys_write+0x19/0x30
[ 8.760499] x64_sys_call+0x2a3/0x2310
[ 8.760502] do_syscall_64+0x91/0x180
[ 8.760504] ? trace_hardirqs_off+0x5d/0xe0
[ 8.760506] ? handle_softirqs+0x479/0x4d0
[ 8.760508] ? hrtimer_interrupt+0x13f/0x280
[ 8.760511] ? irqentry_exit_to_user_mode+0x8b/0x260
[ 8.760513] ? clear_bhb_loop+0x15/0x70
[ 8.760515] ? clear_bhb_loop+0x15/0x70
[ 8.760516] ? clear_bhb_loop+0x15/0x70
[ 8.760518] entry_SYSCALL_64_after_hwframe+0x76/0x7e
[ 8.760520] RIP: 0033:0x7aa3bf2f5504
[ 8.760522] Code: c7 00 16 00 00 00 b8 ff ff ff ff c3 66 2e 0f 1f 84 00 00 00 00 00 f3 0f 1e fa 80 3d c5 8b 10 00 00 74 13 b8 01 00 00 00 0f 05 <48> 3d 00 f0 ff ff 77 54 c3 0f 1f 00 55 48 89 e5 48 83 ec 20 48 89
[ 8.760523] RSP: 002b:00007ffc1e3697d8 EFLAGS: 00000202 ORIG_RAX: 0000000000000001
[ 8.760526] RAX: ffffffffffffffda RBX: 0000000000000003 RCX: 00007aa3bf2f5504
[ 8.760527] RDX: 0000000000000003 RSI: 00007ffc1e369ae0 RDI: 000000000000001c
[ 8.760528] RBP: 00007ffc1e369800 R08: 00007aa3bf3f51c8 R09: 00007ffc1e3698b0
[ 8.760528] R10: 0000000000000000 R11: 0000000000000202 R12: 0000000000000003
[ 8.760529] R13: 00007ffc1e369ae0 R14: 0000613ccf21f2f0 R15: 00007aa3bf3f4e80
[ 8.760533] </TASK>
v2:
- Update a code comment to increase readability (Ming Lei).
Cc: Jens Axboe <axboe@kernel.dk>
Cc: linux-block@vger.kernel.org
Cc: linux-kernel@vger.kernel.org
Cc: Ming Lei <ming.lei@redhat.com>
Signed-off-by: Thomas HellstrΓΆm <thomas.hellstrom@linux.intel.com>
Reviewed-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20250318095548.5187-1-thomas.hellstrom@linux.intel.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-core.c b/block/blk-core.c
index 362d0a55b07a..4623de79effa 100644
--- a/block/blk-core.c
+++ b/block/blk-core.c
@@ -456,6 +456,12 @@ struct request_queue *blk_alloc_queue(struct queue_limits *lim, int node_id)
lockdep_init_map(&q->q_lockdep_map, "&q->q_usage_counter(queue)",
&q->q_lock_cls_key, 0);
+ /* Teach lockdep about lock ordering (reclaim WRT queue freeze lock). */
+ fs_reclaim_acquire(GFP_KERNEL);
+ rwsem_acquire_read(&q->io_lockdep_map, 0, 0, _RET_IP_);
+ rwsem_release(&q->io_lockdep_map, _RET_IP_);
+ fs_reclaim_release(GFP_KERNEL);
+
q->nr_requests = BLKDEV_DEFAULT_RQ;
return q;
]
|
| 212/2 |
2026/11/03 17:37 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 357e1b7f730bd85a383e7afa75a3caba329c5707
Author: Ming Lei <ming.lei@redhat.com>
Date: Thu Oct 31 21:37:20 2024 +0800
block: don't verify IO lock for freeze/unfreeze in elevator_init_mq()
elevator_init_mq() is only called at the entry of add_disk_fwnode() when
disk IO isn't allowed yet.
So not verify io lock(q->io_lockdep_map) for freeze & unfreeze in
elevator_init_mq().
Reported-by: Marek Szyprowski <m.szyprowski@samsung.com>
Reported-by: Lai Yi <yi1.lai@linux.intel.com>
Fixes: f1be1788a32e ("block: model freeze & enter queue as lock for supporting lockdep")
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241031133723.303835-5-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/elevator.c b/block/elevator.c
index f169f4bae917..7c3ba80e5ff4 100644
--- a/block/elevator.c
+++ b/block/elevator.c
@@ -598,13 +598,19 @@ void elevator_init_mq(struct request_queue *q)
* drain any dispatch activities originated from passthrough
* requests, then no need to quiesce queue which may add long boot
* latency, especially when lots of disks are involved.
+ *
+ * Disk isn't added yet, so verifying queue lock only manually.
*/
- blk_mq_freeze_queue(q);
+ blk_freeze_queue_start_non_owner(q);
+ blk_freeze_acquire_lock(q, true, false);
+ blk_mq_freeze_queue_wait(q);
+
blk_mq_cancel_work_sync(q);
err = blk_mq_init_sched(q, e);
- blk_mq_unfreeze_queue(q);
+ blk_unfreeze_release_lock(q, true, false);
+ blk_mq_unfreeze_queue_non_owner(q);
if (err) {
pr_warn("\"%s\" elevator initialization failed, "
]
|
| 213/2 |
2026/11/03 17:37 |
llm |
history-explorer |
5m
Model:
Tokens:
input: 62095
output: 32
thoughts: 45
Thoughts: Okay, let's dive into this.
**Examining Elevator Code**
Alright, my focus is on how the elevator logic is implemented. Specifically, I need to understand the mechanics of the `elevator_switch` or `elevator_change` functions within the `block/elevator.c` file. My initial thought is to go straight to `block/elevator.c` and analyze the `elevator_change` function directly. It's the most likely place to find the core behavior I'm looking for. Let's see what's actually going on in that code.
|
| 214/2 |
2026/11/03 17:42 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/elevator.c Name:elevator_change]
Results: map[SourceCode: 650: /*
651: * Switch this queue to the given IO scheduler.
652: */
653: static int elevator_change(struct request_queue *q, struct elv_change_ctx *ctx)
654: {
655: unsigned int memflags;
656: struct blk_mq_tag_set *set = q->tag_set;
657: int ret = 0;
658:
659: lockdep_assert_held(&set->update_nr_hwq_lock);
660:
661: if (strncmp(ctx->name, "none", 4)) {
662: ret = blk_mq_alloc_sched_res(q, ctx->type, &ctx->res,
663: set->nr_hw_queues);
664: if (ret)
665: return ret;
666: }
667:
668: memflags = blk_mq_freeze_queue(q);
669: /*
670: * May be called before adding disk, when there isn't any FS I/O,
671: * so freezing queue plus canceling dispatch work is enough to
672: * drain any dispatch activities originated from passthrough
673: * requests, then no need to quiesce queue which may add long boot
674: * latency, especially when lots of disks are involved.
675: *
676: * Disk isn't added yet, so verifying queue lock only manually.
677: */
678: blk_mq_cancel_work_sync(q);
679: mutex_lock(&q->elevator_lock);
680: if (!(q->elevator && elevator_match(q->elevator->type, ctx->name)))
681: ret = elevator_switch(q, ctx);
682: mutex_unlock(&q->elevator_lock);
683: blk_mq_unfreeze_queue(q, memflags);
684: if (!ret)
685: ret = elevator_change_done(q, ctx);
686:
687: /*
688: * Free sched resource if it's allocated but we couldn't switch elevator.
689: */
690: if (!ctx->new)
691: blk_mq_free_sched_res(&ctx->res, ctx->type, set);
692:
693: return ret;
694: }
SourceFile:block/elevator.c]
|
| 215/2 |
2026/11/03 17:42 |
llm |
history-explorer |
3m
Model:
Tokens:
input: 63015
output: 52
thoughts: 281
Thoughts: **Analyzing Elevator Code and Device Mapper Interactions**
Okay, so I'm looking at this `elevator_change` function, specifically line 676. That comment, "Disk isn't added yet, so verifying queue lock only manually," is a relic from back when `elevator_change` was unified with `elevator_init_mq`. I remember that commit `b9d4eee7e04b` simplified things by switching `elevator_init_mq` to use `blk_mq_freeze_queue(q)` and `blk_mq_unfreeze_queue(q)`. I should investigate how these functions changed.
Let's dig in and see how `elevator_switch` and the evolution of `elevator_init_mq` and `elevator_change` have played out. I can see in the current `elevator_change`, there's a `memflags = blk_mq_freeze_queue(q);` call at line 668 and a corresponding `blk_mq_unfreeze_queue(q, memflags);` call at line 683. That confirms my recollection.
Now, my focus shifts to the Device Mapper code, specifically `drivers/md/dm-ioctl.c` and `drivers/md/dm.c`. I need to understand the interaction between `DM_TABLE_LOAD` and `DM_DEV_REMOVE`. To get the full picture, I'll search the `git-log` history of `dm-ioctl.c` for commits that touch on the concepts of "holders," `dm_lock_for_deletion`, `dev_remove`, `table_load`, and related mechanisms. This should reveal how these operations synchronize and interact, and hopefully expose any potential race conditions.
|
| 216/2 |
2026/11/03 17:45 |
tool |
git-log |
0m
Args: map[Count:20 MessageRegexps:[holders|dev_remove|table_load|dm_destroy] PathPrefix:drivers/md/ Since:3 years]
Results:
|
| 217/2 |
2026/11/03 17:45 |
llm |
history-explorer |
3m
Model:
Tokens:
input: 63734
output: 40
thoughts: 25
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Analyzing Potential Issues in the `drivers/md/` Directory**
Alright, so I'm thinking about the RAID driver code again. I need to get a handle on potential issues around resource management. My first instinct is to dig into the commit history for `drivers/md/`. I'm going to leverage my familiarity with the codebase and search for commit messages that might flag problematic areas. Specifically, I'm zeroing in on keywords that scream potential concurrency or lifecycle issues. I'm focusing on "destroy," "remove," and "race." Those three terms are pretty common indicators of where problems tend to hide, particularly when it comes to shared resources and asynchronous operations. A "destroy" or "remove" might be incorrectly synchronized, leading to use-after-free or double-free scenarios. And, of course, "race" is a red flag on its own, suggesting the kind of data corruption or device misbehavior that I need to pre-emptively discover. Let's see what the commit history tells us.
|
| 218/2 |
2026/11/03 17:49 |
tool |
git-log |
0m
Args: map[Count:20 MessageRegexps:[race] PathPrefix:drivers/md/ Since:3 years]
Results: map[Output:005d2ec5723c dm-bufio: fix a race leading to an unsigned integer underflow
4c90b76e0198 md: Fix the null-ptr-deref of 'mddev->private' while submitting IO
73b0df929494 md/raid5: protect big_stripe_tree lookup with RCU
c9417c1c5269 dm: fix reading free memory in do_resume
370ca0760b18 md/raid5: reject a per-device size smaller than one chunk
0669c7dbd1d3 md/raid5: don't BUG() on an inconsistent reshape state from the superblock
f00eb0ff4579 md/raid10: fix missing wakeup in wait_barrier_nolock
b2fd92f016e9 dm-integrity: require stable writes for internal hash modes
148845aa1921 dm-crypt: fix a tiny race condition in crypt_dec_pending
9b2d455305f1 md/md-llbitmap: remap checkpointed bits as reshape progresses
5553d64e01d9 md/md-llbitmap: stop daemon timer rearm on destroy
a41bb2ee1aca md/raid5: reject zero-sector reshape chunks
140234b2380f md/raid1: create serial pool adding rdev to array with serialize_policy=1
c7d34d17ea43 md: recheck spare changes before starting sync
a47431dfb353 md/raid5: protect lockless recovery_offset accesses during reshape
6cb6ab75bdf2 md/raid5: fix lockless max_nr_stripes reads
e12e619c2e2d md/raid1: protect sequential read hints for read balance
f565925810cb md/raid5: protect bitmap batch counters aka seq_flush/seq_write consistency
5380c7f6335c dm: fix race when loading and unloading a table
44b43ec132f1 dm: fix resume-vs-remove race
]
|
| 219/2 |
2026/11/03 17:49 |
llm |
history-explorer |
3m
Model:
Tokens:
input: 64565
output: 26
thoughts: 41
Thoughts: Okay, here's my interpretation of that:
**Diving Deep into a Critical Commit**
Right, let's take a look at this commit, `44b43ec132f1`, a fix for a resume-versus-remove race condition, specifically. Immediately I'm thinking, "Let's pull up the details with `git show` and dissect it." I want to see the exact code changes. I'm keen to understand the root cause of the race, the approach taken to resolve it, and the potential implications of this fix in the larger architecture. I'll be looking for any signs of a narrow fix versus a more generalized solution. Are there tests accompanying this commit? That's a must, of course. I'll be paying close attention to the specific concurrency primitives involved and how they've been employed to eliminate the race. Ultimately, my goal is to assess the robustness of this solution and whether it introduces any new vulnerabilities or performance bottlenecks. I also wonder about how this relates to other work in that area.
|
| 220/2 |
2026/11/03 17:52 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 44b43ec132f1cf3275ecc182d0c82f50c3c4c3d5
Author: Mikulas Patocka <mpatocka@redhat.com>
Date: Mon Jul 27 22:26:36 2026 +0200
dm: fix resume-vs-remove race
If the user issues the resume ioctl and the remove ioctl at the same
time, it may be possible that the device is resumed after it is suspended
in __dm_destroy. The result is that the table is destroyed without
calling the postsuspend method.
Dm targets expect that they may be removed only after the postsuspend
method method was called. If we break this expectation, it can cause
misbehavior in various targets. For example - in the dm-integrity target,
the reboot notifier is not unregistered, leading to use-after-free.
Fix this bug by refusing to resume if the device is being destroyed.
Signed-off-by: Mikulas Patocka <mpatocka@redhat.com>
Cc: stable@vger.kernel.org
diff --git a/drivers/md/dm.c b/drivers/md/dm.c
index d413bfaf3527..e907fe278c72 100644
--- a/drivers/md/dm.c
+++ b/drivers/md/dm.c
@@ -3140,7 +3140,7 @@ int dm_resume(struct mapped_device *md)
r = -EINVAL;
mutex_lock_nested(&md->suspend_lock, SINGLE_DEPTH_NESTING);
- if (!dm_suspended_md(md))
+ if (!dm_suspended_md(md) || test_bit(DMF_FREEING, &md->flags))
goto out;
if (dm_suspended_internally_md(md)) {
]
|
| 221/2 |
2026/11/03 17:52 |
llm |
history-explorer |
5m
Model:
Tokens:
input: 65355
output: 37
thoughts: 97
Thoughts: Okay, here's my take on those thoughts, framed for my expert perspective:
**Investigating a Device Mapper Race Condition Fix**
That's a fantastic commit! Mikulas Patocka just squashed a nasty race condition in Device Mapper β specifically, the one between the resume ioctl and the remove ioctl. I remember that was a tricky one to diagnose, and getting those two operations interleaving like that could cause some pretty gnarly data corruption or even kernel panics. Kudos to him for nailing it down. I wonder what the root cause was.
Let's see, now...I'm curious about the surrounding work in those files. I'll need to dig into `drivers/md/dm-ioctl.c` and `drivers/md/dm.c`. I'll start by checking Mikulas Patocka's other contributions to those files, and the broader Device Mapper infrastructure within `drivers/md/`. It will be worth seeing if this was an isolated fix, or if it indicates a broader vulnerability and or an active period of improvements in that area. Probably worth scanning git log for recent activity.
|
| 222/2 |
2026/11/03 17:57 |
tool |
git-log |
0m
Args: map[Count:20 PathPrefix:drivers/md/dm-ioctl.c Since:3 years]
Results: map[Output:c9417c1c5269 dm: fix reading free memory in do_resume
9b3fcf519d37 dm ioctl: don't let data_start run past the buffer
cd516571e975 dm: lookup_ioctl(): Use designated array initialers
96979634af39 dm: list_devices(): Only process devices once
78726ba0ffe3 dm: __list_versions(): Only process targets once
0729a9b4ee5a dm: drop redundant nonseekable_open() return check
a02d51919b05 dm-ioctl: delete a useless condition
76c6f845dc0c dm-ioctl: fix a possible overflow in list_version_get_info
366665416f20 dm_early_create: fix freeing used table on dm_resume failure
457e32348d60 dm-ioctl: report an error if a device has no table
c90decb190bc dm-ima: remove new_map from dm_ima_measure_on_device_clear
5534cac9b56d dm-ima: Fix UAF errors and measuring incorrect context
b1a80737a9af dm-ima: Remove status_flags from dm_ima_measure_on_table_load()
2fa49cc884f6 dm: fix a buffer overflow in ioctl processing
23e6e57a93bc dm: make "dmsetup remove_all" interruptible
b7cce3e2cca9 dm: don't report warning when doing deferred remove
bf4afc53b77a Convert 'alloc_obj' family to use the new default GFP_KERNEL argument
69050f8d6d07 treewide: Replace kmalloc with kmalloc_obj for non-scalar types
4550a71b179b Revert "dm: fix a race condition in retrieve_deps"
7734fb4ad98c dm mpath: Interface for explicit probing of active paths
]
|
| 223/2 |
2026/11/03 17:57 |
llm |
history-explorer |
2m
Model:
Tokens:
input: 66241
output: 27
thoughts: 38
Thoughts: Okay, let's dive into commit `4550a71b179b Revert "dm: fix a race condition in retrieve_deps"`. My initial thought is to figure out *why* this was reverted. A revert usually signifies that the fix itself introduced more problems, or that the cost of the fix outweighed the benefits. I need to understand the nature of the race condition the original commit was addressing, and then the fallout that led to its reversal. My expertise tells me that race conditions in dependency retrieval, especially in a system like Device Mapper, could be particularly nasty, leading to data corruption or inconsistent states. I need to see if the original patch introduces a regression elsewhere, perhaps performance-related, or causes deadlock, or maybe breaks some obscure corner case that's essential in the context of our overall system architecture. Let me compare the commit before the revert with the one that was reverted, and understand the context of this dependency retrieval. I am expecting I may need to dive into related commits and issues as well.
|
| 224/2 |
2026/11/03 18:00 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 4550a71b179be9e2a17015c018b231a2daca2dd1
Author: Benjamin Marzinski <bmarzins@redhat.com>
Date: Tue Jan 27 19:12:23 2026 -0500
Revert "dm: fix a race condition in retrieve_deps"
This reverts commit f6007dce0cd35d634d9be91ef3515a6385dcee16.
Commit f6007dce0cd3 ("dm: fix a race condition in retrieve_deps") was
added to fix a race between retrieving the list of dm table devices and
multipath_message() modifying the list of table devices. But Commit
a48f6b82c5c4 ("dm mpath: don't call dm_get_device in multipath_message")
removed the call to dm_get_device() from multipath_message(). After that
commit, the only calls to dm_get_device() and dm_put_device() are in
target constructors and destructors, so the race with retrieve_deps() is
no longer possible.
Suggested-by: Martin Wilck <mwilck@suse.com>
Signed-off-by: Benjamin Marzinski <bmarzins@redhat.com>
Signed-off-by: Mikulas Patocka <mpatocka@redhat.com>
diff --git a/drivers/md/dm-core.h b/drivers/md/dm-core.h
index 1cda8618d74d..a3b8ad6e1c42 100644
--- a/drivers/md/dm-core.h
+++ b/drivers/md/dm-core.h
@@ -215,7 +215,6 @@ struct dm_table {
/* a list of devices used by this table */
struct list_head devices;
- struct rw_semaphore devices_lock;
/* events get handed up using this callback */
void (*event_fn)(void *data);
diff --git a/drivers/md/dm-ioctl.c b/drivers/md/dm-ioctl.c
index 4165fef4c170..fd4bf8e1d73e 100644
--- a/drivers/md/dm-ioctl.c
+++ b/drivers/md/dm-ioctl.c
@@ -1648,8 +1648,6 @@ static void retrieve_deps(struct dm_table *table,
struct dm_dev_internal *dd;
struct dm_target_deps *deps;
- down_read(&table->devices_lock);
-
deps = get_result_buffer(param, param_size, &len);
/*
@@ -1664,7 +1662,7 @@ static void retrieve_deps(struct dm_table *table,
needed = struct_size(deps, dev, count);
if (len < needed) {
param->flags |= DM_BUFFER_FULL_FLAG;
- goto out;
+ return;
}
/*
@@ -1676,9 +1674,6 @@ static void retrieve_deps(struct dm_table *table,
deps->dev[count++] = huge_encode_dev(dd->dm_dev->bdev->bd_dev);
param->data_size = param->data_start + needed;
-
-out:
- up_read(&table->devices_lock);
}
static int table_deps(struct file *filp, struct dm_ioctl *param, size_t param_size)
diff --git a/drivers/md/dm-table.c b/drivers/md/dm-table.c
index 4b70872725d0..7be1d8dc8bdd 100644
--- a/drivers/md/dm-table.c
+++ b/drivers/md/dm-table.c
@@ -139,7 +139,6 @@ int dm_table_create(struct dm_table **result, blk_mode_t mode,
return -ENOMEM;
INIT_LIST_HEAD(&t->devices);
- init_rwsem(&t->devices_lock);
if (!num_targets)
num_targets = KEYS_PER_NODE;
@@ -380,20 +379,16 @@ int dm_get_device(struct dm_target *ti, const char *path, blk_mode_t mode,
if (dev == disk_devt(t->md->disk))
return -EINVAL;
- down_write(&t->devices_lock);
-
dd = find_device(&t->devices, dev);
if (!dd) {
dd = kmalloc(sizeof(*dd), GFP_KERNEL);
- if (!dd) {
- r = -ENOMEM;
- goto unlock_ret_r;
- }
+ if (!dd)
+ return -ENOMEM;
r = dm_get_table_device(t->md, dev, mode, &dd->dm_dev);
if (r) {
kfree(dd);
- goto unlock_ret_r;
+ return r;
}
refcount_set(&dd->count, 1);
@@ -403,17 +398,12 @@ int dm_get_device(struct dm_target *ti, const char *path, blk_mode_t mode,
} else if (dd->dm_dev->mode != (mode | dd->dm_dev->mode)) {
r = upgrade_mode(dd, mode, t->md);
if (r)
- goto unlock_ret_r;
+ return r;
}
refcount_inc(&dd->count);
out:
- up_write(&t->devices_lock);
*result = dd->dm_dev;
return 0;
-
-unlock_ret_r:
- up_write(&t->devices_lock);
- return r;
}
EXPORT_SYMBOL(dm_get_device);
@@ -464,12 +454,9 @@ static int dm_set_device_limits(struct dm_target *ti, struct dm_dev *dev,
void dm_put_device(struct dm_target *ti, struct dm_dev *d)
{
int found = 0;
- struct dm_table *t = ti->table;
- struct list_head *devices = &t->devices;
+ struct list_head *devices = &ti->table->devices;
struct dm_dev_internal *dd;
- down_write(&t->devices_lock);
-
list_for_each_entry(dd, devices, list) {
if (dd->dm_dev == d) {
found = 1;
@@ -478,17 +465,14 @@ void dm_put_device(struct dm_target *ti, struct dm_dev *d)
}
if (!found) {
DMERR("%s: device %s not in table devices list",
- dm_device_name(t->md), d->name);
- goto unlock_ret;
+ dm_device_name(ti->table->md), d->name);
+ return;
}
if (refcount_dec_and_test(&dd->count)) {
- dm_put_table_device(t->md, d);
+ dm_put_table_device(ti->table->md, d);
list_del(&dd->list);
kfree(dd);
}
-
-unlock_ret:
- up_write(&t->devices_lock);
}
EXPORT_SYMBOL(dm_put_device);
]
|
| 225/2 |
2026/11/03 18:00 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 68542
output: 36
thoughts: 46
Thoughts: Okay, let's dive into this. Here's my understanding, thinking through `table_load` in `drivers/md/dm-ioctl.c`:
**Dissecting `table_load` in `drivers/md/dm-ioctl.c`**
Alright, so I'm focusing on the `table_load` function within `drivers/md/dm-ioctl.c`. I need to understand exactly what goes on during this process. My initial step is to delve directly into the code and give it a thorough read-through. I want to build a very precise understanding of what this function does.
|
| 226/2 |
2026/11/03 18:00 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/md/dm-ioctl.c Name:table_load]
Results: map[SourceCode:1626: static int table_load(struct file *filp, struct dm_ioctl *param, size_t param_size)
1627: {
1628: int r, srcu_idx;
1629: struct hash_cell *hc;
1630: struct dm_table *t, *old_map = NULL;
1631: struct mapped_device *md;
1632: struct target_type *immutable_target_type;
1633: struct dm_ima_context *ima_context = NULL;
1634:
1635: md = find_device(param);
1636: if (!md)
1637: return -ENXIO;
1638:
1639: r = dm_table_create(&t, get_mode(param), param->target_count, md);
1640: if (r)
1641: goto err;
1642:
1643: /* Protect md->type and md->queue against concurrent table loads. */
1644: dm_lock_md_type(md);
1645: r = populate_table(t, param, param_size);
1646: if (r)
1647: goto err_unlock_md_type;
1648:
1649: immutable_target_type = dm_get_immutable_target_type(md);
1650: if (immutable_target_type &&
1651: (immutable_target_type != dm_table_get_immutable_target_type(t)) &&
1652: !dm_table_get_wildcard_target(t)) {
1653: DMERR("can't replace immutable target type %s",
1654: immutable_target_type->name);
1655: r = -EINVAL;
1656: goto err_unlock_md_type;
1657: }
1658:
1659: if (dm_get_md_type(md) == DM_TYPE_NONE) {
1660: /* setup md->queue to reflect md's type (may block) */
1661: r = dm_setup_md_queue(md, t);
1662: if (r) {
1663: DMERR("unable to set up device queue for new table.");
1664: goto err_unlock_md_type;
1665: }
1666: } else if (!is_valid_type(dm_get_md_type(md), dm_table_get_type(t))) {
1667: DMERR("can't change device type (old=%u vs new=%u) after initial table load.",
1668: dm_get_md_type(md), dm_table_get_type(t));
1669: r = -EINVAL;
1670: goto err_unlock_md_type;
1671: }
1672:
1673: dm_unlock_md_type(md);
1674:
1675: dm_ima_alloc_context(&ima_context, false);
1676: /* stage inactive table */
1677: down_write(&_hash_lock);
1678: hc = dm_get_mdptr(md);
1679: if (!hc) {
1680: DMERR("device has been removed from the dev hash table.");
1681: up_write(&_hash_lock);
1682: dm_ima_free_context(ima_context);
1683: r = -ENXIO;
1684: goto err_destroy_table;
1685: }
1686:
1687: if (hc->new_map)
1688: old_map = hc->new_map;
1689: hc->new_map = t;
1690: dm_ima_init_context(hc, ima_context, false);
1691: /* Make sure new_map doesn't get freed before we measure it*/
1692: dm_get_live_table(md, &srcu_idx);
1693: up_write(&_hash_lock);
1694:
1695: dm_ima_measure_on_table_load(t, ima_context);
1696: dm_ima_free_context(ima_context);
1697: dm_put_live_table(md, srcu_idx);
1698:
1699: param->flags |= DM_INACTIVE_PRESENT_FLAG;
1700: __dev_status(md, param);
1701:
1702: if (old_map) {
1703: dm_sync_table(md);
1704: dm_table_destroy(old_map);
1705: }
1706:
1707: dm_put(md);
1708:
1709: return 0;
1710:
1711: err_unlock_md_type:
1712: dm_unlock_md_type(md);
1713: err_destroy_table:
1714: dm_table_destroy(t);
1715: err:
1716: dm_put(md);
1717:
1718: return r;
1719: }
SourceFile:drivers/md/dm-ioctl.c]
|
| 227/2 |
2026/11/03 18:01 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 70238
output: 36
thoughts: 237
Thoughts: **Analyzing Device Mapper Table Loading and Removal**
Okay, let's break this down. I'm focusing on the interaction between `table_load()` and `dev_remove()` within the Device Mapper framework. My primary concern is the potential for race conditions and data corruption, so I'm paying close attention to reference counting and locking mechanisms.
First, `table_load()`β¦ I see it begins with `md = find_device(param);` which, importantly, increments `md->holders` through `dm_get(md)`. This is my primary reference point for the lifespan of `md`. Following that, `dm_lock_md_type(md)` enforces some synchronization around the device's type, then `populate_table(t, ...)` is called. After that, this conditional `if (dm_get_md_type(md) == DM_TYPE_NONE)` checks, and if so calls `dm_setup_md_queue(md, t)`, and finally `dm_unlock_md_type(md)` completes the type modification. So far, so good.
Now, things get a little trickier here: `down_write(&_hash_lock)`. The critical thing is the device hash table. Right after that, it calls `hc = dm_get_mdptr(md);` If that value is null, then the device has been removed from the hash table, and the function goes to `err_destroy_table;`, which calls `dm_put(md); return -ENXIO;` This looks like a critical point where a device could be removed (potentially concurrently) while a table is being loaded.
Next, I need to read `dev_remove()` from `drivers/md/dm-ioctl.c` to understand exactly what happens there, to see the whole picture. I'm keen to ensure that references are decremented consistently and that locking is properly managed to prevent a use-after-free or double-free situation. This is where the devil is, in the details.
|
| 228/2 |
2026/11/03 18:01 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/md/dm-ioctl.c Name:dev_remove]
Results: map[SourceCode:1063: static int dev_remove(struct file *filp, struct dm_ioctl *param, size_t param_size)
1064: {
1065: struct hash_cell *hc;
1066: struct mapped_device *md;
1067: int r;
1068: struct dm_table *t;
1069: struct dm_ima_context *ima_context = NULL;
1070: unsigned int ima_idx;
1071:
1072: dm_ima_alloc_context(&ima_context, true);
1073: down_write(&_hash_lock);
1074: hc = __find_device_hash_cell(param);
1075:
1076: if (!hc) {
1077: DMDEBUG_LIMIT("device doesn't appear to be in the dev hash table.");
1078: up_write(&_hash_lock);
1079: dm_ima_free_context(ima_context);
1080: return -ENXIO;
1081: }
1082:
1083: md = hc->md;
1084:
1085: /*
1086: * Ensure the device is not open and nothing further can open it.
1087: */
1088: r = dm_lock_for_deletion(md, !!(param->flags & DM_DEFERRED_REMOVE), false);
1089: if (r) {
1090: if (r == -EBUSY && param->flags & DM_DEFERRED_REMOVE) {
1091: up_write(&_hash_lock);
1092: dm_put(md);
1093: dm_ima_free_context(ima_context);
1094: return 0;
1095: }
1096: DMDEBUG_LIMIT("unable to remove open device %s", hc->name);
1097: up_write(&_hash_lock);
1098: dm_put(md);
1099: dm_ima_free_context(ima_context);
1100: return r;
1101: }
1102:
1103: ima_idx = dm_ima_init_context(hc, ima_context, true);
1104: t = __hash_remove(hc);
1105: up_write(&_hash_lock);
1106:
1107: if (t) {
1108: dm_sync_table(md);
1109: dm_table_destroy(t);
1110: }
1111:
1112: param->flags &= ~DM_DEFERRED_REMOVE;
1113:
1114: dm_ima_measure_on_device_remove(md, false, ima_context, ima_idx);
1115: dm_ima_free_context(ima_context);
1116:
1117: if (!dm_kobject_uevent(md, KOBJ_REMOVE, param->event_nr, false))
1118: param->flags |= DM_UEVENT_GENERATED_FLAG;
1119:
1120: dm_put(md);
1121: dm_destroy(md);
1122: return 0;
1123: }
SourceFile:drivers/md/dm-ioctl.c]
|
| 229/2 |
2026/11/03 18:01 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 71878
output: 40
thoughts: 36
Thoughts: Here's a breakdown of my thought process:
**Diving Deep into Device Removal**
Okay, I'm digging into the device removal process, specifically starting with the `dev_remove()` function. Right off the bat, I see a call to `dm_lock_for_deletion()`. My focus immediately shifts to that function because it likely holds the key to how the system manages the locking required for deletion. I need to understand how the locking works in order to fully grasp the ramifications of the removal procedure. Let's get into the weeds of `dm_lock_for_deletion()` and see what we're dealing with.
|
| 230/2 |
2026/11/03 18:01 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/md/dm-ioctl.c Name:dm_lock_for_deletion]
Results: map[SourceCode: 362: /*
363: * Guarantees nothing is using the device before it's deleted.
364: */
365: int dm_lock_for_deletion(struct mapped_device *md, bool mark_deferred, bool only_deferred)
366: {
367: int r = 0;
368:
369: spin_lock(&_minor_lock);
370:
371: if (dm_open_count(md)) {
372: r = -EBUSY;
373: if (mark_deferred)
374: set_bit(DMF_DEFERRED_REMOVE, &md->flags);
375: } else if (only_deferred && !test_bit(DMF_DEFERRED_REMOVE, &md->flags))
376: r = -EEXIST;
377: else
378: set_bit(DMF_DELETING, &md->flags);
379:
380: spin_unlock(&_minor_lock);
381:
382: return r;
383: }
SourceFile:drivers/md/dm.c]
|
| 231/2 |
2026/11/03 18:01 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 72431
output: 34
thoughts: 598
Thoughts: **Analyzing the Device Mapper Destruction Process**
Okay, let's break this down. I see `dm_lock_for_deletion` calls `dm_open_count(md)`. Makes sense, we need to check if there are any open handles before deletion. It then sets the `DMF_DELETING` flag. Got it. Now, I'm diving into `__dm_destroy()`. It's where the actual cleanup happens.
First, a quick `might_sleep()`. Then it grabs the `_minor_lock`, replaces the minor number in the `_minor_idr`, and sets `DMF_FREEING`. That's how it ensures no new accesses are possible and that the minor number gets reassigned. After that, it marks the disk as dead using `blk_mark_disk_dead()`.
Here's where it gets interesting: the `suspend_lock`. The code takes this lock to prevent races between presuspend/postsuspend methods and internal suspend operations. Then it grabs the live table using `dm_get_live_table()`. It checks if the device is already suspended; if not, it calls the table's presuspend and postsuspend methods. Setting `DMF_SUSPENDED` and `DMF_POST_SUSPENDING` flags. Important to note that `dm_put_live_table()` *must* come before the fsleep, to avoid potential deadlocks.
Now, the crucial part: waiting for outstanding I/O. The code checks `md->holders`. This is where it gets a little aggressive. If the `wait` flag is true, it enters a loop, sleeping for a millisecond until `md->holders` becomes zero. If `wait` is false, it prints a warning if there are still users, which is more of a safety valve, but still...forceful. Good to know, though; it highlights a potential for data corruption if we're not careful.
Finally, it destroys the table using `dm_table_destroy()` and frees the device with `free_dev(md)`. Looks pretty standard. Wait, let's pause. I should check how `free_dev(md)` is implemented. Need to make sure I fully understand that last step.
|
| 232/2 |
2026/11/03 18:02 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/md/dm.c Name:free_dev]
Results: map[SourceCode:2424: static void free_dev(struct mapped_device *md)
2425: {
2426: int minor = MINOR(disk_devt(md->disk));
2427:
2428: unlock_fs(md);
2429:
2430: cleanup_mapped_device(md);
2431:
2432: WARN_ON_ONCE(!list_empty(&md->table_devices));
2433: dm_stats_cleanup(&md->stats);
2434: free_minor(minor);
2435:
2436: module_put(THIS_MODULE);
2437: kvfree(md);
2438: }
SourceFile:drivers/md/dm.c]
|
| 233/2 |
2026/11/03 18:02 |
llm |
history-explorer |
2m
Model:
Tokens:
input: 73776
output: 29
thoughts: 35
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Investigating the `del_gendisk` Call in the Device Mapper Context**
Right, so I'm trying to trace the lifecycle of a `gendisk` object within the Device Mapper framework. The question is, precisely *where* does `del_gendisk` get called when dealing with DM devices? It's a fundamental part of the device removal and cleanup process, so knowing the exact location is crucial for understanding how the system handles device persistence and resource management.
My instinct is to dive directly into the `drivers/md/dm.c` source code. Itβs the central point for Device Mapper's core functionality, so it's the obvious place to begin the search. I'm going to leverage my familiarity with the codebase and use `grep` (or my preferred search tool) for a direct search for the function name `del_gendisk` within that file. That should quickly pinpoint the calling contexts and provide the necessary details. I'll be looking for the surrounding code to determine the conditions under which the function is called. From there, I'll analyse the control flow and understand the complete picture.
|
| 234/2 |
2026/11/03 18:04 |
tool |
grepper |
0m
Args: map[Expression:del_gendisk PathPrefixes:[drivers/md/]]
Results: map[Output:drivers/md/bcache/super.c=1353=static CLOSURE_CALLBACK(cached_dev_free)
--
drivers/md/bcache/super.c-1368- bd_unlink_disk_holder(dc->bdev, dc->disk.disk);
drivers/md/bcache/super.c:1369: del_gendisk(dc->disk.disk);
drivers/md/bcache/super.c-1370- }
--
drivers/md/bcache/super.c=1511=static CLOSURE_CALLBACK(flash_dev_free)
--
drivers/md/bcache/super.c-1517- &d->c->flash_dev_dirty_sectors);
drivers/md/bcache/super.c:1518: del_gendisk(d->disk);
drivers/md/bcache/super.c-1519- bcache_device_free(d);
--
drivers/md/dm.c=2245=static void cleanup_mapped_device(struct mapped_device *md)
--
drivers/md/dm.c-2271- /*
drivers/md/dm.c:2272: * Hold lock to make sure del_gendisk() won't concurrent
drivers/md/dm.c-2273- * with open/close_table_device().
--
drivers/md/dm.c-2275- mutex_lock(&md->table_devices_lock);
drivers/md/dm.c:2276: del_gendisk(md->disk);
drivers/md/dm.c-2277- mutex_unlock(&md->table_devices_lock);
--
drivers/md/dm.c=2600=int dm_setup_md_queue(struct mapped_device *md, struct dm_table *t)
--
drivers/md/dm.c-2627- /*
drivers/md/dm.c:2628: * Hold lock to make sure add_disk() and del_gendisk() won't concurrent
drivers/md/dm.c-2629- * with open_table_device() and close_table_device().
--
drivers/md/dm.c-2661- bd_unlink_disk_holder(td->dm_dev.bdev, md->disk);
drivers/md/dm.c:2662: del_gendisk(md->disk);
drivers/md/dm.c-2663- mutex_unlock(&md->table_devices_lock);
--
drivers/md/md.c=340=static bool create_on_open = true;
drivers/md/md.c:341:static bool legacy_async_del_gendisk = true;
drivers/md/md.c-342-static bool check_new_feature = true;
--
drivers/md/md.c=929=void mddev_unlock(struct mddev *mddev)
--
drivers/md/md.c-985-
drivers/md/md.c:986: if (!legacy_async_del_gendisk) {
drivers/md/md.c-987- /*
drivers/md/md.c:988: * Call del_gendisk after release reconfig_mutex to avoid
drivers/md/md.c:989: * deadlock (e.g. call del_gendisk under the lock and an
drivers/md/md.c-990- * access to sysfs files waits the lock)
--
drivers/md/md.c-997- kobject_del(&mddev->kobj);
drivers/md/md.c:998: del_gendisk(mddev->gendisk);
drivers/md/md.c-999- }
--
drivers/md/md.c=6192=static void md_kobj_release(struct kobject *ko)
--
drivers/md/md.c-6195-
drivers/md/md.c:6196: if (legacy_async_del_gendisk) {
drivers/md/md.c-6197- if (mddev->sysfs_state)
--
drivers/md/md.c-6200- sysfs_put(mddev->sysfs_level);
drivers/md/md.c:6201: del_gendisk(mddev->gendisk);
drivers/md/md.c-6202- }
--
drivers/md/md.c=6450=static int md_alloc_and_put(dev_t dev, char *name)
--
drivers/md/md.c-6453-
drivers/md/md.c:6454: if (legacy_async_del_gendisk)
drivers/md/md.c:6455: pr_warn("md: async del_gendisk mode will be removed in future, please upgrade to mdadm-4.5+\n");
drivers/md/md.c-6456-
--
drivers/md/md.c=6996=static void md_clean(struct mddev *mddev)
--
drivers/md/md.c-7011- /*
drivers/md/md.c:7012: * For legacy_async_del_gendisk mode, it can stop the array in the
drivers/md/md.c-7013- * middle of assembling it, then it still can access the array. So
drivers/md/md.c:7014: * it needs to clear MD_CLOSING. If not legacy_async_del_gendisk,
drivers/md/md.c-7015- * it can't open the array again after stopping it. So it doesn't
--
drivers/md/md.c-7017- */
drivers/md/md.c:7018: if (legacy_async_del_gendisk && mddev->hold_active) {
drivers/md/md.c-7019- clear_bit(MD_CLOSING, &mddev->flags);
--
drivers/md/md.c=7191=static int do_md_stop(struct mddev *mddev, int mode)
--
drivers/md/md.c-7253- md_clean(mddev);
drivers/md/md.c:7254: if (!legacy_async_del_gendisk)
drivers/md/md.c-7255- set_bit(MD_DELETED, &mddev->flags);
--
drivers/md/md.c=11140=module_param(create_on_open, bool, S_IRUSR|S_IWUSR);
drivers/md/md.c:11141:module_param(legacy_async_del_gendisk, bool, 0600);
drivers/md/md.c-11142-module_param(check_new_feature, bool, 0600);
]
|
| 235/2 |
2026/11/03 18:04 |
llm |
history-explorer |
6m
Model:
Tokens:
input: 75834
output: 26
thoughts: 488
Thoughts: **Analyzing the Data Mapper Device Cleanup Sequence**
Okay, let's break this down. In `cleanup_mapped_device(md)`, we have a mutex protecting `del_gendisk(md->disk)` from concurrent operations in `open/close_table_device()`. That's standard and expected. And this function is only called from `free_dev(md)`, which is at the very end of `__dm_destroy(md, wait)`, after that spinlock, after a check on `md->holders`.
The interesting part is in `__dm_destroy` itself. We're replacing the minor number in the IDR, setting the `DMF_FREEING` flag, and then, crucially, calling `blk_mark_disk_dead(md->disk)`. Now, this is done *before* waiting for `md->holders` to drop to zero! That's the key point. Why are we marking the disk as dead *before* all holders release it? That seems counterintuitive. I need to understand the rationale behind that ordering.
The clue is probably in the commit history for this section of code. I'm going to look up the `git blame` or `git log` on that line in `drivers/md/dm.c`. It's commit `7a5428dcb7902` that changed `blk_set_queue_dying(md->queue)` to `blk_mark_disk_dead(md->disk)`. Before that, I should inspect commit `3f77316de0ec0` to figure out what was changing before the `blk_set_queue_dying` call.
|
| 236/2 |
2026/11/03 18:10 |
tool |
git-show |
0m
Args: map[Commit:3f77316de0ec0]
Results: map[Output:commit 3f77316de0ec0fd208467fbee8d9edc70e2c73b2
Author: Kiyoshi Ueda <k-ueda@ct.jp.nec.com>
Date: Thu Aug 12 04:13:56 2010 +0100
dm: separate device deletion from dm_put
This patch separates the device deletion code from dm_put()
to make sure the deletion happens in the process context.
By this patch, device deletion always occurs in an ioctl (process)
context and dm_put() can be called in interrupt context.
As a result, the request-based dm's bad dm_put() usage pointed out
by Mikulas below disappears.
http://marc.info/?l=dm-devel&m=126699981019735&w=2
Without this patch, I confirmed there is a case to crash the system:
dm_put() => dm_table_destroy() => vfree() => BUG_ON(in_interrupt())
Some more backgrounds and details:
In request-based dm, a device opener can remove a mapped_device
while the last request is still completing, because bios in the last
request complete first and then the device opener can close and remove
the mapped_device before the last request completes:
CPU0 CPU1
=================================================================
<<INTERRUPT>>
blk_end_request_all(clone_rq)
blk_update_request(clone_rq)
bio_endio(clone_bio) == end_clone_bio
blk_update_request(orig_rq)
bio_endio(orig_bio)
<<I/O completed>>
dm_blk_close()
dev_remove()
dm_put(md)
<<Free md>>
blk_finish_request(clone_rq)
....
dm_end_request(clone_rq)
free_rq_clone(clone_rq)
blk_end_request_all(orig_rq)
rq_completed(md)
So request-based dm used dm_get()/dm_put() to hold md for each I/O
until its request completion handling is fully done.
However, the final dm_put() can call the device deletion code which
must not be run in interrupt context and may cause kernel panic.
To solve the problem, this patch moves the device deletion code,
dm_destroy(), to predetermined places that is actually deleting
the mapped_device in ioctl (process) context, and changes dm_put()
just to decrement the reference count of the mapped_device.
By this change, dm_put() can be used in any context and the symmetric
model below is introduced:
dm_create(): create a mapped_device
dm_destroy(): destroy a mapped_device
dm_get(): increment the reference count of a mapped_device
dm_put(): decrement the reference count of a mapped_device
dm_destroy() waits for all references of the mapped_device to disappear,
then deletes the mapped_device.
dm_destroy() uses active waiting with msleep(1), since deleting
the mapped_device isn't performance-critical task.
And since at this point, nobody opens the mapped_device and no new
reference will be taken, the pending counts are just for racing
completing activity and will eventually decrease to zero.
For the unlikely case of the forced module unload, dm_destroy_immediate(),
which doesn't wait and forcibly deletes the mapped_device, is also
introduced and used in dm_hash_remove_all(). Otherwise, "rmmod -f"
may be stuck and never return.
And now, because the mapped_device is deleted at this point, subsequent
accesses to the mapped_device may cause NULL pointer references.
Cc: stable@kernel.org
Signed-off-by: Kiyoshi Ueda <k-ueda@ct.jp.nec.com>
Signed-off-by: Jun'ichi Nomura <j-nomura@ce.jp.nec.com>
Signed-off-by: Alasdair G Kergon <agk@redhat.com>
diff --git a/drivers/md/dm-ioctl.c b/drivers/md/dm-ioctl.c
index 6a6d475f8e80..feb64d65fbfb 100644
--- a/drivers/md/dm-ioctl.c
+++ b/drivers/md/dm-ioctl.c
@@ -274,6 +274,10 @@ static void dm_hash_remove_all(int keep_open_devices)
up_write(&_hash_lock);
dm_put(md);
+ if (likely(keep_open_devices))
+ dm_destroy(md);
+ else
+ dm_destroy_immediate(md);
/*
* Some mapped devices may be using other mapped
@@ -644,17 +648,19 @@ static int dev_create(struct dm_ioctl *param, size_t param_size)
return r;
r = dm_hash_insert(param->name, *param->uuid ? param->uuid : NULL, md);
- if (r)
- goto out;
+ if (r) {
+ dm_put(md);
+ dm_destroy(md);
+ return r;
+ }
param->flags &= ~DM_INACTIVE_PRESENT_FLAG;
__dev_status(md, param);
-out:
dm_put(md);
- return r;
+ return 0;
}
/*
@@ -748,6 +754,7 @@ static int dev_remove(struct dm_ioctl *param, size_t param_size)
param->flags |= DM_UEVENT_GENERATED_FLAG;
dm_put(md);
+ dm_destroy(md);
return 0;
}
diff --git a/drivers/md/dm.c b/drivers/md/dm.c
index ba6934c3e2c5..a503b95ecbfb 100644
--- a/drivers/md/dm.c
+++ b/drivers/md/dm.c
@@ -20,6 +20,7 @@
#include <linux/slab.h>
#include <linux/idr.h>
#include <linux/hdreg.h>
+#include <linux/delay.h>
#include <trace/events/block.h>
@@ -2171,6 +2172,7 @@ void dm_set_mdptr(struct mapped_device *md, void *ptr)
void dm_get(struct mapped_device *md)
{
atomic_inc(&md->holders);
+ BUG_ON(test_bit(DMF_FREEING, &md->flags));
}
const char *dm_device_name(struct mapped_device *md)
@@ -2179,27 +2181,55 @@ const char *dm_device_name(struct mapped_device *md)
}
EXPORT_SYMBOL_GPL(dm_device_name);
-void dm_put(struct mapped_device *md)
+static void __dm_destroy(struct mapped_device *md, bool wait)
{
struct dm_table *map;
- BUG_ON(test_bit(DMF_FREEING, &md->flags));
+ might_sleep();
- if (atomic_dec_and_lock(&md->holders, &_minor_lock)) {
- map = dm_get_live_table(md);
- idr_replace(&_minor_idr, MINOR_ALLOCED,
- MINOR(disk_devt(dm_disk(md))));
- set_bit(DMF_FREEING, &md->flags);
- spin_unlock(&_minor_lock);
- if (!dm_suspended_md(md)) {
- dm_table_presuspend_targets(map);
- dm_table_postsuspend_targets(map);
- }
- dm_sysfs_exit(md);
- dm_table_put(map);
- dm_table_destroy(__unbind(md));
- free_dev(md);
+ spin_lock(&_minor_lock);
+ map = dm_get_live_table(md);
+ idr_replace(&_minor_idr, MINOR_ALLOCED, MINOR(disk_devt(dm_disk(md))));
+ set_bit(DMF_FREEING, &md->flags);
+ spin_unlock(&_minor_lock);
+
+ if (!dm_suspended_md(md)) {
+ dm_table_presuspend_targets(map);
+ dm_table_postsuspend_targets(map);
}
+
+ /*
+ * Rare, but there may be I/O requests still going to complete,
+ * for example. Wait for all references to disappear.
+ * No one should increment the reference count of the mapped_device,
+ * after the mapped_device state becomes DMF_FREEING.
+ */
+ if (wait)
+ while (atomic_read(&md->holders))
+ msleep(1);
+ else if (atomic_read(&md->holders))
+ DMWARN("%s: Forcibly removing mapped_device still in use! (%d users)",
+ dm_device_name(md), atomic_read(&md->holders));
+
+ dm_sysfs_exit(md);
+ dm_table_put(map);
+ dm_table_destroy(__unbind(md));
+ free_dev(md);
+}
+
+void dm_destroy(struct mapped_device *md)
+{
+ __dm_destroy(md, true);
+}
+
+void dm_destroy_immediate(struct mapped_device *md)
+{
+ __dm_destroy(md, false);
+}
+
+void dm_put(struct mapped_device *md)
+{
+ atomic_dec(&md->holders);
}
EXPORT_SYMBOL_GPL(dm_put);
diff --git a/drivers/md/dm.h b/drivers/md/dm.h
index bad1724d4869..8223671e4901 100644
--- a/drivers/md/dm.h
+++ b/drivers/md/dm.h
@@ -122,6 +122,11 @@ void dm_linear_exit(void);
int dm_stripe_init(void);
void dm_stripe_exit(void);
+/*
+ * mapped_device operations
+ */
+void dm_destroy(struct mapped_device *md);
+void dm_destroy_immediate(struct mapped_device *md);
int dm_open_count(struct mapped_device *md);
int dm_lock_for_deletion(struct mapped_device *md);
]
|
| 237/2 |
2026/11/03 18:10 |
llm |
history-explorer |
2m
Model:
Tokens:
input: 79460
output: 26
thoughts: 62
Thoughts: Here's a summary of my thought process, as requested:
**Diving into the History of `blk_set_queue_dying` in `__dm_destroy`**
Okay, so I need to understand why this `blk_set_queue_dying` call was added to `__dm_destroy`. I remember vaguely something about a race condition or a specific issue, but I need to refresh my memory and pinpoint the exact commit. Let's start by digging into the Git history. I'm going to pull up the commit, which I think starts with `3b785fbcf81c3`, or something similar. Then I can use `git show` to read the commit message, the diff, and try to jog my memory and understand the context. Hopefully the commit message is clear enough to point me in the right direction. It's time to get a bit more granular here.
|
| 238/2 |
2026/11/03 18:12 |
tool |
git-show |
0m
Args: map[Commit:3b785fbcf81c3]
Results: map[Output:commit 3b785fbcf81c3533772c52b717f77293099498d3
Author: Bart Van Assche <bvanassche@acm.org>
Date: Wed Aug 31 15:17:49 2016 -0700
dm: mark request_queue dead before destroying the DM device
This avoids that new requests are queued while __dm_destroy() is in
progress.
Signed-off-by: Bart Van Assche <bart.vanassche@sandisk.com>
Signed-off-by: Mike Snitzer <snitzer@redhat.com>
Cc: stable@vger.kernel.org
diff --git a/drivers/md/dm.c b/drivers/md/dm.c
index c0742129a9cb..0f2928b3136b 100644
--- a/drivers/md/dm.c
+++ b/drivers/md/dm.c
@@ -1873,6 +1873,7 @@ EXPORT_SYMBOL_GPL(dm_device_name);
static void __dm_destroy(struct mapped_device *md, bool wait)
{
+ struct request_queue *q = dm_get_md_queue(md);
struct dm_table *map;
int srcu_idx;
@@ -1883,6 +1884,10 @@ static void __dm_destroy(struct mapped_device *md, bool wait)
set_bit(DMF_FREEING, &md->flags);
spin_unlock(&_minor_lock);
+ spin_lock_irq(q->queue_lock);
+ queue_flag_set(QUEUE_FLAG_DYING, q);
+ spin_unlock_irq(q->queue_lock);
+
if (dm_request_based(md) && md->kworker_task)
flush_kthread_worker(&md->kworker);
]
|
| 239/2 |
2026/11/03 18:13 |
llm |
history-explorer |
8m
Model:
Tokens:
input: 80264
output: 43
thoughts: 2519
Thoughts: **Analyzing the Block Layer Lockdep Design**
Okay, let's dive deep into the `block` layer's lockdep design, specifically focusing on `blk_freeze_acquire_lock` and `blk_unfreeze_release_lock`. I need to understand the interaction between these functions, particularly in the context of `blk-mq.c`. I see `__blk_freeze_queue_start` and `__blk_mq_unfreeze_queue` which appear to handle freezing and unfreezing of request queues, and they both use a mutex (`q->mq_freeze_lock`).
A crucial question pops up: why is `blk_unfreeze_release_lock` being called *outside* the scope of `q->mq_freeze_lock`? Is this required? Can `rwsem_release` be safely called while holding the `q->mq_freeze_lock`? I see that `rwsem_release` is simply releasing the lockdep map.
My attention is drawn to `del_gendisk` where I see `blk_freeze_acquire_lock` being called within a critical section. Now I'm focused on the history. Commit `f1be1788a32e` is where the current logic was introduced, which then evolved in commits `6f491a8d4b92` and `f6661b1d0525` where the booleans for disk and queue state were removed from the API, and new members were added to the `request_queue` struct instead.
The commit messages from those changes cite the desire to only verify the outmost freeze/unfreeze in the current context, and they aim to save disk and queue state reliably. The logic seemed to make sense initially, but, now, I see a flaw.
Here's the problem: The *state* of `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying` is *stored in the queue*, not the current task. When `__blk_mq_unfreeze_queue()` decrements `q->mq_freeze_depth` to 0, it *releases* the `q->mq_freeze_lock*. After that, *another* task *can immediately* call `__blk_freeze_queue_start(q, current)`. This new task *acquires* the lock and *overwrites* `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead`. Then, the first task can read these overwritten values when it calls `blk_unfreeze_release_lock(q)`. That's a classic race condition.
I need to confirm if this is the only race. What happens if operations like `del_gendisk` or `blk_mark_disk_dead` occur while the queue is frozen? If `blk_mark_disk_dead` is called while the queue is frozen, `blk_freeze_set_owner` will *not* write to the `q->mq_freeze_queue_dying`, because the queue isn't *completely* unfrozen.
However, a scenario comes to mind:
* Thread 1: Freeze is at depth 1.
* Thread 2: Calls `blk_mark_disk_dead`, which calls `__blk_freeze_queue_start` and *increments* `q->mq_freeze_depth` to 2.
In the unfreeze path, the freeze depth will get decremented from 2 to 1 and the owner is still Thread 1 which calls `blk_unfreeze_release_lock` and the race happens. It is still possible that thread 2 overwrites state when it calls `__blk_freeze_queue_start`.
I now look at `blk_unfreeze_check_owner`. If another thread calls `__blk_freeze_queue_start` in the middle of this and increments freeze depth, the problem is still there.
Okay, I need to expand my search. I'm going to search the `block` layer's git history for commits that touch `rwsem_release`, `rwsem_acquire`, `lockdep`, or phrases like "lock held when returning to user space," combined with "freeze," to see if there are similar lock-related issues. I need to be sure I'm not missing anything.
|
| 240/2 |
2026/11/03 18:21 |
tool |
git-log |
0m
Args: map[Count:20 MessageRegexps:[lockdep freeze] PathPrefix:block/ Since:3 years]
Results: map[Output:3dd63dba8f9c block: avoid potential deadlock on zone revalidation failure
539d1b47e935 block: break pcpu_alloc_mutex dependency on freeze_lock
d4c3ef56a161 block: define alloc_sched_data and free_sched_data methods for kyber
61019afdf6ac block: introduce alloc_sched_data and free_sched_data elevator methods
5d726c4dbeed blk-cgroup: fix possible deadlock while configuring policy
370ac285f23a block: avoid cpu_hotplug_lock depedency on freeze_lock
2d82f3bd8910 blk-mq: fix lockdep warning in __blk_mq_update_nr_hw_queues
04225d13aef1 block: fix potential deadlock while running nr_hw_queue update
f5a6604f7a44 block: fix lockdep warning caused by lock dependency in elv_iosched_store
2d8951aee844 block: unfreeze queue if realloc tag set fails during nr_hw_queues update
7ed7fa561c35 block: move hctx cpuhp add/del out of queue freezing
01b91bf14f6d block: don't grab elevator lock during queue initialization
9730763f4756 block: correct locking order for protecting blk-wbt parameters
ffa1e7ada456 block: Make request_queue lockdep splats show up earlier
1bf70d08cc3b block: introduce a dedicated lock for protecting queue elevator updates
f6661b1d0525 block: track queue dying state automatically for modeling queue freeze lockdep
6f491a8d4b92 block: track disk DEAD state automatically for modeling queue freeze lockdep
be26ba96421a block: Fix potential deadlock while freezing queue and acquiring sysfs_lock
0b83c86b444a block: Prevent potential deadlock in blk_revalidate_disk_zones()
357e1b7f730b block: don't verify IO lock for freeze/unfreeze in elevator_init_mq()
]
|
| 241/2 |
2026/11/03 18:21 |
llm |
history-explorer |
3m
Model:
Tokens:
input: 84319
output: 26
thoughts: 46
Thoughts: Okay, let's dive into these commits: `be26ba96421a`, `0b83c86b444a`, and `2d82f3bd8910`. I need to understand what's changed and what the implications are. Given my expertise in [**insert the user's field**], I should be able to quickly analyze these commits and understand their relevance. I'm going to look for key modifications, any new features implemented, bugs fixed, or performance changes. I'll pay close attention to the context of these commits to identify any dependencies on other modules or processes and see how these commits integrate with the larger architecture and workflow. From there, I can determine if any specific considerations are warranted.
|
| 242/2 |
2026/11/03 18:25 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 2d82f3bd8910eb65e30bb2a3c9b945bfb3b6d661
Author: Ming Lei <ming.lei@redhat.com>
Date: Fri Aug 15 21:17:37 2025 +0800
blk-mq: fix lockdep warning in __blk_mq_update_nr_hw_queues
Commit 5989bfe6ac6b ("block: restore two stage elevator switch while
running nr_hw_queue update") reintroduced a lockdep warning by calling
blk_mq_freeze_queue_nomemsave() before switching the I/O scheduler.
The function blk_mq_elv_switch_none() calls elevator_change_done().
Running this while the queue is frozen causes a lockdep warning.
Fix this by reordering the operations: first, switch the I/O scheduler
to 'none', and then freeze the queue. This ensures that elevator_change_done()
is not called on an already frozen queue. And this way is safe because
elevator_set_none() does freeze queue before switching to none.
Also we still have to rely on blk_mq_elv_switch_back() for switching
back, and it has to cover unfrozen queue case.
Cc: Nilay Shroff <nilay@linux.ibm.com>
Cc: Yu Kuai <yukuai3@huawei.com>
Fixes: 5989bfe6ac6b ("block: restore two stage elevator switch while running nr_hw_queue update")
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Reviewed-by: Yu Kuai <yukuai3@huawei.com>
Reviewed-by: Nilay Shroff <nilay@linux.ibm.com>
Link: https://lore.kernel.org/r/20250815131737.331692-1-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-mq.c b/block/blk-mq.c
index b67d6c02eceb..ba3a4b77f578 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -5033,6 +5033,7 @@ static void __blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set,
unsigned int memflags;
int i;
struct xarray elv_tbl, et_tbl;
+ bool queues_frozen = false;
lockdep_assert_held(&set->tag_list_lock);
@@ -5056,9 +5057,6 @@ static void __blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set,
blk_mq_sysfs_unregister_hctxs(q);
}
- list_for_each_entry(q, &set->tag_list, tag_set_list)
- blk_mq_freeze_queue_nomemsave(q);
-
/*
* Switch IO scheduler to 'none', cleaning up the data associated
* with the previous scheduler. We will switch back once we are done
@@ -5068,6 +5066,9 @@ static void __blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set,
if (blk_mq_elv_switch_none(q, &elv_tbl))
goto switch_back;
+ list_for_each_entry(q, &set->tag_list, tag_set_list)
+ blk_mq_freeze_queue_nomemsave(q);
+ queues_frozen = true;
if (blk_mq_realloc_tag_set_tags(set, nr_hw_queues) < 0)
goto switch_back;
@@ -5091,8 +5092,12 @@ static void __blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set,
}
switch_back:
/* The blk_mq_elv_switch_back unfreezes queue for us. */
- list_for_each_entry(q, &set->tag_list, tag_set_list)
+ list_for_each_entry(q, &set->tag_list, tag_set_list) {
+ /* switch_back expects queue to be frozen */
+ if (!queues_frozen)
+ blk_mq_freeze_queue_nomemsave(q);
blk_mq_elv_switch_back(q, &elv_tbl, &et_tbl);
+ }
list_for_each_entry(q, &set->tag_list, tag_set_list) {
blk_mq_sysfs_register_hctxs(q);
]
|
| 243/2 |
2026/11/03 18:25 |
llm |
history-explorer |
13m
Model:
Tokens:
input: 85832
output: 25
thoughts: 20
Thoughts: Okay, here's my interpretation of that request, formatted as requested:
**Digging into Commit History**
Alright, I need to take a look at commit `be26ba96421a`. I know the project and codebase pretty well, and based on the context, I'm already anticipating what might be in that commit. However, a quick check of the diff will confirm, or maybe surprise me. I'm going to quickly review the code changes and the commit message - just to make sure the fix or feature that was implemented is what I think it is. This is all part of the due diligence. Need to verify that I'm on the same page as the original committer, and to ensure there's no misunderstanding. Let's see what's there...
|
| 244/2 |
2026/11/03 18:39 |
tool |
git-show |
0m
Args:
Results: map[Output:commit be26ba96421ab0a8fa2055ccf7db7832a13c44d2
Author: Nilay Shroff <nilay@linux.ibm.com>
Date: Tue Dec 10 20:11:43 2024 +0530
block: Fix potential deadlock while freezing queue and acquiring sysfs_lock
For storing a value to a queue attribute, the queue_attr_store function
first freezes the queue (->q_usage_counter(io)) and then acquire
->sysfs_lock. This seems not correct as the usual ordering should be to
acquire ->sysfs_lock before freezing the queue. This incorrect ordering
causes the following lockdep splat which we are able to reproduce always
simply by accessing /sys/kernel/debug file using ls command:
[ 57.597146] WARNING: possible circular locking dependency detected
[ 57.597154] 6.12.0-10553-gb86545e02e8c #20 Tainted: G W
[ 57.597162] ------------------------------------------------------
[ 57.597168] ls/4605 is trying to acquire lock:
[ 57.597176] c00000003eb56710 (&mm->mmap_lock){++++}-{4:4}, at: __might_fault+0x58/0xc0
[ 57.597200]
but task is already holding lock:
[ 57.597207] c0000018e27c6810 (&sb->s_type->i_mutex_key#3){++++}-{4:4}, at: iterate_dir+0x94/0x1d4
[ 57.597226]
which lock already depends on the new lock.
[ 57.597233]
the existing dependency chain (in reverse order) is:
[ 57.597241]
-> #5 (&sb->s_type->i_mutex_key#3){++++}-{4:4}:
[ 57.597255] down_write+0x6c/0x18c
[ 57.597264] start_creating+0xb4/0x24c
[ 57.597274] debugfs_create_dir+0x2c/0x1e8
[ 57.597283] blk_register_queue+0xec/0x294
[ 57.597292] add_disk_fwnode+0x2e4/0x548
[ 57.597302] brd_alloc+0x2c8/0x338
[ 57.597309] brd_init+0x100/0x178
[ 57.597317] do_one_initcall+0x88/0x3e4
[ 57.597326] kernel_init_freeable+0x3cc/0x6e0
[ 57.597334] kernel_init+0x34/0x1cc
[ 57.597342] ret_from_kernel_user_thread+0x14/0x1c
[ 57.597350]
-> #4 (&q->debugfs_mutex){+.+.}-{4:4}:
[ 57.597362] __mutex_lock+0xfc/0x12a0
[ 57.597370] blk_register_queue+0xd4/0x294
[ 57.597379] add_disk_fwnode+0x2e4/0x548
[ 57.597388] brd_alloc+0x2c8/0x338
[ 57.597395] brd_init+0x100/0x178
[ 57.597402] do_one_initcall+0x88/0x3e4
[ 57.597410] kernel_init_freeable+0x3cc/0x6e0
[ 57.597418] kernel_init+0x34/0x1cc
[ 57.597426] ret_from_kernel_user_thread+0x14/0x1c
[ 57.597434]
-> #3 (&q->sysfs_lock){+.+.}-{4:4}:
[ 57.597446] __mutex_lock+0xfc/0x12a0
[ 57.597454] queue_attr_store+0x9c/0x110
[ 57.597462] sysfs_kf_write+0x70/0xb0
[ 57.597471] kernfs_fop_write_iter+0x1b0/0x2ac
[ 57.597480] vfs_write+0x3dc/0x6e8
[ 57.597488] ksys_write+0x84/0x140
[ 57.597495] system_call_exception+0x130/0x360
[ 57.597504] system_call_common+0x160/0x2c4
[ 57.597516]
-> #2 (&q->q_usage_counter(io)#21){++++}-{0:0}:
[ 57.597530] __submit_bio+0x5ec/0x828
[ 57.597538] submit_bio_noacct_nocheck+0x1e4/0x4f0
[ 57.597547] iomap_readahead+0x2a0/0x448
[ 57.597556] xfs_vm_readahead+0x28/0x3c
[ 57.597564] read_pages+0x88/0x41c
[ 57.597571] page_cache_ra_unbounded+0x1ac/0x2d8
[ 57.597580] filemap_get_pages+0x188/0x984
[ 57.597588] filemap_read+0x13c/0x4bc
[ 57.597596] xfs_file_buffered_read+0x88/0x17c
[ 57.597605] xfs_file_read_iter+0xac/0x158
[ 57.597614] vfs_read+0x2d4/0x3b4
[ 57.597622] ksys_read+0x84/0x144
[ 57.597629] system_call_exception+0x130/0x360
[ 57.597637] system_call_common+0x160/0x2c4
[ 57.597647]
-> #1 (mapping.invalidate_lock#2){++++}-{4:4}:
[ 57.597661] down_read+0x6c/0x220
[ 57.597669] filemap_fault+0x870/0x100c
[ 57.597677] xfs_filemap_fault+0xc4/0x18c
[ 57.597684] __do_fault+0x64/0x164
[ 57.597693] __handle_mm_fault+0x1274/0x1dac
[ 57.597702] handle_mm_fault+0x248/0x484
[ 57.597711] ___do_page_fault+0x428/0xc0c
[ 57.597719] hash__do_page_fault+0x30/0x68
[ 57.597727] do_hash_fault+0x90/0x35c
[ 57.597736] data_access_common_virt+0x210/0x220
[ 57.597745] _copy_from_user+0xf8/0x19c
[ 57.597754] sel_write_load+0x178/0xd54
[ 57.597762] vfs_write+0x108/0x6e8
[ 57.597769] ksys_write+0x84/0x140
[ 57.597777] system_call_exception+0x130/0x360
[ 57.597785] system_call_common+0x160/0x2c4
[ 57.597794]
-> #0 (&mm->mmap_lock){++++}-{4:4}:
[ 57.597806] __lock_acquire+0x17cc/0x2330
[ 57.597814] lock_acquire+0x138/0x400
[ 57.597822] __might_fault+0x7c/0xc0
[ 57.597830] filldir64+0xe8/0x390
[ 57.597839] dcache_readdir+0x80/0x2d4
[ 57.597846] iterate_dir+0xd8/0x1d4
[ 57.597855] sys_getdents64+0x88/0x2d4
[ 57.597864] system_call_exception+0x130/0x360
[ 57.597872] system_call_common+0x160/0x2c4
[ 57.597881]
other info that might help us debug this:
[ 57.597888] Chain exists of:
&mm->mmap_lock --> &q->debugfs_mutex --> &sb->s_type->i_mutex_key#3
[ 57.597905] Possible unsafe locking scenario:
[ 57.597911] CPU0 CPU1
[ 57.597917] ---- ----
[ 57.597922] rlock(&sb->s_type->i_mutex_key#3);
[ 57.597932] lock(&q->debugfs_mutex);
[ 57.597940] lock(&sb->s_type->i_mutex_key#3);
[ 57.597950] rlock(&mm->mmap_lock);
[ 57.597958]
*** DEADLOCK ***
[ 57.597965] 2 locks held by ls/4605:
[ 57.597971] #0: c0000000137c12f8 (&f->f_pos_lock){+.+.}-{4:4}, at: fdget_pos+0xcc/0x154
[ 57.597989] #1: c0000018e27c6810 (&sb->s_type->i_mutex_key#3){++++}-{4:4}, at: iterate_dir+0x94/0x1d4
Prevent the above lockdep warning by acquiring ->sysfs_lock before
freezing the queue while storing a queue attribute in queue_attr_store
function. Later, we also found[1] another function __blk_mq_update_nr_
hw_queues where we first freeze queue and then acquire the ->sysfs_lock.
So we've also updated lock ordering in __blk_mq_update_nr_hw_queues
function and ensured that in all code paths we follow the correct lock
ordering i.e. acquire ->sysfs_lock before freezing the queue.
[1] https://lore.kernel.org/all/CAFj5m9Ke8+EHKQBs_Nk6hqd=LGXtk4mUxZUN5==ZcCjnZSBwHw@mail.gmail.com/
Reported-by: kjain@linux.ibm.com
Fixes: af2814149883 ("block: freeze the queue in queue_attr_store")
Tested-by: kjain@linux.ibm.com
Cc: hch@lst.de
Cc: axboe@kernel.dk
Cc: ritesh.list@gmail.com
Cc: ming.lei@redhat.com
Cc: gjoyce@linux.ibm.com
Signed-off-by: Nilay Shroff <nilay@linux.ibm.com>
Reviewed-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241210144222.1066229-1-nilay@linux.ibm.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-mq-sysfs.c b/block/blk-mq-sysfs.c
index 156e9bb07abf..cd5ea6eaa76b 100644
--- a/block/blk-mq-sysfs.c
+++ b/block/blk-mq-sysfs.c
@@ -275,15 +275,13 @@ void blk_mq_sysfs_unregister_hctxs(struct request_queue *q)
struct blk_mq_hw_ctx *hctx;
unsigned long i;
- mutex_lock(&q->sysfs_dir_lock);
+ lockdep_assert_held(&q->sysfs_dir_lock);
+
if (!q->mq_sysfs_init_done)
- goto unlock;
+ return;
queue_for_each_hw_ctx(q, hctx, i)
blk_mq_unregister_hctx(hctx);
-
-unlock:
- mutex_unlock(&q->sysfs_dir_lock);
}
int blk_mq_sysfs_register_hctxs(struct request_queue *q)
@@ -292,9 +290,10 @@ int blk_mq_sysfs_register_hctxs(struct request_queue *q)
unsigned long i;
int ret = 0;
- mutex_lock(&q->sysfs_dir_lock);
+ lockdep_assert_held(&q->sysfs_dir_lock);
+
if (!q->mq_sysfs_init_done)
- goto unlock;
+ return ret;
queue_for_each_hw_ctx(q, hctx, i) {
ret = blk_mq_register_hctx(hctx);
@@ -302,8 +301,5 @@ int blk_mq_sysfs_register_hctxs(struct request_queue *q)
break;
}
-unlock:
- mutex_unlock(&q->sysfs_dir_lock);
-
return ret;
}
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 92e8ddf34575..6b6111513986 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -4453,7 +4453,8 @@ static void blk_mq_realloc_hw_ctxs(struct blk_mq_tag_set *set,
unsigned long i, j;
/* protect against switching io scheduler */
- mutex_lock(&q->sysfs_lock);
+ lockdep_assert_held(&q->sysfs_lock);
+
for (i = 0; i < set->nr_hw_queues; i++) {
int old_node;
int node = blk_mq_get_hctx_node(set, i);
@@ -4486,7 +4487,6 @@ static void blk_mq_realloc_hw_ctxs(struct blk_mq_tag_set *set,
xa_for_each_start(&q->hctx_table, j, hctx, j)
blk_mq_exit_hctx(q, set, hctx, j);
- mutex_unlock(&q->sysfs_lock);
/* unregister cpuhp callbacks for exited hctxs */
blk_mq_remove_hw_queues_cpuhp(q);
@@ -4518,10 +4518,14 @@ int blk_mq_init_allocated_queue(struct blk_mq_tag_set *set,
xa_init(&q->hctx_table);
+ mutex_lock(&q->sysfs_lock);
+
blk_mq_realloc_hw_ctxs(set, q);
if (!q->nr_hw_queues)
goto err_hctxs;
+ mutex_unlock(&q->sysfs_lock);
+
INIT_WORK(&q->timeout_work, blk_mq_timeout_work);
blk_queue_rq_timeout(q, set->timeout ? set->timeout : 30 * HZ);
@@ -4540,6 +4544,7 @@ int blk_mq_init_allocated_queue(struct blk_mq_tag_set *set,
return 0;
err_hctxs:
+ mutex_unlock(&q->sysfs_lock);
blk_mq_release(q);
err_exit:
q->mq_ops = NULL;
@@ -4920,12 +4925,12 @@ static bool blk_mq_elv_switch_none(struct list_head *head,
return false;
/* q->elevator needs protection from ->sysfs_lock */
- mutex_lock(&q->sysfs_lock);
+ lockdep_assert_held(&q->sysfs_lock);
/* the check has to be done with holding sysfs_lock */
if (!q->elevator) {
kfree(qe);
- goto unlock;
+ goto out;
}
INIT_LIST_HEAD(&qe->node);
@@ -4935,9 +4940,7 @@ static bool blk_mq_elv_switch_none(struct list_head *head,
__elevator_get(qe->type);
list_add(&qe->node, head);
elevator_disable(q);
-unlock:
- mutex_unlock(&q->sysfs_lock);
-
+out:
return true;
}
@@ -4966,11 +4969,9 @@ static void blk_mq_elv_switch_back(struct list_head *head,
list_del(&qe->node);
kfree(qe);
- mutex_lock(&q->sysfs_lock);
elevator_switch(q, t);
/* drop the reference acquired in blk_mq_elv_switch_none */
elevator_put(t);
- mutex_unlock(&q->sysfs_lock);
}
static void __blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set,
@@ -4990,8 +4991,11 @@ static void __blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set,
if (set->nr_maps == 1 && nr_hw_queues == set->nr_hw_queues)
return;
- list_for_each_entry(q, &set->tag_list, tag_set_list)
+ list_for_each_entry(q, &set->tag_list, tag_set_list) {
+ mutex_lock(&q->sysfs_dir_lock);
+ mutex_lock(&q->sysfs_lock);
blk_mq_freeze_queue(q);
+ }
/*
* Switch IO scheduler to 'none', cleaning up the data associated
* with the previous scheduler. We will switch back once we are done
@@ -5047,8 +5051,11 @@ static void __blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set,
list_for_each_entry(q, &set->tag_list, tag_set_list)
blk_mq_elv_switch_back(&head, q);
- list_for_each_entry(q, &set->tag_list, tag_set_list)
+ list_for_each_entry(q, &set->tag_list, tag_set_list) {
blk_mq_unfreeze_queue(q);
+ mutex_unlock(&q->sysfs_lock);
+ mutex_unlock(&q->sysfs_dir_lock);
+ }
/* Free the excess tags when nr_hw_queues shrink. */
for (i = set->nr_hw_queues; i < prev_nr_hw_queues; i++)
diff --git a/block/blk-sysfs.c b/block/blk-sysfs.c
index 767598e719ab..64f70c713d2f 100644
--- a/block/blk-sysfs.c
+++ b/block/blk-sysfs.c
@@ -706,11 +706,11 @@ queue_attr_store(struct kobject *kobj, struct attribute *attr,
if (entry->load_module)
entry->load_module(disk, page, length);
- blk_mq_freeze_queue(q);
mutex_lock(&q->sysfs_lock);
+ blk_mq_freeze_queue(q);
res = entry->store(disk, page, length);
- mutex_unlock(&q->sysfs_lock);
blk_mq_unfreeze_queue(q);
+ mutex_unlock(&q->sysfs_lock);
return res;
}
]
|
| 245/2 |
2026/11/03 18:39 |
llm |
history-explorer |
2m
Model:
Tokens:
input: 92091
output: 27
thoughts: 22
Thoughts: Okay, let's dive into this. I've been working through this sequence, and I need to methodically check this next one: `0b83c86b444a`. It's a key step in this process. I'm already formulating my hypothesis around the surrounding elements, but to proceed, I'll need to deeply analyze this binary representation. My expertise has enabled me to develop a keen understanding of similar representations; I can likely make some inferences just by seeing the sequence. Still, I'll need to carefully dissect each section of this data to ensure there aren't any anomalies.
|
| 246/2 |
2026/11/03 18:42 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 0b83c86b444ab467134b0e618f45ad2216a4973c
Author: Damien Le Moal <dlemoal@kernel.org>
Date: Tue Nov 26 19:47:05 2024 +0900
block: Prevent potential deadlock in blk_revalidate_disk_zones()
The function blk_revalidate_disk_zones() calls the function
disk_update_zone_resources() after freezing the device queue. In turn,
disk_update_zone_resources() calls queue_limits_start_update() which
takes a queue limits mutex lock, resulting in the ordering:
q->q_usage_counter check -> q->limits_lock. However, the usual ordering
is to always take a queue limit lock before freezing the queue to commit
the limits updates, e.g., the code pattern:
lim = queue_limits_start_update(q);
...
blk_mq_freeze_queue(q);
ret = queue_limits_commit_update(q, &lim);
blk_mq_unfreeze_queue(q);
Thus, blk_revalidate_disk_zones() introduces a potential circular
locking dependency deadlock that lockdep sometimes catches with the
splat:
[ 51.934109] ======================================================
[ 51.935916] WARNING: possible circular locking dependency detected
[ 51.937561] 6.12.0+ #2107 Not tainted
[ 51.938648] ------------------------------------------------------
[ 51.940351] kworker/u16:4/157 is trying to acquire lock:
[ 51.941805] ffff9fff0aa0bea8 (&q->limits_lock){+.+.}-{4:4}, at: disk_update_zone_resources+0x86/0x170
[ 51.944314]
but task is already holding lock:
[ 51.945688] ffff9fff0aa0b890 (&q->q_usage_counter(queue)#3){++++}-{0:0}, at: blk_revalidate_disk_zones+0x15f/0x340
[ 51.948527]
which lock already depends on the new lock.
[ 51.951296]
the existing dependency chain (in reverse order) is:
[ 51.953708]
-> #1 (&q->q_usage_counter(queue)#3){++++}-{0:0}:
[ 51.956131] blk_queue_enter+0x1c9/0x1e0
[ 51.957290] blk_mq_alloc_request+0x187/0x2a0
[ 51.958365] scsi_execute_cmd+0x78/0x490 [scsi_mod]
[ 51.959514] read_capacity_16+0x111/0x410 [sd_mod]
[ 51.960693] sd_revalidate_disk.isra.0+0x872/0x3240 [sd_mod]
[ 51.962004] sd_probe+0x2d7/0x520 [sd_mod]
[ 51.962993] really_probe+0xd5/0x330
[ 51.963898] __driver_probe_device+0x78/0x110
[ 51.964925] driver_probe_device+0x1f/0xa0
[ 51.965916] __driver_attach_async_helper+0x60/0xe0
[ 51.967017] async_run_entry_fn+0x2e/0x140
[ 51.968004] process_one_work+0x21f/0x5a0
[ 51.968987] worker_thread+0x1dc/0x3c0
[ 51.969868] kthread+0xe0/0x110
[ 51.970377] ret_from_fork+0x31/0x50
[ 51.970983] ret_from_fork_asm+0x11/0x20
[ 51.971587]
-> #0 (&q->limits_lock){+.+.}-{4:4}:
[ 51.972479] __lock_acquire+0x1337/0x2130
[ 51.973133] lock_acquire+0xc5/0x2d0
[ 51.973691] __mutex_lock+0xda/0xcf0
[ 51.974300] disk_update_zone_resources+0x86/0x170
[ 51.975032] blk_revalidate_disk_zones+0x16c/0x340
[ 51.975740] sd_zbc_revalidate_zones+0x73/0x160 [sd_mod]
[ 51.976524] sd_revalidate_disk.isra.0+0x465/0x3240 [sd_mod]
[ 51.977824] sd_probe+0x2d7/0x520 [sd_mod]
[ 51.978917] really_probe+0xd5/0x330
[ 51.979915] __driver_probe_device+0x78/0x110
[ 51.981047] driver_probe_device+0x1f/0xa0
[ 51.982143] __driver_attach_async_helper+0x60/0xe0
[ 51.983282] async_run_entry_fn+0x2e/0x140
[ 51.984319] process_one_work+0x21f/0x5a0
[ 51.985873] worker_thread+0x1dc/0x3c0
[ 51.987289] kthread+0xe0/0x110
[ 51.988546] ret_from_fork+0x31/0x50
[ 51.989926] ret_from_fork_asm+0x11/0x20
[ 51.991376]
other info that might help us debug this:
[ 51.994127] Possible unsafe locking scenario:
[ 51.995651] CPU0 CPU1
[ 51.996694] ---- ----
[ 51.997716] lock(&q->q_usage_counter(queue)#3);
[ 51.998817] lock(&q->limits_lock);
[ 52.000043] lock(&q->q_usage_counter(queue)#3);
[ 52.001638] lock(&q->limits_lock);
[ 52.002485]
*** DEADLOCK ***
Prevent this issue by moving the calls to blk_mq_freeze_queue() and
blk_mq_unfreeze_queue() around the call to queue_limits_commit_update()
in disk_update_zone_resources(). In case of revalidation failure, the
call to disk_free_zone_resources() in blk_revalidate_disk_zones()
is still done with the queue frozen as before.
Fixes: 843283e96e5a ("block: Fake max open zones limit when there is no limit")
Cc: stable@vger.kernel.org
Signed-off-by: Damien Le Moal <dlemoal@kernel.org>
Reviewed-by: Christoph Hellwig <hch@lst.de>
Link: https://lore.kernel.org/r/20241126104705.183996-1-dlemoal@kernel.org
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-zoned.c b/block/blk-zoned.c
index 70211751df16..263e28b72053 100644
--- a/block/blk-zoned.c
+++ b/block/blk-zoned.c
@@ -1551,6 +1551,7 @@ static int disk_update_zone_resources(struct gendisk *disk,
unsigned int nr_seq_zones, nr_conv_zones;
unsigned int pool_size;
struct queue_limits lim;
+ int ret;
disk->nr_zones = args->nr_zones;
disk->zone_capacity = args->zone_capacity;
@@ -1601,7 +1602,11 @@ static int disk_update_zone_resources(struct gendisk *disk,
}
commit:
- return queue_limits_commit_update(q, &lim);
+ blk_mq_freeze_queue(q);
+ ret = queue_limits_commit_update(q, &lim);
+ blk_mq_unfreeze_queue(q);
+
+ return ret;
}
static int blk_revalidate_conv_zone(struct blk_zone *zone, unsigned int idx,
@@ -1816,14 +1821,15 @@ int blk_revalidate_disk_zones(struct gendisk *disk)
* Set the new disk zone parameters only once the queue is frozen and
* all I/Os are completed.
*/
- blk_mq_freeze_queue(q);
if (ret > 0)
ret = disk_update_zone_resources(disk, &args);
else
pr_warn("%s: failed to revalidate zones\n", disk->disk_name);
- if (ret)
+ if (ret) {
+ blk_mq_freeze_queue(q);
disk_free_zone_resources(disk);
- blk_mq_unfreeze_queue(q);
+ blk_mq_unfreeze_queue(q);
+ }
return ret;
}
]
|
| 247/2 |
2026/11/03 18:42 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 95110
output: 43
thoughts: 57
Thoughts: Okay, here's my take on those thoughts, framed as an expert's internal monologue:
**Investigating Potential Data Loss Vulnerabilities in the Device Mapper Code**
Alright, time to get serious. I need to dig into the Device Mapper code, specifically focusing on potential race conditions related to object deletion and freeing. I'm going to start by scrutinizing the `git-log` history for both `drivers/md/dm-ioctl.c` and `drivers/md/dm.c`. My aim is to track down any instances where the functions `dm_lock_for_deletion`, `DMF_DELETING`, or `DMF_FREEING` are used. These are all alarm bells for me. They scream "critical section," "resource management," and potential for data corruption if not handled meticulously. I need to see how these flags and locks have been used, introduced, and potentially modified over time. Any history around those keywords is going to be incredibly important for understanding the deletion process, potential edge cases, and past vulnerabilities. I'm thinking I'll start by checking the git logs for these key terms and see what comes up.
|
| 248/2 |
2026/11/03 18:42 |
tool |
git-log |
0m
Args: map[CodeRegexp:DMF_FREEING Count:10 PathPrefix:drivers/md/ Since:3 years]
Results: map[Output:44b43ec132f1 dm: fix resume-vs-remove race
]
|
| 249/2 |
2026/11/03 18:42 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 95484
output: 44
thoughts: 17
Thoughts: Here's a summary of my thought process, as requested:
**Searching Git Logs**
Okay, I need to investigate something. My initial instinct is to dig through the git logs. Specifically, I'm looking for a particular string, `DMF_DELETING`. This suggests that I'm trying to track down a code deletion or removal related to something tagged with "DMF". It could be a specific feature, module, or potentially even a variable/constant. Finding where and when this deletion occurred is crucial for understanding the history of the code in question, pinpointing the reason for removal (hopefully the commit message is helpful!), and potentially identifying any related regressions or unintended consequences. This initial search in git-log will hopefully give me the context I need to proceed with the investigation.
|
| 250/2 |
2026/11/03 18:43 |
tool |
git-log |
0m
Args: map[CodeRegexp:DMF_DELETING Count:10 PathPrefix:drivers/md/ Since:3 years]
Results:
|
| 251/2 |
2026/11/03 18:43 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 95720
output: 30
thoughts: 21
Thoughts: Here's my thought process, as if I were delving into this code:
**Locating the `DMF_DELETING` Flag within the `drivers/md/` Directory**
Okay, so I need to find where the `DMF_DELETING` macro is being used, specifically within the `drivers/md/` directory. That's the starting point. Given the name, it's likely related to device management or metadata management. I'd first quickly try a `grep` or similar search within that directory to see where it's referenced directly. I'd be looking for usage in code that interacts with the device mapper framework or RAID-related functions, maybe even error handling related to device removal or shutdown. I'd expect it might be used to control behaviors when the device is being decommissioned or deleted, potentially preventing further operations on a partially destroyed device. My initial search would likely be for the definition itself to get an overview of what other flags may exist. From there, I'd probably focus on areas where I see any of the referenced files.
|
| 252/2 |
2026/11/03 18:44 |
tool |
grepper |
0m
Args: map[Expression:DMF_DELETING PathPrefixes:[drivers/md/]]
Results: map[Output:drivers/md/dm-core.h=49=struct mapped_device {
--
drivers/md/dm-core.h-157-#define DMF_FREEING 3
drivers/md/dm-core.h:158:#define DMF_DELETING 4
drivers/md/dm-core.h-159-#define DMF_NOFLUSH_SUSPENDING 5
--
drivers/md/dm.c=309=int dm_deleting_md(struct mapped_device *md)
drivers/md/dm.c-310-{
drivers/md/dm.c:311: return test_bit(DMF_DELETING, &md->flags);
drivers/md/dm.c-312-}
--
drivers/md/dm.c=365=int dm_lock_for_deletion(struct mapped_device *md, bool mark_deferred, bool only_deferred)
--
drivers/md/dm.c-377- else
drivers/md/dm.c:378: set_bit(DMF_DELETING, &md->flags);
drivers/md/dm.c-379-
--
drivers/md/dm.c=385=int dm_cancel_deferred_remove(struct mapped_device *md)
--
drivers/md/dm.c-390-
drivers/md/dm.c:391: if (test_bit(DMF_DELETING, &md->flags))
drivers/md/dm.c-392- r = -EBUSY;
]
|
| 253/2 |
2026/11/03 18:44 |
llm |
history-explorer |
2m
Model:
Tokens:
input: 96385
output: 29
thoughts: 20
Thoughts: Here's my thought process, as if I were considering this investigation:
**Investigating `DMF_FREEING` in `drivers/md/`**
Okay, so I need to track down where `DMF_FREEING` is being used within the `drivers/md/` directory. This suggests I'm likely dealing with memory management or resource cleanup within the RAID/MD (multiple device) subsystem. This could be crucial, as this area is particularly sensitive to memory leaks or dangling pointers, any of which could result in data corruption. I need to understand the context of its use. Is it a macro, a function, a variable? What is it designed to free? And under what conditions is it being called? I will likely start by using `grep` or a similar tool to pinpoint the exact locations in the code where this appears. From there, I'll need to analyze the surrounding code to determine the purpose and logic behind these calls. I'll be looking for potential race conditions, incorrect freeing of memory, or scenarios where the memory might be freed prematurely. I'll need to trace the allocation and deallocation paths carefully. Specifically, I'll want to cross-reference these call sites with related allocation routines and any locking mechanisms to ensure memory safety. This is going to be a deep dive into the MD driver's memory management strategy.
|
| 254/2 |
2026/11/03 18:46 |
tool |
grepper |
0m
Args: map[Expression:DMF_FREEING PathPrefixes:[drivers/md/]]
Results: map[Output:drivers/md/dm-core.h=49=struct mapped_device {
--
drivers/md/dm-core.h-156-#define DMF_FROZEN 2
drivers/md/dm-core.h:157:#define DMF_FREEING 3
drivers/md/dm-core.h-158-#define DMF_DELETING 4
--
drivers/md/dm.c=314=static int dm_blk_open(struct gendisk *disk, blk_mode_t mode)
--
drivers/md/dm.c-323-
drivers/md/dm.c:324: if (test_bit(DMF_FREEING, &md->flags) ||
drivers/md/dm.c-325- dm_deleting_md(md)) {
--
drivers/md/dm.c=2667=struct mapped_device *dm_get_md(dev_t dev)
--
drivers/md/dm.c-2678- if (!md || md == MINOR_ALLOCED || (MINOR(disk_devt(dm_disk(md))) != minor) ||
drivers/md/dm.c:2679: test_bit(DMF_FREEING, &md->flags) || dm_deleting_md(md)) {
drivers/md/dm.c-2680- md = NULL;
--
drivers/md/dm.c=2701=void dm_get(struct mapped_device *md)
--
drivers/md/dm.c-2703- atomic_inc(&md->holders);
drivers/md/dm.c:2704: BUG_ON(test_bit(DMF_FREEING, &md->flags));
drivers/md/dm.c-2705-}
--
drivers/md/dm.c=2707=int dm_hold(struct mapped_device *md)
--
drivers/md/dm.c-2709- spin_lock(&_minor_lock);
drivers/md/dm.c:2710: if (test_bit(DMF_FREEING, &md->flags)) {
drivers/md/dm.c-2711- spin_unlock(&_minor_lock);
--
drivers/md/dm.c=2726=static void __dm_destroy(struct mapped_device *md, bool wait)
--
drivers/md/dm.c-2734- idr_replace(&_minor_idr, MINOR_ALLOCED, MINOR(disk_devt(dm_disk(md))));
drivers/md/dm.c:2735: set_bit(DMF_FREEING, &md->flags);
drivers/md/dm.c-2736- spin_unlock(&_minor_lock);
--
drivers/md/dm.c-2759- * No one should increment the reference count of the mapped_device,
drivers/md/dm.c:2760: * after the mapped_device state becomes DMF_FREEING.
drivers/md/dm.c-2761- */
--
drivers/md/dm.c=3138=int dm_resume(struct mapped_device *md)
--
drivers/md/dm.c-3146-
drivers/md/dm.c:3147: if (!dm_suspended_md(md) || test_bit(DMF_FREEING, &md->flags))
drivers/md/dm.c-3148- goto out;
--
drivers/md/dm.c=3363=struct mapped_device *dm_get_from_kobject(struct kobject *kobj)
--
drivers/md/dm.c-3369- spin_lock(&_minor_lock);
drivers/md/dm.c:3370: if (test_bit(DMF_FREEING, &md->flags) || dm_deleting_md(md)) {
drivers/md/dm.c-3371- md = NULL;
]
|
| 255/2 |
2026/11/03 18:46 |
llm |
history-explorer |
3m
Model:
Tokens:
input: 97708
output: 36
thoughts: 95
Thoughts: Okay, let me take a look at this.
**Analyzing Device Mapper Holder Management**
Alright, so I'm diving into this code. First, `dm_get`. I see this function, `dm_get`, taking a `mapped_device` structure as its argument. The first thing it does is an atomic increment on `md->holders`. Makes sense, we're tracking holders, a basic reference count. Then, we have a `BUG_ON` call that checks if the `DMF_FREEING` flag is set on `md->flags`. This is a crucial safety check; it prevents further holder increases if the device is already in the process of being freed. That's good, prevents potential race conditions, and possible use-after-free situations.
Now, I'm going to shift gears and examine `find_device` within `drivers/md/dm-ioctl.c`. Let's see how that fits into this picture of holder management. Clearly, `find_device` plays a role in identifying or locating devices, which would then be subject to holder control by `dm_get` or similar functions. I need to dig into `find_device` to understand how the devices are discovered.
|
| 256/2 |
2026/11/03 18:50 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/md/dm-ioctl.c Name:find_device]
Results: map[SourceCode:1049: static struct mapped_device *find_device(struct dm_ioctl *param)
1050: {
1051: struct hash_cell *hc;
1052: struct mapped_device *md = NULL;
1053:
1054: down_read(&_hash_lock);
1055: hc = __find_device_hash_cell(param);
1056: if (hc)
1057: md = hc->md;
1058: up_read(&_hash_lock);
1059:
1060: return md;
1061: }
SourceFile:drivers/md/dm-ioctl.c]
|
| 257/2 |
2026/11/03 18:50 |
llm |
history-explorer |
5m
Model:
Tokens:
input: 98298
output: 41
thoughts: 14
Thoughts: Okay, let's dive into this. Here's my take on those thoughts, as if they're my own:
**Analyzing the Function Call**
Alright, my internal radar is pinging on this function name: `__find_device_hash_cell`. This immediately suggests we're dealing with something related to device identification and potentially some kind of hash table or similar data structure. The double underscore prefix is interesting; it's a common convention for internal or "private" functions in some coding styles, indicating it's not meant for direct external use. I'm already formulating hypotheses:
* **Hashing Purpose:** I'm guessing this function's core purpose is to locate a specific entry related to a device, likely using a hash value derived from some device identifier (perhaps a serial number, MAC address, or a combination thereof).
* **Data Structure:** The term "cell" implies the underlying data structure is likely a hash table, a similar structure, or a sparse array where the "cell" represents a storage location for the device's information based on its hash. The "cell" might contain other information besides the hash value.
* **Device Context:** I also think about what it means to be "device" within the system. Is this a virtual device or a physical device? Is the method tied to device-specific code or a general framework?
* **Performance Considerations:** Considering it's a lookup operation, I immediately start to think about performance. Is the hash function good? Is there any collision resolution strategy used? How big is the potential hash table? Are we optimizing for fast lookups or memory efficiency?
* **Error Handling:** It would be good to understand the error handling approach. What happens if the device isn't found? Does it return an error code, throw an exception, or return a special null/empty value?
* **Potential Areas to Explore:** My mind starts to consider what other related functions might exist. Are there functions for inserting, deleting, or updating device entries in this "hash cell"? Are there related data structures that might affect the logic of this function?
|
| 258/2 |
2026/11/03 18:56 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/md/dm-ioctl.c Name:__find_device_hash_cell]
Results: map[SourceCode: 997: /*
998: * Always use UUID for lookups if it's present, otherwise use name or dev.
999: */
1000: static struct hash_cell *__find_device_hash_cell(struct dm_ioctl *param)
1001: {
1002: struct hash_cell *hc = NULL;
1003:
1004: if (*param->uuid) {
1005: if (*param->name || param->dev) {
1006: DMERR("Invalid ioctl structure: uuid %s, name %s, dev %llx",
1007: param->uuid, param->name, (unsigned long long)param->dev);
1008: return NULL;
1009: }
1010:
1011: hc = __get_uuid_cell(param->uuid);
1012: if (!hc)
1013: return NULL;
1014: } else if (*param->name) {
1015: if (param->dev) {
1016: DMERR("Invalid ioctl structure: name %s, dev %llx",
1017: param->name, (unsigned long long)param->dev);
1018: return NULL;
1019: }
1020:
1021: hc = __get_name_cell(param->name);
1022: if (!hc)
1023: return NULL;
1024: } else if (param->dev) {
1025: hc = __get_dev_cell(param->dev);
1026: if (!hc)
1027: return NULL;
1028: } else
1029: return NULL;
1030:
1031: /*
1032: * Sneakily write in both the name and the uuid
1033: * while we have the cell.
1034: */
1035: strscpy(param->name, hc->name, sizeof(param->name));
1036: if (hc->uuid)
1037: strscpy(param->uuid, hc->uuid, sizeof(param->uuid));
1038: else
1039: param->uuid[0] = '\0';
1040:
1041: if (hc->new_map)
1042: param->flags |= DM_INACTIVE_PRESENT_FLAG;
1043: else
1044: param->flags &= ~DM_INACTIVE_PRESENT_FLAG;
1045:
1046: return hc;
1047: }
SourceFile:drivers/md/dm-ioctl.c]
|
| 259/2 |
2026/11/03 18:56 |
llm |
history-explorer |
7m
Model:
Tokens:
input: 99541
output: 34
thoughts: 4164
Thoughts: **A Deep Dive into Concurrent State Management: Device Mapper and Block Layer**
Okay, so I've been digging into this Device Mapper issue, and it's starting to look like a concurrency problem. The core of it boils down to the timing of `dev_remove()` and how it interacts with other threads accessing the device. I've traced the code, and I see that `dev_remove()` marks the disk as dead (`blk_mark_disk_dead`) *before* waiting for the holders count to drop to zero. This opens a window where another thread could still be setting up the queue or disk after the "dead" flag is set. That's a classic race condition and potentially a serious bug.
I immediately wanted to explore what other similar scenarios exist and what solutions were applied to them. I need to understand if similar issues exist in the block layer and how these issues were handled. I'm focusing particularly on how queue freeze/unfreeze states are managed for lockdep. The block layer work is particularly interesting, especially the changes introduced by Ming Lei and other engineers.
Iβve reviewed a series of relevant commits. These include the addition of the `q_lockdep_map` and `io_lockdep_map` within the block layer which seem similar to what may be needed in Device Mapper. The earlier versions of these changes used flags passed as function arguments to represent `disk_dead` and `queue_dying`. Later, those were migrated into struct request_queue. I see the evolution of how these freeze and unfreeze operations are modeled for lockdep to detect potential deadlocks. I also see that `blk_freeze_set_owner` and `blk_unfreeze_check_owner` were introduced to track the freeze owner.
Here's the critical bit: Ming Lei's "per-task variable" assumption. I'm seeing that, in an attempt to address false positives, the code now records `disk_dead` and `queue_dying` states *outside* the critical section protected by `q->mq_freeze_lock`. The owner task, as recorded by `blk_freeze_set_owner` and `blk_unfreeze_check_owner`, would then acquire the state outside of the lock and check those variables outside the lock. The assumption that the `mq_freeze_disk_dead` and `mq_freeze_queue_dying` variables are "per-task" is a major concern. They're stored in `struct request_queue`, which is shared and can be overwritten by other tasks. This means a second task can, *after* the first task has set the queue to dead and released the lock, overwrite the queue as it continues to work. This makes for a potential race condition.
Iβm now considering how other locking patterns in the kernel handle returning state values or releasing locks and how state is preserved across these calls. I'm starting to think we need to rethink how we handle the `blk_mark_disk_dead` call and the waiting on `holders` in `dev_remove()`. Can we return what locks to release from the freeze/unfreeze functions? Can we release those locks inside the lock? Or return the flags? There has to be a safer way to track the state across those two crucial points. I need to go deeper and see how the block layer handles this kind of synchronization in detail. The `del_gendisk` function in `block/genhd.c` might provide some insight into similar patterns.
|
| 260/2 |
2026/11/03 19:03 |
tool |
read-file |
0m
Args: map[File:block/genhd.c FirstLine:725 LineCount:65]
Results: map[Contents: 725:
726: /*
727: * Drop all partitions now that the disk is marked dead.
728: */
729: mutex_lock(&disk->open_mutex);
730: start_drain = __blk_mark_disk_dead(disk);
731: if (start_drain)
732: blk_freeze_acquire_lock(q);
733: xa_for_each_start(&disk->part_tbl, idx, part, 1)
734: drop_partition(part);
735: mutex_unlock(&disk->open_mutex);
736:
737: if (!(disk->flags & GENHD_FL_HIDDEN)) {
738: sysfs_remove_link(&disk_to_dev(disk)->kobj, "bdi");
739:
740: /*
741: * Unregister bdi before releasing device numbers (as they can
742: * get reused and we'd get clashes in sysfs).
743: */
744: bdi_unregister(disk->bdi);
745: }
746:
747: blk_unregister_queue(disk);
748:
749: kobject_put(disk->part0->bd_holder_dir);
750: kobject_put(disk->slave_dir);
751: disk->slave_dir = NULL;
752:
753: part_stat_set_all(disk->part0, 0);
754: disk->part0->bd_stamp = 0;
755: sysfs_remove_link(block_depr, dev_name(disk_to_dev(disk)));
756: pm_runtime_set_memalloc_noio(disk_to_dev(disk), false);
757: device_del(disk_to_dev(disk));
758:
759: blk_mq_freeze_queue_wait(q);
760:
761: blk_throtl_cancel_bios(disk);
762:
763: blk_sync_queue(q);
764: blk_flush_integrity();
765:
766: if (queue_is_mq(q))
767: blk_mq_cancel_work_sync(q);
768:
769: rq_qos_exit(q);
770:
771: /*
772: * If the disk does not own the queue, allow using passthrough requests
773: * again. Else leave the queue frozen to fail all I/O.
774: */
775: if (!test_bit(GD_OWNS_QUEUE, &disk->state))
776: __blk_mq_unfreeze_queue(q, true);
777: else if (queue_is_mq(q))
778: blk_mq_exit_queue(q);
779:
780: if (start_drain)
781: blk_unfreeze_release_lock(q);
782: }
783:
784: static void disable_elv_switch(struct request_queue *q)
785: {
786: struct blk_mq_tag_set *set = q->tag_set;
787: WARN_ON_ONCE(!queue_is_mq(q));
788:
789: down_write(&set->update_nr_hwq_lock);
]
|
| 261/2 |
2026/11/03 19:03 |
llm |
history-explorer |
5m
Model:
Tokens:
input: 105481
output: 42
thoughts: 4325
Thoughts: **Analyzing the Block Layer Freeze and Lockdep Interaction**
Okay, let's break this down. My initial focus was on the interaction between `__del_gendisk` and the block queue freezing mechanisms. I noticed a subtle but critical issue stemming from how the freeze state (`mq_freeze_disk_dead`, `mq_freeze_queue_dying`, etc.) is managed and used in conjunction with the lockdep modeling.
The core problem, as I see it, centers around a race condition. `del_gendisk` calls `blk_freeze_acquire_lock(q)` and then `blk_unfreeze_release_lock(q)`. The critical point is that `blk_unfreeze_release_lock` checks `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead` to conditionally release the lockdep locks, however, these flags are written by a *different* thread/context. The fact that the freeze depth hits zero and releases the lock *before* the lockdep check in the unfreeze means we have no safety.
The bug hinges on this: if one thread freezes the queue (e.g., in `elevator_change`) and then quickly unfrozes it (dropping `mq_freeze_lock`), another thread (during disk removal using `blk_mark_disk_dead` called by `del_gendisk`) can sneak in, acquire the same `mq_freeze_lock`, and *change* the values of `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead`. The original thread, having already dropped its `mq_freeze_lock`, reads the modified state when it calls `blk_unfreeze_release_lock`, leading to incorrect lockdep checks or lock leaks.
The analysis is further complicated by the use of `q->mq_freeze_depth`, `mq_freeze_owner`, `mq_freeze_owner_depth`, and the per-task flags `mq_freeze_disk_dead` and `mq_freeze_queue_dying`. These state variables are intended to track the freeze status and are supposed to be valid only within the context of the freezing thread/task. Ming Lei documented that they were intended for this "current context" use for the *unfreeze*. But, because they live in a shared data structure without protection *between* the unlock and the `blk_unfreeze_release_lock()` call, a concurrent modification can happen.
My hypothesis, confirmed by reviewing related commits, is that this race was introduced because of changes that stored freeze status *in* the `request_queue` structure. The earlier freeze/unfreeze mechanism used direct booleans on the stack. The introduction of these per-queue flags, while perhaps intended to improve the overall model, inadvertently created a window for the race condition. The comments say the flags were per "context", but that context is no longer valid after the unlock.
Now, I'll need to develop a fix that properly synchronizes access to these flags and ensures lockdep is consistent, even when concurrent freezes and unfreezes occur. It looks like the fix lies in moving the state back to the context or adding a lock around these reads and writes.
|
| 262/2 |
2026/11/03 19:08 |
tool |
git-log |
0m
Args: map[CodeRegexp:mq_freeze_lock Count:15 PathPrefix:block/ Since:3 years]
Results:
|
| 263/2 |
2026/11/03 19:08 |
llm |
history-explorer |
2m
Model:
Tokens:
input: 110545
output: 40
thoughts: 21
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Investigating a Potentially Empty `mq_freeze_lock`**
Okay, hold on a second. I'm seeing something unusual: the `mq_freeze_lock` variable is apparently empty, which is unexpected. My initial reaction is to immediately verify this crucial data point. I need to make absolutely sure that this observed state of `mq_freeze_lock` is accurate, and that I'm not misinterpreting something. So, let's double-check the underlying `freeze_lock` variable to confirm what's actually going on. This is a critical point to ensure correctness of the analysis.
|
| 264/2 |
2026/11/03 19:11 |
tool |
git-log |
0m
Args: map[CodeRegexp:freeze_lock Count:15 PathPrefix:block/ Since:3 years]
Results:
|
| 265/2 |
2026/11/03 19:11 |
llm |
history-explorer |
4m
Model:
Tokens:
input: 110766
output: 42
thoughts: 80
Thoughts: Okay, let me break this down.
**Debugging a Code Search Query**
Hmm, that's odd. Why did my search using `CodeRegexp: "freeze_lock"` come up empty? I was expecting to see results related to that lock. Ah, right! The actual field name is `mq_freeze_lock`, not `freeze_lock`. The Git log with `CodeRegexp` is looking at diffs that *add* or *remove* lines that match the regular expression I provided. So, it wouldn't find something if I was just using the base word, I need the full expression, as well as the context of additions and removals in the diff.
Alright, let's try a new search. I'll test `CodeRegexp: "mq_freeze_depth"` instead. Hopefully, that will give me the results I am looking for.
|
| 266/2 |
2026/11/03 19:16 |
tool |
git-log |
0m
Args: map[CodeRegexp:mq_freeze_depth Count:15 PathPrefix:block/ Since:3 years]
Results: map[Output:dfe48ea17973 blk-mq: use NOIO context to prevent deadlock during debugfs creation
65d466b62984 blk-mq-debugfs: warn about possible deadlock
8bd7195fea6d blk-mq: remove useless checkings in blk_mq_update_nr_requests()
596dce110b7d block: simplify elevator reattachment for updating nr_hw_queues
1bb7fba0e262 block: fold elevator_disable into elevator_switch
f8e111c859b9 block: don't call freeze queue in elevator_switch() and elevator_disable()
6a78699838a0 block: always verify unfreeze lock on the owner task
af2814149883 block: freeze the queue in queue_attr_store
]
|
| 267/2 |
2026/11/03 19:16 |
llm |
history-explorer |
2m
Model:
Tokens:
input: 111294
output: 27
thoughts: 267
Thoughts: **Analyzing Recent Block Layer Changes**
Okay, let's dive into these commits. First glance, looks like we've got a cluster of activity around `blk-mq` and the block layer. I see several commits focused on debugfs, specifically addressing potential deadlocks during creation and related warnings. That's good; always important to be proactive about those types of issues. Then there's some cleanup, like the removal of that useless check in `blk_mq_update_nr_requests()`. Nice to see the code getting leaner. And then, here, a few commits dealing with elevator reattachment and switching. I'll flag those to come back to.
But specifically, I want to take a closer look at `f8e111c859b9` and `1bb7fba0e262`. I'm interested in how they're handling freezing and unfreezing the queues during elevator switches and disables. I want to see if this is handling locking properly. I see a couple of others in the list that likely relate to them as well.
|
| 268/2 |
2026/11/03 19:19 |
tool |
git-show |
0m
Args:
Results: map[Output:commit f8e111c859b92ee909f1676f90c791e7165d3860
Author: Ming Lei <ming.lei@redhat.com>
Date: Mon May 5 22:17:41 2025 +0800
block: don't call freeze queue in elevator_switch() and elevator_disable()
Both elevator_switch() and elevator_disable() are only called from the
two code paths, in which queue is guaranteed to be frozen.
So don't call freeze queue in the two functions, also add asserts for
queue freeze.
Reviewed-by: Christoph Hellwig <hch@lst.de>
Reviewed-by: Hannes Reinecke <hare@suse.de>
Reviewed-by: Nilay Shroff <nilay@linux.ibm.com>
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Reviewed-by: Yu Kuai <yukuai3@huawei.com>
Link: https://lore.kernel.org/r/20250505141805.2751237-4-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/elevator.c b/block/elevator.c
index b4d08026b02c..5051a98dc08c 100644
--- a/block/elevator.c
+++ b/block/elevator.c
@@ -615,12 +615,11 @@ void elevator_init_mq(struct request_queue *q)
*/
int elevator_switch(struct request_queue *q, struct elevator_type *new_e)
{
- unsigned int memflags;
int ret;
+ WARN_ON_ONCE(q->mq_freeze_depth == 0);
lockdep_assert_held(&q->elevator_lock);
- memflags = blk_mq_freeze_queue(q);
blk_mq_quiesce_queue(q);
if (q->elevator) {
@@ -641,7 +640,6 @@ int elevator_switch(struct request_queue *q, struct elevator_type *new_e)
out_unfreeze:
blk_mq_unquiesce_queue(q);
- blk_mq_unfreeze_queue(q, memflags);
if (ret) {
pr_warn("elv: switch to \"%s\" failed, falling back to \"none\"\n",
@@ -653,11 +651,9 @@ int elevator_switch(struct request_queue *q, struct elevator_type *new_e)
void elevator_disable(struct request_queue *q)
{
- unsigned int memflags;
-
+ WARN_ON_ONCE(q->mq_freeze_depth == 0);
lockdep_assert_held(&q->elevator_lock);
- memflags = blk_mq_freeze_queue(q);
blk_mq_quiesce_queue(q);
elv_unregister_queue(q);
@@ -668,7 +664,6 @@ void elevator_disable(struct request_queue *q)
blk_add_trace_msg(q, "elv switch: none");
blk_mq_unquiesce_queue(q);
- blk_mq_unfreeze_queue(q, memflags);
}
/*
]
|
| 269/2 |
2026/11/03 19:19 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 112727
output: 20
thoughts: 1942
Thoughts: **Analyzing the Freeze/Unfreeze Logic in Block Layer**
Okay, so Ming Lei removed an inner `blk_mq_freeze_queue` from `elevator_switch` and `elevator_disable` (commit `f8e111c859b9`), which makes sense because those functions are called with the queue already frozen. Now I need to circle back to commit `6a78699838a0` which, I recall, is about verifying the unfreeze lock on the owner task. Why was that necessary? Right, let's refresh my memory: commit `f1be1788a32e` introduced lockdep for freeze/unfreeze, but it only validated the outermost freeze/unfreeze, and this was flawed. The depth could drop to zero on another task.
Commit `6a78699838a0` addressed this by always verifying the final unfreeze within the context of the owner task. Looking at the code: `__blk_freeze_queue_start` and `__blk_mq_unfreeze_queue` use `mutex_lock(&q->mq_freeze_lock)` to ensure atomicity. Crucially, when `6a78699838a0` was written, `blk_freeze_acquire_lock` and `blk_unfreeze_release_lock` took boolean parameters.
Then, there were changes in `6f491a8d4b92` and `f6661b1d0525` on Nov 27, 2024. These changes introduced `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying`, storing them in the `request_queue` struct, and removed those boolean parameters from `blk_freeze_acquire_lock` and `blk_unfreeze_release_lock`. Now, in `blk_unfreeze_release_lock`, these flags are used to determine which locks to release. Importantly, `blk_unfreeze_check_owner` now checks if the current task is the freeze owner and decrements the owner depth. If it drops to 0, then the owner is set to NULL.
Here's the problem: inside `__blk_mq_unfreeze_queue`, the sequence is: 1. lock the mutex; 2. decrement the freeze depth; 3. call `blk_unfreeze_check_owner`; 4. unlock the mutex. And THEN, *after* the mutex is unlocked, `blk_unfreeze_release_lock` is called. That function accesses `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead`. The original assumption was that because the unfreezing task was the owner, no other task could modify those flags. But that's wrong!
As soon as the mutex is unlocked, another task can call `__blk_freeze_queue_start`. If the queue isn't frozen, which it isn't (since the depth is 0) this other task can modify the owner and freeze flags, overwriting the values set by the unfreezing task. The unfreezing task is then going to read the *stale* flags. This can lead to a missed release of `q_lockdep_map`. This is a clear race condition and a pretty serious bug.
I need to figure out *why* `blk_unfreeze_release_lock` is done outside the lock. Why wasn't the release handled under the `q->mq_freeze_lock`? Or why weren't the flags captured and saved *before* releasing the lock? I need to check if `rwsem_release` can be safely called inside the `q->mq_freeze_lock`. I need to look at the lockdep implementation of `rwsem_release` to see if that's the blocker. This needs immediate attention.
|
| 270/2 |
2026/11/03 19:19 |
tool |
grepper |
0m
Args: map[Expression:#define rwsem_release]
Results: map[Output:include/linux/lockdep.h=522=do { \
--
include/linux/lockdep.h-541-#define rwsem_acquire_read(l, s, t, i) lock_acquire_shared(l, s, t, NULL, i)
include/linux/lockdep.h:542:#define rwsem_release(l, i) lock_release(l, i)
include/linux/lockdep.h-543-
]
|
| 271/2 |
2026/11/03 19:19 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 115669
output: 42
thoughts: 4697
Thoughts: **Deep Dive into Block Layer Freeze/Unfreeze Logic**
Okay, here's what I've got after this deep dive: the core issue revolves around how the block layer handles queue freezing and unfreezing, specifically regarding the interaction between `q_lockdep_map`, `io_lockdep_map`, and the `mq_freeze_lock`. It all boils down to whether the freeze state information (`mq_freeze_disk_dead`, `mq_freeze_queue_dying`) is properly protected during unfreeze operations.
My initial thought was that `rwsem_release` just releases the lock, no dependencies are added when releasing. But what about when this happens under `mq_freeze_lock`? Then it matters that `q_lockdep_map` or `io_lockdep_map` was acquired at an earlier time. The lock dependency is then `mq_freeze_lock` -> `q_lockdep_map`. The question then becomes, is `mq_freeze_lock` ever acquired while other locks are held?
Then I went to the `__blk_freeze_queue_start` function and noticed how `blk_mq_run_hw_queues` is called. It's a key function in multiple scenarios (`__blk_freeze_queue_start`, `blk_freeze_queue_start_non_owner`, `blk_queue_start_drain`). Specifically, `del_gendisk` is an interesting case: it calls `blk_queue_start_drain` which indirectly triggers the freeze process. The crucial part is that `__blk_freeze_queue_start` returns a freeze boolean, which gets passed on, eventually leading to `blk_freeze_acquire_lock` and then `blk_unfreeze_release_lock` (or not). It becomes important if `del_gendisk` is called when `q->mq_freeze_disk_dead` or `q->mq_freeze_queue_dying` are recorded.
The key observation is how the flags `mq_freeze_disk_dead` and `mq_freeze_queue_dying` are set within `blk_freeze_set_owner`. The critical thing is that these flags are set *only* when the freeze depth is zero. This introduces a race: `__blk_mq_unfreeze_queue` drops `mq_freeze_lock` *before* `blk_unfreeze_release_lock` is called, allowing another thread to enter a freeze operation and overwrite these flags *before* the unfreeze can finish.
This is a subtle but significant issue! The fact that the flags are set at depth zero leaves them vulnerable to race conditions between threads freezing and unfreezing the queue. The flags are not captured or restored properly during the unfreeze process.
I also looked at Ming Lei's commit `6a78699838a0`, which introduced these flags and the owner tracking (through `blk_freeze_set_owner` and `blk_unfreeze_check_owner`). The critical vulnerability is that `blk_unfreeze_check_owner` *doesn't* clear or preserve `mq_freeze_disk_dead` and `mq_freeze_queue_dying`. This means that if another freeze occurs *after* the owner check but *before* the unfreeze completes, the new freeze can clobber the flags.
This commit then was amended with a change that used to pass flags to `blk_freeze_acquire_lock` and `blk_unfreeze_release_lock`. But then those parameters were removed! `del_gendisk` *used* to pass boolean flags to these functions. This means that the flag values were once captured on the stack but that is not the case now. This means that if `blk_mq_unfreeze_queue` or `blk_unfreeze_check_owner` returns information on these flags OR if `blk_unfreeze_release_lock` is called under `q->mq_freeze_lock`, then the race is eliminated.
So, the ideal solution would be to take a snapshot of these flags when calling `blk_mq_unfreeze_queue` or `blk_unfreeze_check_owner` inside `mq_freeze_lock`. Or to pass the values to the release function. Or to ensure that `blk_unfreeze_release_lock(q)` is called *before* releasing the `q->mq_freeze_lock` entirely. The code should take a snapshot of the `disk_dead` and `queue_dying` flags when the lock is held to avoid racing.
The nested freeze behavior is critical. For nested freezes by the *same* task, it's safe because `mq_freeze_owner_depth` protects it. The first freeze sets depth to 1 and the flags
|
| 272/2 |
2026/11/03 19:20 |
tool |
git-log |
0m
Args: map[CodeRegexp:type_lock Count:15 PathPrefix:drivers/md/ Since:3 years]
Results: map[Output:feb83afa4e07 dm: Remove unused dm_set_md_type
]
|
| 273/2 |
2026/11/03 19:20 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 121466
output: 35
thoughts: 27
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Analyzing the Codebase for Synchronization Issues**
Alright, I need to pinpoint the source of this concurrency issue, which seems to revolve around locking mechanisms. My first instinct is to dive directly into commit `feb83afa4e07`. I want to see what changes were introduced there, especially if they touch upon how the system handles shared resources.
If that initial commit doesn't immediately reveal the smoking gun, I'm going to broaden the search. I'll execute a global code search for "type_lock" across all commits. That keyword suggests a specific type of lock implementation and might be the key to understanding the synchronization strategy or a potential point of contention. I'm thinking I'll start with the most recent commits and work backward, noting the history of changes. I want to see how this particular locking mechanism was introduced, modified, or potentially removed over time. Knowing the history will help me determine where things started to go wrong, or what has been changed recently that might be contributing to the issue. I need to be methodical here, checking for obvious lock contention, race conditions, or even improper usage of the lock itself.
|
| 274/2 |
2026/11/03 19:20 |
tool |
git-log |
0m
Args: map[CodeRegexp:type_lock Count:15 PathPrefix:drivers/md/]
Results: map[Output:feb83afa4e07 dm: Remove unused dm_set_md_type
d5ffebdd797a dm: backfill missing calls to mutex_destroy()
4cc96131afce dm: move request-based code out to dm-rq.[hc]
16f122661dbb dm: optimize dm_mq_queue_rq()
00c4fc3b1f59 dm ioctl: increase granularity of type_lock when loading table
a5664dad7e1a dm ioctl: make bio or request based device type immutable
]
|
| 275/2 |
2026/11/03 19:21 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 121932
output: 26
thoughts: 62
Thoughts: Here's my analysis of the commits, presented as a summary of my thought process:
**Diving Deep into Device Mapper Locking and Immutability**
Okay, let's zero in on these Device Mapper commits: `00c4fc3b1f59 dm ioctl: increase granularity of type_lock when loading table` and `a5664dad7e1a dm ioctl: make bio or request based device type immutable`. My immediate instinct is to dissect the locking strategy changes in the first and the immutability implications of the second.
The granularity increase for the `type_lock` in the loading table routine is interesting. My guess is we're looking at a performance optimization here. I need to understand *why* the original lock was too coarse and *how* this finer-grained approach improves concurrency, specifically during table loading. Are we reducing contention during concurrent operations that touch different device types? Does this impact overall boot speed or dynamic table updates? I'll be looking for detailed rationale in the commit message and the actual code changes to get a clear picture of the impact. I want to see if this change properly addresses potential race conditions in the context of device type management.
Moving to the second commit, `a5664dad7e1a dm ioctl: make bio or request based device type immutable` is, in my professional opinion, a crucial shift. Making the device type immutable in the context of bio or request-based operations feels like a fundamental step towards enhanced data integrity and reduced complexity. My initial thought is it's likely a significant step towards preventing accidental (or malicious) modification of device types during I/O. I need to explore how this impacts existing workflows and what potential refactoring, if any, was required. The commit message needs to clearly articulate the threat model being addressed and the associated design goals. I'll want to see how this immutable device type is enforced and managed in the code and what potential performance implications might exist with the added immutable constraint. I'm keen to see if this change simplifies debugging and auditability by eliminating a class of potential bugs related to the accidental or malicious mutation of device types. I will pay close attention to the impact on any existing users of the Device Mapper I/O path.
|
| 276/2 |
2026/11/03 19:21 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 00c4fc3b1f590288cb3c42f36da50f49a513cfcf
Author: Mike Snitzer <snitzer@redhat.com>
Date: Tue Aug 27 18:57:03 2013 -0400
dm ioctl: increase granularity of type_lock when loading table
Hold the mapped device's type_lock before calling populate_table() since
it is where the table's type is determined based on the specified
targets. There is no need to allow concurrent table loads to race to
establish the table's targets or type.
This eliminates the need to grab the lock in dm_table_set_type().
Also verify that the type_lock is held in both dm_set_md_type() and
dm_get_md_type().
Signed-off-by: Mike Snitzer <snitzer@redhat.com>
Signed-off-by: Alasdair G Kergon <agk@redhat.com>
diff --git a/drivers/md/dm-ioctl.c b/drivers/md/dm-ioctl.c
index 5667cea55e71..42cca3642010 100644
--- a/drivers/md/dm-ioctl.c
+++ b/drivers/md/dm-ioctl.c
@@ -1264,9 +1264,12 @@ static int table_load(struct dm_ioctl *param, size_t param_size)
if (r)
goto out;
+ /* Protect md->type and md->queue against concurrent table loads. */
+ dm_lock_md_type(md);
r = populate_table(t, param, param_size);
if (r) {
dm_table_destroy(t);
+ dm_unlock_md_type(md);
goto out;
}
@@ -1276,12 +1279,11 @@ static int table_load(struct dm_ioctl *param, size_t param_size)
DMWARN("can't replace immutable target type %s",
immutable_target_type->name);
dm_table_destroy(t);
+ dm_unlock_md_type(md);
r = -EINVAL;
goto out;
}
- /* Protect md->type and md->queue against concurrent table loads. */
- dm_lock_md_type(md);
if (dm_get_md_type(md) == DM_TYPE_NONE)
/* Initial table load: acquire type of table. */
dm_set_md_type(md, dm_table_get_type(t));
diff --git a/drivers/md/dm-table.c b/drivers/md/dm-table.c
index f309477d7efe..8f8783533ac7 100644
--- a/drivers/md/dm-table.c
+++ b/drivers/md/dm-table.c
@@ -888,9 +888,7 @@ static int dm_table_set_type(struct dm_table *t)
* Determine the type from the live device.
* Default to bio-based if device is new.
*/
- dm_lock_md_type(t->md);
live_md_type = dm_get_md_type(t->md);
- dm_unlock_md_type(t->md);
if (live_md_type == DM_TYPE_REQUEST_BASED)
request_based = 1;
else
diff --git a/drivers/md/dm.c b/drivers/md/dm.c
index ef095a96d039..7faeaa3d4835 100644
--- a/drivers/md/dm.c
+++ b/drivers/md/dm.c
@@ -2235,11 +2235,13 @@ void dm_unlock_md_type(struct mapped_device *md)
void dm_set_md_type(struct mapped_device *md, unsigned type)
{
+ BUG_ON(!mutex_is_locked(&md->type_lock));
md->type = type;
}
unsigned dm_get_md_type(struct mapped_device *md)
{
+ BUG_ON(!mutex_is_locked(&md->type_lock));
return md->type;
}
]
|
| 277/2 |
2026/11/03 19:21 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 123643
output: 42
thoughts: 2614
Thoughts: **Analysis of Race Condition in Device Mapper's Table Load and Device Removal**
Okay, so I've been digging into the Device Mapper code, specifically focusing on a potential race condition between `table_load` (the ioctl for loading a new table) and device removal (`dev_remove`). My initial hunch was correct, it seems. The core of the problem lies in the interaction between how `table_load` acquires and releases references to the `mapped_device` (`md`) and the timing of device destruction.
The code in `drivers/md/dm-ioctl.c`, particularly the `table_load` function, caught my attention. The comment about protecting `md->type` and `md->queue` with a lock (`dm_lock_md_type`) is crucial. This lock's *sole* purpose is to guard against *concurrent table loads*. It's *not* held during device destruction (`dm_destroy` or `__dm_destroy`).
Now, `__dm_destroy` is where things get interesting. It marks the device as `DMF_FREEING` and waits for `md->holders` to drop to zero before freeing the device's resources. The comment suggests this wait is for "racing completing activity". In commit `3f77316de0ec0`, the assumption was "nobody opens the mapped_device and no new reference will be taken."
However, that assumption is flawed because `dev_remove` checks only `dm_open_count(md) == 0`. It *doesn't* check if an ioctl like `table_load` is actively running, holding a reference to the device. Any ioctl that starts by looking up the device in `find_device(param)`, calls `dm_get(md)`, which increments `md->holders`.
Here's the race:
1. `table_load` is running, has incremented `md->holders`.
2. `dev_remove` is called concurrently. `dm_open_count(md)` is 0, so it proceeds.
3. `dev_remove` calls `__hash_remove(hc)` to remove device from hash table.
4. `dev_remove` calls `dm_destroy(md)`.
5. `__dm_destroy` sets `DMF_FREEING`.
6. `__dm_destroy` calls `blk_mark_disk_dead(md->disk)`.
7. Meanwhile, `table_load` is still in `dm_setup_md_queue(md, t)`! This function modifies the device queue (freezing, unfreezing).
8. `add_disk(md->disk)` -> `blk_register_queue` -> `elevator_set_default` -> `elevator_change` calls freeze and unfreeze of the queue.
9. Right as it unfreezes, `blk_mark_disk_dead` runs and marks the queue dying!
10. `table_load` finishes `dm_setup_md_queue(md, t)`, tries to look up `hc = dm_get_mdptr(md)`, finds it's `NULL` because `dev_remove` removed it from hash table.
11. `table_load` prints an error and drops the reference it had, after `blk_mark_disk_dead` runs, allowing the queue to be dead.
12. `__dm_destroy`'s `while (atomic_read(&md->holders))` loop eventually finishes.
The critical flaw is that `table_load` doesn't check the device's state (e.g., `DMF_FREEING`) *before* calling `dm_setup_md_queue`. This allows `table_load` to operate on a device that's in the process of being destroyed.
Interestingly, I looked at a previous fix for a `resume-vs-remove race` (`44b43ec132f1`), where Mikulas Patocka checked `test_bit(DMF_FREEING, &md->flags)` in `dm_resume`. This highlights that the existing code *does* recognize the need to check the device's destruction state in *some* ioctls, but apparently not in `table_load`. `table_load` only checks if the device is in the hash table after the queue setup, and by then it could be already dead.
Finally, a quick search for `DMF_DELETING` and `DMF_FREEING` in `drivers/md/` confirms that other ioctls do *not* generally check if the device is being deleted or freed. This suggests that the current protection is incomplete, and a broader fix might be required.
|
| 278/2 |
2026/11/03 19:21 |
tool |
grepper |
0m
Args: map[Expression:dm_deleting_md|DMF_DELETING|DMF_FREEING PathPrefixes:[drivers/md/]]
Results: map[Output:drivers/md/dm-core.h=49=struct mapped_device {
--
drivers/md/dm-core.h-156-#define DMF_FROZEN 2
drivers/md/dm-core.h:157:#define DMF_FREEING 3
drivers/md/dm-core.h:158:#define DMF_DELETING 4
drivers/md/dm-core.h-159-#define DMF_NOFLUSH_SUSPENDING 5
--
drivers/md/dm-ioctl.c=1883=static int target_message(struct file *filp, struct dm_ioctl *param, size_t param_size)
--
drivers/md/dm-ioctl.c-1928-
drivers/md/dm-ioctl.c:1929: if (dm_deleting_md(md)) {
drivers/md/dm-ioctl.c-1930- r = -ENXIO;
--
drivers/md/dm.c=293=static void __exit dm_exit(void)
--
drivers/md/dm.c-308- */
drivers/md/dm.c:309:int dm_deleting_md(struct mapped_device *md)
drivers/md/dm.c-310-{
drivers/md/dm.c:311: return test_bit(DMF_DELETING, &md->flags);
drivers/md/dm.c-312-}
--
drivers/md/dm.c=314=static int dm_blk_open(struct gendisk *disk, blk_mode_t mode)
--
drivers/md/dm.c-323-
drivers/md/dm.c:324: if (test_bit(DMF_FREEING, &md->flags) ||
drivers/md/dm.c:325: dm_deleting_md(md)) {
drivers/md/dm.c-326- md = NULL;
--
drivers/md/dm.c=365=int dm_lock_for_deletion(struct mapped_device *md, bool mark_deferred, bool only_deferred)
--
drivers/md/dm.c-377- else
drivers/md/dm.c:378: set_bit(DMF_DELETING, &md->flags);
drivers/md/dm.c-379-
--
drivers/md/dm.c=385=int dm_cancel_deferred_remove(struct mapped_device *md)
--
drivers/md/dm.c-390-
drivers/md/dm.c:391: if (test_bit(DMF_DELETING, &md->flags))
drivers/md/dm.c-392- r = -EBUSY;
--
drivers/md/dm.c=2667=struct mapped_device *dm_get_md(dev_t dev)
--
drivers/md/dm.c-2678- if (!md || md == MINOR_ALLOCED || (MINOR(disk_devt(dm_disk(md))) != minor) ||
drivers/md/dm.c:2679: test_bit(DMF_FREEING, &md->flags) || dm_deleting_md(md)) {
drivers/md/dm.c-2680- md = NULL;
--
drivers/md/dm.c=2701=void dm_get(struct mapped_device *md)
--
drivers/md/dm.c-2703- atomic_inc(&md->holders);
drivers/md/dm.c:2704: BUG_ON(test_bit(DMF_FREEING, &md->flags));
drivers/md/dm.c-2705-}
--
drivers/md/dm.c=2707=int dm_hold(struct mapped_device *md)
--
drivers/md/dm.c-2709- spin_lock(&_minor_lock);
drivers/md/dm.c:2710: if (test_bit(DMF_FREEING, &md->flags)) {
drivers/md/dm.c-2711- spin_unlock(&_minor_lock);
--
drivers/md/dm.c=2726=static void __dm_destroy(struct mapped_device *md, bool wait)
--
drivers/md/dm.c-2734- idr_replace(&_minor_idr, MINOR_ALLOCED, MINOR(disk_devt(dm_disk(md))));
drivers/md/dm.c:2735: set_bit(DMF_FREEING, &md->flags);
drivers/md/dm.c-2736- spin_unlock(&_minor_lock);
--
drivers/md/dm.c-2759- * No one should increment the reference count of the mapped_device,
drivers/md/dm.c:2760: * after the mapped_device state becomes DMF_FREEING.
drivers/md/dm.c-2761- */
--
drivers/md/dm.c=3138=int dm_resume(struct mapped_device *md)
--
drivers/md/dm.c-3146-
drivers/md/dm.c:3147: if (!dm_suspended_md(md) || test_bit(DMF_FREEING, &md->flags))
drivers/md/dm.c-3148- goto out;
--
drivers/md/dm.c=3363=struct mapped_device *dm_get_from_kobject(struct kobject *kobj)
--
drivers/md/dm.c-3369- spin_lock(&_minor_lock);
drivers/md/dm.c:3370: if (test_bit(DMF_FREEING, &md->flags) || dm_deleting_md(md)) {
drivers/md/dm.c-3371- md = NULL;
--
drivers/md/dm.h=140=int dm_split_args(int *argc, char ***argvp, char *input);
--
drivers/md/dm.h-144- */
drivers/md/dm.h:145:int dm_deleting_md(struct mapped_device *md);
drivers/md/dm.h-146-
]
|
| 279/2 |
2026/11/03 19:22 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 128890
output: 38
thoughts: 49
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience:
**Diving into dm-ioctl.c: The Message is the Key**
Alright, my brain just kicked in, and the first thing I'm thinking is, "Get over to `drivers/md/dm-ioctl.c:1929` *immediately*." I need to understand the interaction with that specific section of the kernel. This must be the heart of a data-plane, or block device, control and I need to see *exactly* how we're handling I/O there.
The next thought is, "Okay, that line is probably referencing a structure. Let's dig in and understand what `target_message` is, specifically, around line 1928, or thereabouts. The surrounding code will provide context, of course, but `target_message` is probably the critical piece. I need to see how the system is interpreting and acting upon the message being passed, which will inform any subsequent actions.
|
| 280/2 |
2026/11/03 19:22 |
tool |
read-file |
0m
Args: map[File:drivers/md/dm-ioctl.c FirstLine:1915 LineCount:35]
Results: map[Contents:1915: goto out_argv;
1916: }
1917:
1918: r = message_for_md(md, argc, argv, result, maxlen);
1919: if (r <= 1)
1920: goto out_argv;
1921:
1922: table = dm_get_live_table(md, &srcu_idx);
1923: if (!table) {
1924: DMERR("The device has no table.");
1925: r = -EINVAL;
1926: goto out_table;
1927: }
1928:
1929: if (dm_deleting_md(md)) {
1930: r = -ENXIO;
1931: goto out_table;
1932: }
1933:
1934: ti = dm_table_find_target(table, tmsg->sector);
1935: if (!ti) {
1936: DMERR("Target message sector outside device.");
1937: r = -EINVAL;
1938: } else if (ti->type->message)
1939: r = ti->type->message(ti, argc, argv, result, maxlen);
1940: else {
1941: DMERR("Target type does not support messages");
1942: r = -EINVAL;
1943: }
1944:
1945: out_table:
1946: dm_put_live_table(md, srcu_idx);
1947: out_argv:
1948: kfree(argv);
1949: out:
]
|
| 281/2 |
2026/11/03 19:22 |
llm |
history-explorer-compressor |
3m
Model:
Reply: ### Workspace and Investigation Summary
#### 1. Approaches Tried So Far and Results
- **Researched recent block layer commit history for freeze lockdep modeling:**
- `git-log` on `mq_freeze_queue_dying`, `blk_freeze_acquire_lock`, `mq_freeze_owner`, `lockdep_map`, and `freeze` in `block/` over the past 3 years.
- Examined the exact series introducing the bug:
- `f1be1788a32e` ("block: model freeze & enter queue as lock for supporting lockdep"): First introduced `rwsem_acquire`/`rwsem_release` on `q->io_lockdep_map` and `q->q_lockdep_map`. Both acquire and release took boolean arguments (`disk_dead`, `queue_dying`) passed explicitly from callers.
- `8acdd0e7bfad` ("blk-mq: add non_owner variant of start_freeze/unfreeze queue APIs"): Introduced `blk_freeze_queue_start_non_owner` and `blk_mq_unfreeze_queue_non_owner` to bypass lockdep when freezing/unfreezing across different tasks.
- `6a78699838a0` ("block: always verify unfreeze lock on the owner task"): Added `mq_freeze_owner` and `mq_freeze_owner_depth` to `struct request_queue`. Only the owner task decrements `mq_freeze_owner_depth` to 0 and clears `mq_freeze_owner = NULL` via `blk_unfreeze_check_owner()`, returning `true` to release lockdep locks.
- `6f491a8d4b92` ("block: track disk DEAD state automatically for modeling queue freeze lockdep"): Removed `disk_dead` parameter from `blk_freeze_acquire_lock()` and `blk_unfreeze_release_lock()`. Saved `mq_freeze_disk_dead` into `struct request_queue` inside `blk_freeze_set_owner()` when `!q->mq_freeze_depth`. Commit message claimed it was a "per-task variable now", but it was stored in `struct request_queue`.
- `f6661b1d0525` ("block: track queue dying state automatically for modeling queue freeze lockdep"): Removed `queue_dying` parameter from `blk_freeze_acquire_lock()` and `blk_unfreeze_release_lock()`. Saved `mq_freeze_queue_dying = blk_queue_dying(q)` into `struct request_queue` inside `blk_freeze_set_owner()` when `!q->mq_freeze_depth`.
- `b9d4eee7e04b` & `357e1b7f730b`: Refactored elevator initialization and scheduler changes to use standard `blk_mq_freeze_queue` / `blk_mq_unfreeze_queue` instead of manual lock verification.
- **Researched Device Mapper destruction and synchronization:**
- Investigated `drivers/md/dm.c` and `drivers/md/dm-ioctl.c`.
- Analyzed `__dm_destroy()` history:
- `3f77316de0ec` ("dm: separate device deletion from dm_put"): Introduced separation between `dm_put()` and `dm_destroy()`. `dm_destroy()` waits in a loop with `while (atomic_read(&md->holders)) fsleep(1000);` if `wait == true`.
- `3b785fbcf81c` ("dm: mark request_queue dead before destroying the DM device"): Added setting `QUEUE_FLAG_DYING` on `q` before waiting for `holders` to prevent new requests from being queued while `__dm_destroy()` progresses.
- `7a5428dcb790` ("block: fix surprise removal for drivers calling blk_set_queue_dying"): Replaced `blk_set_queue_dying(md->queue)` in `__dm_destroy()` with `blk_mark_disk_dead(md->disk)`.
- Examined recent race fixes in DM:
- `44b43ec132f1` ("dm: fix resume-vs-remove race"): Checked `test_bit(DMF_FREEING, &md->flags)` under `suspend_lock` to reject resume during destruction.
- `5380c7f6335c` ("dm: fix race when loading and unloading a table"): Extended `table_devices_lock` around `add_disk()` and holder registration/unlinking.
---
#### 2. Verified Facts
- **Root cause in block layer queue-freeze lockdep modeling:**
- `blk_freeze_acquire_lock(q)` and `blk_unfreeze_release_lock(q)` in `block/blk.h` rely on `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying`.
- In `__blk_mq_unfreeze_queue()` (`block/blk-mq.c:211-228`):
- `q->mq_freeze_depth` is decremented to 0 under `q->mq_freeze_lock`.
- `blk_unfreeze_check_owner(q)` resets `q->mq_freeze_owner = NULL` and returns `true`.
- `mutex_unlock(&q->mq_freeze_lock)` is released.
- `blk_unfreeze_release_lock(q)` is called *after* `mutex_unlock(&q->mq_freeze_lock)` in `blk_mq_unfreeze_queue_nomemrestore()` (`block/blk-mq.c:230-234`).
- While `q->mq_freeze_depth == 0` and `mq_freeze_lock` is dropped, any concurrent task (e.g. `blk_mark_disk_dead()` calling `__blk_freeze_queue_start(q, current)`) acquires `q->mq_freeze_lock`, observes `!q->mq_freeze_depth`, and overwrites `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead`.
- When the unfreezing task subsequently enters `blk_unfreeze_release_lock(q)`, `!q->mq_freeze_queue_dying` evaluates to `false`, skipping `rwsem_release(&q->q_lockdep_map)`.
- **Root cause trigger in Device Mapper:**
- `table_load()` holds `md->holders` (via `find_device()` / `dm_get(md)`).
- During request-based queue initialization (`dm_setup_md_queue(md, t)` -> `add_disk()` -> `blk_register_queue()` -> `elevator_set_default()` -> `elevator_change()`), `elevator_change()` freezes and unfreezes the queue.
- Concurrently, `dev_remove()` calls `dm_destroy(md)` -> `__dm_destroy(md, true)`.
- In `__dm_destroy(md, true)`:
- `blk_mark_disk_dead(md->disk)` is called at `drivers/md/dm.c:2738` *before* checking `md->holders` at line 2763.
- `blk_mark_disk_dead()` sets `QUEUE_FLAG_DYING` and calls `blk_queue_start_drain()` -> `__blk_freeze_queue_start(q, current)`.
- It does this while `table_load()` is actively running on `md` and holding `md->holders`.
---
#### 3. Current Hypotheses and Lines of Investigation
- **Fix Pattern in Block Layer:**
- `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead` were originally claimed in `f6661b1d0525` and `6f491a8d4b92` to be "one per-task variable", but storing them on `struct request_queue` broke concurrency assumptions.
- Historical pattern: In `f1be1788a32e`, boolean flags were passed down call stacks or captured locally.
- Alternative pattern: Keep lockdep state acquisition/release serialized or capture the flags under `q->mq_freeze_lock` (or release lockdep before dropping `q->mq_freeze_lock` or before `q->mq_freeze_depth` drops to 0).
- Need to check if any other commits in `block/` handle snapshotting/passing lockdep state or releasing under `mq_freeze_lock`.
- **Fix Pattern in Device Mapper:**
- In `__dm_destroy()`, `blk_mark_disk_dead()` was added in `3b785fbcf81c` / `7a5428dcb790` to avoid new requests during device destruction.
- But calling `blk_mark_disk_dead()` before waiting for `atomic_read(&md->holders) == 0` races with operations that hold `md->holders` (like `table_load()`, which may still be initializing or modifying the queue/disk).
- Need to check if previous DM commits moved `blk_mark_disk_dead` or added synchronization against `table_load` (e.g. `md->type_lock`, `DMF_FREEING` check, or waiting on `md->holders`).
---
#### 4. Critical File Paths and Code Snippets
- **`block/blk-mq.c`**:
```c
static bool blk_freeze_set_owner(struct request_queue *q,
struct task_struct *owner)
{
if (!owner)
return false;
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
q->mq_freeze_disk_dead = !q->disk ||
test_bit(GD_DEAD, &q->disk->state) ||
!blk_queue_registered(q);
q->mq_freeze_queue_dying = blk_queue_dying(q);
return true;
}
if (owner == q->mq_freeze_owner)
q->mq_freeze_owner_depth += 1;
return false;
}
...
bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
bool unfreeze;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
q->q_usage_counter.data->force_atomic = true;
q->mq_freeze_depth--;
WARN_ON_ONCE(q->mq_freeze_depth < 0);
if (!q->mq_freeze_depth) {
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
}
unfreeze = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
return unfreeze;
}
void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
{
if (__blk_mq_unfreeze_queue(q, false))
blk_unfreeze_release_lock(q);
}
```
- **`block/blk.h`**:
```c
#ifdef CONFIG_LOCKDEP
static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
if (!q->mq_freeze_queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
```
- **`drivers/md/dm.c` (`__dm_destroy`)**:
```c
static void __dm_destroy(struct mapped_device *md, bool wait)
{
...
spin_lock(&_minor_lock);
idr_replace(&_minor_idr, MINOR_ALLOCED, MINOR(disk_devt(dm_disk(md))));
set_bit(DMF_FREEING, &md->flags);
spin_unlock(&_minor_lock);
blk_mark_disk_dead(md->disk);
...
if (wait)
while (atomic_read(&md->holders))
fsleep(1000);
...
dm_table_destroy(__unbind(md));
free_dev(md);
}
```
---
#### 5. Repetitive Checks to Avoid
- Do not re-check basic commit histories of `f1be1788a32e`, `6a78699838a0`, `6f491a8d4b92`, `f6661b1d0525`, `7a5428dcb790`, `3b785fbcf81c`, or `3f77316de0ec`. Their exact contents and evolutionary sequence are already fully extracted.
- Do not re-verify the definitions of `blk_mark_disk_dead`, `__blk_mark_disk_dead`, `blk_queue_start_drain`, or `elevator_change`.
---
#### 6. Next Steps
1. Search git history for any commits in the block layer (past 1-2 years or since `f6661b1d0525` in Nov 2024) that fixed races or lockdep warnings specifically involving `blk_unfreeze_release_lock`, `blk_freeze_acquire_lock`, or `q_lockdep_map`.
2. Check whether there have been patches or discussions addressing the locking scope of `blk_unfreeze_release_lock(q)` (e.g., whether `rwsem_release` can be called under `mq_freeze_lock` or if `unfreeze` should return boolean flags by reference/value).
3. Check `drivers/md/` git log to see if any similar races between device initialization (`dm_setup_md_queue` / `table_load`) and deletion (`__dm_destroy`) were addressed by serializing on `md->type_lock`, re-ordering `blk_mark_disk_dead()`, or checking `DMF_FREEING` in `table_load()`.
4. Synthesize the findings into the required final response summarizing the idioms, locking rules, and historical patterns for fixing this bug in the block and device-mapper subsystems.
Tokens:
input: 87535
output: 3513
thoughts: 0
|
| 282/2 |
2026/11/03 19:25 |
llm |
history-explorer |
2m
Model:
Tokens:
input: 49421
output: 27
thoughts: 21
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Analyzing the Deletion Mechanism's Commit History**
Okay, so I want to understand the evolution of the `dm_deleting_md` functionality. The most efficient way to get a granular view is to dive straight into the commit history. I'm thinking, "Let's use `git log`". This gives me the chronology of all changes made to that specific code path. Using `git log` will allow me to track down when, why, and how different modifications were made, by who, and in what order. This is the fastest way to understand the thought process that created the deleting mechanism. It should surface potential bugs, inefficiencies, or design decisions that might be relevant to the current problem at hand. With the right flags, I can filter by author, date range, or even specific keywords within commit messages, which allows for a focused investigation.
|
| 283/2 |
2026/11/03 19:28 |
tool |
git-log |
10m
Error:
Args: map[CodeRegexp:dm_deleting_md Count:5]
Results:
|
| 284/2 |
2026/11/03 19:38 |
llm |
history-explorer |
16m
Model:
Tokens:
input: 49701
output: 37
thoughts: 14
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Adding Path Prefix for Driver Management**
Alright, I'm thinking we need to introduce a `PathPrefix` to manage our drivers. Specifically, I'm leaning towards `drivers/md/`. The aim, as I see it, is to establish a clearer separation and organization for these driver-specific resources. This will help to keep the root directory clean, especially as our driver suite continues to grow, reducing clutter and the likelihood of filename collisions. The "md" bit is probably related to the specific storage path. It would make it easier to pinpoint which storage path to search on the API. This structured path prefix should also improve the maintainability of the directory structure.
|
| 285/2 |
2026/11/03 19:55 |
tool |
git-log |
0m
Args: map[CodeRegexp:dm_deleting_md Count:5 PathPrefix:drivers/md/]
Results: map[Output:49de5769702c dm: small cleanup in dm_get_md()
b9a41d21dcea dm: fix race between dm_get_from_kobject() and __dm_destroy()
2bec1f4a8832 dm: fix a race condition in dm_get_md
abdc568b0540 dm: prevent access to md being deleted
c50abeb38026 dm ioctl: forbid messages to devices being deleted
]
|
| 286/2 |
2026/11/03 19:55 |
llm |
history-explorer |
5m
Model:
Tokens:
input: 50039
output: 25
thoughts: 122
Thoughts: Okay, let's dive into these commits.
**Focusing on Recent Device Mapper (DM) Fixes**
Alright, my immediate reaction is, "Hmm, these commits look familiar!" Four recent ones, all touching on Device Mapper, and they all seem to point toward addressing race conditions and potential issues around device deletion. The commit messages jump out: `b9a41d21dcea`, `2bec1f4a8832`, `abdc568b0540`, and `c50abeb38026`. Race conditions during device deletion are always nasty and can be extremely difficult to track down, so let's dig in and get a better understanding of the issues that were fixed. I need to take a look at the code. I'm going to run `git show` on each of these commits to get the full context; understand precisely what changed and see how these fixes were implemented. I want to see what assumptions were incorrect, and how they were corrected. I'm curious: Were these all related, or separate instances of similar underlying problems? Let's get to the bottom of this.
|
| 287/2 |
2026/11/03 20:01 |
tool |
git-show |
0m
Args:
Results: map[Output:commit b9a41d21dceadf8104812626ef85dc56ee8a60ed
Author: Hou Tao <houtao1@huawei.com>
Date: Wed Nov 1 15:42:36 2017 +0800
dm: fix race between dm_get_from_kobject() and __dm_destroy()
The following BUG_ON was hit when testing repeat creation and removal of
DM devices:
kernel BUG at drivers/md/dm.c:2919!
CPU: 7 PID: 750 Comm: systemd-udevd Not tainted 4.1.44
Call Trace:
[<ffffffff81649e8b>] dm_get_from_kobject+0x34/0x3a
[<ffffffff81650ef1>] dm_attr_show+0x2b/0x5e
[<ffffffff817b46d1>] ? mutex_lock+0x26/0x44
[<ffffffff811df7f5>] sysfs_kf_seq_show+0x83/0xcf
[<ffffffff811de257>] kernfs_seq_show+0x23/0x25
[<ffffffff81199118>] seq_read+0x16f/0x325
[<ffffffff811de994>] kernfs_fop_read+0x3a/0x13f
[<ffffffff8117b625>] __vfs_read+0x26/0x9d
[<ffffffff8130eb59>] ? security_file_permission+0x3c/0x44
[<ffffffff8117bdb8>] ? rw_verify_area+0x83/0xd9
[<ffffffff8117be9d>] vfs_read+0x8f/0xcf
[<ffffffff81193e34>] ? __fdget_pos+0x12/0x41
[<ffffffff8117c686>] SyS_read+0x4b/0x76
[<ffffffff817b606e>] system_call_fastpath+0x12/0x71
The bug can be easily triggered, if an extra delay (e.g. 10ms) is added
between the test of DMF_FREEING & DMF_DELETING and dm_get() in
dm_get_from_kobject().
To fix it, we need to ensure the test of DMF_FREEING & DMF_DELETING and
dm_get() are done in an atomic way, so _minor_lock is used.
The other callers of dm_get() have also been checked to be OK: some
callers invoke dm_get() under _minor_lock, some callers invoke it under
_hash_lock, and dm_start_request() invoke it after increasing
md->open_count.
Cc: stable@vger.kernel.org
Signed-off-by: Hou Tao <houtao1@huawei.com>
Signed-off-by: Mike Snitzer <snitzer@redhat.com>
diff --git a/drivers/md/dm.c b/drivers/md/dm.c
index adb874c2411b..dcfa1a8c9390 100644
--- a/drivers/md/dm.c
+++ b/drivers/md/dm.c
@@ -2711,11 +2711,15 @@ struct mapped_device *dm_get_from_kobject(struct kobject *kobj)
md = container_of(kobj, struct mapped_device, kobj_holder.kobj);
- if (test_bit(DMF_FREEING, &md->flags) ||
- dm_deleting_md(md))
- return NULL;
-
+ spin_lock(&_minor_lock);
+ if (test_bit(DMF_FREEING, &md->flags) || dm_deleting_md(md)) {
+ md = NULL;
+ goto out;
+ }
dm_get(md);
+out:
+ spin_unlock(&_minor_lock);
+
return md;
}
]
|
| 288/2 |
2026/11/03 20:01 |
llm |
history-explorer |
5m
Model:
Tokens:
input: 51551
output: 25
thoughts: 17
Thoughts: Okay, here's my interpretation of what's going through my mind when I encounter that Git commit ID:
**Analyzing Commit abdc568b0540**
Alright, *abdc568b0540*. Let's pull that commit hash up and take a look. My initial thoughts are, where does this fit into the bigger picture? What's the context? Is this something I'm already familiar with, or is this a new piece of code I need to understand? My mind immediately starts running through possible related branches, tags, and pull requests. I'm going to want to know:
* **Who authored this?** I need to know who wrote this code. I am familiar with the code base and the people who write code.
* **What was the message?** The commit message better be descriptive and insightful, otherwise I'm going to waste time digging.
* **What files were touched?** I will be looking for what files were modified, and how deeply they were modified. This will determine my approach. Was it a simple bug fix, a feature addition, or a significant refactor?
* **Was it tested?** I need to know about any tests that are involved in this commit. Were they good tests?
* **What does the diff say?** Ok, show me the diff. Is it straightforward or complex? Are there any potential integration issues I need to be aware of? Are there any obvious areas for code review concerns or potential bugs? Does the code adhere to the style guide?
I'm starting to build a mental map of this commit's impact. The specific questions I'll be asking depend heavily on the project and the context in which I'm viewing it. My goal is to quickly and accurately assess the significance of this change, and how it impacts the rest of the code. This will allow me to integrate this into the rest of the project.
|
| 289/2 |
2026/11/03 20:06 |
tool |
git-show |
0m
Args:
Results: map[Output:commit abdc568b0540bec6d3e0afebac496adef1189b77
Author: Kiyoshi Ueda <k-ueda@ct.jp.nec.com>
Date: Thu Aug 12 04:13:54 2010 +0100
dm: prevent access to md being deleted
This patch prevents access to mapped_device which is being deleted.
Currently, even after a mapped_device has been removed from the hash,
it could be accessed through idr_find() using minor number.
That could cause a race and NULL pointer reference below:
CPU0 CPU1
------------------------------------------------------------------
dev_remove(param)
down_write(_hash_lock)
dm_lock_for_deletion(md)
spin_lock(_minor_lock)
set_bit(DMF_DELETING)
spin_unlock(_minor_lock)
__hash_remove(hc)
up_write(_hash_lock)
dev_status(param)
md = find_device(param)
down_read(_hash_lock)
__find_device_hash_cell(param)
dm_get_md(param->dev)
md = dm_find_md(dev)
spin_lock(_minor_lock)
md = idr_find(MINOR(dev))
spin_unlock(_minor_lock)
dm_put(md)
free_dev(md)
dm_get(md)
up_read(_hash_lock)
__dev_status(md, param)
dm_put(md)
This patch fixes such problems.
Signed-off-by: Kiyoshi Ueda <k-ueda@ct.jp.nec.com>
Signed-off-by: Jun'ichi Nomura <j-nomura@ce.jp.nec.com>
Cc: stable@kernel.org
Signed-off-by: Alasdair G Kergon <agk@redhat.com>
diff --git a/drivers/md/dm.c b/drivers/md/dm.c
index a3f21dc02bd8..ba6934c3e2c5 100644
--- a/drivers/md/dm.c
+++ b/drivers/md/dm.c
@@ -2136,6 +2136,7 @@ static struct mapped_device *dm_find_md(dev_t dev)
md = idr_find(&_minor_idr, minor);
if (md && (md == MINOR_ALLOCED ||
(MINOR(disk_devt(dm_disk(md))) != minor) ||
+ dm_deleting_md(md) ||
test_bit(DMF_FREEING, &md->flags))) {
md = NULL;
goto out;
]
|
| 290/2 |
2026/11/03 20:06 |
llm |
history-explorer |
3m
Model:
Tokens:
input: 52739
output: 38
thoughts: 104
Thoughts: Here's my analysis of the code sequence, as I see it:
**Deletion Sequence Deep Dive**
Okay, so I'm looking at commit `abdc568b0540` and specifically the `dev_remove(param)` function. The core of this seems to be managing device removal within the device mapper framework. First, we take a write lock, `down_write(_hash_lock)`. This suggests a global or frequently accessed data structure, likely a hash table, that needs protection from concurrent modification during the deletion.
Then we hit the interesting part: `dm_lock_for_deletion(md)`. My instincts immediately go to `drivers/md/dm.c` to see how this function is implemented. This sounds like it's preparing the device metadata, likely the `md` struct itself, for deletion. Inside `dm_lock_for_deletion()`, `set_bit(DMF_DELETING)` is called. That's a strong signal. The `DMF_DELETING` bit probably indicates that this device is in a transient state, preventing new operations or potentially blocking other processes.
Next is `__hash_remove(hc)`. This seems pretty straightforward, it's removing an entry from the hash table. Given the prior lock, the `hc` (hash container) element is likely the structure containing the mapping information.
Finally, `up_write(_hash_lock)` releases the write lock on the hash table. So, it appears we're locking, manipulating the metadata, removing the entry from a hash, and then unlocking. Seems like a safe and efficient way to handle deletion.
|
| 291/2 |
2026/11/03 20:10 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/md/dm.c Name:dm_lock_for_deletion]
Results: map[SourceCode: 362: /*
363: * Guarantees nothing is using the device before it's deleted.
364: */
365: int dm_lock_for_deletion(struct mapped_device *md, bool mark_deferred, bool only_deferred)
366: {
367: int r = 0;
368:
369: spin_lock(&_minor_lock);
370:
371: if (dm_open_count(md)) {
372: r = -EBUSY;
373: if (mark_deferred)
374: set_bit(DMF_DEFERRED_REMOVE, &md->flags);
375: } else if (only_deferred && !test_bit(DMF_DEFERRED_REMOVE, &md->flags))
376: r = -EEXIST;
377: else
378: set_bit(DMF_DELETING, &md->flags);
379:
380: spin_unlock(&_minor_lock);
381:
382: return r;
383: }
SourceFile:drivers/md/dm.c]
|
| 292/2 |
2026/11/03 20:10 |
llm |
history-explorer |
3m
Model:
Tokens:
input: 53572
output: 36
thoughts: 118
Thoughts: Okay, let's break this down.
**Ensuring Safe Device Deletion in the Device Mapper**
Right, so I'm digging into `dm_lock_for_deletion` and it's making sure no process is actively using a device before it gets the axe. Makes perfect sense, a critical safety check. The key is this call to `dm_open_count(md)`. This *has* to be the heart of the matter. If that count is zero, meaning nothing has the device open, *then* it flips the `DMF_DELETING` flag on `md->flags`. That's the signal, the go-ahead.
Now, where does the actual removal happen? Ah, `dev_remove()` within `drivers/md/dm-ioctl.c`. Got it. That's the function that'll take the device offline, now I need to dive into its logic to understand the full deletion process, making sure it respects this "DELETING" flag. This is likely the crucial sequence of operations I need to review, the details of which are central to ensuring data integrity. I need to understand how the system guarantees this device is indeed safely removed.
|
| 293/2 |
2026/11/03 20:13 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/md/dm-ioctl.c Name:dev_remove]
Results: map[SourceCode:1063: static int dev_remove(struct file *filp, struct dm_ioctl *param, size_t param_size)
1064: {
1065: struct hash_cell *hc;
1066: struct mapped_device *md;
1067: int r;
1068: struct dm_table *t;
1069: struct dm_ima_context *ima_context = NULL;
1070: unsigned int ima_idx;
1071:
1072: dm_ima_alloc_context(&ima_context, true);
1073: down_write(&_hash_lock);
1074: hc = __find_device_hash_cell(param);
1075:
1076: if (!hc) {
1077: DMDEBUG_LIMIT("device doesn't appear to be in the dev hash table.");
1078: up_write(&_hash_lock);
1079: dm_ima_free_context(ima_context);
1080: return -ENXIO;
1081: }
1082:
1083: md = hc->md;
1084:
1085: /*
1086: * Ensure the device is not open and nothing further can open it.
1087: */
1088: r = dm_lock_for_deletion(md, !!(param->flags & DM_DEFERRED_REMOVE), false);
1089: if (r) {
1090: if (r == -EBUSY && param->flags & DM_DEFERRED_REMOVE) {
1091: up_write(&_hash_lock);
1092: dm_put(md);
1093: dm_ima_free_context(ima_context);
1094: return 0;
1095: }
1096: DMDEBUG_LIMIT("unable to remove open device %s", hc->name);
1097: up_write(&_hash_lock);
1098: dm_put(md);
1099: dm_ima_free_context(ima_context);
1100: return r;
1101: }
1102:
1103: ima_idx = dm_ima_init_context(hc, ima_context, true);
1104: t = __hash_remove(hc);
1105: up_write(&_hash_lock);
1106:
1107: if (t) {
1108: dm_sync_table(md);
1109: dm_table_destroy(t);
1110: }
1111:
1112: param->flags &= ~DM_DEFERRED_REMOVE;
1113:
1114: dm_ima_measure_on_device_remove(md, false, ima_context, ima_idx);
1115: dm_ima_free_context(ima_context);
1116:
1117: if (!dm_kobject_uevent(md, KOBJ_REMOVE, param->event_nr, false))
1118: param->flags |= DM_UEVENT_GENERATED_FLAG;
1119:
1120: dm_put(md);
1121: dm_destroy(md);
1122: return 0;
1123: }
SourceFile:drivers/md/dm-ioctl.c]
|
| 294/2 |
2026/11/03 20:13 |
llm |
history-explorer |
4m
Model:
Tokens:
input: 54913
output: 25
thoughts: 837
Thoughts: **Analyzing the Device Mapper Removal Process**
Okay, let's break this down. I'm looking at `dev_remove` and tracing its steps. The flow seems straightforward enough: `dm_lock_for_deletion` checks if the device is open, but crucially, *not* if there are any active holders. Then, it removes the hash cell and destroys the device with `dm_destroy`. `dm_destroy` calls `__dm_destroy` with a `true` flag.
Inside `__dm_destroy`, the minor ID is replaced in the IDR, and the `DMF_FREEING` flag is set. Then it calls `blk_mark_disk_dead(md->disk)`. It then acquires the `suspend_lock`, performs some target pre- and post-suspend operations (conditionally), and then releases the lock. Finally, there's a loop that waits on `atomic_read(&md->holders)` to reach zero, which represents the remaining references to the device. The comments here explicitly state this wait is to ensure no one increments the reference count after the device enters the `DMF_FREEING` state.
But here's where my alarm bells start ringing. `blk_mark_disk_dead(md->disk)` is called immediately when `__dm_destroy` *starts*, before we wait for `atomic_read(&md->holders)`! The comment explains why the wait on `md->holders` is there: to allow references held by other tasks (e.g., `table_load()`) to be dropped safely before the device is actually destroyed.
Now, why is that a problem? The logic implies that `table_load()` is holding a reference (via `md->holders`) and, more importantly, it's currently executing in `dm_setup_md_queue()` or `add_disk()`. That's the crux of it. `table_load()` is touching the request queue. If `__dm_destroy()` waits for `md->holders` to reach zero *before* calling `blk_mark_disk_dead()`, or if it acquires `md->type_lock`, or if `table_load()` checks `DMF_DELETING` / `DMF_FREEING` *before* modifying the queue/disk, then `table_load()` would either finish or fail before `__dm_destroy()` touches the disk. This would allow `table_load()` to operate on a valid request queue. But if not, we have a race.
I need to see what the justification was for this design. I'm going to look at commit `3b785fbcf81c` to understand the rationale behind `blk_set_queue_dying`. I need to figure out *why* `blk_mark_disk_dead` was moved there.
|
| 295/2 |
2026/11/03 20:18 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 3b785fbcf81c3533772c52b717f77293099498d3
Author: Bart Van Assche <bvanassche@acm.org>
Date: Wed Aug 31 15:17:49 2016 -0700
dm: mark request_queue dead before destroying the DM device
This avoids that new requests are queued while __dm_destroy() is in
progress.
Signed-off-by: Bart Van Assche <bart.vanassche@sandisk.com>
Signed-off-by: Mike Snitzer <snitzer@redhat.com>
Cc: stable@vger.kernel.org
diff --git a/drivers/md/dm.c b/drivers/md/dm.c
index c0742129a9cb..0f2928b3136b 100644
--- a/drivers/md/dm.c
+++ b/drivers/md/dm.c
@@ -1873,6 +1873,7 @@ EXPORT_SYMBOL_GPL(dm_device_name);
static void __dm_destroy(struct mapped_device *md, bool wait)
{
+ struct request_queue *q = dm_get_md_queue(md);
struct dm_table *map;
int srcu_idx;
@@ -1883,6 +1884,10 @@ static void __dm_destroy(struct mapped_device *md, bool wait)
set_bit(DMF_FREEING, &md->flags);
spin_unlock(&_minor_lock);
+ spin_lock_irq(q->queue_lock);
+ queue_flag_set(QUEUE_FLAG_DYING, q);
+ spin_unlock_irq(q->queue_lock);
+
if (dm_request_based(md) && md->kworker_task)
flush_kthread_worker(&md->kworker);
]
|
| 296/2 |
2026/11/03 20:18 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 56901
output: 26
thoughts: 156
Thoughts: **Analyzing a Recent Code Change**
Okay, let's dive into this. I'm looking at commit `3b785fbcf81c`. Ah, right, in 2016, Bart Van Assche added `queue_flag_set(QUEUE_FLAG_DYING, q)` *immediately* after `set_bit(DMF_FREEING, &md->flags)`. Interesting placement...
And now, I see that commit `7a5428dcb790`, "block: fix surprise removal for drivers calling blk_set_queue_dying," is relevant. It looks like this commit replaced the call to `blk_set_queue_dying(md->queue)` in `__dm_destroy` with a call to `blk_mark_disk_dead(md->disk)`. Hmmm, I need to see what's changed and why. I'm going to take a closer look at the changes in `7a5428dcb790` to understand the implications of this shift. Let's start by examining that commit itself to see what was updated.
|
| 297/2 |
2026/11/03 20:18 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 7a5428dcb7902700b830e912feee4e845df7c019
Author: Christoph Hellwig <hch@lst.de>
Date: Thu Feb 17 08:52:31 2022 +0100
block: fix surprise removal for drivers calling blk_set_queue_dying
Various block drivers call blk_set_queue_dying to mark a disk as dead due
to surprise removal events, but since commit 8e141f9eb803 that doesn't
work given that the GD_DEAD flag needs to be set to stop I/O.
Replace the driver calls to blk_set_queue_dying with a new (and properly
documented) blk_mark_disk_dead API, and fold blk_set_queue_dying into the
only remaining caller.
Fixes: 8e141f9eb803 ("block: drain file system I/O on del_gendisk")
Reported-by: Markus BlΓΆchl <markus.bloechl@ipetronik.com>
Signed-off-by: Christoph Hellwig <hch@lst.de>
Reviewed-by: Sagi Grimberg <sagi@grimberg.me>
Link: https://lore.kernel.org/r/20220217075231.1140-1-hch@lst.de
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-core.c b/block/blk-core.c
index d93e3bb9a769..1039515c99d6 100644
--- a/block/blk-core.c
+++ b/block/blk-core.c
@@ -284,13 +284,6 @@ void blk_queue_start_drain(struct request_queue *q)
wake_up_all(&q->mq_freeze_wq);
}
-void blk_set_queue_dying(struct request_queue *q)
-{
- blk_queue_flag_set(QUEUE_FLAG_DYING, q);
- blk_queue_start_drain(q);
-}
-EXPORT_SYMBOL_GPL(blk_set_queue_dying);
-
/**
* blk_cleanup_queue - shutdown a request queue
* @q: request queue to shutdown
@@ -308,7 +301,8 @@ void blk_cleanup_queue(struct request_queue *q)
WARN_ON_ONCE(blk_queue_registered(q));
/* mark @q DYING, no new request or merges will be allowed afterwards */
- blk_set_queue_dying(q);
+ blk_queue_flag_set(QUEUE_FLAG_DYING, q);
+ blk_queue_start_drain(q);
blk_queue_flag_set(QUEUE_FLAG_NOMERGES, q);
blk_queue_flag_set(QUEUE_FLAG_NOXMERGES, q);
diff --git a/block/genhd.c b/block/genhd.c
index 626c8406f21a..9eca1f7d35c9 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -548,6 +548,20 @@ int __must_check device_add_disk(struct device *parent, struct gendisk *disk,
}
EXPORT_SYMBOL(device_add_disk);
+/**
+ * blk_mark_disk_dead - mark a disk as dead
+ * @disk: disk to mark as dead
+ *
+ * Mark as disk as dead (e.g. surprise removed) and don't accept any new I/O
+ * to this disk.
+ */
+void blk_mark_disk_dead(struct gendisk *disk)
+{
+ set_bit(GD_DEAD, &disk->state);
+ blk_queue_start_drain(disk->queue);
+}
+EXPORT_SYMBOL_GPL(blk_mark_disk_dead);
+
/**
* del_gendisk - remove the gendisk
* @disk: the struct gendisk to remove
diff --git a/drivers/block/mtip32xx/mtip32xx.c b/drivers/block/mtip32xx/mtip32xx.c
index e6005c232328..2b588b62cbbb 100644
--- a/drivers/block/mtip32xx/mtip32xx.c
+++ b/drivers/block/mtip32xx/mtip32xx.c
@@ -4112,7 +4112,7 @@ static void mtip_pci_remove(struct pci_dev *pdev)
"Completion workers still active!\n");
}
- blk_set_queue_dying(dd->queue);
+ blk_mark_disk_dead(dd->disk);
set_bit(MTIP_DDF_REMOVE_PENDING_BIT, &dd->dd_flag);
/* Clean up the block layer. */
diff --git a/drivers/block/rbd.c b/drivers/block/rbd.c
index 4203cdab8abf..b844432bad20 100644
--- a/drivers/block/rbd.c
+++ b/drivers/block/rbd.c
@@ -7185,7 +7185,7 @@ static ssize_t do_rbd_remove(struct bus_type *bus,
* IO to complete/fail.
*/
blk_mq_freeze_queue(rbd_dev->disk->queue);
- blk_set_queue_dying(rbd_dev->disk->queue);
+ blk_mark_disk_dead(rbd_dev->disk);
}
del_gendisk(rbd_dev->disk);
diff --git a/drivers/block/xen-blkfront.c b/drivers/block/xen-blkfront.c
index ccd0dd0c6b83..ca71a0585333 100644
--- a/drivers/block/xen-blkfront.c
+++ b/drivers/block/xen-blkfront.c
@@ -2126,7 +2126,7 @@ static void blkfront_closing(struct blkfront_info *info)
/* No more blkif_request(). */
blk_mq_stop_hw_queues(info->rq);
- blk_set_queue_dying(info->rq);
+ blk_mark_disk_dead(info->gd);
set_capacity(info->gd, 0);
for_each_rinfo(info, rinfo, i) {
diff --git a/drivers/md/dm.c b/drivers/md/dm.c
index dcbd6d201619..997ace47bbd5 100644
--- a/drivers/md/dm.c
+++ b/drivers/md/dm.c
@@ -2077,7 +2077,7 @@ static void __dm_destroy(struct mapped_device *md, bool wait)
set_bit(DMF_FREEING, &md->flags);
spin_unlock(&_minor_lock);
- blk_set_queue_dying(md->queue);
+ blk_mark_disk_dead(md->disk);
/*
* Take suspend_lock so that presuspend and postsuspend methods
diff --git a/drivers/nvme/host/core.c b/drivers/nvme/host/core.c
index 79005ea1a33e..469f23186159 100644
--- a/drivers/nvme/host/core.c
+++ b/drivers/nvme/host/core.c
@@ -4574,7 +4574,7 @@ static void nvme_set_queue_dying(struct nvme_ns *ns)
if (test_and_set_bit(NVME_NS_DEAD, &ns->flags))
return;
- blk_set_queue_dying(ns->queue);
+ blk_mark_disk_dead(ns->disk);
nvme_start_ns_queue(ns);
set_capacity_and_notify(ns->disk, 0);
diff --git a/drivers/nvme/host/multipath.c b/drivers/nvme/host/multipath.c
index f8bf6606eb2f..ff775235534c 100644
--- a/drivers/nvme/host/multipath.c
+++ b/drivers/nvme/host/multipath.c
@@ -848,7 +848,7 @@ void nvme_mpath_remove_disk(struct nvme_ns_head *head)
{
if (!head->disk)
return;
- blk_set_queue_dying(head->disk->queue);
+ blk_mark_disk_dead(head->disk);
/* make sure all pending bios are cleaned up */
kblockd_schedule_work(&head->requeue_work);
flush_work(&head->requeue_work);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index f35aea98bc35..16b47035e4b0 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -748,7 +748,8 @@ extern bool blk_queue_can_use_dma_map_merging(struct request_queue *q,
bool __must_check blk_get_queue(struct request_queue *);
extern void blk_put_queue(struct request_queue *);
-extern void blk_set_queue_dying(struct request_queue *);
+
+void blk_mark_disk_dead(struct gendisk *disk);
#ifdef CONFIG_BLOCK
/*
]
|
| 298/2 |
2026/11/03 20:18 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 59926
output: 34
thoughts: 171
Thoughts: Here's my analysis of that code change:
**Analyzing the Block Device Death Sequence**
Okay, so I'm looking at commit `7a5428dcb790`. It seems someone's replaced `blk_mark_disk_dead(md->disk)` with `blk_set_queue_dying(md->queue)`. Interesting. And *then* I see that `blk_mark_disk_dead` itself calls `blk_queue_start_drain(disk->queue)`. Now *that* function, `blk_queue_start_drain`, calls `__blk_freeze_queue_start(q, current)`. This all seems like a targeted approach to gracefully handling the death of a block device. The flow of calling routines strongly suggests a carefully designed mechanism for freezing, draining, and ultimately marking the queue as dead.
Now, I'm curious about the specific details of when the `QUEUE_FLAG_DYING` flag gets set. I'd like to trace back and pinpoint the exact commit that introduced the use of `blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue)` within `blk_mark_disk_dead`. A quick `git-blame` on `block/genhd.c` around the `blk_mark_disk_dead` function will likely give me a clear history of that code path. That will tell me when and why this specific flag was introduced, giving me a better understanding of the overall design decision.
|
| 299/2 |
2026/11/03 20:18 |
tool |
git-blame |
0m
Args: map[End:700 File:block/genhd.c Start:685]
Results: map[Output:d8530de5a6e82 block/genhd.c 685) *
d8530de5a6e82 block/genhd.c 686) * Mark as disk as dead (e.g. surprise removed) and don't accept any new I/O
d8530de5a6e82 block/genhd.c 687) * to this disk.
d8530de5a6e82 block/genhd.c 688) */
d8530de5a6e82 block/genhd.c 689) void blk_mark_disk_dead(struct gendisk *disk)
d8530de5a6e82 block/genhd.c 690) {
7e9a46004b471 block/genhd.c 691) blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
d8530de5a6e82 block/genhd.c 692) __blk_mark_disk_dead(disk);
d8530de5a6e82 block/genhd.c 693) blk_report_disk_dead(disk, true);
7a5428dcb7902 block/genhd.c 694) }
7a5428dcb7902 block/genhd.c 695) EXPORT_SYMBOL_GPL(blk_mark_disk_dead);
7a5428dcb7902 block/genhd.c 696)
98e68f67020ce block/genhd.c 697) static void __del_gendisk(struct gendisk *disk)
^1da177e4c3f4 drivers/block/genhd.c 698) {
8e141f9eb803e block/genhd.c 699) struct request_queue *q = disk->queue;
eec1be4c30df7 block/genhd.c 700) struct block_device *part;
]
|
| 300/2 |
2026/11/03 20:18 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 61007
output: 28
thoughts: 21
Thoughts: Okay, let's dive into commit `7e9a46004b471`. I need to understand what changed there. I'm hoping it's something relatively straightforward, ideally addressing a specific issue or implementing a clear improvement. I'll start by looking at the diffs; that's always the best entry point. I'll pay close attention to the context of any changes β are they touching core algorithms, data structures, or just UI elements? Are there any obvious performance implications? I'll be looking for potential regressions, unintended side effects, or any code smells that might indicate a deeper problem. Depending on the size of the commit, I may need to consult associated documentation, any relevant bug reports or tickets that this addresses, or even other commits. And of course, I'll assess the commit message to see if it concisely summarizes the rationale behind the change. I expect to be able to quickly grasp the intention and impact of the changes to determine whether or not it warrants further investigation.
|
| 301/2 |
2026/11/03 20:18 |
tool |
git-show |
0m
Args: map[Commit:7e9a46004b471]
Results: map[Output:commit 7e9a46004b471eaf69b082c473d865316a4158e0
Author: θ‘θΏε€ <hulianqin@vivo.com>
Date: Wed Aug 12 11:59:04 2026 +0000
block: set QUEUE_FLAG_DYING unconditionally in blk_mark_disk_dead()
Disks created via blk_mq_alloc_disk_for_queue() (e.g. SCSI SD disks)
do not have GD_OWNS_QUEUE set. Currently __blk_mark_disk_dead() only
sets QUEUE_FLAG_DYING when GD_OWNS_QUEUE is set, so for such disks
blk_queue_enter() and __bio_queue_enter() cannot detect the dying
state via blk_queue_dying() and remain blocked waiting for I/O that
will never complete after surprise removal.
blk_mark_disk_dead() is the explicit "surprise removal" API -- the
caller has already decided the disk is dead. Setting QUEUE_FLAG_DYING
unconditionally here is appropriate: any in-flight I/O from other
threads should get -ENODEV immediately from blk_queue_enter()
regardless of GD_OWNS_QUEUE ownership.
For disks that already have GD_OWNS_QUEUE set, __blk_mark_disk_dead()
will set the flag again which is harmless.
Fixes: 6f8191fdf41d ("block: simplify disk shutdown")
Cc: stable@vger.kernel.org
Signed-off-by: Lianqin Hu <hulianqin@vivo.com>
Reviewed-by: Christoph Hellwig <hch@lst.de>
Link: https://patch.msgid.link/PUZPR06MB62247E82E66A3ED46CC3E6C7D2DC2@PUZPR06MB6224.apcprd06.prod.outlook.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/genhd.c b/block/genhd.c
index df2c3c69b467..7b089e2d52c4 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -681,6 +681,7 @@ static bool __blk_mark_disk_dead(struct gendisk *disk)
*/
void blk_mark_disk_dead(struct gendisk *disk)
{
+ blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
__blk_mark_disk_dead(disk);
blk_report_disk_dead(disk, true);
}
]
|
| 302/2 |
2026/11/03 20:18 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 61986
output: 38
thoughts: 38
Thoughts: Okay, let's dive into this. I need to understand `__blk_mark_disk_dead(struct gendisk *disk)`. My immediate instinct is to check its implementation, and that's going to be in `block/genhd.c`. Let's see what's happening under the hood there.
|
| 303/2 |
2026/11/03 20:19 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/genhd.c Name:__blk_mark_disk_dead]
Results: map[SourceCode: 660: static bool __blk_mark_disk_dead(struct gendisk *disk)
661: {
662: /*
663: * Fail any new I/O.
664: */
665: if (test_and_set_bit(GD_DEAD, &disk->state))
666: return false;
667:
668: if (test_bit(GD_OWNS_QUEUE, &disk->state))
669: blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
670:
671: /*
672: * Stop buffered writers from dirtying pages that can't be written out.
673: */
674: set_capacity(disk, 0);
675:
676: /*
677: * Prevent new I/O from crossing bio_queue_enter().
678: */
679: return blk_queue_start_drain(disk->queue);
680: }
SourceFile:block/genhd.c]
|
| 304/2 |
2026/11/03 20:19 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 62452
output: 38
thoughts: 226
Thoughts: Here's my analysis of the provided code snippet:
**Diving into Disk Death**
Okay, so I'm looking at this `__blk_mark_disk_dead` function. It seems pretty critical for handling a disk going belly up. My first thought is to understand how it works and its implications, so let's break it down.
First, the function uses `test_and_set_bit(GD_DEAD, &disk->state)`. That's a classic atomic operation to mark the disk as "dead" if it isn't already. If the disk *was* already dead, it bails out quickly with `return false`. Makes sense, we don't need to do this twice.
Then there's `test_bit(GD_OWNS_QUEUE, &disk->state)`. If the disk owns its own queue, this sets the `QUEUE_FLAG_DYING` flag on the queue itself using `blk_queue_flag_set`. That's smart; we're signaling the queue that it's going through some changes.
Next, `set_capacity(disk, 0)` is a simple and effective measure to prevent buffered writers from trying to dirty pages that are no longer usable. No writes should occur from here!
Finally, the function calls `blk_queue_start_drain(disk->queue)`. Okay, this is the crux of it. This is where the magic (or at least, the crucial mechanics) of preventing further I/O lies. Obviously, the intention is to stop new I/O requests from entering the queue. I should really understand what this `blk_queue_start_drain` function actually does. I'll have to investigate that to confirm this assumption, so let me go and find the definition of `blk_queue_start_drain`. I'll head over to `block/blk-core.c` and dig into that.
|
| 305/2 |
2026/11/03 20:19 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/blk-core.c Name:blk_queue_start_drain]
Results: map[SourceCode: 327: bool blk_queue_start_drain(struct request_queue *q)
328: {
329: /*
330: * When queue DYING flag is set, we need to block new req
331: * entering queue, so we call blk_freeze_queue_start() to
332: * prevent I/O from crossing blk_queue_enter().
333: */
334: bool freeze = __blk_freeze_queue_start(q, current);
335: if (queue_is_mq(q))
336: blk_mq_wake_waiters(q);
337: /* Make blk_queue_enter() reexamine the DYING flag. */
338: wake_up_all(&q->mq_freeze_wq);
339:
340: return freeze;
341: }
SourceFile:block/blk-core.c]
|
| 306/2 |
2026/11/03 20:19 |
llm |
history-explorer |
1m
Model:
Tokens:
input: 63398
output: 41
thoughts: 516
Thoughts: **Analyzing a Potential Block Layer Race Condition**
Okay, so I've been digging into this block layer issue, and here's what I've got so far. It seems like we're dealing with a nasty race condition related to queue freezing, disk death handling, and lockdep. I've been tracing the execution path, and here's the scenario:
`blk_queue_start_drain` ultimately calls `__blk_freeze_queue_start`. On the other hand, `blk_mark_disk_dead` is where things get interesting. It calls `blk_queue_flag_set` to signal the `QUEUE_FLAG_DYING` state and then proceeds to `__blk_mark_disk_dead`. Critically, `__blk_mark_disk_dead` then *also* calls `blk_queue_start_drain`, resulting in another call to `__blk_freeze_queue_start`.
The core problem, as I see it, stems from the fact that `blk_mark_disk_dead` doesn't acquire or release any lockdep locks itself. This is where the concurrency issue pops up. Specifically, it means the thread that initiates the disk death, let's call it Thread 2, can become the `q->mq_freeze_owner` if the freeze depth is 0 at that point. It also sets `q->mq_freeze_queue_dying = true`.
Now consider the unfreezing thread, Thread 1, which calls `blk_mq_unfreeze_queue`. It eventually decrements `q->mq_freeze_depth` to 0 and unlocks `q->mq_freeze_lock`. Here's the rub: Thread 2 can then *immediately* call `blk_mark_disk_dead`, re-acquiring the lock and becoming the owner, and resetting the `mq_freeze_queue_dying` flag!
Thread 1 then calls `blk_unfreeze_release_lock(q)`. It checks if `q->mq_freeze_queue_dying` is false, and it won't be, so it skips releasing the `q->q_lockdep_map`. This is critical: Thread 1 exits with the lock still *held*, even though it believes the queue is unfrozen, creating the potential for lockdep violations later on.
My immediate thought is, are there similar race conditions lurking in other parts of the block layer or in related drivers, like the MD driver? I need to broaden the search to see if this pattern has been seen before. I'm going to look for commits in `block/` that touch `blk-mq.c` or `blk.h` and relate to `freeze`, `lockdep`, or `unfreeze`. This should give me a better understanding of the wider context and possibly reveal similar past issues or corrective measures. I'm going to also check how the code is structured in other parts of the kernel to see if there is any similar concurrency or locking setup.
|
| 307/2 |
2026/11/03 20:20 |
tool |
git-log |
0m
Args: map[CodeRegexp:unfreeze.*lock Count:10 PathPrefix:block/ Since:3 years]
Results: map[Output:f6661b1d0525 block: track queue dying state automatically for modeling queue freeze lockdep
b9d4eee7e04b block: don't verify queue freeze manually in elevator_init_mq()
6f491a8d4b92 block: track disk DEAD state automatically for modeling queue freeze lockdep
357e1b7f730b block: don't verify IO lock for freeze/unfreeze in elevator_init_mq()
f1be1788a32e block: model freeze & enter queue as lock for supporting lockdep
]
|
| 308/2 |
2026/11/03 20:20 |
llm |
history-explorer |
2m
Model:
Tokens:
input: 64747
output: 44
thoughts: 28
Thoughts: Okay, here's my attempt at summarizing those thoughts from an expert's perspective, using a first-person narrative:
**Digging into the Block Layer Ownership Changes**
Right, let's get down to brass tacks. I need to pinpoint the changes related to `blk_freeze_set_owner` and `blk_unfreeze_check_owner`. These are crucial functions; they're the heart of how the block layer handles freezing and unfreezing, specifically regarding ownership. I need to understand the commits that touched these. This is likely related to the overall change for security improvements. Knowing what changed, and why, is vital for several reasons: perhaps there's a vulnerability that was patched, maybe the freeze/unfreeze logic changed, or perhaps a new feature was introduced that relied on these functions. Understanding these commits is the path to solving this.
|
| 309/2 |
2026/11/03 20:23 |
tool |
git-log |
0m
Args: map[CodeRegexp:blk_freeze_set_owner Count:10 PathPrefix:block/ Since:3 years]
Results: map[Output:6a78699838a0 block: always verify unfreeze lock on the owner task
]
|
| 310/2 |
2026/11/03 20:23 |
llm |
history-explorer |
4m
Model:
Tokens:
input: 65037
output: 45
thoughts: 18
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Analyzing `blk_unfreeze_check_owner` Commits**
Right, let's dive into the commit history surrounding `blk_unfreeze_check_owner`. I need to understand the evolution of this particular function. My primary goal here is to identify any potential regression points, security vulnerabilities, or subtle performance changes introduced through modification of this function, considering the importance of block layer freezing/unfreezing in general system stability. I'll be looking for changes in error handling, locking behavior, and any alterations to data structures this function touches. I expect to see commits related to filesystem integration, device mapper interactions, and perhaps even some interactions with the control group infrastructure. Given its name, I'd pay close attention to the `owner` aspect, which might involve security contexts or resource management considerations. I'll be particularly interested in commits that seem to increase the scope of this check, as an overly aggressive check might hurt performance. I might also look for related functions that could have impact as well.
|
| 311/2 |
2026/11/03 20:27 |
tool |
git-log |
0m
Args: map[CodeRegexp:blk_unfreeze_check_owner Count:10 PathPrefix:block/ Since:3 years]
Results: map[Output:6a78699838a0 block: always verify unfreeze lock on the owner task
]
|
| 312/2 |
2026/11/03 20:27 |
llm |
history-explorer |
2m
Model:
Tokens:
input: 65363
output: 36
thoughts: 32
Thoughts: Here's my thought process, summarized as you requested:
**Investigating Potential Deadlock Scenarios in Kernel Space**
Okay, so I'm thinking, "Where would I even start looking for this specific issue?" The phrase "lock held when returning to user space" screams potential deadlock, especially if we're dealing with block device interaction or RAID functionality. That symptom points to a common bug pattern where a kernel lock isn't released correctly, and the subsequent return to userspace causes all sorts of problems. Given my expertise, I know that `block/` and `drivers/md/` are obvious candidates for that kind of misbehavior. My instinct is that's where I need to focus my search for this type of bug. Therefore, I need to start my investigation by searching the commit messages for that very phrase across all commits in those two kernel directories! It's a targeted approach, hopefully I can quickly pinpoint some relevant commits.
|
| 313/2 |
2026/11/03 20:30 |
tool |
git-log |
0m
Args: map[Count:10 MessageRegexps:[lock held when returning to user space] Since:3 years]
Results: map[Output:d42032c0fe3c mm/hugetlb: don't clear the resv_map of a VMA whose lock is held
17a4fde81d3a afs: Fix merge preference rule failure condition
9b234a97b10c rtnetlink: fix rtnl_dump_ifinfo() error path
]
|
| 314/2 |
2026/11/03 20:30 |
llm |
history-explorer |
1m
Model:
Tokens:
input: 65724
output: 34
thoughts: 18
Thoughts: Okay, here's my summary, presented as a stream of thought:
**Diving into the Codebase: Targeting `q_usage_counter`**
Alright, time to get to work. I need to understand how `q_usage_counter` is being utilized across this repository. My first instinct, given the size and complexity, is to go straight for the commit messages. I'm going to leverage my familiarity with the search tools to quickly identify any modifications related to that specific term. This is a targeted approach; hopefully, it will reveal contexts, justifications for changes, and potential dependencies that I can then analyze in more detail. This quick scan of commit history should provide an initial roadmap for deeper investigations, I will assess from that point.
|
| 315/2 |
2026/11/03 20:32 |
tool |
git-log |
0m
Args: map[Count:10 MessageRegexps:[q_usage_counter] Since:3 years]
Results: map[Output:b3ce7572130f nvme-multipath: revalidate head zones after unfreezing the head queue
7fc61cdab130 Revert "nvme-tcp: lockdep: use dynamic lockdep keys per socket instance"
0ba6912f7e97 Revert "once: don't use a work queue to reset sleepable static key"
06a2ff603f1f loop: Fix recently introduced lock inversion
3dd63dba8f9c block: avoid potential deadlock on zone revalidation failure
19bdb70c77d3 nvme-tcp: lockdep: use dynamic lockdep keys per socket instance
26bb12b9caaf nvme-tcp: teardown circular locking fixes
e9b004ff8306 blk-wbt: remove WARN_ON_ONCE from wbt_init_enable_default()
6a5e3de9c2bb f2fs: fix false alarm of lockdep on cp_global_sem lock
41afaeeda509 blk-wbt: fix possible deadlock to nest pcpu_alloc_mutex under q_usage_counter
]
|
| 316/2 |
2026/11/03 20:32 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 66216
output: 41
thoughts: 24
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Analyzing Commit Messages Related to Lockdep Maps**
Alright, my internal radar just pinged. I'm focusing on the commit logs and immediately scanning for mentions of `q_lockdep_map` or `io_lockdep_map`. These are the red flags that I need to investigate further. They are indicators of potential lock dependency issues related to either queue locks or I/O subsystem locks within this specific codebase. I am especially interested if the messages give some indication of the fix itself. Iβm thinking deadlocks, livelocks, or incorrect lock ordering are all potential suspects when I see these in relation to these lock maps. Time to drill down on those commits and see what the authors were wrestling with, and if their solutions hold up to scrutiny. I'm going to start with the commit messages themselves, but if they are too cursory, I'll need to go deeper into the diffs to fully understand the context and the problem's resolution. I'm also thinking this could be a good point to review the lock hierarchy or dependency tracking if the commit message alludes to changes that were related to that. This will give me a good sense of the current state of lock-related stability.
|
| 317/2 |
2026/11/03 20:33 |
tool |
git-log |
0m
Args: map[Count:10 MessageRegexps:[lockdep_map] PathPrefix:block/ Since:3 years]
Results: map[Output:ffa1e7ada456 block: Make request_queue lockdep splats show up earlier
357e1b7f730b block: don't verify IO lock for freeze/unfreeze in elevator_init_mq()
]
|
| 318/2 |
2026/11/03 20:33 |
llm |
history-explorer |
5m
Model:
Tokens:
input: 66617
output: 23
thoughts: 14
Thoughts: Okay, here's my interpretation of that.
**Analyzing `ffa1e7ada456`**
Alright, let's dive in. My initial thought is to take a close look at `ffa1e7ada456`. There's likely some significant data or code represented by that identifier. My expertise kicks in β depending on the context, this could be anything from a database hash, a commit ID, a file name, a cryptographic key, a process ID, or something entirely unique to a specific system. I need more context to know for sure what it is, and what its significance is. I'll need to know where I found this identifier, what it's related to, and ideally, what tool or log produced it. From there I can determine the appropriate method to examine it; whether it is a query I need to run, a file I must open, or a command I should execute. Let's see what we can find.
|
| 319/2 |
2026/11/03 20:38 |
tool |
git-show |
0m
Args:
Results: map[Output:commit ffa1e7ada456087c2402b37cd6b2863ced29aff0
Author: Thomas HellstrΓΆm <thomas.hellstrom@linux.intel.com>
Date: Tue Mar 18 10:55:48 2025 +0100
block: Make request_queue lockdep splats show up earlier
In recent kernels, there are lockdep splats around the
struct request_queue::io_lockdep_map, similar to [1], but they
typically don't show up until reclaim with writeback happens.
Having multiple kernel versions released with a known risc of kernel
deadlock during reclaim writeback should IMHO be addressed and
backported to -stable with the highest priority.
In order to have these lockdep splats show up earlier,
preferrably during system initialization, prime the
struct request_queue::io_lockdep_map as GFP_KERNEL reclaim-
tainted. This will instead lead to lockdep splats looking similar
to [2], but without the need for reclaim + writeback
happening.
[1]:
[ 189.762244] ======================================================
[ 189.762432] WARNING: possible circular locking dependency detected
[ 189.762441] 6.14.0-rc6-xe+ #6 Tainted: G U
[ 189.762450] ------------------------------------------------------
[ 189.762459] kswapd0/119 is trying to acquire lock:
[ 189.762467] ffff888110ceb710 (&q->q_usage_counter(io)#26){++++}-{0:0}, at: __submit_bio+0x76/0x230
[ 189.762485]
but task is already holding lock:
[ 189.762494] ffffffff834c97c0 (fs_reclaim){+.+.}-{0:0}, at: balance_pgdat+0xbe/0xb00
[ 189.762507]
which lock already depends on the new lock.
[ 189.762519]
the existing dependency chain (in reverse order) is:
[ 189.762529]
-> #2 (fs_reclaim){+.+.}-{0:0}:
[ 189.762540] fs_reclaim_acquire+0xc5/0x100
[ 189.762548] kmem_cache_alloc_lru_noprof+0x4a/0x480
[ 189.762558] alloc_inode+0xaa/0xe0
[ 189.762566] iget_locked+0x157/0x330
[ 189.762573] kernfs_get_inode+0x1b/0x110
[ 189.762582] kernfs_get_tree+0x1b0/0x2e0
[ 189.762590] sysfs_get_tree+0x1f/0x60
[ 189.762597] vfs_get_tree+0x2a/0xf0
[ 189.762605] path_mount+0x4cd/0xc00
[ 189.762613] __x64_sys_mount+0x119/0x150
[ 189.762621] x64_sys_call+0x14f2/0x2310
[ 189.762630] do_syscall_64+0x91/0x180
[ 189.762637] entry_SYSCALL_64_after_hwframe+0x76/0x7e
[ 189.762647]
-> #1 (&root->kernfs_rwsem){++++}-{3:3}:
[ 189.762659] down_write+0x3e/0xf0
[ 189.762667] kernfs_remove+0x32/0x60
[ 189.762676] sysfs_remove_dir+0x4f/0x60
[ 189.762685] __kobject_del+0x33/0xa0
[ 189.762709] kobject_del+0x13/0x30
[ 189.762716] elv_unregister_queue+0x52/0x80
[ 189.762725] elevator_switch+0x68/0x360
[ 189.762733] elv_iosched_store+0x14b/0x1b0
[ 189.762756] queue_attr_store+0x181/0x1e0
[ 189.762765] sysfs_kf_write+0x49/0x80
[ 189.762773] kernfs_fop_write_iter+0x17d/0x250
[ 189.762781] vfs_write+0x281/0x540
[ 189.762790] ksys_write+0x72/0xf0
[ 189.762798] __x64_sys_write+0x19/0x30
[ 189.762807] x64_sys_call+0x2a3/0x2310
[ 189.762815] do_syscall_64+0x91/0x180
[ 189.762823] entry_SYSCALL_64_after_hwframe+0x76/0x7e
[ 189.762833]
-> #0 (&q->q_usage_counter(io)#26){++++}-{0:0}:
[ 189.762845] __lock_acquire+0x1525/0x2760
[ 189.762854] lock_acquire+0xca/0x310
[ 189.762861] blk_mq_submit_bio+0x8a2/0xba0
[ 189.762870] __submit_bio+0x76/0x230
[ 189.762878] submit_bio_noacct_nocheck+0x323/0x430
[ 189.762888] submit_bio_noacct+0x2cc/0x620
[ 189.762896] submit_bio+0x38/0x110
[ 189.762904] __swap_writepage+0xf5/0x380
[ 189.762912] swap_writepage+0x3c7/0x600
[ 189.762920] shmem_writepage+0x3da/0x4f0
[ 189.762929] pageout+0x13f/0x310
[ 189.762937] shrink_folio_list+0x61c/0xf60
[ 189.763261] evict_folios+0x378/0xcd0
[ 189.763584] try_to_shrink_lruvec+0x1b0/0x360
[ 189.763946] shrink_one+0x10e/0x200
[ 189.764266] shrink_node+0xc02/0x1490
[ 189.764586] balance_pgdat+0x563/0xb00
[ 189.764934] kswapd+0x1e8/0x430
[ 189.765249] kthread+0x10b/0x260
[ 189.765559] ret_from_fork+0x44/0x70
[ 189.765889] ret_from_fork_asm+0x1a/0x30
[ 189.766198]
other info that might help us debug this:
[ 189.767089] Chain exists of:
&q->q_usage_counter(io)#26 --> &root->kernfs_rwsem --> fs_reclaim
[ 189.767971] Possible unsafe locking scenario:
[ 189.768555] CPU0 CPU1
[ 189.768849] ---- ----
[ 189.769136] lock(fs_reclaim);
[ 189.769421] lock(&root->kernfs_rwsem);
[ 189.769714] lock(fs_reclaim);
[ 189.770016] rlock(&q->q_usage_counter(io)#26);
[ 189.770305]
*** DEADLOCK ***
[ 189.771167] 1 lock held by kswapd0/119:
[ 189.771453] #0: ffffffff834c97c0 (fs_reclaim){+.+.}-{0:0}, at: balance_pgdat+0xbe/0xb00
[ 189.771770]
stack backtrace:
[ 189.772351] CPU: 4 UID: 0 PID: 119 Comm: kswapd0 Tainted: G U 6.14.0-rc6-xe+ #6
[ 189.772353] Tainted: [U]=USER
[ 189.772354] Hardware name: ASUS System Product Name/PRIME B560M-A AC, BIOS 2001 02/01/2023
[ 189.772354] Call Trace:
[ 189.772355] <TASK>
[ 189.772356] dump_stack_lvl+0x6e/0xa0
[ 189.772359] dump_stack+0x10/0x18
[ 189.772360] print_circular_bug.cold+0x17a/0x1b7
[ 189.772363] check_noncircular+0x13a/0x150
[ 189.772365] ? __pfx_stack_trace_consume_entry+0x10/0x10
[ 189.772368] __lock_acquire+0x1525/0x2760
[ 189.772368] ? ret_from_fork_asm+0x1a/0x30
[ 189.772371] lock_acquire+0xca/0x310
[ 189.772372] ? __submit_bio+0x76/0x230
[ 189.772375] ? lock_release+0xd5/0x2c0
[ 189.772376] blk_mq_submit_bio+0x8a2/0xba0
[ 189.772378] ? __submit_bio+0x76/0x230
[ 189.772380] __submit_bio+0x76/0x230
[ 189.772382] ? trace_hardirqs_on+0x1e/0xe0
[ 189.772384] submit_bio_noacct_nocheck+0x323/0x430
[ 189.772386] ? submit_bio_noacct_nocheck+0x323/0x430
[ 189.772387] ? __might_sleep+0x58/0xa0
[ 189.772390] submit_bio_noacct+0x2cc/0x620
[ 189.772391] ? count_memcg_events+0x68/0x90
[ 189.772393] submit_bio+0x38/0x110
[ 189.772395] __swap_writepage+0xf5/0x380
[ 189.772396] swap_writepage+0x3c7/0x600
[ 189.772397] shmem_writepage+0x3da/0x4f0
[ 189.772401] pageout+0x13f/0x310
[ 189.772406] shrink_folio_list+0x61c/0xf60
[ 189.772409] ? isolate_folios+0xe80/0x16b0
[ 189.772410] ? mark_held_locks+0x46/0x90
[ 189.772412] evict_folios+0x378/0xcd0
[ 189.772414] ? evict_folios+0x34a/0xcd0
[ 189.772415] ? lock_is_held_type+0xa3/0x130
[ 189.772417] try_to_shrink_lruvec+0x1b0/0x360
[ 189.772420] shrink_one+0x10e/0x200
[ 189.772421] shrink_node+0xc02/0x1490
[ 189.772423] ? shrink_node+0xa08/0x1490
[ 189.772424] ? shrink_node+0xbd8/0x1490
[ 189.772425] ? mem_cgroup_iter+0x366/0x480
[ 189.772427] balance_pgdat+0x563/0xb00
[ 189.772428] ? balance_pgdat+0x563/0xb00
[ 189.772430] ? trace_hardirqs_on+0x1e/0xe0
[ 189.772431] ? finish_task_switch.isra.0+0xcb/0x330
[ 189.772433] ? __switch_to_asm+0x33/0x70
[ 189.772437] kswapd+0x1e8/0x430
[ 189.772438] ? __pfx_autoremove_wake_function+0x10/0x10
[ 189.772440] ? __pfx_kswapd+0x10/0x10
[ 189.772441] kthread+0x10b/0x260
[ 189.772443] ? __pfx_kthread+0x10/0x10
[ 189.772444] ret_from_fork+0x44/0x70
[ 189.772446] ? __pfx_kthread+0x10/0x10
[ 189.772447] ret_from_fork_asm+0x1a/0x30
[ 189.772450] </TASK>
[2]:
[ 8.760253] ======================================================
[ 8.760254] WARNING: possible circular locking dependency detected
[ 8.760255] 6.14.0-rc6-xe+ #7 Tainted: G U
[ 8.760256] ------------------------------------------------------
[ 8.760257] (udev-worker)/674 is trying to acquire lock:
[ 8.760259] ffff888100e39148 (&root->kernfs_rwsem){++++}-{3:3}, at: kernfs_remove+0x32/0x60
[ 8.760265]
but task is already holding lock:
[ 8.760266] ffff888110dc7680 (&q->q_usage_counter(io)#27){++++}-{0:0}, at: blk_mq_freeze_queue_nomemsave+0x12/0x30
[ 8.760272]
which lock already depends on the new lock.
[ 8.760272]
the existing dependency chain (in reverse order) is:
[ 8.760273]
-> #2 (&q->q_usage_counter(io)#27){++++}-{0:0}:
[ 8.760276] blk_alloc_queue+0x30a/0x350
[ 8.760279] blk_mq_alloc_queue+0x6b/0xe0
[ 8.760281] scsi_alloc_sdev+0x276/0x3c0
[ 8.760284] scsi_probe_and_add_lun+0x22a/0x440
[ 8.760286] __scsi_scan_target+0x109/0x230
[ 8.760288] scsi_scan_channel+0x65/0xc0
[ 8.760290] scsi_scan_host_selected+0xff/0x140
[ 8.760292] do_scsi_scan_host+0xa7/0xc0
[ 8.760293] do_scan_async+0x1c/0x160
[ 8.760295] async_run_entry_fn+0x32/0x150
[ 8.760299] process_one_work+0x224/0x5f0
[ 8.760302] worker_thread+0x1d4/0x3e0
[ 8.760304] kthread+0x10b/0x260
[ 8.760306] ret_from_fork+0x44/0x70
[ 8.760309] ret_from_fork_asm+0x1a/0x30
[ 8.760312]
-> #1 (fs_reclaim){+.+.}-{0:0}:
[ 8.760315] fs_reclaim_acquire+0xc5/0x100
[ 8.760317] kmem_cache_alloc_lru_noprof+0x4a/0x480
[ 8.760319] alloc_inode+0xaa/0xe0
[ 8.760322] iget_locked+0x157/0x330
[ 8.760323] kernfs_get_inode+0x1b/0x110
[ 8.760325] kernfs_get_tree+0x1b0/0x2e0
[ 8.760327] sysfs_get_tree+0x1f/0x60
[ 8.760329] vfs_get_tree+0x2a/0xf0
[ 8.760332] path_mount+0x4cd/0xc00
[ 8.760334] __x64_sys_mount+0x119/0x150
[ 8.760336] x64_sys_call+0x14f2/0x2310
[ 8.760338] do_syscall_64+0x91/0x180
[ 8.760340] entry_SYSCALL_64_after_hwframe+0x76/0x7e
[ 8.760342]
-> #0 (&root->kernfs_rwsem){++++}-{3:3}:
[ 8.760345] __lock_acquire+0x1525/0x2760
[ 8.760347] lock_acquire+0xca/0x310
[ 8.760348] down_write+0x3e/0xf0
[ 8.760350] kernfs_remove+0x32/0x60
[ 8.760351] sysfs_remove_dir+0x4f/0x60
[ 8.760353] __kobject_del+0x33/0xa0
[ 8.760355] kobject_del+0x13/0x30
[ 8.760356] elv_unregister_queue+0x52/0x80
[ 8.760358] elevator_switch+0x68/0x360
[ 8.760360] elv_iosched_store+0x14b/0x1b0
[ 8.760362] queue_attr_store+0x181/0x1e0
[ 8.760364] sysfs_kf_write+0x49/0x80
[ 8.760366] kernfs_fop_write_iter+0x17d/0x250
[ 8.760367] vfs_write+0x281/0x540
[ 8.760370] ksys_write+0x72/0xf0
[ 8.760372] __x64_sys_write+0x19/0x30
[ 8.760374] x64_sys_call+0x2a3/0x2310
[ 8.760376] do_syscall_64+0x91/0x180
[ 8.760377] entry_SYSCALL_64_after_hwframe+0x76/0x7e
[ 8.760380]
other info that might help us debug this:
[ 8.760380] Chain exists of:
&root->kernfs_rwsem --> fs_reclaim --> &q->q_usage_counter(io)#27
[ 8.760384] Possible unsafe locking scenario:
[ 8.760384] CPU0 CPU1
[ 8.760385] ---- ----
[ 8.760385] lock(&q->q_usage_counter(io)#27);
[ 8.760387] lock(fs_reclaim);
[ 8.760388] lock(&q->q_usage_counter(io)#27);
[ 8.760390] lock(&root->kernfs_rwsem);
[ 8.760391]
*** DEADLOCK ***
[ 8.760391] 6 locks held by (udev-worker)/674:
[ 8.760392] #0: ffff8881209ac420 (sb_writers#4){.+.+}-{0:0}, at: ksys_write+0x72/0xf0
[ 8.760398] #1: ffff88810c80f488 (&of->mutex#2){+.+.}-{3:3}, at: kernfs_fop_write_iter+0x136/0x250
[ 8.760402] #2: ffff888125d1d330 (kn->active#101){.+.+}-{0:0}, at: kernfs_fop_write_iter+0x13f/0x250
[ 8.760406] #3: ffff888110dc7bb0 (&q->sysfs_lock){+.+.}-{3:3}, at: queue_attr_store+0x148/0x1e0
[ 8.760411] #4: ffff888110dc7680 (&q->q_usage_counter(io)#27){++++}-{0:0}, at: blk_mq_freeze_queue_nomemsave+0x12/0x30
[ 8.760416] #5: ffff888110dc76b8 (&q->q_usage_counter(queue)#27){++++}-{0:0}, at: blk_mq_freeze_queue_nomemsave+0x12/0x30
[ 8.760421]
stack backtrace:
[ 8.760422] CPU: 7 UID: 0 PID: 674 Comm: (udev-worker) Tainted: G U 6.14.0-rc6-xe+ #7
[ 8.760424] Tainted: [U]=USER
[ 8.760425] Hardware name: ASUS System Product Name/PRIME B560M-A AC, BIOS 2001 02/01/2023
[ 8.760426] Call Trace:
[ 8.760427] <TASK>
[ 8.760428] dump_stack_lvl+0x6e/0xa0
[ 8.760431] dump_stack+0x10/0x18
[ 8.760433] print_circular_bug.cold+0x17a/0x1b7
[ 8.760437] check_noncircular+0x13a/0x150
[ 8.760441] ? save_trace+0x54/0x360
[ 8.760445] __lock_acquire+0x1525/0x2760
[ 8.760446] ? irqentry_exit+0x3a/0xb0
[ 8.760448] ? sysvec_apic_timer_interrupt+0x57/0xc0
[ 8.760452] lock_acquire+0xca/0x310
[ 8.760453] ? kernfs_remove+0x32/0x60
[ 8.760457] down_write+0x3e/0xf0
[ 8.760459] ? kernfs_remove+0x32/0x60
[ 8.760460] kernfs_remove+0x32/0x60
[ 8.760462] sysfs_remove_dir+0x4f/0x60
[ 8.760464] __kobject_del+0x33/0xa0
[ 8.760466] kobject_del+0x13/0x30
[ 8.760467] elv_unregister_queue+0x52/0x80
[ 8.760470] elevator_switch+0x68/0x360
[ 8.760472] elv_iosched_store+0x14b/0x1b0
[ 8.760475] queue_attr_store+0x181/0x1e0
[ 8.760479] ? lock_acquire+0xca/0x310
[ 8.760480] ? kernfs_fop_write_iter+0x13f/0x250
[ 8.760482] ? lock_is_held_type+0xa3/0x130
[ 8.760485] sysfs_kf_write+0x49/0x80
[ 8.760487] kernfs_fop_write_iter+0x17d/0x250
[ 8.760489] vfs_write+0x281/0x540
[ 8.760494] ksys_write+0x72/0xf0
[ 8.760497] __x64_sys_write+0x19/0x30
[ 8.760499] x64_sys_call+0x2a3/0x2310
[ 8.760502] do_syscall_64+0x91/0x180
[ 8.760504] ? trace_hardirqs_off+0x5d/0xe0
[ 8.760506] ? handle_softirqs+0x479/0x4d0
[ 8.760508] ? hrtimer_interrupt+0x13f/0x280
[ 8.760511] ? irqentry_exit_to_user_mode+0x8b/0x260
[ 8.760513] ? clear_bhb_loop+0x15/0x70
[ 8.760515] ? clear_bhb_loop+0x15/0x70
[ 8.760516] ? clear_bhb_loop+0x15/0x70
[ 8.760518] entry_SYSCALL_64_after_hwframe+0x76/0x7e
[ 8.760520] RIP: 0033:0x7aa3bf2f5504
[ 8.760522] Code: c7 00 16 00 00 00 b8 ff ff ff ff c3 66 2e 0f 1f 84 00 00 00 00 00 f3 0f 1e fa 80 3d c5 8b 10 00 00 74 13 b8 01 00 00 00 0f 05 <48> 3d 00 f0 ff ff 77 54 c3 0f 1f 00 55 48 89 e5 48 83 ec 20 48 89
[ 8.760523] RSP: 002b:00007ffc1e3697d8 EFLAGS: 00000202 ORIG_RAX: 0000000000000001
[ 8.760526] RAX: ffffffffffffffda RBX: 0000000000000003 RCX: 00007aa3bf2f5504
[ 8.760527] RDX: 0000000000000003 RSI: 00007ffc1e369ae0 RDI: 000000000000001c
[ 8.760528] RBP: 00007ffc1e369800 R08: 00007aa3bf3f51c8 R09: 00007ffc1e3698b0
[ 8.760528] R10: 0000000000000000 R11: 0000000000000202 R12: 0000000000000003
[ 8.760529] R13: 00007ffc1e369ae0 R14: 0000613ccf21f2f0 R15: 00007aa3bf3f4e80
[ 8.760533] </TASK>
v2:
- Update a code comment to increase readability (Ming Lei).
Cc: Jens Axboe <axboe@kernel.dk>
Cc: linux-block@vger.kernel.org
Cc: linux-kernel@vger.kernel.org
Cc: Ming Lei <ming.lei@redhat.com>
Signed-off-by: Thomas HellstrΓΆm <thomas.hellstrom@linux.intel.com>
Reviewed-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20250318095548.5187-1-thomas.hellstrom@linux.intel.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-core.c b/block/blk-core.c
index 362d0a55b07a..4623de79effa 100644
--- a/block/blk-core.c
+++ b/block/blk-core.c
@@ -456,6 +456,12 @@ struct request_queue *blk_alloc_queue(struct queue_limits *lim, int node_id)
lockdep_init_map(&q->q_lockdep_map, "&q->q_usage_counter(queue)",
&q->q_lock_cls_key, 0);
+ /* Teach lockdep about lock ordering (reclaim WRT queue freeze lock). */
+ fs_reclaim_acquire(GFP_KERNEL);
+ rwsem_acquire_read(&q->io_lockdep_map, 0, 0, _RET_IP_);
+ rwsem_release(&q->io_lockdep_map, _RET_IP_);
+ fs_reclaim_release(GFP_KERNEL);
+
q->nr_requests = BLKDEV_DEFAULT_RQ;
return q;
]
|
| 320/2 |
2026/11/03 20:38 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 76437
output: 25
thoughts: 235
Thoughts: Okay, let me take a look at this.
**Analyzing a Request Queue Lockdep Commit**
Alright, so I'm focusing on commit `ffa1e7ada456`. HellstrΓΆm and Lei were tweaking the request_queue lockdep maps, specifically those related to `&q->q_usage_counter(queue)` and `&q->q_usage_counter(io)`. I see these interesting lines:
The critical thing here is that `blk_mq_freeze_queue_nomemsave` function is involved. I'm going to dig into the definition of this function to understand what these lockdep maps are actually doing in relation to this operation. I will need to use codesearch or grepper to find where it is defined.
|
| 321/2 |
2026/11/03 20:38 |
tool |
grepper |
0m
Args: map[Expression:blk_mq_freeze_queue_nomemsave]
Results: map[Output:block/blk-mq.c=202=EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait_timeout);
block/blk-mq.c-203-
block/blk-mq.c:204:void blk_mq_freeze_queue_nomemsave(struct request_queue *q)
block/blk-mq.c-205-{
--
block/blk-mq.c-208-}
block/blk-mq.c:209:EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_nomemsave);
block/blk-mq.c-210-
--
block/blk-mq.c=5165=static void __blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set,
--
block/blk-mq.c-5212- list_for_each_entry(q, &set->tag_list, tag_set_list)
block/blk-mq.c:5213: blk_mq_freeze_queue_nomemsave(q);
block/blk-mq.c-5214- queues_frozen = true;
--
block/blk-mq.c-5246- if (!queues_frozen)
block/blk-mq.c:5247: blk_mq_freeze_queue_nomemsave(q);
block/blk-mq.c-5248- blk_mq_elv_switch_back(q, &elv_tbl);
--
drivers/ufs/core/ufs-sysfs.c=1626=static ssize_t max_number_of_rtt_store(struct device *dev,
--
drivers/ufs/core/ufs-sysfs.c-1654- shost_for_each_device(sdev, hba->host)
drivers/ufs/core/ufs-sysfs.c:1655: blk_mq_freeze_queue_nomemsave(sdev->request_queue);
drivers/ufs/core/ufs-sysfs.c-1656-
--
include/linux/blk-mq.h=951=void blk_mq_tagset_wait_completed_request(struct blk_mq_tag_set *tagset);
include/linux/blk-mq.h:952:void blk_mq_freeze_queue_nomemsave(struct request_queue *q);
include/linux/blk-mq.h-953-void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q);
--
include/linux/blk-mq.h=955=blk_mq_freeze_queue(struct request_queue *q)
--
include/linux/blk-mq.h-958-
include/linux/blk-mq.h:959: blk_mq_freeze_queue_nomemsave(q);
include/linux/blk-mq.h-960- return memflags;
]
|
| 322/2 |
2026/11/03 20:38 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 77596
output: 46
thoughts: 43
Thoughts: Here's my thought process, summarized as you requested:
**Investigating Block Device Life Cycle in `dm.c`**
Okay, so I need to understand how the device mapper handles the life cycle of its virtual block devices. My immediate thought is to check the `git-log` for `drivers/md/dm.c`. I want to focus on functions related to adding and removing disks and marking them as dead, which are key events in a block device's lifecycle. Specifically, I'm thinking I should search for commit messages that mention `add_disk`, `del_gendisk`, or `blk_mark_disk_dead`. These will likely be the most relevant entry points for understanding how the device mapper creates, destroys, and handles failures of its block devices. This git log inspection should give me a good overview of the relevant code history. I'm hoping to see when these functions were introduced, how they've evolved, and, ideally, see relevant bug fixes or performance optimizations relating to device lifecycle.
|
| 323/2 |
2026/11/03 20:39 |
tool |
git-log |
0m
Args: map[CodeRegexp:blk_mark_disk_dead Count:10 PathPrefix:drivers/md/ Since:3 years]
Results:
|
| 324/2 |
2026/11/03 20:39 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 77912
output: 45
thoughts: 74
Thoughts: Okay, let's break this down.
**Investigating a Kernel Module's History**
Right, so I need to figure out when this particular identifier, `7a5428dcb790`, was last relevant. That was in February 2022, which means we're looking at roughly three years of history. Okay, that puts things into a reasonable timeframe. I'll need to go to the source to check.
Now, I'm going to leverage `git log`. Specifically, I'll be querying the history of the `drivers/md/dm.c` file for any commits that touch either `dm_destroy` or `__dm_destroy` within that three-year window. That should give me a focused view of relevant modifications or uses of that function within that period. This seems like a reasonable way to approach this.
|
| 325/2 |
2026/11/03 20:39 |
tool |
git-log |
0m
Error:
Args: map[Count:10 PathPrefix:drivers/md/dm.c Since:3 years SymbolName:__dm_destroy]
Results:
|
| 326/2 |
2026/11/03 20:39 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 78238
output: 45
thoughts: 19
Thoughts: Here's my take on those thoughts:
**Refactoring for Clarity and Consistency**
Okay, so I'm looking at this naming convention, and it feels a little clunky. We've got `PathPrefix` and `SymbolName` kicking around, and while technically correct, it's not the most elegant. I think we can streamline this and increase the clarity of the code.
My gut feeling is that `SourcePath` feels like a more intuitive and direct replacement for `PathPrefix` when paired with `SymbolName`. It more accurately reflects what we're actually dealing with: the location of the source material. It's a subtle shift, but I think it reads better and is less prone to misinterpretation down the line. It's about optimizing for the next person who's going to work with this, or even future-me. Let's make this change and see how it fits. I bet it will provide a cleaner representation of the codebase.
|
| 327/2 |
2026/11/03 20:40 |
tool |
git-log |
0m
Args: map[Count:10 Since:3 years SourcePath:drivers/md/dm.c SymbolName:__dm_destroy]
Results:
|
| 328/2 |
2026/11/03 20:40 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 78519
output: 45
thoughts: 13
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and presented as if it were my own internal monologue:
**Navigating the Nuances of a Search Query**
Alright, so the task at hand is to generate a summary of some thoughts. Let's see... a simple search term has been identified: "5 years". The obvious initial thought is to strip out the potentially problematic "Since" or "since" to avoid conflating different uses of the term. Why? Because the presence of "since" often implies a temporal reference that can limit the scope, depending on the surrounding context. By eliminating those words, I immediately broaden the focus. I'm telling myself to be flexible; the initial goal is likely just to find information tied to that term in some way, and not to make assumptions about how it's used at this stage. I'm focusing on "5 years" as the core element. This seems like a good, basic search to establish a baseline of results before refining the query.
|
| 329/2 |
2026/11/03 20:41 |
tool |
git-log |
0m
Args: map[Count:10 Since:5 years SourcePath:drivers/md/dm.c SymbolName:__dm_destroy]
Results: map[Output:238d991f054a dm: use fsleep() instead of msleep() for deterministic sleep duration
7a5428dcb790 block: fix surprise removal for drivers calling blk_set_queue_dying
]
|
| 330/2 |
2026/11/03 20:41 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 78862
output: 46
thoughts: 40
Thoughts: Okay, let's dive into this. Here's how I'd approach this task.
**Investigating `table_load` in `dm-ioctl.c`**
Alright, I'm going to start by getting a look at the `table_load` function within `drivers/md/dm-ioctl.c`. My immediate goal is to understand its current implementation and, more importantly, its history. To do this, I'm going to leverage my knowledge of the codebase and use a tool or command, likely something that allows me to search the source code repository. I'll need to use `SymbolName: "table_load"` to precisely target the function and then trace its evolution through commits. This will give me a timeline of changes, any bug fixes, and potentially the reasoning behind modifications. This will give me a high-level view of how this function has evolved. I can then use that information to understand any current problems, if there are any.
|
| 331/2 |
2026/11/03 20:41 |
tool |
git-log |
0m
Args: map[Count:10 Since:3 years SourcePath:drivers/md/dm-ioctl.c SymbolName:table_load]
Results: map[Output:5534cac9b56d dm-ima: Fix UAF errors and measuring incorrect context
b1a80737a9af dm-ima: Remove status_flags from dm_ima_measure_on_table_load()
]
|
| 332/2 |
2026/11/03 20:41 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 79221
output: 25
thoughts: 29
Thoughts: Okay, here's my interpretation of that commit message, tailored for an expert audience, and framed as my own internal thought process:
**Fixing a Tricky Memory Bug in IMA**
Alright, I'm diving into commit `5534cac9b56d dm-ima: Fix UAF errors and measuring incorrect context`. The gist is that the Direct Mapping IMA (dm-ima) implementation has some critical vulnerabilities that need to be addressed. We're talking about use-after-free (UAF) errors, which are *nasty*. I can already imagine the debugging nightmare that that must have been. These kinds of bugs can lead to arbitrary code execution, and they often manifest as subtle, intermittent crashes β the worst kind.
On top of the UAF issue, it looks like there was also a problem with the context used for measurements. This is a bit worrying because incorrect context leads to untrustworthy integrity measurements. A flaw like that undermines the whole purpose of IMA, which is to verify the integrity of the system. We're talking potentially incorrect attestation data or false positives/negatives in security audits. I wonder what the root cause was... was it a race condition, a faulty pointer, an off-by-one error?
I need to see what they did to fix it. My first thought is to check how the UAF issue was triggered. Was it in the handling of device events, or in the interaction with the IMA subsystem itself? From the sound of the commit message, the fix has to be pretty comprehensive to deal with the UAF and context issues in a single commit, so I'm expecting some significant refactoring or a significant change in how the interactions are handled. Then I want to assess the impact of the patch. I'll check its performance implications and if the change has created any new vulnerabilities. Let's see what they came up with...
|
| 333/2 |
2026/11/03 20:42 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 5534cac9b56d8f51343718f71737a69d40cb2bb9
Author: Benjamin Marzinski <bmarzins@redhat.com>
Date: Wed Apr 29 16:21:03 2026 -0400
dm-ima: Fix UAF errors and measuring incorrect context
the dm-ima code did not keep the dm_ima_measure_on_* functions from
running at the same time. This could lead to various errors. If two
processes were updating the device state, one could update the state
first, but the other could measure the state first, causing the the
current device state to appear incorrect. If a table load happened while
a device was resuming, the IMA measurement could report the wrong table
being active. And if two dm_ima_measure_on_* functions ran at the same
time, one of them could free data that the other was accessing, causing
a crash.
All the core dm functions that call a dm_ima_measure_on_* function
update the device state they want to measure under the _hash_lock,
except for do_resume(). But holding the _hash_lock is not a good way to
synchronize these functions. It's a global mutex, that is needed in many
dm operations, and the dm_ima_measure_* functions can sleep, blocking
any dm operation on any device that needs the _hash_lock.
To serialize and order the IMA measurement functions, the
dm_ima_measurements now has two counters, update_idx and measure_idx.
update_idx is incremented while holding the _hash_lock and saved, along
with the device name and uuid, in a dm_ima_context struct. Once the
_hash_lock is dropped, the dm_ima_measure_* function is called. It waits
until measure_idx matches the saved value of update_idx, ensuring that
the updates and measurements happen in the same order if there are
multiple processes changing the device at the same time. Then it
measures the device, updates measure_idx, and wakes up any other
process waiting to do a measurement. This makes sure that the
measurements are serialized and done in the order that the _hash_lock
was acquired in. But they only block other measurements for the same
device, which are unlikely to happen at the same time.
do_resume() is trickier, because it removes the inactive table while
holding the _hash_lock, but doesn't hold it while updating md->map. To
make sure it is also ordered, the IMA code grabs the _hash_lock after
md->map is updated. Then it makes sure that the device isn't being
removed and that another do_resume() hasn't already changed the active
table again, and serializes like the other functions do.
Signed-off-by: Benjamin Marzinski <bmarzins@redhat.com>
Signed-off-by: Mikulas Patocka <mpatocka@redhat.com>
diff --git a/drivers/md/dm-ima.c b/drivers/md/dm-ima.c
index c141068bc6b4..096c664d855c 100644
--- a/drivers/md/dm-ima.c
+++ b/drivers/md/dm-ima.c
@@ -21,25 +21,32 @@
* character, so that they don't interfere with the construction of key-value pairs,
* and clients can split the key1=val1,key2=val2,key3=val3; pairs properly.
*/
-static void fix_separator_chars(char **buf)
+static void fix_separator_chars(char *buf)
{
- int l = strlen(*buf);
+ int l = strlen(buf);
int i, j, sp = 0;
for (i = 0; i < l; i++)
- if ((*buf)[i] == '\\' || (*buf)[i] == ';' || (*buf)[i] == '=' || (*buf)[i] == ',')
+ if (buf[i] == '\\' || buf[i] == ';' || buf[i] == '=' || buf[i] == ',')
sp++;
if (!sp)
return;
+ buf[l + sp] = '\0';
for (i = l-1, j = i+sp; i >= 0; i--) {
- (*buf)[j--] = (*buf)[i];
- if ((*buf)[i] == '\\' || (*buf)[i] == ';' || (*buf)[i] == '=' || (*buf)[i] == ',')
- (*buf)[j--] = '\\';
+ buf[j--] = buf[i];
+ if (buf[i] == '\\' || buf[i] == ';' || buf[i] == '=' || buf[i] == ',')
+ buf[j--] = '\\';
}
}
+static void fix_context_strings(struct dm_ima_context *context)
+{
+ fix_separator_chars(context->dev_name);
+ fix_separator_chars(context->dev_uuid);
+}
+
/*
* Internal function to allocate memory for IMA measurements.
*/
@@ -59,68 +66,89 @@ static void *dm_ima_alloc(size_t len, bool noio)
return ptr;
}
+void dm_ima_init(struct mapped_device *md)
+{
+ md->ima.update_idx = 0;
+ md->ima.measure_idx = 0;
+ init_waitqueue_head(&md->ima.ima_wq);
+ spin_lock_init(&md->ima.ima_lock);
+}
+
+void dm_ima_alloc_context(struct dm_ima_context **context, bool noio)
+{
+ *context = dm_ima_alloc(sizeof(struct dm_ima_context), noio);
+}
+
+void dm_ima_free_context(struct dm_ima_context *context)
+{
+ if (likely(context)) {
+ kfree(context->table.device_metadata);
+ kfree(context->table.hash);
+ kfree(context);
+ }
+}
+
+static void wait_to_measure(struct dm_ima_measurements *ima,
+ unsigned int update_idx)
+{
+ spin_lock_irq(&ima->ima_lock);
+ wait_event_lock_irq(ima->ima_wq,
+ ima->measure_idx == update_idx,
+ ima->ima_lock);
+ spin_unlock_irq(&ima->ima_lock);
+}
+
+static void wake_next_measure(struct dm_ima_measurements *ima)
+{
+ spin_lock_irq(&ima->ima_lock);
+ ima->measure_idx++;
+ spin_unlock_irq(&ima->ima_lock);
+ wake_up_all(&ima->ima_wq);
+}
+
/*
- * Internal function to allocate and copy name and uuid for IMA measurements.
+ * Helper function for swapping the table, to make sure that the
+ * correct table metadata is saved and restored.
*/
-static int dm_ima_alloc_and_copy_name_uuid(struct mapped_device *md, char **dev_name,
- char **dev_uuid, bool noio)
+void dm_ima_context_table_op(struct mapped_device *md,
+ struct dm_ima_context *context,
+ enum dm_ima_table_op op)
{
- int r;
- *dev_name = dm_ima_alloc(DM_NAME_LEN*2, noio);
- if (!(*dev_name)) {
- r = -ENOMEM;
- goto error;
- }
+ struct dm_ima_measurements *ima = &md->ima;
- *dev_uuid = dm_ima_alloc(DM_UUID_LEN*2, noio);
- if (!(*dev_uuid)) {
- r = -ENOMEM;
- goto error;
- }
+ if (unlikely(!context))
+ return;
- r = dm_copy_name_and_uuid(md, *dev_name, *dev_uuid);
- if (r)
- goto error;
+ wait_to_measure(ima, context->update_idx);
- fix_separator_chars(dev_name);
- fix_separator_chars(dev_uuid);
+ if (op == DM_IMA_TABLE_SAVE) {
+ context->table = ima->inactive_table;
+ memset(&ima->inactive_table, 0, sizeof(ima->inactive_table));
+ } else {
+ ima->inactive_table = context->table;
+ memset(&context->table, 0, sizeof(context->table));
+ }
- return 0;
-error:
- kfree(*dev_name);
- kfree(*dev_uuid);
- *dev_name = NULL;
- *dev_uuid = NULL;
- return r;
+ wake_next_measure(ima);
}
/*
* Internal function to allocate and copy device data for IMA measurements.
*/
static int dm_ima_alloc_and_copy_device_data(struct mapped_device *md, char **device_data,
+ struct dm_ima_context *context,
unsigned int num_targets, bool noio)
{
- char *dev_name = NULL, *dev_uuid = NULL;
- int r;
-
- r = dm_ima_alloc_and_copy_name_uuid(md, &dev_name, &dev_uuid, noio);
- if (r)
- return r;
-
*device_data = dm_ima_alloc(DM_IMA_DEVICE_BUF_LEN, noio);
- if (!(*device_data)) {
- r = -ENOMEM;
- goto error;
- }
+ if (!(*device_data))
+ return -ENOMEM;
scnprintf(*device_data, DM_IMA_DEVICE_BUF_LEN,
"name=%s,uuid=%s,major=%d,minor=%d,minor_count=%d,num_targets=%u;",
- dev_name, dev_uuid, md->disk->major, md->disk->first_minor,
- md->disk->minors, num_targets);
-error:
- kfree(dev_name);
- kfree(dev_uuid);
- return r;
+ context->dev_name, context->dev_uuid, md->disk->major,
+ md->disk->first_minor, md->disk->minors, num_targets);
+
+ return 0;
}
/*
@@ -162,7 +190,8 @@ static int dm_ima_alloc_and_copy_capacity_str(struct mapped_device *md, char **c
/*
* Build up the IMA data for each target, and finally measure.
*/
-void dm_ima_measure_on_table_load(struct dm_table *table)
+void dm_ima_measure_on_table_load(struct dm_table *table,
+ struct dm_ima_context *context)
{
size_t device_data_buf_len, target_metadata_buf_len, target_data_buf_len, l = 0;
char *target_metadata_buf = NULL, *target_data_buf = NULL, *digest_buf = NULL;
@@ -175,9 +204,14 @@ void dm_ima_measure_on_table_load(struct dm_table *table)
bool noio = false;
char table_load_event_name[] = "dm_table_load";
+ if (unlikely(!context))
+ return;
+
+ wait_to_measure(&table->md->ima, context->update_idx);
+
ima_buf = dm_ima_alloc(DM_IMA_MEASUREMENT_BUF_LEN, noio);
if (!ima_buf)
- return;
+ goto error;
target_metadata_buf = dm_ima_alloc(DM_IMA_TARGET_METADATA_BUF_LEN, noio);
if (!target_metadata_buf)
@@ -189,7 +223,9 @@ void dm_ima_measure_on_table_load(struct dm_table *table)
num_targets = table->num_targets;
- if (dm_ima_alloc_and_copy_device_data(table->md, &device_data_buf, num_targets, noio))
+ fix_context_strings(context);
+ if (dm_ima_alloc_and_copy_device_data(table->md, &device_data_buf,
+ context, num_targets, noio))
goto error;
sha256_init(&hash_ctx);
@@ -299,14 +335,17 @@ void dm_ima_measure_on_table_load(struct dm_table *table)
kfree(ima_buf);
kfree(target_metadata_buf);
kfree(target_data_buf);
+
+ wake_next_measure(&table->md->ima);
}
/*
* Measure IMA data on device resume.
*/
-void dm_ima_measure_on_device_resume(struct mapped_device *md, bool swap)
+void dm_ima_measure_on_device_resume(struct mapped_device *md, bool swap,
+ struct dm_ima_context *context)
{
- char *device_table_data, *dev_name = NULL, *dev_uuid = NULL, *capacity_str = NULL;
+ char *device_table_data = NULL, *capacity_str = NULL;
char active[] = "active_table_hash=";
unsigned int active_len = strlen(active);
unsigned int l = 0;
@@ -314,9 +353,14 @@ void dm_ima_measure_on_device_resume(struct mapped_device *md, bool swap)
bool nodata = true;
int capacity_len;
+ if (unlikely(!context))
+ return;
+
+ wait_to_measure(&md->ima, context->update_idx);
+
device_table_data = dm_ima_alloc(DM_IMA_DEVICE_BUF_LEN, noio);
if (!device_table_data)
- return;
+ goto error;
capacity_len = dm_ima_alloc_and_copy_capacity_str(md, &capacity_str, noio);
if (capacity_len < 0)
@@ -328,25 +372,8 @@ void dm_ima_measure_on_device_resume(struct mapped_device *md, bool swap)
if (swap) {
kfree(md->ima.active_table.hash);
kfree(md->ima.active_table.device_metadata);
- memset(&md->ima.active_table, 0, sizeof(md->ima.active_table));
-
- if (md->ima.inactive_table.hash) {
- md->ima.active_table.hash = md->ima.inactive_table.hash;
- md->ima.active_table.hash_len = md->ima.inactive_table.hash_len;
- md->ima.inactive_table.hash = NULL;
- md->ima.inactive_table.hash_len = 0;
- }
-
- if (md->ima.inactive_table.device_metadata) {
- md->ima.active_table.device_metadata =
- md->ima.inactive_table.device_metadata;
- md->ima.active_table.device_metadata_len =
- md->ima.inactive_table.device_metadata_len;
- md->ima.active_table.num_targets = md->ima.inactive_table.num_targets;
- md->ima.inactive_table.device_metadata = NULL;
- md->ima.inactive_table.device_metadata_len = 0;
- md->ima.inactive_table.num_targets = 0;
- }
+ md->ima.active_table = context->table;
+ memset(&context->table, 0, sizeof(context->table));
}
if (md->ima.active_table.device_metadata) {
@@ -372,12 +399,11 @@ void dm_ima_measure_on_device_resume(struct mapped_device *md, bool swap)
}
if (nodata) {
- if (dm_ima_alloc_and_copy_name_uuid(md, &dev_name, &dev_uuid, noio))
- goto error;
-
+ fix_context_strings(context);
l = scnprintf(device_table_data, DM_IMA_DEVICE_BUF_LEN,
"%sname=%s,uuid=%s;device_resume=no_data;",
- DM_IMA_VERSION_STR, dev_name, dev_uuid);
+ DM_IMA_VERSION_STR, context->dev_name,
+ context->dev_uuid);
}
memcpy(device_table_data + l, capacity_str, capacity_len);
@@ -385,19 +411,21 @@ void dm_ima_measure_on_device_resume(struct mapped_device *md, bool swap)
dm_ima_measure_data("dm_device_resume", device_table_data, l, noio);
- kfree(dev_name);
- kfree(dev_uuid);
error:
kfree(capacity_str);
kfree(device_table_data);
+
+ wake_next_measure(&md->ima);
}
/*
* Measure IMA data on remove.
*/
-void dm_ima_measure_on_device_remove(struct mapped_device *md, bool remove_all)
+void dm_ima_measure_on_device_remove(struct mapped_device *md, bool remove_all,
+ struct dm_ima_context *context,
+ unsigned int idx)
{
- char *device_table_data, *dev_name = NULL, *dev_uuid = NULL, *capacity_str = NULL;
+ char *device_table_data, *capacity_str = NULL;
char active_table_str[] = "active_table_hash=";
char inactive_table_str[] = "inactive_table_hash=";
char device_active_str[] = "device_active_metadata=";
@@ -413,6 +441,11 @@ void dm_ima_measure_on_device_remove(struct mapped_device *md, bool remove_all)
bool nodata = true;
int capacity_len;
+ wait_to_measure(&md->ima, idx);
+
+ if (unlikely(!context))
+ goto exit;
+
device_table_data = dm_ima_alloc(DM_IMA_DEVICE_BUF_LEN*2, noio);
if (!device_table_data)
goto exit;
@@ -481,12 +514,11 @@ void dm_ima_measure_on_device_remove(struct mapped_device *md, bool remove_all)
* in IMA measurements.
*/
if (nodata) {
- if (dm_ima_alloc_and_copy_name_uuid(md, &dev_name, &dev_uuid, noio))
- goto error;
-
+ fix_context_strings(context);
l = scnprintf(device_table_data, DM_IMA_DEVICE_BUF_LEN,
"%sname=%s,uuid=%s;device_remove=no_data;",
- DM_IMA_VERSION_STR, dev_name, dev_uuid);
+ DM_IMA_VERSION_STR, context->dev_name,
+ context->dev_uuid);
}
memcpy(device_table_data + l, remove_all_str, remove_all_len);
@@ -499,7 +531,6 @@ void dm_ima_measure_on_device_remove(struct mapped_device *md, bool remove_all)
dm_ima_measure_data("dm_device_remove", device_table_data, l, noio);
-error:
kfree(device_table_data);
kfree(capacity_str);
exit:
@@ -512,30 +543,35 @@ void dm_ima_measure_on_device_remove(struct mapped_device *md, bool remove_all)
memset(&md->ima.active_table, 0, sizeof(md->ima.active_table));
memset(&md->ima.inactive_table, 0, sizeof(md->ima.inactive_table));
- kfree(dev_name);
- kfree(dev_uuid);
+ wake_next_measure(&md->ima);
}
/*
* Measure ima data on table clear.
*/
-void dm_ima_measure_on_table_clear(struct mapped_device *md, bool new_map)
+void dm_ima_measure_on_table_clear(struct mapped_device *md, bool new_map,
+ struct dm_ima_context *context)
{
unsigned int l = 0;
- char *device_table_data = NULL, *dev_name = NULL, *dev_uuid = NULL, *capacity_str = NULL;
+ char *device_table_data = NULL, *capacity_str = NULL;
char inactive_str[] = "inactive_table_hash=";
unsigned int inactive_len = strlen(inactive_str);
bool noio = true;
bool nodata = true;
int capacity_len;
+ if (unlikely(!context))
+ return;
+
+ wait_to_measure(&md->ima, context->update_idx);
+
device_table_data = dm_ima_alloc(DM_IMA_DEVICE_BUF_LEN, noio);
if (!device_table_data)
- return;
+ goto error;
capacity_len = dm_ima_alloc_and_copy_capacity_str(md, &capacity_str, noio);
if (capacity_len < 0)
- goto error1;
+ goto error;
memcpy(device_table_data + l, DM_IMA_VERSION_STR, strlen(DM_IMA_VERSION_STR));
l += strlen(DM_IMA_VERSION_STR);
@@ -561,12 +597,11 @@ void dm_ima_measure_on_table_clear(struct mapped_device *md, bool new_map)
}
if (nodata) {
- if (dm_ima_alloc_and_copy_name_uuid(md, &dev_name, &dev_uuid, noio))
- goto error2;
-
+ fix_context_strings(context);
l = scnprintf(device_table_data, DM_IMA_DEVICE_BUF_LEN,
"%sname=%s,uuid=%s;table_clear=no_data;",
- DM_IMA_VERSION_STR, dev_name, dev_uuid);
+ DM_IMA_VERSION_STR, context->dev_name,
+ context->dev_uuid);
}
memcpy(device_table_data + l, capacity_str, capacity_len);
@@ -580,29 +615,33 @@ void dm_ima_measure_on_table_clear(struct mapped_device *md, bool new_map)
memset(&md->ima.inactive_table, 0, sizeof(md->ima.inactive_table));
}
- kfree(dev_name);
- kfree(dev_uuid);
-error2:
+error:
kfree(capacity_str);
-error1:
kfree(device_table_data);
+
+ wake_next_measure(&md->ima);
}
/*
* Measure IMA data on device rename.
*/
-void dm_ima_measure_on_device_rename(struct mapped_device *md)
+void dm_ima_measure_on_device_rename(struct mapped_device *md,
+ struct dm_ima_context *context)
{
- char *old_device_data = NULL, *new_device_data = NULL, *combined_device_data = NULL;
- char *new_dev_name = NULL, *new_dev_uuid = NULL, *capacity_str = NULL;
+ char *old_device_data = NULL, *new_device_data = NULL;
+ char *combined_device_data = NULL, *capacity_str = NULL;
bool noio = true;
int len;
- if (dm_ima_alloc_and_copy_device_data(md, &new_device_data,
- md->ima.active_table.num_targets, noio))
+ if (unlikely(!context))
return;
- if (dm_ima_alloc_and_copy_name_uuid(md, &new_dev_name, &new_dev_uuid, noio))
+ wait_to_measure(&md->ima, context->update_idx);
+
+ fix_context_strings(context);
+ if (dm_ima_alloc_and_copy_device_data(md, &new_device_data, context,
+ md->ima.active_table.num_targets,
+ noio))
goto error;
combined_device_data = dm_ima_alloc(DM_IMA_DEVICE_BUF_LEN * 2, noio);
@@ -619,7 +658,7 @@ void dm_ima_measure_on_device_rename(struct mapped_device *md)
len = scnprintf(combined_device_data, DM_IMA_DEVICE_BUF_LEN * 2,
"%s%snew_name=%s,new_uuid=%s;%s", DM_IMA_VERSION_STR, old_device_data,
- new_dev_name, new_dev_uuid, capacity_str);
+ context->dev_name, context->dev_uuid, capacity_str);
dm_ima_measure_data("dm_device_rename", combined_device_data, len, noio);
@@ -631,6 +670,6 @@ void dm_ima_measure_on_device_rename(struct mapped_device *md)
kfree(capacity_str);
kfree(combined_device_data);
kfree(old_device_data);
- kfree(new_dev_name);
- kfree(new_dev_uuid);
+
+ wake_next_measure(&md->ima);
}
diff --git a/drivers/md/dm-ima.h b/drivers/md/dm-ima.h
index c0548492bef0..01fa0b89a385 100644
--- a/drivers/md/dm-ima.h
+++ b/drivers/md/dm-ima.h
@@ -24,6 +24,11 @@
__dm_ima_str(DM_VERSION_MINOR) "." \
__dm_ima_str(DM_VERSION_PATCHLEVEL) ";"
+enum dm_ima_table_op {
+ DM_IMA_TABLE_SAVE,
+ DM_IMA_TABLE_RESTORE,
+};
+
#ifdef CONFIG_IMA
struct dm_ima_device_table_metadata {
@@ -45,28 +50,68 @@ struct dm_ima_device_table_metadata {
unsigned int hash_len;
};
+struct dm_ima_context {
+ struct dm_ima_device_table_metadata table;
+ unsigned int update_idx;
+ char dev_name[DM_NAME_LEN*2];
+ char dev_uuid[DM_UUID_LEN*2];
+};
+
/*
* This structure contains device metadata, and table hash for
* active and inactive tables for ima measurements.
*/
struct dm_ima_measurements {
+ unsigned int update_idx;
+ unsigned int measure_idx;
+ struct wait_queue_head ima_wq;
+ spinlock_t ima_lock;
struct dm_ima_device_table_metadata active_table;
struct dm_ima_device_table_metadata inactive_table;
};
-void dm_ima_measure_on_table_load(struct dm_table *table);
-void dm_ima_measure_on_device_resume(struct mapped_device *md, bool swap);
-void dm_ima_measure_on_device_remove(struct mapped_device *md, bool remove_all);
-void dm_ima_measure_on_table_clear(struct mapped_device *md, bool new_map);
-void dm_ima_measure_on_device_rename(struct mapped_device *md);
+void dm_ima_init(struct mapped_device *md);
+void dm_ima_alloc_context(struct dm_ima_context **context, bool noio);
+void dm_ima_free_context(struct dm_ima_context *context);
+void dm_ima_context_table_op(struct mapped_device *md,
+ struct dm_ima_context *context,
+ enum dm_ima_table_op op);
+void dm_ima_measure_on_table_load(struct dm_table *table,
+ struct dm_ima_context *context);
+void dm_ima_measure_on_device_resume(struct mapped_device *md, bool swap,
+ struct dm_ima_context *context);
+void dm_ima_measure_on_device_remove(struct mapped_device *md, bool remove_all,
+ struct dm_ima_context *context,
+ unsigned int idx);
+void dm_ima_measure_on_table_clear(struct mapped_device *md, bool new_map,
+ struct dm_ima_context *context);
+void dm_ima_measure_on_device_rename(struct mapped_device *md,
+ struct dm_ima_context *context);
#else
-static inline void dm_ima_measure_on_table_load(struct dm_table *table) {}
-static inline void dm_ima_measure_on_device_resume(struct mapped_device *md, bool swap) {}
-static inline void dm_ima_measure_on_device_remove(struct mapped_device *md, bool remove_all) {}
-static inline void dm_ima_measure_on_table_clear(struct mapped_device *md, bool new_map) {}
-static inline void dm_ima_measure_on_device_rename(struct mapped_device *md) {}
+struct dm_ima_context;
+
+static inline void dm_ima_init(struct mapped_device *md) {}
+static inline void dm_ima_alloc_context(struct dm_ima_context **context, bool noio) {}
+static inline void dm_ima_free_context(struct dm_ima_context *context) {}
+static inline void dm_ima_context_table_op(struct mapped_device *md,
+ struct dm_ima_context *context,
+ enum dm_ima_table_op op) {}
+static inline void dm_ima_measure_on_table_load(struct dm_table *table,
+ struct dm_ima_context *context) {}
+static inline void dm_ima_measure_on_device_resume(struct mapped_device *md,
+ bool swap,
+ struct dm_ima_context *context) {}
+static inline void dm_ima_measure_on_device_remove(struct mapped_device *md,
+ bool remove_all,
+ struct dm_ima_context *context,
+ unsigned int idx) {}
+static inline void dm_ima_measure_on_table_clear(struct mapped_device *md,
+ bool new_map,
+ struct dm_ima_context *context) {}
+static inline void dm_ima_measure_on_device_rename(struct mapped_device *md,
+ struct dm_ima_context *context) {}
#endif /* CONFIG_IMA */
diff --git a/drivers/md/dm-ioctl.c b/drivers/md/dm-ioctl.c
index 074a3c71297e..3da8b33cdc54 100644
--- a/drivers/md/dm-ioctl.c
+++ b/drivers/md/dm-ioctl.c
@@ -259,6 +259,80 @@ static void free_cell(struct hash_cell *hc)
}
}
+#ifdef CONFIG_IMA
+
+/*
+ * Called while holding to _hash_lock, to guarantee the ordering of the
+ * following dm_ima_measure_on_* functions, which should be called
+ * right after dropping the _hash_lock
+ */
+static unsigned int dm_ima_init_context(struct hash_cell *hc,
+ struct dm_ima_context *context,
+ bool need_idx)
+{
+ lockdep_assert_held(&_hash_lock);
+
+ if (unlikely(!context))
+ return need_idx ? hc->md->ima.update_idx++ : 0;
+
+ context->update_idx = hc->md->ima.update_idx++;
+ strcpy(context->dev_name, hc->name);
+ strcpy(context->dev_uuid, hc->uuid ? : "");
+
+ return context->update_idx;
+}
+
+/*
+ * Called by do_resume() to guarantee correct ordering, since do_resume()
+ * does not grab the _hash_lock when the table is not getting swapped or
+ * when actually swapping the active table
+ */
+static bool dm_ima_need_measure(struct mapped_device *md,
+ struct dm_table *table,
+ struct dm_ima_context *context)
+{
+ int srcu_idx;
+ struct hash_cell *hc;
+ bool need_measure = false;
+
+ if (unlikely(!context))
+ return false;
+
+ down_write(&_hash_lock);
+ /* Check if the device has been removed */
+ hc = dm_get_mdptr(md);
+ if (hc) {
+ /*
+ * If we have a table, we need to make sure that it's the
+ * active table. Otherwise we raced with another process
+ * setting the active table and it will do the measurement
+ */
+ if (!table || dm_get_live_table(md, &srcu_idx) == table) {
+ dm_ima_init_context(hc, context, false);
+ need_measure = true;
+ }
+ if (table)
+ dm_put_live_table(md, srcu_idx);
+ }
+ up_write(&_hash_lock);
+
+ return need_measure;
+}
+#else
+static inline unsigned int dm_ima_init_context(struct hash_cell *hc,
+ struct dm_ima_context *context,
+ bool neex_idx)
+{
+ return 0;
+}
+static inline bool dm_ima_need_measure(struct mapped_device *md,
+ struct dm_table *table,
+ struct dm_ima_context *context)
+{
+ return false;
+}
+#endif
+
/*
* The kdev_t and uuid of a device can never change once it is
* initially inserted.
@@ -344,7 +418,10 @@ static int dm_hash_remove_all(unsigned flags)
struct hash_cell *hc;
struct mapped_device *md;
struct dm_table *t;
+ struct dm_ima_context *ima_context = NULL;
+ unsigned int ima_idx;
+ dm_ima_alloc_context(&ima_context, true);
retry:
dev_skipped = 0;
@@ -353,6 +430,7 @@ static int dm_hash_remove_all(unsigned flags)
for (n = rb_first(&name_rb_tree); n; n = rb_next(n)) {
if (flags & DM_REMOVE_INTERRUPTIBLE && fatal_signal_pending(current)) {
up_write(&_hash_lock);
+ dm_ima_free_context(ima_context);
return -EINTR;
}
@@ -367,6 +445,7 @@ static int dm_hash_remove_all(unsigned flags)
continue;
}
+ ima_idx = dm_ima_init_context(hc, ima_context, true);
t = __hash_remove(hc);
up_write(&_hash_lock);
@@ -375,7 +454,7 @@ static int dm_hash_remove_all(unsigned flags)
dm_sync_table(md);
dm_table_destroy(t);
}
- dm_ima_measure_on_device_remove(md, true);
+ dm_ima_measure_on_device_remove(md, true, ima_context, ima_idx);
dm_put(md);
if (likely(flags & DM_REMOVE_KEEP_OPEN_DEVICES))
dm_destroy(md);
@@ -396,6 +475,7 @@ static int dm_hash_remove_all(unsigned flags)
if (dev_skipped && !(flags & DM_REMOVE_ONLY_DEFERRED))
DMWARN("remove_all left %d open device(s)", dev_skipped);
+ dm_ima_free_context(ima_context);
return 0;
}
@@ -443,6 +523,7 @@ static struct mapped_device *dm_hash_rename(struct dm_ioctl *param,
struct mapped_device *md;
unsigned int change_uuid = (param->flags & DM_UUID_FLAG) ? 1 : 0;
int srcu_idx;
+ struct dm_ima_context *ima_context = NULL;
/*
* duplicate new.
@@ -451,6 +532,7 @@ static struct mapped_device *dm_hash_rename(struct dm_ioctl *param,
if (!new_data)
return ERR_PTR(-ENOMEM);
+ dm_ima_alloc_context(&ima_context, true);
down_write(&_hash_lock);
/*
@@ -467,6 +549,7 @@ static struct mapped_device *dm_hash_rename(struct dm_ioctl *param,
param->name, new);
dm_put(hc->md);
up_write(&_hash_lock);
+ dm_ima_free_context(ima_context);
kfree(new_data);
return ERR_PTR(-EBUSY);
}
@@ -479,6 +562,7 @@ static struct mapped_device *dm_hash_rename(struct dm_ioctl *param,
DMERR("Unable to rename non-existent device, %s to %s%s",
param->name, change_uuid ? "uuid " : "", new);
up_write(&_hash_lock);
+ dm_ima_free_context(ima_context);
kfree(new_data);
return ERR_PTR(-ENXIO);
}
@@ -492,6 +576,7 @@ static struct mapped_device *dm_hash_rename(struct dm_ioctl *param,
param->name, new, hc->uuid);
dm_put(hc->md);
up_write(&_hash_lock);
+ dm_ima_free_context(ima_context);
kfree(new_data);
return ERR_PTR(-EINVAL);
}
@@ -514,9 +599,11 @@ static struct mapped_device *dm_hash_rename(struct dm_ioctl *param,
md = hc->md;
- dm_ima_measure_on_device_rename(md);
+ dm_ima_init_context(hc, ima_context, false);
up_write(&_hash_lock);
+ dm_ima_measure_on_device_rename(md, ima_context);
+ dm_ima_free_context(ima_context);
kfree(old_name);
return md;
@@ -995,13 +1082,17 @@ static int dev_remove(struct file *filp, struct dm_ioctl *param, size_t param_si
struct mapped_device *md;
int r;
struct dm_table *t;
+ struct dm_ima_context *ima_context = NULL;
+ unsigned int ima_idx;
+ dm_ima_alloc_context(&ima_context, true);
down_write(&_hash_lock);
hc = __find_device_hash_cell(param);
if (!hc) {
DMDEBUG_LIMIT("device doesn't appear to be in the dev hash table.");
up_write(&_hash_lock);
+ dm_ima_free_context(ima_context);
return -ENXIO;
}
@@ -1015,14 +1106,17 @@ static int dev_remove(struct file *filp, struct dm_ioctl *param, size_t param_si
if (r == -EBUSY && param->flags & DM_DEFERRED_REMOVE) {
up_write(&_hash_lock);
dm_put(md);
+ dm_ima_free_context(ima_context);
return 0;
}
DMDEBUG_LIMIT("unable to remove open device %s", hc->name);
up_write(&_hash_lock);
dm_put(md);
+ dm_ima_free_context(ima_context);
return r;
}
+ ima_idx = dm_ima_init_context(hc, ima_context, true);
t = __hash_remove(hc);
up_write(&_hash_lock);
@@ -1033,7 +1127,8 @@ static int dev_remove(struct file *filp, struct dm_ioctl *param, size_t param_si
param->flags &= ~DM_DEFERRED_REMOVE;
- dm_ima_measure_on_device_remove(md, false);
+ dm_ima_measure_on_device_remove(md, false, ima_context, ima_idx);
+ dm_ima_free_context(ima_context);
if (!dm_kobject_uevent(md, KOBJ_REMOVE, param->event_nr, false))
param->flags |= DM_UEVENT_GENERATED_FLAG;
@@ -1169,13 +1264,16 @@ static int do_resume(struct dm_ioctl *param)
struct mapped_device *md;
struct dm_table *new_map, *old_map = NULL;
bool need_resize_uevent = false;
+ struct dm_ima_context *ima_context = NULL;
+ dm_ima_alloc_context(&ima_context, true);
down_write(&_hash_lock);
hc = __find_device_hash_cell(param);
if (!hc) {
DMDEBUG_LIMIT("device doesn't appear to be in the dev hash table.");
up_write(&_hash_lock);
+ dm_ima_free_context(ima_context);
return -ENXIO;
}
@@ -1184,13 +1282,15 @@ static int do_resume(struct dm_ioctl *param)
new_map = hc->new_map;
hc->new_map = NULL;
param->flags &= ~DM_INACTIVE_PRESENT_FLAG;
-
+ if (new_map)
+ dm_ima_init_context(hc, ima_context, false);
up_write(&_hash_lock);
/* Do we need to load a new map ? */
if (new_map) {
sector_t old_size, new_size;
+ dm_ima_context_table_op(md, ima_context, DM_IMA_TABLE_SAVE);
/* Suspend if it isn't already suspended */
if (param->flags & DM_SKIP_LOCKFS_FLAG)
suspend_flags &= ~DM_SUSPEND_LOCKFS_FLAG;
@@ -1204,6 +1304,8 @@ static int do_resume(struct dm_ioctl *param)
if (hc && !hc->new_map) {
hc->new_map = new_map;
new_map = NULL;
+ dm_ima_init_context(hc, ima_context,
+ false);
} else {
r = -ENXIO;
}
@@ -1211,7 +1313,9 @@ static int do_resume(struct dm_ioctl *param)
if (new_map) {
dm_sync_table(md);
dm_table_destroy(new_map);
- }
+ } else
+ dm_ima_context_table_op(md, ima_context, DM_IMA_TABLE_RESTORE);
+ dm_ima_free_context(ima_context);
dm_put(md);
return r;
}
@@ -1222,9 +1326,12 @@ static int do_resume(struct dm_ioctl *param)
if (IS_ERR(old_map)) {
dm_sync_table(md);
dm_table_destroy(new_map);
+ dm_ima_free_context(ima_context);
dm_put(md);
return PTR_ERR(old_map);
}
+ if (dm_ima_need_measure(md, new_map, ima_context))
+ dm_ima_measure_on_device_resume(md, true, ima_context);
new_size = dm_get_size(md);
if (old_size && new_size && old_size != new_size)
need_resize_uevent = true;
@@ -1238,7 +1345,10 @@ static int do_resume(struct dm_ioctl *param)
if (dm_suspended_md(md)) {
r = dm_resume(md);
if (!r) {
- dm_ima_measure_on_device_resume(md, new_map ? true : false);
+ if (!new_map && dm_ima_need_measure(md, NULL,
+ ima_context))
+ dm_ima_measure_on_device_resume(md, false,
+ ima_context);
if (!dm_kobject_uevent(md, KOBJ_CHANGE, param->event_nr, need_resize_uevent))
param->flags |= DM_UEVENT_GENERATED_FLAG;
@@ -1255,6 +1365,7 @@ static int do_resume(struct dm_ioctl *param)
if (!r)
__dev_status(md, param);
+ dm_ima_free_context(ima_context);
dm_put(md);
return r;
}
@@ -1532,11 +1643,12 @@ static bool is_valid_type(enum dm_queue_mode cur, enum dm_queue_mode new)
static int table_load(struct file *filp, struct dm_ioctl *param, size_t param_size)
{
- int r;
+ int r, srcu_idx;
struct hash_cell *hc;
struct dm_table *t, *old_map = NULL;
struct mapped_device *md;
struct target_type *immutable_target_type;
+ struct dm_ima_context *ima_context = NULL;
md = find_device(param);
if (!md)
@@ -1552,8 +1664,6 @@ static int table_load(struct file *filp, struct dm_ioctl *param, size_t param_si
if (r)
goto err_unlock_md_type;
- dm_ima_measure_on_table_load(t);
-
immutable_target_type = dm_get_immutable_target_type(md);
if (immutable_target_type &&
(immutable_target_type != dm_table_get_immutable_target_type(t)) &&
@@ -1580,12 +1690,14 @@ static int table_load(struct file *filp, struct dm_ioctl *param, size_t param_si
dm_unlock_md_type(md);
+ dm_ima_alloc_context(&ima_context, false);
/* stage inactive table */
down_write(&_hash_lock);
hc = dm_get_mdptr(md);
if (!hc) {
DMERR("device has been removed from the dev hash table.");
up_write(&_hash_lock);
+ dm_ima_free_context(ima_context);
r = -ENXIO;
goto err_destroy_table;
}
@@ -1593,8 +1705,15 @@ static int table_load(struct file *filp, struct dm_ioctl *param, size_t param_si
if (hc->new_map)
old_map = hc->new_map;
hc->new_map = t;
+ dm_ima_init_context(hc, ima_context, false);
+ /* Make sure new_map doesn't get freed before we measure it*/
+ dm_get_live_table(md, &srcu_idx);
up_write(&_hash_lock);
+ dm_ima_measure_on_table_load(t, ima_context);
+ dm_ima_free_context(ima_context);
+ dm_put_live_table(md, srcu_idx);
+
param->flags |= DM_INACTIVE_PRESENT_FLAG;
__dev_status(md, param);
@@ -1623,13 +1742,16 @@ static int table_clear(struct file *filp, struct dm_ioctl *param, size_t param_s
struct mapped_device *md;
struct dm_table *old_map = NULL;
bool has_new_map = false;
+ struct dm_ima_context *ima_context = NULL;
+ dm_ima_alloc_context(&ima_context, true);
down_write(&_hash_lock);
hc = __find_device_hash_cell(param);
if (!hc) {
DMDEBUG_LIMIT("device doesn't appear to be in the dev hash table.");
up_write(&_hash_lock);
+ dm_ima_free_context(ima_context);
[Output truncated: showing 1000 of 1036 lines]]
|
| 334/2 |
2026/11/03 20:42 |
llm |
history-explorer |
1m
Model:
Tokens:
input: 92706
output: 1930
thoughts: 2804
Thoughts: **Race Condition Analysis: Device Mapper and Block Layer Interaction**
Alright, let's break this down. From what I've seen, this is a textbook race condition between Device Mapper's `table_load()` function and the device removal process, particularly the `dev_remove()` function, which culminates in a lockdep splat in the block layer. The root cause lies in how queue freeze lockdep states are modeled, which allows `blk_mark_disk_dead()` to be called at an unsafe time.
Looking at the Device Mapper side, the key vulnerability appears to be that `dm_lock_md_type()` in `table_load()` protects concurrent table loads but *doesn't* protect against a concurrent `dev_remove`. Consequently, `dev_remove` can proceed with the destruction of the device, including calling `blk_mark_disk_dead()` *before* `table_load` has completed setting up the queue via `dm_setup_md_queue()` and `add_disk()`. The `md->holders` counter, intended for reference tracking, isn't adequately protected here. Several past commits highlight that these kinds of races have been addressed by:
* Checking `DMF_FREEING` or `dm_deleting_md(md)`: For example, `44b43ec132f1` protected critical sections with `suspend_lock` and checked `test_bit(DMF_FREEING, &md->flags)`. `c50abeb38026` checked `dm_deleting_md(md)` in `target_message()`. And `b9a41d21dcea` used atomic checks for `DMF_FREEING` and `DMF_DELETING` under `_minor_lock`. These patterns emphasize that concurrent access to a device being destroyed is problematic, and these flags are crucial protection, indicating that the device has been marked for deletion, avoiding ioctl operations on devices being deleted.
* Protecting against race with `__dm_destroy` from the block layer: `3f77316de0ec` introduced waiting for `atomic_read(&md->holders)` in `__dm_destroy()`. However, `blk_mark_disk_dead(md->disk)` was introduced *before* this wait loop and has caused this race condition, highlighting that reference counting is not enough.
In the block layer, the race condition is exposed due to the handling of queue freeze and unfreeze operations. Commits like `6a78699838a0` and `6f491a8d4b92` have attempted to refine lockdep tracking. The issue stems from the fact that `blk_mark_disk_dead()` can acquire `q->mq_freeze_lock`, overwrite flags in `struct request_queue`, and these flags are then read by a later call to `blk_unfreeze_release_lock(q)`, leading to incorrect lockdep state. Relevant patterns include:
* Managing freeze/unfreeze explicitly: In the past, commit `f1be1788a32e` used to store flags on the call stack or passed them explicitly. And `6a78699838a0` required that lockdep checks were limited to the task that initiated a freeze operation. Flags/releases must correlate to the owner.
* Tracking Freeze State: The flags need to be snapshotted or consumed while `q->mq_freeze_lock` is held. Commits like `f6661b1d0525` removed the explicit boolean arguments and tracked `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying` automatically, causing issues with synchronization.
The historical context clearly illustrates the critical need for robust synchronization in both Device Mapper and the block layer. Any fix must ensure that the device's lifecycle is managed atomically and that the lockdep state transitions are handled consistently with the owner task and are protected across the block layer. Either a snapshot is needed, or all operations must stay within the lock. The placement of the `blk_mark_disk_dead()` call relative to the `md->holders` counter in `__dm_destroy()` needs careful review and revision.
|
| 335/1 |
2026/11/03 20:44 |
agent |
patch-planner |
30m
Model:
Instruction:
Design the fix strategy for a Linux kernel bug before implementation.
You are given a crash report, a detailed root cause explanation, and historical context on how similar bugs were
fixed in the subsystem.
Your goal is to design a concrete, single-patch implementation plan for another developer who will write and test
the code. Evaluate candidate approaches against the architectural design guidelines below and pick the best one
that fits a single, standalone patch.
Frequently the same coding mistake is done in several locations in the source code. Check if the fix should be
extended to similar cases in the same file or closely related files in the same subsystem, and include them in
the plan if they fit a single logical patch (do not expand to a large kernel-wide refactoring).
If you are changing post-conditions of a function, consider all callers of the functions,
and if they need to be updated to handle new post-conditions. For example, if you make
a function that previously never returned a NULL, return NULL, consider if callers
need to be updated to handle NULL return value.
Your final reply must be a concise, actionable implementation plan specifying:
1. The chosen fix approach and why it satisfies the subsystem's invariants and lifecycle rules.
2. The exact files, functions, and structs to modify, and the specific changes to make in each.
3. Any caller updates, locking/refcounting details, or error-unwinding ordering to follow.
Don't make assumptions about the kernel source code (it may be different from what you assume it is).
Extensively use the provided code access tools (codesearch-*, git-*, grepper, etc)
to examine the actual source code, and confirm any assumptions.
---
# Kernel Architectural Design & Maintainer Taste
Evaluate kernel patches and fix proposals beyond binary bug presence. Enforce **maintainer taste**, **lifecycle symmetry**, **typestate soundness**, and **topological graph simplicity**.
---
## 1. Core Philosophy: Band-Aid vs. Architectural Design
Naive patches often introduce **defensive sentinel guards** (e.g., ad-hoc `if (!ptr) return;` checks, status flags, or suppressed warnings) directly at the point of failure. While locally avoiding crashes, they degrade subsystem architecture by leaving uninitialized states reachable.
Maintainer "good taste" solves the root cause by **shifting invariants** (making invalid states unrepresentable) and moving dynamic runtime checks into static typestate guarantees.
```
HACKY BAND-AID FIX (Monolithic Cleanup) ARCHITECTURAL DESIGN (Scoped RAII / Invariant Shift)
βββββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββββββ
[ Init / Entry ] [ Init / Entry ]
β β
(Register Global Cleanup) (Allocate Resource A)
β β
[ Init Sub-B ] ββfailβββ [ Init Sub-B ] ββfailβββ
β (success) β β (success) β
βΌ β βΌ βΌ
[ Setup Complete ] β (Arm B Cleanup / RAII) (Unwind A Only:
β β β B never armed)
(Deferred Teardown) β βΌ β
β β [ Setup Complete ] βΌ
βΌ βΌ β [ Error Exit ]
[ release_all ] βββββββββ (LIFO Scope Teardown)
β β
(if (!ctx->b) return;) <-- Defensive guard! βΌ
β [ Clean Destruction ]
[ Unsafe State ] (Zero sentinel checks needed)
```
```c
// ANTI-PATTERN (Defensive Sentinel Guard): Teardown called on partial init -> callee needs guard
void driver_cleanup(struct ctx *ctx) {
if (!ctx->buf) return; // <-- Sentinel band-aid
free_buffer(ctx->buf);
}
// CANONICAL SHIFT (Granular Scoped Action): Registered only upon complete initialization
ctx->buf = alloc_buffer();
if (!ctx->buf) return -ENOMEM;
devm_add_action_or_reset(dev, free_buffer_action, ctx->buf);
```
---
## 2. Maintainer Taste as Graph Topology & Structural Simplicity
Software design quality maps directly to graph-theoretic properties across the Control-Flow Graph (CFG), Data-Flow Graph (DFG), and Object Lifecycle DAG:
### A. Control-Flow Graph (CFG) Simplification
* **Branch Minimization & Path Explosion (McCabe 1976):** Every defensive check added to a compound destructor or callback (`if (!ctx->buffer) return;`) adds a predicate node ($\pi$), increases cyclomatic complexity $v(G) = |E| - |V| + 2$, causes exponential path explosion ($O(2^k)$ paths), and enlarges explicit state spaces ($|S| = \prod |D_i|$). Good taste eliminates the branch by guaranteeing destructors are invoked only on initialized typestates. *(Note: Standard idempotent leaf deallocators like `kfree(NULL)` and public API input sanitizers are exempt).*
* **Single-Entry Single-Exit (SESE) Symmetry (Ferrante 1987, Johnson 1994, Dijkstra 1972):** Resource acquisition and release must form strict **nested dominator trees**. If resource $R_i$ is acquired at node $A$, the set of release actions $\{B_1, \dots, B_m\}$ must form a strict **post-dominating cut** relative to $A$ across all maximal exit paths.
* **Pointer Uniformity (Linus's "Good Taste" Rule):** Eliminate special-case conditional branches by operating on address indirection (e.g., indirect pointers `**curr` in linked list unlinking) to unify edge and interior cases into a branchless invariant.
* **Lexical Scope Invariants & Affine Lifecycles (Wadler 1990, RAII):** Enforce SESE symmetry and "consumed exactly once" affine invariants using compiler-backed scoped cleanup (`<linux/cleanup.h>` `guard()`, `scoped_guard()`, `__free()`).
### B. Ownership & Lifetime DAGs
* **Acyclic Lifecycles & Topological Teardown (Tarjan 1972, Kahn 1962):** Resource ownership must form a strict Directed Acyclic Graph (DAG) $G = (R, E)$. Teardown order must strictly follow reverse topological sort $\text{toposort}(G)^R$. Mixing conflicting lifetime paradigms (e.g., embedding a dynamic refcounted `kref`/socket struct inside a device-managed `devres` buffer or parent container) violates DAG acyclicity, creating synchronous blocking hacks (`wait_for_completion`), circular pins, and Use-After-Free hazards.
* **Three-Phase Concurrent Quiescence:** Multi-threaded and asynchronous teardown (networking, block layer, RCU) must strictly sequence: (1) **Deactivation/Delisting** (make unreachable) -> (2) **Quiescence & Draining** (`synchronize_rcu()`, `cancel_work_sync()`, `napi_disable()`) -> (3) **Physical Reclamation** (`kfree()`, `kmem_cache_destroy()`).
* **Typestate Validity (Strom & Yemini 1986, Aldrich et al. 2009):** A struct with $N$ fields should not use runtime boolean flags (`ctx->is_initialized`) to model incomplete typestates. Sub-resources must transition as a deterministic typestate automaton ($S_{uninit} \xrightarrow{\text{alloc}} S_{init} \xrightarrow{\text{publish}} S_{registered}$), and registration functions must accept only fully initialized typestates.
---
## 3. Deterministic Decision Trigger Matrix
| Code Symptom / Trigger (When you see X) | Anti-Pattern Band-Aid (DO NOT DO Z) | Canonical Invariant Shift (DO Y) |
| :--- | :--- | :--- |
| **Null deref in compound destructor / cleanup callback** | Add `if (!priv->buf) return;` in composite cleanup handler | Register granular cleanup immediately upon allocation via `devm_add_action_or_reset()`, `<linux/cleanup.h>` `__free()`, or discrete reverse LIFO labels |
| **UAF on dynamic object after container unbind** | Allocate with `devm_kzalloc()` and block on `wait_for_completion()` | Allocate with `kzalloc()`, manage lifetime via `kref_get()`/`kref_put()`, call unbind/delist on unbind, free in `kref` release callback |
| **Goto ladder lock leaks on early error exit** | Sprinkle manual `mutex_unlock()` across error returns | Use `guard(mutex)(&lock)` or `scoped_guard(spinlock, &lock)` from `<linux/cleanup.h>` |
| **Callback / IRQ / timer fires before full init** | Add `if (!priv->ready)` check inside IRQ/timer handler | Move `request_irq()`, `timer_setup()`, or `napi_enable()` strictly to the end of setup after all state structures are fully initialized |
| **Multi-step setup failure leaks resources** | Route all errors to a single `err:` label calling a monolithic `cleanup(priv)` with NULL checks | Use `cleanup.h` RAII, granular `devm` actions, or a strict reverse LIFO goto ladder (`err_free_b:` -> `err_free_a:`) |
| **Mixed ownership / asymmetric refcount drops** | Conditionally call `kref_put()` in caller based on error code | Enforce unconditional callee-cleans or caller-cleans ownership convention across all paths |
| **Ad-hoc state flag polling during teardown** | Add `priv->stopping = true` and spin/poll in callbacks | Use atomic typestate transitions and synchronous flush/drain APIs (`cancel_work_sync()`, `drain_workqueue()`) |
---
## 4. The Architectural Review Checklist
Before finalizing any kernel fix or review, audit against the following four criteria:
1. **The Sentinel Test (Caller vs. Callee Responsibility):**
* *Smell:* Adding a defensive guard (`if (!ptr)` or `if (flags & INITIALIZED)`) inside a compound teardown callback or destructor to mask partial initialization.
* *Invariant:* If a destructor executes on uninitialized data, the defect is at the **caller's registration/invocation point**, not the callee.
* *Note:* Standard C allocator no-ops (`kfree(NULL)`) and public API parameter validators (`if (WARN_ON(!ptr)) return -EINVAL;`) are exempt; this rule targets *internal subsystem lifecycle pipelines and teardown paths*.
* *Action:* Move registration to the point of complete initialization (`devm_add_action_or_reset()`, RAII/`__free()`, or discrete caller unwinding).
2. **LIFO Stack Unwinding Symmetry:**
* *Smell:* Releasing resources in arbitrary order or invoking destructors for partially initialized subsystems.
* *Invariant:* Resource release must strictly mirror acquisition order in reverse (LIFO) without monolithic cleanup guards.
* *Action:* Verify that partial setup/initialization failures (e.g., `probe()`, `mount()`, `open()`, `alloc_pool()`) unwind only already-allocated resources in reverse order via strict LIFO labels or `cleanup.h` scope exit.
3. **Ownership Decoupling:**
* *Smell:* Embedding dynamically refcounted objects (`kref`, `struct sock`, `struct inode`, `struct file`) directly inside hardware device-bound allocations (`devres`) or parent containers (`super_block`, `net_device`).
* *Invariant:* Dynamic consumer references must outlive parent unregistration without use-after-free, circular pins, or blocking hacks.
* *Action:* Decouple the refcounted core object from the container binding; container teardown must unbind/delist the object, but memory is freed exclusively by the final `kref_put()`.
4. **Codebase Idiom Alignment:**
* *Smell:* Using legacy custom rollback ladders, ad-hoc state flags, or manual lock unlocking on error paths.
* *Invariant:* Prefer standard, modern kernel abstractions with compiler-enforced safety guarantees.
* *Action (Modern >= 6.6):* Replace manual boilerplate with `cleanup.h` (`guard()`, `scoped_guard()`, `__free()`), `devm_add_action_or_reset()`, `refcount_t`, and standard `kref` helpers.
* *Action (Legacy / LTS / No-RAII Subsystems):* Enforce clean, branchless reverse LIFO goto ladders (`err_free_b:` -> `err_free_a:`).
Prefer calling several tools at the same time to save round-trips.
Prompt:
The crash that corresponds to the bug is:
device-mapper: ioctl: device has been removed from the dev hash table.
================================================
WARNING: lock held when returning to user space!
syzkaller #1 Not tainted
------------------------------------------------
syz.3.1525/11804 is leaving the kernel with locks still held!
locks held by syz.3.1525/11804: 1, last CPU#0:
#0: ffff88805abdd468 (&q->q_usage_counter(queue)#52){+.+.}-{0:0}, at: blk_mq_freeze_queue include/linux/blk-mq.h:959 [inline]
#0: ffff88805abdd468 (&q->q_usage_counter(queue)#52){+.+.}-{0:0}, at: elevator_change+0x194/0x480 block/elevator.c:668
The explanation of the root cause of the bug is:
### Root Cause Analysis
#### Summary
The `WARNING: lock held when returning to user space!` for `&q->q_usage_counter(queue)` (which is the lockdep map `q->q_lockdep_map` acquired at `elevator_change+0x194/0x480`, `block/elevator.c:668`) is caused by a race condition between:
1. **`DM_TABLE_LOAD` (`table_load`)** initializing and registering the request-based DM queue/gendisk (`dm_setup_md_queue()` -> `add_disk()` -> `blk_register_queue()` -> `elevator_set_default()` -> `elevator_change()`), and
2. **`DM_DEV_REMOVE` (`dev_remove`)** concurrently destroying the same DM device (`dm_destroy()` -> `__dm_destroy()` -> `blk_mark_disk_dead()`), which marks the queue dying and starts draining/freezing the queue.
Specifically, in the block layer's queue-freeze lockdep tracking (`block/blk-mq.c` and `block/blk.h`), the flags `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead` are stored as per-`request_queue` fields protected by `q->mq_freeze_lock` when `q->mq_freeze_depth == 0`, **but `blk_unfreeze_release_lock(q)` reads them outside `q->mq_freeze_lock` after `q->mq_freeze_depth` has already been decremented to `0`**. When `blk_mark_disk_dead()` races with `blk_mq_unfreeze_queue()`, `q->mq_freeze_queue_dying` is overwritten from `false` to `true` before `blk_unfreeze_release_lock(q)` runs, causing `blk_unfreeze_release_lock(q)` to skip releasing `q->q_lockdep_map`.
---
#### Detailed Mechanism
##### 1. Lockdep modeling of `blk_mq_freeze_queue()` / `blk_mq_unfreeze_queue()`
In `block/blk-core.c:500`, `q->q_lockdep_map` is initialized with the name `"&q->q_usage_counter(queue)"`:
```c
lockdep_init_map(&q->q_lockdep_map, "&q->q_usage_counter(queue)",
&q->q_lock_cls_key, 0);
```
In `block/blk-mq.c`, when a task freezes a queue via `blk_mq_freeze_queue(q)` -> `blk_freeze_queue_start(q)`:
```c
static bool blk_freeze_set_owner(struct request_queue *q,
struct task_struct *owner)
{
if (!owner)
return false;
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
q->mq_freeze_disk_dead = !q->disk ||
test_bit(GD_DEAD, &q->disk->state) ||
!blk_queue_registered(q);
q->mq_freeze_queue_dying = blk_queue_dying(q);
return true;
}
if (owner == q->mq_freeze_owner)
q->mq_freeze_owner_depth += 1;
return false;
}
```
```c
bool __blk_freeze_queue_start(struct request_queue *q,
struct task_struct *owner)
{
bool freeze;
mutex_lock(&q->mq_freeze_lock);
freeze = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
if (queue_is_mq(q))
blk_mq_run_hw_queues(q, false);
} else {
mutex_unlock(&q->mq_freeze_lock);
}
return freeze;
}
void blk_freeze_queue_start(struct request_queue *q)
{
if (__blk_freeze_queue_start(q, current))
blk_freeze_acquire_lock(q);
}
```
And in `block/blk.h:715-728`:
```c
static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
if (!q->mq_freeze_queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
```
When the owner task unfreezes the queue via `blk_mq_unfreeze_queue(q, memflags)` -> `blk_mq_unfreeze_queue_nomemrestore(q)` (`block/blk-mq.c:211-235`):
```c
bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
bool unfreeze;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
q->q_usage_counter.data->force_atomic = true;
q->mq_freeze_depth--;
WARN_ON_ONCE(q->mq_freeze_depth < 0);
if (!q->mq_freeze_depth) {
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
}
unfreeze = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
return unfreeze;
}
void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
{
if (__blk_mq_unfreeze_queue(q, false))
blk_unfreeze_release_lock(q);
}
```
Notice the bug here:
1. Inside `__blk_mq_unfreeze_queue()`, `q->mq_freeze_depth` is decremented to `0` and `q->mq_freeze_owner` is cleared to `NULL`, and then `mutex_unlock(&q->mq_freeze_lock)` is called.
2. Only **after** `q->mq_freeze_lock` is released does `blk_mq_unfreeze_queue_nomemrestore()` call `blk_unfreeze_release_lock(q)`, which inspects `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead`.
3. Because `q->mq_freeze_depth` is already `0` and `q->mq_freeze_lock` is unlocked, another thread calling `__blk_freeze_queue_start()` can immediately acquire `q->mq_freeze_lock`, see `!q->mq_freeze_depth`, and overwrite `q->mq_freeze_queue_dying` (and `q->mq_freeze_disk_dead`) in `blk_freeze_set_owner()`.
##### 2. How Device Mapper triggers this race
In the reproducer:
1. `ioctl(DM_DEV_CREATE)` creates a DM device `md` (`md->type == DM_TYPE_NONE`, with `md->disk` allocated via `blk_alloc_disk()`).
2. **Thread 1 (`syz.3.1525/11804`)** calls `ioctl(DM_TABLE_LOAD)` (`table_load()` in `drivers/md/dm-ioctl.c:1622`) with a request-based `"multipath"` target:
- `find_device(param)` looks up `md` under `_hash_lock`, increments `md->holders` (`dm_get(md)`), and drops `_hash_lock`.
- `populate_table()` parses the `"multipath"` target, setting the table type to `DM_TYPE_REQUEST_BASED`.
- Since `dm_get_md_type(md) == DM_TYPE_NONE`, `table_load()` calls `dm_setup_md_queue(md, t)` (`drivers/md/dm.c:2606`):
- `dm_mq_init_request_queue(md, t)` initializes `md->queue` as a `blk-mq` queue.
- `add_disk(md->disk)` -> `device_add_disk()` -> `add_disk_fwnode()` -> `__add_disk()` -> `blk_register_queue(md->disk)` (`block/blk-sysfs.c:991`):
```c
if (queue_is_mq(q))
elevator_set_default(q);
```
- `elevator_set_default(q)` calls `elevator_change(q, &ctx)` (`block/elevator.c:653`).
3. Concurrently, **Thread 2** calls `ioctl(DM_DEV_REMOVE)` (`dev_remove()` in `drivers/md/dm-ioctl.c:1063`):
- Under `_hash_lock`, `dm_lock_for_deletion(md, ...)` succeeds because it only checks `dm_open_count(md)` (`0`), **not** `md->holders`.
- `__hash_remove(hc)` removes `hc` from the hash table and clears `md->interface_ptr` (`dm_set_mdptr(md, NULL)`).
- `dev_remove()` drops `_hash_lock`, calls `dm_put(md)`, and calls `dm_destroy(md)` -> `__dm_destroy(md, true)` (`drivers/md/dm.c:2726`):
```c
blk_mark_disk_dead(md->disk);
...
if (wait)
while (atomic_read(&md->holders))
fsleep(1000);
```
- Notice that `__dm_destroy()` calls `blk_mark_disk_dead(md->disk)` **before** waiting for `md->holders` to drop to `0`.
##### 3. Exact Race Sequence
1. **Thread 1 (`table_load`)** enters `elevator_change()` (`block/elevator.c:668`):
```c
memflags = blk_mq_freeze_queue(q);
```
- `q->mq_freeze_depth` is `0`.
- `blk_freeze_set_owner(q, Thread_1)` sets:
- `q->mq_freeze_owner = Thread_1`
- `q->mq_freeze_owner_depth = 1`
- `q->mq_freeze_disk_dead = true` (since `QUEUE_FLAG_REGISTERED` is not set yet)
- `q->mq_freeze_queue_dying = false` (since `QUEUE_FLAG_DYING` is not set yet)
- `q->mq_freeze_depth` becomes `1`.
- `blk_freeze_acquire_lock(q)` sees `!q->mq_freeze_queue_dying == true` and calls:
```c
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
```
2. **Thread 1 (`table_load`)** finishes `elevator_switch()` and calls `blk_mq_unfreeze_queue(q, memflags)` at `block/elevator.c:683`:
- Inside `__blk_mq_unfreeze_queue(q, false)` (`block/blk-mq.c:211`):
- `q->mq_freeze_depth` is decremented from `1` to `0`.
- `blk_unfreeze_check_owner(q)` decrements `q->mq_freeze_owner_depth` to `0`, sets `q->mq_freeze_owner = NULL`, and returns `true`.
- `mutex_unlock(&q->mq_freeze_lock)` unlocks `q->mq_freeze_lock`.
3. **Thread 2 (`dev_remove`)** executes `blk_mark_disk_dead(md->disk)` (`block/genhd.c:689`):
```c
void blk_mark_disk_dead(struct gendisk *disk)
{
blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
__blk_mark_disk_dead(disk);
blk_report_disk_dead(disk, true);
}
```
- `blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue)` sets `QUEUE_FLAG_DYING` on `q`.
- `__blk_mark_disk_dead(disk)` calls `blk_queue_start_drain(disk->queue)` -> `__blk_freeze_queue_start(q, Thread_2)`.
- Right after Thread 1 unlocks `q->mq_freeze_lock` in step 2 (e.g., when woken from `q->mq_freeze_lock` wait_list during `mutex_unlock`), Thread 2 acquires `q->mq_freeze_lock`.
- Because `q->mq_freeze_depth` is `0`, `blk_freeze_set_owner(q, Thread_2)` runs and sets:
```c
q->mq_freeze_queue_dying = blk_queue_dying(q); /* true! */
```
4. **Thread 1 (`table_load`)** now executes `blk_unfreeze_release_lock(q)` (`block/blk-mq.c:233` -> `block/blk.h:722`):
```c
static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
```
Because `q->mq_freeze_queue_dying` was overwritten with `true` by Thread 2 in step 3, `!q->mq_freeze_queue_dying` evaluates to `false`, and **`rwsem_release(&q->q_lockdep_map, _RET_IP_)` is skipped**.
5. **Thread 1 (`table_load`)** finishes `dm_setup_md_queue()`, acquires `_hash_lock` in `table_load()` (`drivers/md/dm-ioctl.c:1678`), sees `hc = dm_get_mdptr(md)` is `NULL`, logs:
```
device-mapper: ioctl: device has been removed from the dev hash table.
```
cleans up `t`, drops `md->holders` (`dm_put(md)`), and returns `-ENXIO` to user space with `q->q_lockdep_map` (`&q->q_usage_counter(queue)`) still held in lockdep, triggering the warning.
---
#### How to Fix
1. **In the block layer (`block/blk-mq.c`, `block/blk.h`, `block/genhd.c`)**:
`blk_freeze_acquire_lock(q)` and `blk_unfreeze_release_lock(q)` must not read mutable per-queue `q->mq_freeze_queue_dying` / `q->mq_freeze_disk_dead` fields outside `q->mq_freeze_lock` after `q->mq_freeze_depth` has dropped to `0` (where another task starting a new freeze can overwrite them). Either:
- Perform the lockdep release (`blk_unfreeze_release_lock(q)`) / state consumption under `q->mq_freeze_lock` before `q->mq_freeze_depth` is decremented / unlocked (or pass the saved `disk_dead` and `queue_dying` booleans out of `__blk_mq_unfreeze_queue()` by value while still holding `q->mq_freeze_lock`), and similarly pass/snapshot them under `q->mq_freeze_lock` in `__blk_freeze_queue_start()`.
2. **In Device Mapper (`drivers/md/dm.c`)**:
In `__dm_destroy()`, `blk_mark_disk_dead(md->disk)` should not be called while another thread holds `md->holders` and may still be in `dm_setup_md_queue()` / `add_disk(md->disk)` initializing and registering the disk/queue (i.e., wait for `atomic_read(&md->holders)` or serialize against `md->type_lock` before marking the disk dead).
Historical context on how similar bugs were fixed in the past:
Based on research into the commit history of the **Block Layer** and **Device Mapper** subsystems over the past 3 years (and relevant foundational commits), here is the historical context, prior art, and subsystem idioms for addressing this bug.
---
### 1. Block Layer: Queue Freeze Lockdep Tracking (`block/blk-mq.c`, `block/blk.h`)
#### Historical Context and Evolution
The queue freeze and unfreeze lockdep tracking was introduced and refined across several recent commits:
* **`f1be1788a32e` ("block: model freeze & enter queue as lock for supporting lockdep")**:
Initially modeled queue freeze/unfreeze using lockdep (`q->q_lockdep_map` and `q->io_lockdep_map`). Originally, `blk_freeze_acquire_lock()` and `blk_unfreeze_release_lock()` took explicit boolean parameters (`disk_dead`, `queue_dying`) passed down the call stack or stored as local variables.
* **`6a78699838a0` ("block: always verify unfreeze lock on the owner task")**:
Addressed an issue where freeze depth could drop across different tasks. It established the rule that lockdep verification must only occur on the **freeze owner task context** by tracking `q->mq_freeze_owner` and `q->mq_freeze_owner_depth` under `q->mq_freeze_lock`. `blk_freeze_set_owner()` only assigns ownership on outermost freeze (`!q->mq_freeze_depth`), and `blk_unfreeze_check_owner()` only authorizes releasing the lockdep map on the outermost unfreeze when `mq_freeze_owner_depth` drops to 0.
* **`6f491a8d4b92` ("block: track disk DEAD state automatically for modeling queue freeze lockdep")** and **`f6661b1d0525` ("block: track queue dying state automatically for modeling queue freeze lockdep")**:
Eliminated the boolean parameters to make lockdep tracking automatic. Under `q->mq_freeze_lock`, `blk_freeze_set_owner()` records `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying` on `struct request_queue`. The commit log noted that *"the state is one per-task variable now"*.
**However**, storing these booleans directly in `struct request_queue` without snapshotting them or protecting their read in `blk_unfreeze_release_lock()` broke this per-task guarantee: `blk_unfreeze_release_lock(q)` reads `q->mq_freeze_queue_dying` **outside** `q->mq_freeze_lock` after `q->mq_freeze_depth` has already been decremented to 0.
#### Idioms and Locking Patterns from Prior Art
1. **Never read per-queue mutable lockdep state outside `q->mq_freeze_lock` once `mq_freeze_depth == 0`**:
Any fields in `struct request_queue` conditioned on `!q->mq_freeze_depth` can immediately be overwritten by another task starting a new freeze (e.g. `__blk_freeze_queue_start()` called via `blk_mark_disk_dead()` or `blk_queue_start_drain()`) the instant `q->mq_freeze_lock` is dropped in `__blk_mq_unfreeze_queue()`.
2. **Snapshot state under the lock or perform the lockdep release before releasing the lock**:
* *Passing by value / snapshotting*: Similar to the pattern in `f1be1788a32e`, when a task needs to remember the state captured at freeze time, that state must either be snapshotted under `q->mq_freeze_lock` into local stack variables before unlocking (e.g., returned by `blk_unfreeze_check_owner()` / `__blk_mq_unfreeze_queue()`), or
* *Lockdep release under `q->mq_freeze_lock`*: Releasing a lockdep map (`rwsem_release()` / `lock_release()`) simply removes the held lock from the task's held-lock list and does not establish new lock dependency edges, so state consumption and release under `q->mq_freeze_lock` before depth drops to 0 avoids the race window entirely.
---
### 2. Device Mapper: Device Removal vs Table Load Synchronization (`drivers/md/dm.c`, `drivers/md/dm-ioctl.c`)
#### Historical Context and Evolution
The race occurs because `table_load()` is setting up the request-based queue (`dm_setup_md_queue()` -> `add_disk()` -> `elevator_change()`) while `dev_remove()` concurrently calls `dm_destroy()` -> `__dm_destroy()` -> `blk_mark_disk_dead()`:
* **`3f77316de0ec` ("dm: separate device deletion from dm_put")**:
Separated mapped device deletion from reference counting. It established the convention that `__dm_destroy()` must wait for all in-flight references held on the mapped device via `while (atomic_read(&md->holders)) fsleep(1000);`.
* **`3b785fbcf81c` ("dm: mark request_queue dead before destroying the DM device")** and **`7a5428dcb790` ("block: fix surprise removal for drivers calling blk_set_queue_dying")**:
Replaced direct queue flag setting with `blk_mark_disk_dead(md->disk)` at the top of `__dm_destroy()`. This was intended to reject new I/O during removal, but placed the call **before** `__dm_destroy()` waits for `atomic_read(&md->holders)`.
* **`00c4fc3b1f59` ("dm ioctl: increase granularity of type_lock when loading table")**:
Recognized that `md->type` and `md->queue` setup must be serialized, introducing `dm_lock_md_type()` / `md->type_lock` during `table_load()` around `dm_setup_md_queue()`. However, `__dm_destroy()` does not acquire or synchronize against `md->type_lock`.
* **`44b43ec132f1` ("dm: fix resume-vs-remove race")**:
Fixed a race where an ioctl (`dm_resume`) raced with `__dm_destroy()`. The pattern used was explicitly checking device removal flags (`test_bit(DMF_FREEING, &md->flags)`) under the appropriate lock (`suspend_lock`) to reject operations on devices undergoing destruction.
* **`c50abeb38026` ("dm ioctl: forbid messages to devices being deleted")** and **`abdc568b0540` ("dm: prevent access to md being deleted")**:
Prevented operations on devices being deleted by checking `dm_deleting_md(md)` (which tests `DMF_DELETING`, set in `dm_lock_for_deletion()`) under `_minor_lock`.
#### Idioms and Locking Patterns from Prior Art
1. **Do not mark a disk dead before in-flight device holders finish setup**:
In `__dm_destroy()`, calling `blk_mark_disk_dead(md->disk)` while `atomic_read(&md->holders) > 0` allows `blk_mark_disk_dead()` to race with concurrent operations (such as `table_load()`) that hold `md->holders` and are still in the middle of disk registration or queue setup (`dm_setup_md_queue()` / `add_disk()`). In DM's lifecycle model, disk teardown actions should follow the drainage of active holders.
2. **Check deletion flags (`DMF_DELETING` / `DMF_FREEING`) before mutating queue/device state**:
As demonstrated in `44b43ec132f1` and `c50abeb38026`, ioctls modifying device state must check `dm_deleting_md(md)` or `DMF_FREEING` to abort cleanly (returning `-ENXIO`) before performing heavy setup like initializing request queues or adding disks.
3. **Serialize queue type initialization against device destruction**:
`table_load()` uses `md->type_lock` to serialize queue setup. Ensuring that `__dm_destroy()` synchronizes with `md->type_lock` prevents tearing down or marking a queue dying while `dm_setup_md_queue()` is configuring it.
Reply: ### Implementation Plan
#### 1. Fix Strategy & Architectural Rationale
The bug is a race condition in the block layer's queue-freeze lockdep tracking (`block/blk-mq.c`, `block/blk.h`, `block/genhd.c`, `block/blk-core.c`).
Currently, `blk_freeze_set_owner()` records `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying` on `struct request_queue` under `q->mq_freeze_lock` when `q->mq_freeze_depth == 0`. However, `blk_freeze_acquire_lock(q)` and `blk_unfreeze_release_lock(q)` read those mutable per-queue fields **outside** `q->mq_freeze_lock`. On unfreeze (`blk_mq_unfreeze_queue_nomemrestore()`), `__blk_mq_unfreeze_queue()` decrements `q->mq_freeze_depth` to `0`, clears `q->mq_freeze_owner = NULL`, and unlocks `q->mq_freeze_lock` **before** `blk_unfreeze_release_lock(q)` runs. Any concurrent freeze starting on another CPU (such as `blk_mark_disk_dead()` during `DM_DEV_REMOVE`, or another `blk_mq_freeze_queue()`) can immediately acquire `q->mq_freeze_lock`, observe `!q->mq_freeze_depth`, and overwrite `q->mq_freeze_queue_dying` / `q->mq_freeze_disk_dead` before the unfreezing task executes `blk_unfreeze_release_lock(q)`. This causes `blk_unfreeze_release_lock(q)` to skip releasing `q->q_lockdep_map` (or `q->io_lockdep_map`), leaving the task returning to user space with the lockdep lock still held.
Additionally, `blk_queue_start_drain(q)` unconditionally passes `current` as the freeze `owner` to `__blk_freeze_queue_start(q, current)`. When `QUEUE_FLAG_DYING` is set (`blk_mark_disk_dead()`, `blk_mq_destroy_queue()`, or `__del_gendisk()` with `GD_OWNS_QUEUE`), the caller neither acquires lockdep maps nor unfreezes the queue; if called while `current` already holds an outer freeze (e.g., `do_rbd_remove()`), incrementing `q->mq_freeze_owner_depth` prevents the outer `blk_mq_unfreeze_queue()` from ever reaching `mq_freeze_owner_depth == 0`.
**Chosen Approach:**
1. **Snapshot and return a lockdep bitmask under `q->mq_freeze_lock`:**
Replace `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying` with a bitmask `q->mq_freeze_lock_mask` (`BLK_FREEZE_LOCK_IO`, `BLK_FREEZE_LOCK_QUEUE`) protected strictly by `q->mq_freeze_lock`. Have `blk_freeze_set_owner()` / `__blk_freeze_queue_start()` and `blk_unfreeze_check_owner()` / `__blk_mq_unfreeze_queue()` return this `unsigned int` bitmask by value while holding `q->mq_freeze_lock` (`0` if not the outermost owner or if neither lockdep map applies). Pass the returned `lock_mask` by value into `blk_freeze_acquire_lock(q, lock_mask)` and `blk_unfreeze_release_lock(q, lock_mask)` outside `q->mq_freeze_lock`.
- This preserves strict LIFO lock ordering relative to `q->mq_freeze_lock` (avoiding `mq_freeze_lock -> q_lockdep_map` lockdep inversions on acquire and non-LIFO lockdep stack unwinding on release).
- It eliminates all unlocked reads of mutable `struct request_queue` lockdep state in `blk_freeze_acquire_lock()` and `blk_unfreeze_release_lock()`.
- It simplifies the control-flow graph at all call sites by folding the `bool` ownership check and individual lockdep map predicates into `lock_mask`.
2. **Avoid claiming freeze ownership on dying drains in `blk_queue_start_drain()`:**
Pass `blk_queue_dying(q) ? NULL : current` to `__blk_freeze_queue_start()` in `blk_queue_start_drain()` so that permanent/dying drains do not claim or increment `q->mq_freeze_owner_depth`.
---
#### 2. Exact Files, Structs, and Functions to Modify
##### A. `include/linux/blkdev.h`
* **`struct request_queue` (lines 636β645):**
Replace `bool mq_freeze_disk_dead;` and `bool mq_freeze_queue_dying;` under `#ifdef CONFIG_LOCKDEP` with `unsigned int mq_freeze_lock_mask;`:
```c
#ifdef CONFIG_LOCKDEP
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
/*
* Records lockdep locks acquired in owner context, used in unfreeze
* queue
*/
unsigned int mq_freeze_lock_mask;
#endif
```
##### B. `block/blk.h`
* **Function declarations (lines 58β61):**
Update the return types of `__blk_mq_unfreeze_queue()`, `blk_queue_start_drain()`, and `__blk_freeze_queue_start()` from `bool` to `unsigned int`:
```c
unsigned int __blk_mq_unfreeze_queue(struct request_queue *q,
bool force_atomic);
unsigned int blk_queue_start_drain(struct request_queue *q);
unsigned int __blk_freeze_queue_start(struct request_queue *q,
struct task_struct *owner);
```
* **Lockdep helpers `blk_freeze_acquire_lock()` and `blk_unfreeze_release_lock()` (lines 780β803):**
Define the lock mask flags and update both inline helpers to take `unsigned int lock_mask` instead of reading `q->mq_freeze_*`:
```c
enum {
BLK_FREEZE_LOCK_IO = (1 << 0),
BLK_FREEZE_LOCK_QUEUE = (1 << 1),
};
#ifdef CONFIG_LOCKDEP
static inline void blk_freeze_acquire_lock(struct request_queue *q,
unsigned int lock_mask)
{
if (lock_mask & BLK_FREEZE_LOCK_IO)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
if (lock_mask & BLK_FREEZE_LOCK_QUEUE)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
static inline void blk_unfreeze_release_lock(struct request_queue *q,
unsigned int lock_mask)
{
if (lock_mask & BLK_FREEZE_LOCK_QUEUE)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (lock_mask & BLK_FREEZE_LOCK_IO)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
#else
static inline void blk_freeze_acquire_lock(struct request_queue *q,
unsigned int lock_mask)
{
}
static inline void blk_unfreeze_release_lock(struct request_queue *q,
unsigned int lock_mask)
{
}
#endif
```
##### C. `block/blk-mq.c`
* **`blk_freeze_set_owner()` and `blk_unfreeze_check_owner()` (lines 115β161):**
Change return types from `bool` to `unsigned int`. Compute, store, and return `q->mq_freeze_lock_mask` while holding `q->mq_freeze_lock`:
```c
#ifdef CONFIG_LOCKDEP
static unsigned int blk_freeze_set_owner(struct request_queue *q,
struct task_struct *owner)
{
unsigned int lock_mask = 0;
if (!owner)
return 0;
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
if (q->disk && !test_bit(GD_DEAD, &q->disk->state) &&
blk_queue_registered(q))
lock_mask |= BLK_FREEZE_LOCK_IO;
if (!blk_queue_dying(q))
lock_mask |= BLK_FREEZE_LOCK_QUEUE;
q->mq_freeze_lock_mask = lock_mask;
return lock_mask;
}
if (owner == q->mq_freeze_owner)
q->mq_freeze_owner_depth += 1;
return 0;
}
/* verify the last unfreeze in owner context */
static unsigned int blk_unfreeze_check_owner(struct request_queue *q)
{
if (q->mq_freeze_owner != current)
return 0;
if (--q->mq_freeze_owner_depth == 0) {
q->mq_freeze_owner = NULL;
return q->mq_freeze_lock_mask;
}
return 0;
}
#else
static unsigned int blk_freeze_set_owner(struct request_queue *q,
struct task_struct *owner)
{
return 0;
}
static unsigned int blk_unfreeze_check_owner(struct request_queue *q)
{
return 0;
}
#endif
```
* **`__blk_freeze_queue_start()` and `blk_freeze_queue_start()` (lines 163β187):**
Return `lock_mask` from `__blk_freeze_queue_start()` and pass it to `blk_freeze_acquire_lock()`:
```c
unsigned int __blk_freeze_queue_start(struct request_queue *q,
struct task_struct *owner)
{
unsigned int lock_mask;
mutex_lock(&q->mq_freeze_lock);
lock_mask = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
if (queue_is_mq(q))
blk_mq_run_hw_queues(q, false);
} else {
mutex_unlock(&q->mq_freeze_lock);
}
return lock_mask;
}
void blk_freeze_queue_start(struct request_queue *q)
{
unsigned int lock_mask = __blk_freeze_queue_start(q, current);
blk_freeze_acquire_lock(q, lock_mask);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
```
* **`__blk_mq_unfreeze_queue()` and `blk_mq_unfreeze_queue_nomemrestore()` (lines 211β235):**
Return `lock_mask` from `__blk_mq_unfreeze_queue()` (captured under `q->mq_freeze_lock`) and pass it to `blk_unfreeze_release_lock()`:
```c
unsigned int __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
unsigned int lock_mask;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
q->q_usage_counter.data->force_atomic = true;
q->mq_freeze_depth--;
WARN_ON_ONCE(q->mq_freeze_depth < 0);
if (!q->mq_freeze_depth) {
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
}
lock_mask = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
return lock_mask;
}
void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
{
unsigned int lock_mask = __blk_mq_unfreeze_queue(q, false);
blk_unfreeze_release_lock(q, lock_mask);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_nomemrestore);
```
##### D. `block/blk-core.c`
* **`blk_queue_start_drain()` (lines 327β341):**
Change return type to `unsigned int` and pass `NULL` as owner if `blk_queue_dying(q)` is set:
```c
unsigned int blk_queue_start_drain(struct request_queue *q)
{
/*
* When queue DYING flag is set, we need to block new req
* entering queue, so we call blk_freeze_queue_start() to
* prevent I/O from crossing blk_queue_enter().
*/
unsigned int lock_mask = __blk_freeze_queue_start(q,
blk_queue_dying(q) ? NULL : current);
if (queue_is_mq(q))
blk_mq_wake_waiters(q);
/* Make blk_queue_enter() reexamine the DYING flag. */
wake_up_all(&q->mq_freeze_wq);
return lock_mask;
}
```
##### E. `block/genhd.c`
* **`__blk_mark_disk_dead()` (lines 660β680):**
Change return type from `bool` to `unsigned int` (returning `0` instead of `false` when `GD_DEAD` is already set).
* **`__del_gendisk()` (lines 697β782):**
Replace `bool start_drain;` with `unsigned int lock_mask;` and pass `lock_mask` to `blk_freeze_acquire_lock()` and `blk_unfreeze_release_lock()`:
```c
mutex_lock(&disk->open_mutex);
lock_mask = __blk_mark_disk_dead(disk);
blk_freeze_acquire_lock(q, lock_mask);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
...
if (!test_bit(GD_OWNS_QUEUE, &disk->state))
__blk_mq_unfreeze_queue(q, true);
else if (queue_is_mq(q))
blk_mq_exit_queue(q);
blk_unfreeze_release_lock(q, lock_mask);
```
---
#### 3. Caller Audit & Locking / Ordering Invariants
1. **All callers of modified functions:**
- `__blk_freeze_queue_start()`: called by `blk_freeze_queue_start()`, `blk_freeze_queue_start_non_owner()` (ignores return value), and `blk_queue_start_drain()` (propagates `unsigned int`).
- `blk_queue_start_drain()`: called by `blk_mq_destroy_queue()` (ignores return value) and `__blk_mark_disk_dead()` (propagates `unsigned int`).
- `__blk_mark_disk_dead()`: called by `blk_mark_disk_dead()` (ignores return value) and `__del_gendisk()` (stores `lock_mask`).
- `__blk_mq_unfreeze_queue()`: called by `blk_mq_unfreeze_queue_nomemrestore()`, `blk_mq_unfreeze_queue_non_owner()` (ignores return value), and `__del_gendisk()`.
- `blk_freeze_acquire_lock()` and `blk_unfreeze_release_lock()`: only called in `blk_freeze_queue_start()`, `blk_mq_unfreeze_queue_nomemrestore()`, and `__del_gendisk()`.
- No exported public APIs change signature (`blk_freeze_queue_start()` and `blk_mq_unfreeze_queue_nomemrestore()` retain `void` return type).
2. **Locking and Lockdep Ordering Rules:**
- `q->mq_freeze_lock_mask`, `q->mq_freeze_owner`, and `q->mq_freeze_owner_depth` must only be read or modified while holding `q->mq_freeze_lock`.
- `blk_freeze_acquire_lock(q, lock_mask)` and `blk_unfreeze_release_lock(q, lock_mask)` must be invoked **outside** `q->mq_freeze_lock`, operating exclusively on the local `lock_mask` value returned from the critical section, preserving LIFO order (`io_lockdep_map` then `q_lockdep_map` on acquire; `q_lockdep_map` then `io_lockdep_map` on release).
|
| 336/2 |
2026/11/03 20:44 |
llm |
patch-planner |
3m
Model:
Tokens:
input: 12643
output: 274
thoughts: 83
Thoughts: Okay, here's my summary, considering my expertise:
**Diving Deep into the Block Layer and DM Implementation**
Alright, let's get down to brass tacks. I'm going to leverage these tools to dissect the core of the block layer and Device Mapper implementation. I need to get a clear picture of how things are structured and how they've evolved. My target is the meat of the matter: Specifically, I want to thoroughly examine `block/blk-mq.c`, `block/blk.h`, and `include/linux/blkdev.h`. These files are critical to understand the modern multi-queue block layer. Then, I need to get a handle on the Device Mapper implementation: that means spending time with `drivers/md/dm.c` and `drivers/md/dm-ioctl.c` to see how it fits into the broader kernel context. Of course, this isn't just about static code analysis, I'll be reviewing relevant commits, the evolution of this code is important too. Given that there's a lot to unpack, I'll be running several tool calls in parallel to accelerate the process. Efficiency is key!
|
| 337/2 |
2026/11/03 20:48 |
tool |
read-file |
0m
Args: map[File:block/blk-mq.c FirstLine:130 LineCount:130]
Results: map[Contents: 130: }
131:
132: if (owner == q->mq_freeze_owner)
133: q->mq_freeze_owner_depth += 1;
134: return false;
135: }
136:
137: /* verify the last unfreeze in owner context */
138: static bool blk_unfreeze_check_owner(struct request_queue *q)
139: {
140: if (q->mq_freeze_owner != current)
141: return false;
142: if (--q->mq_freeze_owner_depth == 0) {
143: q->mq_freeze_owner = NULL;
144: return true;
145: }
146: return false;
147: }
148:
149: #else
150:
151: static bool blk_freeze_set_owner(struct request_queue *q,
152: struct task_struct *owner)
153: {
154: return false;
155: }
156:
157: static bool blk_unfreeze_check_owner(struct request_queue *q)
158: {
159: return false;
160: }
161: #endif
162:
163: bool __blk_freeze_queue_start(struct request_queue *q,
164: struct task_struct *owner)
165: {
166: bool freeze;
167:
168: mutex_lock(&q->mq_freeze_lock);
169: freeze = blk_freeze_set_owner(q, owner);
170: if (++q->mq_freeze_depth == 1) {
171: percpu_ref_kill(&q->q_usage_counter);
172: mutex_unlock(&q->mq_freeze_lock);
173: if (queue_is_mq(q))
174: blk_mq_run_hw_queues(q, false);
175: } else {
176: mutex_unlock(&q->mq_freeze_lock);
177: }
178:
179: return freeze;
180: }
181:
182: void blk_freeze_queue_start(struct request_queue *q)
183: {
184: if (__blk_freeze_queue_start(q, current))
185: blk_freeze_acquire_lock(q);
186: }
187: EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
188:
189: void blk_mq_freeze_queue_wait(struct request_queue *q)
190: {
191: wait_event(q->mq_freeze_wq, percpu_ref_is_zero(&q->q_usage_counter));
192: }
193: EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait);
194:
195: int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
196: unsigned long timeout)
197: {
198: return wait_event_timeout(q->mq_freeze_wq,
199: percpu_ref_is_zero(&q->q_usage_counter),
200: timeout);
201: }
202: EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait_timeout);
203:
204: void blk_mq_freeze_queue_nomemsave(struct request_queue *q)
205: {
206: blk_freeze_queue_start(q);
207: blk_mq_freeze_queue_wait(q);
208: }
209: EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_nomemsave);
210:
211: bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
212: {
213: bool unfreeze;
214:
215: mutex_lock(&q->mq_freeze_lock);
216: if (force_atomic)
217: q->q_usage_counter.data->force_atomic = true;
218: q->mq_freeze_depth--;
219: WARN_ON_ONCE(q->mq_freeze_depth < 0);
220: if (!q->mq_freeze_depth) {
221: percpu_ref_resurrect(&q->q_usage_counter);
222: wake_up_all(&q->mq_freeze_wq);
223: }
224: unfreeze = blk_unfreeze_check_owner(q);
225: mutex_unlock(&q->mq_freeze_lock);
226:
227: return unfreeze;
228: }
229:
]
|
| 338/2 |
2026/11/03 20:48 |
tool |
read-file |
0m
Args: map[File:block/blk.h FirstLine:700 LineCount:50]
Results: map[Contents: 700: unsigned int bytes)
701: {
702: return false;
703: }
704: #endif /* CONFIG_FAIL_MAKE_REQUEST */
705:
706: /*
707: * Optimized request reference counting. Ideally we'd make timeouts be more
708: * clever, as that's the only reason we need references at all... But until
709: * this happens, this is faster than using refcount_t. Also see:
710: *
711: * abc54d634334 ("io_uring: switch to atomic_t for io_kiocb reference count")
712: */
713: #define req_ref_zero_or_close_to_overflow(req) \
714: ((unsigned int) atomic_read(&(req->ref)) + 127u <= 127u)
715:
716: static inline bool req_ref_inc_not_zero(struct request *req)
717: {
718: return atomic_inc_not_zero(&req->ref);
719: }
720:
721: static inline bool req_ref_put_and_test(struct request *req)
722: {
723: WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
724: return atomic_dec_and_test(&req->ref);
725: }
726:
727: static inline void req_ref_set(struct request *req, int value)
728: {
729: atomic_set(&req->ref, value);
730: }
731:
732: static inline int req_ref_read(struct request *req)
733: {
734: return atomic_read(&req->ref);
735: }
736:
737: static inline u64 blk_time_get_ns(void)
738: {
739: struct blk_plug *plug = current->plug;
740: u64 now;
741:
742: if (!plug || !in_task())
743: return ktime_get_ns();
744:
745: /*
746: * 0 could very well be a valid time, but rather than flag "this is
747: * a valid timestamp" separately, just accept that we'll do an extra
748: * ktime_get_ns() if we just happen to get 0 as the current time.
749: *
]
|
| 339/2 |
2026/11/03 20:48 |
tool |
git-show |
0m
Args:
Results: map[Output:commit f6661b1d0525f3764596a1b65eeed9e75aecafa7
Author: Ming Lei <ming.lei@redhat.com>
Date: Wed Nov 27 21:51:30 2024 +0800
block: track queue dying state automatically for modeling queue freeze lockdep
Now we only verify the outmost freeze & unfreeze in current context in case
that !q->mq_freeze_depth, so it is reliable to save queue lying state when
we want to lock the freeze queue since the state is one per-task variable
now.
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241127135133.3952153-5-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 0c6a319fb936..fca2ec64a06b 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -134,6 +134,7 @@ static bool blk_freeze_set_owner(struct request_queue *q,
q->mq_freeze_disk_dead = !q->disk ||
test_bit(GD_DEAD, &q->disk->state) ||
!blk_queue_registered(q);
+ q->mq_freeze_queue_dying = blk_queue_dying(q);
return true;
}
@@ -190,7 +191,7 @@ bool __blk_freeze_queue_start(struct request_queue *q,
void blk_freeze_queue_start(struct request_queue *q)
{
if (__blk_freeze_queue_start(q, current))
- blk_freeze_acquire_lock(q, false);
+ blk_freeze_acquire_lock(q);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -238,7 +239,7 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
void blk_mq_unfreeze_queue(struct request_queue *q)
{
if (__blk_mq_unfreeze_queue(q, false))
- blk_unfreeze_release_lock(q, false);
+ blk_unfreeze_release_lock(q);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
diff --git a/block/blk.h b/block/blk.h
index 8708168d50e4..cbf6a676ffe9 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -721,26 +721,26 @@ void blk_integrity_prepare(struct request *rq);
void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
#ifdef CONFIG_LOCKDEP
-static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
- if (!queue_dying)
+ if (!q->mq_freeze_queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
- if (!queue_dying)
+ if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
#else
-static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
}
#endif
diff --git a/block/genhd.c b/block/genhd.c
index 59ac299909b3..5678194b6b1a 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -661,7 +661,7 @@ void del_gendisk(struct gendisk *disk)
struct request_queue *q = disk->queue;
struct block_device *part;
unsigned long idx;
- bool start_drain, queue_dying;
+ bool start_drain;
might_sleep();
@@ -690,9 +690,8 @@ void del_gendisk(struct gendisk *disk)
*/
mutex_lock(&disk->open_mutex);
start_drain = __blk_mark_disk_dead(disk);
- queue_dying = blk_queue_dying(q);
if (start_drain)
- blk_freeze_acquire_lock(q, queue_dying);
+ blk_freeze_acquire_lock(q);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
@@ -748,7 +747,7 @@ void del_gendisk(struct gendisk *disk)
blk_mq_exit_queue(q);
if (start_drain)
- blk_unfreeze_release_lock(q, queue_dying);
+ blk_unfreeze_release_lock(q);
}
EXPORT_SYMBOL(del_gendisk);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 522cf8eef66c..5d40af2ef971 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -581,8 +581,12 @@ struct request_queue {
#ifdef CONFIG_LOCKDEP
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
- /* Records disk state in current context, used in unfreeze queue */
+ /*
+ * Records disk & queue state in current context, used in unfreeze
+ * queue
+ */
bool mq_freeze_disk_dead;
+ bool mq_freeze_queue_dying;
#endif
wait_queue_head_t mq_freeze_wq;
/*
]
|
| 340/2 |
2026/11/03 20:48 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 6f491a8d4b92d1a840fd9209cba783c84437d0b7
Author: Ming Lei <ming.lei@redhat.com>
Date: Wed Nov 27 21:51:28 2024 +0800
block: track disk DEAD state automatically for modeling queue freeze lockdep
Now we only verify the outmost freeze & unfreeze in current context in case
that !q->mq_freeze_depth, so it is reliable to save disk DEAD state when
we want to lock the freeze queue since the state is one per-task variable
now.
Doing this way can kill lots of false positive when freeze queue is
called before adding disk[1].
[1] https://lore.kernel.org/linux-block/6741f6b2.050a0220.1cc393.0017.GAE@google.com/
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241127135133.3952153-3-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 60f457f62913..0c6a319fb936 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -131,6 +131,9 @@ static bool blk_freeze_set_owner(struct request_queue *q,
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
+ q->mq_freeze_disk_dead = !q->disk ||
+ test_bit(GD_DEAD, &q->disk->state) ||
+ !blk_queue_registered(q);
return true;
}
@@ -187,7 +190,7 @@ bool __blk_freeze_queue_start(struct request_queue *q,
void blk_freeze_queue_start(struct request_queue *q)
{
if (__blk_freeze_queue_start(q, current))
- blk_freeze_acquire_lock(q, false, false);
+ blk_freeze_acquire_lock(q, false);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -235,7 +238,7 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
void blk_mq_unfreeze_queue(struct request_queue *q)
{
if (__blk_mq_unfreeze_queue(q, false))
- blk_unfreeze_release_lock(q, false, false);
+ blk_unfreeze_release_lock(q, false);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
diff --git a/block/blk.h b/block/blk.h
index 2c26abf505b8..8708168d50e4 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -720,22 +720,29 @@ void blk_integrity_verify(struct bio *bio);
void blk_integrity_prepare(struct request *rq);
void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
-static inline void blk_freeze_acquire_lock(struct request_queue *q, bool
- disk_dead, bool queue_dying)
+#ifdef CONFIG_LOCKDEP
+static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
{
- if (!disk_dead)
+ if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
if (!queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q, bool
- disk_dead, bool queue_dying)
+static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
{
if (!queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
- if (!disk_dead)
+ if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
+#else
+static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
+{
+}
+static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
+{
+}
+#endif
#endif /* BLK_INTERNAL_H */
diff --git a/block/elevator.c b/block/elevator.c
index 7c3ba80e5ff4..ca0a74369f1c 100644
--- a/block/elevator.c
+++ b/block/elevator.c
@@ -602,14 +602,14 @@ void elevator_init_mq(struct request_queue *q)
* Disk isn't added yet, so verifying queue lock only manually.
*/
blk_freeze_queue_start_non_owner(q);
- blk_freeze_acquire_lock(q, true, false);
+ blk_freeze_acquire_lock(q, false);
blk_mq_freeze_queue_wait(q);
blk_mq_cancel_work_sync(q);
err = blk_mq_init_sched(q, e);
- blk_unfreeze_release_lock(q, true, false);
+ blk_unfreeze_release_lock(q, false);
blk_mq_unfreeze_queue_non_owner(q);
if (err) {
diff --git a/block/genhd.c b/block/genhd.c
index 79230c109fca..59ac299909b3 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -692,7 +692,7 @@ void del_gendisk(struct gendisk *disk)
start_drain = __blk_mark_disk_dead(disk);
queue_dying = blk_queue_dying(q);
if (start_drain)
- blk_freeze_acquire_lock(q, true, queue_dying);
+ blk_freeze_acquire_lock(q, queue_dying);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
@@ -748,7 +748,7 @@ void del_gendisk(struct gendisk *disk)
blk_mq_exit_queue(q);
if (start_drain)
- blk_unfreeze_release_lock(q, true, queue_dying);
+ blk_unfreeze_release_lock(q, queue_dying);
}
EXPORT_SYMBOL(del_gendisk);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 378d3a1a22fc..522cf8eef66c 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -581,6 +581,8 @@ struct request_queue {
#ifdef CONFIG_LOCKDEP
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
+ /* Records disk state in current context, used in unfreeze queue */
+ bool mq_freeze_disk_dead;
#endif
wait_queue_head_t mq_freeze_wq;
/*
]
|
| 341/2 |
2026/11/03 20:48 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 6a78699838a0ddeed3620ddf50c1521f1fe1e811
Author: Ming Lei <ming.lei@redhat.com>
Date: Thu Oct 31 21:37:19 2024 +0800
block: always verify unfreeze lock on the owner task
commit f1be1788a32e ("block: model freeze & enter queue as lock for
supporting lockdep") tries to apply lockdep for verifying freeze &
unfreeze. However, the verification is only done the outmost freeze and
unfreeze. This way is actually not correct because q->mq_freeze_depth
still may drop to zero on other task instead of the freeze owner task.
Fix this issue by always verifying the last unfreeze lock on the owner
task context, and make sure both the outmost freeze & unfreeze are
verified in the current task.
Fixes: f1be1788a32e ("block: model freeze & enter queue as lock for supporting lockdep")
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241031133723.303835-4-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-core.c b/block/blk-core.c
index 09d10bb95fda..4f791a3114a1 100644
--- a/block/blk-core.c
+++ b/block/blk-core.c
@@ -287,7 +287,7 @@ bool blk_queue_start_drain(struct request_queue *q)
* entering queue, so we call blk_freeze_queue_start() to
* prevent I/O from crossing blk_queue_enter().
*/
- bool freeze = __blk_freeze_queue_start(q);
+ bool freeze = __blk_freeze_queue_start(q, current);
if (queue_is_mq(q))
blk_mq_wake_waiters(q);
/* Make blk_queue_enter() reexamine the DYING flag. */
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 5f4496220432..5e240a4b6be0 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -120,20 +120,66 @@ void blk_mq_in_flight_rw(struct request_queue *q, struct block_device *part,
inflight[1] = mi.inflight[1];
}
-bool __blk_freeze_queue_start(struct request_queue *q)
+#ifdef CONFIG_LOCKDEP
+static bool blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
{
- int freeze;
+ if (!owner)
+ return false;
+
+ if (!q->mq_freeze_depth) {
+ q->mq_freeze_owner = owner;
+ q->mq_freeze_owner_depth = 1;
+ return true;
+ }
+
+ if (owner == q->mq_freeze_owner)
+ q->mq_freeze_owner_depth += 1;
+ return false;
+}
+
+/* verify the last unfreeze in owner context */
+static bool blk_unfreeze_check_owner(struct request_queue *q)
+{
+ if (!q->mq_freeze_owner)
+ return false;
+ if (q->mq_freeze_owner != current)
+ return false;
+ if (--q->mq_freeze_owner_depth == 0) {
+ q->mq_freeze_owner = NULL;
+ return true;
+ }
+ return false;
+}
+
+#else
+
+static bool blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
+{
+ return false;
+}
+
+static bool blk_unfreeze_check_owner(struct request_queue *q)
+{
+ return false;
+}
+#endif
+
+bool __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner)
+{
+ bool freeze;
mutex_lock(&q->mq_freeze_lock);
+ freeze = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
if (queue_is_mq(q))
blk_mq_run_hw_queues(q, false);
- freeze = true;
} else {
mutex_unlock(&q->mq_freeze_lock);
- freeze = false;
}
return freeze;
@@ -141,7 +187,7 @@ bool __blk_freeze_queue_start(struct request_queue *q)
void blk_freeze_queue_start(struct request_queue *q)
{
- if (__blk_freeze_queue_start(q))
+ if (__blk_freeze_queue_start(q, current))
blk_freeze_acquire_lock(q, false, false);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -170,7 +216,7 @@ EXPORT_SYMBOL_GPL(blk_mq_freeze_queue);
bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
- int unfreeze = false;
+ bool unfreeze;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
@@ -180,8 +226,8 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
if (!q->mq_freeze_depth) {
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
- unfreeze = true;
}
+ unfreeze = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
return unfreeze;
@@ -203,7 +249,7 @@ EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
*/
void blk_freeze_queue_start_non_owner(struct request_queue *q)
{
- __blk_freeze_queue_start(q);
+ __blk_freeze_queue_start(q, NULL);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start_non_owner);
diff --git a/block/blk.h b/block/blk.h
index ac48b79cbf80..57fc035620d6 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -37,7 +37,8 @@ void blk_free_flush_queue(struct blk_flush_queue *q);
bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
bool blk_queue_start_drain(struct request_queue *q);
-bool __blk_freeze_queue_start(struct request_queue *q);
+bool __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner);
int __bio_queue_enter(struct request_queue *q, struct bio *bio);
void submit_bio_noacct_nocheck(struct bio *bio);
void bio_await_chain(struct bio *bio);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 93551772c1d6..1b51a7c92e9b 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -575,6 +575,10 @@ struct request_queue {
struct throtl_data *td;
#endif
struct rcu_head rcu_head;
+#ifdef CONFIG_LOCKDEP
+ struct task_struct *mq_freeze_owner;
+ int mq_freeze_owner_depth;
+#endif
wait_queue_head_t mq_freeze_wq;
/*
* Protect concurrent access to q_usage_counter by
]
|
| 342/2 |
2026/11/03 20:48 |
tool |
codesearch-find-references |
0m
Args: map[Name:blk_freeze_acquire_lock]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__del_gendisk SourceFile:block/genhd.c SourceLine:732] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_freeze_queue_start SourceFile:block/blk-mq.c SourceLine:185]] TruncatedOutput:false]
|
| 343/2 |
2026/11/03 20:48 |
tool |
codesearch-find-references |
0m
Args: map[Name:blk_unfreeze_release_lock]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__del_gendisk SourceFile:block/genhd.c SourceLine:781] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_mq_unfreeze_queue_nomemrestore SourceFile:block/blk-mq.c SourceLine:233]] TruncatedOutput:false]
|
| 344/2 |
2026/11/03 20:48 |
tool |
codesearch-find-references |
0m
Error:
Args: map[Name:mq_freeze_queue_dying]
Results: map[References:<nil> TruncatedOutput:false]
|
| 345/2 |
2026/11/03 20:48 |
tool |
codesearch-find-references |
0m
Error:
Args: map[Name:mq_freeze_disk_dead]
Results: map[References:<nil> TruncatedOutput:false]
|
| 346/2 |
2026/11/03 20:48 |
llm |
patch-planner |
0m
Model:
Tokens:
input: 21731
output: 269
thoughts: 105
Thoughts: Here's a breakdown of my thought process:
**Diving Deep into the Block Layer and DM**
Okay, I need to get a better handle on how this all fits together. My immediate focus is on understanding the block layer's inner workings, specifically the drain mechanism and how it interacts with device mapper. I'm going to start by examining `block/blk-mq.c` from lines 100 to 270. This area likely deals with the multi-queue block layer and I want to see how queues are managed, and drained. Next I'll switch over to `block/blk.h`, looking at lines 600-800, to get a handle on the data structures and definitions associated with the block layer. Then I'll peek into `block/genhd.c` around lines 650-800; I'm curious to see how general disk headers are created and initialized as they tie into the block layer too. After that, I will trace execution through `block/blk-core.c` around `blk_queue_start_drain`. This function is key for me, I need to understand how queues are drained, which then informs everything else. Finally, since Device Mapper is involved, I *must* look at the relevant parts of the Device Mapper code, specifically `drivers/md/dm.c` and `drivers/md/dm-ioctl.c`. This will give me the end-to-end perspective that I need. This collection of code provides a solid cross-section and should paint a comprehensive picture of the flow and interdependencies in the block layer, especially where DM is involved.
|
| 347/2 |
2026/11/03 20:48 |
tool |
read-file |
0m
Args: map[File:block/blk-mq.c FirstLine:110 LineCount:160]
Results: map[Contents: 110: &mi);
111: inflight[READ] = mi.inflight[READ];
112: inflight[WRITE] = mi.inflight[WRITE];
113: }
114:
115: #ifdef CONFIG_LOCKDEP
116: static bool blk_freeze_set_owner(struct request_queue *q,
117: struct task_struct *owner)
118: {
119: if (!owner)
120: return false;
121:
122: if (!q->mq_freeze_depth) {
123: q->mq_freeze_owner = owner;
124: q->mq_freeze_owner_depth = 1;
125: q->mq_freeze_disk_dead = !q->disk ||
126: test_bit(GD_DEAD, &q->disk->state) ||
127: !blk_queue_registered(q);
128: q->mq_freeze_queue_dying = blk_queue_dying(q);
129: return true;
130: }
131:
132: if (owner == q->mq_freeze_owner)
133: q->mq_freeze_owner_depth += 1;
134: return false;
135: }
136:
137: /* verify the last unfreeze in owner context */
138: static bool blk_unfreeze_check_owner(struct request_queue *q)
139: {
140: if (q->mq_freeze_owner != current)
141: return false;
142: if (--q->mq_freeze_owner_depth == 0) {
143: q->mq_freeze_owner = NULL;
144: return true;
145: }
146: return false;
147: }
148:
149: #else
150:
151: static bool blk_freeze_set_owner(struct request_queue *q,
152: struct task_struct *owner)
153: {
154: return false;
155: }
156:
157: static bool blk_unfreeze_check_owner(struct request_queue *q)
158: {
159: return false;
160: }
161: #endif
162:
163: bool __blk_freeze_queue_start(struct request_queue *q,
164: struct task_struct *owner)
165: {
166: bool freeze;
167:
168: mutex_lock(&q->mq_freeze_lock);
169: freeze = blk_freeze_set_owner(q, owner);
170: if (++q->mq_freeze_depth == 1) {
171: percpu_ref_kill(&q->q_usage_counter);
172: mutex_unlock(&q->mq_freeze_lock);
173: if (queue_is_mq(q))
174: blk_mq_run_hw_queues(q, false);
175: } else {
176: mutex_unlock(&q->mq_freeze_lock);
177: }
178:
179: return freeze;
180: }
181:
182: void blk_freeze_queue_start(struct request_queue *q)
183: {
184: if (__blk_freeze_queue_start(q, current))
185: blk_freeze_acquire_lock(q);
186: }
187: EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
188:
189: void blk_mq_freeze_queue_wait(struct request_queue *q)
190: {
191: wait_event(q->mq_freeze_wq, percpu_ref_is_zero(&q->q_usage_counter));
192: }
193: EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait);
194:
195: int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
196: unsigned long timeout)
197: {
198: return wait_event_timeout(q->mq_freeze_wq,
199: percpu_ref_is_zero(&q->q_usage_counter),
200: timeout);
201: }
202: EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait_timeout);
203:
204: void blk_mq_freeze_queue_nomemsave(struct request_queue *q)
205: {
206: blk_freeze_queue_start(q);
207: blk_mq_freeze_queue_wait(q);
208: }
209: EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_nomemsave);
]
|
| 348/2 |
2026/11/03 20:48 |
tool |
read-file |
0m
Args: map[File:block/blk.h FirstLine:750 LineCount:60]
Results: map[Contents: 750: * cur_ktime can be zeroed by pre-emption the moment PF_BLOCK_TS is set.
751: */
752: now = READ_ONCE(plug->cur_ktime);
753: if (!now) {
754: now = ktime_get_ns();
755: WRITE_ONCE(plug->cur_ktime, now);
756: /* Ensure PF_BLOCK_TS is set after cur_ktime. */
757: barrier();
758: current->flags |= PF_BLOCK_TS;
759: }
760: return now;
761: }
762:
763: static inline ktime_t blk_time_get(void)
764: {
765: return ns_to_ktime(blk_time_get_ns());
766: }
767:
768: void bdev_release(struct file *bdev_file);
769: int bdev_open(struct block_device *bdev, blk_mode_t mode, void *holder,
770: const struct blk_holder_ops *hops, struct file *bdev_file);
771: int bdev_permission(dev_t dev, blk_mode_t mode, void *holder);
772:
773: void bio_integrity_generate(struct bio *bio);
774: blk_status_t bio_integrity_verify(struct bio *bio,
775: struct bvec_iter *saved_iter);
776:
777: void blk_integrity_prepare(struct request *rq);
778: void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
779:
780: #ifdef CONFIG_LOCKDEP
781: static inline void blk_freeze_acquire_lock(struct request_queue *q)
782: {
783: if (!q->mq_freeze_disk_dead)
784: rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
785: if (!q->mq_freeze_queue_dying)
786: rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
787: }
788:
789: static inline void blk_unfreeze_release_lock(struct request_queue *q)
790: {
791: if (!q->mq_freeze_queue_dying)
792: rwsem_release(&q->q_lockdep_map, _RET_IP_);
793: if (!q->mq_freeze_disk_dead)
794: rwsem_release(&q->io_lockdep_map, _RET_IP_);
795: }
796: #else
797: static inline void blk_freeze_acquire_lock(struct request_queue *q)
798: {
799: }
800: static inline void blk_unfreeze_release_lock(struct request_queue *q)
801: {
802: }
803: #endif
804:
805: /*
806: * debugfs directory and file creation can trigger fs reclaim, which can enter
807: * back into the block layer request_queue. This can cause deadlock if the
808: * queue is frozen. Use NOIO context together with debugfs_mutex to prevent fs
809: * reclaim from triggering block I/O.
]
|
| 349/2 |
2026/11/03 20:48 |
tool |
read-file |
0m
Args: map[File:block/genhd.c FirstLine:680 LineCount:120]
Results: map[Contents: 680: }
681:
682: /**
683: * blk_mark_disk_dead - mark a disk as dead
684: * @disk: disk to mark as dead
685: *
686: * Mark as disk as dead (e.g. surprise removed) and don't accept any new I/O
687: * to this disk.
688: */
689: void blk_mark_disk_dead(struct gendisk *disk)
690: {
691: blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
692: __blk_mark_disk_dead(disk);
693: blk_report_disk_dead(disk, true);
694: }
695: EXPORT_SYMBOL_GPL(blk_mark_disk_dead);
696:
697: static void __del_gendisk(struct gendisk *disk)
698: {
699: struct request_queue *q = disk->queue;
700: struct block_device *part;
701: unsigned long idx;
702: bool start_drain;
703:
704: might_sleep();
705:
706: if (WARN_ON_ONCE(!disk_live(disk) && !(disk->flags & GENHD_FL_HIDDEN)))
707: return;
708:
709: disk_del_events(disk);
710:
711: /*
712: * Prevent new openers by unlinked the bdev inode.
713: */
714: mutex_lock(&disk->open_mutex);
715: xa_for_each(&disk->part_tbl, idx, part)
716: bdev_unhash(part);
717: mutex_unlock(&disk->open_mutex);
718:
719: /*
720: * Tell the file system to write back all dirty data and shut down if
721: * it hasn't been notified earlier.
722: */
723: if (!test_bit(GD_DEAD, &disk->state))
724: blk_report_disk_dead(disk, false);
725:
726: /*
727: * Drop all partitions now that the disk is marked dead.
728: */
729: mutex_lock(&disk->open_mutex);
730: start_drain = __blk_mark_disk_dead(disk);
731: if (start_drain)
732: blk_freeze_acquire_lock(q);
733: xa_for_each_start(&disk->part_tbl, idx, part, 1)
734: drop_partition(part);
735: mutex_unlock(&disk->open_mutex);
736:
737: if (!(disk->flags & GENHD_FL_HIDDEN)) {
738: sysfs_remove_link(&disk_to_dev(disk)->kobj, "bdi");
739:
740: /*
741: * Unregister bdi before releasing device numbers (as they can
742: * get reused and we'd get clashes in sysfs).
743: */
744: bdi_unregister(disk->bdi);
745: }
746:
747: blk_unregister_queue(disk);
748:
749: kobject_put(disk->part0->bd_holder_dir);
750: kobject_put(disk->slave_dir);
751: disk->slave_dir = NULL;
752:
753: part_stat_set_all(disk->part0, 0);
754: disk->part0->bd_stamp = 0;
755: sysfs_remove_link(block_depr, dev_name(disk_to_dev(disk)));
756: pm_runtime_set_memalloc_noio(disk_to_dev(disk), false);
757: device_del(disk_to_dev(disk));
758:
759: blk_mq_freeze_queue_wait(q);
760:
761: blk_throtl_cancel_bios(disk);
762:
763: blk_sync_queue(q);
764: blk_flush_integrity();
765:
766: if (queue_is_mq(q))
767: blk_mq_cancel_work_sync(q);
768:
769: rq_qos_exit(q);
770:
771: /*
772: * If the disk does not own the queue, allow using passthrough requests
773: * again. Else leave the queue frozen to fail all I/O.
774: */
775: if (!test_bit(GD_OWNS_QUEUE, &disk->state))
776: __blk_mq_unfreeze_queue(q, true);
777: else if (queue_is_mq(q))
778: blk_mq_exit_queue(q);
779:
]
|
| 350/2 |
2026/11/03 20:48 |
tool |
read-file |
0m
Args: map[File:block/blk-core.c FirstLine:275 LineCount:45]
Results: map[Contents: 275: void blk_set_pm_only(struct request_queue *q)
276: {
277: atomic_inc(&q->pm_only);
278: }
279: EXPORT_SYMBOL_GPL(blk_set_pm_only);
280:
281: void blk_clear_pm_only(struct request_queue *q)
282: {
283: int pm_only;
284:
285: pm_only = atomic_dec_return(&q->pm_only);
286: WARN_ON_ONCE(pm_only < 0);
287: if (pm_only == 0)
288: wake_up_all(&q->mq_freeze_wq);
289: }
290: EXPORT_SYMBOL_GPL(blk_clear_pm_only);
291:
292: static void blk_free_queue_rcu(struct rcu_head *rcu_head)
293: {
294: struct request_queue *q = container_of(rcu_head,
295: struct request_queue, rcu_head);
296:
297: percpu_ref_exit(&q->q_usage_counter);
298: kmem_cache_free(blk_requestq_cachep, q);
299: }
300:
301: static void blk_free_queue(struct request_queue *q)
302: {
303: blk_free_queue_stats(q->stats);
304: if (queue_is_mq(q))
305: blk_mq_release(q);
306:
307: ida_free(&blk_queue_ida, q->id);
308: lockdep_unregister_key(&q->io_lock_cls_key);
309: lockdep_unregister_key(&q->q_lock_cls_key);
310: call_rcu(&q->rcu_head, blk_free_queue_rcu);
311: }
312:
313: /**
314: * blk_put_queue - decrement the request_queue refcount
315: * @q: the request_queue structure to decrement the refcount for
316: *
317: * Decrements the refcount of the request_queue and free it when the refcount
318: * reaches 0.
319: */
]
|
| 351/2 |
2026/11/03 20:48 |
tool |
read-file |
0m
Args: map[File:drivers/md/dm.c FirstLine:2700 LineCount:90]
Results: map[Contents:2700:
2701: void dm_get(struct mapped_device *md)
2702: {
2703: atomic_inc(&md->holders);
2704: BUG_ON(test_bit(DMF_FREEING, &md->flags));
2705: }
2706:
2707: int dm_hold(struct mapped_device *md)
2708: {
2709: spin_lock(&_minor_lock);
2710: if (test_bit(DMF_FREEING, &md->flags)) {
2711: spin_unlock(&_minor_lock);
2712: return -EBUSY;
2713: }
2714: dm_get(md);
2715: spin_unlock(&_minor_lock);
2716: return 0;
2717: }
2718: EXPORT_SYMBOL_GPL(dm_hold);
2719:
2720: const char *dm_device_name(struct mapped_device *md)
2721: {
2722: return md->name;
2723: }
2724: EXPORT_SYMBOL_GPL(dm_device_name);
2725:
2726: static void __dm_destroy(struct mapped_device *md, bool wait)
2727: {
2728: struct dm_table *map;
2729: int srcu_idx;
2730:
2731: might_sleep();
2732:
2733: spin_lock(&_minor_lock);
2734: idr_replace(&_minor_idr, MINOR_ALLOCED, MINOR(disk_devt(dm_disk(md))));
2735: set_bit(DMF_FREEING, &md->flags);
2736: spin_unlock(&_minor_lock);
2737:
2738: blk_mark_disk_dead(md->disk);
2739:
2740: /*
2741: * Take suspend_lock so that presuspend and postsuspend methods
2742: * do not race with internal suspend.
2743: */
2744: mutex_lock(&md->suspend_lock);
2745: map = dm_get_live_table(md, &srcu_idx);
2746: if (!dm_suspended_md(md)) {
2747: dm_table_presuspend_targets(map);
2748: set_bit(DMF_SUSPENDED, &md->flags);
2749: set_bit(DMF_POST_SUSPENDING, &md->flags);
2750: dm_table_postsuspend_targets(map);
2751: }
2752: /* dm_put_live_table must be before fsleep, otherwise deadlock is possible */
2753: dm_put_live_table(md, srcu_idx);
2754: mutex_unlock(&md->suspend_lock);
2755:
2756: /*
2757: * Rare, but there may be I/O requests still going to complete,
2758: * for example. Wait for all references to disappear.
2759: * No one should increment the reference count of the mapped_device,
2760: * after the mapped_device state becomes DMF_FREEING.
2761: */
2762: if (wait)
2763: while (atomic_read(&md->holders))
2764: fsleep(1000);
2765: else if (atomic_read(&md->holders))
2766: DMWARN("%s: Forcibly removing mapped_device still in use! (%d users)",
2767: dm_device_name(md), atomic_read(&md->holders));
2768:
2769: dm_table_destroy(__unbind(md));
2770: free_dev(md);
2771: }
2772:
2773: void dm_destroy(struct mapped_device *md)
2774: {
2775: __dm_destroy(md, true);
2776: }
2777:
2778: void dm_destroy_immediate(struct mapped_device *md)
2779: {
2780: __dm_destroy(md, false);
2781: }
2782:
2783: void dm_put(struct mapped_device *md)
2784: {
2785: atomic_dec(&md->holders);
2786: }
2787: EXPORT_SYMBOL_GPL(dm_put);
2788:
2789: static bool dm_in_flight_bios(struct mapped_device *md)
]
|
| 352/2 |
2026/11/03 20:48 |
tool |
read-file |
0m
Args: map[File:drivers/md/dm-ioctl.c FirstLine:1050 LineCount:50]
Results: map[Contents:1050: {
1051: struct hash_cell *hc;
1052: struct mapped_device *md = NULL;
1053:
1054: down_read(&_hash_lock);
1055: hc = __find_device_hash_cell(param);
1056: if (hc)
1057: md = hc->md;
1058: up_read(&_hash_lock);
1059:
1060: return md;
1061: }
1062:
1063: static int dev_remove(struct file *filp, struct dm_ioctl *param, size_t param_size)
1064: {
1065: struct hash_cell *hc;
1066: struct mapped_device *md;
1067: int r;
1068: struct dm_table *t;
1069: struct dm_ima_context *ima_context = NULL;
1070: unsigned int ima_idx;
1071:
1072: dm_ima_alloc_context(&ima_context, true);
1073: down_write(&_hash_lock);
1074: hc = __find_device_hash_cell(param);
1075:
1076: if (!hc) {
1077: DMDEBUG_LIMIT("device doesn't appear to be in the dev hash table.");
1078: up_write(&_hash_lock);
1079: dm_ima_free_context(ima_context);
1080: return -ENXIO;
1081: }
1082:
1083: md = hc->md;
1084:
1085: /*
1086: * Ensure the device is not open and nothing further can open it.
1087: */
1088: r = dm_lock_for_deletion(md, !!(param->flags & DM_DEFERRED_REMOVE), false);
1089: if (r) {
1090: if (r == -EBUSY && param->flags & DM_DEFERRED_REMOVE) {
1091: up_write(&_hash_lock);
1092: dm_put(md);
1093: dm_ima_free_context(ima_context);
1094: return 0;
1095: }
1096: DMDEBUG_LIMIT("unable to remove open device %s", hc->name);
1097: up_write(&_hash_lock);
1098: dm_put(md);
1099: dm_ima_free_context(ima_context);
]
|
| 353/2 |
2026/11/03 20:48 |
tool |
read-file |
0m
Args: map[File:drivers/md/dm-ioctl.c FirstLine:1620 LineCount:90]
Results: map[Contents:1620: (cur == DM_TYPE_BIO_BASED && new == DM_TYPE_DAX_BIO_BASED))
1621: return true;
1622:
1623: return false;
1624: }
1625:
1626: static int table_load(struct file *filp, struct dm_ioctl *param, size_t param_size)
1627: {
1628: int r, srcu_idx;
1629: struct hash_cell *hc;
1630: struct dm_table *t, *old_map = NULL;
1631: struct mapped_device *md;
1632: struct target_type *immutable_target_type;
1633: struct dm_ima_context *ima_context = NULL;
1634:
1635: md = find_device(param);
1636: if (!md)
1637: return -ENXIO;
1638:
1639: r = dm_table_create(&t, get_mode(param), param->target_count, md);
1640: if (r)
1641: goto err;
1642:
1643: /* Protect md->type and md->queue against concurrent table loads. */
1644: dm_lock_md_type(md);
1645: r = populate_table(t, param, param_size);
1646: if (r)
1647: goto err_unlock_md_type;
1648:
1649: immutable_target_type = dm_get_immutable_target_type(md);
1650: if (immutable_target_type &&
1651: (immutable_target_type != dm_table_get_immutable_target_type(t)) &&
1652: !dm_table_get_wildcard_target(t)) {
1653: DMERR("can't replace immutable target type %s",
1654: immutable_target_type->name);
1655: r = -EINVAL;
1656: goto err_unlock_md_type;
1657: }
1658:
1659: if (dm_get_md_type(md) == DM_TYPE_NONE) {
1660: /* setup md->queue to reflect md's type (may block) */
1661: r = dm_setup_md_queue(md, t);
1662: if (r) {
1663: DMERR("unable to set up device queue for new table.");
1664: goto err_unlock_md_type;
1665: }
1666: } else if (!is_valid_type(dm_get_md_type(md), dm_table_get_type(t))) {
1667: DMERR("can't change device type (old=%u vs new=%u) after initial table load.",
1668: dm_get_md_type(md), dm_table_get_type(t));
1669: r = -EINVAL;
1670: goto err_unlock_md_type;
1671: }
1672:
1673: dm_unlock_md_type(md);
1674:
1675: dm_ima_alloc_context(&ima_context, false);
1676: /* stage inactive table */
1677: down_write(&_hash_lock);
1678: hc = dm_get_mdptr(md);
1679: if (!hc) {
1680: DMERR("device has been removed from the dev hash table.");
1681: up_write(&_hash_lock);
1682: dm_ima_free_context(ima_context);
1683: r = -ENXIO;
1684: goto err_destroy_table;
1685: }
1686:
1687: if (hc->new_map)
1688: old_map = hc->new_map;
1689: hc->new_map = t;
1690: dm_ima_init_context(hc, ima_context, false);
1691: /* Make sure new_map doesn't get freed before we measure it*/
1692: dm_get_live_table(md, &srcu_idx);
1693: up_write(&_hash_lock);
1694:
1695: dm_ima_measure_on_table_load(t, ima_context);
1696: dm_ima_free_context(ima_context);
1697: dm_put_live_table(md, srcu_idx);
1698:
1699: param->flags |= DM_INACTIVE_PRESENT_FLAG;
1700: __dev_status(md, param);
1701:
1702: if (old_map) {
1703: dm_sync_table(md);
1704: dm_table_destroy(old_map);
1705: }
1706:
1707: dm_put(md);
1708:
1709: return 0;
]
|
| 354/2 |
2026/11/03 20:48 |
llm |
patch-planner |
0m
Model:
Tokens:
input: 30228
output: 229
thoughts: 73
Thoughts: Here's my summary, as the expert:
**Investigating Potential Queue Drainage Issues**
Okay, so I need to dig into the block layer code to understand what's happening with this queue drainage issue. My focus is going to be on a few key areas to start. I'm going to jump into `block/blk-mq.c` around lines 210 to 280; that section likely deals with the basic multi-queue interactions and might reveal something about how requests are being handled before a drainage event is triggered. Next, I'm going to switch gears and examine `block/genhd.c` around lines 650-800. I suspect this will be interesting given this area often focuses on generic disk header and queue handling, and perhaps there are some interactions going on that I'm missing. Lastly, and perhaps most importantly, I'll be looking at `block/blk-core.c` around the `blk_queue_start_drain` function. Thatβs the most likely place where the root cause lies. I'm reading these to see exactly what's happening and figure out what might be leading to this observed behavior.
|
| 355/2 |
2026/11/03 20:48 |
tool |
read-file |
0m
Args: map[File:block/blk-mq.c FirstLine:210 LineCount:70]
Results: map[Contents: 210:
211: bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
212: {
213: bool unfreeze;
214:
215: mutex_lock(&q->mq_freeze_lock);
216: if (force_atomic)
217: q->q_usage_counter.data->force_atomic = true;
218: q->mq_freeze_depth--;
219: WARN_ON_ONCE(q->mq_freeze_depth < 0);
220: if (!q->mq_freeze_depth) {
221: percpu_ref_resurrect(&q->q_usage_counter);
222: wake_up_all(&q->mq_freeze_wq);
223: }
224: unfreeze = blk_unfreeze_check_owner(q);
225: mutex_unlock(&q->mq_freeze_lock);
226:
227: return unfreeze;
228: }
229:
230: void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
231: {
232: if (__blk_mq_unfreeze_queue(q, false))
233: blk_unfreeze_release_lock(q);
234: }
235: EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_nomemrestore);
236:
237: /*
238: * non_owner variant of blk_freeze_queue_start
239: *
240: * Unlike blk_freeze_queue_start, the queue doesn't need to be unfrozen
241: * by the same task. This is fragile and should not be used if at all
242: * possible.
243: */
244: void blk_freeze_queue_start_non_owner(struct request_queue *q)
245: {
246: __blk_freeze_queue_start(q, NULL);
247: }
248: EXPORT_SYMBOL_GPL(blk_freeze_queue_start_non_owner);
249:
250: /* non_owner variant of blk_mq_unfreeze_queue */
251: void blk_mq_unfreeze_queue_non_owner(struct request_queue *q)
252: {
253: __blk_mq_unfreeze_queue(q, false);
254: }
255: EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_non_owner);
256:
257: /*
258: * FIXME: replace the scsi_internal_device_*block_nowait() calls in the
259: * mpt3sas driver such that this function can be removed.
260: */
261: void blk_mq_quiesce_queue_nowait(struct request_queue *q)
262: {
263: unsigned long flags;
264:
265: spin_lock_irqsave(&q->queue_lock, flags);
266: if (!q->quiesce_depth++)
267: blk_queue_flag_set(QUEUE_FLAG_QUIESCED, q);
268: spin_unlock_irqrestore(&q->queue_lock, flags);
269: }
270: EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue_nowait);
271:
272: /**
273: * blk_mq_wait_quiesce_done() - wait until in-progress quiesce is done
274: * @set: tag_set to wait on
275: *
276: * Note: it is driver's responsibility for making sure that quiesce has
277: * been started on or more of the request_queues of the tag_set. This
278: * function only waits for the quiesce on those request_queues that had
279: * the quiesce flag set using blk_mq_quiesce_queue_nowait.
]
|
| 356/2 |
2026/11/03 20:48 |
tool |
read-file |
0m
Args: map[File:block/genhd.c FirstLine:640 LineCount:160]
Results: map[Contents: 640: * On surprise disk removal, bdev_mark_dead() may call into file
641: * systems below. Make it clear that we're expecting to not hold
642: * disk->open_mutex.
643: */
644: lockdep_assert_not_held(&disk->open_mutex);
645:
646: rcu_read_lock();
647: xa_for_each(&disk->part_tbl, idx, bdev) {
648: if (!kobject_get_unless_zero(&bdev->bd_device.kobj))
649: continue;
650: rcu_read_unlock();
651:
652: bdev_mark_dead(bdev, surprise);
653:
654: put_device(&bdev->bd_device);
655: rcu_read_lock();
656: }
657: rcu_read_unlock();
658: }
659:
660: static bool __blk_mark_disk_dead(struct gendisk *disk)
661: {
662: /*
663: * Fail any new I/O.
664: */
665: if (test_and_set_bit(GD_DEAD, &disk->state))
666: return false;
667:
668: if (test_bit(GD_OWNS_QUEUE, &disk->state))
669: blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
670:
671: /*
672: * Stop buffered writers from dirtying pages that can't be written out.
673: */
674: set_capacity(disk, 0);
675:
676: /*
677: * Prevent new I/O from crossing bio_queue_enter().
678: */
679: return blk_queue_start_drain(disk->queue);
680: }
681:
682: /**
683: * blk_mark_disk_dead - mark a disk as dead
684: * @disk: disk to mark as dead
685: *
686: * Mark as disk as dead (e.g. surprise removed) and don't accept any new I/O
687: * to this disk.
688: */
689: void blk_mark_disk_dead(struct gendisk *disk)
690: {
691: blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
692: __blk_mark_disk_dead(disk);
693: blk_report_disk_dead(disk, true);
694: }
695: EXPORT_SYMBOL_GPL(blk_mark_disk_dead);
696:
697: static void __del_gendisk(struct gendisk *disk)
698: {
699: struct request_queue *q = disk->queue;
700: struct block_device *part;
701: unsigned long idx;
702: bool start_drain;
703:
704: might_sleep();
705:
706: if (WARN_ON_ONCE(!disk_live(disk) && !(disk->flags & GENHD_FL_HIDDEN)))
707: return;
708:
709: disk_del_events(disk);
710:
711: /*
712: * Prevent new openers by unlinked the bdev inode.
713: */
714: mutex_lock(&disk->open_mutex);
715: xa_for_each(&disk->part_tbl, idx, part)
716: bdev_unhash(part);
717: mutex_unlock(&disk->open_mutex);
718:
719: /*
720: * Tell the file system to write back all dirty data and shut down if
721: * it hasn't been notified earlier.
722: */
723: if (!test_bit(GD_DEAD, &disk->state))
724: blk_report_disk_dead(disk, false);
725:
726: /*
727: * Drop all partitions now that the disk is marked dead.
728: */
729: mutex_lock(&disk->open_mutex);
730: start_drain = __blk_mark_disk_dead(disk);
731: if (start_drain)
732: blk_freeze_acquire_lock(q);
733: xa_for_each_start(&disk->part_tbl, idx, part, 1)
734: drop_partition(part);
735: mutex_unlock(&disk->open_mutex);
736:
737: if (!(disk->flags & GENHD_FL_HIDDEN)) {
738: sysfs_remove_link(&disk_to_dev(disk)->kobj, "bdi");
739:
]
|
| 357/2 |
2026/11/03 20:48 |
tool |
read-file |
0m
Args: map[File:block/blk-core.c FirstLine:240 LineCount:50]
Results: map[Contents: 240: * Return BLK_STS_OK for mismatches as this function is intended to
241: * parse error status values.
242: */
243: return BLK_STS_OK;
244: }
245:
246: /**
247: * blk_sync_queue - cancel any pending callbacks on a queue
248: * @q: the queue
249: *
250: * Description:
251: * The block layer may perform asynchronous callback activity
252: * on a queue, such as calling the unplug function after a timeout.
253: * A block device may call blk_sync_queue to ensure that any
254: * such activity is cancelled, thus allowing it to release resources
255: * that the callbacks might use. The caller must already have made sure
256: * that its ->submit_bio will not re-add plugging prior to calling
257: * this function.
258: *
259: * This function does not cancel any asynchronous activity arising
260: * out of elevator or throttling code. That would require elevator_exit()
261: * and blkcg_exit_queue() to be called with queue lock initialized.
262: *
263: */
264: void blk_sync_queue(struct request_queue *q)
265: {
266: timer_delete_sync(&q->timeout);
267: cancel_work_sync(&q->timeout_work);
268: }
269: EXPORT_SYMBOL(blk_sync_queue);
270:
271: /**
272: * blk_set_pm_only - increment pm_only counter
273: * @q: request queue pointer
274: */
275: void blk_set_pm_only(struct request_queue *q)
276: {
277: atomic_inc(&q->pm_only);
278: }
279: EXPORT_SYMBOL_GPL(blk_set_pm_only);
280:
281: void blk_clear_pm_only(struct request_queue *q)
282: {
283: int pm_only;
284:
285: pm_only = atomic_dec_return(&q->pm_only);
286: WARN_ON_ONCE(pm_only < 0);
287: if (pm_only == 0)
288: wake_up_all(&q->mq_freeze_wq);
289: }
]
|
| 358/2 |
2026/11/03 20:49 |
tool |
read-file |
0m
Args: map[File:include/linux/blkdev.h FirstLine:560 LineCount:50]
Results: map[Contents: 560: */
561: int id;
562:
563: /*
564: * queue settings
565: */
566: unsigned int nr_requests; /* Max # of requests */
567: unsigned int async_depth; /* Max # of async requests */
568:
569: #ifdef CONFIG_BLK_INLINE_ENCRYPTION
570: struct blk_crypto_profile *crypto_profile;
571: struct kobject *crypto_kobject;
572: #endif
573:
574: struct timer_list timeout;
575: struct work_struct timeout_work;
576:
577: atomic_t nr_active_requests_shared_tags;
578:
579: struct blk_mq_tags *sched_shared_tags;
580:
581: struct list_head icq_list;
582: #ifdef CONFIG_BLK_CGROUP
583: DECLARE_BITMAP (blkcg_pols, BLKCG_MAX_POLS);
584: struct blkcg_gq *root_blkg;
585: struct list_head blkg_list;
586: struct mutex blkcg_mutex;
587: #endif
588:
589: int node;
590:
591: spinlock_t requeue_lock;
592: struct list_head requeue_list;
593: struct delayed_work requeue_work;
594:
595: #ifdef CONFIG_BLK_DEV_IO_TRACE
596: struct blk_trace __rcu *blk_trace;
597: #endif
598: /*
599: * for flush operations
600: */
601: struct blk_flush_queue *fq;
602: struct list_head flush_list;
603:
604: /*
605: * Protects against I/O scheduler switching, particularly when updating
606: * q->elevator. Since the elevator update code path may also modify q->
607: * nr_requests and wbt latency, this lock also protects the sysfs attrs
608: * nr_requests and wbt_lat_usec. Additionally the nr_hw_queues update
609: * may modify hctx tags, reserved-tags and cpumask, so this lock also
]
|
| 359/2 |
2026/11/03 20:49 |
tool |
git-log |
0m
Error:
Args: map[Count:20 PathPrefix:block/ SymbolName:blk_freeze_set_owner]
Results:
|
| 360/2 |
2026/11/03 20:49 |
tool |
git-log |
0m
Args: map[Count:20 MessageRegexps:[lockdep freeze] PathPrefix:block/]
Results: map[Output:3dd63dba8f9c block: avoid potential deadlock on zone revalidation failure
539d1b47e935 block: break pcpu_alloc_mutex dependency on freeze_lock
d4c3ef56a161 block: define alloc_sched_data and free_sched_data methods for kyber
61019afdf6ac block: introduce alloc_sched_data and free_sched_data elevator methods
5d726c4dbeed blk-cgroup: fix possible deadlock while configuring policy
370ac285f23a block: avoid cpu_hotplug_lock depedency on freeze_lock
2d82f3bd8910 blk-mq: fix lockdep warning in __blk_mq_update_nr_hw_queues
04225d13aef1 block: fix potential deadlock while running nr_hw_queue update
f5a6604f7a44 block: fix lockdep warning caused by lock dependency in elv_iosched_store
2d8951aee844 block: unfreeze queue if realloc tag set fails during nr_hw_queues update
7ed7fa561c35 block: move hctx cpuhp add/del out of queue freezing
01b91bf14f6d block: don't grab elevator lock during queue initialization
9730763f4756 block: correct locking order for protecting blk-wbt parameters
ffa1e7ada456 block: Make request_queue lockdep splats show up earlier
1bf70d08cc3b block: introduce a dedicated lock for protecting queue elevator updates
f6661b1d0525 block: track queue dying state automatically for modeling queue freeze lockdep
6f491a8d4b92 block: track disk DEAD state automatically for modeling queue freeze lockdep
be26ba96421a block: Fix potential deadlock while freezing queue and acquiring sysfs_lock
0b83c86b444a block: Prevent potential deadlock in blk_revalidate_disk_zones()
357e1b7f730b block: don't verify IO lock for freeze/unfreeze in elevator_init_mq()
]
|
| 361/2 |
2026/11/03 20:49 |
llm |
patch-planner |
0m
Model:
Tokens:
input: 35188
output: 217
thoughts: 60
Thoughts: Here's my summary, as though I'm thinking through this process:
**Diving into Block Device Freeze/Drain Operations**
Alright, let's get down to brass tacks. I need to understand this block device freezing and draining logic more thoroughly. My initial plan is to drill down into the kernel code directly. I'll start by examining `include/linux/blkdev.h`. This header file should give me a solid overview of the relevant data structures and function prototypes related to freezing and unfreezing block device queues. Then, I'll move to the implementation details in `block/blk-core.c`. This is where the real meat of the operation should reside, the actual freezing and unfreezing routines. I need to get a clear picture of how these primitives interact with the rest of the block layer.
I'm particularly interested in how these routines relate to the request queue, so the next stage is to track down all the usages. I'll need to meticulously check all references to `__blk_freeze_queue_start`, `__blk_mq_unfreeze_queue`, and `blk_queue_start_drain`. Cross-referencing these functions will help me understand their roles in the whole block device stack, and how these functions affect block queue states, as well as the conditions that trigger the usage of these functions. I need to map out the call paths and analyze the conditions under which these calls happen. This should give me the fine-grained understanding I need to debug, optimize, or modify this part of the block layer.
|
| 362/2 |
2026/11/03 20:49 |
tool |
read-file |
0m
Args: map[File:include/linux/blkdev.h FirstLine:610 LineCount:60]
Results: map[Contents: 610: * helps protect the hctx sysfs/debugfs attrs. To ensure proper locking
611: * order during an elevator or nr_hw_queue update, first freeze the
612: * queue, then acquire ->elevator_lock.
613: */
614: struct mutex elevator_lock;
615:
616: struct mutex sysfs_lock;
617: /*
618: * Protects queue limits and also sysfs attribute read_ahead_kb.
619: */
620: struct mutex limits_lock;
621:
622: /*
623: * for reusing dead hctx instance in case of updating
624: * nr_hw_queues
625: */
626: struct list_head unused_hctx_list;
627: spinlock_t unused_hctx_lock;
628:
629: int mq_freeze_depth;
630:
631: #ifdef CONFIG_BLK_DEV_THROTTLING
632: /* Throttle data */
633: struct throtl_data *td;
634: #endif
635: struct rcu_head rcu_head;
636: #ifdef CONFIG_LOCKDEP
637: struct task_struct *mq_freeze_owner;
638: int mq_freeze_owner_depth;
639: /*
640: * Records disk & queue state in current context, used in unfreeze
641: * queue
642: */
643: bool mq_freeze_disk_dead;
644: bool mq_freeze_queue_dying;
645: #endif
646: wait_queue_head_t mq_freeze_wq;
647: /*
648: * Protect concurrent access to q_usage_counter by
649: * percpu_ref_kill() and percpu_ref_reinit().
650: */
651: struct mutex mq_freeze_lock;
652:
653: struct blk_mq_tag_set *tag_set;
654: struct list_head tag_set_list;
655:
656: struct dentry *debugfs_dir;
657: struct dentry *sched_debugfs_dir;
658: struct dentry *rqos_debugfs_dir;
659: /*
660: * Serializes all debugfs metadata operations using the above dentries.
661: */
662: struct mutex debugfs_mutex;
663: };
664:
665: /* Keep blk_queue_flag_name[] in sync with the definitions below */
666: enum {
667: QUEUE_FLAG_DYING, /* queue being torn down */
668: QUEUE_FLAG_NOMERGES, /* disable merge attempts */
669: QUEUE_FLAG_SAME_COMP, /* complete on same CPU-group */
]
|
| 363/2 |
2026/11/03 20:49 |
tool |
codesearch-find-references |
0m
Args: map[Name:__blk_freeze_queue_start]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_freeze_queue_start SourceFile:block/blk-mq.c SourceLine:184] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_freeze_queue_start_non_owner SourceFile:block/blk-mq.c SourceLine:246] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_queue_start_drain SourceFile:block/blk-core.c SourceLine:334]] TruncatedOutput:false]
|
| 364/2 |
2026/11/03 20:49 |
tool |
codesearch-find-references |
0m
Args: map[Name:__blk_mq_unfreeze_queue]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__del_gendisk SourceFile:block/genhd.c SourceLine:776] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_mq_unfreeze_queue_nomemrestore SourceFile:block/blk-mq.c SourceLine:232] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_mq_unfreeze_queue_non_owner SourceFile:block/blk-mq.c SourceLine:253]] TruncatedOutput:false]
|
| 365/2 |
2026/11/03 20:49 |
tool |
codesearch-find-references |
0m
Args: map[Name:blk_queue_start_drain]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__blk_mark_disk_dead SourceFile:block/genhd.c SourceLine:679] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_mq_destroy_queue SourceFile:block/blk-mq.c SourceLine:4491]] TruncatedOutput:false]
|
| 366/2 |
2026/11/03 20:49 |
tool |
codesearch-find-references |
0m
Args: map[Name:__blk_mark_disk_dead]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__del_gendisk SourceFile:block/genhd.c SourceLine:730] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_mark_disk_dead SourceFile:block/genhd.c SourceLine:692]] TruncatedOutput:false]
|
| 367/2 |
2026/11/03 20:49 |
tool |
codesearch-find-references |
0m
Args: map[Name:blk_mark_disk_dead]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__dm_destroy SourceFile:drivers/md/dm.c SourceLine:2738] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:nvme_mark_namespaces_dead SourceFile:drivers/nvme/host/core.c SourceLine:5354] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:sd_remove SourceFile:drivers/scsi/sd.c SourceLine:4279] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__UNIQUE_ID_addressable_blk_mark_disk_dead_1047 SourceFile:block/genhd.c SourceLine:695] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__gendwarfksyms_ptr_blk_mark_disk_dead SourceFile:block/genhd.c SourceLine:695] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__gendwarfksyms_ptr_blk_mark_disk_dead SourceFile:block/genhd.c SourceLine:695]] TruncatedOutput:false]
|
| 368/2 |
2026/11/03 20:49 |
tool |
read-file |
0m
Args: map[File:block/genhd.c FirstLine:770 LineCount:35]
Results: map[Contents: 770:
771: /*
772: * If the disk does not own the queue, allow using passthrough requests
773: * again. Else leave the queue frozen to fail all I/O.
774: */
775: if (!test_bit(GD_OWNS_QUEUE, &disk->state))
776: __blk_mq_unfreeze_queue(q, true);
777: else if (queue_is_mq(q))
778: blk_mq_exit_queue(q);
779:
780: if (start_drain)
781: blk_unfreeze_release_lock(q);
782: }
783:
784: static void disable_elv_switch(struct request_queue *q)
785: {
786: struct blk_mq_tag_set *set = q->tag_set;
787: WARN_ON_ONCE(!queue_is_mq(q));
788:
789: down_write(&set->update_nr_hwq_lock);
790: blk_queue_flag_set(QUEUE_FLAG_NO_ELV_SWITCH, q);
791: up_write(&set->update_nr_hwq_lock);
792: }
793:
794: /**
795: * del_gendisk - remove the gendisk
796: * @disk: the struct gendisk to remove
797: *
798: * Removes the gendisk and all its associated resources. This deletes the
799: * partitions associated with the gendisk, and unregisters the associated
800: * request_queue.
801: *
802: * This is the counter to the respective device_add_disk() call.
803: *
804: * The final removal of the struct gendisk happens when its refcount reaches 0
]
|
| 369/2 |
2026/11/03 20:49 |
llm |
patch-planner |
0m
Model:
Tokens:
input: 37888
output: 136
thoughts: 65
Thoughts: Here's my take on those lines of code, focusing on what I find important:
**Diving into Block Device Drain and Queue Destruction**
Okay, so I want to get a clearer picture of how block devices are drained and their queues are ultimately destroyed in the kernel, specifically with regard to `blk_queue_start_drain` and `blk_mq_destroy_queue`. Let's hit the source code. I need to refresh my memory on the interactions here, so I'm going to head directly to `block/blk-core.c`, looking at lines 315-360, and then I'll jump over to `block/blk-mq.c` and check out lines 4480-4510.
I'm expecting to see the core logic around initiating a drain operation within the traditional block layer (if applicable) and how that might differ or interact with the multi-queue (blk-mq) implementation. I'll be looking for synchronization primitives, state transitions, and the overall sequence of events. Specifically, I'm interested in how these routines handle outstanding requests, flush caches, and prevent race conditions during the final stages of the device's lifetime. I'm also hoping to see the exact relationship and responsibilities of these functions, if any.
|
| 370/2 |
2026/11/03 20:49 |
tool |
read-file |
0m
Args: map[File:block/blk-core.c FirstLine:315 LineCount:50]
Results: map[Contents: 315: * @q: the request_queue structure to decrement the refcount for
316: *
317: * Decrements the refcount of the request_queue and free it when the refcount
318: * reaches 0.
319: */
320: void blk_put_queue(struct request_queue *q)
321: {
322: if (refcount_dec_and_test(&q->refs))
323: blk_free_queue(q);
324: }
325: EXPORT_SYMBOL(blk_put_queue);
326:
327: bool blk_queue_start_drain(struct request_queue *q)
328: {
329: /*
330: * When queue DYING flag is set, we need to block new req
331: * entering queue, so we call blk_freeze_queue_start() to
332: * prevent I/O from crossing blk_queue_enter().
333: */
334: bool freeze = __blk_freeze_queue_start(q, current);
335: if (queue_is_mq(q))
336: blk_mq_wake_waiters(q);
337: /* Make blk_queue_enter() reexamine the DYING flag. */
338: wake_up_all(&q->mq_freeze_wq);
339:
340: return freeze;
341: }
342:
343: /**
344: * blk_queue_enter() - try to increase q->q_usage_counter
345: * @q: request queue pointer
346: * @flags: BLK_MQ_REQ_NOWAIT and/or BLK_MQ_REQ_PM
347: */
348: int blk_queue_enter(struct request_queue *q, blk_mq_req_flags_t flags)
349: {
350: const bool pm = flags & BLK_MQ_REQ_PM;
351:
352: while (!blk_try_enter_queue(q, pm)) {
353: if (flags & BLK_MQ_REQ_NOWAIT)
354: return -EAGAIN;
355:
356: /*
357: * read pair of barrier in blk_freeze_queue_start(), we need to
358: * order reading __PERCPU_REF_DEAD flag of .q_usage_counter and
359: * reading .mq_freeze_depth or queue dying flag, otherwise the
360: * following wait may never return if the two reads are
361: * reordered.
362: */
363: smp_rmb();
364: wait_event(q->mq_freeze_wq,
]
|
| 371/2 |
2026/11/03 20:49 |
tool |
read-file |
0m
Args: map[File:block/blk-mq.c FirstLine:4480 LineCount:40]
Results: map[Contents:4480: *
4481: * Context: can sleep
4482: */
4483: void blk_mq_destroy_queue(struct request_queue *q)
4484: {
4485: WARN_ON_ONCE(!queue_is_mq(q));
4486: WARN_ON_ONCE(blk_queue_registered(q));
4487:
4488: might_sleep();
4489:
4490: blk_queue_flag_set(QUEUE_FLAG_DYING, q);
4491: blk_queue_start_drain(q);
4492: blk_mq_freeze_queue_wait(q);
4493:
4494: blk_sync_queue(q);
4495: blk_mq_cancel_work_sync(q);
4496: blk_mq_exit_queue(q);
4497: }
4498: EXPORT_SYMBOL(blk_mq_destroy_queue);
4499:
4500: struct gendisk *__blk_mq_alloc_disk(struct blk_mq_tag_set *set,
4501: struct queue_limits *lim, void *queuedata,
4502: struct lock_class_key *lkclass)
4503: {
4504: struct request_queue *q;
4505: struct gendisk *disk;
4506:
4507: q = blk_mq_alloc_queue(set, lim, queuedata);
4508: if (IS_ERR(q))
4509: return ERR_CAST(q);
4510:
4511: disk = __alloc_disk_node(q, set->numa_node, lkclass);
4512: if (!disk) {
4513: blk_mq_destroy_queue(q);
4514: blk_put_queue(q);
4515: return ERR_PTR(-ENOMEM);
4516: }
4517: set_bit(GD_OWNS_QUEUE, &disk->state);
4518: return disk;
4519: }
]
|
| 372/2 |
2026/11/03 20:49 |
tool |
git-show |
0m
Args:
Results: map[Output:commit f1be1788a32e8fa63416ad4518bbd1a85a825c9d
Author: Ming Lei <ming.lei@redhat.com>
Date: Fri Oct 25 08:37:20 2024 +0800
block: model freeze & enter queue as lock for supporting lockdep
Recently we got several deadlock report[1][2][3] caused by
blk_mq_freeze_queue and blk_enter_queue().
Turns out the two are just like acquiring read/write lock, so model them
as read/write lock for supporting lockdep:
1) model q->q_usage_counter as two locks(io and queue lock)
- queue lock covers sync with blk_enter_queue()
- io lock covers sync with bio_enter_queue()
2) make the lockdep class/key as per-queue:
- different subsystem has very different lock use pattern, shared lock
class causes false positive easily
- freeze_queue degrades to no lock in case that disk state becomes DEAD
because bio_enter_queue() won't be blocked any more
- freeze_queue degrades to no lock in case that request queue becomes dying
because blk_enter_queue() won't be blocked any more
3) model blk_mq_freeze_queue() as acquire_exclusive & try_lock
- it is exclusive lock, so dependency with blk_enter_queue() is covered
- it is trylock because blk_mq_freeze_queue() are allowed to run
concurrently
4) model blk_enter_queue() & bio_enter_queue() as acquire_read()
- nested blk_enter_queue() are allowed
- dependency with blk_mq_freeze_queue() is covered
- blk_queue_exit() is often called from other contexts(such as irq), and
it can't be annotated as lock_release(), so simply do it in
blk_enter_queue(), this way still covered cases as many as possible
With lockdep support, such kind of reports may be reported asap and
needn't wait until the real deadlock is triggered.
For example, lockdep report can be triggered in the report[3] with this
patch applied.
[1] occasional block layer hang when setting 'echo noop > /sys/block/sda/queue/scheduler'
https://bugzilla.kernel.org/show_bug.cgi?id=219166
[2] del_gendisk() vs blk_queue_enter() race condition
https://lore.kernel.org/linux-block/20241003085610.GK11458@google.com/
[3] queue_freeze & queue_enter deadlock in scsi
https://lore.kernel.org/linux-block/ZxG38G9BuFdBpBHZ@fedora/T/#u
Reviewed-by: Christoph Hellwig <hch@lst.de>
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241025003722.3630252-4-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-core.c b/block/blk-core.c
index bc5e8c5eaac9..09d10bb95fda 100644
--- a/block/blk-core.c
+++ b/block/blk-core.c
@@ -261,6 +261,8 @@ static void blk_free_queue(struct request_queue *q)
blk_mq_release(q);
ida_free(&blk_queue_ida, q->id);
+ lockdep_unregister_key(&q->io_lock_cls_key);
+ lockdep_unregister_key(&q->q_lock_cls_key);
call_rcu(&q->rcu_head, blk_free_queue_rcu);
}
@@ -278,18 +280,20 @@ void blk_put_queue(struct request_queue *q)
}
EXPORT_SYMBOL(blk_put_queue);
-void blk_queue_start_drain(struct request_queue *q)
+bool blk_queue_start_drain(struct request_queue *q)
{
/*
* When queue DYING flag is set, we need to block new req
* entering queue, so we call blk_freeze_queue_start() to
* prevent I/O from crossing blk_queue_enter().
*/
- blk_freeze_queue_start(q);
+ bool freeze = __blk_freeze_queue_start(q);
if (queue_is_mq(q))
blk_mq_wake_waiters(q);
/* Make blk_queue_enter() reexamine the DYING flag. */
wake_up_all(&q->mq_freeze_wq);
+
+ return freeze;
}
/**
@@ -321,6 +325,8 @@ int blk_queue_enter(struct request_queue *q, blk_mq_req_flags_t flags)
return -ENODEV;
}
+ rwsem_acquire_read(&q->q_lockdep_map, 0, 0, _RET_IP_);
+ rwsem_release(&q->q_lockdep_map, _RET_IP_);
return 0;
}
@@ -352,6 +358,8 @@ int __bio_queue_enter(struct request_queue *q, struct bio *bio)
goto dead;
}
+ rwsem_acquire_read(&q->io_lockdep_map, 0, 0, _RET_IP_);
+ rwsem_release(&q->io_lockdep_map, _RET_IP_);
return 0;
dead:
bio_io_error(bio);
@@ -441,6 +449,12 @@ struct request_queue *blk_alloc_queue(struct queue_limits *lim, int node_id)
PERCPU_REF_INIT_ATOMIC, GFP_KERNEL);
if (error)
goto fail_stats;
+ lockdep_register_key(&q->io_lock_cls_key);
+ lockdep_register_key(&q->q_lock_cls_key);
+ lockdep_init_map(&q->io_lockdep_map, "&q->q_usage_counter(io)",
+ &q->io_lock_cls_key, 0);
+ lockdep_init_map(&q->q_lockdep_map, "&q->q_usage_counter(queue)",
+ &q->q_lock_cls_key, 0);
q->nr_requests = BLKDEV_DEFAULT_RQ;
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 770276815507..4ae7eb335fbd 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -120,17 +120,29 @@ void blk_mq_in_flight_rw(struct request_queue *q, struct block_device *part,
inflight[1] = mi.inflight[1];
}
-void blk_freeze_queue_start(struct request_queue *q)
+bool __blk_freeze_queue_start(struct request_queue *q)
{
+ int freeze;
+
mutex_lock(&q->mq_freeze_lock);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
if (queue_is_mq(q))
blk_mq_run_hw_queues(q, false);
+ freeze = true;
} else {
mutex_unlock(&q->mq_freeze_lock);
+ freeze = false;
}
+
+ return freeze;
+}
+
+void blk_freeze_queue_start(struct request_queue *q)
+{
+ if (__blk_freeze_queue_start(q))
+ blk_freeze_acquire_lock(q, false, false);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -176,8 +188,10 @@ void blk_mq_freeze_queue(struct request_queue *q)
}
EXPORT_SYMBOL_GPL(blk_mq_freeze_queue);
-void __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
+bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
+ int unfreeze = false;
+
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
q->q_usage_counter.data->force_atomic = true;
@@ -186,13 +200,17 @@ void __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
if (!q->mq_freeze_depth) {
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
+ unfreeze = true;
}
mutex_unlock(&q->mq_freeze_lock);
+
+ return unfreeze;
}
void blk_mq_unfreeze_queue(struct request_queue *q)
{
- __blk_mq_unfreeze_queue(q, false);
+ if (__blk_mq_unfreeze_queue(q, false))
+ blk_unfreeze_release_lock(q, false, false);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
@@ -205,7 +223,7 @@ EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
*/
void blk_freeze_queue_start_non_owner(struct request_queue *q)
{
- blk_freeze_queue_start(q);
+ __blk_freeze_queue_start(q);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start_non_owner);
diff --git a/block/blk.h b/block/blk.h
index 8fddaf6eae49..63d5df0dc29c 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -4,6 +4,7 @@
#include <linux/bio-integrity.h>
#include <linux/blk-crypto.h>
+#include <linux/lockdep.h>
#include <linux/memblock.h> /* for max_pfn/max_low_pfn */
#include <linux/sched/sysctl.h>
#include <linux/timekeeping.h>
@@ -35,8 +36,9 @@ struct blk_flush_queue *blk_alloc_flush_queue(int node, int cmd_size,
void blk_free_flush_queue(struct blk_flush_queue *q);
void blk_freeze_queue(struct request_queue *q);
-void __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
-void blk_queue_start_drain(struct request_queue *q);
+bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
+bool blk_queue_start_drain(struct request_queue *q);
+bool __blk_freeze_queue_start(struct request_queue *q);
int __bio_queue_enter(struct request_queue *q, struct bio *bio);
void submit_bio_noacct_nocheck(struct bio *bio);
void bio_await_chain(struct bio *bio);
@@ -69,8 +71,11 @@ static inline int bio_queue_enter(struct bio *bio)
{
struct request_queue *q = bdev_get_queue(bio->bi_bdev);
- if (blk_try_enter_queue(q, false))
+ if (blk_try_enter_queue(q, false)) {
+ rwsem_acquire_read(&q->io_lockdep_map, 0, 0, _RET_IP_);
+ rwsem_release(&q->io_lockdep_map, _RET_IP_);
return 0;
+ }
return __bio_queue_enter(q, bio);
}
@@ -724,4 +729,22 @@ void blk_integrity_verify(struct bio *bio);
void blk_integrity_prepare(struct request *rq);
void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
+static inline void blk_freeze_acquire_lock(struct request_queue *q, bool
+ disk_dead, bool queue_dying)
+{
+ if (!disk_dead)
+ rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
+ if (!queue_dying)
+ rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
+}
+
+static inline void blk_unfreeze_release_lock(struct request_queue *q, bool
+ disk_dead, bool queue_dying)
+{
+ if (!queue_dying)
+ rwsem_release(&q->q_lockdep_map, _RET_IP_);
+ if (!disk_dead)
+ rwsem_release(&q->io_lockdep_map, _RET_IP_);
+}
+
#endif /* BLK_INTERNAL_H */
diff --git a/block/genhd.c b/block/genhd.c
index bc30eee7ab16..dfee66146bd1 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -601,13 +601,13 @@ static void blk_report_disk_dead(struct gendisk *disk, bool surprise)
rcu_read_unlock();
}
-static void __blk_mark_disk_dead(struct gendisk *disk)
+static bool __blk_mark_disk_dead(struct gendisk *disk)
{
/*
* Fail any new I/O.
*/
if (test_and_set_bit(GD_DEAD, &disk->state))
- return;
+ return false;
if (test_bit(GD_OWNS_QUEUE, &disk->state))
blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
@@ -620,7 +620,7 @@ static void __blk_mark_disk_dead(struct gendisk *disk)
/*
* Prevent new I/O from crossing bio_queue_enter().
*/
- blk_queue_start_drain(disk->queue);
+ return blk_queue_start_drain(disk->queue);
}
/**
@@ -661,6 +661,7 @@ void del_gendisk(struct gendisk *disk)
struct request_queue *q = disk->queue;
struct block_device *part;
unsigned long idx;
+ bool start_drain, queue_dying;
might_sleep();
@@ -688,7 +689,10 @@ void del_gendisk(struct gendisk *disk)
* Drop all partitions now that the disk is marked dead.
*/
mutex_lock(&disk->open_mutex);
- __blk_mark_disk_dead(disk);
+ start_drain = __blk_mark_disk_dead(disk);
+ queue_dying = blk_queue_dying(q);
+ if (start_drain)
+ blk_freeze_acquire_lock(q, true, queue_dying);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
@@ -745,6 +749,9 @@ void del_gendisk(struct gendisk *disk)
if (queue_is_mq(q))
blk_mq_exit_queue(q);
}
+
+ if (start_drain)
+ blk_unfreeze_release_lock(q, true, queue_dying);
}
EXPORT_SYMBOL(del_gendisk);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 55bec14fe55f..d0a52ed05e60 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -25,6 +25,7 @@
#include <linux/uuid.h>
#include <linux/xarray.h>
#include <linux/file.h>
+#include <linux/lockdep.h>
struct module;
struct request_queue;
@@ -474,6 +475,11 @@ struct request_queue {
struct xarray hctx_table;
struct percpu_ref q_usage_counter;
+ struct lock_class_key io_lock_cls_key;
+ struct lockdep_map io_lockdep_map;
+
+ struct lock_class_key q_lock_cls_key;
+ struct lockdep_map q_lockdep_map;
struct request *last_merge;
]
|
| 373/2 |
2026/11/03 20:49 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 357e1b7f730bd85a383e7afa75a3caba329c5707
Author: Ming Lei <ming.lei@redhat.com>
Date: Thu Oct 31 21:37:20 2024 +0800
block: don't verify IO lock for freeze/unfreeze in elevator_init_mq()
elevator_init_mq() is only called at the entry of add_disk_fwnode() when
disk IO isn't allowed yet.
So not verify io lock(q->io_lockdep_map) for freeze & unfreeze in
elevator_init_mq().
Reported-by: Marek Szyprowski <m.szyprowski@samsung.com>
Reported-by: Lai Yi <yi1.lai@linux.intel.com>
Fixes: f1be1788a32e ("block: model freeze & enter queue as lock for supporting lockdep")
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241031133723.303835-5-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/elevator.c b/block/elevator.c
index f169f4bae917..7c3ba80e5ff4 100644
--- a/block/elevator.c
+++ b/block/elevator.c
@@ -598,13 +598,19 @@ void elevator_init_mq(struct request_queue *q)
* drain any dispatch activities originated from passthrough
* requests, then no need to quiesce queue which may add long boot
* latency, especially when lots of disks are involved.
+ *
+ * Disk isn't added yet, so verifying queue lock only manually.
*/
- blk_mq_freeze_queue(q);
+ blk_freeze_queue_start_non_owner(q);
+ blk_freeze_acquire_lock(q, true, false);
+ blk_mq_freeze_queue_wait(q);
+
blk_mq_cancel_work_sync(q);
err = blk_mq_init_sched(q, e);
- blk_mq_unfreeze_queue(q);
+ blk_unfreeze_release_lock(q, true, false);
+ blk_mq_unfreeze_queue_non_owner(q);
if (err) {
pr_warn("\"%s\" elevator initialization failed, "
]
|
| 374/2 |
2026/11/03 20:49 |
llm |
patch-planner |
0m
Model:
Tokens:
input: 44674
output: 63
thoughts: 101
Thoughts: **Analyzing Recent Block Layer Changes**
Okay, let's dive into some potentially impactful block layer changes. My immediate focus is the region defined by the commit hashes around `6f491a8d4b92` and `f6661b1d0525`. These commits are often where interesting refactors or bug fixes tend to be centered. I want to thoroughly understand the evolution in this area.
My next step is to use `git log` to walk through the commits between those two points. I'll likely start by focusing on `block/blk-mq.c` and `block/genhd.c` β they're key files in that domain and likely candidates for containing the changes of interest. With that command I will gain insight into the specific modifications, reasoning, and context behind the changes within that span. Hopefully, that will give me a good understanding of what went down.
|
| 375/2 |
2026/11/03 20:50 |
tool |
git-log |
0m
Args: map[Count:20 PathPrefix:block/blk-mq.c]
Results: map[Output:4fcc499ea9bc blk-mq: set up a queue under tag_list_lock
89a2381482d8 blk-mq: exit the hctxs of a queue under tag_list_lock
71ec3c7d6db8 blk-mq: quiesce a queue that joins a quiesced tag set
0db9f8968a89 blk-mq: don't forget a timer the driver has restarted
9531230ee1fc blk-mq: don't bring back flags of a completed request
620cfc7a6642 blk-mq: keep sharing tags fairly after a queue update
24974185999f blk-mq: don't trust the cookie in blk_mq_poll()
afc1de47a7ab blk-mq: clear stale inactive flag on hctx reuse
5f702d4bd61b blk-mq: drop the tag_set argument from blk_mq_free_rq_map/tags
e1c51edd6a57 blk-mq: share one tags_srcu instance across all tag sets
20d808694e40 block: fix indention for dma-buf checks
d88e44f43e93 block: introduce dma map backed bio type
e0f2224433b1 block: drop the cached plug time when blk_add_rq_to_plug() flushes
9d2c70986bb7 blk-mq: allow cached requests to be used for flush operations
ab6c756f28c7 blk-mq: set RQF_USE_SCHED when the operation is known
1207dbb91c11 blk-mq: add missing call to srcu_barrier() in blk_mq_free_tag_set()
30e542a36228 blk-mq: bound blk_hctx_poll() to one jiffy
5bdb8ec58b54 block: propagate in_flight to whole disk on partition I/O
b7f40ab50190 block: export passthrough stats enabled
a7d8eaee7faf block: add a bio_endio_status helper
]
|
| 376/2 |
2026/11/03 20:50 |
tool |
git-log |
0m
Args: map[Count:20 PathPrefix:block/genhd.c]
Results: map[Output:3f9c7a108c0e block: flag zoned disks with GENHD_FL_NO_PART
7e9a46004b47 block: set QUEUE_FLAG_DYING unconditionally in blk_mark_disk_dead()
26cb8ebbfaf7 block: stop the timeout timer when releasing a never added disk
181bb9c9eae4 block: remove redundant GD_NEED_PART_SCAN in add_disk_final()
3dd63dba8f9c block: avoid potential deadlock on zone revalidation failure
e8dcf2d142bd block: add configurable error injection
bf4afc53b77a Convert 'alloc_obj' family to use the new default GFP_KERNEL argument
69050f8d6d07 treewide: Replace kmalloc with kmalloc_obj for non-scalar types
a74de0c3663c block: Remove references to __device_add_disk()
3179a5f7f86b block: rate-limit capacity change info log
343dc5423bfe block: fix kobject double initialization in add_disk
c007062188d8 block: fix false warning in bdev_count_inflight_rw()
f2987c5816bd block: export API to get the number of bdev inflight IO
6b6c3a97abde block: clean up blk_mq_in_flight_rw()
f5482ee5edb9 block: WARN if bdev inflight counter is negative
5b8f19aee474 block: reuse part_in_flight_rw for part_in_flight
78c271344b6f block: move wbt_enable_default() out of queue freezing from sched ->exit()
21eed794ab4b block: add new helper for disabling elevator switch when deleting disk
1e44bedbc921 block: unifying elevator change
98e68f67020c block: prevent adding/deleting disk during updating nr_hw_queues
]
|
| 377/2 |
2026/11/03 20:50 |
llm |
patch-planner |
0m
Model:
Tokens:
input: 45885
output: 64
thoughts: 73
Thoughts: Here's a summary of my thought process, as requested:
**Diving Deep into Block Layer Death Handling**
Alright, let's get down to brass tacks. I need to understand how the block layer handles a dying disk. My focus is sharpened on commit `7e9a46004b47`, specifically, the unconditional setting of `QUEUE_FLAG_DYING` in `blk_mark_disk_dead()`. This feels like a core piece of the puzzle. I want to see exactly *how* that flag is being used, and what guarantees are established with the approach.
Before I get too deep, I'll compare it to the changes just before it, so let's check `f6661b1d0525~1`.
To get a clear picture of *why* this change was made, and *what* it impacts, I'm going to pull up `git show` for both of those commits. That should provide a concise view of the code diffs, the commit messages, and any relevant context that's already in the kernel tree. My initial impression is that the unconditional setting is likely a response to a race condition or a corner case that could lead to data corruption or incomplete shutdown procedures if the dying flag wasn't set reliably. I need to make sure I understand the interaction between `blk_mark_disk_dead()` and everything else that touches the I/O queue. Time to dig in!
|
| 378/2 |
2026/11/03 20:50 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 7e9a46004b471eaf69b082c473d865316a4158e0
Author: θ‘θΏε€ <hulianqin@vivo.com>
Date: Wed Aug 12 11:59:04 2026 +0000
block: set QUEUE_FLAG_DYING unconditionally in blk_mark_disk_dead()
Disks created via blk_mq_alloc_disk_for_queue() (e.g. SCSI SD disks)
do not have GD_OWNS_QUEUE set. Currently __blk_mark_disk_dead() only
sets QUEUE_FLAG_DYING when GD_OWNS_QUEUE is set, so for such disks
blk_queue_enter() and __bio_queue_enter() cannot detect the dying
state via blk_queue_dying() and remain blocked waiting for I/O that
will never complete after surprise removal.
blk_mark_disk_dead() is the explicit "surprise removal" API -- the
caller has already decided the disk is dead. Setting QUEUE_FLAG_DYING
unconditionally here is appropriate: any in-flight I/O from other
threads should get -ENODEV immediately from blk_queue_enter()
regardless of GD_OWNS_QUEUE ownership.
For disks that already have GD_OWNS_QUEUE set, __blk_mark_disk_dead()
will set the flag again which is harmless.
Fixes: 6f8191fdf41d ("block: simplify disk shutdown")
Cc: stable@vger.kernel.org
Signed-off-by: Lianqin Hu <hulianqin@vivo.com>
Reviewed-by: Christoph Hellwig <hch@lst.de>
Link: https://patch.msgid.link/PUZPR06MB62247E82E66A3ED46CC3E6C7D2DC2@PUZPR06MB6224.apcprd06.prod.outlook.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/genhd.c b/block/genhd.c
index df2c3c69b467..7b089e2d52c4 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -681,6 +681,7 @@ static bool __blk_mark_disk_dead(struct gendisk *disk)
*/
void blk_mark_disk_dead(struct gendisk *disk)
{
+ blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
__blk_mark_disk_dead(disk);
blk_report_disk_dead(disk, true);
}
]
|
| 379/2 |
2026/11/03 20:50 |
tool |
git-show |
0m
Args: map[Commit:f6661b1d0525~1]
Results: map[Output:commit b9d4eee7e04b9cfb0b4bcd748fe6b3ec517171d9
Author: Ming Lei <ming.lei@redhat.com>
Date: Wed Nov 27 21:51:29 2024 +0800
block: don't verify queue freeze manually in elevator_init_mq()
Now blk_freeze_queue_start() can track disk state automatically, and
it isn't necessary to verify queue freeze manually in elevator_init_mq()
any more.
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241127135133.3952153-4-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/elevator.c b/block/elevator.c
index ca0a74369f1c..a26b96662620 100644
--- a/block/elevator.c
+++ b/block/elevator.c
@@ -601,16 +601,13 @@ void elevator_init_mq(struct request_queue *q)
*
* Disk isn't added yet, so verifying queue lock only manually.
*/
- blk_freeze_queue_start_non_owner(q);
- blk_freeze_acquire_lock(q, false);
- blk_mq_freeze_queue_wait(q);
+ blk_mq_freeze_queue(q);
blk_mq_cancel_work_sync(q);
err = blk_mq_init_sched(q, e);
- blk_unfreeze_release_lock(q, false);
- blk_mq_unfreeze_queue_non_owner(q);
+ blk_mq_unfreeze_queue(q);
if (err) {
pr_warn("\"%s\" elevator initialization failed, "
]
|
| 380/2 |
2026/11/03 20:50 |
llm |
patch-planner |
0m
Model:
Tokens:
input: 47272
output: 43
thoughts: 3343
Thoughts: **Analyzing the Block Layer Queue Freeze and Potential Races**
Okay, let's break this down systematically. My initial focus is to pinpoint the root cause of this lockdep warning. Is this a generic block layer problem, or specific to DM? And can I design a solid single-patch fix? I'm going to start by tracing the code and looking for race conditions, especially those related to freezing and unfreezing queues in the block layer, and how they interact with disk death and queue destruction.
First, let's consider a scenario without DM. I need to see if this freeze/unfreeze race can happen on *any* block device, not just DM. My analysis starts by walking through the basic freeze/unfreeze sequence: a CPU freezes the queue, and then a separate CPU does some action (del_gendisk etc.) that should not be able to interact with the first CPU.
I've sketched a typical freeze and unfreeze scenario and I see a possible race if a second thread, Thread B, calls `del_gendisk` *after* Thread A has frozen the queue, but *before* it has released the locks during unfreeze! Specifically, if Thread B calls `blk_mark_disk_dead(disk)` or `blk_mq_destroy_queue(q)`, after Thread A calls `blk_mq_freeze_queue(q)`.
It appears that Thread B, after marking the disk as dead, calls `blk_queue_start_drain(q)` (as part of `blk_mark_disk_dead`, which calls `__blk_mark_disk_dead`). This call acquires the same locks as the original freeze!
The interesting bit here is that `blk_mark_disk_dead` effectively starts another freeze operation (through `blk_queue_start_drain`), which happens while the original thread is *unfreezing*. This race can lead to the initial thread returning to userspace while *still* holding `q->q_lockdep_map` or `q->io_lockdep_map`.
Now I'm looking at the reverse case and the sequence of actions that can take place during a call to `blk_freeze_queue_start`. The analysis shows that while an owner is freezing a queue, no other thread should be able to alter the state variables (`q->mq_freeze_disk_dead` or `q->mq_freeze_queue_dying`) that are being checked.
I need to understand what happens in the `__del_gendisk` path, since this is part of marking the disk as dead. I'm focusing on the interaction with `blk_mark_disk_dead` and the calls to `blk_queue_start_drain(disk->queue)`. This function seems key to triggering the race.
The analysis shows that `blk_mark_disk_dead(disk)` calls `blk_queue_start_drain(disk->queue)`, which in turn calls `__blk_freeze_queue_start(q, current)`. I've determined that this is where the *second* thread (Thread B in the initial race) is freezing the queue. This function passes `current` as the owner!
A crucial detail here is that `blk_mark_disk_dead` does *not* acquire and release locks, but it *does* call `__blk_freeze_queue_start` on the queue, which is a key observation.
Crucially, what if `blk_mark_disk_dead(disk)` runs and then `blk_mq_freeze_queue(q)` is called again? In this case, since `q->mq_freeze_depth` is already 1, the lock's *owner* is now set to `current` when it was not before.
I'm now tracing `__del_gendisk` more closely when the disk does *not* own the queue (like a SCSI disk, e.g.). After `__blk_mark_disk_dead(disk)` is called, `blk_queue_start_drain` will set `q->mq_freeze_depth` to 1. This means that a freeze has happened with a different owner (the `current` task). When `!GD_OWNS_QUEUE`, `__blk_mq_unfreeze_queue(q, true)` is called *after* this has happened, potentially racing. This function is interesting because it calls `blk_unfreeze_release_lock(q)`. Is this the critical point? The previous thread returns while potentially still holding the lock.
|
| 381/2 |
2026/11/03 20:51 |
tool |
read-file |
0m
Args: map[File:block/blk-sysfs.c FirstLine:1015 LineCount:65]
Results: map[Contents:1015: return ret;
1016:
1017: out_unregister_ia_ranges:
1018: disk_unregister_independent_access_ranges(disk);
1019: out_debugfs_remove:
1020: blk_debugfs_remove(disk);
1021: mutex_unlock(&q->sysfs_lock);
1022: if (queue_is_mq(q))
1023: blk_mq_sysfs_unregister(disk);
1024: out_del_queue_kobj:
1025: kobject_del(&disk->queue_kobj);
1026: return ret;
1027: }
1028:
1029: /**
1030: * blk_unregister_queue - counterpart of blk_register_queue()
1031: * @disk: Disk of which the request queue should be unregistered from sysfs.
1032: *
1033: * Note: the caller is responsible for guaranteeing that this function is called
1034: * after blk_register_queue() has finished.
1035: */
1036: void blk_unregister_queue(struct gendisk *disk)
1037: {
1038: struct request_queue *q = disk->queue;
1039:
1040: if (WARN_ON(!q))
1041: return;
1042:
1043: /* Return early if disk->queue was never registered. */
1044: if (!blk_queue_registered(q))
1045: return;
1046:
1047: /*
1048: * Since sysfs_remove_dir() prevents adding new directory entries
1049: * before removal of existing entries starts, protect against
1050: * concurrent elv_iosched_store() calls.
1051: */
1052: mutex_lock(&q->sysfs_lock);
1053: blk_queue_flag_clear(QUEUE_FLAG_REGISTERED, q);
1054: mutex_unlock(&q->sysfs_lock);
1055:
1056: /*
1057: * Remove the sysfs attributes before unregistering the queue data
1058: * structures that can be modified through sysfs.
1059: */
1060: if (queue_is_mq(q))
1061: blk_mq_sysfs_unregister(disk);
1062: blk_crypto_sysfs_unregister(disk);
1063:
1064: mutex_lock(&q->sysfs_lock);
1065: disk_unregister_independent_access_ranges(disk);
1066: mutex_unlock(&q->sysfs_lock);
1067:
1068: /* Now that we've deleted all child objects, we can delete the queue. */
1069: kobject_uevent(&disk->queue_kobj, KOBJ_REMOVE);
1070: kobject_del(&disk->queue_kobj);
1071:
1072: if (queue_is_mq(q))
1073: elevator_set_none(q);
1074:
1075: blk_debugfs_remove(disk);
1076: }
]
|
| 382/2 |
2026/11/03 20:51 |
llm |
patch-planner |
0m
Model:
Tokens:
input: 51566
output: 83
thoughts: 1181
Thoughts: **Analyzing Potential Race Conditions in Block Layer Queue Freezing**
Okay, let's break this down. Line 1073 of `block/blk-sysfs.c` catches my eye because `elevator_set_none(q)` calls `elevator_change(q, &ctx)`, which then immediately triggers `blk_mq_freeze_queue(q)` and `blk_mq_unfreeze_queue(q)`. That's the initial setup, but I need to understand what happens during queue unregistration, specifically within `__del_gendisk`.
Right, `q->mq_freeze_depth` is initially 1, the owner is the current process, and the owner depth is also 1. When `blk_mq_freeze_queue(q)` is called, the depth becomes 2 and then back to 1. Then `blk_mq_unfreeze_queue(q)` gets called and the depth becomes 1, and the owner depth becomes 1. Alright, so that's the setup.
Now, at the end of `__del_gendisk(disk)`, it checks `!test_bit(GD_OWNS_QUEUE, &disk->state)`. If this is true, `__blk_mq_unfreeze_queue(q, true)` is called, which sounds straightforward. Here's the key: within that function, the depth goes to zero, the owner is set to NULL and the mutex is unlocked. That's a *complete* unfreeze. The race condition alert bells are going off. Immediately following that, *regardless* of whether the queue was unfrozen (because the `if` statement is `true`), `blk_unfreeze_release_lock(q)` is called! That's a potential problem - `blk_unfreeze_release_lock` is being called *after* a complete unfreeze, meaning it's releasing a lock that may not actually be held anymore.
Okay, let's consider the flip side: what if `GD_OWNS_QUEUE` *is* true? In that case, `__blk_mq_unfreeze_queue(q, true)` is *not* called, because the queue stays frozen. The `if (start_drain)` part *is* called. This is very important. That means `blk_unfreeze_release_lock(q)` is called while `q->mq_freeze_depth` is still 1 and the owner is the current process.
And now I'm thinking, why would `start_drain` ever acquire any lock in `blk_freeze_acquire_lock(q)` if `GD_OWNS_QUEUE` is true? That makes no sense.
Okay, let's step back and look at `__blk_mark_disk_dead(disk)`. Here, if `GD_OWNS_QUEUE` is true, both `GD_DEAD` and `QUEUE_FLAG_DYING` are set before `blk_queue_start_drain(disk->queue)` is called. This indicates the queue is effectively transitioning to a dying state. So, if `GD_OWNS_QUEUE` is true, then `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying` are both true. The lock acquisition and release in `blk_freeze_acquire_lock(q)` and `blk_unfreeze_release_lock(q)` appear to be optimized out in this path.
But wait. What if `GD_OWNS_QUEUE` is *false*? This is where it gets interesting, especially for things like SCSI `sd` devices, where the queue is shared. The request queue belongs to `scsi_device`, and itβs potentially shared between `sd_probe`, `sd_remove`, or passthrough. I need to investigate how `blk_mark_disk_dead` and `del_gendisk` are used in these scenarios in `drivers/scsi/sd.c:4279` and also in `drivers/nvme/host/core.c:5354` to understand these race condition scenarios fully! This is where the real vulnerability likely lies. I need to see how the queue unfreezing and draining is handled when the queue *doesn't* belong exclusively to the disk being removed.
|
| 383/2 |
2026/11/03 20:51 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sd.c FirstLine:4265 LineCount:40]
Results: map[Contents:4265: **/
4266: static void sd_remove(struct scsi_device *sdp)
4267: {
4268: struct device *dev = &sdp->sdev_gendev;
4269: struct scsi_disk *sdkp = dev_get_drvdata(dev);
4270:
4271: /*
4272: * If runtime resume fails, e.g. because the device was unplugged
4273: * while runtime suspended, the request queue stays in the pm-only
4274: * state and any I/O submitted by del_gendisk(), e.g. from
4275: * sync_filesystem(), would wait forever in __bio_queue_enter().
4276: * Prevent this by marking the disk dead.
4277: */
4278: if (scsi_autopm_get_device(sdkp->device) < 0)
4279: blk_mark_disk_dead(sdkp->disk);
4280:
4281: device_del(&sdkp->disk_dev);
4282: del_gendisk(sdkp->disk);
4283: if (!sdkp->suspended)
4284: sd_shutdown(sdp);
4285:
4286: put_disk(sdkp->disk);
4287:
4288: if (sdp->sector_size > PAGE_SIZE)
4289: sd_large_pool_destroy();
4290: }
4291:
4292: static inline bool sd_do_start_stop(struct scsi_device *sdev, bool runtime)
4293: {
4294: return (sdev->manage_system_start_stop && !runtime) ||
4295: (sdev->manage_runtime_start_stop && runtime);
4296: }
4297:
4298: static int sd_suspend_common(struct device *dev, bool runtime)
4299: {
4300: struct scsi_disk *sdkp = dev_get_drvdata(dev);
4301: int ret = 0;
4302:
4303: if (!sdkp) /* E.g.: runtime suspend following sd_remove() */
4304: return 0;
]
|
| 384/2 |
2026/11/03 20:51 |
tool |
read-file |
0m
Args: map[File:drivers/nvme/host/core.c FirstLine:5340 LineCount:35]
Results: map[Contents:5340:
5341: return 0;
5342: }
5343: EXPORT_SYMBOL_GPL(nvme_add_ctrl);
5344:
5345: /* let I/O to all namespaces fail in preparation for surprise removal */
5346: void nvme_mark_namespaces_dead(struct nvme_ctrl *ctrl)
5347: {
5348: struct nvme_ns *ns;
5349: int srcu_idx;
5350:
5351: srcu_idx = srcu_read_lock(&ctrl->srcu);
5352: list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
5353: srcu_read_lock_held(&ctrl->srcu))
5354: blk_mark_disk_dead(ns->disk);
5355: srcu_read_unlock(&ctrl->srcu, srcu_idx);
5356: }
5357: EXPORT_SYMBOL_GPL(nvme_mark_namespaces_dead);
5358:
5359: void nvme_unfreeze(struct nvme_ctrl *ctrl)
5360: {
5361: struct nvme_ns *ns;
5362: int srcu_idx;
5363:
5364: srcu_idx = srcu_read_lock(&ctrl->srcu);
5365: list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
5366: srcu_read_lock_held(&ctrl->srcu))
5367: blk_mq_unfreeze_queue_non_owner(ns->queue);
5368: srcu_read_unlock(&ctrl->srcu, srcu_idx);
5369: clear_bit(NVME_CTRL_FROZEN, &ctrl->flags);
5370: }
5371: EXPORT_SYMBOL_GPL(nvme_unfreeze);
5372:
5373: int nvme_wait_freeze_timeout(struct nvme_ctrl *ctrl)
5374: {
]
|
| 385/2 |
2026/11/03 20:51 |
llm |
patch-planner |
0m
Model:
Tokens:
input: 54055
output: 43
thoughts: 1623
Thoughts: **Analyzing SCSI Disk Removal and Queue Freezing**
Okay, let's break this down. I'm looking at the `sd_remove` function in `drivers/scsi/sd.c`. Specifically, what happens if `scsi_autopm_get_device(sdkp->device)` fails? If it does, we call `blk_mark_disk_dead(sdkp->disk)`. That's where things get interesting.
First, `blk_mark_disk_dead` sets the `QUEUE_FLAG_DYING` flag on the queue and then calls `__blk_mark_disk_dead`. This function sets the `GD_DEAD` bit and triggers `blk_queue_start_drain(q)`, which eventually calls `__blk_freeze_queue_start`. This freezes the queue by incrementing `q->mq_freeze_depth` and sets `mq_freeze_disk_dead` and `mq_freeze_queue_dying` to true. Importantly, the code *doesn't* call `blk_freeze_acquire_lock(q)` here, which is fine since both `disk_dead` and `queue_dying` are set so a lock would be a no-op anyway.
Next, `del_gendisk(sdkp->disk)` is called, which results in a call to `__del_gendisk`. Because `GD_DEAD` was already set, `__blk_mark_disk_dead` returns `false` (no drain) and *doesn't* increment `q->mq_freeze_depth` again. Crucially, after this, we have:
Since the `sd` driver doesn't own the queue, this unfreezes the queue (releasing the drain that was started earlier).
Now, the important part: what's the purpose of `blk_freeze_acquire_lock` and `blk_unfreeze_release_lock`? Where are they used, and how do they work? There are only two places in the entire kernel where these are called: in `blk-mq.c` and `genhd.c` within `__del_gendisk`.
In `blk-mq.c`, `blk_freeze_queue_start` calls `blk_freeze_acquire_lock` (if the queue is frozen). Then `blk_mq_unfreeze_queue_nomemrestore` calls `blk_unfreeze_release_lock`.
In `genhd.c`, the `__del_gendisk` function acquires and releases the lock using `blk_freeze_acquire_lock` and `blk_unfreeze_release_lock` if `start_drain` (a result of calling `__blk_mark_disk_dead`) is true.
But wait a minute! Let's examine the definitions in `block/blk.h`:
static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
#endif
These functions are `static inline`. That's interesting. Let's look at `_RET_IP_`. It's `__builtin_return_address(0)`. Because they are inline, when called, the `_RET_IP_` is the return address of the *calling* function. For example, in a crash report, there's `elevator_change+0x194/0x480` in the stack trace, and, in fact, `elevator_change` calls `blk_mq_freeze_queue`. I need to go back and check line 959 of `include/linux/blk-mq.h` to fully understand what's happening.
|
| 386/2 |
2026/11/03 20:52 |
tool |
read-file |
0m
Args: map[File:include/linux/blk-mq.h FirstLine:940 LineCount:50]
Results: map[Contents: 940: void blk_mq_quiesce_queue(struct request_queue *q);
941: void blk_mq_wait_quiesce_done(struct blk_mq_tag_set *set);
942: void blk_mq_quiesce_tagset(struct blk_mq_tag_set *set);
943: void blk_mq_unquiesce_tagset(struct blk_mq_tag_set *set);
944: void blk_mq_unquiesce_queue(struct request_queue *q);
945: void blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx *hctx, unsigned long msecs);
946: void blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async);
947: void blk_mq_run_hw_queues(struct request_queue *q, bool async);
948: void blk_mq_delay_run_hw_queues(struct request_queue *q, unsigned long msecs);
949: void blk_mq_tagset_busy_iter(struct blk_mq_tag_set *tagset,
950: busy_tag_iter_fn *fn, void *priv);
951: void blk_mq_tagset_wait_completed_request(struct blk_mq_tag_set *tagset);
952: void blk_mq_freeze_queue_nomemsave(struct request_queue *q);
953: void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q);
954: static inline unsigned int __must_check
955: blk_mq_freeze_queue(struct request_queue *q)
956: {
957: unsigned int memflags = memalloc_noio_save();
958:
959: blk_mq_freeze_queue_nomemsave(q);
960: return memflags;
961: }
962: static inline void
963: blk_mq_unfreeze_queue(struct request_queue *q, unsigned int memflags)
964: {
965: blk_mq_unfreeze_queue_nomemrestore(q);
966: memalloc_noio_restore(memflags);
967: }
968: void blk_freeze_queue_start(struct request_queue *q);
969: void blk_mq_freeze_queue_wait(struct request_queue *q);
970: int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
971: unsigned long timeout);
972: void blk_mq_unfreeze_queue_non_owner(struct request_queue *q);
973: void blk_freeze_queue_start_non_owner(struct request_queue *q);
974:
975: unsigned int blk_mq_num_possible_queues(unsigned int max_queues);
976: unsigned int blk_mq_num_online_queues(unsigned int max_queues);
977: void blk_mq_map_queues(struct blk_mq_queue_map *qmap);
978: void blk_mq_map_hw_queues(struct blk_mq_queue_map *qmap,
979: struct device *dev, unsigned int offset);
980: void blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set, int nr_hw_queues);
981:
982: void blk_mq_quiesce_queue_nowait(struct request_queue *q);
983:
984: unsigned int blk_mq_rq_cpu(struct request *rq);
985:
986: bool __blk_should_fake_timeout(struct request_queue *q);
987: static inline bool blk_should_fake_timeout(struct request_queue *q)
988: {
989: if (IS_ENABLED(CONFIG_FAIL_IO_TIMEOUT) &&
]
|
| 387/2 |
2026/11/03 20:52 |
llm |
patch-planner |
0m
Model:
Tokens:
input: 56819
output: 79
thoughts: 822
Thoughts: **Analyzing a Potential Lock Ordering Issue in the Block Layer Freezing Mechanism**
Okay, so I've been digging into this `blk_mq_freeze_queue` function, and something has jumped out at me. The compiler inlined `blk_freeze_queue_start` into `blk_mq_freeze_queue_nomemsave`, and because of that, `_RET_IP_` in `blk_freeze_acquire_lock` is resolving to `blk_mq_freeze_queue_nomemsave`'s caller. This, I believe, is `blk_mq_freeze_queue` inlined in `elevator_change`.
My brain is already buzzing with questions: What if `blk_freeze_acquire_lock` or its counterpart, `blk_unfreeze_release_lock`, end up being called inside functions like `blk_freeze_set_owner`, `blk_unfreeze_check_owner`, or the internal freezing/unfreezing functions?
Hold on a second, though. Before I get too carried away, let's back up and think about the implications of how these locks interact. Specifically, what happens when `rwsem_acquire` or `rwsem_release` is called while holding `q->mq_freeze_lock`?
WAIT A SECOND! This is where things get interesting. I need to think carefully about the lockdep lock ordering here. If we have a situation where `rwsem_acquire(&q->io_lockdep_map)` or `rwsem_acquire(&q->q_lockdep_map)` is called *while* holding `q->mq_freeze_lock`, then lockdep will see a dependency: `q->mq_freeze_lock` -> `q->io_lockdep_map` or `q->q_lockdep_map`.
Now the question becomes: What is the *actual* intended lock ordering between `q->q_lockdep_map`, `q->io_lockdep_map`, and `q->mq_freeze_lock`?
Let's break down the freeze/unfreeze process:
1. **Freezing the queue (`blk_mq_freeze_queue`)**: The current code acquires `q->mq_freeze_lock`, unlocks it, and then acquires `q->io_lockdep_map` and `q->q_lockdep_map`.
2. **Nested Freezing/Unfreezing**: While holding the `io_lockdep_map` and `q_lockdep_map` (i.e. the queue is frozen), the same or another task could call `blk_mq_freeze_queue(q)` or `blk_mq_unfreeze_queue(q)`. Now what does `blk_mq_unfreeze_queue(q)` do? While holding `q->io_lockdep_map` and `q->q_lockdep_map`, `blk_mq_unfreeze_queue(q)` calls `mutex_lock(&q->mq_freeze_lock)`!
Therefore, the intended lock order during unfreeze (and any nested freeze) is: `q->io_lockdep_map` -> `q->q_lockdep_map` -> `q->mq_freeze_lock`.
If `blk_freeze_acquire_lock` (called from an inlined function!) were somehow called UNDER `q->mq_freeze_lock`, then lockdep would *immediately* report an ABBA deadlock inversion between `q->mq_freeze_lock` and the `q->io_lockdep_map`/`q->q_lockdep_map`!
But wait, what about `rwsem_release` (in `blk_unfreeze_release_lock`)? Does `lock_release`, which is called by `rwsem_release` in `kernel/locking/lockdep.c`, even care about lock ordering or if `q->mq_freeze_lock` is held? I need to check `lock_release` in `kernel/locking/lockdep.c` to be sure. I'm going to read it and then I'll understand what's going on!
|
| 388/2 |
2026/11/03 20:52 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/locking/lockdep.c Name:lock_release]
Results: map[SourceCode:5950: void lock_release(struct lockdep_map *lock, unsigned long ip)
5951: {
5952: unsigned long flags;
5953:
5954: trace_lock_release(lock, ip);
5955:
5956: if (unlikely(!lockdep_enabled() ||
5957: lock->key == &__lockdep_no_track__))
5958: return;
5959:
5960: raw_local_irq_save(flags);
5961: check_flags(flags);
5962:
5963: lockdep_recursion_inc();
5964: if (__lock_release(lock, ip))
5965: check_chain_key(current);
5966: lockdep_recursion_finish();
5967: raw_local_irq_restore(flags);
5968: }
SourceFile:kernel/locking/lockdep.c]
|
| 389/2 |
2026/11/03 20:52 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/locking/lockdep.c Name:__lock_release]
Results: map[SourceCode:5558: /*
5559: * Remove the lock from the list of currently held locks - this gets
5560: * called on mutex_unlock()/spin_unlock*() (or on a failed
5561: * mutex_lock_interruptible()).
5562: */
5563: static int
5564: __lock_release(struct lockdep_map *lock, unsigned long ip)
5565: {
5566: struct task_struct *curr = current;
5567: unsigned int depth, merged = 1;
5568: struct held_lock *hlock;
5569: int i;
5570:
5571: if (unlikely(!debug_locks))
5572: return 0;
5573:
5574: depth = curr->lockdep_depth;
5575: /*
5576: * So we're all set to release this lock.. wait what lock? We don't
5577: * own any locks, you've been drinking again?
5578: */
5579: if (depth <= 0) {
5580: print_unlock_imbalance_bug(curr, lock, ip);
5581: return 0;
5582: }
5583:
5584: /*
5585: * Check whether the lock exists in the current stack
5586: * of held locks:
5587: */
5588: hlock = find_held_lock(curr, lock, depth, &i);
5589: if (!hlock) {
5590: print_unlock_imbalance_bug(curr, lock, ip);
5591: return 0;
5592: }
5593:
5594: if (hlock->instance == lock)
5595: lock_release_holdtime(hlock);
5596:
5597: WARN(hlock->pin_count, "releasing a pinned lock\n");
5598:
5599: if (hlock->references) {
5600: hlock->references--;
5601: if (hlock->references) {
5602: /*
5603: * We had, and after removing one, still have
5604: * references, the current lock stack is still
5605: * valid. We're done!
5606: */
5607: return 1;
5608: }
5609: }
5610:
5611: /*
5612: * We have the right lock to unlock, 'hlock' points to it.
5613: * Now we remove it from the stack, and add back the other
5614: * entries (if any), recalculating the hash along the way:
5615: */
5616:
5617: curr->lockdep_depth = i;
5618: curr->curr_chain_key = hlock->prev_chain_key;
5619:
5620: /*
5621: * The most likely case is when the unlock is on the innermost
5622: * lock. In this case, we are done!
5623: */
5624: if (i == depth-1)
5625: return 1;
5626:
5627: if (reacquire_held_locks(curr, depth, i + 1, &merged))
5628: return 0;
5629:
5630: /*
5631: * We had N bottles of beer on the wall, we drank one, but now
5632: * there's not N-1 bottles of beer left on the wall...
5633: * Pouring two of the bottles together is acceptable.
5634: */
5635: DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth - merged);
5636:
5637: /*
5638: * Since reacquire_held_locks() would have called check_chain_key()
5639: * indirectly via __lock_acquire(), we don't need to do it again
5640: * on return.
5641: */
5642: return 0;
5643: }
SourceFile:kernel/locking/lockdep.c]
|
| 390/2 |
2026/11/03 20:52 |
llm |
patch-planner |
2m
Model:
Tokens:
input: 59214
output: 82
thoughts: 11699
Thoughts: **Analyzing the Block Layer and Device Mapper Freeze/Unfreeze Logic**
Okay, so I've been digging into this lockdep issue with the block layer's freeze/unfreeze mechanisms. The key seems to be around the interaction between `__lock_release`, `blk_freeze_queue_start`, `blk_freeze_acquire_lock`, and `blk_unfreeze_release_lock`, especially when dealing with the `mq_freeze_lock` and the `q_lockdep_map`/`io_lockdep_map`.
Initially, the expected LIFO (last-in, first-out) order in `__lock_release` looks straightforward, but it gets complicated when `blk_unfreeze_release_lock` is called *after* `mutex_unlock(&q->mq_freeze_lock)`. The main issue is that during `blk_freeze_queue_start`, we have to be sure the lock order `io_lockdep_map` -> `q_lockdep_map` -> `mq_freeze_lock` -> unlock `mq_freeze_lock` -> release `q_lockdep_map` -> release `io_lockdep_map`.
The crucial race condition seems to be around `blk_freeze_acquire_lock` and `blk_unfreeze_release_lock`, where `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead` might be modified *outside* the protection of `q->mq_freeze_lock`. Essentially, if a queue is in the process of being unfrozen and some other task starts freezing it while one of them is outside the protection, there's a window where those flags can get flipped, causing problems. A task may be holding a lock and return to user space.
After analyzing the code, here are my main concerns:
1. **Race on `mq_freeze_queue_dying` / `mq_freeze_disk_dead`**: The current approach reads these state flags *outside* `q->mq_freeze_lock` which means another thread could modify these flags *after* depth has gone down to 0 and we are about to release `q_lockdep_map` / `io_lockdep_map`. This leads to missed releases or incorrect state checks, especially if `blk_mark_disk_dead` is called.
2. **`blk_freeze_acquire_lock` timing**: Whether it's called after the mutex unlock and reads those flags, or what the unfreeze side looks like, is important because, if it is called after the mutex unlock and reads the flags, then the release is incorrect. The lock could be acquired in a way that doesn't track lockdep.
3. **`blk_queue_start_drain(q)` and its callers**: The way `blk_queue_start_drain` is used by `blk_mq_destroy_queue`, `blk_mark_disk_dead`, and `__del_gendisk` is another point of concern. The callers all have different behaviors. In the `destroy_queue` case, no problems arise, but in the `mark_disk_dead` and `__del_gendisk` cases, there are races. In `__del_gendisk`, if the queue is *not* owned by the disk (`!GD_OWNS_QUEUE`), then `__blk_mq_unfreeze_queue` is called. But it's called after those fields have been read and before the queue has been set.
Now, let's connect it to Device Mapper. The analysis suggests that the crash report is not caused by the block layer alone. The Device Mapper part is, in `__dm_destroy`, we call `blk_mark_disk_dead` on the queue. If, in `__dm_destroy`, `!test_bit(GD_OWNS_QUEUE, &disk->state)`, the queue will be unfrozen. The Device Mapper part of the problem comes from the fact that `blk_mark_disk_dead` is called from a thread A, then later from a thread B, and the queue could be touched by thread C.
The analysis points out that `blk_mark_disk_dead` should not be called while initialization is still going on.
To fix, the block layer code needs to be modified so that `blk_unfreeze_release_lock` either:
- Performs the lockdep release *inside* of the lock or uses a cached value for `queue_dying`.
Similarly, snapshot the dying state under the freeze lock in `__blk_freeze_queue_start`.
In Device Mapper, `blk_mark_disk_dead(md->disk)` needs to be serialized to prevent races between destruction and initialization.
|
| 391/2 |
2026/11/03 20:54 |
tool |
read-file |
0m
Args: map[File:drivers/md/dm.c FirstLine:2250 LineCount:100]
Results: map[Contents:2250:
2251: if (md->dax_dev) {
2252: dax_remove_host(md->disk);
2253: kill_dax(md->dax_dev);
2254: put_dax(md->dax_dev);
2255: md->dax_dev = NULL;
2256: }
2257:
2258: if (md->disk) {
2259: spin_lock(&_minor_lock);
2260: md->disk->private_data = NULL;
2261: spin_unlock(&_minor_lock);
2262: if (dm_get_md_type(md) != DM_TYPE_NONE) {
2263: struct table_device *td;
2264:
2265: dm_sysfs_exit(md);
2266: list_for_each_entry(td, &md->table_devices, list) {
2267: bd_unlink_disk_holder(td->dm_dev.bdev,
2268: md->disk);
2269: }
2270:
2271: /*
2272: * Hold lock to make sure del_gendisk() won't concurrent
2273: * with open/close_table_device().
2274: */
2275: mutex_lock(&md->table_devices_lock);
2276: del_gendisk(md->disk);
2277: mutex_unlock(&md->table_devices_lock);
2278: }
2279: dm_queue_destroy_crypto_profile(md->queue);
2280: put_disk(md->disk);
2281: }
2282:
2283: if (md->pending_io) {
2284: free_percpu(md->pending_io);
2285: md->pending_io = NULL;
2286: }
2287:
2288: cleanup_srcu_struct(&md->io_barrier);
2289:
2290: mutex_destroy(&md->suspend_lock);
2291: mutex_destroy(&md->type_lock);
2292: mutex_destroy(&md->table_devices_lock);
2293: mutex_destroy(&md->swap_bios_lock);
2294:
2295: dm_mq_cleanup_mapped_device(md);
2296: }
2297:
2298: /*
2299: * Allocate and initialise a blank device with a given minor.
2300: */
2301: static struct mapped_device *alloc_dev(int minor)
2302: {
2303: int r, numa_node_id = dm_get_numa_node();
2304: struct dax_device *dax_dev;
2305: struct mapped_device *md;
2306: void *old_md;
2307:
2308: md = kvzalloc_node(sizeof(*md), GFP_KERNEL, numa_node_id);
2309: if (!md) {
2310: DMERR("unable to allocate device, out of memory.");
2311: return NULL;
2312: }
2313:
2314: if (!try_module_get(THIS_MODULE))
2315: goto bad_module_get;
2316:
2317: /* get a minor number for the dev */
2318: if (minor == DM_ANY_MINOR)
2319: r = next_free_minor(&minor);
2320: else
2321: r = specific_minor(minor);
2322: if (r < 0)
2323: goto bad_minor;
2324:
2325: r = init_srcu_struct(&md->io_barrier);
2326: if (r < 0)
2327: goto bad_io_barrier;
2328:
2329: md->numa_node_id = numa_node_id;
2330: md->init_tio_pdu = false;
2331: md->type = DM_TYPE_NONE;
2332: mutex_init(&md->suspend_lock);
2333: mutex_init(&md->type_lock);
2334: mutex_init(&md->table_devices_lock);
2335: spin_lock_init(&md->deferred_lock);
2336: atomic_set(&md->holders, 1);
2337: atomic_set(&md->open_count, 0);
2338: atomic_set(&md->event_nr, 0);
2339: atomic_set(&md->uevent_seq, 0);
2340: INIT_LIST_HEAD(&md->uevent_list);
2341: INIT_LIST_HEAD(&md->table_devices);
2342: spin_lock_init(&md->uevent_lock);
2343:
2344: /*
2345: * default to bio-based until DM table is loaded and md->type
2346: * established. If request-based table is loaded: blk-mq will
2347: * override accordingly.
2348: */
2349: md->disk = blk_alloc_disk(NULL, md->numa_node_id);
]
|
| 392/2 |
2026/11/03 20:54 |
tool |
read-file |
0m
Args: map[File:drivers/md/dm.c FirstLine:2550 LineCount:150]
Results: map[Contents:2550: RCU_INIT_POINTER(md->map, NULL);
2551: dm_sync_table(md);
2552:
2553: return map;
2554: }
2555:
2556: /*
2557: * Constructor for a new device.
2558: */
2559: int dm_create(int minor, struct mapped_device **result)
2560: {
2561: struct mapped_device *md;
2562:
2563: md = alloc_dev(minor);
2564: if (!md)
2565: return -ENXIO;
2566:
2567: dm_ima_init(md);
2568:
2569: *result = md;
2570: return 0;
2571: }
2572:
2573: /*
2574: * Functions to manage md->type.
2575: * All are required to hold md->type_lock.
2576: */
2577: void dm_lock_md_type(struct mapped_device *md)
2578: {
2579: mutex_lock(&md->type_lock);
2580: }
2581:
2582: void dm_unlock_md_type(struct mapped_device *md)
2583: {
2584: mutex_unlock(&md->type_lock);
2585: }
2586:
2587: enum dm_queue_mode dm_get_md_type(struct mapped_device *md)
2588: {
2589: return md->type;
2590: }
2591:
2592: struct target_type *dm_get_immutable_target_type(struct mapped_device *md)
2593: {
2594: return md->immutable_target_type;
2595: }
2596:
2597: /*
2598: * Setup the DM device's queue based on md's type
2599: */
2600: int dm_setup_md_queue(struct mapped_device *md, struct dm_table *t)
2601: {
2602: enum dm_queue_mode type = dm_table_get_type(t);
2603: struct queue_limits limits;
2604: struct table_device *td;
2605: int r;
2606:
2607: WARN_ON_ONCE(type == DM_TYPE_NONE);
2608:
2609: if (type == DM_TYPE_REQUEST_BASED) {
2610: md->disk->fops = &dm_rq_blk_dops;
2611: r = dm_mq_init_request_queue(md, t);
2612: if (r) {
2613: DMERR("Cannot initialize queue for request-based dm mapped device");
2614: return r;
2615: }
2616: }
2617:
2618: r = dm_calculate_queue_limits(t, &limits);
2619: if (r) {
2620: DMERR("Cannot calculate initial queue limits");
2621: return r;
2622: }
2623: r = dm_table_set_restrictions(t, md->queue, &limits);
2624: if (r)
2625: return r;
2626:
2627: /*
2628: * Hold lock to make sure add_disk() and del_gendisk() won't concurrent
2629: * with open_table_device() and close_table_device().
2630: */
2631: mutex_lock(&md->table_devices_lock);
2632: r = add_disk(md->disk);
2633: if (r) {
2634: mutex_unlock(&md->table_devices_lock);
2635: return r;
2636: }
2637:
2638: /*
2639: * Register the holder relationship for devices added before the disk
2640: * was live.
2641: */
2642: list_for_each_entry(td, &md->table_devices, list) {
2643: r = bd_link_disk_holder(td->dm_dev.bdev, md->disk);
2644: if (r)
2645: goto out_undo_holders;
2646: }
2647: mutex_unlock(&md->table_devices_lock);
2648:
2649: r = dm_sysfs_init(md);
]
|
| 393/2 |
2026/11/03 20:54 |
llm |
patch-planner |
0m
Model:
Tokens:
input: 73836
output: 58
thoughts: 542
Thoughts: **Analyzing the Bug and Crafting a Targeted Solution**
Okay, let's break this down. First, I need to pinpoint the root cause of this "lock held when returning to user space" warning. Is it solely a Block Layer issue, a DM issue, or both? The prompt's guidelines are key: single-patch implementation, best fit against architectural design. I need to make sure I don't touch code outside of the appropriate subsystem and don't make more changes than I need.
I know that `block/` and `drivers/md/dm.c` involve different maintainers (Jens Axboe and Mikulas Patocka respectively), which makes a single patch that touches both unlikely. Given the error message points to `block/elevator.c`, I'll focus there initially.
Now, if I *only* fix the DM-specific code, will it completely eliminate the race condition between `blk_mq_unfreeze_queue()` and concurrent calls to functions like `blk_mq_freeze_queue()`, `blk_mark_disk_dead()`, or `del_gendisk()` on *any* block device? No, it won't. I'm seeing it.
The critical question is, does fixing the Block Layer race itself in `block/blk-mq.c`, `block/blk.h`, or `block/genhd.c` *fully* eliminate the crash for both DM *and* all other block devices? I think the answer is yes. This is the more general fix that could resolve this more broadly.
There's one more edge case to check: what if DM calls `blk_mark_disk_dead(md->disk)` in `__dm_destroy()` while `table_load()` is in `dm_setup_md_queue()`? That's a critical point to consider.
And then I need to consider... why did those two commitsβ`3b785fbcf81c` and `7a5428dcb790`βplace `blk_mark_disk_dead(md->disk)` *before* the `while (atomic_read(&md->holders)) fsleep(1000);` loop in `__dm_destroy()`? That's definitely worth investigating. I'll use `git-show` to review those commits, especially since it seems the intent was to fix a related issue, and possibly introduce a subtle regression or different race.
|
| 394/2 |
2026/11/03 20:54 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 3b785fbcf81c3533772c52b717f77293099498d3
Author: Bart Van Assche <bvanassche@acm.org>
Date: Wed Aug 31 15:17:49 2016 -0700
dm: mark request_queue dead before destroying the DM device
This avoids that new requests are queued while __dm_destroy() is in
progress.
Signed-off-by: Bart Van Assche <bart.vanassche@sandisk.com>
Signed-off-by: Mike Snitzer <snitzer@redhat.com>
Cc: stable@vger.kernel.org
diff --git a/drivers/md/dm.c b/drivers/md/dm.c
index c0742129a9cb..0f2928b3136b 100644
--- a/drivers/md/dm.c
+++ b/drivers/md/dm.c
@@ -1873,6 +1873,7 @@ EXPORT_SYMBOL_GPL(dm_device_name);
static void __dm_destroy(struct mapped_device *md, bool wait)
{
+ struct request_queue *q = dm_get_md_queue(md);
struct dm_table *map;
int srcu_idx;
@@ -1883,6 +1884,10 @@ static void __dm_destroy(struct mapped_device *md, bool wait)
set_bit(DMF_FREEING, &md->flags);
spin_unlock(&_minor_lock);
+ spin_lock_irq(q->queue_lock);
+ queue_flag_set(QUEUE_FLAG_DYING, q);
+ spin_unlock_irq(q->queue_lock);
+
if (dm_request_based(md) && md->kworker_task)
flush_kthread_worker(&md->kworker);
]
|
| 395/2 |
2026/11/03 20:55 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 7a5428dcb7902700b830e912feee4e845df7c019
Author: Christoph Hellwig <hch@lst.de>
Date: Thu Feb 17 08:52:31 2022 +0100
block: fix surprise removal for drivers calling blk_set_queue_dying
Various block drivers call blk_set_queue_dying to mark a disk as dead due
to surprise removal events, but since commit 8e141f9eb803 that doesn't
work given that the GD_DEAD flag needs to be set to stop I/O.
Replace the driver calls to blk_set_queue_dying with a new (and properly
documented) blk_mark_disk_dead API, and fold blk_set_queue_dying into the
only remaining caller.
Fixes: 8e141f9eb803 ("block: drain file system I/O on del_gendisk")
Reported-by: Markus BlΓΆchl <markus.bloechl@ipetronik.com>
Signed-off-by: Christoph Hellwig <hch@lst.de>
Reviewed-by: Sagi Grimberg <sagi@grimberg.me>
Link: https://lore.kernel.org/r/20220217075231.1140-1-hch@lst.de
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-core.c b/block/blk-core.c
index d93e3bb9a769..1039515c99d6 100644
--- a/block/blk-core.c
+++ b/block/blk-core.c
@@ -284,13 +284,6 @@ void blk_queue_start_drain(struct request_queue *q)
wake_up_all(&q->mq_freeze_wq);
}
-void blk_set_queue_dying(struct request_queue *q)
-{
- blk_queue_flag_set(QUEUE_FLAG_DYING, q);
- blk_queue_start_drain(q);
-}
-EXPORT_SYMBOL_GPL(blk_set_queue_dying);
-
/**
* blk_cleanup_queue - shutdown a request queue
* @q: request queue to shutdown
@@ -308,7 +301,8 @@ void blk_cleanup_queue(struct request_queue *q)
WARN_ON_ONCE(blk_queue_registered(q));
/* mark @q DYING, no new request or merges will be allowed afterwards */
- blk_set_queue_dying(q);
+ blk_queue_flag_set(QUEUE_FLAG_DYING, q);
+ blk_queue_start_drain(q);
blk_queue_flag_set(QUEUE_FLAG_NOMERGES, q);
blk_queue_flag_set(QUEUE_FLAG_NOXMERGES, q);
diff --git a/block/genhd.c b/block/genhd.c
index 626c8406f21a..9eca1f7d35c9 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -548,6 +548,20 @@ int __must_check device_add_disk(struct device *parent, struct gendisk *disk,
}
EXPORT_SYMBOL(device_add_disk);
+/**
+ * blk_mark_disk_dead - mark a disk as dead
+ * @disk: disk to mark as dead
+ *
+ * Mark as disk as dead (e.g. surprise removed) and don't accept any new I/O
+ * to this disk.
+ */
+void blk_mark_disk_dead(struct gendisk *disk)
+{
+ set_bit(GD_DEAD, &disk->state);
+ blk_queue_start_drain(disk->queue);
+}
+EXPORT_SYMBOL_GPL(blk_mark_disk_dead);
+
/**
* del_gendisk - remove the gendisk
* @disk: the struct gendisk to remove
diff --git a/drivers/block/mtip32xx/mtip32xx.c b/drivers/block/mtip32xx/mtip32xx.c
index e6005c232328..2b588b62cbbb 100644
--- a/drivers/block/mtip32xx/mtip32xx.c
+++ b/drivers/block/mtip32xx/mtip32xx.c
@@ -4112,7 +4112,7 @@ static void mtip_pci_remove(struct pci_dev *pdev)
"Completion workers still active!\n");
}
- blk_set_queue_dying(dd->queue);
+ blk_mark_disk_dead(dd->disk);
set_bit(MTIP_DDF_REMOVE_PENDING_BIT, &dd->dd_flag);
/* Clean up the block layer. */
diff --git a/drivers/block/rbd.c b/drivers/block/rbd.c
index 4203cdab8abf..b844432bad20 100644
--- a/drivers/block/rbd.c
+++ b/drivers/block/rbd.c
@@ -7185,7 +7185,7 @@ static ssize_t do_rbd_remove(struct bus_type *bus,
* IO to complete/fail.
*/
blk_mq_freeze_queue(rbd_dev->disk->queue);
- blk_set_queue_dying(rbd_dev->disk->queue);
+ blk_mark_disk_dead(rbd_dev->disk);
}
del_gendisk(rbd_dev->disk);
diff --git a/drivers/block/xen-blkfront.c b/drivers/block/xen-blkfront.c
index ccd0dd0c6b83..ca71a0585333 100644
--- a/drivers/block/xen-blkfront.c
+++ b/drivers/block/xen-blkfront.c
@@ -2126,7 +2126,7 @@ static void blkfront_closing(struct blkfront_info *info)
/* No more blkif_request(). */
blk_mq_stop_hw_queues(info->rq);
- blk_set_queue_dying(info->rq);
+ blk_mark_disk_dead(info->gd);
set_capacity(info->gd, 0);
for_each_rinfo(info, rinfo, i) {
diff --git a/drivers/md/dm.c b/drivers/md/dm.c
index dcbd6d201619..997ace47bbd5 100644
--- a/drivers/md/dm.c
+++ b/drivers/md/dm.c
@@ -2077,7 +2077,7 @@ static void __dm_destroy(struct mapped_device *md, bool wait)
set_bit(DMF_FREEING, &md->flags);
spin_unlock(&_minor_lock);
- blk_set_queue_dying(md->queue);
+ blk_mark_disk_dead(md->disk);
/*
* Take suspend_lock so that presuspend and postsuspend methods
diff --git a/drivers/nvme/host/core.c b/drivers/nvme/host/core.c
index 79005ea1a33e..469f23186159 100644
--- a/drivers/nvme/host/core.c
+++ b/drivers/nvme/host/core.c
@@ -4574,7 +4574,7 @@ static void nvme_set_queue_dying(struct nvme_ns *ns)
if (test_and_set_bit(NVME_NS_DEAD, &ns->flags))
return;
- blk_set_queue_dying(ns->queue);
+ blk_mark_disk_dead(ns->disk);
nvme_start_ns_queue(ns);
set_capacity_and_notify(ns->disk, 0);
diff --git a/drivers/nvme/host/multipath.c b/drivers/nvme/host/multipath.c
index f8bf6606eb2f..ff775235534c 100644
--- a/drivers/nvme/host/multipath.c
+++ b/drivers/nvme/host/multipath.c
@@ -848,7 +848,7 @@ void nvme_mpath_remove_disk(struct nvme_ns_head *head)
{
if (!head->disk)
return;
- blk_set_queue_dying(head->disk->queue);
+ blk_mark_disk_dead(head->disk);
/* make sure all pending bios are cleaned up */
kblockd_schedule_work(&head->requeue_work);
flush_work(&head->requeue_work);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index f35aea98bc35..16b47035e4b0 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -748,7 +748,8 @@ extern bool blk_queue_can_use_dma_map_merging(struct request_queue *q,
bool __must_check blk_get_queue(struct request_queue *);
extern void blk_put_queue(struct request_queue *);
-extern void blk_set_queue_dying(struct request_queue *);
+
+void blk_mark_disk_dead(struct gendisk *disk);
#ifdef CONFIG_BLOCK
/*
]
|
| 396/2 |
2026/11/03 20:55 |
llm |
patch-planner |
0m
Model:
Tokens:
input: 77518
output: 24
thoughts: 898
Thoughts: **The Block Layer Queue Freeze Lockdep Bug**
Alright, let's break this down. Analyzing that code, specifically `3b785fbcf81c`, it's clear: `blk_mark_disk_dead(md->disk)` *must* be called *before* that `while (atomic_read(&md->holders))` loop in `__dm_destroy()`. This is because in-flight I/Os or `postsuspend` functions might still be holding onto `md->holders`, and we need to reject new requests while we're waiting for everything to settle down in `__dm_destroy()`. So, the ordering is intentional, and there's a reason for it.
The real culprit here is a block-layer queue freeze lockdep tracking bug. The core issue is that even when you call `blk_mark_disk_dead` β whether on NVMe (`nvme_mark_namespaces_dead`), SCSI (`sd_remove`), or even something simpler like loop or null_blk β the same race condition in `block/blk-mq.c` pops up.
Think about the scenario:
* Thread 1 modifies something in `/sys/block/.../queue/`, triggering `elv_iosched_store`, `elevator_change`, which eventually calls `blk_mq_freeze_queue` or `blk_mq_unfreeze_queue`, or even `queue_requests_store`, or `queue_wb_lat_store`, or `bdev_open`!
* Simultaneously, Thread 2 removes the device, maybe with `del_gendisk` or `blk_mark_disk_dead`. Or even just another thread calls `blk_mq_freeze_queue` right after `GD_DEAD` and `QUEUE_FLAG_DYING` are set!
* Thread 1 is in `blk_mq_unfreeze_queue_nomemrestore(q)` and decrements `q->mq_freeze_depth` to 0 and unlocks the `q->mq_freeze_lock`.
* Thread 2 enters `__blk_freeze_queue_start(q, current)`, locks `q->mq_freeze_lock`, sees `!q->mq_freeze_depth`, and overwrites `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying`!
* Then Thread 1 executes `blk_unfreeze_release_lock(q)` outside of that lock. It reads the values that Thread 2 has set: `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying`, and completely skips the call to `rwsem_release()`!
That's the smoking gun! The bug is in the block layer, specifically in how the queue freeze lockdep state is handled across freeze and unfreeze, in `block/blk-mq.c`, `block/blk.h`, `block/genhd.c`, and `include/linux/blkdev.h`.
Now, it's time to dig into the details. I need to carefully examine `blk_freeze_set_owner`, `blk_unfreeze_check_owner`, `blk_freeze_acquire_lock`, `blk_unfreeze_release_lock`, `__blk_freeze_queue_start`, `__blk_mq_unfreeze_queue`, `blk_mq_unfreeze_queue_nomemrestore`, `blk_queue_start_drain`, `__blk_mark_disk_dead`, `blk_mark_disk_dead`, and `__del_gendisk`. I need a complete understanding of how these pieces interact. Let's start with a systematic review of the `block/` directory, checking all the code paths that use these functions or fields. Let's use `grepper` and search for every instance of `mq_freeze_` across the entire kernel source tree!
|
| 397/2 |
2026/11/03 20:55 |
tool |
grepper |
0m
Args: map[Expression:mq_freeze_]
Results: map[Output:
Full output is too long, showing 200 out of 469 lines.
Use more precise expression or PathPrefixes if possible.
Number of matching lines per file (33 files in total):
block/bfq-iosched.c:1
block/blk-cgroup.c:2
block/blk-core.c:11
block/blk-iocost.c:2
block/blk-iolatency.c:1
block/blk-mq.c:33
block/blk-rq-qos.c:2
block/blk-settings.c:1
block/blk-sysfs.c:3
block/blk-throttle.c:1
block/blk-wbt.c:1
block/blk-zoned.c:1
block/blk.h:4
block/elevator.c:4
block/genhd.c:1
drivers/block/amiflop.c:2
drivers/block/aoe/aoedev.c:1
drivers/block/ataflop.c:1
drivers/block/loop.c:4
drivers/block/rbd.c:1
drivers/block/sunvdc.c:1
drivers/block/swim3.c:1
drivers/block/ublk_drv.c:1
drivers/block/virtio_blk.c:1
drivers/mtd/mtd_blkdevs.c:1
drivers/nvme/host/core.c:5
drivers/nvme/host/multipath.c:1
drivers/scsi/scsi_lib.c:1
drivers/scsi/scsi_scan.c:1
drivers/scsi/scsi_sysfs.c:1
drivers/ufs/core/ufs-sysfs.c:1
include/linux/blk-mq.h:5
include/linux/blkdev.h:8
block/bfq-iosched.c=7196=static int bfq_init_queue(struct request_queue *q, struct elevator_queue *eq)
--
block/bfq-iosched.c-7329- * (bfq_create_group_hierarchy->blkcg_activate_policy->
block/bfq-iosched.c:7330: * blk_mq_freeze_queue) that may lead to the invocation of the
block/bfq-iosched.c-7331- * has_work hook function. For this reason,
--
block/blk-cgroup.c=1608=int blkcg_activate_policy(struct gendisk *disk, const struct blkcg_policy *pol)
--
block/blk-cgroup.c-1627- if (queue_is_mq(q))
block/blk-cgroup.c:1628: memflags = blk_mq_freeze_queue(q);
block/blk-cgroup.c-1629-
--
block/blk-cgroup.c=1723=void blkcg_deactivate_policy(struct gendisk *disk,
--
block/blk-cgroup.c-1732- if (queue_is_mq(q))
block/blk-cgroup.c:1733: memflags = blk_mq_freeze_queue(q);
block/blk-cgroup.c-1734-
--
block/blk-core.c=281=void blk_clear_pm_only(struct request_queue *q)
--
block/blk-core.c-287- if (pm_only == 0)
block/blk-core.c:288: wake_up_all(&q->mq_freeze_wq);
block/blk-core.c-289-}
--
block/blk-core.c=327=bool blk_queue_start_drain(struct request_queue *q)
--
block/blk-core.c-337- /* Make blk_queue_enter() reexamine the DYING flag. */
block/blk-core.c:338: wake_up_all(&q->mq_freeze_wq);
block/blk-core.c-339-
--
block/blk-core.c=348=int blk_queue_enter(struct request_queue *q, blk_mq_req_flags_t flags)
--
block/blk-core.c-358- * order reading __PERCPU_REF_DEAD flag of .q_usage_counter and
block/blk-core.c:359: * reading .mq_freeze_depth or queue dying flag, otherwise the
block/blk-core.c-360- * following wait may never return if the two reads are
--
block/blk-core.c-363- smp_rmb();
block/blk-core.c:364: wait_event(q->mq_freeze_wq,
block/blk-core.c:365: (!q->mq_freeze_depth &&
block/blk-core.c-366- blk_pm_resume_queue(pm, q)) ||
--
block/blk-core.c=377=int __bio_queue_enter(struct request_queue *q, struct bio *bio)
--
block/blk-core.c-391- * order reading __PERCPU_REF_DEAD flag of .q_usage_counter and
block/blk-core.c:392: * reading .mq_freeze_depth or queue dying flag, otherwise the
block/blk-core.c-393- * following wait may never return if the two reads are
--
block/blk-core.c-396- smp_rmb();
block/blk-core.c:397: wait_event(q->mq_freeze_wq,
block/blk-core.c:398: (!q->mq_freeze_depth &&
block/blk-core.c-399- blk_pm_resume_queue(false, q)) ||
--
block/blk-core.c=418=static void blk_queue_usage_counter_release(struct percpu_ref *ref)
--
block/blk-core.c-422-
block/blk-core.c:423: wake_up_all(&q->mq_freeze_wq);
block/blk-core.c-424-}
--
block/blk-core.c=437=struct request_queue *blk_alloc_queue(struct queue_limits *lim, int node_id)
--
block/blk-core.c-481-
block/blk-core.c:482: init_waitqueue_head(&q->mq_freeze_wq);
block/blk-core.c:483: mutex_init(&q->mq_freeze_lock);
block/blk-core.c-484-
--
block/blk-iocost.c=3366=static ssize_t ioc_qos_write(struct kernfs_open_file *of, char *input,
--
block/blk-iocost.c-3391-
block/blk-iocost.c:3392: memflags = blk_mq_freeze_queue(ctx.bdev->bd_queue);
block/blk-iocost.c-3393- mutex_lock(&ctx.bdev->bd_queue->rq_qos_mutex);
--
block/blk-iocost.c=3572=static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
--
block/blk-iocost.c-3604-
block/blk-iocost.c:3605: memflags = blk_mq_freeze_queue(q);
block/blk-iocost.c-3606- blk_mq_quiesce_queue(q);
--
block/blk-iolatency.c=729=static void blkiolatency_enable_work_fn(struct work_struct *work)
--
block/blk-iolatency.c-748-
block/blk-iolatency.c:749: memflags = blk_mq_freeze_queue(blkiolat->rqos.disk->queue);
block/blk-iolatency.c-750- blkiolat->enabled = enabled;
--
block/blk-mq.c=116=static bool blk_freeze_set_owner(struct request_queue *q,
--
block/blk-mq.c-121-
block/blk-mq.c:122: if (!q->mq_freeze_depth) {
block/blk-mq.c:123: q->mq_freeze_owner = owner;
block/blk-mq.c:124: q->mq_freeze_owner_depth = 1;
block/blk-mq.c:125: q->mq_freeze_disk_dead = !q->disk ||
block/blk-mq.c-126- test_bit(GD_DEAD, &q->disk->state) ||
block/blk-mq.c-127- !blk_queue_registered(q);
block/blk-mq.c:128: q->mq_freeze_queue_dying = blk_queue_dying(q);
block/blk-mq.c-129- return true;
--
block/blk-mq.c-131-
block/blk-mq.c:132: if (owner == q->mq_freeze_owner)
block/blk-mq.c:133: q->mq_freeze_owner_depth += 1;
block/blk-mq.c-134- return false;
--
block/blk-mq.c=138=static bool blk_unfreeze_check_owner(struct request_queue *q)
block/blk-mq.c-139-{
block/blk-mq.c:140: if (q->mq_freeze_owner != current)
block/blk-mq.c-141- return false;
block/blk-mq.c:142: if (--q->mq_freeze_owner_depth == 0) {
block/blk-mq.c:143: q->mq_freeze_owner = NULL;
block/blk-mq.c-144- return true;
--
block/blk-mq.c=163=bool __blk_freeze_queue_start(struct request_queue *q,
--
block/blk-mq.c-167-
block/blk-mq.c:168: mutex_lock(&q->mq_freeze_lock);
block/blk-mq.c-169- freeze = blk_freeze_set_owner(q, owner);
block/blk-mq.c:170: if (++q->mq_freeze_depth == 1) {
block/blk-mq.c-171- percpu_ref_kill(&q->q_usage_counter);
block/blk-mq.c:172: mutex_unlock(&q->mq_freeze_lock);
block/blk-mq.c-173- if (queue_is_mq(q))
--
block/blk-mq.c-175- } else {
block/blk-mq.c:176: mutex_unlock(&q->mq_freeze_lock);
block/blk-mq.c-177- }
--
block/blk-mq.c=187=EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
block/blk-mq.c-188-
block/blk-mq.c:189:void blk_mq_freeze_queue_wait(struct request_queue *q)
block/blk-mq.c-190-{
block/blk-mq.c:191: wait_event(q->mq_freeze_wq, percpu_ref_is_zero(&q->q_usage_counter));
block/blk-mq.c-192-}
block/blk-mq.c:193:EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait);
block/blk-mq.c-194-
block/blk-mq.c:195:int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
block/blk-mq.c-196- unsigned long timeout)
block/blk-mq.c-197-{
block/blk-mq.c:198: return wait_event_timeout(q->mq_freeze_wq,
block/blk-mq.c-199- percpu_ref_is_zero(&q->q_usage_counter),
--
block/blk-mq.c-201-}
block/blk-mq.c:202:EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait_timeout);
block/blk-mq.c-203-
block/blk-mq.c:204:void blk_mq_freeze_queue_nomemsave(struct request_queue *q)
block/blk-mq.c-205-{
block/blk-mq.c-206- blk_freeze_queue_start(q);
block/blk-mq.c:207: blk_mq_freeze_queue_wait(q);
block/blk-mq.c-208-}
block/blk-mq.c:209:EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_nomemsave);
block/blk-mq.c-210-
block/blk-mq.c=211=bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
--
block/blk-mq.c-214-
block/blk-mq.c:215: mutex_lock(&q->mq_freeze_lock);
block/blk-mq.c-216- if (force_atomic)
block/blk-mq.c-217- q->q_usage_counter.data->force_atomic = true;
block/blk-mq.c:218: q->mq_freeze_depth--;
block/blk-mq.c:219: WARN_ON_ONCE(q->mq_freeze_depth < 0);
block/blk-mq.c:220: if (!q->mq_freeze_depth) {
block/blk-mq.c-221- percpu_ref_resurrect(&q->q_usage_counter);
block/blk-mq.c:222: wake_up_all(&q->mq_freeze_wq);
block/blk-mq.c-223- }
block/blk-mq.c-224- unfreeze = blk_unfreeze_check_owner(q);
block/blk-mq.c:225: mutex_unlock(&q->mq_freeze_lock);
block/blk-mq.c-226-
--
block/blk-mq.c=4328=static void blk_mq_update_tag_set_shared(struct blk_mq_tag_set *set,
--
block/blk-mq.c-4336- list_for_each_entry(q, &set->tag_list, tag_set_list) {
block/blk-mq.c:4337: memflags = blk_mq_freeze_queue(q);
block/blk-mq.c-4338- queue_set_hctx_shared(q, shared);
--
block/blk-mq.c=4483=void blk_mq_destroy_queue(struct request_queue *q)
--
block/blk-mq.c-4491- blk_queue_start_drain(q);
block/blk-mq.c:4492: blk_mq_freeze_queue_wait(q);
block/blk-mq.c-4493-
--
block/blk-mq.c=5165=static void __blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set,
--
block/blk-mq.c-5212- list_for_each_entry(q, &set->tag_list, tag_set_list)
block/blk-mq.c:5213: blk_mq_freeze_queue_nomemsave(q);
block/blk-mq.c-5214- queues_frozen = true;
--
block/blk-mq.c-5246- if (!queues_frozen)
block/blk-mq.c:5247: blk_mq_freeze_queue_nomemsave(q);
block/blk-mq.c-5248- blk_mq_elv_switch_back(q, &elv_tbl);
--
block/blk-rq-qos.c=325=int rq_qos_add(struct rq_qos *rqos, struct gendisk *disk, enum rq_qos_id id,
--
block/blk-rq-qos.c-340- */
block/blk-rq-qos.c:341: memflags = blk_mq_freeze_queue(q);
block/blk-rq-qos.c-342-
--
block/blk-rq-qos.c=356=void rq_qos_del(struct rq_qos *rqos)
--
block/blk-rq-qos.c-363-
block/blk-rq-qos.c:364: memflags = blk_mq_freeze_queue(q);
block/blk-rq-qos.c-365- for (cur = &q->rq_qos; *cur; cur = &(*cur)->next) {
--
block/blk-settings.c=592=int queue_limits_commit_update_frozen(struct request_queue *q,
--
block/blk-settings.c-597-
block/blk-settings.c:598: memflags = blk_mq_freeze_queue(q);
]
|
| 398/2 |
2026/11/03 20:55 |
llm |
patch-planner |
1m
Model:
Tokens:
input: 82846
output: 85
thoughts: 10218
Thoughts: **Analyzing Queue Freeze Lockdep in Block Layer**
Okay, let's break this down. My goal is to understand how the queue freeze mechanism works in the block layer, specifically focusing on the lockdep-related parts in `block/blk-mq.c`, `block/blk.h`, `block/genhd.c`, `block/blk-core.c`, and `include/linux/blkdev.h`. The core idea is to see how we can design the fix, and carefully evaluate each candidate approach!
First, in `block/blk.h`, I see the basic freeze/unfreeze functions declared: `__blk_mq_unfreeze_queue`, `blk_queue_start_drain`, and `__blk_freeze_queue_start`. The `#ifdef CONFIG_LOCKDEP` block is where the lockdep instrumentation comes into play. `blk_freeze_acquire_lock` acquires `io_lockdep_map` and `q_lockdep_map`, and `blk_unfreeze_release_lock` releases these. If lockdep is not enabled, these are just empty functions.
Then in `block/blk-mq.c`, the `blk_freeze_set_owner` and `blk_unfreeze_check_owner` functions are key. They manage the `mq_freeze_depth`, `mq_freeze_owner`, `mq_freeze_owner_depth`, `mq_freeze_disk_dead`, and `mq_freeze_queue_dying` fields within the `request_queue`. These fields track the freeze status and the "owner" of the freeze. `blk_freeze_set_owner` only modifies these fields if `mq_freeze_depth` is zero! `blk_unfreeze_check_owner` verifies that the current task is the owner and decrements the owner depth, and if it is 0 then the owner is set to NULL.
The `__blk_freeze_queue_start` function acquires `mq_freeze_lock`, calls `blk_freeze_set_owner`, and increments the freeze depth. If the depth goes from 0 to 1, the percpu ref counter is killed, and hardware queues are stopped. Then `blk_freeze_acquire_lock` is called. The `__blk_mq_unfreeze_queue` function decrements the depth, resurrects the ref counter if depth goes to 0, checks for the owner, and wakes up waiters.
Now, let's look at `block/genhd.c`, particularly how disk death is handled. The `__blk_mark_disk_dead` function sets the `GD_DEAD` bit, potentially sets `QUEUE_FLAG_DYING`, and calls `blk_queue_start_drain`. This is a crucial area because it introduces potential races. If `GD_OWNS_QUEUE` is true, then `q->mq_freeze_disk_dead` is always true. In `__del_gendisk`, if the disk doesn't own the queue, we unfreeze it. Otherwise, we leave the queue frozen. Critically, `blk_freeze_acquire_lock` is called if `start_drain` is true; and in that case `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead` are also `true`, so no lockdep lock is acquired.
The main concern is `__del_gendisk`, which has the potential race: when do we release `q_lockdep_map` after the queue has been frozen! If `GD_OWNS_QUEUE` is true, then we never unfreeze the queue.
* **Candidate Approach 1: Snapshot `disk_dead` and `queue_dying`**
Let's examine: What if we call `blk_unfreeze_release_lock(q)` inside `blk_unfreeze_check_owner(q)`? Or, what about inside `__blk_mq_unfreeze_queue` while holding `q->mq_freeze_lock`?
If we put `blk_unfreeze_release_lock(q)` inside `__blk_mq_unfreeze_queue`, that would *always* release it under the protection of `q->mq_freeze_lock`, *always*.
Now, let's think about `__del_gendisk(disk)` when `test_bit(GD_OWNS_QUEUE, &disk->state)` is true: In this case, `__blk_mq_unfreeze_queue` is *not* called!
When `GD_OWNS_QUEUE` is true, `__blk_mark_disk_dead(disk)` set `q->mq_freeze_disk_dead` is ALWAYS true, and `q->
|
| 399/2 |
2026/11/03 20:57 |
tool |
grepper |
0m
Args: map[Expression:del_gendisk|blk_mark_disk_dead PathPrefixes:[drivers/block/rbd.c]]
Results: map[Output:drivers/block/rbd.c=7231=static ssize_t do_rbd_remove(const char *buf, size_t count)
--
drivers/block/rbd.c-7285-
drivers/block/rbd.c:7286: blk_mark_disk_dead(rbd_dev->disk);
drivers/block/rbd.c-7287- blk_mq_unfreeze_queue(rbd_dev->disk->queue, memflags);
--
drivers/block/rbd.c-7289-
drivers/block/rbd.c:7290: del_gendisk(rbd_dev->disk);
drivers/block/rbd.c-7291- spin_lock(&rbd_dev_list_lock);
]
|
| 400/2 |
2026/11/03 20:57 |
tool |
read-file |
0m
Args: map[File:drivers/block/rbd.c FirstLine:7100 LineCount:50]
Results: map[Contents:7100: rc = PTR_ERR(rbdc);
7101: goto err_out_args;
7102: }
7103:
7104: /* pick the pool */
7105: rc = ceph_pg_poolid_by_name(rbdc->client->osdc.osdmap, spec->pool_name);
7106: if (rc < 0) {
7107: if (rc == -ENOENT)
7108: pr_info("pool %s does not exist\n", spec->pool_name);
7109: goto err_out_client;
7110: }
7111: spec->pool_id = (u64)rc;
7112:
7113: rbd_dev = rbd_dev_create(rbdc, spec, rbd_opts);
7114: if (!rbd_dev) {
7115: rc = -ENOMEM;
7116: goto err_out_client;
7117: }
7118: rbdc = NULL; /* rbd_dev now owns this */
7119: spec = NULL; /* rbd_dev now owns this */
7120: rbd_opts = NULL; /* rbd_dev now owns this */
7121:
7122: /* if we are mapping a snapshot it will be a read-only mapping */
7123: if (rbd_dev->opts->read_only ||
7124: strcmp(rbd_dev->spec->snap_name, RBD_SNAP_HEAD_NAME))
7125: __set_bit(RBD_DEV_FLAG_READONLY, &rbd_dev->flags);
7126:
7127: rbd_dev->config_info = kstrdup(buf, GFP_KERNEL);
7128: if (!rbd_dev->config_info) {
7129: rc = -ENOMEM;
7130: goto err_out_rbd_dev;
7131: }
7132:
7133: rc = rbd_dev_image_probe(rbd_dev, 0);
7134: if (rc < 0)
7135: goto err_out_rbd_dev;
7136:
7137: if (rbd_dev->opts->alloc_size > rbd_dev->layout.object_size) {
7138: rbd_warn(rbd_dev, "alloc_size adjusted to %u",
7139: rbd_dev->layout.object_size);
7140: rbd_dev->opts->alloc_size = rbd_dev->layout.object_size;
7141: }
7142:
7143: rc = rbd_dev_device_setup(rbd_dev);
7144: if (rc)
7145: goto err_out_image_probe;
7146:
7147: rc = rbd_add_acquire_lock(rbd_dev);
7148: if (rc)
7149: goto err_out_image_lock;
]
|
| 401/2 |
2026/11/03 20:57 |
llm |
patch-planner |
0m
Model:
Tokens:
input: 94218
output: 43
thoughts: 53
Thoughts: Here's my analysis of the provided snippet, framed as a thought process:
**Diving Deep into the RBD Driver**
Okay, hold on a second! I need to zero in on a specific part of the RBD driver. Specifically, I need to understand what's happening around lines 7275-7295 in `drivers/block/rbd.c`. That section is critical, so I'm going to back up a few lines to get more context and encompass lines 7265-7305 in my study of the code. The immediate focus is on the behavior of this part of the driver. Let's see what's going on... I need to understand the logic flow here thoroughly.
|
| 402/2 |
2026/11/03 20:57 |
tool |
read-file |
0m
Args: map[File:drivers/block/rbd.c FirstLine:7265 LineCount:40]
Results: map[Contents:7265: }
7266: if (!ret) {
7267: spin_lock_irq(&rbd_dev->lock);
7268: if (rbd_dev->open_count && !force)
7269: ret = -EBUSY;
7270: else if (test_and_set_bit(RBD_DEV_FLAG_REMOVING,
7271: &rbd_dev->flags))
7272: ret = -EINPROGRESS;
7273: spin_unlock_irq(&rbd_dev->lock);
7274: }
7275: spin_unlock(&rbd_dev_list_lock);
7276: if (ret)
7277: return ret;
7278:
7279: if (force) {
7280: /*
7281: * Prevent new IO from being queued and wait for existing
7282: * IO to complete/fail.
7283: */
7284: unsigned int memflags = blk_mq_freeze_queue(rbd_dev->disk->queue);
7285:
7286: blk_mark_disk_dead(rbd_dev->disk);
7287: blk_mq_unfreeze_queue(rbd_dev->disk->queue, memflags);
7288: }
7289:
7290: del_gendisk(rbd_dev->disk);
7291: spin_lock(&rbd_dev_list_lock);
7292: list_del_init(&rbd_dev->node);
7293: spin_unlock(&rbd_dev_list_lock);
7294: device_del(&rbd_dev->dev);
7295:
7296: rbd_dev_image_unlock(rbd_dev);
7297: rbd_dev_device_release(rbd_dev);
7298: rbd_dev_image_release(rbd_dev);
7299: rbd_dev_destroy(rbd_dev);
7300: return count;
7301: }
7302:
7303: static ssize_t remove_store(const struct bus_type *bus, const char *buf, size_t count)
7304: {
]
|
| 403/2 |
2026/11/03 20:57 |
llm |
patch-planner |
2m
Model:
Tokens:
input: 94952
output: 94
thoughts: 17548
Thoughts: **Deep Dive into Block Layer Freeze/Unfreeze Logic**
My analysis has led me to a critical realization regarding the block layer's queue freeze/unfreeze mechanism. The syzkaller crash, and the rbd deadlock, and potential memory corruption all boil down to the same root issue. The fundamental problem is that the state used to determine if lockdep resources need to be released after a freeze is done in the wrong context.
Specifically, the `mq_freeze_disk_dead` and `mq_freeze_queue_dying` flags within the `request_queue` structure are not properly protected in a way that aligns with the intended lockdep behavior. These flags are set *before* acquiring lockdep resources (or are *not* set when a non-owner freeze happens), and then are read *after* releasing the lock that protects them. This introduces a race condition. When `blk_freeze_queue` is called and then `blk_mark_disk_dead` is called, those flags may be overwritten, and then, at unfreeze time, the *wrong* state is used to determine if the lockdep resources should be released or not, which can lead to a crash or a lockdep leak.
The two main invariants that are *broken* by the existing code are:
1. **Per-Owner Lockdep Symmetry:** The lockdep maps acquired by a freezing task (`q->io_lockdep_map`, `q->q_lockdep_map`) *must* be the exact same maps released during unfreeze. The code currently violates this by allowing modification of the state used to determine whether to release those resources *after* the initial freeze and before the subsequent unfreeze.
2. **Owner vs. Non-Owner Freeze Symmetry:** The block layer conflates the notion of an "owner" and whether a freeze *needs* to be released or not (non-owners do not need to be unfreezed). The `q->mq_freeze_owner` is set when a drain is started. However, the system assumes that the same `current` thread that increments `q->mq_freeze_owner_depth` will decrement it. However, because of the way `blk_mark_disk_dead()` calls `blk_queue_start_drain()` in situations where the queue is never unfrozen. The result is that in situations such as the crash in the `do_rbd_remove` or the syzkaller crash, or `__del_gendisk` when `GD_OWNS_QUEUE` is true, a lock can be leaked.
The current code's design flaw stems from the fact that the flags determining lockdep map release are stored directly in `request_queue` and are read outside of the critical section protected by `q->mq_freeze_lock`. A key aspect of this analysis is that it shows the *existing* code is not written in a manner that ensures that those values are read under the `mq_freeze_lock`. When the depth of the lock is 0, the state variables are overwritten, leading to incorrect lockdep releases during unfreeze. The existing code uses those state variables *after* decrementing the freeze depth.
The analysis shows that the `blk_queue_start_drain()` function should *never* be called with `current` or an *owner*, unless the queue is actually going to be unfrozen and that `current` is *actually* the owner (which does not happen for `blk_mq_destroy_queue`, `blk_mark_disk_dead`, or `__del_gendisk` when `GD_OWNS_QUEUE` is set).
I need to implement a solution that ensures `blk_freeze_acquire_lock()` and `blk_unfreeze_release_lock()` operates with consistent, protected state, based on the **exact state that was in effect when the freeze was established.** This includes properly accounting for cases where the queue is never unfrozen. To address these issues, it is imperative to come up with a design that eliminates the race and ensures the two invariants are never violated, so lockdep resources can never be leaked.
|
| 404/2 |
2026/11/03 21:00 |
tool |
codesearch-find-references |
0m
Args: map[Name:blk_freeze_queue_start]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_mq_freeze_queue_nomemsave SourceFile:block/blk-mq.c SourceLine:206] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_pre_runtime_suspend SourceFile:block/blk-pm.c SourceLine:81] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:nvme_mpath_start_freeze SourceFile:drivers/nvme/host/multipath.c SourceLine:144] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__UNIQUE_ID_addressable_blk_freeze_queue_start_1301 SourceFile:block/blk-mq.c SourceLine:187] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__gendwarfksyms_ptr_blk_freeze_queue_start SourceFile:block/blk-mq.c SourceLine:187] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__gendwarfksyms_ptr_blk_freeze_queue_start SourceFile:block/blk-mq.c SourceLine:187]] TruncatedOutput:false]
|
| 405/2 |
2026/11/03 21:00 |
tool |
codesearch-find-references |
0m
Args: map[Name:blk_freeze_queue_start_non_owner]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:nvme_start_freeze SourceFile:drivers/nvme/host/core.c SourceLine:5418] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__UNIQUE_ID_addressable_blk_freeze_queue_start_non_owner_1308 SourceFile:block/blk-mq.c SourceLine:248] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__gendwarfksyms_ptr_blk_freeze_queue_start_non_owner SourceFile:block/blk-mq.c SourceLine:248] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__gendwarfksyms_ptr_blk_freeze_queue_start_non_owner SourceFile:block/blk-mq.c SourceLine:248]] TruncatedOutput:false]
|
| 406/2 |
2026/11/03 21:00 |
tool |
codesearch-find-references |
0m
Args: map[Name:blk_mq_unfreeze_queue_non_owner]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:nvme_unfreeze SourceFile:drivers/nvme/host/core.c SourceLine:5367] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__UNIQUE_ID_addressable_blk_mq_unfreeze_queue_non_owner_1309 SourceFile:block/blk-mq.c SourceLine:255] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__gendwarfksyms_ptr_blk_mq_unfreeze_queue_non_owner SourceFile:block/blk-mq.c SourceLine:255] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__gendwarfksyms_ptr_blk_mq_unfreeze_queue_non_owner SourceFile:block/blk-mq.c SourceLine:255]] TruncatedOutput:false]
|
| 407/2 |
2026/11/03 21:00 |
llm |
patch-planner |
0m
Model:
Tokens:
input: 113562
output: 81
thoughts: 50
Thoughts: Here's my take:
**Investigating `blk_freeze_queue_start` Usage**
Alright, let's dive into some code. I'm curious about the real-world application of `blk_freeze_queue_start`. My immediate thought is to check two interesting spots: `block/blk-pm.c:81` and `drivers/nvme/host/multipath.c:144`. These seem like good starting points; the first deals with block layer power management, and the second is related to NVMe multipathing, which presents some interesting challenges. It'll be instructive to understand how they specifically employ `blk_freeze_queue_start` in their respective contexts. I'm expecting to uncover some subtle differences and gain insights into best practices in queue management during freeze operations. Time to get my hands dirty!
|
| 408/2 |
2026/11/03 21:01 |
tool |
read-file |
0m
Args: map[File:block/blk-pm.c FirstLine:70 LineCount:35]
Results: map[Contents: 70: spin_unlock_irq(&q->queue_lock);
71:
72: /*
73: * Increase the pm_only counter before checking whether any
74: * non-PM blk_queue_enter() calls are in progress to avoid that any
75: * new non-PM blk_queue_enter() calls succeed before the pm_only
76: * counter is decreased again.
77: */
78: blk_set_pm_only(q);
79: ret = -EBUSY;
80: /* Switch q_usage_counter from per-cpu to atomic mode. */
81: blk_freeze_queue_start(q);
82: /*
83: * Wait until atomic mode has been reached. Since that
84: * involves calling call_rcu(), it is guaranteed that later
85: * blk_queue_enter() calls see the pm-only state. See also
86: * http://lwn.net/Articles/573497/.
87: */
88: percpu_ref_switch_to_atomic_sync(&q->q_usage_counter);
89: if (percpu_ref_is_zero(&q->q_usage_counter))
90: ret = 0;
91: /* Switch q_usage_counter back to per-cpu mode. */
92: blk_mq_unfreeze_queue_nomemrestore(q);
93:
94: if (ret < 0) {
95: spin_lock_irq(&q->queue_lock);
96: q->rpm_status = RPM_ACTIVE;
97: pm_runtime_mark_last_busy(q->dev);
98: spin_unlock_irq(&q->queue_lock);
99:
100: blk_clear_pm_only(q);
101: }
102:
103: return ret;
104: }
]
|
| 409/2 |
2026/11/03 21:01 |
tool |
read-file |
0m
Args: map[File:drivers/nvme/host/multipath.c FirstLine:130 LineCount:30]
Results: map[Contents: 130:
131: lockdep_assert_held(&subsys->lock);
132: list_for_each_entry(h, &subsys->nsheads, entry)
133: if (h->disk)
134: blk_mq_freeze_queue_wait(h->disk->queue);
135: }
136:
137: void nvme_mpath_start_freeze(struct nvme_subsystem *subsys)
138: {
139: struct nvme_ns_head *h;
140:
141: lockdep_assert_held(&subsys->lock);
142: list_for_each_entry(h, &subsys->nsheads, entry)
143: if (h->disk)
144: blk_freeze_queue_start(h->disk->queue);
145: }
146:
147: void nvme_failover_req(struct request *req)
148: {
149: struct nvme_ns *ns = req->q->queuedata;
150: u16 status = nvme_req(req)->status & NVME_SCT_SC_MASK;
151: unsigned long flags;
152: struct bio *bio;
153:
154: nvme_mpath_clear_current_path(ns);
155: atomic_long_inc(&ns->failover);
156:
157: /*
158: * If we got back an ANA error, we know the controller is alive but not
159: * ready to serve this namespace. Kick of a re-read of the ANA
]
|
| 410/2 |
2026/11/03 21:01 |
llm |
patch-planner |
0m
Model:
Tokens:
input: 114727
output: 36
thoughts: 23
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Investigating Callers of `blk_mq_unfreeze_queue_nomemrestore`**
Alright, I'm diving into this `blk_mq_unfreeze_queue_nomemrestore` function again. We're obviously concerned about its behavior, especially related to the "nomemrestore" aspect, so let's tighten the net here. My immediate thought is, beyond understanding *what* the function does and *when* it's called in the code, I need to understand *who* is calling it. A careful examination of all the call sites will be critical. This will help identify any potential misuses or areas where we might be inadvertently introducing subtle memory management problems or unexpected states. I'll need to go through the source code with a fine-toothed comb to identify all direct and indirect callers. Let's get to work!
|
| 411/2 |
2026/11/03 21:01 |
tool |
codesearch-find-references |
0m
Args: map[Name:blk_mq_unfreeze_queue_nomemrestore]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_mq_unfreeze_queue SourceFile:include/linux/blk-mq.h SourceLine:965] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_pre_runtime_suspend SourceFile:block/blk-pm.c SourceLine:92] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:elv_update_nr_hw_queues SourceFile:block/elevator.c SourceLine:714] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:max_number_of_rtt_store SourceFile:drivers/ufs/core/ufs-sysfs.c SourceLine:1661] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:nvme_mpath_unfreeze SourceFile:drivers/nvme/host/multipath.c SourceLine:124] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__UNIQUE_ID_addressable_blk_mq_unfreeze_queue_nomemrestore_1307 SourceFile:block/blk-mq.c SourceLine:235] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__gendwarfksyms_ptr_blk_mq_unfreeze_queue_nomemrestore SourceFile:block/blk-mq.c SourceLine:235] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__gendwarfksyms_ptr_blk_mq_unfreeze_queue_nomemrestore SourceFile:block/blk-mq.c SourceLine:235]] TruncatedOutput:false]
|
| 412/2 |
2026/11/03 21:01 |
llm |
patch-planner |
0m
Model:
Tokens:
input: 115295
output: 45
thoughts: 70
Thoughts: Okay, let's dive into the core of how this NVMe multipathing functionality operates. I need to understand the freezing and unfreezing mechanisms, so I'm heading directly to `drivers/nvme/host/multipath.c`. Specifically, I'm focusing on the functions `nvme_mpath_start_freeze` and `nvme_mpath_unfreeze`. I know these are critical for ensuring data consistency during path changes and potential failovers. I'm going to carefully analyze lines 110 through 146; that's where the heart of these routines should be located, and where I can begin to unravel the logic behind the freeze and unfreeze process. My goal is to grasp the intricacies of how the multipathing driver manages these states to maintain data integrity and availability. I expect to find mechanisms for pausing I/O, synchronizing access, and resuming operations once a path change has been initiated or completed. I'm keen to see if there is any subtle locking, or carefully implemented state management.
|
| 413/2 |
2026/11/03 21:02 |
tool |
read-file |
0m
Args: map[File:drivers/nvme/host/multipath.c FirstLine:110 LineCount:40]
Results: map[Contents: 110: "Default multipath I/O policy; 'numa' (default), 'round-robin' or 'queue-depth'");
111:
112: void nvme_mpath_default_iopolicy(struct nvme_subsystem *subsys)
113: {
114: subsys->iopolicy = iopolicy;
115: }
116:
117: void nvme_mpath_unfreeze(struct nvme_subsystem *subsys)
118: {
119: struct nvme_ns_head *h;
120:
121: lockdep_assert_held(&subsys->lock);
122: list_for_each_entry(h, &subsys->nsheads, entry)
123: if (h->disk)
124: blk_mq_unfreeze_queue_nomemrestore(h->disk->queue);
125: }
126:
127: void nvme_mpath_wait_freeze(struct nvme_subsystem *subsys)
128: {
129: struct nvme_ns_head *h;
130:
131: lockdep_assert_held(&subsys->lock);
132: list_for_each_entry(h, &subsys->nsheads, entry)
133: if (h->disk)
134: blk_mq_freeze_queue_wait(h->disk->queue);
135: }
136:
137: void nvme_mpath_start_freeze(struct nvme_subsystem *subsys)
138: {
139: struct nvme_ns_head *h;
140:
141: lockdep_assert_held(&subsys->lock);
142: list_for_each_entry(h, &subsys->nsheads, entry)
143: if (h->disk)
144: blk_freeze_queue_start(h->disk->queue);
145: }
146:
147: void nvme_failover_req(struct request *req)
148: {
149: struct nvme_ns *ns = req->q->queuedata;
]
|
| 414/2 |
2026/11/03 21:02 |
llm |
patch-planner |
3m
Model:
Tokens:
input: 116052
output: 26
thoughts: 20973
Thoughts: **Analyzing Block Layer Freeze/Unfreeze Logic**
Okay, so I've been diving deep into the block layer, specifically the freeze/unfreeze mechanisms. My goal is to craft the cleanest, most idiomatic fix for a race conditionβparticularly around the interplay of `blk_freeze_acquire_lock`, `blk_unfreeze_release_lock`, and those crucial flags, `mq_freeze_disk_dead` and `mq_freeze_queue_dying`, within the `request_queue` structure. I need to make sure this is robust. I'm focusing on `block/blk-mq.c`, `block/blk.h`, `block/genhd.c`, `block/blk-core.c`, and `include/linux/blkdev.h`.
I'm initially considering two primary approaches. Approach 1 is to call `blk_unfreeze_release_lock(q)` *while still holding* `q->mq_freeze_lock` (or within `blk_unfreeze_check_owner`), versus **Approach 2**, snapshotting the lock state/passing it out from within the functions. It's really the crucial point of how to transmit the relevant state information, such as whether or not the disk or queue is dead, to the functions which release the locks. I'm not sure which is safer, or cleaner, so I need to think carefully!
First, if I call `blk_unfreeze_release_lock(q)` before vs after unlocking `q->mq_freeze_lock` and the interaction with `rwsem_acquire` makes me start thinking about lockdep! I *need* to be sure about the lock order, or I'm going to cause a deadlock! This leads me to believe that `blk_freeze_acquire_lock` MUST be called *outside* the `q->mq_freeze_lock` which means I am going to have to carefully consider the state being read outside of a lock.
The real problem is that I am currently reading `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying` *outside* of the `q->mq_freeze_lock` in `blk_freeze_acquire_lock(q)`. Even if `q->mq_freeze_depth >= 1` normally *prevents* `blk_freeze_set_owner()` from overwriting `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying` *during* the freeze, what about the NVMe non-owner scenario? NVMe is a classic example of something that can break the usual model. That is a *violation* of the basic locking rule!
So, which is bestβ*calling* `blk_unfreeze_release_lock` inside or outside `q->mq_freeze_lock`? If inside, then I am *losing* some lockdep benefits!
Now let's consider approach 2, and what if `__blk_freeze_queue_start()` and `__blk_mq_unfreeze_queue()` (or `blk_freeze_set_owner()` and `blk_unfreeze_check_owner()`) return/pass the lock state! It has two very key attributes: what bits of state are required, and the semantics of the calls!
Then I notice: `blk_freeze_acquire_lock` and `blk_unfreeze_release_lock` are the functions that actually *do* something when a freeze is held! It means `q->io_lockdep_map` is acquired *only if* `!disk_dead` and released *only if* `!disk_dead`! The same is true for `q->q_lockdep_map`, which is related to queue dying status.
This gives me an idea! If I'm careful with returning a bitmask, then I have found a solution:
* I can create a bitmask (or flags) to represent the lockdep locks being acquired/released, instead of the original booleans (`disk_dead`, `queue_dying`).
* In `struct request_queue`, I can use a `mq_freeze_lock_mask` (`unsigned int`) to *store* that bitmask.
With the bitmask, functions can pass around which locks they are going to modify (or not) which seems like a more elegant and reliable solution. It's worth testing how all of this integrates with `blk_mark_disk_dead`, `blk_mq_destroy_queue`, and `__del_gendisk`. I need to be sure there are no races in these functions. It is key to have a solid solution, and by testing the edge cases, I believe I can have a solid lock mask solution!
|
| 415/2 |
2026/11/03 21:05 |
tool |
grepper |
0m
Args: map[Expression:QUEUE_FLAG_DYING]
Results: map[Output:block/blk-mq.c=4483=void blk_mq_destroy_queue(struct request_queue *q)
--
block/blk-mq.c-4489-
block/blk-mq.c:4490: blk_queue_flag_set(QUEUE_FLAG_DYING, q);
block/blk-mq.c-4491- blk_queue_start_drain(q);
--
block/genhd.c=660=static bool __blk_mark_disk_dead(struct gendisk *disk)
--
block/genhd.c-668- if (test_bit(GD_OWNS_QUEUE, &disk->state))
block/genhd.c:669: blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
block/genhd.c-670-
--
block/genhd.c=689=void blk_mark_disk_dead(struct gendisk *disk)
block/genhd.c-690-{
block/genhd.c:691: blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
block/genhd.c-692- __blk_mark_disk_dead(disk);
--
drivers/scsi/scsi_lib.c=488=static void scsi_starved_list_run(struct Scsi_Host *shost)
--
drivers/scsi/scsi_lib.c-529- * function then blk_run_queue() will return immediately since
drivers/scsi/scsi_lib.c:530: * blk_mq_destroy_queue() marks the queue with QUEUE_FLAG_DYING.
drivers/scsi/scsi_lib.c-531- */
--
include/linux/blkdev.h=666=enum {
include/linux/blkdev.h:667: QUEUE_FLAG_DYING, /* queue being torn down */
include/linux/blkdev.h-668- QUEUE_FLAG_NOMERGES, /* disable merge attempts */
--
include/linux/blkdev.h=691=void blk_queue_flag_clear(unsigned int flag, struct request_queue *q);
include/linux/blkdev.h-692-
include/linux/blkdev.h:693:#define blk_queue_dying(q) test_bit(QUEUE_FLAG_DYING, &(q)->queue_flags)
include/linux/blkdev.h-694-#define blk_queue_init_done(q) test_bit(QUEUE_FLAG_INIT_DONE, &(q)->queue_flags)
]
|
| 416/2 |
2026/11/03 21:05 |
llm |
patch-planner-compressor |
3m
Model:
Reply: ### 1. Approaches Investigated & Results
#### Approach A: Fix Device Mapper serialization in `drivers/md/dm.c`
- **Idea**: In `__dm_destroy()`, move `blk_mark_disk_dead(md->disk)` after `while (atomic_read(&md->holders)) fsleep(1000);` or synchronize with `md->type_lock`.
- **Finding/Dead End**: Investigating git commit history (`3b785fbcf81c` and `7a5428dcb790`) revealed that `blk_mark_disk_dead(md->disk)` was intentionally placed at the top of `__dm_destroy()` before draining holders. This is required so that incoming I/O requests are rejected immediately while `__dm_destroy()` waits for holders to drop.
- **Dead End Conclusion**: Altering DM teardown ordering does not address the fundamental block layer bug: any concurrent freeze/unfreeze vs. disk removal / drain on SCSI (`sd_remove`), NVMe (`nvme_mark_namespaces_dead`), RBD (`do_rbd_remove`), or sysfs queue attribute modification (`elevator_change`, `queue_requests_store`) will hit the exact same lockdep race condition. DM is merely the trigger; the defect is inside the block layer queue freeze lockdep tracking.
#### Approach B: Passing `queue_dying` and `disk_dead` out of `__blk_mq_unfreeze_queue()` by value
- **Idea**: Revert to the pre-`f6661b1d0525` / `6f491a8d4b92` pattern of passing booleans across function parameters.
- **Finding**: Ming Lei's series deliberately eliminated boolean arguments across multiple callers (`elevator_init_mq`, `del_gendisk`, `blk_freeze_queue_start`, `blk_mq_unfreeze_queue`) because tracking them per-queue was intended to make verification automatic. Storing them in `struct request_queue` without snapshotting or releasing under `q->mq_freeze_lock` caused the regression.
#### Approach C: Block Layer queue freeze lockdep lifecycle symmetry and race elimination
- **Idea**: Address how `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying` are recorded, protected, and consumed in `block/blk-mq.c`, `block/blk.h`, `block/genhd.c`, and `block/blk-core.c`.
- **Finding**:
1. `blk_unfreeze_release_lock(q)` is currently called in `blk_mq_unfreeze_queue_nomemrestore(q)` *after* `__blk_mq_unfreeze_queue()` has unlocked `q->mq_freeze_lock` and decremented `q->mq_freeze_depth` to 0.
2. Outside the lock, another thread entering `__blk_freeze_queue_start()` immediately overwrites `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead`.
3. Furthermore, `blk_queue_start_drain(q)` (called by `blk_mark_disk_dead`, `blk_mq_destroy_queue`, `__blk_mark_disk_dead`) calls `__blk_freeze_queue_start(q, current)`, which claims `current` as `mq_freeze_owner` and sets `mq_freeze_owner_depth = 1` even when the caller has no intention of unfreezing the queue (or is calling it as non-owner drain).
---
### 2. Verified Facts & Established Conclusions
1. **Lockdep Map Identity**:
- `&q->q_usage_counter(queue)` is `q->q_lockdep_map`.
- `&q->q_usage_counter(io)` is `q->io_lockdep_map`.
- Both are initialized in `blk_alloc_queue()` (`block/blk-core.c:500`).
2. **Acquisition / Release Locations**:
- `blk_freeze_acquire_lock(q)` acquires:
- `q->io_lockdep_map` (exclusive write lock) if `!q->mq_freeze_disk_dead`.
- `q->q_lockdep_map` (exclusive write lock) if `!q->mq_freeze_queue_dying`.
- `blk_unfreeze_release_lock(q)` releases:
- `q->q_lockdep_map` if `!q->mq_freeze_queue_dying`.
- `q->io_lockdep_map` if `!q->mq_freeze_disk_dead`.
- Direct callers of `blk_freeze_acquire_lock(q)`:
- `blk_freeze_queue_start(q)` in `block/blk-mq.c:185`.
- `__del_gendisk(disk)` in `block/genhd.c:732`.
- Direct callers of `blk_unfreeze_release_lock(q)`:
- `blk_mq_unfreeze_queue_nomemrestore(q)` in `block/blk-mq.c:233`.
- `__del_gendisk(disk)` in `block/genhd.c:781`.
3. **Nature of Lockdep Release (`rwsem_release` / `lock_release`)**:
- In `kernel/locking/lockdep.c:5950` (`lock_release()` / `__lock_release()`), releasing a lockdep map does **not** check lock dependencies or record new edges. It only removes the entry from `current->held_locks`.
- Calling `rwsem_release()` while holding `q->mq_freeze_lock` does **not** create an ABBA lockdep dependency against `q->mq_freeze_lock`.
- However, calling `rwsem_acquire()` while holding `q->mq_freeze_lock` **would** create a lock dependency (`mq_freeze_lock` -> `q_lockdep_map`), which could conflict with paths that freeze first and then take `mq_freeze_lock`.
4. **Root Cause Mechanism**:
- In `__blk_mq_unfreeze_queue(q)`:
- `q->mq_freeze_depth` is decremented to 0.
- `blk_unfreeze_check_owner(q)` clears `q->mq_freeze_owner = NULL` and returns `true`.
- `mutex_unlock(&q->mq_freeze_lock)` is executed.
- Concurrently, Thread 2 runs `blk_mark_disk_dead()` -> `__blk_mark_disk_dead()` -> `blk_queue_start_drain()` -> `__blk_freeze_queue_start(q, current)`:
- Acquires `q->mq_freeze_lock`.
- Sees `!q->mq_freeze_depth` (0).
- Overwrites `q->mq_freeze_queue_dying = true` (and `q->mq_freeze_disk_dead = true`).
- Increments `q->mq_freeze_depth = 1`.
- Drops `q->mq_freeze_lock`.
- Thread 1 runs `blk_unfreeze_release_lock(q)` outside `q->mq_freeze_lock`:
- Reads `q->mq_freeze_queue_dying`, which is now `true`.
- Skips `rwsem_release(&q->q_lockdep_map, _RET_IP_)`.
- Leaves kernel with `q->q_lockdep_map` held in lockdep.
5. **Drain Context Asymmetry in `blk_queue_start_drain()`**:
- `blk_queue_start_drain()` in `block/blk-core.c:334` calls `__blk_freeze_queue_start(q, current)`.
- This sets `q->mq_freeze_owner = current`.
- But `blk_queue_start_drain()` is used for draining before queue destruction or disk dead (`blk_mq_destroy_queue`, `__blk_mark_disk_dead`). It is not paired with a regular owner unfreeze.
- When called via `del_gendisk()` on disks with `GD_OWNS_QUEUE`, `__del_gendisk()` intentionally leaves the queue frozen (`q->mq_freeze_depth == 1`) and calls `blk_unfreeze_release_lock(q)` without unfreezing.
---
### 3. Critical Files, Functions, and Struct Fields
- **`include/linux/blkdev.h`**:
```c
struct request_queue {
#ifdef CONFIG_LOCKDEP
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
bool mq_freeze_disk_dead;
bool mq_freeze_queue_dying;
#endif
...
int mq_freeze_depth;
struct mutex mq_freeze_lock;
```
- **`block/blk.h`**:
```c
#ifdef CONFIG_LOCKDEP
static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
if (!q->mq_freeze_queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
#endif
```
- **`block/blk-mq.c`**:
- `blk_freeze_set_owner()` (`lines 116-135`)
- `blk_unfreeze_check_owner()` (`lines 138-147`)
- `__blk_freeze_queue_start()` (`lines 163-180`)
- `blk_freeze_queue_start()` (`lines 182-187`)
- `__blk_mq_unfreeze_queue()` (`lines 211-228`)
- `blk_mq_unfreeze_queue_nomemrestore()` (`lines 230-235`)
- **`block/blk-core.c`**:
- `blk_queue_start_drain()` (`lines 327-341`): calls `__blk_freeze_queue_start(q, current)`
- **`block/genhd.c`**:
- `__blk_mark_disk_dead()` (`lines 660-680`)
- `__del_gendisk()` (`lines 697-782`)
---
### 4. Active Investigation & Fix Hypotheses
#### Core Hypothesis: Releasing Lockdep Map or Snapshotting State Under `q->mq_freeze_lock`
The race window exists because `blk_unfreeze_release_lock(q)` reads `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead` after `q->mq_freeze_lock` is unlocked and after `q->mq_freeze_depth` has become 0.
Two candidate variations for the single standalone patch:
1. **Variation 1: Release lockdep map inside `q->mq_freeze_lock` before dropping freeze depth / unlocking**:
- In `blk_unfreeze_check_owner(q)`: when `q->mq_freeze_owner == current` and `--q->mq_freeze_owner_depth == 0`:
Call `blk_unfreeze_release_lock(q)` right there, while `q->mq_freeze_lock` is still held!
- Because `q->mq_freeze_lock` is still held, no other task can enter `blk_freeze_set_owner()` to overwrite `q->mq_freeze_queue_dying` or `q->mq_freeze_disk_dead`.
- `rwsem_release()` simply untracks the held lock from `current->held_locks`.
- Check interaction with `__del_gendisk()`: in `__del_gendisk()`, if `start_drain` is true, does it call `blk_unfreeze_release_lock(q)`? If `__blk_mq_unfreeze_queue()` handles the release when owner depth drops to 0, what does `__del_gendisk()` do when `test_bit(GD_OWNS_QUEUE, &disk->state)` is true?
2. **Variation 2: Snapshot `queue_dying` and `disk_dead` under `q->mq_freeze_lock` or preserve them in per-task or stack state**:
- Snapshot the boolean flags inside `q->mq_freeze_lock` before unlocking, and pass them to `blk_unfreeze_release_lock()`, or
- Return a bitmask/struct from `__blk_mq_unfreeze_queue()` containing whether to release and which maps to release, or
- In `__blk_mq_unfreeze_queue(q)`: if `blk_unfreeze_check_owner(q)` returns true, execute `blk_unfreeze_release_lock(q)` before `mutex_unlock(&q->mq_freeze_lock)`.
#### Additionally: Audit of `blk_queue_start_drain()`
- In `blk_queue_start_drain(q)`, commit `6a78699838a0` changed `__blk_freeze_queue_start(q)` to `__blk_freeze_queue_start(q, current)`.
- But `blk_queue_start_drain()` is called from `blk_mq_destroy_queue(q)` and `__blk_mark_disk_dead(disk)`.
- If `blk_queue_start_drain()` passes `current`, it sets `q->mq_freeze_owner = current` without ever acquiring the lockdep lock (no `blk_freeze_acquire_lock()` call in `blk_queue_start_drain()`).
- In `__del_gendisk()`, if `start_drain` is true, `blk_freeze_acquire_lock(q)` is called after `__blk_mark_disk_dead(disk)`. But by then, `__blk_mark_disk_dead()` had already called `__blk_freeze_queue_start(q, current)`.
- Need to check if `blk_queue_start_drain(q)` should pass `NULL` as owner or how `start_drain` in `__del_gendisk` interacts.
---
### 5. Watch-outs & Anti-Patterns to Avoid
- **Do NOT alter DM `__dm_destroy()` ordering**: Changing DM holder waiting order breaks early I/O rejection during removal and does not fix the block layer bug for all other drivers.
- **Do NOT add defensive sentinel guards** like `if (in_table_load) ...` or local boolean checks in DM.
- **Do NOT acquire lockdep maps under `q->mq_freeze_lock`**: `rwsem_acquire()` under `q->mq_freeze_lock` would invert lock ordering against any caller that freezes the queue and later acquires `q->mq_freeze_lock` (or other locks).
- Releasing lockdep maps (`rwsem_release()`) under `q->mq_freeze_lock` is safe because `lock_release()` has no lock dependency graph side effects.
---
### 6. Concrete Next Steps
1. **Verify lockdep release placement inside `__blk_mq_unfreeze_queue`**:
- Check if moving `blk_unfreeze_release_lock(q)` into `__blk_mq_unfreeze_queue()` under `q->mq_freeze_lock` cleanly handles all unfreeze callers (`blk_mq_unfreeze_queue_nomemrestore`, `blk_mq_unfreeze_queue`, `del_gendisk`).
2. **Audit `del_gendisk()` path in `block/genhd.c`**:
- Check lines 730-732 and 775-782 in `block/genhd.c`.
- Determine how `start_drain` and `test_bit(GD_OWNS_QUEUE, &disk->state)` interact with `blk_unfreeze_check_owner()` and `blk_unfreeze_release_lock()`.
3. **Draft the exact patch plan**:
- Specify the exact struct, file, and function changes across `block/blk-mq.c`, `block/blk.h`, and `block/genhd.c`.
- Verify all callers of modified functions and ensure no lockdep imbalance or ABI changes.
Tokens:
input: 81001
output: 3910
thoughts: 0
|
| 417/2 |
2026/11/03 21:08 |
llm |
patch-planner |
0m
Model:
Tokens:
input: 40717
output: 151
thoughts: 213
Thoughts: Okay, here's my breakdown of what's going on, thinking it through:
**Investigating the `QUEUE_FLAG_DYING` Flag in the Kernel**
Alright, I need to get to the bottom of how this `QUEUE_FLAG_DYING` flag is being used. My immediate task is to identify where in the kernel this flag gets set, because that will tell me when a block device is going into a dying state, or at least being marked as such. I see that there are only **three** locations where this crucial flag is being manipulated. The first is in `block/blk-mq.c` within the `blk_mq_destroy_queue(q)` function. The second two locations appear to be in `block/genhd.c`: The first one in `__blk_mark_disk_dead(disk)`, triggered when `test_bit(GD_OWNS_QUEUE, &disk->state)` is true, and the third location in the same file `blk_mark_disk_dead(disk)`.
Now, to get a clear and complete picture, I know I have to dive into the code. I'm going to pull up and carefully review `block/blk-mq.c` lines 110-245, `block/blk.h` lines 710-740, `block/genhd.c` lines 655-785, and also `block/blk-core.c` lines 320-345. I need those exact line numbers and the surrounding code context to fully understand the logic that leads to this flag being set and what implications are. That should give me the full story.
|
| 418/2 |
2026/11/03 21:08 |
tool |
read-file |
0m
Args: map[File:block/blk-mq.c FirstLine:110 LineCount:135]
Results: map[Contents: 110: &mi);
111: inflight[READ] = mi.inflight[READ];
112: inflight[WRITE] = mi.inflight[WRITE];
113: }
114:
115: #ifdef CONFIG_LOCKDEP
116: static bool blk_freeze_set_owner(struct request_queue *q,
117: struct task_struct *owner)
118: {
119: if (!owner)
120: return false;
121:
122: if (!q->mq_freeze_depth) {
123: q->mq_freeze_owner = owner;
124: q->mq_freeze_owner_depth = 1;
125: q->mq_freeze_disk_dead = !q->disk ||
126: test_bit(GD_DEAD, &q->disk->state) ||
127: !blk_queue_registered(q);
128: q->mq_freeze_queue_dying = blk_queue_dying(q);
129: return true;
130: }
131:
132: if (owner == q->mq_freeze_owner)
133: q->mq_freeze_owner_depth += 1;
134: return false;
135: }
136:
137: /* verify the last unfreeze in owner context */
138: static bool blk_unfreeze_check_owner(struct request_queue *q)
139: {
140: if (q->mq_freeze_owner != current)
141: return false;
142: if (--q->mq_freeze_owner_depth == 0) {
143: q->mq_freeze_owner = NULL;
144: return true;
145: }
146: return false;
147: }
148:
149: #else
150:
151: static bool blk_freeze_set_owner(struct request_queue *q,
152: struct task_struct *owner)
153: {
154: return false;
155: }
156:
157: static bool blk_unfreeze_check_owner(struct request_queue *q)
158: {
159: return false;
160: }
161: #endif
162:
163: bool __blk_freeze_queue_start(struct request_queue *q,
164: struct task_struct *owner)
165: {
166: bool freeze;
167:
168: mutex_lock(&q->mq_freeze_lock);
169: freeze = blk_freeze_set_owner(q, owner);
170: if (++q->mq_freeze_depth == 1) {
171: percpu_ref_kill(&q->q_usage_counter);
172: mutex_unlock(&q->mq_freeze_lock);
173: if (queue_is_mq(q))
174: blk_mq_run_hw_queues(q, false);
175: } else {
176: mutex_unlock(&q->mq_freeze_lock);
177: }
178:
179: return freeze;
180: }
181:
182: void blk_freeze_queue_start(struct request_queue *q)
183: {
184: if (__blk_freeze_queue_start(q, current))
185: blk_freeze_acquire_lock(q);
186: }
187: EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
188:
189: void blk_mq_freeze_queue_wait(struct request_queue *q)
190: {
191: wait_event(q->mq_freeze_wq, percpu_ref_is_zero(&q->q_usage_counter));
192: }
193: EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait);
194:
195: int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
196: unsigned long timeout)
197: {
198: return wait_event_timeout(q->mq_freeze_wq,
199: percpu_ref_is_zero(&q->q_usage_counter),
200: timeout);
201: }
202: EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait_timeout);
203:
204: void blk_mq_freeze_queue_nomemsave(struct request_queue *q)
205: {
206: blk_freeze_queue_start(q);
207: blk_mq_freeze_queue_wait(q);
208: }
209: EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_nomemsave);
]
|
| 419/2 |
2026/11/03 21:08 |
tool |
read-file |
0m
Args: map[File:block/blk.h FirstLine:710 LineCount:35]
Results: map[Contents: 710: *
711: * abc54d634334 ("io_uring: switch to atomic_t for io_kiocb reference count")
712: */
713: #define req_ref_zero_or_close_to_overflow(req) \
714: ((unsigned int) atomic_read(&(req->ref)) + 127u <= 127u)
715:
716: static inline bool req_ref_inc_not_zero(struct request *req)
717: {
718: return atomic_inc_not_zero(&req->ref);
719: }
720:
721: static inline bool req_ref_put_and_test(struct request *req)
722: {
723: WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
724: return atomic_dec_and_test(&req->ref);
725: }
726:
727: static inline void req_ref_set(struct request *req, int value)
728: {
729: atomic_set(&req->ref, value);
730: }
731:
732: static inline int req_ref_read(struct request *req)
733: {
734: return atomic_read(&req->ref);
735: }
736:
737: static inline u64 blk_time_get_ns(void)
738: {
739: struct blk_plug *plug = current->plug;
740: u64 now;
741:
742: if (!plug || !in_task())
743: return ktime_get_ns();
744:
]
|
| 420/2 |
2026/11/03 21:08 |
tool |
read-file |
0m
Args: map[File:block/genhd.c FirstLine:655 LineCount:130]
Results: map[Contents: 655: rcu_read_lock();
656: }
657: rcu_read_unlock();
658: }
659:
660: static bool __blk_mark_disk_dead(struct gendisk *disk)
661: {
662: /*
663: * Fail any new I/O.
664: */
665: if (test_and_set_bit(GD_DEAD, &disk->state))
666: return false;
667:
668: if (test_bit(GD_OWNS_QUEUE, &disk->state))
669: blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
670:
671: /*
672: * Stop buffered writers from dirtying pages that can't be written out.
673: */
674: set_capacity(disk, 0);
675:
676: /*
677: * Prevent new I/O from crossing bio_queue_enter().
678: */
679: return blk_queue_start_drain(disk->queue);
680: }
681:
682: /**
683: * blk_mark_disk_dead - mark a disk as dead
684: * @disk: disk to mark as dead
685: *
686: * Mark as disk as dead (e.g. surprise removed) and don't accept any new I/O
687: * to this disk.
688: */
689: void blk_mark_disk_dead(struct gendisk *disk)
690: {
691: blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
692: __blk_mark_disk_dead(disk);
693: blk_report_disk_dead(disk, true);
694: }
695: EXPORT_SYMBOL_GPL(blk_mark_disk_dead);
696:
697: static void __del_gendisk(struct gendisk *disk)
698: {
699: struct request_queue *q = disk->queue;
700: struct block_device *part;
701: unsigned long idx;
702: bool start_drain;
703:
704: might_sleep();
705:
706: if (WARN_ON_ONCE(!disk_live(disk) && !(disk->flags & GENHD_FL_HIDDEN)))
707: return;
708:
709: disk_del_events(disk);
710:
711: /*
712: * Prevent new openers by unlinked the bdev inode.
713: */
714: mutex_lock(&disk->open_mutex);
715: xa_for_each(&disk->part_tbl, idx, part)
716: bdev_unhash(part);
717: mutex_unlock(&disk->open_mutex);
718:
719: /*
720: * Tell the file system to write back all dirty data and shut down if
721: * it hasn't been notified earlier.
722: */
723: if (!test_bit(GD_DEAD, &disk->state))
724: blk_report_disk_dead(disk, false);
725:
726: /*
727: * Drop all partitions now that the disk is marked dead.
728: */
729: mutex_lock(&disk->open_mutex);
730: start_drain = __blk_mark_disk_dead(disk);
731: if (start_drain)
732: blk_freeze_acquire_lock(q);
733: xa_for_each_start(&disk->part_tbl, idx, part, 1)
734: drop_partition(part);
735: mutex_unlock(&disk->open_mutex);
736:
737: if (!(disk->flags & GENHD_FL_HIDDEN)) {
738: sysfs_remove_link(&disk_to_dev(disk)->kobj, "bdi");
739:
740: /*
741: * Unregister bdi before releasing device numbers (as they can
742: * get reused and we'd get clashes in sysfs).
743: */
744: bdi_unregister(disk->bdi);
745: }
746:
747: blk_unregister_queue(disk);
748:
749: kobject_put(disk->part0->bd_holder_dir);
750: kobject_put(disk->slave_dir);
751: disk->slave_dir = NULL;
752:
753: part_stat_set_all(disk->part0, 0);
754: disk->part0->bd_stamp = 0;
]
|
| 421/2 |
2026/11/03 21:08 |
tool |
read-file |
0m
Args: map[File:block/blk-core.c FirstLine:320 LineCount:25]
Results: map[Contents: 320: void blk_put_queue(struct request_queue *q)
321: {
322: if (refcount_dec_and_test(&q->refs))
323: blk_free_queue(q);
324: }
325: EXPORT_SYMBOL(blk_put_queue);
326:
327: bool blk_queue_start_drain(struct request_queue *q)
328: {
329: /*
330: * When queue DYING flag is set, we need to block new req
331: * entering queue, so we call blk_freeze_queue_start() to
332: * prevent I/O from crossing blk_queue_enter().
333: */
334: bool freeze = __blk_freeze_queue_start(q, current);
335: if (queue_is_mq(q))
336: blk_mq_wake_waiters(q);
337: /* Make blk_queue_enter() reexamine the DYING flag. */
338: wake_up_all(&q->mq_freeze_wq);
339:
340: return freeze;
341: }
342:
343: /**
344: * blk_queue_enter() - try to increase q->q_usage_counter
]
|
| 422/2 |
2026/11/03 21:08 |
llm |
patch-planner |
0m
Model:
Tokens:
input: 44891
output: 150
thoughts: 79
Thoughts: Okay, here's my take on those specific code sections, as a seasoned expert:
**Diving Deep into the Block Layer**
Alright, let's get down to brass tacks. I'm going to quickly refresh my memory on some key areas of the block layer. Specifically, I'm thinking about those lines in `block/blk.h` (740-775), that'll probably be about request handling and potentially some of the core data structures, likely the `request_queue` and associated structures and how they are handled. Then I want to jump over to `block/blk-mq.c` (210-250); I'm guessing this might deal with some of the multi-queue setup or maybe some of the dispatch logic for block-mq. It'll be essential to understand the modern multi-queue implementation. I know that's where the interesting stuff is happening these days. I'll probably focus on any lock implementations and how that has changed between the implementations. Next, I'm shifting to `block/genhd.c` (750-788). This is probably related to the generic hard disk driver interface, so I want to understand how devices are registered, how the gendisk structure is used, and how it interfaces with the lower layers. I know there are some interesting subtleties with partitions and device naming there. Finally, I'll need a refresher on the relevant definitions within `include/linux/blkdev.h` (390-420). This is the key header for understanding the interfaces and data structures. I'll need to check the exact definitions of the `request` structure, any new queuing APIs, and anything related to bio structures, as that's often where the core of I/O operations are described. By reviewing these specific sections I'll get a really comprehensive overview of the current block layer design.
|
| 423/2 |
2026/11/03 21:09 |
tool |
read-file |
0m
Args: map[File:block/blk.h FirstLine:740 LineCount:45]
Results: map[Contents: 740: u64 now;
741:
742: if (!plug || !in_task())
743: return ktime_get_ns();
744:
745: /*
746: * 0 could very well be a valid time, but rather than flag "this is
747: * a valid timestamp" separately, just accept that we'll do an extra
748: * ktime_get_ns() if we just happen to get 0 as the current time.
749: *
750: * cur_ktime can be zeroed by pre-emption the moment PF_BLOCK_TS is set.
751: */
752: now = READ_ONCE(plug->cur_ktime);
753: if (!now) {
754: now = ktime_get_ns();
755: WRITE_ONCE(plug->cur_ktime, now);
756: /* Ensure PF_BLOCK_TS is set after cur_ktime. */
757: barrier();
758: current->flags |= PF_BLOCK_TS;
759: }
760: return now;
761: }
762:
763: static inline ktime_t blk_time_get(void)
764: {
765: return ns_to_ktime(blk_time_get_ns());
766: }
767:
768: void bdev_release(struct file *bdev_file);
769: int bdev_open(struct block_device *bdev, blk_mode_t mode, void *holder,
770: const struct blk_holder_ops *hops, struct file *bdev_file);
771: int bdev_permission(dev_t dev, blk_mode_t mode, void *holder);
772:
773: void bio_integrity_generate(struct bio *bio);
774: blk_status_t bio_integrity_verify(struct bio *bio,
775: struct bvec_iter *saved_iter);
776:
777: void blk_integrity_prepare(struct request *rq);
778: void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
779:
780: #ifdef CONFIG_LOCKDEP
781: static inline void blk_freeze_acquire_lock(struct request_queue *q)
782: {
783: if (!q->mq_freeze_disk_dead)
784: rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
]
|
| 424/2 |
2026/11/03 21:09 |
tool |
read-file |
0m
Args: map[File:block/blk-mq.c FirstLine:210 LineCount:40]
Results: map[Contents: 210:
211: bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
212: {
213: bool unfreeze;
214:
215: mutex_lock(&q->mq_freeze_lock);
216: if (force_atomic)
217: q->q_usage_counter.data->force_atomic = true;
218: q->mq_freeze_depth--;
219: WARN_ON_ONCE(q->mq_freeze_depth < 0);
220: if (!q->mq_freeze_depth) {
221: percpu_ref_resurrect(&q->q_usage_counter);
222: wake_up_all(&q->mq_freeze_wq);
223: }
224: unfreeze = blk_unfreeze_check_owner(q);
225: mutex_unlock(&q->mq_freeze_lock);
226:
227: return unfreeze;
228: }
229:
230: void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
231: {
232: if (__blk_mq_unfreeze_queue(q, false))
233: blk_unfreeze_release_lock(q);
234: }
235: EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_nomemrestore);
236:
237: /*
238: * non_owner variant of blk_freeze_queue_start
239: *
240: * Unlike blk_freeze_queue_start, the queue doesn't need to be unfrozen
241: * by the same task. This is fragile and should not be used if at all
242: * possible.
243: */
244: void blk_freeze_queue_start_non_owner(struct request_queue *q)
245: {
246: __blk_freeze_queue_start(q, NULL);
247: }
248: EXPORT_SYMBOL_GPL(blk_freeze_queue_start_non_owner);
249:
]
|
| 425/2 |
2026/11/03 21:09 |
tool |
read-file |
0m
Args: map[File:block/genhd.c FirstLine:750 LineCount:40]
Results: map[Contents: 750: kobject_put(disk->slave_dir);
751: disk->slave_dir = NULL;
752:
753: part_stat_set_all(disk->part0, 0);
754: disk->part0->bd_stamp = 0;
755: sysfs_remove_link(block_depr, dev_name(disk_to_dev(disk)));
756: pm_runtime_set_memalloc_noio(disk_to_dev(disk), false);
757: device_del(disk_to_dev(disk));
758:
759: blk_mq_freeze_queue_wait(q);
760:
761: blk_throtl_cancel_bios(disk);
762:
763: blk_sync_queue(q);
764: blk_flush_integrity();
765:
766: if (queue_is_mq(q))
767: blk_mq_cancel_work_sync(q);
768:
769: rq_qos_exit(q);
770:
771: /*
772: * If the disk does not own the queue, allow using passthrough requests
773: * again. Else leave the queue frozen to fail all I/O.
774: */
775: if (!test_bit(GD_OWNS_QUEUE, &disk->state))
776: __blk_mq_unfreeze_queue(q, true);
777: else if (queue_is_mq(q))
778: blk_mq_exit_queue(q);
779:
780: if (start_drain)
781: blk_unfreeze_release_lock(q);
782: }
783:
784: static void disable_elv_switch(struct request_queue *q)
785: {
786: struct blk_mq_tag_set *set = q->tag_set;
787: WARN_ON_ONCE(!queue_is_mq(q));
788:
789: down_write(&set->update_nr_hwq_lock);
]
|
| 426/2 |
2026/11/03 21:09 |
tool |
read-file |
0m
Args: map[File:include/linux/blkdev.h FirstLine:390 LineCount:35]
Results: map[Contents: 390: unsigned int max_dev_sectors;
391: unsigned int chunk_sectors;
392: unsigned int max_sectors;
393: unsigned int max_user_sectors;
394: unsigned int max_segment_size;
395: unsigned int max_fast_segment_size;
396: unsigned int physical_block_size;
397: unsigned int logical_block_size;
398: unsigned int alignment_offset;
399: unsigned int io_min;
400: unsigned int io_opt;
401: unsigned int max_discard_sectors;
402: unsigned int max_hw_discard_sectors;
403: unsigned int max_user_discard_sectors;
404: unsigned int max_secure_erase_sectors;
405: unsigned int max_write_zeroes_sectors;
406: unsigned int max_wzeroes_unmap_sectors;
407: unsigned int max_hw_wzeroes_unmap_sectors;
408: unsigned int max_user_wzeroes_unmap_sectors;
409: unsigned int max_hw_zone_append_sectors;
410: unsigned int max_zone_append_sectors;
411: unsigned int discard_granularity;
412: unsigned int discard_alignment;
413: unsigned int zone_write_granularity;
414:
415: /* atomic write limits */
416: unsigned int atomic_write_hw_max;
417: unsigned int atomic_write_max_sectors;
418: unsigned int atomic_write_hw_boundary;
419: unsigned int atomic_write_boundary_sectors;
420: unsigned int atomic_write_hw_unit_min;
421: unsigned int atomic_write_unit_min;
422: unsigned int atomic_write_hw_unit_max;
423: unsigned int atomic_write_unit_max;
424:
]
|
| 427/2 |
2026/11/03 21:09 |
llm |
patch-planner |
0m
Model:
Tokens:
input: 47740
output: 77
thoughts: 65
Thoughts: Here's my take on the thought process, as requested:
**Diving Deeper into Block Device Implementation**
Okay, so we're looking to understand this block device behavior better, and I think we need to get granular. To really grasp the interplay here, I'm going to pull up some specific header files and line numbers. I need to zero in on exactly what's going on at the code level. Specifically, I'm thinking we should examine `block/blk.h`, lines 780 through 810, and also take a look at `include/linux/blkdev.h`, focusing on lines 550 to 610. That should give me a solid view of the pertinent structures, definitions, and any relevant function prototypes that contribute to the function in question. Knowing those particular lines should illuminate the specific interactions we're interested in, and offer a precise understanding to my current problem.
|
| 428/2 |
2026/11/03 21:09 |
tool |
read-file |
0m
Args: map[File:block/blk.h FirstLine:780 LineCount:35]
Results: map[Contents: 780: #ifdef CONFIG_LOCKDEP
781: static inline void blk_freeze_acquire_lock(struct request_queue *q)
782: {
783: if (!q->mq_freeze_disk_dead)
784: rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
785: if (!q->mq_freeze_queue_dying)
786: rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
787: }
788:
789: static inline void blk_unfreeze_release_lock(struct request_queue *q)
790: {
791: if (!q->mq_freeze_queue_dying)
792: rwsem_release(&q->q_lockdep_map, _RET_IP_);
793: if (!q->mq_freeze_disk_dead)
794: rwsem_release(&q->io_lockdep_map, _RET_IP_);
795: }
796: #else
797: static inline void blk_freeze_acquire_lock(struct request_queue *q)
798: {
799: }
800: static inline void blk_unfreeze_release_lock(struct request_queue *q)
801: {
802: }
803: #endif
804:
805: /*
806: * debugfs directory and file creation can trigger fs reclaim, which can enter
807: * back into the block layer request_queue. This can cause deadlock if the
808: * queue is frozen. Use NOIO context together with debugfs_mutex to prevent fs
809: * reclaim from triggering block I/O.
810: */
811: static inline void blk_debugfs_lock_nomemsave(struct request_queue *q)
812: __acquires(&q->debugfs_mutex)
813: {
814: mutex_lock(&q->debugfs_mutex);
]
|
| 429/2 |
2026/11/03 21:09 |
tool |
read-file |
0m
Args: map[File:include/linux/blkdev.h FirstLine:550 LineCount:60]
Results: map[Contents: 550: */
551: atomic_t pm_only;
552:
553: struct blk_queue_stats *stats;
554: struct rq_qos *rq_qos;
555: struct mutex rq_qos_mutex;
556:
557: /*
558: * ida allocated id for this queue. Used to index queues from
559: * ioctx.
560: */
561: int id;
562:
563: /*
564: * queue settings
565: */
566: unsigned int nr_requests; /* Max # of requests */
567: unsigned int async_depth; /* Max # of async requests */
568:
569: #ifdef CONFIG_BLK_INLINE_ENCRYPTION
570: struct blk_crypto_profile *crypto_profile;
571: struct kobject *crypto_kobject;
572: #endif
573:
574: struct timer_list timeout;
575: struct work_struct timeout_work;
576:
577: atomic_t nr_active_requests_shared_tags;
578:
579: struct blk_mq_tags *sched_shared_tags;
580:
581: struct list_head icq_list;
582: #ifdef CONFIG_BLK_CGROUP
583: DECLARE_BITMAP (blkcg_pols, BLKCG_MAX_POLS);
584: struct blkcg_gq *root_blkg;
585: struct list_head blkg_list;
586: struct mutex blkcg_mutex;
587: #endif
588:
589: int node;
590:
591: spinlock_t requeue_lock;
592: struct list_head requeue_list;
593: struct delayed_work requeue_work;
594:
595: #ifdef CONFIG_BLK_DEV_IO_TRACE
596: struct blk_trace __rcu *blk_trace;
597: #endif
598: /*
599: * for flush operations
600: */
601: struct blk_flush_queue *fq;
602: struct list_head flush_list;
603:
604: /*
605: * Protects against I/O scheduler switching, particularly when updating
606: * q->elevator. Since the elevator update code path may also modify q->
607: * nr_requests and wbt latency, this lock also protects the sysfs attrs
608: * nr_requests and wbt_lat_usec. Additionally the nr_hw_queues update
609: * may modify hctx tags, reserved-tags and cpumask, so this lock also
]
|
| 430/2 |
2026/11/03 21:09 |
llm |
patch-planner |
0m
Model:
Tokens:
input: 49326
output: 76
thoughts: 48
Thoughts: Here's my take on the thought process:
**Diving into Block Device Declarations**
Alright, to get a solid grasp on how this all hangs together, I need to dig into the actual code. Specifically, I'm thinking I should start by looking at the declarations. I want to see the key structures and functions that are defined for block devices. My immediate thought is to check out `include/linux/blkdev.h`, specifically lines 610 through 665. That should give me a good chunk of the core definitions related to the block layer. Then, to get a broader picture of the block layer, I'll need to expand my search to `block/blk.h` and scan lines 50-100 to compare and contrast the different definitions. This seems like a reasonable way to start. That should provide a useful overview of the key structures and declarations, setting the stage for a deeper dive later.
|
| 431/2 |
2026/11/03 21:09 |
tool |
read-file |
0m
Args: map[File:include/linux/blkdev.h FirstLine:610 LineCount:55]
Results: map[Contents: 610: * helps protect the hctx sysfs/debugfs attrs. To ensure proper locking
611: * order during an elevator or nr_hw_queue update, first freeze the
612: * queue, then acquire ->elevator_lock.
613: */
614: struct mutex elevator_lock;
615:
616: struct mutex sysfs_lock;
617: /*
618: * Protects queue limits and also sysfs attribute read_ahead_kb.
619: */
620: struct mutex limits_lock;
621:
622: /*
623: * for reusing dead hctx instance in case of updating
624: * nr_hw_queues
625: */
626: struct list_head unused_hctx_list;
627: spinlock_t unused_hctx_lock;
628:
629: int mq_freeze_depth;
630:
631: #ifdef CONFIG_BLK_DEV_THROTTLING
632: /* Throttle data */
633: struct throtl_data *td;
634: #endif
635: struct rcu_head rcu_head;
636: #ifdef CONFIG_LOCKDEP
637: struct task_struct *mq_freeze_owner;
638: int mq_freeze_owner_depth;
639: /*
640: * Records disk & queue state in current context, used in unfreeze
641: * queue
642: */
643: bool mq_freeze_disk_dead;
644: bool mq_freeze_queue_dying;
645: #endif
646: wait_queue_head_t mq_freeze_wq;
647: /*
648: * Protect concurrent access to q_usage_counter by
649: * percpu_ref_kill() and percpu_ref_reinit().
650: */
651: struct mutex mq_freeze_lock;
652:
653: struct blk_mq_tag_set *tag_set;
654: struct list_head tag_set_list;
655:
656: struct dentry *debugfs_dir;
657: struct dentry *sched_debugfs_dir;
658: struct dentry *rqos_debugfs_dir;
659: /*
660: * Serializes all debugfs metadata operations using the above dentries.
661: */
662: struct mutex debugfs_mutex;
663: };
664:
]
|
| 432/2 |
2026/11/03 21:09 |
tool |
read-file |
0m
Args: map[File:block/blk.h FirstLine:50 LineCount:65]
Results: map[Contents: 50: gfp_t flags);
51: void blk_free_flush_queue(struct blk_flush_queue *q);
52:
53: const char *blk_status_to_str(blk_status_t status);
54: const char *blk_status_to_tag(blk_status_t status);
55: blk_status_t tag_to_blk_status(const char *tag);
56: enum req_op str_to_blk_op(const char *op);
57:
58: bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
59: bool blk_queue_start_drain(struct request_queue *q);
60: bool __blk_freeze_queue_start(struct request_queue *q,
61: struct task_struct *owner);
62: int __bio_queue_enter(struct request_queue *q, struct bio *bio);
63: void submit_bio_noacct_nocheck(struct bio *bio, bool split);
64: int bio_submit_or_kill(struct bio *bio, unsigned int flags);
65:
66: static inline bool blk_try_enter_queue(struct request_queue *q, bool pm)
67: {
68: rcu_read_lock();
69: if (!percpu_ref_tryget_live_rcu(&q->q_usage_counter))
70: goto fail;
71:
72: /*
73: * The code that increments the pm_only counter must ensure that the
74: * counter is globally visible before the queue is unfrozen.
75: */
76: if (blk_queue_pm_only(q) &&
77: (!pm || queue_rpm_status(q) == RPM_SUSPENDED))
78: goto fail_put;
79:
80: rcu_read_unlock();
81: return true;
82:
83: fail_put:
84: blk_queue_exit(q);
85: fail:
86: rcu_read_unlock();
87: return false;
88: }
89:
90: static inline int bio_queue_enter(struct bio *bio)
91: {
92: struct request_queue *q = bdev_get_queue(bio->bi_bdev);
93:
94: if (blk_try_enter_queue(q, false)) {
95: rwsem_acquire_read(&q->io_lockdep_map, 0, 0, _RET_IP_);
96: rwsem_release(&q->io_lockdep_map, _RET_IP_);
97: return 0;
98: }
99: return __bio_queue_enter(q, bio);
100: }
101:
102: static inline void blk_wait_io(struct completion *done)
103: {
104: /* Prevent hang_check timer from firing at us during very long I/O */
105: unsigned long timeout = sysctl_hung_task_timeout_secs * HZ / 2;
106:
107: if (timeout)
108: while (!wait_for_completion_io_timeout(done, timeout))
109: ;
110: else
111: wait_for_completion_io(done);
112: }
113:
114: struct block_device *blkdev_get_no_open(dev_t dev, bool autoload);
]
|
| 433/2 |
2026/11/03 21:09 |
llm |
patch-planner |
0m
Model:
Tokens:
input: 51248
output: 33
thoughts: 343
Thoughts: **Analyzing Block Device Death and Drain Procedures**
Okay, let's dive into this block device death handling, because something feels off. I need to understand the complete sequence from marking a disk as dead to the queue teardown. I'm going to carefully trace the code paths.
First, I need to check `include/linux/blkdev.h` for general definitions, specifically lines 636-645, which probably contain some crucial structures or macros related to request queues and devices. Then, I'll move to `block/blk.h` at lines 58-61 and 780-803 for more core definitions and any relevant helper functions. Now, for the real meat, I need to look at `block/blk-mq.c` (lines 115-248 and 4483) and `block/genhd.c` (lines 660-782 and 689-695) and `block/blk-core.c` (lines 327-341).
Specifically, I need to understand what happens when a disk is marked dead. I'm looking at `blk_queue_start_drain` in `block/blk-core.c`, lines 327-341, and its call to `__blk_freeze_queue_start`. Also, let's examine `__blk_mark_disk_dead` and `blk_mark_disk_dead` in `block/genhd.c` (lines 660-680 and 689-695 respectively). And the all important `blk_mq_destroy_queue` in `block/blk-mq.c`, line 4483, will shed light on the final teardown process.
The key question that bugs me: Why does `blk_queue_start_drain` *not* take an `owner` parameter? It instead passes `current` to `__blk_freeze_queue_start`. I need to understand the rationale behind this design. Is this intended behavior, or did it change at some point? Was this a threading/locking issue? This needs to be understood.
I should also check what was changed in commit `6a78699838a0`. Let's use `git show 6a78699838a0` to see if that commit gives any clue to what is going on.
|
| 434/2 |
2026/11/03 21:10 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 6a78699838a0ddeed3620ddf50c1521f1fe1e811
Author: Ming Lei <ming.lei@redhat.com>
Date: Thu Oct 31 21:37:19 2024 +0800
block: always verify unfreeze lock on the owner task
commit f1be1788a32e ("block: model freeze & enter queue as lock for
supporting lockdep") tries to apply lockdep for verifying freeze &
unfreeze. However, the verification is only done the outmost freeze and
unfreeze. This way is actually not correct because q->mq_freeze_depth
still may drop to zero on other task instead of the freeze owner task.
Fix this issue by always verifying the last unfreeze lock on the owner
task context, and make sure both the outmost freeze & unfreeze are
verified in the current task.
Fixes: f1be1788a32e ("block: model freeze & enter queue as lock for supporting lockdep")
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241031133723.303835-4-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-core.c b/block/blk-core.c
index 09d10bb95fda..4f791a3114a1 100644
--- a/block/blk-core.c
+++ b/block/blk-core.c
@@ -287,7 +287,7 @@ bool blk_queue_start_drain(struct request_queue *q)
* entering queue, so we call blk_freeze_queue_start() to
* prevent I/O from crossing blk_queue_enter().
*/
- bool freeze = __blk_freeze_queue_start(q);
+ bool freeze = __blk_freeze_queue_start(q, current);
if (queue_is_mq(q))
blk_mq_wake_waiters(q);
/* Make blk_queue_enter() reexamine the DYING flag. */
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 5f4496220432..5e240a4b6be0 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -120,20 +120,66 @@ void blk_mq_in_flight_rw(struct request_queue *q, struct block_device *part,
inflight[1] = mi.inflight[1];
}
-bool __blk_freeze_queue_start(struct request_queue *q)
+#ifdef CONFIG_LOCKDEP
+static bool blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
{
- int freeze;
+ if (!owner)
+ return false;
+
+ if (!q->mq_freeze_depth) {
+ q->mq_freeze_owner = owner;
+ q->mq_freeze_owner_depth = 1;
+ return true;
+ }
+
+ if (owner == q->mq_freeze_owner)
+ q->mq_freeze_owner_depth += 1;
+ return false;
+}
+
+/* verify the last unfreeze in owner context */
+static bool blk_unfreeze_check_owner(struct request_queue *q)
+{
+ if (!q->mq_freeze_owner)
+ return false;
+ if (q->mq_freeze_owner != current)
+ return false;
+ if (--q->mq_freeze_owner_depth == 0) {
+ q->mq_freeze_owner = NULL;
+ return true;
+ }
+ return false;
+}
+
+#else
+
+static bool blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
+{
+ return false;
+}
+
+static bool blk_unfreeze_check_owner(struct request_queue *q)
+{
+ return false;
+}
+#endif
+
+bool __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner)
+{
+ bool freeze;
mutex_lock(&q->mq_freeze_lock);
+ freeze = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
if (queue_is_mq(q))
blk_mq_run_hw_queues(q, false);
- freeze = true;
} else {
mutex_unlock(&q->mq_freeze_lock);
- freeze = false;
}
return freeze;
@@ -141,7 +187,7 @@ bool __blk_freeze_queue_start(struct request_queue *q)
void blk_freeze_queue_start(struct request_queue *q)
{
- if (__blk_freeze_queue_start(q))
+ if (__blk_freeze_queue_start(q, current))
blk_freeze_acquire_lock(q, false, false);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -170,7 +216,7 @@ EXPORT_SYMBOL_GPL(blk_mq_freeze_queue);
bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
- int unfreeze = false;
+ bool unfreeze;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
@@ -180,8 +226,8 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
if (!q->mq_freeze_depth) {
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
- unfreeze = true;
}
+ unfreeze = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
return unfreeze;
@@ -203,7 +249,7 @@ EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
*/
void blk_freeze_queue_start_non_owner(struct request_queue *q)
{
- __blk_freeze_queue_start(q);
+ __blk_freeze_queue_start(q, NULL);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start_non_owner);
diff --git a/block/blk.h b/block/blk.h
index ac48b79cbf80..57fc035620d6 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -37,7 +37,8 @@ void blk_free_flush_queue(struct blk_flush_queue *q);
bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
bool blk_queue_start_drain(struct request_queue *q);
-bool __blk_freeze_queue_start(struct request_queue *q);
+bool __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner);
int __bio_queue_enter(struct request_queue *q, struct bio *bio);
void submit_bio_noacct_nocheck(struct bio *bio);
void bio_await_chain(struct bio *bio);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 93551772c1d6..1b51a7c92e9b 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -575,6 +575,10 @@ struct request_queue {
struct throtl_data *td;
#endif
struct rcu_head rcu_head;
+#ifdef CONFIG_LOCKDEP
+ struct task_struct *mq_freeze_owner;
+ int mq_freeze_owner_depth;
+#endif
wait_queue_head_t mq_freeze_wq;
/*
* Protect concurrent access to q_usage_counter by
]
|
| 435/2 |
2026/11/03 21:10 |
llm |
patch-planner |
0m
Model:
Tokens:
input: 53848
output: 62
thoughts: 40
Thoughts: Okay, here's my interpretation of those thoughts, tailored for an expert audience, and delivered as a first-person summary:
**Digging into Commit History for Clarity**
Right, let's keep this investigation focused. I need to take a closer look at a couple of specific commits related to the recent issue. I'm going to run `git show 6f491a8d4b92` and `git show f6661b1d0525`. My experience tells me that these commits are likely pivotal. I expect to see the code changes introduced there, which will hopefully give me context I need. This will quickly tell me what was implemented and any accompanying context in the commit messages, so I can establish a baseline and potentially identify the root cause of the bug. It will be much quicker than wading through the diffs of a larger range of commits at this point.
|
| 436/2 |
2026/11/03 21:10 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 6f491a8d4b92d1a840fd9209cba783c84437d0b7
Author: Ming Lei <ming.lei@redhat.com>
Date: Wed Nov 27 21:51:28 2024 +0800
block: track disk DEAD state automatically for modeling queue freeze lockdep
Now we only verify the outmost freeze & unfreeze in current context in case
that !q->mq_freeze_depth, so it is reliable to save disk DEAD state when
we want to lock the freeze queue since the state is one per-task variable
now.
Doing this way can kill lots of false positive when freeze queue is
called before adding disk[1].
[1] https://lore.kernel.org/linux-block/6741f6b2.050a0220.1cc393.0017.GAE@google.com/
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241127135133.3952153-3-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 60f457f62913..0c6a319fb936 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -131,6 +131,9 @@ static bool blk_freeze_set_owner(struct request_queue *q,
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
+ q->mq_freeze_disk_dead = !q->disk ||
+ test_bit(GD_DEAD, &q->disk->state) ||
+ !blk_queue_registered(q);
return true;
}
@@ -187,7 +190,7 @@ bool __blk_freeze_queue_start(struct request_queue *q,
void blk_freeze_queue_start(struct request_queue *q)
{
if (__blk_freeze_queue_start(q, current))
- blk_freeze_acquire_lock(q, false, false);
+ blk_freeze_acquire_lock(q, false);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -235,7 +238,7 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
void blk_mq_unfreeze_queue(struct request_queue *q)
{
if (__blk_mq_unfreeze_queue(q, false))
- blk_unfreeze_release_lock(q, false, false);
+ blk_unfreeze_release_lock(q, false);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
diff --git a/block/blk.h b/block/blk.h
index 2c26abf505b8..8708168d50e4 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -720,22 +720,29 @@ void blk_integrity_verify(struct bio *bio);
void blk_integrity_prepare(struct request *rq);
void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
-static inline void blk_freeze_acquire_lock(struct request_queue *q, bool
- disk_dead, bool queue_dying)
+#ifdef CONFIG_LOCKDEP
+static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
{
- if (!disk_dead)
+ if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
if (!queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q, bool
- disk_dead, bool queue_dying)
+static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
{
if (!queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
- if (!disk_dead)
+ if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
+#else
+static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
+{
+}
+static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
+{
+}
+#endif
#endif /* BLK_INTERNAL_H */
diff --git a/block/elevator.c b/block/elevator.c
index 7c3ba80e5ff4..ca0a74369f1c 100644
--- a/block/elevator.c
+++ b/block/elevator.c
@@ -602,14 +602,14 @@ void elevator_init_mq(struct request_queue *q)
* Disk isn't added yet, so verifying queue lock only manually.
*/
blk_freeze_queue_start_non_owner(q);
- blk_freeze_acquire_lock(q, true, false);
+ blk_freeze_acquire_lock(q, false);
blk_mq_freeze_queue_wait(q);
blk_mq_cancel_work_sync(q);
err = blk_mq_init_sched(q, e);
- blk_unfreeze_release_lock(q, true, false);
+ blk_unfreeze_release_lock(q, false);
blk_mq_unfreeze_queue_non_owner(q);
if (err) {
diff --git a/block/genhd.c b/block/genhd.c
index 79230c109fca..59ac299909b3 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -692,7 +692,7 @@ void del_gendisk(struct gendisk *disk)
start_drain = __blk_mark_disk_dead(disk);
queue_dying = blk_queue_dying(q);
if (start_drain)
- blk_freeze_acquire_lock(q, true, queue_dying);
+ blk_freeze_acquire_lock(q, queue_dying);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
@@ -748,7 +748,7 @@ void del_gendisk(struct gendisk *disk)
blk_mq_exit_queue(q);
if (start_drain)
- blk_unfreeze_release_lock(q, true, queue_dying);
+ blk_unfreeze_release_lock(q, queue_dying);
}
EXPORT_SYMBOL(del_gendisk);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 378d3a1a22fc..522cf8eef66c 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -581,6 +581,8 @@ struct request_queue {
#ifdef CONFIG_LOCKDEP
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
+ /* Records disk state in current context, used in unfreeze queue */
+ bool mq_freeze_disk_dead;
#endif
wait_queue_head_t mq_freeze_wq;
/*
]
|
| 437/2 |
2026/11/03 21:10 |
tool |
git-show |
0m
Args:
Results: map[Output:commit f6661b1d0525f3764596a1b65eeed9e75aecafa7
Author: Ming Lei <ming.lei@redhat.com>
Date: Wed Nov 27 21:51:30 2024 +0800
block: track queue dying state automatically for modeling queue freeze lockdep
Now we only verify the outmost freeze & unfreeze in current context in case
that !q->mq_freeze_depth, so it is reliable to save queue lying state when
we want to lock the freeze queue since the state is one per-task variable
now.
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241127135133.3952153-5-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 0c6a319fb936..fca2ec64a06b 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -134,6 +134,7 @@ static bool blk_freeze_set_owner(struct request_queue *q,
q->mq_freeze_disk_dead = !q->disk ||
test_bit(GD_DEAD, &q->disk->state) ||
!blk_queue_registered(q);
+ q->mq_freeze_queue_dying = blk_queue_dying(q);
return true;
}
@@ -190,7 +191,7 @@ bool __blk_freeze_queue_start(struct request_queue *q,
void blk_freeze_queue_start(struct request_queue *q)
{
if (__blk_freeze_queue_start(q, current))
- blk_freeze_acquire_lock(q, false);
+ blk_freeze_acquire_lock(q);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -238,7 +239,7 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
void blk_mq_unfreeze_queue(struct request_queue *q)
{
if (__blk_mq_unfreeze_queue(q, false))
- blk_unfreeze_release_lock(q, false);
+ blk_unfreeze_release_lock(q);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
diff --git a/block/blk.h b/block/blk.h
index 8708168d50e4..cbf6a676ffe9 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -721,26 +721,26 @@ void blk_integrity_prepare(struct request *rq);
void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
#ifdef CONFIG_LOCKDEP
-static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
- if (!queue_dying)
+ if (!q->mq_freeze_queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
- if (!queue_dying)
+ if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
#else
-static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
}
#endif
diff --git a/block/genhd.c b/block/genhd.c
index 59ac299909b3..5678194b6b1a 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -661,7 +661,7 @@ void del_gendisk(struct gendisk *disk)
struct request_queue *q = disk->queue;
struct block_device *part;
unsigned long idx;
- bool start_drain, queue_dying;
+ bool start_drain;
might_sleep();
@@ -690,9 +690,8 @@ void del_gendisk(struct gendisk *disk)
*/
mutex_lock(&disk->open_mutex);
start_drain = __blk_mark_disk_dead(disk);
- queue_dying = blk_queue_dying(q);
if (start_drain)
- blk_freeze_acquire_lock(q, queue_dying);
+ blk_freeze_acquire_lock(q);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
@@ -748,7 +747,7 @@ void del_gendisk(struct gendisk *disk)
blk_mq_exit_queue(q);
if (start_drain)
- blk_unfreeze_release_lock(q, queue_dying);
+ blk_unfreeze_release_lock(q);
}
EXPORT_SYMBOL(del_gendisk);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 522cf8eef66c..5d40af2ef971 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -581,8 +581,12 @@ struct request_queue {
#ifdef CONFIG_LOCKDEP
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
- /* Records disk state in current context, used in unfreeze queue */
+ /*
+ * Records disk & queue state in current context, used in unfreeze
+ * queue
+ */
bool mq_freeze_disk_dead;
+ bool mq_freeze_queue_dying;
#endif
wait_queue_head_t mq_freeze_wq;
/*
]
|
| 438/2 |
2026/11/03 21:10 |
llm |
patch-planner |
1m
Model:
Tokens:
input: 57950
output: 43
thoughts: 2869
Thoughts: **Deep Dive into Block Layer Freeze/Unfreeze Logic**
Okay, after staring at those commits (`6a78699838a0`, `6f491a8d4b92`, `f6661b1d0525`), the picture is becoming clearer. Initially, Ming Lei's goal was to make the freeze/unfreeze logic more robust by tracking lockdep maps related to `io_lockdep_map` and `q_lockdep_map`. The idea was that `blk_freeze_set_owner()` would determine whether these lockdep maps needed acquiring, and then `blk_unfreeze_check_owner()` would release them.
The problem, as I see it, is that the current implementation of `blk_freeze_set_owner()`, `blk_freeze_queue_start()`, `blk_queue_start_drain()`, and `blk_unfreeze_check_owner()` return a boolean, which results in `blk_freeze_acquire_lock(q)` and `blk_unfreeze_release_lock(q)` having to check `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying` outside of the protection of `q->mq_freeze_lock`. This opens a potential race condition. In `blk_mq_unfreeze_queue_nomemrestore(q)` and `__del_gendisk()`, we see that by the time `blk_unfreeze_release_lock(q)` is called, the queue might already be unfrozen and the lock released. This is problematic because a concurrent freeze could potentially overwrite critical flags before they are used.
Looking further, I'm concerned about how `blk_queue_start_drain(q)` is called from `blk_mark_disk_dead(disk)` and `blk_mq_destroy_queue(q)`. Here's what I've discovered: `blk_mark_disk_dead(disk)` sets `QUEUE_FLAG_DYING` and calls `__blk_mark_disk_dead()`, followed by `blk_report_disk_dead()`. Meanwhile, `blk_mq_destroy_queue(q)` sets the same flag and then directly calls `blk_queue_start_drain(q)`. The critical thing here is how this interacts with the freeze/unfreeze mechanism. `__del_gendisk(disk)` calls `blk_freeze_acquire_lock(q)` and `blk_unfreeze_release_lock(q)`, but crucially, it does this only if it doesn't own the queue, so it has to drain and unfreeze. In the cases of `blk_mark_disk_dead(disk)` and `blk_mq_destroy_queue(q)`, the situation is different.
In both of those cases, if `q->mq_freeze_depth == 0`, both `disk_dead` and `queue_dying` are true. This means no lockdep map is acquired or released. But what if we're in a scenario where the queue *is* frozen at some depth, like in `do_rbd_remove`? The queue drain routine in `blk_mark_disk_dead(disk)` *still* calls `blk_queue_start_drain`, meaning `blk_freeze_set_owner` can increment the depth. But `blk_mark_disk_dead(disk)` never unfreezes! This means the depth is incremented, even though the queue is never un-frozen, or the lockdep maps released.
I need to confirm if this drain freeze is ever unfrozen if `GD_OWNS_QUEUE` is true. `QUEUE_FLAG_DYING` is set in this case so no lockdep lock is acquired and no drain/freeze needs to occur.
Digging further, I realize that in scenarios where `blk_queue_dying(q)` is true, can any lockdep map be acquired by `blk_queue_start_drain(q)`? The answer is no, because the code paths that call `blk_queue_start_drain(q)` are all ones where the disk is dead or dying. This suggests a simplification, in that the depth and ownership should not change in the dying case.
Now I'm focusing on the heart of the problem: `blk_freeze_set_owner()`. Its primary purpose is to track the task that holds the outermost freeze, so that that same task handles the unfreeze, and releases the lockdep maps. The most important thing here is what if on the outermost freeze (`!q->mq_freeze_depth`), *neither* lockdep map is acquired (because both `disk_dead` and `queue_dying` are true)? Now,
|
| 439/2 |
2026/11/03 21:11 |
tool |
git-show |
0m
Args: map[Commit:f1be1788a32e File:block/genhd.c]
Results: map[Output:commit f1be1788a32e8fa63416ad4518bbd1a85a825c9d
Author: Ming Lei <ming.lei@redhat.com>
Date: Fri Oct 25 08:37:20 2024 +0800
block: model freeze & enter queue as lock for supporting lockdep
Recently we got several deadlock report[1][2][3] caused by
blk_mq_freeze_queue and blk_enter_queue().
Turns out the two are just like acquiring read/write lock, so model them
as read/write lock for supporting lockdep:
1) model q->q_usage_counter as two locks(io and queue lock)
- queue lock covers sync with blk_enter_queue()
- io lock covers sync with bio_enter_queue()
2) make the lockdep class/key as per-queue:
- different subsystem has very different lock use pattern, shared lock
class causes false positive easily
- freeze_queue degrades to no lock in case that disk state becomes DEAD
because bio_enter_queue() won't be blocked any more
- freeze_queue degrades to no lock in case that request queue becomes dying
because blk_enter_queue() won't be blocked any more
3) model blk_mq_freeze_queue() as acquire_exclusive & try_lock
- it is exclusive lock, so dependency with blk_enter_queue() is covered
- it is trylock because blk_mq_freeze_queue() are allowed to run
concurrently
4) model blk_enter_queue() & bio_enter_queue() as acquire_read()
- nested blk_enter_queue() are allowed
- dependency with blk_mq_freeze_queue() is covered
- blk_queue_exit() is often called from other contexts(such as irq), and
it can't be annotated as lock_release(), so simply do it in
blk_enter_queue(), this way still covered cases as many as possible
With lockdep support, such kind of reports may be reported asap and
needn't wait until the real deadlock is triggered.
For example, lockdep report can be triggered in the report[3] with this
patch applied.
[1] occasional block layer hang when setting 'echo noop > /sys/block/sda/queue/scheduler'
https://bugzilla.kernel.org/show_bug.cgi?id=219166
[2] del_gendisk() vs blk_queue_enter() race condition
https://lore.kernel.org/linux-block/20241003085610.GK11458@google.com/
[3] queue_freeze & queue_enter deadlock in scsi
https://lore.kernel.org/linux-block/ZxG38G9BuFdBpBHZ@fedora/T/#u
Reviewed-by: Christoph Hellwig <hch@lst.de>
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241025003722.3630252-4-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/genhd.c b/block/genhd.c
index bc30eee7ab16..dfee66146bd1 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -601,13 +601,13 @@ static void blk_report_disk_dead(struct gendisk *disk, bool surprise)
rcu_read_unlock();
}
-static void __blk_mark_disk_dead(struct gendisk *disk)
+static bool __blk_mark_disk_dead(struct gendisk *disk)
{
/*
* Fail any new I/O.
*/
if (test_and_set_bit(GD_DEAD, &disk->state))
- return;
+ return false;
if (test_bit(GD_OWNS_QUEUE, &disk->state))
blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
@@ -620,7 +620,7 @@ static void __blk_mark_disk_dead(struct gendisk *disk)
/*
* Prevent new I/O from crossing bio_queue_enter().
*/
- blk_queue_start_drain(disk->queue);
+ return blk_queue_start_drain(disk->queue);
}
/**
@@ -661,6 +661,7 @@ void del_gendisk(struct gendisk *disk)
struct request_queue *q = disk->queue;
struct block_device *part;
unsigned long idx;
+ bool start_drain, queue_dying;
might_sleep();
@@ -688,7 +689,10 @@ void del_gendisk(struct gendisk *disk)
* Drop all partitions now that the disk is marked dead.
*/
mutex_lock(&disk->open_mutex);
- __blk_mark_disk_dead(disk);
+ start_drain = __blk_mark_disk_dead(disk);
+ queue_dying = blk_queue_dying(q);
+ if (start_drain)
+ blk_freeze_acquire_lock(q, true, queue_dying);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
@@ -745,6 +749,9 @@ void del_gendisk(struct gendisk *disk)
if (queue_is_mq(q))
blk_mq_exit_queue(q);
}
+
+ if (start_drain)
+ blk_unfreeze_release_lock(q, true, queue_dying);
}
EXPORT_SYMBOL(del_gendisk);
]
|
| 440/2 |
2026/11/03 21:11 |
llm |
patch-planner |
1m
Model:
Tokens:
input: 62427
output: 67
thoughts: 7922
Thoughts: **Analyzing Block Layer Queue Freezing and Unfreezing**
Okay, let's break this down. My goal is to understand how the block layer handles queue freezing and unfreezing, specifically around disk removal and queue destruction. I'm focusing on the potential for race conditions and lockdep warnings.
The core issue seems to revolve around when and how `q_lockdep_map` and `io_lockdep_map` are acquired and released, especially when a queue is being marked dead or destroyed. The key functions involved are `del_gendisk`, `blk_mark_disk_dead`, `blk_mq_destroy_queue`, `blk_freeze_queue_start`, `blk_mq_freeze_queue`, and their corresponding unfreeze counterparts.
I've identified two main scenarios that can cause problems:
1. **Lockdep Mismatch (WARNING: bad unlock balance detected!):** This happens when `blk_freeze_queue` (and its nested calls) doesn't synchronize correctly with the "dying" state of the queue as determined by `blk_mark_disk_dead` or `blk_mq_destroy_queue`. If a thread freezes the queue while `disk_dead` (or `!blk_queue_registered(q)`) is false (acquiring the lock), and another thread later sets `disk_dead` (or `blk_queue_registered(q)`), it's possible that the initial thread incorrectly releases a lock it never fully acquired. This is the "bad unlock balance" warning. This is caused by reading `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying` outside `q->mq_freeze_lock`.
2. **Lock Held at Return (WARNING: lock held when returning to user space!):** Conversely, if a thread *does* acquire the lock *after* the "dying" state is set (e.g. `disk_dead` or `blk_queue_dying`), it might skip releasing the acquired lock due to the changed state. This could lead to a "lock held when returning to user space" warning. Again, this is caused by the same race condition: reading `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying` outside `q->mq_freeze_lock`.
The crux of the matter is that `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying` need to be consistently protected and managed in the race condition.
I now focus on examining the current implementation, particularly how the `lock_mask` is managed and passed between `blk_freeze_set_owner`, `blk_freeze_queue_start`, `blk_unfreeze_check_owner`, and `__blk_mq_unfreeze_queue`. By returning the `lock_mask` from these functions and passing it between function calls, we can have a safer approach to managing the locking. By including `BLK_FREEZE_LOCK_IO` and `BLK_FREEZE_LOCK_QUEUE` in `lock_mask`, we can acquire and release both `io_lockdep_map` and `q_lockdep_map` consistently, which is necessary.
Looking at how scenarios like `del_gendisk`, `blk_mark_disk_dead`, and `do_rbd_remove` behave with this updated locking scheme: The code now correctly handles `GD_OWNS_QUEUE` scenarios, as well as cases where `blk_mark_disk_dead` is called before `del_gendisk` (like `sd_remove`) and `do_rbd_remove`. In all these scenarios, with the proposed changes, the locking is now clean. In the fourth scenario, the proposed change would also safely handle the freeze-mark-unfreeze cycle, preventing lockdep problems.
The key improvement is to ensure that a task always releases the *same* lockdep maps that it acquired. The proposed change achieves this by tracking the needed locks using `lock_mask`, which is returned by the freeze functions and used to release the correct maps. This eliminates the race condition and the related lockdep warnings.
In summary, my analysis indicates that the proposed modifications to use the `lock_mask` system will address the identified race conditions and prevent the lockdep warnings. This will provide a more robust and predictable block layer queue freezing and unfreezing mechanism.
|
| 441/2 |
2026/11/03 21:13 |
tool |
codesearch-find-references |
0m
Args: map[Name:blk_freeze_queue_start_non_owner]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:nvme_start_freeze SourceFile:drivers/nvme/host/core.c SourceLine:5418] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__UNIQUE_ID_addressable_blk_freeze_queue_start_non_owner_1308 SourceFile:block/blk-mq.c SourceLine:248] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__gendwarfksyms_ptr_blk_freeze_queue_start_non_owner SourceFile:block/blk-mq.c SourceLine:248] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__gendwarfksyms_ptr_blk_freeze_queue_start_non_owner SourceFile:block/blk-mq.c SourceLine:248]] TruncatedOutput:false]
|
| 442/2 |
2026/11/03 21:13 |
tool |
codesearch-find-references |
0m
Args: map[Name:blk_mq_unfreeze_queue_non_owner]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:nvme_unfreeze SourceFile:drivers/nvme/host/core.c SourceLine:5367] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__UNIQUE_ID_addressable_blk_mq_unfreeze_queue_non_owner_1309 SourceFile:block/blk-mq.c SourceLine:255] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__gendwarfksyms_ptr_blk_mq_unfreeze_queue_non_owner SourceFile:block/blk-mq.c SourceLine:255] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__gendwarfksyms_ptr_blk_mq_unfreeze_queue_non_owner SourceFile:block/blk-mq.c SourceLine:255]] TruncatedOutput:false]
|
| 443/2 |
2026/11/03 21:13 |
llm |
patch-planner |
0m
Model:
Tokens:
input: 70998
output: 41
thoughts: 40
Thoughts: Here's my take on the thought process, tailored for an expert audience:
**Diving into blk-mq.c for Queue Unfreezing**
Okay, so we're looking at queue unfreezing, specifically the non-owner path. Let's dig into `block/blk-mq.c` and zero in on lines 240-260 to get a solid handle on `blk_mq_unfreeze_queue_non_owner`. I want to understand exactly how the non-owner path handles unfreezing, especially given the potential for contention and the need for careful synchronization in this area. It's crucial to grasp the nuances here to identify any possible bottlenecks or potential race conditions, and to see how the code ensures proper and safe unfreezing in scenarios where the original freezer isn't the one triggering the unfreeze. This will give me a better understanding of the overall block layer flow and if there are any optimizations possible.
|
| 444/2 |
2026/11/03 21:13 |
tool |
read-file |
0m
Args: map[File:block/blk-mq.c FirstLine:240 LineCount:25]
Results: map[Contents: 240: * Unlike blk_freeze_queue_start, the queue doesn't need to be unfrozen
241: * by the same task. This is fragile and should not be used if at all
242: * possible.
243: */
244: void blk_freeze_queue_start_non_owner(struct request_queue *q)
245: {
246: __blk_freeze_queue_start(q, NULL);
247: }
248: EXPORT_SYMBOL_GPL(blk_freeze_queue_start_non_owner);
249:
250: /* non_owner variant of blk_mq_unfreeze_queue */
251: void blk_mq_unfreeze_queue_non_owner(struct request_queue *q)
252: {
253: __blk_mq_unfreeze_queue(q, false);
254: }
255: EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_non_owner);
256:
257: /*
258: * FIXME: replace the scsi_internal_device_*block_nowait() calls in the
259: * mpt3sas driver such that this function can be removed.
260: */
261: void blk_mq_quiesce_queue_nowait(struct request_queue *q)
262: {
263: unsigned long flags;
264:
]
|
| 445/2 |
2026/11/03 21:13 |
llm |
patch-planner |
1m
Model:
Tokens:
input: 71499
output: 4214
thoughts: 2691
Thoughts: **Refactoring Block Freeze and Unfreeze Logic**
Okay, so I've been digging into the block layer's freeze/unfreeze mechanisms. My primary concern stems from how `blk_mq_unfreeze_queue_non_owner()` interacts with the freezing process, particularly regarding potential race conditions if a non-owner unfreezes before the owner has finished. Specifically, I'm thinking about situations where `blk_freeze_queue_start_non_owner()` doesn't increment the depth counter, leading to a premature decrement by `blk_unfreeze_check_owner()` called from `blk_mq_unfreeze_queue_non_owner()`. The current use of `nvme_start_freeze` / `nvme_unfreeze` aren't a concern.
I need to decide if we can make use of a simpler bitmask for controlling this behavior, instead of separate booleans for "disk dead" and "queue dying." My immediate thought is to replace those two booleans with an `unsigned int mq_freeze_lock_mask`. By inspecting the `struct request_queue`, I see that the fields fit neatly in the same memory footprint and doesn't increase `sizeof(struct request_queue)`.
The crucial advantage here is that by using a bitmask, we encapsulate the logic around those states, making it impossible to accidentally modify those flags outside the intended lock context. I can see this already being beneficial in `blk_freeze_set_owner()` and `blk_unfreeze_check_owner()` since the operations become clearer and less error-prone. This new method will be useful in `blk_freeze_acquire_lock()` and `blk_unfreeze_release_lock()` also.
We need to make sure that we refactor these functions to take this new bitmask. This is especially useful in functions like `blk_freeze_queue_start`, `blk_mq_unfreeze_queue_nomemrestore`, and `__del_gendisk()`, where the "outermost owner" predicate will be folded into the `lock_mask`.
Finally, I'm thinking about LIFO symmetry in lock acquisition/release and how to handle non-owner drains. Passing `NULL` (in certain cases) to `__blk_freeze_queue_start()` will ensure that certain operations don't mess with the depth counter when they don't need the lock.
With this approach, I'm confident that we can simplify the code, improve maintainability, and reduce the risk of subtle concurrency bugs related to freezing and unfreezing block queues.
|
| 446/1 |
2026/11/03 21:14 |
action |
kernel-scratch-checkouter |
0m
Results: map[KernelScratchSrc:/app/workdir/cache/tmp/tmp3297542794]
|
| 447/1 |
2026/11/03 21:15 |
loop |
|
1h27m
|
| 448/2 |
2026/11/03 21:15 |
iteration |
0 |
1h27m
|
| 449/3 |
2026/11/03 21:15 |
agent |
patch-generator |
56m
Model:
Instruction:
You are an experienced Linux kernel developer tasked with implementing a fix for a kernel bug.
You will be given a crash report, an explanation of the root cause, historical context on how
similar bugs were fixed in the past, and a concrete implementation plan.
Use the codeeditor tool to do code edits.
Note: you will not see your changes when looking at the code using codesearch tools.
Use the patch-diff tool to review the modifications you applied.
Follow the provided implementation plan directly. Do not re-debug the root cause, re-explore
git history, or redesign the fix from scratch unless concrete evidence in the target functions,
a build/test failure, or reviewer feedback shows that the planned approach cannot work. If a
test failure or reviewer feedback conflicts with the initial implementation plan, the test
failure or reviewer feedback takes precedence.
Work incrementally. Inspect only the target code you need to edit, apply your changes with
codeeditor promptly, and verify them with patch-diff. Your conversation
history may be summarized and raw tool outputs discarded, while the source tree is your only
durable memory: edits persist, but research does not. You can always revise earlier edits.
Your final reply should contain explanation of what you did in the patch and why
(details not present in the initial explanation of the bug).
If you are changing post-conditions of a function, consider all callers of the functions,
and if they need to be updated to handle new post-conditions. For example, if you make
a function that previously never returned a NULL, return NULL, consider if callers
need to be updated to handle NULL return value.
Prefer calling several tools at the same time to save round-trips.
Prompt:
The crash that corresponds to the bug is:
device-mapper: ioctl: device has been removed from the dev hash table.
================================================
WARNING: lock held when returning to user space!
syzkaller #1 Not tainted
------------------------------------------------
syz.3.1525/11804 is leaving the kernel with locks still held!
locks held by syz.3.1525/11804: 1, last CPU#0:
#0: ffff88805abdd468 (&q->q_usage_counter(queue)#52){+.+.}-{0:0}, at: blk_mq_freeze_queue include/linux/blk-mq.h:959 [inline]
#0: ffff88805abdd468 (&q->q_usage_counter(queue)#52){+.+.}-{0:0}, at: elevator_change+0x194/0x480 block/elevator.c:668
The explanation of the root cause of the bug is:
### Root Cause Analysis
#### Summary
The `WARNING: lock held when returning to user space!` for `&q->q_usage_counter(queue)` (which is the lockdep map `q->q_lockdep_map` acquired at `elevator_change+0x194/0x480`, `block/elevator.c:668`) is caused by a race condition between:
1. **`DM_TABLE_LOAD` (`table_load`)** initializing and registering the request-based DM queue/gendisk (`dm_setup_md_queue()` -> `add_disk()` -> `blk_register_queue()` -> `elevator_set_default()` -> `elevator_change()`), and
2. **`DM_DEV_REMOVE` (`dev_remove`)** concurrently destroying the same DM device (`dm_destroy()` -> `__dm_destroy()` -> `blk_mark_disk_dead()`), which marks the queue dying and starts draining/freezing the queue.
Specifically, in the block layer's queue-freeze lockdep tracking (`block/blk-mq.c` and `block/blk.h`), the flags `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead` are stored as per-`request_queue` fields protected by `q->mq_freeze_lock` when `q->mq_freeze_depth == 0`, **but `blk_unfreeze_release_lock(q)` reads them outside `q->mq_freeze_lock` after `q->mq_freeze_depth` has already been decremented to `0`**. When `blk_mark_disk_dead()` races with `blk_mq_unfreeze_queue()`, `q->mq_freeze_queue_dying` is overwritten from `false` to `true` before `blk_unfreeze_release_lock(q)` runs, causing `blk_unfreeze_release_lock(q)` to skip releasing `q->q_lockdep_map`.
---
#### Detailed Mechanism
##### 1. Lockdep modeling of `blk_mq_freeze_queue()` / `blk_mq_unfreeze_queue()`
In `block/blk-core.c:500`, `q->q_lockdep_map` is initialized with the name `"&q->q_usage_counter(queue)"`:
```c
lockdep_init_map(&q->q_lockdep_map, "&q->q_usage_counter(queue)",
&q->q_lock_cls_key, 0);
```
In `block/blk-mq.c`, when a task freezes a queue via `blk_mq_freeze_queue(q)` -> `blk_freeze_queue_start(q)`:
```c
static bool blk_freeze_set_owner(struct request_queue *q,
struct task_struct *owner)
{
if (!owner)
return false;
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
q->mq_freeze_disk_dead = !q->disk ||
test_bit(GD_DEAD, &q->disk->state) ||
!blk_queue_registered(q);
q->mq_freeze_queue_dying = blk_queue_dying(q);
return true;
}
if (owner == q->mq_freeze_owner)
q->mq_freeze_owner_depth += 1;
return false;
}
```
```c
bool __blk_freeze_queue_start(struct request_queue *q,
struct task_struct *owner)
{
bool freeze;
mutex_lock(&q->mq_freeze_lock);
freeze = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
if (queue_is_mq(q))
blk_mq_run_hw_queues(q, false);
} else {
mutex_unlock(&q->mq_freeze_lock);
}
return freeze;
}
void blk_freeze_queue_start(struct request_queue *q)
{
if (__blk_freeze_queue_start(q, current))
blk_freeze_acquire_lock(q);
}
```
And in `block/blk.h:715-728`:
```c
static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
if (!q->mq_freeze_queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
```
When the owner task unfreezes the queue via `blk_mq_unfreeze_queue(q, memflags)` -> `blk_mq_unfreeze_queue_nomemrestore(q)` (`block/blk-mq.c:211-235`):
```c
bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
bool unfreeze;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
q->q_usage_counter.data->force_atomic = true;
q->mq_freeze_depth--;
WARN_ON_ONCE(q->mq_freeze_depth < 0);
if (!q->mq_freeze_depth) {
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
}
unfreeze = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
return unfreeze;
}
void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
{
if (__blk_mq_unfreeze_queue(q, false))
blk_unfreeze_release_lock(q);
}
```
Notice the bug here:
1. Inside `__blk_mq_unfreeze_queue()`, `q->mq_freeze_depth` is decremented to `0` and `q->mq_freeze_owner` is cleared to `NULL`, and then `mutex_unlock(&q->mq_freeze_lock)` is called.
2. Only **after** `q->mq_freeze_lock` is released does `blk_mq_unfreeze_queue_nomemrestore()` call `blk_unfreeze_release_lock(q)`, which inspects `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead`.
3. Because `q->mq_freeze_depth` is already `0` and `q->mq_freeze_lock` is unlocked, another thread calling `__blk_freeze_queue_start()` can immediately acquire `q->mq_freeze_lock`, see `!q->mq_freeze_depth`, and overwrite `q->mq_freeze_queue_dying` (and `q->mq_freeze_disk_dead`) in `blk_freeze_set_owner()`.
##### 2. How Device Mapper triggers this race
In the reproducer:
1. `ioctl(DM_DEV_CREATE)` creates a DM device `md` (`md->type == DM_TYPE_NONE`, with `md->disk` allocated via `blk_alloc_disk()`).
2. **Thread 1 (`syz.3.1525/11804`)** calls `ioctl(DM_TABLE_LOAD)` (`table_load()` in `drivers/md/dm-ioctl.c:1622`) with a request-based `"multipath"` target:
- `find_device(param)` looks up `md` under `_hash_lock`, increments `md->holders` (`dm_get(md)`), and drops `_hash_lock`.
- `populate_table()` parses the `"multipath"` target, setting the table type to `DM_TYPE_REQUEST_BASED`.
- Since `dm_get_md_type(md) == DM_TYPE_NONE`, `table_load()` calls `dm_setup_md_queue(md, t)` (`drivers/md/dm.c:2606`):
- `dm_mq_init_request_queue(md, t)` initializes `md->queue` as a `blk-mq` queue.
- `add_disk(md->disk)` -> `device_add_disk()` -> `add_disk_fwnode()` -> `__add_disk()` -> `blk_register_queue(md->disk)` (`block/blk-sysfs.c:991`):
```c
if (queue_is_mq(q))
elevator_set_default(q);
```
- `elevator_set_default(q)` calls `elevator_change(q, &ctx)` (`block/elevator.c:653`).
3. Concurrently, **Thread 2** calls `ioctl(DM_DEV_REMOVE)` (`dev_remove()` in `drivers/md/dm-ioctl.c:1063`):
- Under `_hash_lock`, `dm_lock_for_deletion(md, ...)` succeeds because it only checks `dm_open_count(md)` (`0`), **not** `md->holders`.
- `__hash_remove(hc)` removes `hc` from the hash table and clears `md->interface_ptr` (`dm_set_mdptr(md, NULL)`).
- `dev_remove()` drops `_hash_lock`, calls `dm_put(md)`, and calls `dm_destroy(md)` -> `__dm_destroy(md, true)` (`drivers/md/dm.c:2726`):
```c
blk_mark_disk_dead(md->disk);
...
if (wait)
while (atomic_read(&md->holders))
fsleep(1000);
```
- Notice that `__dm_destroy()` calls `blk_mark_disk_dead(md->disk)` **before** waiting for `md->holders` to drop to `0`.
##### 3. Exact Race Sequence
1. **Thread 1 (`table_load`)** enters `elevator_change()` (`block/elevator.c:668`):
```c
memflags = blk_mq_freeze_queue(q);
```
- `q->mq_freeze_depth` is `0`.
- `blk_freeze_set_owner(q, Thread_1)` sets:
- `q->mq_freeze_owner = Thread_1`
- `q->mq_freeze_owner_depth = 1`
- `q->mq_freeze_disk_dead = true` (since `QUEUE_FLAG_REGISTERED` is not set yet)
- `q->mq_freeze_queue_dying = false` (since `QUEUE_FLAG_DYING` is not set yet)
- `q->mq_freeze_depth` becomes `1`.
- `blk_freeze_acquire_lock(q)` sees `!q->mq_freeze_queue_dying == true` and calls:
```c
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
```
2. **Thread 1 (`table_load`)** finishes `elevator_switch()` and calls `blk_mq_unfreeze_queue(q, memflags)` at `block/elevator.c:683`:
- Inside `__blk_mq_unfreeze_queue(q, false)` (`block/blk-mq.c:211`):
- `q->mq_freeze_depth` is decremented from `1` to `0`.
- `blk_unfreeze_check_owner(q)` decrements `q->mq_freeze_owner_depth` to `0`, sets `q->mq_freeze_owner = NULL`, and returns `true`.
- `mutex_unlock(&q->mq_freeze_lock)` unlocks `q->mq_freeze_lock`.
3. **Thread 2 (`dev_remove`)** executes `blk_mark_disk_dead(md->disk)` (`block/genhd.c:689`):
```c
void blk_mark_disk_dead(struct gendisk *disk)
{
blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
__blk_mark_disk_dead(disk);
blk_report_disk_dead(disk, true);
}
```
- `blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue)` sets `QUEUE_FLAG_DYING` on `q`.
- `__blk_mark_disk_dead(disk)` calls `blk_queue_start_drain(disk->queue)` -> `__blk_freeze_queue_start(q, Thread_2)`.
- Right after Thread 1 unlocks `q->mq_freeze_lock` in step 2 (e.g., when woken from `q->mq_freeze_lock` wait_list during `mutex_unlock`), Thread 2 acquires `q->mq_freeze_lock`.
- Because `q->mq_freeze_depth` is `0`, `blk_freeze_set_owner(q, Thread_2)` runs and sets:
```c
q->mq_freeze_queue_dying = blk_queue_dying(q); /* true! */
```
4. **Thread 1 (`table_load`)** now executes `blk_unfreeze_release_lock(q)` (`block/blk-mq.c:233` -> `block/blk.h:722`):
```c
static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
```
Because `q->mq_freeze_queue_dying` was overwritten with `true` by Thread 2 in step 3, `!q->mq_freeze_queue_dying` evaluates to `false`, and **`rwsem_release(&q->q_lockdep_map, _RET_IP_)` is skipped**.
5. **Thread 1 (`table_load`)** finishes `dm_setup_md_queue()`, acquires `_hash_lock` in `table_load()` (`drivers/md/dm-ioctl.c:1678`), sees `hc = dm_get_mdptr(md)` is `NULL`, logs:
```
device-mapper: ioctl: device has been removed from the dev hash table.
```
cleans up `t`, drops `md->holders` (`dm_put(md)`), and returns `-ENXIO` to user space with `q->q_lockdep_map` (`&q->q_usage_counter(queue)`) still held in lockdep, triggering the warning.
---
#### How to Fix
1. **In the block layer (`block/blk-mq.c`, `block/blk.h`, `block/genhd.c`)**:
`blk_freeze_acquire_lock(q)` and `blk_unfreeze_release_lock(q)` must not read mutable per-queue `q->mq_freeze_queue_dying` / `q->mq_freeze_disk_dead` fields outside `q->mq_freeze_lock` after `q->mq_freeze_depth` has dropped to `0` (where another task starting a new freeze can overwrite them). Either:
- Perform the lockdep release (`blk_unfreeze_release_lock(q)`) / state consumption under `q->mq_freeze_lock` before `q->mq_freeze_depth` is decremented / unlocked (or pass the saved `disk_dead` and `queue_dying` booleans out of `__blk_mq_unfreeze_queue()` by value while still holding `q->mq_freeze_lock`), and similarly pass/snapshot them under `q->mq_freeze_lock` in `__blk_freeze_queue_start()`.
2. **In Device Mapper (`drivers/md/dm.c`)**:
In `__dm_destroy()`, `blk_mark_disk_dead(md->disk)` should not be called while another thread holds `md->holders` and may still be in `dm_setup_md_queue()` / `add_disk(md->disk)` initializing and registering the disk/queue (i.e., wait for `atomic_read(&md->holders)` or serialize against `md->type_lock` before marking the disk dead).
Historical context on how similar bugs were fixed in the past:
Based on research into the commit history of the **Block Layer** and **Device Mapper** subsystems over the past 3 years (and relevant foundational commits), here is the historical context, prior art, and subsystem idioms for addressing this bug.
---
### 1. Block Layer: Queue Freeze Lockdep Tracking (`block/blk-mq.c`, `block/blk.h`)
#### Historical Context and Evolution
The queue freeze and unfreeze lockdep tracking was introduced and refined across several recent commits:
* **`f1be1788a32e` ("block: model freeze & enter queue as lock for supporting lockdep")**:
Initially modeled queue freeze/unfreeze using lockdep (`q->q_lockdep_map` and `q->io_lockdep_map`). Originally, `blk_freeze_acquire_lock()` and `blk_unfreeze_release_lock()` took explicit boolean parameters (`disk_dead`, `queue_dying`) passed down the call stack or stored as local variables.
* **`6a78699838a0` ("block: always verify unfreeze lock on the owner task")**:
Addressed an issue where freeze depth could drop across different tasks. It established the rule that lockdep verification must only occur on the **freeze owner task context** by tracking `q->mq_freeze_owner` and `q->mq_freeze_owner_depth` under `q->mq_freeze_lock`. `blk_freeze_set_owner()` only assigns ownership on outermost freeze (`!q->mq_freeze_depth`), and `blk_unfreeze_check_owner()` only authorizes releasing the lockdep map on the outermost unfreeze when `mq_freeze_owner_depth` drops to 0.
* **`6f491a8d4b92` ("block: track disk DEAD state automatically for modeling queue freeze lockdep")** and **`f6661b1d0525` ("block: track queue dying state automatically for modeling queue freeze lockdep")**:
Eliminated the boolean parameters to make lockdep tracking automatic. Under `q->mq_freeze_lock`, `blk_freeze_set_owner()` records `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying` on `struct request_queue`. The commit log noted that *"the state is one per-task variable now"*.
**However**, storing these booleans directly in `struct request_queue` without snapshotting them or protecting their read in `blk_unfreeze_release_lock()` broke this per-task guarantee: `blk_unfreeze_release_lock(q)` reads `q->mq_freeze_queue_dying` **outside** `q->mq_freeze_lock` after `q->mq_freeze_depth` has already been decremented to 0.
#### Idioms and Locking Patterns from Prior Art
1. **Never read per-queue mutable lockdep state outside `q->mq_freeze_lock` once `mq_freeze_depth == 0`**:
Any fields in `struct request_queue` conditioned on `!q->mq_freeze_depth` can immediately be overwritten by another task starting a new freeze (e.g. `__blk_freeze_queue_start()` called via `blk_mark_disk_dead()` or `blk_queue_start_drain()`) the instant `q->mq_freeze_lock` is dropped in `__blk_mq_unfreeze_queue()`.
2. **Snapshot state under the lock or perform the lockdep release before releasing the lock**:
* *Passing by value / snapshotting*: Similar to the pattern in `f1be1788a32e`, when a task needs to remember the state captured at freeze time, that state must either be snapshotted under `q->mq_freeze_lock` into local stack variables before unlocking (e.g., returned by `blk_unfreeze_check_owner()` / `__blk_mq_unfreeze_queue()`), or
* *Lockdep release under `q->mq_freeze_lock`*: Releasing a lockdep map (`rwsem_release()` / `lock_release()`) simply removes the held lock from the task's held-lock list and does not establish new lock dependency edges, so state consumption and release under `q->mq_freeze_lock` before depth drops to 0 avoids the race window entirely.
---
### 2. Device Mapper: Device Removal vs Table Load Synchronization (`drivers/md/dm.c`, `drivers/md/dm-ioctl.c`)
#### Historical Context and Evolution
The race occurs because `table_load()` is setting up the request-based queue (`dm_setup_md_queue()` -> `add_disk()` -> `elevator_change()`) while `dev_remove()` concurrently calls `dm_destroy()` -> `__dm_destroy()` -> `blk_mark_disk_dead()`:
* **`3f77316de0ec` ("dm: separate device deletion from dm_put")**:
Separated mapped device deletion from reference counting. It established the convention that `__dm_destroy()` must wait for all in-flight references held on the mapped device via `while (atomic_read(&md->holders)) fsleep(1000);`.
* **`3b785fbcf81c` ("dm: mark request_queue dead before destroying the DM device")** and **`7a5428dcb790` ("block: fix surprise removal for drivers calling blk_set_queue_dying")**:
Replaced direct queue flag setting with `blk_mark_disk_dead(md->disk)` at the top of `__dm_destroy()`. This was intended to reject new I/O during removal, but placed the call **before** `__dm_destroy()` waits for `atomic_read(&md->holders)`.
* **`00c4fc3b1f59` ("dm ioctl: increase granularity of type_lock when loading table")**:
Recognized that `md->type` and `md->queue` setup must be serialized, introducing `dm_lock_md_type()` / `md->type_lock` during `table_load()` around `dm_setup_md_queue()`. However, `__dm_destroy()` does not acquire or synchronize against `md->type_lock`.
* **`44b43ec132f1` ("dm: fix resume-vs-remove race")**:
Fixed a race where an ioctl (`dm_resume`) raced with `__dm_destroy()`. The pattern used was explicitly checking device removal flags (`test_bit(DMF_FREEING, &md->flags)`) under the appropriate lock (`suspend_lock`) to reject operations on devices undergoing destruction.
* **`c50abeb38026` ("dm ioctl: forbid messages to devices being deleted")** and **`abdc568b0540` ("dm: prevent access to md being deleted")**:
Prevented operations on devices being deleted by checking `dm_deleting_md(md)` (which tests `DMF_DELETING`, set in `dm_lock_for_deletion()`) under `_minor_lock`.
#### Idioms and Locking Patterns from Prior Art
1. **Do not mark a disk dead before in-flight device holders finish setup**:
In `__dm_destroy()`, calling `blk_mark_disk_dead(md->disk)` while `atomic_read(&md->holders) > 0` allows `blk_mark_disk_dead()` to race with concurrent operations (such as `table_load()`) that hold `md->holders` and are still in the middle of disk registration or queue setup (`dm_setup_md_queue()` / `add_disk()`). In DM's lifecycle model, disk teardown actions should follow the drainage of active holders.
2. **Check deletion flags (`DMF_DELETING` / `DMF_FREEING`) before mutating queue/device state**:
As demonstrated in `44b43ec132f1` and `c50abeb38026`, ioctls modifying device state must check `dm_deleting_md(md)` or `DMF_FREEING` to abort cleanly (returning `-ENXIO`) before performing heavy setup like initializing request queues or adding disks.
3. **Serialize queue type initialization against device destruction**:
`table_load()` uses `md->type_lock` to serialize queue setup. Ensuring that `__dm_destroy()` synchronizes with `md->type_lock` prevents tearing down or marking a queue dying while `dm_setup_md_queue()` is configuring it.
The implementation plan for the fix is:
### Implementation Plan
#### 1. Fix Strategy & Architectural Rationale
The bug is a race condition in the block layer's queue-freeze lockdep tracking (`block/blk-mq.c`, `block/blk.h`, `block/genhd.c`, `block/blk-core.c`).
Currently, `blk_freeze_set_owner()` records `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying` on `struct request_queue` under `q->mq_freeze_lock` when `q->mq_freeze_depth == 0`. However, `blk_freeze_acquire_lock(q)` and `blk_unfreeze_release_lock(q)` read those mutable per-queue fields **outside** `q->mq_freeze_lock`. On unfreeze (`blk_mq_unfreeze_queue_nomemrestore()`), `__blk_mq_unfreeze_queue()` decrements `q->mq_freeze_depth` to `0`, clears `q->mq_freeze_owner = NULL`, and unlocks `q->mq_freeze_lock` **before** `blk_unfreeze_release_lock(q)` runs. Any concurrent freeze starting on another CPU (such as `blk_mark_disk_dead()` during `DM_DEV_REMOVE`, or another `blk_mq_freeze_queue()`) can immediately acquire `q->mq_freeze_lock`, observe `!q->mq_freeze_depth`, and overwrite `q->mq_freeze_queue_dying` / `q->mq_freeze_disk_dead` before the unfreezing task executes `blk_unfreeze_release_lock(q)`. This causes `blk_unfreeze_release_lock(q)` to skip releasing `q->q_lockdep_map` (or `q->io_lockdep_map`), leaving the task returning to user space with the lockdep lock still held.
Additionally, `blk_queue_start_drain(q)` unconditionally passes `current` as the freeze `owner` to `__blk_freeze_queue_start(q, current)`. When `QUEUE_FLAG_DYING` is set (`blk_mark_disk_dead()`, `blk_mq_destroy_queue()`, or `__del_gendisk()` with `GD_OWNS_QUEUE`), the caller neither acquires lockdep maps nor unfreezes the queue; if called while `current` already holds an outer freeze (e.g., `do_rbd_remove()`), incrementing `q->mq_freeze_owner_depth` prevents the outer `blk_mq_unfreeze_queue()` from ever reaching `mq_freeze_owner_depth == 0`.
**Chosen Approach:**
1. **Snapshot and return a lockdep bitmask under `q->mq_freeze_lock`:**
Replace `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying` with a bitmask `q->mq_freeze_lock_mask` (`BLK_FREEZE_LOCK_IO`, `BLK_FREEZE_LOCK_QUEUE`) protected strictly by `q->mq_freeze_lock`. Have `blk_freeze_set_owner()` / `__blk_freeze_queue_start()` and `blk_unfreeze_check_owner()` / `__blk_mq_unfreeze_queue()` return this `unsigned int` bitmask by value while holding `q->mq_freeze_lock` (`0` if not the outermost owner or if neither lockdep map applies). Pass the returned `lock_mask` by value into `blk_freeze_acquire_lock(q, lock_mask)` and `blk_unfreeze_release_lock(q, lock_mask)` outside `q->mq_freeze_lock`.
- This preserves strict LIFO lock ordering relative to `q->mq_freeze_lock` (avoiding `mq_freeze_lock -> q_lockdep_map` lockdep inversions on acquire and non-LIFO lockdep stack unwinding on release).
- It eliminates all unlocked reads of mutable `struct request_queue` lockdep state in `blk_freeze_acquire_lock()` and `blk_unfreeze_release_lock()`.
- It simplifies the control-flow graph at all call sites by folding the `bool` ownership check and individual lockdep map predicates into `lock_mask`.
2. **Avoid claiming freeze ownership on dying drains in `blk_queue_start_drain()`:**
Pass `blk_queue_dying(q) ? NULL : current` to `__blk_freeze_queue_start()` in `blk_queue_start_drain()` so that permanent/dying drains do not claim or increment `q->mq_freeze_owner_depth`.
---
#### 2. Exact Files, Structs, and Functions to Modify
##### A. `include/linux/blkdev.h`
* **`struct request_queue` (lines 636β645):**
Replace `bool mq_freeze_disk_dead;` and `bool mq_freeze_queue_dying;` under `#ifdef CONFIG_LOCKDEP` with `unsigned int mq_freeze_lock_mask;`:
```c
#ifdef CONFIG_LOCKDEP
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
/*
* Records lockdep locks acquired in owner context, used in unfreeze
* queue
*/
unsigned int mq_freeze_lock_mask;
#endif
```
##### B. `block/blk.h`
* **Function declarations (lines 58β61):**
Update the return types of `__blk_mq_unfreeze_queue()`, `blk_queue_start_drain()`, and `__blk_freeze_queue_start()` from `bool` to `unsigned int`:
```c
unsigned int __blk_mq_unfreeze_queue(struct request_queue *q,
bool force_atomic);
unsigned int blk_queue_start_drain(struct request_queue *q);
unsigned int __blk_freeze_queue_start(struct request_queue *q,
struct task_struct *owner);
```
* **Lockdep helpers `blk_freeze_acquire_lock()` and `blk_unfreeze_release_lock()` (lines 780β803):**
Define the lock mask flags and update both inline helpers to take `unsigned int lock_mask` instead of reading `q->mq_freeze_*`:
```c
enum {
BLK_FREEZE_LOCK_IO = (1 << 0),
BLK_FREEZE_LOCK_QUEUE = (1 << 1),
};
#ifdef CONFIG_LOCKDEP
static inline void blk_freeze_acquire_lock(struct request_queue *q,
unsigned int lock_mask)
{
if (lock_mask & BLK_FREEZE_LOCK_IO)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
if (lock_mask & BLK_FREEZE_LOCK_QUEUE)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
static inline void blk_unfreeze_release_lock(struct request_queue *q,
unsigned int lock_mask)
{
if (lock_mask & BLK_FREEZE_LOCK_QUEUE)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (lock_mask & BLK_FREEZE_LOCK_IO)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
#else
static inline void blk_freeze_acquire_lock(struct request_queue *q,
unsigned int lock_mask)
{
}
static inline void blk_unfreeze_release_lock(struct request_queue *q,
unsigned int lock_mask)
{
}
#endif
```
##### C. `block/blk-mq.c`
* **`blk_freeze_set_owner()` and `blk_unfreeze_check_owner()` (lines 115β161):**
Change return types from `bool` to `unsigned int`. Compute, store, and return `q->mq_freeze_lock_mask` while holding `q->mq_freeze_lock`:
```c
#ifdef CONFIG_LOCKDEP
static unsigned int blk_freeze_set_owner(struct request_queue *q,
struct task_struct *owner)
{
unsigned int lock_mask = 0;
if (!owner)
return 0;
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
if (q->disk && !test_bit(GD_DEAD, &q->disk->state) &&
blk_queue_registered(q))
lock_mask |= BLK_FREEZE_LOCK_IO;
if (!blk_queue_dying(q))
lock_mask |= BLK_FREEZE_LOCK_QUEUE;
q->mq_freeze_lock_mask = lock_mask;
return lock_mask;
}
if (owner == q->mq_freeze_owner)
q->mq_freeze_owner_depth += 1;
return 0;
}
/* verify the last unfreeze in owner context */
static unsigned int blk_unfreeze_check_owner(struct request_queue *q)
{
if (q->mq_freeze_owner != current)
return 0;
if (--q->mq_freeze_owner_depth == 0) {
q->mq_freeze_owner = NULL;
return q->mq_freeze_lock_mask;
}
return 0;
}
#else
static unsigned int blk_freeze_set_owner(struct request_queue *q,
struct task_struct *owner)
{
return 0;
}
static unsigned int blk_unfreeze_check_owner(struct request_queue *q)
{
return 0;
}
#endif
```
* **`__blk_freeze_queue_start()` and `blk_freeze_queue_start()` (lines 163β187):**
Return `lock_mask` from `__blk_freeze_queue_start()` and pass it to `blk_freeze_acquire_lock()`:
```c
unsigned int __blk_freeze_queue_start(struct request_queue *q,
struct task_struct *owner)
{
unsigned int lock_mask;
mutex_lock(&q->mq_freeze_lock);
lock_mask = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
if (queue_is_mq(q))
blk_mq_run_hw_queues(q, false);
} else {
mutex_unlock(&q->mq_freeze_lock);
}
return lock_mask;
}
void blk_freeze_queue_start(struct request_queue *q)
{
unsigned int lock_mask = __blk_freeze_queue_start(q, current);
blk_freeze_acquire_lock(q, lock_mask);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
```
* **`__blk_mq_unfreeze_queue()` and `blk_mq_unfreeze_queue_nomemrestore()` (lines 211β235):**
Return `lock_mask` from `__blk_mq_unfreeze_queue()` (captured under `q->mq_freeze_lock`) and pass it to `blk_unfreeze_release_lock()`:
```c
unsigned int __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
unsigned int lock_mask;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
q->q_usage_counter.data->force_atomic = true;
q->mq_freeze_depth--;
WARN_ON_ONCE(q->mq_freeze_depth < 0);
if (!q->mq_freeze_depth) {
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
}
lock_mask = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
return lock_mask;
}
void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
{
unsigned int lock_mask = __blk_mq_unfreeze_queue(q, false);
blk_unfreeze_release_lock(q, lock_mask);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_nomemrestore);
```
##### D. `block/blk-core.c`
* **`blk_queue_start_drain()` (lines 327β341):**
Change return type to `unsigned int` and pass `NULL` as owner if `blk_queue_dying(q)` is set:
```c
unsigned int blk_queue_start_drain(struct request_queue *q)
{
/*
* When queue DYING flag is set, we need to block new req
* entering queue, so we call blk_freeze_queue_start() to
* prevent I/O from crossing blk_queue_enter().
*/
unsigned int lock_mask = __blk_freeze_queue_start(q,
blk_queue_dying(q) ? NULL : current);
if (queue_is_mq(q))
blk_mq_wake_waiters(q);
/* Make blk_queue_enter() reexamine the DYING flag. */
wake_up_all(&q->mq_freeze_wq);
return lock_mask;
}
```
##### E. `block/genhd.c`
* **`__blk_mark_disk_dead()` (lines 660β680):**
Change return type from `bool` to `unsigned int` (returning `0` instead of `false` when `GD_DEAD` is already set).
* **`__del_gendisk()` (lines 697β782):**
Replace `bool start_drain;` with `unsigned int lock_mask;` and pass `lock_mask` to `blk_freeze_acquire_lock()` and `blk_unfreeze_release_lock()`:
```c
mutex_lock(&disk->open_mutex);
lock_mask = __blk_mark_disk_dead(disk);
blk_freeze_acquire_lock(q, lock_mask);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
...
if (!test_bit(GD_OWNS_QUEUE, &disk->state))
__blk_mq_unfreeze_queue(q, true);
else if (queue_is_mq(q))
blk_mq_exit_queue(q);
blk_unfreeze_release_lock(q, lock_mask);
```
---
#### 3. Caller Audit & Locking / Ordering Invariants
1. **All callers of modified functions:**
- `__blk_freeze_queue_start()`: called by `blk_freeze_queue_start()`, `blk_freeze_queue_start_non_owner()` (ignores return value), and `blk_queue_start_drain()` (propagates `unsigned int`).
- `blk_queue_start_drain()`: called by `blk_mq_destroy_queue()` (ignores return value) and `__blk_mark_disk_dead()` (propagates `unsigned int`).
- `__blk_mark_disk_dead()`: called by `blk_mark_disk_dead()` (ignores return value) and `__del_gendisk()` (stores `lock_mask`).
- `__blk_mq_unfreeze_queue()`: called by `blk_mq_unfreeze_queue_nomemrestore()`, `blk_mq_unfreeze_queue_non_owner()` (ignores return value), and `__del_gendisk()`.
- `blk_freeze_acquire_lock()` and `blk_unfreeze_release_lock()`: only called in `blk_freeze_queue_start()`, `blk_mq_unfreeze_queue_nomemrestore()`, and `__del_gendisk()`.
- No exported public APIs change signature (`blk_freeze_queue_start()` and `blk_mq_unfreeze_queue_nomemrestore()` retain `void` return type).
2. **Locking and Lockdep Ordering Rules:**
- `q->mq_freeze_lock_mask`, `q->mq_freeze_owner`, and `q->mq_freeze_owner_depth` must only be read or modified while holding `q->mq_freeze_lock`.
- `blk_freeze_acquire_lock(q, lock_mask)` and `blk_unfreeze_release_lock(q, lock_mask)` must be invoked **outside** `q->mq_freeze_lock`, operating exclusively on the local `lock_mask` value returned from the critical section, preserving LIFO order (`io_lockdep_map` then `q_lockdep_map` on acquire; `q_lockdep_map` then `io_lockdep_map` on release).
Reply: ### Analysis and Explanation of the Fix
#### Root Cause
The `WARNING: lock held when returning to user space!` warning on `&q->q_usage_counter(queue)` (`q->q_lockdep_map`) occurred because of a race between:
1. A thread performing `elevator_change()` (e.g., during table loading of a request-based device mapper target via `dm_setup_md_queue()` -> `add_disk()` -> `blk_register_queue()` -> `elevator_set_default()`), which calls `blk_mq_freeze_queue()` followed by `blk_mq_unfreeze_queue()`.
2. A concurrent thread calling `blk_mark_disk_dead()` (e.g., during device removal via `dm_destroy()`), which sets `QUEUE_FLAG_DYING` and starts queue draining via `__blk_freeze_queue_start()`.
Previously, the lockdep tracking for queue freeze/unfreeze stored `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead` directly in `struct request_queue`, protected by `q->mq_freeze_lock` only during freeze initiation when `!q->mq_freeze_depth`. On unfreeze, `__blk_mq_unfreeze_queue()` decremented `q->mq_freeze_depth` to `0`, cleared `q->mq_freeze_owner = NULL`, and dropped `q->mq_freeze_lock`. Only **after** unlocking did `blk_mq_unfreeze_queue_nomemrestore()` invoke `blk_unfreeze_release_lock(q)`.
Because `q->mq_freeze_lock` was dropped while depth was 0, a concurrent call to `blk_mark_disk_dead()` could acquire `q->mq_freeze_lock`, see `!q->mq_freeze_depth`, and overwrite `q->mq_freeze_queue_dying = true` before `blk_unfreeze_release_lock(q)` executed on the unfreezing thread. As a result, `blk_unfreeze_release_lock()` evaluated `!q->mq_freeze_queue_dying` as `false` and skipped releasing `q->q_lockdep_map`, leaking the held lockdep lock back to user space.
Furthermore, `blk_queue_start_drain()` previously passed `current` as the freeze owner to `__blk_freeze_queue_start()`. When `QUEUE_FLAG_DYING` was set, queue draining is permanent and does not release lockdep maps; setting or incrementing freeze ownership on dying queues could corrupt owner tracking if called in contexts already holding an outer freeze.
---
#### Implementation Details
1. **Per-Queue State Replaced with a Snapshotted Lock Mask:**
- In `struct request_queue` (`include/linux/blkdev.h`), replaced `bool mq_freeze_disk_dead` and `bool mq_freeze_queue_dying` with `unsigned int mq_freeze_lock_mask`.
- Defined `BLK_FREEZE_LOCK_IO` and `BLK_FREEZE_LOCK_QUEUE` bit flags in `block/blk.h`.
- Updated `blk_freeze_acquire_lock()` and `blk_unfreeze_release_lock()` to accept `unsigned int lock_mask` by value, removing all unlocked reads of mutable `request_queue` lockdep fields. Lock release order (`BLK_FREEZE_LOCK_QUEUE` followed by `BLK_FREEZE_LOCK_IO`) preserves strict LIFO ordering relative to lock acquisition.
2. **Snapshotting Lock Masks Under `q->mq_freeze_lock`:**
- In `block/blk-mq.c`, `blk_freeze_set_owner()` computes and records the applicable lock mask (`q->mq_freeze_lock_mask`) only on the outermost freeze (`!q->mq_freeze_depth`) under `q->mq_freeze_lock`, and returns it by value. Nested freezes return 0.
- `blk_unfreeze_check_owner()` returns `q->mq_freeze_lock_mask` by value when `mq_freeze_owner_depth` reaches 0 under `q->mq_freeze_lock`.
- `__blk_freeze_queue_start()` and `__blk_mq_unfreeze_queue()` return this `unsigned int lock_mask` from within their `q->mq_freeze_lock` critical sections.
- Callers (`blk_freeze_queue_start()` and `blk_mq_unfreeze_queue_nomemrestore()`) pass the returned `lock_mask` into `blk_freeze_acquire_lock()` and `blk_unfreeze_release_lock()` respectively. Because the unfreezing thread holds its own copy of `lock_mask` on the stack, concurrent freezes modifying `request_queue` fields can no longer corrupt the unfreeze lockdep release.
3. **Queue Draining Ownership Handling:**
- In `blk_queue_start_drain()` (`block/blk-core.c`), pass `blk_queue_dying(q) ? NULL : current` to `__blk_freeze_queue_start()` so that permanent dying drains do not claim or increment freeze owner depth.
- Updated `__blk_mark_disk_dead()` and `__del_gendisk()` (`block/genhd.c`) to propagate and consume the `unsigned int lock_mask` when acquiring and releasing queue freeze locks across partition drop and gendisk teardown.
|
| 450/4 |
2026/11/03 21:15 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 14920
output: 38
thoughts: 261
Thoughts: **Analyzing the Bug Fix Implementation Plan**
Okay, let's take a methodical approach to this. First, I need to thoroughly understand the prompt and implementation plan β ensuring I haven't missed any nuances in the bug description or the proposed solution. The crash report pinpoints the core issue: a "lock held when returning to user space" warning, specifically involving `&q->q_usage_counter` being held at the `elevator_change` point, traced back through `blk_mq_freeze_queue`. The root cause analysis lays it bare: a race condition where `blk_unfreeze_release_lock` is reading `q->mq_freeze_queue_dying` outside the protection of `q->mq_freeze_lock` after the freeze depth hits zero and the lock is released. Then, `blk_mark_disk_dead()` comes in and overwrites the relevant data. This makes perfect sense.
Now, onto the implementation itself. The plan is well-defined, thankfully. I'll start by diving into the files mentioned: `include/linux/blkdev.h`, `block/blk.h`, `block/blk-mq.c`, `block/blk-core.c`, and `block/genhd.c`. Before I even think about making any edits, I'll leverage `read-file` or `grepper` β whatever's most efficient β to precisely inspect the relevant lines of code within each of these files. Understanding the existing code is paramount before introducing any changes, no matter how small. A meticulous line-by-line inspection is the order of the day.
|
| 451/4 |
2026/11/03 21:16 |
tool |
grepper |
0m
Args: map[Expression:mq_freeze_ PathPrefixes:[include/linux/blkdev.h block/]]
Results: map[Output:
Full output is too long, showing 200 out of 309 lines.
Use more precise expression or PathPrefixes if possible.
Number of matching lines per file (16 files in total):
block/bfq-iosched.c:1
block/blk-cgroup.c:2
block/blk-core.c:11
block/blk-iocost.c:2
block/blk-iolatency.c:1
block/blk-mq.c:33
block/blk-rq-qos.c:2
block/blk-settings.c:1
block/blk-sysfs.c:3
block/blk-throttle.c:1
block/blk-wbt.c:1
block/blk-zoned.c:1
block/blk.h:4
block/elevator.c:4
block/genhd.c:1
include/linux/blkdev.h:8
block/bfq-iosched.c=7196=static int bfq_init_queue(struct request_queue *q, struct elevator_queue *eq)
--
block/bfq-iosched.c-7329- * (bfq_create_group_hierarchy->blkcg_activate_policy->
block/bfq-iosched.c:7330: * blk_mq_freeze_queue) that may lead to the invocation of the
block/bfq-iosched.c-7331- * has_work hook function. For this reason,
--
block/blk-cgroup.c=1608=int blkcg_activate_policy(struct gendisk *disk, const struct blkcg_policy *pol)
--
block/blk-cgroup.c-1627- if (queue_is_mq(q))
block/blk-cgroup.c:1628: memflags = blk_mq_freeze_queue(q);
block/blk-cgroup.c-1629-
--
block/blk-cgroup.c=1723=void blkcg_deactivate_policy(struct gendisk *disk,
--
block/blk-cgroup.c-1732- if (queue_is_mq(q))
block/blk-cgroup.c:1733: memflags = blk_mq_freeze_queue(q);
block/blk-cgroup.c-1734-
--
block/blk-core.c=281=void blk_clear_pm_only(struct request_queue *q)
--
block/blk-core.c-287- if (pm_only == 0)
block/blk-core.c:288: wake_up_all(&q->mq_freeze_wq);
block/blk-core.c-289-}
--
block/blk-core.c=327=bool blk_queue_start_drain(struct request_queue *q)
--
block/blk-core.c-337- /* Make blk_queue_enter() reexamine the DYING flag. */
block/blk-core.c:338: wake_up_all(&q->mq_freeze_wq);
block/blk-core.c-339-
--
block/blk-core.c=348=int blk_queue_enter(struct request_queue *q, blk_mq_req_flags_t flags)
--
block/blk-core.c-358- * order reading __PERCPU_REF_DEAD flag of .q_usage_counter and
block/blk-core.c:359: * reading .mq_freeze_depth or queue dying flag, otherwise the
block/blk-core.c-360- * following wait may never return if the two reads are
--
block/blk-core.c-363- smp_rmb();
block/blk-core.c:364: wait_event(q->mq_freeze_wq,
block/blk-core.c:365: (!q->mq_freeze_depth &&
block/blk-core.c-366- blk_pm_resume_queue(pm, q)) ||
--
block/blk-core.c=377=int __bio_queue_enter(struct request_queue *q, struct bio *bio)
--
block/blk-core.c-391- * order reading __PERCPU_REF_DEAD flag of .q_usage_counter and
block/blk-core.c:392: * reading .mq_freeze_depth or queue dying flag, otherwise the
block/blk-core.c-393- * following wait may never return if the two reads are
--
block/blk-core.c-396- smp_rmb();
block/blk-core.c:397: wait_event(q->mq_freeze_wq,
block/blk-core.c:398: (!q->mq_freeze_depth &&
block/blk-core.c-399- blk_pm_resume_queue(false, q)) ||
--
block/blk-core.c=418=static void blk_queue_usage_counter_release(struct percpu_ref *ref)
--
block/blk-core.c-422-
block/blk-core.c:423: wake_up_all(&q->mq_freeze_wq);
block/blk-core.c-424-}
--
block/blk-core.c=437=struct request_queue *blk_alloc_queue(struct queue_limits *lim, int node_id)
--
block/blk-core.c-481-
block/blk-core.c:482: init_waitqueue_head(&q->mq_freeze_wq);
block/blk-core.c:483: mutex_init(&q->mq_freeze_lock);
block/blk-core.c-484-
--
block/blk-iocost.c=3366=static ssize_t ioc_qos_write(struct kernfs_open_file *of, char *input,
--
block/blk-iocost.c-3391-
block/blk-iocost.c:3392: memflags = blk_mq_freeze_queue(ctx.bdev->bd_queue);
block/blk-iocost.c-3393- mutex_lock(&ctx.bdev->bd_queue->rq_qos_mutex);
--
block/blk-iocost.c=3572=static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
--
block/blk-iocost.c-3604-
block/blk-iocost.c:3605: memflags = blk_mq_freeze_queue(q);
block/blk-iocost.c-3606- blk_mq_quiesce_queue(q);
--
block/blk-iolatency.c=729=static void blkiolatency_enable_work_fn(struct work_struct *work)
--
block/blk-iolatency.c-748-
block/blk-iolatency.c:749: memflags = blk_mq_freeze_queue(blkiolat->rqos.disk->queue);
block/blk-iolatency.c-750- blkiolat->enabled = enabled;
--
block/blk-mq.c=116=static bool blk_freeze_set_owner(struct request_queue *q,
--
block/blk-mq.c-121-
block/blk-mq.c:122: if (!q->mq_freeze_depth) {
block/blk-mq.c:123: q->mq_freeze_owner = owner;
block/blk-mq.c:124: q->mq_freeze_owner_depth = 1;
block/blk-mq.c:125: q->mq_freeze_disk_dead = !q->disk ||
block/blk-mq.c-126- test_bit(GD_DEAD, &q->disk->state) ||
block/blk-mq.c-127- !blk_queue_registered(q);
block/blk-mq.c:128: q->mq_freeze_queue_dying = blk_queue_dying(q);
block/blk-mq.c-129- return true;
--
block/blk-mq.c-131-
block/blk-mq.c:132: if (owner == q->mq_freeze_owner)
block/blk-mq.c:133: q->mq_freeze_owner_depth += 1;
block/blk-mq.c-134- return false;
--
block/blk-mq.c=138=static bool blk_unfreeze_check_owner(struct request_queue *q)
block/blk-mq.c-139-{
block/blk-mq.c:140: if (q->mq_freeze_owner != current)
block/blk-mq.c-141- return false;
block/blk-mq.c:142: if (--q->mq_freeze_owner_depth == 0) {
block/blk-mq.c:143: q->mq_freeze_owner = NULL;
block/blk-mq.c-144- return true;
--
block/blk-mq.c=163=bool __blk_freeze_queue_start(struct request_queue *q,
--
block/blk-mq.c-167-
block/blk-mq.c:168: mutex_lock(&q->mq_freeze_lock);
block/blk-mq.c-169- freeze = blk_freeze_set_owner(q, owner);
block/blk-mq.c:170: if (++q->mq_freeze_depth == 1) {
block/blk-mq.c-171- percpu_ref_kill(&q->q_usage_counter);
block/blk-mq.c:172: mutex_unlock(&q->mq_freeze_lock);
block/blk-mq.c-173- if (queue_is_mq(q))
--
block/blk-mq.c-175- } else {
block/blk-mq.c:176: mutex_unlock(&q->mq_freeze_lock);
block/blk-mq.c-177- }
--
block/blk-mq.c=187=EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
block/blk-mq.c-188-
block/blk-mq.c:189:void blk_mq_freeze_queue_wait(struct request_queue *q)
block/blk-mq.c-190-{
block/blk-mq.c:191: wait_event(q->mq_freeze_wq, percpu_ref_is_zero(&q->q_usage_counter));
block/blk-mq.c-192-}
block/blk-mq.c:193:EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait);
block/blk-mq.c-194-
block/blk-mq.c:195:int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
block/blk-mq.c-196- unsigned long timeout)
block/blk-mq.c-197-{
block/blk-mq.c:198: return wait_event_timeout(q->mq_freeze_wq,
block/blk-mq.c-199- percpu_ref_is_zero(&q->q_usage_counter),
--
block/blk-mq.c-201-}
block/blk-mq.c:202:EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait_timeout);
block/blk-mq.c-203-
block/blk-mq.c:204:void blk_mq_freeze_queue_nomemsave(struct request_queue *q)
block/blk-mq.c-205-{
block/blk-mq.c-206- blk_freeze_queue_start(q);
block/blk-mq.c:207: blk_mq_freeze_queue_wait(q);
block/blk-mq.c-208-}
block/blk-mq.c:209:EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_nomemsave);
block/blk-mq.c-210-
block/blk-mq.c=211=bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
--
block/blk-mq.c-214-
block/blk-mq.c:215: mutex_lock(&q->mq_freeze_lock);
block/blk-mq.c-216- if (force_atomic)
block/blk-mq.c-217- q->q_usage_counter.data->force_atomic = true;
block/blk-mq.c:218: q->mq_freeze_depth--;
block/blk-mq.c:219: WARN_ON_ONCE(q->mq_freeze_depth < 0);
block/blk-mq.c:220: if (!q->mq_freeze_depth) {
block/blk-mq.c-221- percpu_ref_resurrect(&q->q_usage_counter);
block/blk-mq.c:222: wake_up_all(&q->mq_freeze_wq);
block/blk-mq.c-223- }
block/blk-mq.c-224- unfreeze = blk_unfreeze_check_owner(q);
block/blk-mq.c:225: mutex_unlock(&q->mq_freeze_lock);
block/blk-mq.c-226-
--
block/blk-mq.c=4328=static void blk_mq_update_tag_set_shared(struct blk_mq_tag_set *set,
--
block/blk-mq.c-4336- list_for_each_entry(q, &set->tag_list, tag_set_list) {
block/blk-mq.c:4337: memflags = blk_mq_freeze_queue(q);
block/blk-mq.c-4338- queue_set_hctx_shared(q, shared);
--
block/blk-mq.c=4483=void blk_mq_destroy_queue(struct request_queue *q)
--
block/blk-mq.c-4491- blk_queue_start_drain(q);
block/blk-mq.c:4492: blk_mq_freeze_queue_wait(q);
block/blk-mq.c-4493-
--
block/blk-mq.c=5165=static void __blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set,
--
block/blk-mq.c-5212- list_for_each_entry(q, &set->tag_list, tag_set_list)
block/blk-mq.c:5213: blk_mq_freeze_queue_nomemsave(q);
block/blk-mq.c-5214- queues_frozen = true;
--
block/blk-mq.c-5246- if (!queues_frozen)
block/blk-mq.c:5247: blk_mq_freeze_queue_nomemsave(q);
block/blk-mq.c-5248- blk_mq_elv_switch_back(q, &elv_tbl);
--
block/blk-rq-qos.c=325=int rq_qos_add(struct rq_qos *rqos, struct gendisk *disk, enum rq_qos_id id,
--
block/blk-rq-qos.c-340- */
block/blk-rq-qos.c:341: memflags = blk_mq_freeze_queue(q);
block/blk-rq-qos.c-342-
--
block/blk-rq-qos.c=356=void rq_qos_del(struct rq_qos *rqos)
--
block/blk-rq-qos.c-363-
block/blk-rq-qos.c:364: memflags = blk_mq_freeze_queue(q);
block/blk-rq-qos.c-365- for (cur = &q->rq_qos; *cur; cur = &(*cur)->next) {
--
block/blk-settings.c=592=int queue_limits_commit_update_frozen(struct request_queue *q,
--
block/blk-settings.c-597-
block/blk-settings.c:598: memflags = blk_mq_freeze_queue(q);
]
|
| 452/4 |
2026/11/03 21:16 |
llm |
patch-generator |
2m
Model:
Tokens:
input: 19801
output: 36
thoughts: 52
Thoughts: Okay, let's dive into this. I need to get a solid understanding of how the block layer is functioning under the hood. To really grasp this, I'm going to start by going straight to the source.
**Diving Deep into the Block Layer**
First things first, I'm reaching for the header files. I'm going to pore over `include/linux/blkdev.h`. This should give me a high-level view of the core data structures and key definitions at the very foundation of the block layer. From there, I'll switch over to `block/blk.h` as that should fill in any gaps and provide further critical foundational definitions.
Once I've established that base, it's time to start tracing the execution flow. I'll need to scrutinize the `block/blk-mq.c` file and understand the intricacies of the multi-queue block layer. This is where the magic of concurrency happens, so I need a very clear picture of the queuing mechanisms and how requests are dispatched.
Then, I'll follow up with `block/blk-core.c`. This is likely where the heart of the block layer logic resides. I'll focus on request handling, I/O scheduling, and device interaction to understand how it all fits together.
Finally, I'll peek into `block/genhd.c`. This will give me perspective on how generic disk headers are handled and I'll gain some context to how the individual devices are structured within the overall system. I'm looking for the commonalities and the variations. By focusing on these key files, I should get a really clear picture of how the block layer works within this system.
|
| 453/4 |
2026/11/03 21:18 |
tool |
read-file |
0m
Args: map[File:include/linux/blkdev.h FirstLine:630 LineCount:30]
Results: map[Contents: 630:
631: #ifdef CONFIG_BLK_DEV_THROTTLING
632: /* Throttle data */
633: struct throtl_data *td;
634: #endif
635: struct rcu_head rcu_head;
636: #ifdef CONFIG_LOCKDEP
637: struct task_struct *mq_freeze_owner;
638: int mq_freeze_owner_depth;
639: /*
640: * Records disk & queue state in current context, used in unfreeze
641: * queue
642: */
643: bool mq_freeze_disk_dead;
644: bool mq_freeze_queue_dying;
645: #endif
646: wait_queue_head_t mq_freeze_wq;
647: /*
648: * Protect concurrent access to q_usage_counter by
649: * percpu_ref_kill() and percpu_ref_reinit().
650: */
651: struct mutex mq_freeze_lock;
652:
653: struct blk_mq_tag_set *tag_set;
654: struct list_head tag_set_list;
655:
656: struct dentry *debugfs_dir;
657: struct dentry *sched_debugfs_dir;
658: struct dentry *rqos_debugfs_dir;
659: /*
]
|
| 454/4 |
2026/11/03 21:18 |
llm |
patch-generator |
2m
Model:
Tokens:
input: 20691
output: 32
thoughts: 12
Thoughts: Here's my take on the thought process, as requested:
**Diving into Block Device Headers**
Okay, time to get my hands dirty. I need to understand the low-level block device interaction, so I'm heading straight for the `block/blk.h` header file. This is where the magic happens, the core definitions and structures that control how we talk to storage devices. I'm expecting to find the key data structures here, the layout of request queues, descriptors for I/O operations, and probably a lot of low-level definitions regarding alignment and sector sizing. This is where the rubber meets the road, so to speak, in terms of the kernel and the physical hardware. Let's see what gems are hidden in there.
|
| 455/4 |
2026/11/03 21:21 |
tool |
read-file |
0m
Args: map[File:block/blk.h FirstLine:50 LineCount:30]
Results: map[Contents: 50: gfp_t flags);
51: void blk_free_flush_queue(struct blk_flush_queue *q);
52:
53: const char *blk_status_to_str(blk_status_t status);
54: const char *blk_status_to_tag(blk_status_t status);
55: blk_status_t tag_to_blk_status(const char *tag);
56: enum req_op str_to_blk_op(const char *op);
57:
58: bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
59: bool blk_queue_start_drain(struct request_queue *q);
60: bool __blk_freeze_queue_start(struct request_queue *q,
61: struct task_struct *owner);
62: int __bio_queue_enter(struct request_queue *q, struct bio *bio);
63: void submit_bio_noacct_nocheck(struct bio *bio, bool split);
64: int bio_submit_or_kill(struct bio *bio, unsigned int flags);
65:
66: static inline bool blk_try_enter_queue(struct request_queue *q, bool pm)
67: {
68: rcu_read_lock();
69: if (!percpu_ref_tryget_live_rcu(&q->q_usage_counter))
70: goto fail;
71:
72: /*
73: * The code that increments the pm_only counter must ensure that the
74: * counter is globally visible before the queue is unfrozen.
75: */
76: if (blk_queue_pm_only(q) &&
77: (!pm || queue_rpm_status(q) == RPM_SUSPENDED))
78: goto fail_put;
79:
]
|
| 456/4 |
2026/11/03 21:21 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 21430
output: 33
thoughts: 24
Thoughts: Here's a summary of my thought process, keeping in mind my field of expertise:
**Diving Deeper into Block Device Implementation**
Okay, so we're investigating this issue. To get a comprehensive understanding, I think it's crucial to examine the core of the block device interaction. Let's shift our focus to the `block/blk.h` header file. Specifically, I want to zero in on lines 780-810. That range often contains key definitions related to [insert specific areas relevant to the user's field, e.g., request queuing, I/O scheduling parameters, error handling structures, bio construction]. By understanding the structures and macros declared within that block, I can better assess [insert specific objectives, e.g., the potential impact of the current problem on I/O performance, whether the issue stems from a configuration discrepancy, the specific place in the block I/O processing where the problem manifests]. This should give us valuable context.
|
| 457/4 |
2026/11/03 21:23 |
tool |
read-file |
0m
Args: map[File:block/blk.h FirstLine:770 LineCount:45]
Results: map[Contents: 770: const struct blk_holder_ops *hops, struct file *bdev_file);
771: int bdev_permission(dev_t dev, blk_mode_t mode, void *holder);
772:
773: void bio_integrity_generate(struct bio *bio);
774: blk_status_t bio_integrity_verify(struct bio *bio,
775: struct bvec_iter *saved_iter);
776:
777: void blk_integrity_prepare(struct request *rq);
778: void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
779:
780: #ifdef CONFIG_LOCKDEP
781: static inline void blk_freeze_acquire_lock(struct request_queue *q)
782: {
783: if (!q->mq_freeze_disk_dead)
784: rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
785: if (!q->mq_freeze_queue_dying)
786: rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
787: }
788:
789: static inline void blk_unfreeze_release_lock(struct request_queue *q)
790: {
791: if (!q->mq_freeze_queue_dying)
792: rwsem_release(&q->q_lockdep_map, _RET_IP_);
793: if (!q->mq_freeze_disk_dead)
794: rwsem_release(&q->io_lockdep_map, _RET_IP_);
795: }
796: #else
797: static inline void blk_freeze_acquire_lock(struct request_queue *q)
798: {
799: }
800: static inline void blk_unfreeze_release_lock(struct request_queue *q)
801: {
802: }
803: #endif
804:
805: /*
806: * debugfs directory and file creation can trigger fs reclaim, which can enter
807: * back into the block layer request_queue. This can cause deadlock if the
808: * queue is frozen. Use NOIO context together with debugfs_mutex to prevent fs
809: * reclaim from triggering block I/O.
810: */
811: static inline void blk_debugfs_lock_nomemsave(struct request_queue *q)
812: __acquires(&q->debugfs_mutex)
813: {
814: mutex_lock(&q->debugfs_mutex);
]
|
| 458/4 |
2026/11/03 21:23 |
llm |
patch-generator |
3m
Model:
Tokens:
input: 22474
output: 35
thoughts: 14
Thoughts: Okay, let's dive into this. I'm going to take a look at the `block/blk-mq.c` file. This is where the core of the multi-queue block layer implementation resides, so I need to understand its structure, how it handles requests, and what's going on with the queuing and dispatching. I'll be looking for the key data structures, the lock contention points, and how it handles concurrency. I'll need to refresh my understanding of how this ties into the rest of the block layer and the device drivers. Let's see what gems are hidden in this code!
|
| 459/4 |
2026/11/03 21:26 |
tool |
read-file |
0m
Args: map[File:block/blk-mq.c FirstLine:110 LineCount:80]
Results: map[Contents: 110: &mi);
111: inflight[READ] = mi.inflight[READ];
112: inflight[WRITE] = mi.inflight[WRITE];
113: }
114:
115: #ifdef CONFIG_LOCKDEP
116: static bool blk_freeze_set_owner(struct request_queue *q,
117: struct task_struct *owner)
118: {
119: if (!owner)
120: return false;
121:
122: if (!q->mq_freeze_depth) {
123: q->mq_freeze_owner = owner;
124: q->mq_freeze_owner_depth = 1;
125: q->mq_freeze_disk_dead = !q->disk ||
126: test_bit(GD_DEAD, &q->disk->state) ||
127: !blk_queue_registered(q);
128: q->mq_freeze_queue_dying = blk_queue_dying(q);
129: return true;
130: }
131:
132: if (owner == q->mq_freeze_owner)
133: q->mq_freeze_owner_depth += 1;
134: return false;
135: }
136:
137: /* verify the last unfreeze in owner context */
138: static bool blk_unfreeze_check_owner(struct request_queue *q)
139: {
140: if (q->mq_freeze_owner != current)
141: return false;
142: if (--q->mq_freeze_owner_depth == 0) {
143: q->mq_freeze_owner = NULL;
144: return true;
145: }
146: return false;
147: }
148:
149: #else
150:
151: static bool blk_freeze_set_owner(struct request_queue *q,
152: struct task_struct *owner)
153: {
154: return false;
155: }
156:
157: static bool blk_unfreeze_check_owner(struct request_queue *q)
158: {
159: return false;
160: }
161: #endif
162:
163: bool __blk_freeze_queue_start(struct request_queue *q,
164: struct task_struct *owner)
165: {
166: bool freeze;
167:
168: mutex_lock(&q->mq_freeze_lock);
169: freeze = blk_freeze_set_owner(q, owner);
170: if (++q->mq_freeze_depth == 1) {
171: percpu_ref_kill(&q->q_usage_counter);
172: mutex_unlock(&q->mq_freeze_lock);
173: if (queue_is_mq(q))
174: blk_mq_run_hw_queues(q, false);
175: } else {
176: mutex_unlock(&q->mq_freeze_lock);
177: }
178:
179: return freeze;
180: }
181:
182: void blk_freeze_queue_start(struct request_queue *q)
183: {
184: if (__blk_freeze_queue_start(q, current))
185: blk_freeze_acquire_lock(q);
186: }
187: EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
188:
189: void blk_mq_freeze_queue_wait(struct request_queue *q)
]
|
| 460/4 |
2026/11/03 21:26 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 23780
output: 35
thoughts: 26
Thoughts: Okay, let's dive into this. Here's my take on those lines in `block/blk-mq.c`.
**Diving into blk-mq.c: Lines 210-250**
Alright, so we're talking about `block/blk-mq.c` in the 210-250 range, huh? Let's quickly refresh the context... that's where we're likely dealing with the core mechanics of the Multi-Queue Block Layer, probably around how requests are being handled or perhaps dispatched to hardware. Knowing that, I'm expecting to find some crucial work management happening here. Probably some kind of function that manages request queueing, scheduling, or perhaps even the initial stages of sending requests to the storage devices. Depending on how the code is structured, I anticipate we'll see some interaction with per-queue data structures, maybe lock acquisition or release for thread safety, and definitely some crucial calls into the hardware-specific driver interface. We might see how requests are assigned to different queues. We may even see how the block layer handles error conditions or throttling. The goal, ultimately, is to ensure that requests are managed efficiently and delivered to the hardware with minimal overhead. It's likely we'll see the core request processing loop or perhaps the initial steps of a request being submitted to a specific queue. I need to keep an eye out for any interactions with the scheduler as well. We should be able to deduce the core functions around this chunk of code by looking at it closely.
|
| 461/4 |
2026/11/03 21:27 |
tool |
read-file |
0m
Args: map[File:block/blk-mq.c FirstLine:210 LineCount:40]
Results: map[Contents: 210:
211: bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
212: {
213: bool unfreeze;
214:
215: mutex_lock(&q->mq_freeze_lock);
216: if (force_atomic)
217: q->q_usage_counter.data->force_atomic = true;
218: q->mq_freeze_depth--;
219: WARN_ON_ONCE(q->mq_freeze_depth < 0);
220: if (!q->mq_freeze_depth) {
221: percpu_ref_resurrect(&q->q_usage_counter);
222: wake_up_all(&q->mq_freeze_wq);
223: }
224: unfreeze = blk_unfreeze_check_owner(q);
225: mutex_unlock(&q->mq_freeze_lock);
226:
227: return unfreeze;
228: }
229:
230: void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
231: {
232: if (__blk_mq_unfreeze_queue(q, false))
233: blk_unfreeze_release_lock(q);
234: }
235: EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_nomemrestore);
236:
237: /*
238: * non_owner variant of blk_freeze_queue_start
239: *
240: * Unlike blk_freeze_queue_start, the queue doesn't need to be unfrozen
241: * by the same task. This is fragile and should not be used if at all
242: * possible.
243: */
244: void blk_freeze_queue_start_non_owner(struct request_queue *q)
245: {
246: __blk_freeze_queue_start(q, NULL);
247: }
248: EXPORT_SYMBOL_GPL(blk_freeze_queue_start_non_owner);
249:
]
|
| 462/4 |
2026/11/03 21:28 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 24805
output: 35
thoughts: 44
Thoughts: Okay, let's dive into this.
**Examining `blk_mq_unfreeze_queue_non_owner` in `block/blk-mq.c`**
Alright, I'm going to pull up the source code for `blk_mq_unfreeze_queue_non_owner` in `block/blk-mq.c`. I need to understand its behavior, specifically focusing on lines 245 through 265. I'll need to absorb the critical logic within that section to evaluate its operation within the larger block I/O context. I'll be looking for potential race conditions or synchronization issues, and how it handles the non-owner unfreezing scenario. This is crucial for understanding the implications on queue management and performance, and especially for any potential impact on block device stability and data integrity. Let's see what's being done here.
|
| 463/4 |
2026/11/03 21:29 |
tool |
read-file |
0m
Args: map[File:block/blk-mq.c FirstLine:245 LineCount:25]
Results: map[Contents: 245: {
246: __blk_freeze_queue_start(q, NULL);
247: }
248: EXPORT_SYMBOL_GPL(blk_freeze_queue_start_non_owner);
249:
250: /* non_owner variant of blk_mq_unfreeze_queue */
251: void blk_mq_unfreeze_queue_non_owner(struct request_queue *q)
252: {
253: __blk_mq_unfreeze_queue(q, false);
254: }
255: EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_non_owner);
256:
257: /*
258: * FIXME: replace the scsi_internal_device_*block_nowait() calls in the
259: * mpt3sas driver such that this function can be removed.
260: */
261: void blk_mq_quiesce_queue_nowait(struct request_queue *q)
262: {
263: unsigned long flags;
264:
265: spin_lock_irqsave(&q->queue_lock, flags);
266: if (!q->quiesce_depth++)
267: blk_queue_flag_set(QUEUE_FLAG_QUIESCED, q);
268: spin_unlock_irqrestore(&q->queue_lock, flags);
269: }
]
|
| 464/4 |
2026/11/03 21:29 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 25491
output: 35
thoughts: 29
Thoughts: Here's my summary, as if I were thinking these thoughts:
**Diving into blk-core.c**
Alright, time to get into the nitty-gritty. Let's start by zeroing in on `block/blk-core.c`. I know this is where a lot of the fundamental block layer interactions are handled. My goal is to get a deeper understanding of the request queueing. I think I will focus on lines 320 to 350. I will analyze the section for any nuances relating to error handling. This could be where the interesting stuff happens. I bet I will find some insights in here.
|
| 465/4 |
2026/11/03 21:30 |
tool |
read-file |
0m
Args: map[File:block/blk-core.c FirstLine:320 LineCount:30]
Results: map[Contents: 320: void blk_put_queue(struct request_queue *q)
321: {
322: if (refcount_dec_and_test(&q->refs))
323: blk_free_queue(q);
324: }
325: EXPORT_SYMBOL(blk_put_queue);
326:
327: bool blk_queue_start_drain(struct request_queue *q)
328: {
329: /*
330: * When queue DYING flag is set, we need to block new req
331: * entering queue, so we call blk_freeze_queue_start() to
332: * prevent I/O from crossing blk_queue_enter().
333: */
334: bool freeze = __blk_freeze_queue_start(q, current);
335: if (queue_is_mq(q))
336: blk_mq_wake_waiters(q);
337: /* Make blk_queue_enter() reexamine the DYING flag. */
338: wake_up_all(&q->mq_freeze_wq);
339:
340: return freeze;
341: }
342:
343: /**
344: * blk_queue_enter() - try to increase q->q_usage_counter
345: * @q: request queue pointer
346: * @flags: BLK_MQ_REQ_NOWAIT and/or BLK_MQ_REQ_PM
347: */
348: int blk_queue_enter(struct request_queue *q, blk_mq_req_flags_t flags)
349: {
]
|
| 466/4 |
2026/11/03 21:30 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 26185
output: 34
thoughts: 28
Thoughts: Here's my analysis of the provided text, rendered in the first person, assuming an expert user:
**Diving into `block/genhd.c`**
Alright, let's get down to brass tacks. I'm going to zero in on `block/genhd.c` and specifically, I'm directing my focus to lines 650 through 790. That's where the critical stuff is likely to be β I'm anticipating some core functionality related toβ¦ well, based on the file name, most likely generating or manipulating hard disk images. I want to quickly evaluate that section; likely look at the error conditions being checked and how they're handled. It's time to dig in and see what's happening.
|
| 467/4 |
2026/11/03 21:31 |
tool |
read-file |
0m
Args: map[File:block/genhd.c FirstLine:650 LineCount:90]
Results: map[Contents: 650: rcu_read_unlock();
651:
652: bdev_mark_dead(bdev, surprise);
653:
654: put_device(&bdev->bd_device);
655: rcu_read_lock();
656: }
657: rcu_read_unlock();
658: }
659:
660: static bool __blk_mark_disk_dead(struct gendisk *disk)
661: {
662: /*
663: * Fail any new I/O.
664: */
665: if (test_and_set_bit(GD_DEAD, &disk->state))
666: return false;
667:
668: if (test_bit(GD_OWNS_QUEUE, &disk->state))
669: blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
670:
671: /*
672: * Stop buffered writers from dirtying pages that can't be written out.
673: */
674: set_capacity(disk, 0);
675:
676: /*
677: * Prevent new I/O from crossing bio_queue_enter().
678: */
679: return blk_queue_start_drain(disk->queue);
680: }
681:
682: /**
683: * blk_mark_disk_dead - mark a disk as dead
684: * @disk: disk to mark as dead
685: *
686: * Mark as disk as dead (e.g. surprise removed) and don't accept any new I/O
687: * to this disk.
688: */
689: void blk_mark_disk_dead(struct gendisk *disk)
690: {
691: blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
692: __blk_mark_disk_dead(disk);
693: blk_report_disk_dead(disk, true);
694: }
695: EXPORT_SYMBOL_GPL(blk_mark_disk_dead);
696:
697: static void __del_gendisk(struct gendisk *disk)
698: {
699: struct request_queue *q = disk->queue;
700: struct block_device *part;
701: unsigned long idx;
702: bool start_drain;
703:
704: might_sleep();
705:
706: if (WARN_ON_ONCE(!disk_live(disk) && !(disk->flags & GENHD_FL_HIDDEN)))
707: return;
708:
709: disk_del_events(disk);
710:
711: /*
712: * Prevent new openers by unlinked the bdev inode.
713: */
714: mutex_lock(&disk->open_mutex);
715: xa_for_each(&disk->part_tbl, idx, part)
716: bdev_unhash(part);
717: mutex_unlock(&disk->open_mutex);
718:
719: /*
720: * Tell the file system to write back all dirty data and shut down if
721: * it hasn't been notified earlier.
722: */
723: if (!test_bit(GD_DEAD, &disk->state))
724: blk_report_disk_dead(disk, false);
725:
726: /*
727: * Drop all partitions now that the disk is marked dead.
728: */
729: mutex_lock(&disk->open_mutex);
730: start_drain = __blk_mark_disk_dead(disk);
731: if (start_drain)
732: blk_freeze_acquire_lock(q);
733: xa_for_each_start(&disk->part_tbl, idx, part, 1)
734: drop_partition(part);
735: mutex_unlock(&disk->open_mutex);
736:
737: if (!(disk->flags & GENHD_FL_HIDDEN)) {
738: sysfs_remove_link(&disk_to_dev(disk)->kobj, "bdi");
739:
]
|
| 468/4 |
2026/11/03 21:31 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 27699
output: 34
thoughts: 23
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Diving into `__del_gendisk` in `block/genhd.c`**
Alright, let's get down to brass tacks. I need to understand the implications of the disk removal process, so naturally, I'm heading straight into the heart of the matter β specifically, `__del_gendisk` within `block/genhd.c`. This function is pivotal for gracefully removing a generic disk from the system. I want to thoroughly examine what happens in the removal path here. Is it robust? Are resources cleaned up properly? I expect it to involve unregistering the disk, freeing associated data structures, and ensuring all outstanding I/O operations are handled correctly. I also hope to find all relevant error handling. My ultimate goal is to understand any potential vulnerabilities or race conditions that could arise during disk removal, especially within complex storage stacks or virtualized environments. I'm looking for the nitty-gritty details on how the kernel manages its own resources. I need to be prepared in my understanding of disk management.
|
| 469/4 |
2026/11/03 21:33 |
tool |
read-file |
0m
Args: map[File:block/genhd.c FirstLine:740 LineCount:50]
Results: map[Contents: 740: /*
741: * Unregister bdi before releasing device numbers (as they can
742: * get reused and we'd get clashes in sysfs).
743: */
744: bdi_unregister(disk->bdi);
745: }
746:
747: blk_unregister_queue(disk);
748:
749: kobject_put(disk->part0->bd_holder_dir);
750: kobject_put(disk->slave_dir);
751: disk->slave_dir = NULL;
752:
753: part_stat_set_all(disk->part0, 0);
754: disk->part0->bd_stamp = 0;
755: sysfs_remove_link(block_depr, dev_name(disk_to_dev(disk)));
756: pm_runtime_set_memalloc_noio(disk_to_dev(disk), false);
757: device_del(disk_to_dev(disk));
758:
759: blk_mq_freeze_queue_wait(q);
760:
761: blk_throtl_cancel_bios(disk);
762:
763: blk_sync_queue(q);
764: blk_flush_integrity();
765:
766: if (queue_is_mq(q))
767: blk_mq_cancel_work_sync(q);
768:
769: rq_qos_exit(q);
770:
771: /*
772: * If the disk does not own the queue, allow using passthrough requests
773: * again. Else leave the queue frozen to fail all I/O.
774: */
775: if (!test_bit(GD_OWNS_QUEUE, &disk->state))
776: __blk_mq_unfreeze_queue(q, true);
777: else if (queue_is_mq(q))
778: blk_mq_exit_queue(q);
779:
780: if (start_drain)
781: blk_unfreeze_release_lock(q);
782: }
783:
784: static void disable_elv_switch(struct request_queue *q)
785: {
786: struct blk_mq_tag_set *set = q->tag_set;
787: WARN_ON_ONCE(!queue_is_mq(q));
788:
789: down_write(&set->update_nr_hwq_lock);
]
|
| 470/4 |
2026/11/03 21:33 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 28757
output: 30
thoughts: 80
Thoughts: Here's my thought process, as if I were summarizing my own intentions:
**Kernel Block Layer Concurrency Analysis**
Okay, so I need to get a really good handle on how the kernel block layer is handling its concurrency mechanisms. I'm going to systematically investigate the usage of those key locking and queue manipulation functions: `blk_freeze_acquire_lock`, `blk_unfreeze_release_lock`, `blk_queue_start_drain`, `__blk_freeze_queue_start`, `__blk_mq_unfreeze_queue`, and any others I might have missed that are related.
The most efficient way to do this at this point is going to be a comprehensive search. I'm going to fire up `grepper`, and comb the entire kernel source tree for each of those symbols. This'll give me a complete picture of where they're being called from, how they're being used in context, and hopefully reveal any patterns, potential areas of concern, or interesting implementation details I might have overlooked. That search will form the basis of a solid understanding of how these critical functions function within the system.
|
| 471/4 |
2026/11/03 21:35 |
tool |
grepper |
0m
Args: map[Expression:blk_freeze_acquire_lock|blk_unfreeze_release_lock]
Results: map[Output:block/blk-mq.c=182=void blk_freeze_queue_start(struct request_queue *q)
--
block/blk-mq.c-184- if (__blk_freeze_queue_start(q, current))
block/blk-mq.c:185: blk_freeze_acquire_lock(q);
block/blk-mq.c-186-}
--
block/blk-mq.c=230=void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
--
block/blk-mq.c-232- if (__blk_mq_unfreeze_queue(q, false))
block/blk-mq.c:233: blk_unfreeze_release_lock(q);
block/blk-mq.c-234-}
--
block/blk.h=778=void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
--
block/blk.h-780-#ifdef CONFIG_LOCKDEP
block/blk.h:781:static inline void blk_freeze_acquire_lock(struct request_queue *q)
block/blk.h-782-{
--
block/blk.h-788-
block/blk.h:789:static inline void blk_unfreeze_release_lock(struct request_queue *q)
block/blk.h-790-{
--
block/blk.h-796-#else
block/blk.h:797:static inline void blk_freeze_acquire_lock(struct request_queue *q)
block/blk.h-798-{
block/blk.h-799-}
block/blk.h:800:static inline void blk_unfreeze_release_lock(struct request_queue *q)
block/blk.h-801-{
--
block/genhd.c=697=static void __del_gendisk(struct gendisk *disk)
--
block/genhd.c-731- if (start_drain)
block/genhd.c:732: blk_freeze_acquire_lock(q);
block/genhd.c-733- xa_for_each_start(&disk->part_tbl, idx, part, 1)
--
block/genhd.c-780- if (start_drain)
block/genhd.c:781: blk_unfreeze_release_lock(q);
block/genhd.c-782-}
]
|
| 472/4 |
2026/11/03 21:35 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 29736
output: 22
thoughts: 94
Thoughts: Here's my analysis of the provided information:
**Understanding Block Layer Freezing and Unfreezing**
Okay, so I'm looking at how the block layer handles freezing and unfreezing, specifically focusing on `blk_freeze_acquire_lock` and `blk_unfreeze_release_lock`. My initial analysis reveals that these functions are *exclusively* called within two specific areas: the multi-queue block layer (`blk-mq.c`) and the generic disk layer (`genhd.c`). Specifically, I see them used within `blk_freeze_queue_start` and `blk_mq_unfreeze_queue_nomemrestore` in `blk-mq.c`, and within `__del_gendisk` in `genhd.c`. This is helpful because it narrows down the scope of where these locking primitives are being used and potentially where issues might arise. Now, it seems like a useful next step would be to delve into the usages of `__blk_freeze_queue_start`. Let's see what's happening there.
|
| 473/4 |
2026/11/03 21:36 |
tool |
grepper |
0m
Args: map[Expression:__blk_freeze_queue_start]
Results: map[Output:block/blk-core.c=327=bool blk_queue_start_drain(struct request_queue *q)
--
block/blk-core.c-333- */
block/blk-core.c:334: bool freeze = __blk_freeze_queue_start(q, current);
block/blk-core.c-335- if (queue_is_mq(q))
--
block/blk-mq.c=157=static bool blk_unfreeze_check_owner(struct request_queue *q)
--
block/blk-mq.c-162-
block/blk-mq.c:163:bool __blk_freeze_queue_start(struct request_queue *q,
block/blk-mq.c-164- struct task_struct *owner)
--
block/blk-mq.c=182=void blk_freeze_queue_start(struct request_queue *q)
block/blk-mq.c-183-{
block/blk-mq.c:184: if (__blk_freeze_queue_start(q, current))
block/blk-mq.c-185- blk_freeze_acquire_lock(q);
--
block/blk-mq.c=244=void blk_freeze_queue_start_non_owner(struct request_queue *q)
block/blk-mq.c-245-{
block/blk-mq.c:246: __blk_freeze_queue_start(q, NULL);
block/blk-mq.c-247-}
--
block/blk.h=59=bool blk_queue_start_drain(struct request_queue *q);
block/blk.h:60:bool __blk_freeze_queue_start(struct request_queue *q,
block/blk.h-61- struct task_struct *owner);
]
|
| 474/4 |
2026/11/03 21:36 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 30551
output: 23
thoughts: 17
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience, presented in the first person:
**Investigating `__blk_mq_unfreeze_queue` Usage**
Alright, let's dive into the implications of `__blk_mq_unfreeze_queue`. My immediate thought is, "Where's this function being *called*?". I need to understand its context. Knowing how the queue is being un-frozen will provide clues to potential performance bottlenecks or subtle race conditions. It could be triggered by any number of things β maybe a timer, a resource being available, a threshold being met, or even a completion interrupt. I need the big picture to determine if there's an optimization to be found, or a subtle bug to weed out.
I need to see the *reason* for this un-freezing action. Understanding the 'why' is crucial. Is it part of the normal operation, a recovery mechanism, or something more obscure? Digging into call stacks will show me the higher-level context. I'll need to look beyond the immediate caller to understand the flow of events that lead to the unfreeze. Is it handling I/O submission? Completion? If it's a common path, I can start looking for optimization opportunities. If it's more specific, understanding the specific usage case can help me. I need to be ready to analyze how the queue transitions from frozen to active, and what other threads or processes are interacting during that window. I'm assuming it relates to I/O scheduling, but I need to quickly identify and confirm what types of I/O it is related to.
|
| 475/4 |
2026/11/03 21:38 |
tool |
grepper |
0m
Args: map[Expression:__blk_mq_unfreeze_queue]
Results: map[Output:block/blk-mq.c=209=EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_nomemsave);
block/blk-mq.c-210-
block/blk-mq.c:211:bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
block/blk-mq.c-212-{
--
block/blk-mq.c=230=void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
block/blk-mq.c-231-{
block/blk-mq.c:232: if (__blk_mq_unfreeze_queue(q, false))
block/blk-mq.c-233- blk_unfreeze_release_lock(q);
--
block/blk-mq.c=251=void blk_mq_unfreeze_queue_non_owner(struct request_queue *q)
block/blk-mq.c-252-{
block/blk-mq.c:253: __blk_mq_unfreeze_queue(q, false);
block/blk-mq.c-254-}
--
block/blk.h=56=enum req_op str_to_blk_op(const char *op);
block/blk.h-57-
block/blk.h:58:bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
block/blk.h-59-bool blk_queue_start_drain(struct request_queue *q);
--
block/genhd.c=697=static void __del_gendisk(struct gendisk *disk)
--
block/genhd.c-775- if (!test_bit(GD_OWNS_QUEUE, &disk->state))
block/genhd.c:776: __blk_mq_unfreeze_queue(q, true);
block/genhd.c-777- else if (queue_is_mq(q))
]
|
| 476/4 |
2026/11/03 21:38 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 31445
output: 21
thoughts: 15
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience, presented in the first person:
**Investigating `blk_queue_start_drain` Usage**
Alright, time to dig into `blk_queue_start_drain`. I need to understand its usage patterns. I'm thinking about the implications of invoking this function, the scenarios where it's called, and crucially, what assumptions are made about the queue's state before and after the call. I want to identify the critical paths and any potential race conditions I need to be mindful of. My initial focus will be on tracking down the specific call sites, analyzing how the surrounding code interacts with the block layer, and pinpointing any dependencies on locking or synchronization primitives. I'll need to consider how this function affects IO scheduling, and if it's involved in any deadlock scenarios. Then, once I feel I have a handle on *where* it's used, I'll move on to analyzing *how* it's used β understanding the intended behavior in each context to uncover any potential bugs or performance bottlenecks. I should also check if any changes have been made in this area recently that would require a re-evaluation of this function.
|
| 477/4 |
2026/11/03 21:39 |
tool |
grepper |
0m
Args: map[Expression:blk_queue_start_drain]
Results: map[Output:block/blk-core.c=325=EXPORT_SYMBOL(blk_put_queue);
block/blk-core.c-326-
block/blk-core.c:327:bool blk_queue_start_drain(struct request_queue *q)
block/blk-core.c-328-{
--
block/blk-mq.c=4483=void blk_mq_destroy_queue(struct request_queue *q)
--
block/blk-mq.c-4490- blk_queue_flag_set(QUEUE_FLAG_DYING, q);
block/blk-mq.c:4491: blk_queue_start_drain(q);
block/blk-mq.c-4492- blk_mq_freeze_queue_wait(q);
--
block/blk.h=58=bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
block/blk.h:59:bool blk_queue_start_drain(struct request_queue *q);
block/blk.h-60-bool __blk_freeze_queue_start(struct request_queue *q,
--
block/genhd.c=660=static bool __blk_mark_disk_dead(struct gendisk *disk)
--
block/genhd.c-678- */
block/genhd.c:679: return blk_queue_start_drain(disk->queue);
block/genhd.c-680-}
]
|
| 478/4 |
2026/11/03 21:39 |
llm |
patch-generator |
2m
Model:
Tokens:
input: 32120
output: 22
thoughts: 16
Thoughts: Okay, here's my summary, presented as a stream of thought:
**Checking `__blk_mark_disk_dead` Usage**
Alright, time to dig in. The goal is to understand how `__blk_mark_disk_dead` is being utilized. This is crucial for understanding disk error handling and potential failure scenarios within the block layer, especially if we're investigating a specific issue or performance bottleneck related to disk I/O. I need to figure out where and how this function is called, what contexts trigger its execution, and what actions are subsequently taken. Is it primarily called during error recovery, or is it invoked in more preventative scenarios? Are there any unexpected call sites that warrant further investigation? My initial focus will be identifying the call sites and tracing the execution paths. I'll need to look for any nuances in the calling code. Is the error handling robust? Are all potential error scenarios adequately addressed? Are there any race conditions, or lock contention issues surrounding its use? Knowing the context is key to understanding the implications, and any potential side effects. Let's start with the code base search, and see what the data shows.
|
| 479/4 |
2026/11/03 21:41 |
tool |
grepper |
0m
Args: map[Expression:__blk_mark_disk_dead]
Results: map[Output:block/genhd.c=634=static void blk_report_disk_dead(struct gendisk *disk, bool surprise)
--
block/genhd.c-659-
block/genhd.c:660:static bool __blk_mark_disk_dead(struct gendisk *disk)
block/genhd.c-661-{
--
block/genhd.c=689=void blk_mark_disk_dead(struct gendisk *disk)
--
block/genhd.c-691- blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
block/genhd.c:692: __blk_mark_disk_dead(disk);
block/genhd.c-693- blk_report_disk_dead(disk, true);
--
block/genhd.c=697=static void __del_gendisk(struct gendisk *disk)
--
block/genhd.c-729- mutex_lock(&disk->open_mutex);
block/genhd.c:730: start_drain = __blk_mark_disk_dead(disk);
block/genhd.c-731- if (start_drain)
]
|
| 480/4 |
2026/11/03 21:41 |
llm |
patch-generator |
2m
Model:
Tokens:
input: 32709
output: 30
thoughts: 10444
Thoughts: **Deep Dive into `__del_gendisk` and Freeze Handling**
Okay, let's break down this `__del_gendisk` function and the changes related to freeze handling. It's crucial to ensure we're not introducing any regressions here. First, I'm tracing the original logic, specifically the role of `start_drain` (a `bool`) and how it influenced `blk_freeze_acquire_lock`. It appears that the original code only acquired the freeze lock if `start_drain` was true. The revised code uses `lock_mask` returned by `__blk_mark_disk_dead()` in `__del_gendisk`.
Now, if the freeze ownership wasn't claimed, or if the mask is zero, `blk_freeze_acquire_lock` turns into a no-op! And in the case when the disk does not own the queue, we release any passthrough requests. The return value from `__blk_mark_disk_dead` has a crucial meaning. It is now used as a mask to acquire and release locks, but it used to be just a boolean.
Diving into the `blk_queue_start_drain` function, it seems the code now determines if the queue is "dying". If so, the owner is set to NULL, and the returned mask is zero! So, if a permanent drain is initiated (where the disk owns the queue), a zero mask is returned. However, if the disk doesn't own the queue, the owner is set to current, and the mask is non-zero. The non-zero mask is returned. This is critical because of the way the lockdep is used.
I'm now very carefully tracing the new logic. The changes appear correct; it leverages `blk_unfreeze_check_owner()` to handle unfreezing. I notice the return value of `__blk_mq_unfreeze_queue` is *ignored* in the old code. Previously, calling `__blk_mq_unfreeze_queue` caused the owner to be NULL when unfreezing, but `blk_unfreeze_release_lock` was called. Now, the return value from `__blk_mark_disk_dead` is the mask. So now, the new code makes sure the mask has the exact locks that were acquired.
The crucial insight here is the use of `blk_freeze_set_owner()` with `NULL` as the owner to avoid the claiming of freeze ownership. So, when `blk_queue_dying(q)` is true, owner is NULL, so `blk_freeze_set_owner()` doesn't claim ownership.
Now, if `GD_OWNS_QUEUE` isn't set, `blk_queue_dying(q)` is not set. We pass current as the owner, and now we must acquire the correct lock.
By analyzing different scenarios, it appears the new method fixes the issue related to "permanent/dying drains".
Checking the `blk_mq_destroy_queue` function further confirms this. It ensures proper handling of the dying flag and drain, avoiding potential lock issues due to nested freezes.
Analyzing the nested freezes confirms the change is safe.
I've also verified the behavior under `CONFIG_LOCKDEP` guards.
Now, I'm carefully double-checking the code to see if there is an issue to initialize `mq_freeze_lock_mask` when the `request_queue` is allocated. The fields are zero-initialized. Also, `q->mq_freeze_lock_mask` can be set to zero when unfreezing. And the function always overwrites the mask when it freezes. This doesn't matter since the next freeze will overwrite it, and the return value is a local copy in the calling function. So this local mask is the one that's used.
Finally, I've confirmed that all the necessary enum definitions are correctly placed, ensuring compatibility whether `CONFIG_LOCKDEP` is enabled or not.
I've carefully traced through the changes in `blk-mq.c`, `genhd.c` and `blk-core.c`. This is quite a bit more complex. Based on my analysis, these changes are sound and address the potential lockdep issues in a clean and efficient manner, and the freeze acquisition and release is very clean.
|
| 481/4 |
2026/11/03 21:43 |
tool |
grepper |
0m
Args: map[Expression:#include "blk.h" PathPrefixes:[block/]]
Results: map[Output:block/bdev.c-30-#include "../fs/internal.h"
block/bdev.c:31:#include "blk.h"
block/bdev.c-32-
--
block/bfq-iosched.c-129-#include "elevator.h"
block/bfq-iosched.c:130:#include "blk.h"
block/bfq-iosched.c-131-#include "blk-mq.h"
--
block/bio-integrity-auto.c-13-#include <linux/workqueue.h>
block/bio-integrity-auto.c:14:#include "blk.h"
block/bio-integrity-auto.c-15-
--
block/bio-integrity-fs.c-6-#include <linux/bio-integrity.h>
block/bio-integrity-fs.c:7:#include "blk.h"
block/bio-integrity-fs.c-8-
--
block/bio-integrity.c-10-#include <linux/t10-pi.h>
block/bio-integrity.c:11:#include "blk.h"
block/bio-integrity.c-12-
--
block/bio.c-23-#include <trace/events/block.h>
block/bio.c:24:#include "blk.h"
block/bio.c-25-#include "blk-rq-qos.h"
--
block/blk-cgroup.c-32-#include <linux/part_stat.h>
block/blk-cgroup.c:33:#include "blk.h"
block/blk-cgroup.c-34-#include "blk-cgroup.h"
--
block/blk-cgroup.h-21-#include <linux/llist.h>
block/blk-cgroup.h:22:#include "blk.h"
block/blk-cgroup.h-23-
--
block/blk-core.c-47-
block/blk-core.c:48:#include "blk.h"
block/blk-core.c-49-#include "blk-mq-sched.h"
--
block/blk-flush.c-72-
block/blk-flush.c:73:#include "blk.h"
block/blk-flush.c-74-#include "blk-mq.h"
--
block/blk-ia-ranges.c-11-
block/blk-ia-ranges.c:12:#include "blk.h"
block/blk-ia-ranges.c-13-
--
block/blk-integrity.c-17-
block/blk-integrity.c:18:#include "blk.h"
block/blk-integrity.c-19-
--
block/blk-ioc.c-13-
block/blk-ioc.c:14:#include "blk.h"
block/blk-ioc.c-15-#include "blk-mq-sched.h"
--
block/blk-iolatency.c-79-#include "blk-cgroup.h"
block/blk-iolatency.c:80:#include "blk.h"
block/blk-iolatency.c-81-
--
block/blk-lib.c-10-
block/blk-lib.c:11:#include "blk.h"
block/blk-lib.c-12-
--
block/blk-map.c-11-
block/blk-map.c:12:#include "blk.h"
block/blk-map.c-13-
--
block/blk-merge.c-15-
block/blk-merge.c:16:#include "blk.h"
block/blk-merge.c-17-#include "blk-mq-sched.h"
--
block/blk-mq-cpumap.c-16-
block/blk-mq-cpumap.c:17:#include "blk.h"
block/blk-mq-cpumap.c-18-#include "blk-mq.h"
--
block/blk-mq-debugfs.c-10-
block/blk-mq-debugfs.c:11:#include "blk.h"
block/blk-mq-debugfs.c-12-#include "blk-mq.h"
--
block/blk-mq-dma.c-6-#include <linux/blk-mq-dma.h>
block/blk-mq-dma.c:7:#include "blk.h"
block/blk-mq-dma.c-8-
--
block/blk-mq-sched.c-12-
block/blk-mq-sched.c:13:#include "blk.h"
block/blk-mq-sched.c-14-#include "blk-mq.h"
--
block/blk-mq-sysfs.c-12-
block/blk-mq-sysfs.c:13:#include "blk.h"
block/blk-mq-sysfs.c-14-#include "blk-mq.h"
--
block/blk-mq-tag.c-16-#include <trace/events/block.h>
block/blk-mq-tag.c:17:#include "blk.h"
block/blk-mq-tag.c-18-#include "blk-mq.h"
--
block/blk-mq.c-36-#include <linux/t10-pi.h>
block/blk-mq.c:37:#include "blk.h"
block/blk-mq.c-38-#include "blk-mq.h"
--
block/blk-settings.c-19-
block/blk-settings.c:20:#include "blk.h"
block/blk-settings.c-21-#include "blk-rq-qos.h"
--
block/blk-stat.c-11-#include "blk-mq.h"
block/blk-stat.c:12:#include "blk.h"
block/blk-stat.c-13-
--
block/blk-sysfs.c-13-
block/blk-sysfs.c:14:#include "blk.h"
block/blk-sysfs.c-15-#include "blk-mq.h"
--
block/blk-throttle.c-12-#include <linux/blktrace_api.h>
block/blk-throttle.c:13:#include "blk.h"
block/blk-throttle.c-14-#include "blk-cgroup-rwstat.h"
--
block/blk-timeout.c-9-
block/blk-timeout.c:10:#include "blk.h"
block/blk-timeout.c-11-#include "blk-mq.h"
--
block/blk-wbt.c-31-#include "elevator.h"
block/blk-wbt.c:32:#include "blk.h"
block/blk-wbt.c-33-
--
block/blk-zoned.c-23-
block/blk-zoned.c:24:#include "blk.h"
block/blk-zoned.c-25-#include "blk-mq-sched.h"
--
block/disk-events.c-7-#include <linux/blkdev.h>
block/disk-events.c:8:#include "blk.h"
block/disk-events.c-9-
--
block/elevator.c-41-#include "elevator.h"
block/elevator.c:42:#include "blk.h"
block/elevator.c-43-#include "blk-mq-sched.h"
--
block/error-injection.c-8-#include <linux/seq_file.h>
block/error-injection.c:9:#include "blk.h"
block/error-injection.c-10-#include "error-injection.h"
--
block/fops.c-22-#include <linux/dma-buf-io.h>
block/fops.c:23:#include "blk.h"
block/fops.c-24-
--
block/genhd.c-30-#include "blk-throttle.h"
block/genhd.c:31:#include "blk.h"
block/genhd.c-32-#include "blk-mq-sched.h"
--
block/ioctl.c-18-#include <uapi/linux/blkdev.h>
block/ioctl.c:19:#include "blk.h"
block/ioctl.c-20-#include "blk-crypto-internal.h"
--
block/kyber-iosched.c-16-#include "elevator.h"
block/kyber-iosched.c:17:#include "blk.h"
block/kyber-iosched.c-18-#include "blk-mq.h"
--
block/mq-deadline.c-21-#include "elevator.h"
block/mq-deadline.c:22:#include "blk.h"
block/mq-deadline.c-23-#include "blk-mq.h"
--
block/t10-pi.c-12-#include <linux/unaligned.h>
block/t10-pi.c:13:#include "blk.h"
block/t10-pi.c-14-
]
|
| 482/4 |
2026/11/03 21:43 |
llm |
patch-generator |
2m
Model:
Tokens:
input: 46377
output: 36
thoughts: 4165
Thoughts: **Reviewing Block Layer Freeze/Unfreeze Logic**
Okay, so I've been tasked with reviewing these changes to the block layer's freeze/unfreeze mechanism, all of which use `"blk.h"`, and it's all about improving the lock acquisition strategy during queue freezes. Let's see...
I'm starting by taking a look at these `blkdev.h` changes. It seems we're adding an `mq_freeze_lock_mask` to the `request_queue` struct in `include/linux/blkdev.h`. This replaces some booleans, `mq_freeze_disk_dead` and `mq_freeze_queue_dying`, with an `unsigned int` to represent which locks, the I/O lock and the queue lock, need to be acquired.
Now moving on to `block/blk.h`, I can see that the return types of several functions, `__blk_mq_unfreeze_queue`, `blk_queue_start_drain`, and `__blk_freeze_queue_start`, are being changed from `bool` to `unsigned int`. This is because we're no longer just indicating success or failure. We're now returning a mask of lock types acquired. The inline functions `blk_freeze_acquire_lock` and `blk_unfreeze_release_lock` have also been modified. They now accept a `lock_mask` argument, and conditional logic determines whether to acquire or release the I/O and queue locks based on the bits set in the mask. I see we have defined `BLK_FREEZE_LOCK_IO` and `BLK_FREEZE_LOCK_QUEUE` for readability. The old implementations were doing a simple conditional based on the boolean state.
Next, I need to look into `block/blk-mq.c`. I see that the `blk_freeze_set_owner` and `blk_unfreeze_check_owner` functions also have their return types modified to return the `lock_mask`. They're now responsible for determining the specific lock mask based on the current state and conditions. Specifically, `blk_freeze_set_owner` now sets the mask when the queue is frozen. `blk_unfreeze_check_owner` returns the mask to unfreeze, and the change has been applied to both the `CONFIG_LOCKDEP` and the "else" parts of this code. Then, the `__blk_freeze_queue_start` and `__blk_mq_unfreeze_queue` functions are modified to use and return this `lock_mask` as well. The higher-level functions, `blk_freeze_queue_start` and `blk_mq_unfreeze_queue_nomemrestore`, have been updated to call the new functions, and use the mask to properly acquire and release locks.
Now, into `block/blk-core.c`. `blk_queue_start_drain` is also getting the return type modified to `unsigned int` to allow the lock mask to be returned correctly. In this change, it seems that there is a null `owner` passed for the situation where the queue isn't currently being drained, and that condition seems to have been added to prevent `blk_queue_dying(q)` from being the current drain context when calling this method.
Finally, in `block/genhd.c`, I'm looking at `__blk_mark_disk_dead` and the related code. The return type of `__blk_mark_disk_dead` is being changed to `unsigned int` and assigned to `lock_mask`, with the corresponding adjustments to the calling code. The functions calling `__blk_mark_disk_dead` will now be using the lock mask return to acquire and release the appropriate locks via `blk_freeze_acquire_lock` and `blk_unfreeze_release_lock`. This way we can safely unfreeze the right lock.
Essentially, all these changes are coalescing into a more flexible and granular approach to locking during queue freeze/unfreeze operations. By using a bitmask to indicate the specific locks that need to be acquired/released, and using the `lock_mask` to acquire/release the correct locks, we're likely making this more robust and less prone to errors. It also avoids excessive acquisitions of the `rwsem` structures where only some locks might be required at any given point.
|
| 483/4 |
2026/11/03 21:45 |
tool |
read-file |
0m
Args: map[File:include/linux/blkdev.h FirstLine:635 LineCount:15]
Results: map[Contents: 635: struct rcu_head rcu_head;
636: #ifdef CONFIG_LOCKDEP
637: struct task_struct *mq_freeze_owner;
638: int mq_freeze_owner_depth;
639: /*
640: * Records disk & queue state in current context, used in unfreeze
641: * queue
642: */
643: bool mq_freeze_disk_dead;
644: bool mq_freeze_queue_dying;
645: #endif
646: wait_queue_head_t mq_freeze_wq;
647: /*
648: * Protect concurrent access to q_usage_counter by
649: * percpu_ref_kill() and percpu_ref_reinit().
]
|
| 484/4 |
2026/11/03 21:45 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 51755
output: 195
thoughts: 19
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Diving into `blkdev.h`**
Right, time to get my hands dirty. It looks like the task at hand is to edit `include/linux/blkdev.h`. This likely means I'm either making a core change to the block device layer, potentially impacting a wide range of drivers and subsystems, or I'm adding some specific new feature. Either way, this is going to be delicate. I need to proceed with extreme caution.
I'll be using `codeeditor`, which is fine, but I'll need to double and triple-check all the usual things: indentation, code style, proper comments, and especially any interactions with existing structures, especially those used in any specific block device driver. I'll need to scrutinize the existing definitions, understand their context, and ensure that my edits fit seamlessly, without introducing regressions. I also need to consider the impact on any kernel configurations that might be in place. I want to make sure I don't break any of the existing builds.
I'm mentally preparing to navigate the complexities of this header β the data structures, the function prototypes, potential interactions with other kernel subsystems. I'll need to remember to check for existing relevant discussions on the mailing lists or in the kernel documentation. This is definitely not a task for a quick hack. It demands careful planning and execution. Let's see what needs changing.
|
| 485/4 |
2026/11/03 21:46 |
tool |
codeeditor |
0m
Args: map[CurrentCode:#ifdef CONFIG_LOCKDEP
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
/*
* Records disk & queue state in current context, used in unfreeze
* queue
*/
bool mq_freeze_disk_dead;
bool mq_freeze_queue_dying;
#endif NewCode:#ifdef CONFIG_LOCKDEP
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
/*
* Records lockdep locks acquired in owner context, used in unfreeze
* queue
*/
unsigned int mq_freeze_lock_mask;
#endif SourceFile:include/linux/blkdev.h]
Results:
|
| 486/4 |
2026/11/03 21:46 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 52284
output: 32
thoughts: 30
Thoughts: Okay, here's my take on those lines of code, presented as a personal thought process, given my expertise:
**Diving into `block/blk.h`**
Alright, let's get down to brass tacks. I need to refresh my memory on the critical definitions related to block device interactions. Specifically, I'm heading over to `block/blk.h` and I want to zero in on lines 55-65 and 780-805. I'm expecting to find some fundamental structures here, likely definitions of the core data structures used to represent blocks and perhaps some key macros. This is the bedrock of how the kernel interacts with storage, so understanding these definitions is crucial.
I predict that lines 55-65 will likely house the basic data structures. Perhaps things like `struct request`, `struct bio`, or similar building blocks used in the I/O path. I'm looking for the essential fields, how they relate, and, most importantly, how theyβre sized and organized in memory. I need to be able to immediately visualize these structures to understand their performance implications. Memory layout is key. Are there any unusual padding strategies or bit-field tricks? I will be looking closely.
Now, lines 780-805... this chunk probably defines more advanced aspects of I/O, maybe related to queuing strategies, error handling, or even a higher-level abstraction. I'll likely see definitions of functions or macros that are critical for managing the I/O queue, handling completions, or perhaps even implementing some form of block device driver interface. This section could hold key flags and state variables that are used to coordinate and control the data movement within the block subsystem. I want to pay attention to any locking primitives used within this area, since these structures will likely be accessed from multiple threads. I want to understand how they address the concurrency challenges inherent in block I/O. Any clever use of atomic operations or memory barriers will immediately catch my eye. I'll also be searching for how these lines are related to the architecture's memory model.
|
| 487/4 |
2026/11/03 21:47 |
tool |
read-file |
0m
Args: map[File:block/blk.h FirstLine:56 LineCount:10]
Results: map[Contents: 56: enum req_op str_to_blk_op(const char *op);
57:
58: bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
59: bool blk_queue_start_drain(struct request_queue *q);
60: bool __blk_freeze_queue_start(struct request_queue *q,
61: struct task_struct *owner);
62: int __bio_queue_enter(struct request_queue *q, struct bio *bio);
63: void submit_bio_noacct_nocheck(struct bio *bio, bool split);
64: int bio_submit_or_kill(struct bio *bio, unsigned int flags);
65:
]
|
| 488/4 |
2026/11/03 21:47 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 53001
output: 33
thoughts: 21
Thoughts: Here's a summary of my thought process:
**Diving into `block/blk.h`**
Alright, I need to get to the heart of this. Let's start by zeroing in on a specific section of the `block/blk.h` header file. My instincts tell me the relevant details are probably tucked away between lines 775 and 805. Let's navigate there and see what we can find. I anticipate this range will contain definitions, perhaps structures or macros, related to the topic at hand. It's a focused approach; no need to start sifting through the whole file. Let's see what gems are waiting to be unearthed within that particular slice.
|
| 489/4 |
2026/11/03 21:48 |
tool |
read-file |
0m
Args: map[File:block/blk.h FirstLine:775 LineCount:30]
Results: map[Contents: 775: struct bvec_iter *saved_iter);
776:
777: void blk_integrity_prepare(struct request *rq);
778: void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
779:
780: #ifdef CONFIG_LOCKDEP
781: static inline void blk_freeze_acquire_lock(struct request_queue *q)
782: {
783: if (!q->mq_freeze_disk_dead)
784: rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
785: if (!q->mq_freeze_queue_dying)
786: rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
787: }
788:
789: static inline void blk_unfreeze_release_lock(struct request_queue *q)
790: {
791: if (!q->mq_freeze_queue_dying)
792: rwsem_release(&q->q_lockdep_map, _RET_IP_);
793: if (!q->mq_freeze_disk_dead)
794: rwsem_release(&q->io_lockdep_map, _RET_IP_);
795: }
796: #else
797: static inline void blk_freeze_acquire_lock(struct request_queue *q)
798: {
799: }
800: static inline void blk_unfreeze_release_lock(struct request_queue *q)
801: {
802: }
803: #endif
804:
]
|
| 490/4 |
2026/11/03 21:48 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 53704
output: 176
thoughts: 16
Thoughts: Here's my take on the process, considering I'm deep in the weeds of this:
**Refactoring `block/blk.h` with `codeeditor`**
Okay, time to dive in. I need to make some targeted changes to `block/blk.h`. The goal is focused, let's keep it that way. I'm going to leverage `codeeditor` for this β it's the tool for the job. No need to overthink it; just get in, make the edits I've planned, and get out. I expect `codeeditor` will handle the context and syntax highlighting elegantly. I'll make sure to double check that things look as expected afterward, of course. Let's see what needs to be changed.
|
| 491/4 |
2026/11/03 21:49 |
tool |
codeeditor |
0m
Args: map[CurrentCode:bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
bool blk_queue_start_drain(struct request_queue *q);
bool __blk_freeze_queue_start(struct request_queue *q,
struct task_struct *owner); NewCode:unsigned int __blk_mq_unfreeze_queue(struct request_queue *q,
bool force_atomic);
unsigned int blk_queue_start_drain(struct request_queue *q);
unsigned int __blk_freeze_queue_start(struct request_queue *q,
struct task_struct *owner); SourceFile:block/blk.h]
Results:
|
| 492/4 |
2026/11/03 21:49 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 54065
output: 651
thoughts: 19
Thoughts: Okay, here's the summary, expressed as though I'm the one having the thoughts, keeping in mind I'm speaking to an expert:
**Addressing a Specific Code Segment**
Alright, let's get down to it. Time to focus in on a very specific area of the kernel code. The task at hand is to modify the `block/blk.h` header file. It's a critical piece, and I need to make some precise changes within it. Specifically, the action item is to edit lines 780 through 803. I need to ensure these modifications are absolutely correct, as any misstep here can ripple through the block layer. I need to carefully consider the implications of these changes in relation to the overall design.
|
| 493/4 |
2026/11/03 21:50 |
tool |
codeeditor |
0m
Args: map[CurrentCode:#ifdef CONFIG_LOCKDEP
static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
if (!q->mq_freeze_queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
#else
static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
}
static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
}
#endif NewCode:enum {
BLK_FREEZE_LOCK_IO = (1 << 0),
BLK_FREEZE_LOCK_QUEUE = (1 << 1),
};
#ifdef CONFIG_LOCKDEP
static inline void blk_freeze_acquire_lock(struct request_queue *q,
unsigned int lock_mask)
{
if (lock_mask & BLK_FREEZE_LOCK_IO)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
if (lock_mask & BLK_FREEZE_LOCK_QUEUE)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
static inline void blk_unfreeze_release_lock(struct request_queue *q,
unsigned int lock_mask)
{
if (lock_mask & BLK_FREEZE_LOCK_QUEUE)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (lock_mask & BLK_FREEZE_LOCK_IO)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
#else
static inline void blk_freeze_acquire_lock(struct request_queue *q,
unsigned int lock_mask)
{
}
static inline void blk_unfreeze_release_lock(struct request_queue *q,
unsigned int lock_mask)
{
}
#endif SourceFile:block/blk.h]
Results:
|
| 494/4 |
2026/11/03 21:50 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 54901
output: 35
thoughts: 29
Thoughts: Okay, let's dive into this. I need to get a handle on the `blk-mq.c` file, specifically lines 115 through 190. I know this is a core piece of the block layer's multi-queue implementation, so this chunk of code likely deals with some fundamental data structure or function within the system. Is it the submission path? Perhaps the handling of request prioritization? Or maybe it's the initial setup or tear-down of queues? The specifics of this section are going to be key to understanding the overall performance characteristics of this design. Let's see what gems are contained in this particular section of the code. Let's start reading.
|
| 495/4 |
2026/11/03 21:51 |
tool |
read-file |
0m
Args: map[File:block/blk-mq.c FirstLine:115 LineCount:75]
Results: map[Contents: 115: #ifdef CONFIG_LOCKDEP
116: static bool blk_freeze_set_owner(struct request_queue *q,
117: struct task_struct *owner)
118: {
119: if (!owner)
120: return false;
121:
122: if (!q->mq_freeze_depth) {
123: q->mq_freeze_owner = owner;
124: q->mq_freeze_owner_depth = 1;
125: q->mq_freeze_disk_dead = !q->disk ||
126: test_bit(GD_DEAD, &q->disk->state) ||
127: !blk_queue_registered(q);
128: q->mq_freeze_queue_dying = blk_queue_dying(q);
129: return true;
130: }
131:
132: if (owner == q->mq_freeze_owner)
133: q->mq_freeze_owner_depth += 1;
134: return false;
135: }
136:
137: /* verify the last unfreeze in owner context */
138: static bool blk_unfreeze_check_owner(struct request_queue *q)
139: {
140: if (q->mq_freeze_owner != current)
141: return false;
142: if (--q->mq_freeze_owner_depth == 0) {
143: q->mq_freeze_owner = NULL;
144: return true;
145: }
146: return false;
147: }
148:
149: #else
150:
151: static bool blk_freeze_set_owner(struct request_queue *q,
152: struct task_struct *owner)
153: {
154: return false;
155: }
156:
157: static bool blk_unfreeze_check_owner(struct request_queue *q)
158: {
159: return false;
160: }
161: #endif
162:
163: bool __blk_freeze_queue_start(struct request_queue *q,
164: struct task_struct *owner)
165: {
166: bool freeze;
167:
168: mutex_lock(&q->mq_freeze_lock);
169: freeze = blk_freeze_set_owner(q, owner);
170: if (++q->mq_freeze_depth == 1) {
171: percpu_ref_kill(&q->q_usage_counter);
172: mutex_unlock(&q->mq_freeze_lock);
173: if (queue_is_mq(q))
174: blk_mq_run_hw_queues(q, false);
175: } else {
176: mutex_unlock(&q->mq_freeze_lock);
177: }
178:
179: return freeze;
180: }
181:
182: void blk_freeze_queue_start(struct request_queue *q)
183: {
184: if (__blk_freeze_queue_start(q, current))
185: blk_freeze_acquire_lock(q);
186: }
187: EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
188:
189: void blk_mq_freeze_queue_wait(struct request_queue *q)
]
|
| 496/4 |
2026/11/03 21:51 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 56171
output: 35
thoughts: 25
Thoughts: Okay, here's my interpretation of what I should be doing, as if the request were coming from inside my own thought process:
**Diving into blk-mq.c for Context**
Alright, before I dive too deep into this, I need to understand the surrounding context a bit better. To get a handle on what's going on, it seems crucial to zoom in on a specific section of `blk-mq.c`, specifically lines 210 through 240. That range is probably going to give me the groundwork for whatever function call or process I need to understand. Let's see what that section reveals about the message queue's structure, potential data structures involved, and any critical synchronization mechanisms in place within that segment. I need to understand the immediate environment of whatever I need to look at so I am going to read those lines now.
|
| 497/4 |
2026/11/03 21:52 |
tool |
read-file |
0m
Args: map[File:block/blk-mq.c FirstLine:210 LineCount:30]
Results: map[Contents: 210:
211: bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
212: {
213: bool unfreeze;
214:
215: mutex_lock(&q->mq_freeze_lock);
216: if (force_atomic)
217: q->q_usage_counter.data->force_atomic = true;
218: q->mq_freeze_depth--;
219: WARN_ON_ONCE(q->mq_freeze_depth < 0);
220: if (!q->mq_freeze_depth) {
221: percpu_ref_resurrect(&q->q_usage_counter);
222: wake_up_all(&q->mq_freeze_wq);
223: }
224: unfreeze = blk_unfreeze_check_owner(q);
225: mutex_unlock(&q->mq_freeze_lock);
226:
227: return unfreeze;
228: }
229:
230: void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
231: {
232: if (__blk_mq_unfreeze_queue(q, false))
233: blk_unfreeze_release_lock(q);
234: }
235: EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_nomemrestore);
236:
237: /*
238: * non_owner variant of blk_freeze_queue_start
239: *
]
|
| 498/4 |
2026/11/03 21:52 |
llm |
patch-generator |
2m
Model:
Tokens:
input: 56885
output: 1322
thoughts: 823
Thoughts: **Refactoring Block/MQ Freeze Logic**
Okay, let's break this down. I'm going to tackle the `block/blk-mq.c` file in two logical chunks for this edit. First, I'll focus on lines 115 through 187, dealing with the freeze ownership and start mechanisms: `blk_freeze_set_owner`, `blk_unfreeze_check_owner`, `__blk_freeze_queue_start`, and `blk_freeze_queue_start`.
Before diving into the edit, I'll refresh my memory of what these functions do in `block/blk-mq.c`. I have to be careful with the `#ifdef CONFIG_LOCKDEP` block. If `LOCKDEP` is enabled, the code tracks the owner of the freeze, increasing the depth counter on the owner task's nested freezes. `blk_freeze_set_owner` determines the lock mask if the queue is not already frozen. It then proceeds to increment `mq_freeze_owner_depth` when the owner is the same. Conversely, `blk_unfreeze_check_owner` checks the owner task when unfreezing, ensuring that it's the correct owner and decrementing the depth. When the `mq_freeze_owner_depth` is zero, the owner is set to `NULL`. The lock mask is only returned when LOCKDEP is disabled. The code also checks for the queue dying (`blk_queue_dying`) and if the disk is dead (`GD_DEAD`).
`__blk_freeze_queue_start` takes the `request_queue` and owner task. It acquires the `mq_freeze_lock` mutex and calls `blk_freeze_set_owner`. The freeze depth is incremented and checks if it's the first freeze. When it's the first freeze, the queue usage counter (`q_usage_counter`) is killed and the hw queues are stopped, the mutex is unlocked. The lock mask is returned to the caller. Then there is `blk_freeze_queue_start`, which is a simple wrapper around `__blk_freeze_queue_start` to pass `current` as the owner.
After I've applied the first edit, I'll go back and revisit the second chunk, lines 211-235: `__blk_mq_unfreeze_queue` and `blk_mq_unfreeze_queue_nomemrestore`. I want to make sure the code operates the same.
|
| 499/4 |
2026/11/03 21:55 |
tool |
codeeditor |
0m
Args: map[CurrentCode:#ifdef CONFIG_LOCKDEP
static bool blk_freeze_set_owner(struct request_queue *q,
struct task_struct *owner)
{
if (!owner)
return false;
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
q->mq_freeze_disk_dead = !q->disk ||
test_bit(GD_DEAD, &q->disk->state) ||
!blk_queue_registered(q);
q->mq_freeze_queue_dying = blk_queue_dying(q);
return true;
}
if (owner == q->mq_freeze_owner)
q->mq_freeze_owner_depth += 1;
return false;
}
/* verify the last unfreeze in owner context */
static bool blk_unfreeze_check_owner(struct request_queue *q)
{
if (q->mq_freeze_owner != current)
return false;
if (--q->mq_freeze_owner_depth == 0) {
q->mq_freeze_owner = NULL;
return true;
}
return false;
}
#else
static bool blk_freeze_set_owner(struct request_queue *q,
struct task_struct *owner)
{
return false;
}
static bool blk_unfreeze_check_owner(struct request_queue *q)
{
return false;
}
#endif
bool __blk_freeze_queue_start(struct request_queue *q,
struct task_struct *owner)
{
bool freeze;
mutex_lock(&q->mq_freeze_lock);
freeze = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
if (queue_is_mq(q))
blk_mq_run_hw_queues(q, false);
} else {
mutex_unlock(&q->mq_freeze_lock);
}
return freeze;
}
void blk_freeze_queue_start(struct request_queue *q)
{
if (__blk_freeze_queue_start(q, current))
blk_freeze_acquire_lock(q);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start); NewCode:#ifdef CONFIG_LOCKDEP
static unsigned int blk_freeze_set_owner(struct request_queue *q,
struct task_struct *owner)
{
unsigned int lock_mask = 0;
if (!owner)
return 0;
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
if (q->disk && !test_bit(GD_DEAD, &q->disk->state) &&
blk_queue_registered(q))
lock_mask |= BLK_FREEZE_LOCK_IO;
if (!blk_queue_dying(q))
lock_mask |= BLK_FREEZE_LOCK_QUEUE;
q->mq_freeze_lock_mask = lock_mask;
return lock_mask;
}
if (owner == q->mq_freeze_owner)
q->mq_freeze_owner_depth += 1;
return 0;
}
/* verify the last unfreeze in owner context */
static unsigned int blk_unfreeze_check_owner(struct request_queue *q)
{
if (q->mq_freeze_owner != current)
return 0;
if (--q->mq_freeze_owner_depth == 0) {
q->mq_freeze_owner = NULL;
return q->mq_freeze_lock_mask;
}
return 0;
}
#else
static unsigned int blk_freeze_set_owner(struct request_queue *q,
struct task_struct *owner)
{
return 0;
}
static unsigned int blk_unfreeze_check_owner(struct request_queue *q)
{
return 0;
}
#endif
unsigned int __blk_freeze_queue_start(struct request_queue *q,
struct task_struct *owner)
{
unsigned int lock_mask;
mutex_lock(&q->mq_freeze_lock);
lock_mask = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
if (queue_is_mq(q))
blk_mq_run_hw_queues(q, false);
} else {
mutex_unlock(&q->mq_freeze_lock);
}
return lock_mask;
}
void blk_freeze_queue_start(struct request_queue *q)
{
unsigned int lock_mask = __blk_freeze_queue_start(q, current);
blk_freeze_acquire_lock(q, lock_mask);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start); SourceFile:block/blk-mq.c]
Results:
|
| 500/4 |
2026/11/03 21:55 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 59572
output: 586
thoughts: 44
Thoughts: Here's my summary, as if I were thinking these thoughts:
**Applying the Second Edit to blk-mq.c**
Alright, time to focus. I'm moving on to the second edit I need to apply to `block/blk-mq.c`. Specifically, I'm diving into the `__blk_mq_unfreeze_queue` and `blk_mq_unfreeze_queue_nomemrestore` functions. Let's see what impact this change will have. I need to ensure this edit is correctly integrated and that there are no unintended side effects on the block layer's performance or stability. Understanding how these unfreeze functions interact with the memory management and scheduling components is crucial. I need to make certain this lines up with the broader goals of the revision.
|
| 501/4 |
2026/11/03 21:56 |
tool |
codeeditor |
0m
Args: map[CurrentCode:bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
bool unfreeze;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
q->q_usage_counter.data->force_atomic = true;
q->mq_freeze_depth--;
WARN_ON_ONCE(q->mq_freeze_depth < 0);
if (!q->mq_freeze_depth) {
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
}
unfreeze = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
return unfreeze;
}
void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
{
if (__blk_mq_unfreeze_queue(q, false))
blk_unfreeze_release_lock(q);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_nomemrestore); NewCode:unsigned int __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
unsigned int lock_mask;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
q->q_usage_counter.data->force_atomic = true;
q->mq_freeze_depth--;
WARN_ON_ONCE(q->mq_freeze_depth < 0);
if (!q->mq_freeze_depth) {
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
}
lock_mask = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
return lock_mask;
}
void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
{
unsigned int lock_mask = __blk_mq_unfreeze_queue(q, false);
blk_unfreeze_release_lock(q, lock_mask);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_nomemrestore); SourceFile:block/blk-mq.c]
Results:
|
| 502/4 |
2026/11/03 21:56 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 60375
output: 35
thoughts: 37
Thoughts: Okay, let's dive into this.
**Examining the Block Layer Core**
Right, time to get down to brass tacks. I need to refresh my memory on some core block layer functionality. Let's start with `block/blk-core.c`. Specifically, I want to take a look at lines 325 through 345. I'm going to quickly scan through that section... I expect to find some key data structures or function calls related to how requests are handled, queued, or dispatched. My initial thought is it will have to do with the request queue management or the interaction with the elevator. Let me quickly refresh my understanding of how requests are handled in that section, I need to brush up on this implementation detail as it relates to performance and resource contention.
|
| 503/4 |
2026/11/03 21:57 |
tool |
read-file |
0m
Args: map[File:block/blk-core.c FirstLine:325 LineCount:20]
Results: map[Contents: 325: EXPORT_SYMBOL(blk_put_queue);
326:
327: bool blk_queue_start_drain(struct request_queue *q)
328: {
329: /*
330: * When queue DYING flag is set, we need to block new req
331: * entering queue, so we call blk_freeze_queue_start() to
332: * prevent I/O from crossing blk_queue_enter().
333: */
334: bool freeze = __blk_freeze_queue_start(q, current);
335: if (queue_is_mq(q))
336: blk_mq_wake_waiters(q);
337: /* Make blk_queue_enter() reexamine the DYING flag. */
338: wake_up_all(&q->mq_freeze_wq);
339:
340: return freeze;
341: }
342:
343: /**
344: * blk_queue_enter() - try to increase q->q_usage_counter
]
|
| 504/4 |
2026/11/03 21:57 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 60934
output: 378
thoughts: 18
Thoughts: Here's my summary, as I see it:
**Alright, Time to Tweak `blk-core.c`**
Okay, so I need to dive into `block/blk-core.c`. Looks like it's time to open up the `codeeditor` β that's the tool for this particular task. No need for anything fancy, just need to get in there and make the necessary edits. Let's get to it.
|
| 505/4 |
2026/11/03 21:59 |
tool |
codeeditor |
0m
Args: map[CurrentCode:bool blk_queue_start_drain(struct request_queue *q)
{
/*
* When queue DYING flag is set, we need to block new req
* entering queue, so we call blk_freeze_queue_start() to
* prevent I/O from crossing blk_queue_enter().
*/
bool freeze = __blk_freeze_queue_start(q, current);
if (queue_is_mq(q))
blk_mq_wake_waiters(q);
/* Make blk_queue_enter() reexamine the DYING flag. */
wake_up_all(&q->mq_freeze_wq);
return freeze;
} NewCode:unsigned int blk_queue_start_drain(struct request_queue *q)
{
/*
* When queue DYING flag is set, we need to block new req
* entering queue, so we call blk_freeze_queue_start() to
* prevent I/O from crossing blk_queue_enter().
*/
unsigned int lock_mask = __blk_freeze_queue_start(q,
blk_queue_dying(q) ? NULL : current);
if (queue_is_mq(q))
blk_mq_wake_waiters(q);
/* Make blk_queue_enter() reexamine the DYING flag. */
wake_up_all(&q->mq_freeze_wq);
return lock_mask;
} SourceFile:block/blk-core.c]
Results:
|
| 506/4 |
2026/11/03 21:59 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 61433
output: 34
thoughts: 35
Thoughts: Okay, let's dive into this. I need to get a handle on the current state of `block/genhd.c`. Time to dig in, and I'll focus specifically on lines 660 through 785. I'll read through that section carefully, understanding the code flow and trying to deduce its purpose within the larger block device context. This is where the magic happens, so I'll see what the code does!
|
| 507/4 |
2026/11/03 22:00 |
tool |
read-file |
0m
Args: map[File:block/genhd.c FirstLine:660 LineCount:45]
Results: map[Contents: 660: static bool __blk_mark_disk_dead(struct gendisk *disk)
661: {
662: /*
663: * Fail any new I/O.
664: */
665: if (test_and_set_bit(GD_DEAD, &disk->state))
666: return false;
667:
668: if (test_bit(GD_OWNS_QUEUE, &disk->state))
669: blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
670:
671: /*
672: * Stop buffered writers from dirtying pages that can't be written out.
673: */
674: set_capacity(disk, 0);
675:
676: /*
677: * Prevent new I/O from crossing bio_queue_enter().
678: */
679: return blk_queue_start_drain(disk->queue);
680: }
681:
682: /**
683: * blk_mark_disk_dead - mark a disk as dead
684: * @disk: disk to mark as dead
685: *
686: * Mark as disk as dead (e.g. surprise removed) and don't accept any new I/O
687: * to this disk.
688: */
689: void blk_mark_disk_dead(struct gendisk *disk)
690: {
691: blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
692: __blk_mark_disk_dead(disk);
693: blk_report_disk_dead(disk, true);
694: }
695: EXPORT_SYMBOL_GPL(blk_mark_disk_dead);
696:
697: static void __del_gendisk(struct gendisk *disk)
698: {
699: struct request_queue *q = disk->queue;
700: struct block_device *part;
701: unsigned long idx;
702: bool start_drain;
703:
704: might_sleep();
]
|
| 508/4 |
2026/11/03 22:00 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 62247
output: 34
thoughts: 22
Thoughts: Here's a summary of my thought process, as requested:
**Diving into `block/genhd.c`**
Okay, time to get my hands dirty. I need to understand what's happening within the `block/genhd.c` file, specifically between lines 725 and 785. That section is likely critical to some aspect of the block device handling or generation logic. Given the file's name and the context of my current task, I'm expecting to find code related to generating or managing hard disk images or virtual block devices. I'll need to pay close attention to the data structures used, any error handling present, and the flow of the functions within that range. It will likely reveal the nuts and bolts of how these block devices are created or manipulated. I'll be looking for clues about the supported formats, partitioning schemes, and any interaction with other parts of the storage stack. My goal is to extract the functional essence of this code block. I will parse it for insights into any relevant algorithms or techniques employed. I am ready to dig in and decipher the details.
|
| 509/4 |
2026/11/03 22:01 |
tool |
read-file |
0m
Args: map[File:block/genhd.c FirstLine:725 LineCount:60]
Results: map[Contents: 725:
726: /*
727: * Drop all partitions now that the disk is marked dead.
728: */
729: mutex_lock(&disk->open_mutex);
730: start_drain = __blk_mark_disk_dead(disk);
731: if (start_drain)
732: blk_freeze_acquire_lock(q);
733: xa_for_each_start(&disk->part_tbl, idx, part, 1)
734: drop_partition(part);
735: mutex_unlock(&disk->open_mutex);
736:
737: if (!(disk->flags & GENHD_FL_HIDDEN)) {
738: sysfs_remove_link(&disk_to_dev(disk)->kobj, "bdi");
739:
740: /*
741: * Unregister bdi before releasing device numbers (as they can
742: * get reused and we'd get clashes in sysfs).
743: */
744: bdi_unregister(disk->bdi);
745: }
746:
747: blk_unregister_queue(disk);
748:
749: kobject_put(disk->part0->bd_holder_dir);
750: kobject_put(disk->slave_dir);
751: disk->slave_dir = NULL;
752:
753: part_stat_set_all(disk->part0, 0);
754: disk->part0->bd_stamp = 0;
755: sysfs_remove_link(block_depr, dev_name(disk_to_dev(disk)));
756: pm_runtime_set_memalloc_noio(disk_to_dev(disk), false);
757: device_del(disk_to_dev(disk));
758:
759: blk_mq_freeze_queue_wait(q);
760:
761: blk_throtl_cancel_bios(disk);
762:
763: blk_sync_queue(q);
764: blk_flush_integrity();
765:
766: if (queue_is_mq(q))
767: blk_mq_cancel_work_sync(q);
768:
769: rq_qos_exit(q);
770:
771: /*
772: * If the disk does not own the queue, allow using passthrough requests
773: * again. Else leave the queue frozen to fail all I/O.
774: */
775: if (!test_bit(GD_OWNS_QUEUE, &disk->state))
776: __blk_mq_unfreeze_queue(q, true);
777: else if (queue_is_mq(q))
778: blk_mq_exit_queue(q);
779:
780: if (start_drain)
781: blk_unfreeze_release_lock(q);
782: }
783:
784: static void disable_elv_switch(struct request_queue *q)
]
|
| 510/4 |
2026/11/03 22:01 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 63452
output: 389
thoughts: 510
Thoughts: **Analyzing and Refactoring Disk Death Handling in `block/genhd.c`**
Okay, let's break down this `block/genhd.c` code. It looks like we're dealing with the critical process of marking a disk as "dead" and safely removing it. I need to ensure a robust and controlled shutdown to prevent data corruption.
First, I see the function `__blk_mark_disk_dead(struct gendisk *disk)`. This is where the magic happens. The code first sets the `GD_DEAD` bit in the `disk->state` to indicate that the disk is, well, dead. Crucially, I notice `test_and_set_bit()` being used, which provides atomic operation. This is good as it provides protection from race conditions. After that, it checks if the disk *owns* its queue, using `GD_OWNS_QUEUE`, and if so, it sets the `QUEUE_FLAG_DYING` flag on the queue. I understand that this signals to the I/O scheduler to handle the disk specially and, likely, to begin draining the queue of requests. The call to `set_capacity(disk, 0)` is a simple, effective measure to ensure that new I/O doesn't even get to the queue. Finally, `blk_queue_start_drain(disk->queue)` is called to actually trigger the drainage.
Next, I'm looking at `__del_gendisk(struct gendisk *disk)`, which handles the complete removal of the disk. The code had a variable `start_drain` and this has been renamed to `lock_mask`. This is a useful refactoring, and indicates that the variable is no longer solely related to draining the queue. `__blk_mark_disk_dead()` is called within a mutex lock, which is important for preventing race conditions during this critical path. The code then uses `blk_freeze_acquire_lock()` to ensure there is no new I/O. After this, all partitions that the disk might have are dropped.
The code then checks if the disk *owns* the queue. If it *doesn't* own the queue, it's safe to *unfreeze* the queue. This is handled by `__blk_mq_unfreeze_queue(q, true)`. Otherwise, if the queue *is owned* and is of the `mq` type, we have to call `blk_mq_exit_queue(q)`. This is the crucial part; if we just unfreeze, we risk new I/O being issued. Finally, `blk_unfreeze_release_lock()` releases the lock we acquired earlier, completing the cleanup.
So, in summary, this code looks like a well-structured implementation of disk death handling. It uses a combination of flags, queue manipulation, and locking to ensure that all I/O is safely drained and new I/O is blocked before the disk is truly removed, and the refactor is a clean up that reflects this more accurately. It's a solid approach to prevent data loss in the face of disk failures.
|
| 511/4 |
2026/11/03 22:03 |
tool |
codeeditor |
0m
Args: map[CurrentCode:static bool __blk_mark_disk_dead(struct gendisk *disk)
{
/*
* Fail any new I/O.
*/
if (test_and_set_bit(GD_DEAD, &disk->state))
return false;
if (test_bit(GD_OWNS_QUEUE, &disk->state))
blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
/*
* Stop buffered writers from dirtying pages that can't be written out.
*/
set_capacity(disk, 0);
/*
* Prevent new I/O from crossing bio_queue_enter().
*/
return blk_queue_start_drain(disk->queue);
} NewCode:static unsigned int __blk_mark_disk_dead(struct gendisk *disk)
{
/*
* Fail any new I/O.
*/
if (test_and_set_bit(GD_DEAD, &disk->state))
return 0;
if (test_bit(GD_OWNS_QUEUE, &disk->state))
blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
/*
* Stop buffered writers from dirtying pages that can't be written out.
*/
set_capacity(disk, 0);
/*
* Prevent new I/O from crossing bio_queue_enter().
*/
return blk_queue_start_drain(disk->queue);
} SourceFile:block/genhd.c]
Results:
|
| 512/4 |
2026/11/03 22:03 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 65016
output: 114
thoughts: 18
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience and presented in the first person:
**Modifying `__del_gendisk` in `block/genhd.c`**
Alright, time to get my hands dirty. I need to dive into the core of how the generic disk handling works, specifically the `__del_gendisk` function within `block/genhd.c`. This is where the cleanup happens when a `gendisk` structure is being de-allocated. Given my experience, I'm well aware that any changes here need to be meticulously reviewed to avoid regressions or introducing subtle bugs that could manifest as data corruption or system instability down the line. I'll need to carefully consider the potential impact on any dependent subsystems or drivers that might be relying on the existing behavior, even if it seems a bit quirky. I also anticipate that any changes here will need to be thoroughly tested under a variety of different disk configurations and workload scenarios. Itβs critical I understand the exact order of operations and any resource dependencies involved to guarantee the system stays stable, and avoids any race conditions when the disk's going away. Got to remember that this code is running at the *very* low level.
|
| 513/4 |
2026/11/03 22:04 |
tool |
codeeditor |
0m
Args: map[CurrentCode: struct request_queue *q = disk->queue;
struct block_device *part;
unsigned long idx;
bool start_drain;
might_sleep(); NewCode: struct request_queue *q = disk->queue;
struct block_device *part;
unsigned long idx;
unsigned int lock_mask;
might_sleep(); SourceFile:block/genhd.c]
Results:
|
| 514/4 |
2026/11/03 22:04 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 65410
output: 34
thoughts: 57
Thoughts: Here's my summary, as though I'm thinking through this:
**Refactoring `__del_gendisk` Lock Handling**
Okay, time to address that lock acquisition and release within the `__del_gendisk` function in `block/genhd.c`. I need to ensure this is thread-safe and robust, especially considering the potential for race conditions during disk removal. Let me pinpoint the relevant sections in the code. I'm going to focus my attention on lines around 725-740 and then again around 770-785 of `block/genhd.c`. That should cover the crucial areas where the lock is being manipulated. I need to carefully analyze the current implementation there. Let's see how they're handling these locks and what changes are needed to make it more efficient and correct. I'll need to think about potential contention points. I will look for opportunities to make this code cleaner.
|
| 515/4 |
2026/11/03 22:06 |
tool |
read-file |
0m
Args: map[File:block/genhd.c FirstLine:725 LineCount:60]
Results: map[Contents: 725:
726: /*
727: * Drop all partitions now that the disk is marked dead.
728: */
729: mutex_lock(&disk->open_mutex);
730: start_drain = __blk_mark_disk_dead(disk);
731: if (start_drain)
732: blk_freeze_acquire_lock(q);
733: xa_for_each_start(&disk->part_tbl, idx, part, 1)
734: drop_partition(part);
735: mutex_unlock(&disk->open_mutex);
736:
737: if (!(disk->flags & GENHD_FL_HIDDEN)) {
738: sysfs_remove_link(&disk_to_dev(disk)->kobj, "bdi");
739:
740: /*
741: * Unregister bdi before releasing device numbers (as they can
742: * get reused and we'd get clashes in sysfs).
743: */
744: bdi_unregister(disk->bdi);
745: }
746:
747: blk_unregister_queue(disk);
748:
749: kobject_put(disk->part0->bd_holder_dir);
750: kobject_put(disk->slave_dir);
751: disk->slave_dir = NULL;
752:
753: part_stat_set_all(disk->part0, 0);
754: disk->part0->bd_stamp = 0;
755: sysfs_remove_link(block_depr, dev_name(disk_to_dev(disk)));
756: pm_runtime_set_memalloc_noio(disk_to_dev(disk), false);
757: device_del(disk_to_dev(disk));
758:
759: blk_mq_freeze_queue_wait(q);
760:
761: blk_throtl_cancel_bios(disk);
762:
763: blk_sync_queue(q);
764: blk_flush_integrity();
765:
766: if (queue_is_mq(q))
767: blk_mq_cancel_work_sync(q);
768:
769: rq_qos_exit(q);
770:
771: /*
772: * If the disk does not own the queue, allow using passthrough requests
773: * again. Else leave the queue frozen to fail all I/O.
774: */
775: if (!test_bit(GD_OWNS_QUEUE, &disk->state))
776: __blk_mq_unfreeze_queue(q, true);
777: else if (queue_is_mq(q))
778: blk_mq_exit_queue(q);
779:
780: if (start_drain)
781: blk_unfreeze_release_lock(q);
782: }
783:
784: static void disable_elv_switch(struct request_queue *q)
]
|
| 516/4 |
2026/11/03 22:06 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 66619
output: 211
thoughts: 20
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Diving into `__del_gendisk` in `block/genhd.c`**
Alright, time to crack open the hood and get my hands dirty. I'm thinking we need to modify the `__del_gendisk` function in `block/genhd.c`. This is where the magic happens when we're tearing down a generic disk device, and honestly, that's where things can get tricky. I need to be careful here β a misstep could lead to data corruption or, even worse, a system crash. We're dealing with device lifetimes and resource cleanup, a critical area. I'm assuming that the reasons for the planned edit is to address a bug, a performance issue, or possibly a new feature related to how we handle these generic disks. My goal is always to make the code cleaner, more robust, and more efficient, while ensuring we don't introduce regressions. So, let's get into the weeds, analyze the current implementation, and consider the potential ramifications of the changes I'm about to make. I'm going to start by reviewing existing similar code, and testing to make sure it doesn't break anything.
|
| 517/4 |
2026/11/03 22:07 |
tool |
codeeditor |
0m
Args: map[CurrentCode: mutex_lock(&disk->open_mutex);
start_drain = __blk_mark_disk_dead(disk);
if (start_drain)
blk_freeze_acquire_lock(q);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex); NewCode: mutex_lock(&disk->open_mutex);
lock_mask = __blk_mark_disk_dead(disk);
blk_freeze_acquire_lock(q, lock_mask);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex); SourceFile:block/genhd.c]
Results:
|
| 518/4 |
2026/11/03 22:07 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 67121
output: 195
thoughts: 11
Thoughts: Okay, here's my interpretation of that line and my thought process:
**Release at Line 780: Analysis and Implications**
Alright, so line 780... that's where the release happens. I immediately start running through my mental checklists. Whatβs being released? What module, function, or data structure is implicated? Is this a standard release, or something out of the ordinary? I need to quickly recall the surrounding code context. I'm thinking back to my code map... is this part of the input validation, the core processing loop, or the output formatting? Is it memory allocation, a resource lock, or maybe data stream flushing?
I'm rapidly trying to pinpoint the critical section the release is operating in. My experience tells me the potential ramifications are vast: a memory leak if it's not handled correctly, a data corruption if the sequence is off, or even a deadlock scenario, if, for example, it's not paired with a corresponding lock release. Then I ask myself: is this a user-triggered release, an internal cleanup, or is it event-driven? This all helps me form an immediate mental profile of the system's likely behavior.
My immediate concern is always with any concurrency issues: is this thread-safe? Does it need to be? Are there any race conditions that could manifest? Any potential for the classic "double-free" problem? Iβm checking my assumptions against the coding conventions and best practices for this project.
The release itself β whatβs the underlying implementation? Is it a manual `free()` call, a reference counter decrement, or something more complex with garbage collection? Knowing the mechanism informs my mental model of potential failure modes. I need to get a clear picture of what this signifies within the system's larger context. From there, I'll be ready to assess its significance.
|
| 519/4 |
2026/11/03 22:08 |
tool |
codeeditor |
0m
Args: map[CurrentCode: if (!test_bit(GD_OWNS_QUEUE, &disk->state))
__blk_mq_unfreeze_queue(q, true);
else if (queue_is_mq(q))
blk_mq_exit_queue(q);
if (start_drain)
blk_unfreeze_release_lock(q);
} NewCode: if (!test_bit(GD_OWNS_QUEUE, &disk->state))
__blk_mq_unfreeze_queue(q, true);
else if (queue_is_mq(q))
blk_mq_exit_queue(q);
blk_unfreeze_release_lock(q, lock_mask);
} SourceFile:block/genhd.c]
Results:
|
| 520/4 |
2026/11/03 22:08 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 67724
output: 10
thoughts: 22
Thoughts: Okay, let's dive into this. Here's my understanding, presented as a personal thought process, given my expertise:
**Reviewing Changes with `patch-diff`**
Alright, I'm at a point where I need to take a comprehensive look at the modifications I've made. Instead of painstakingly sifting through each file individually, I'm thinking strategically. Let's leverage `patch-diff`. This is a crucial step for me, especially after making potentially complex or far-reaching alterations. It'll give me that broad, high-level view that I need before getting into any detailed debugging, or testing. With my level of experience, a tool like this is a fundamental part of the workflow. I'm expecting this to be a quick, efficient way to identify any potential oversights, conflicts, or unexpected behavior that might have crept in during the modification process. This will be my sanity check. I want to make sure I'm not overlooking anything crucial before moving forward.
|
| 521/4 |
2026/11/03 22:10 |
tool |
patch-diff |
0m
Results: map[Output:diff --git a/block/blk-core.c b/block/blk-core.c
index 8836c7028..fc3ab62e8 100644
--- a/block/blk-core.c
+++ b/block/blk-core.c
@@ -317,34 +317,35 @@ static void blk_free_queue(struct request_queue *q)
* Decrements the refcount of the request_queue and free it when the refcount
* reaches 0.
*/
void blk_put_queue(struct request_queue *q)
{
if (refcount_dec_and_test(&q->refs))
blk_free_queue(q);
}
EXPORT_SYMBOL(blk_put_queue);
-bool blk_queue_start_drain(struct request_queue *q)
+unsigned int blk_queue_start_drain(struct request_queue *q)
{
/*
* When queue DYING flag is set, we need to block new req
* entering queue, so we call blk_freeze_queue_start() to
* prevent I/O from crossing blk_queue_enter().
*/
- bool freeze = __blk_freeze_queue_start(q, current);
+ unsigned int lock_mask = __blk_freeze_queue_start(q,
+ blk_queue_dying(q) ? NULL : current);
if (queue_is_mq(q))
blk_mq_wake_waiters(q);
/* Make blk_queue_enter() reexamine the DYING flag. */
wake_up_all(&q->mq_freeze_wq);
- return freeze;
+ return lock_mask;
}
/**
* blk_queue_enter() - try to increase q->q_usage_counter
* @q: request queue pointer
* @flags: BLK_MQ_REQ_NOWAIT and/or BLK_MQ_REQ_PM
*/
int blk_queue_enter(struct request_queue *q, blk_mq_req_flags_t flags)
{
const bool pm = flags & BLK_MQ_REQ_PM;
diff --git a/block/blk-mq.c b/block/blk-mq.c
index d9ab295be..3f64a59e5 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -106,90 +106,95 @@ void blk_mq_in_driver_rw(struct block_device *part, unsigned int inflight[2])
{
struct mq_inflight mi = { .part = part };
blk_mq_queue_tag_busy_iter(bdev_get_queue(part), blk_mq_check_in_driver,
&mi);
inflight[READ] = mi.inflight[READ];
inflight[WRITE] = mi.inflight[WRITE];
}
#ifdef CONFIG_LOCKDEP
-static bool blk_freeze_set_owner(struct request_queue *q,
- struct task_struct *owner)
+static unsigned int blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
{
+ unsigned int lock_mask = 0;
+
if (!owner)
- return false;
+ return 0;
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
- q->mq_freeze_disk_dead = !q->disk ||
- test_bit(GD_DEAD, &q->disk->state) ||
- !blk_queue_registered(q);
- q->mq_freeze_queue_dying = blk_queue_dying(q);
- return true;
+ if (q->disk && !test_bit(GD_DEAD, &q->disk->state) &&
+ blk_queue_registered(q))
+ lock_mask |= BLK_FREEZE_LOCK_IO;
+ if (!blk_queue_dying(q))
+ lock_mask |= BLK_FREEZE_LOCK_QUEUE;
+ q->mq_freeze_lock_mask = lock_mask;
+ return lock_mask;
}
if (owner == q->mq_freeze_owner)
q->mq_freeze_owner_depth += 1;
- return false;
+ return 0;
}
/* verify the last unfreeze in owner context */
-static bool blk_unfreeze_check_owner(struct request_queue *q)
+static unsigned int blk_unfreeze_check_owner(struct request_queue *q)
{
if (q->mq_freeze_owner != current)
- return false;
+ return 0;
if (--q->mq_freeze_owner_depth == 0) {
q->mq_freeze_owner = NULL;
- return true;
+ return q->mq_freeze_lock_mask;
}
- return false;
+ return 0;
}
#else
-static bool blk_freeze_set_owner(struct request_queue *q,
- struct task_struct *owner)
+static unsigned int blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
{
- return false;
+ return 0;
}
-static bool blk_unfreeze_check_owner(struct request_queue *q)
+static unsigned int blk_unfreeze_check_owner(struct request_queue *q)
{
- return false;
+ return 0;
}
#endif
-bool __blk_freeze_queue_start(struct request_queue *q,
- struct task_struct *owner)
+unsigned int __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner)
{
- bool freeze;
+ unsigned int lock_mask;
mutex_lock(&q->mq_freeze_lock);
- freeze = blk_freeze_set_owner(q, owner);
+ lock_mask = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
if (queue_is_mq(q))
blk_mq_run_hw_queues(q, false);
} else {
mutex_unlock(&q->mq_freeze_lock);
}
- return freeze;
+ return lock_mask;
}
void blk_freeze_queue_start(struct request_queue *q)
{
- if (__blk_freeze_queue_start(q, current))
- blk_freeze_acquire_lock(q);
+ unsigned int lock_mask = __blk_freeze_queue_start(q, current);
+
+ blk_freeze_acquire_lock(q, lock_mask);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
void blk_mq_freeze_queue_wait(struct request_queue *q)
{
wait_event(q->mq_freeze_wq, percpu_ref_is_zero(&q->q_usage_counter));
}
EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait);
int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
@@ -201,43 +206,44 @@ int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
}
EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait_timeout);
void blk_mq_freeze_queue_nomemsave(struct request_queue *q)
{
blk_freeze_queue_start(q);
blk_mq_freeze_queue_wait(q);
}
EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_nomemsave);
-bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
+unsigned int __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
- bool unfreeze;
+ unsigned int lock_mask;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
q->q_usage_counter.data->force_atomic = true;
q->mq_freeze_depth--;
WARN_ON_ONCE(q->mq_freeze_depth < 0);
if (!q->mq_freeze_depth) {
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
}
- unfreeze = blk_unfreeze_check_owner(q);
+ lock_mask = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
- return unfreeze;
+ return lock_mask;
}
void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
{
- if (__blk_mq_unfreeze_queue(q, false))
- blk_unfreeze_release_lock(q);
+ unsigned int lock_mask = __blk_mq_unfreeze_queue(q, false);
+
+ blk_unfreeze_release_lock(q, lock_mask);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_nomemrestore);
/*
* non_owner variant of blk_freeze_queue_start
*
* Unlike blk_freeze_queue_start, the queue doesn't need to be unfrozen
* by the same task. This is fragile and should not be used if at all
* possible.
*/
diff --git a/block/blk.h b/block/blk.h
index ed2172472..2c4d5ee7d 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -48,24 +48,25 @@ bool is_flush_rq(struct request *req);
struct blk_flush_queue *blk_alloc_flush_queue(int node, int cmd_size,
gfp_t flags);
void blk_free_flush_queue(struct blk_flush_queue *q);
const char *blk_status_to_str(blk_status_t status);
const char *blk_status_to_tag(blk_status_t status);
blk_status_t tag_to_blk_status(const char *tag);
enum req_op str_to_blk_op(const char *op);
-bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
-bool blk_queue_start_drain(struct request_queue *q);
-bool __blk_freeze_queue_start(struct request_queue *q,
- struct task_struct *owner);
+unsigned int __blk_mq_unfreeze_queue(struct request_queue *q,
+ bool force_atomic);
+unsigned int blk_queue_start_drain(struct request_queue *q);
+unsigned int __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner);
int __bio_queue_enter(struct request_queue *q, struct bio *bio);
void submit_bio_noacct_nocheck(struct bio *bio, bool split);
int bio_submit_or_kill(struct bio *bio, unsigned int flags);
static inline bool blk_try_enter_queue(struct request_queue *q, bool pm)
{
rcu_read_lock();
if (!percpu_ref_tryget_live_rcu(&q->q_usage_counter))
goto fail;
@@ -770,41 +771,50 @@ int bdev_open(struct block_device *bdev, blk_mode_t mode, void *holder,
const struct blk_holder_ops *hops, struct file *bdev_file);
int bdev_permission(dev_t dev, blk_mode_t mode, void *holder);
void bio_integrity_generate(struct bio *bio);
blk_status_t bio_integrity_verify(struct bio *bio,
struct bvec_iter *saved_iter);
void blk_integrity_prepare(struct request *rq);
void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
+enum {
+ BLK_FREEZE_LOCK_IO = (1 << 0),
+ BLK_FREEZE_LOCK_QUEUE = (1 << 1),
+};
+
#ifdef CONFIG_LOCKDEP
-static inline void blk_freeze_acquire_lock(struct request_queue *q)
+static inline void blk_freeze_acquire_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
- if (!q->mq_freeze_disk_dead)
+ if (lock_mask & BLK_FREEZE_LOCK_IO)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
- if (!q->mq_freeze_queue_dying)
+ if (lock_mask & BLK_FREEZE_LOCK_QUEUE)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q)
+static inline void blk_unfreeze_release_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
- if (!q->mq_freeze_queue_dying)
+ if (lock_mask & BLK_FREEZE_LOCK_QUEUE)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
- if (!q->mq_freeze_disk_dead)
+ if (lock_mask & BLK_FREEZE_LOCK_IO)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
#else
-static inline void blk_freeze_acquire_lock(struct request_queue *q)
+static inline void blk_freeze_acquire_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q)
+static inline void blk_unfreeze_release_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
}
#endif
/*
* debugfs directory and file creation can trigger fs reclaim, which can enter
* back into the block layer request_queue. This can cause deadlock if the
* queue is frozen. Use NOIO context together with debugfs_mutex to prevent fs
* reclaim from triggering block I/O.
*/
diff --git a/block/genhd.c b/block/genhd.c
index 10ca8b4d6..e73349b74 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -650,39 +650,39 @@ static void blk_report_disk_dead(struct gendisk *disk, bool surprise)
rcu_read_unlock();
bdev_mark_dead(bdev, surprise);
put_device(&bdev->bd_device);
rcu_read_lock();
}
rcu_read_unlock();
}
-static bool __blk_mark_disk_dead(struct gendisk *disk)
+static unsigned int __blk_mark_disk_dead(struct gendisk *disk)
{
/*
* Fail any new I/O.
*/
if (test_and_set_bit(GD_DEAD, &disk->state))
- return false;
+ return 0;
if (test_bit(GD_OWNS_QUEUE, &disk->state))
blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
/*
* Stop buffered writers from dirtying pages that can't be written out.
*/
set_capacity(disk, 0);
/*
* Prevent new I/O from crossing bio_queue_enter().
*/
return blk_queue_start_drain(disk->queue);
}
/**
* blk_mark_disk_dead - mark a disk as dead
* @disk: disk to mark as dead
*
* Mark as disk as dead (e.g. surprise removed) and don't accept any new I/O
* to this disk.
*/
@@ -692,100 +692,98 @@ void blk_mark_disk_dead(struct gendisk *disk)
__blk_mark_disk_dead(disk);
blk_report_disk_dead(disk, true);
}
EXPORT_SYMBOL_GPL(blk_mark_disk_dead);
static void __del_gendisk(struct gendisk *disk)
{
struct request_queue *q = disk->queue;
struct block_device *part;
unsigned long idx;
- bool start_drain;
+ unsigned int lock_mask;
might_sleep();
if (WARN_ON_ONCE(!disk_live(disk) && !(disk->flags & GENHD_FL_HIDDEN)))
return;
disk_del_events(disk);
/*
* Prevent new openers by unlinked the bdev inode.
*/
mutex_lock(&disk->open_mutex);
xa_for_each(&disk->part_tbl, idx, part)
bdev_unhash(part);
mutex_unlock(&disk->open_mutex);
/*
* Tell the file system to write back all dirty data and shut down if
* it hasn't been notified earlier.
*/
if (!test_bit(GD_DEAD, &disk->state))
blk_report_disk_dead(disk, false);
/*
* Drop all partitions now that the disk is marked dead.
*/
mutex_lock(&disk->open_mutex);
- start_drain = __blk_mark_disk_dead(disk);
- if (start_drain)
- blk_freeze_acquire_lock(q);
+ lock_mask = __blk_mark_disk_dead(disk);
+ blk_freeze_acquire_lock(q, lock_mask);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
if (!(disk->flags & GENHD_FL_HIDDEN)) {
sysfs_remove_link(&disk_to_dev(disk)->kobj, "bdi");
/*
* Unregister bdi before releasing device numbers (as they can
* get reused and we'd get clashes in sysfs).
*/
bdi_unregister(disk->bdi);
}
blk_unregister_queue(disk);
kobject_put(disk->part0->bd_holder_dir);
kobject_put(disk->slave_dir);
disk->slave_dir = NULL;
part_stat_set_all(disk->part0, 0);
disk->part0->bd_stamp = 0;
sysfs_remove_link(block_depr, dev_name(disk_to_dev(disk)));
pm_runtime_set_memalloc_noio(disk_to_dev(disk), false);
device_del(disk_to_dev(disk));
blk_mq_freeze_queue_wait(q);
blk_throtl_cancel_bios(disk);
blk_sync_queue(q);
blk_flush_integrity();
if (queue_is_mq(q))
blk_mq_cancel_work_sync(q);
rq_qos_exit(q);
/*
* If the disk does not own the queue, allow using passthrough requests
* again. Else leave the queue frozen to fail all I/O.
*/
if (!test_bit(GD_OWNS_QUEUE, &disk->state))
__blk_mq_unfreeze_queue(q, true);
else if (queue_is_mq(q))
blk_mq_exit_queue(q);
- if (start_drain)
- blk_unfreeze_release_lock(q);
+ blk_unfreeze_release_lock(q, lock_mask);
}
static void disable_elv_switch(struct request_queue *q)
{
struct blk_mq_tag_set *set = q->tag_set;
WARN_ON_ONCE(!queue_is_mq(q));
down_write(&set->update_nr_hwq_lock);
blk_queue_flag_set(QUEUE_FLAG_NO_ELV_SWITCH, q);
up_write(&set->update_nr_hwq_lock);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 0c2010230..32a8e93c4 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -491,175 +491,174 @@ struct blk_independent_access_ranges {
struct request_queue {
/*
* The queue owner gets to use this for whatever they like.
* ll_rw_blk doesn't touch it.
*/
void *queuedata;
struct elevator_queue *elevator;
const struct blk_mq_ops *mq_ops;
/* sw queues */
struct blk_mq_ctx __percpu *queue_ctx;
/*
* various queue flags, see QUEUE_* below
*/
unsigned long queue_flags;
unsigned int __data_racy rq_timeout;
unsigned int queue_depth;
refcount_t refs;
/* hw dispatch queues */
unsigned int nr_hw_queues;
struct blk_mq_hw_ctx * __rcu *queue_hw_ctx __counted_by_ptr(nr_hw_queues);
struct percpu_ref q_usage_counter;
struct lock_class_key io_lock_cls_key;
struct lockdep_map io_lockdep_map;
struct lock_class_key q_lock_cls_key;
struct lockdep_map q_lockdep_map;
struct request *last_merge;
spinlock_t queue_lock;
int quiesce_depth;
struct gendisk *disk;
/*
* mq queue kobject
*/
struct kobject *mq_kobj;
struct queue_limits limits;
#ifdef CONFIG_PM
struct device *dev;
enum rpm_status rpm_status;
#endif
/*
* Number of contexts that have called blk_set_pm_only(). If this
* counter is above zero then only RQF_PM requests are processed.
*/
atomic_t pm_only;
struct blk_queue_stats *stats;
struct rq_qos *rq_qos;
struct mutex rq_qos_mutex;
/*
* ida allocated id for this queue. Used to index queues from
* ioctx.
*/
int id;
/*
* queue settings
*/
unsigned int nr_requests; /* Max # of requests */
unsigned int async_depth; /* Max # of async requests */
#ifdef CONFIG_BLK_INLINE_ENCRYPTION
struct blk_crypto_profile *crypto_profile;
struct kobject *crypto_kobject;
#endif
struct timer_list timeout;
struct work_struct timeout_work;
atomic_t nr_active_requests_shared_tags;
struct blk_mq_tags *sched_shared_tags;
struct list_head icq_list;
#ifdef CONFIG_BLK_CGROUP
DECLARE_BITMAP (blkcg_pols, BLKCG_MAX_POLS);
struct blkcg_gq *root_blkg;
struct list_head blkg_list;
struct mutex blkcg_mutex;
#endif
int node;
spinlock_t requeue_lock;
struct list_head requeue_list;
struct delayed_work requeue_work;
#ifdef CONFIG_BLK_DEV_IO_TRACE
struct blk_trace __rcu *blk_trace;
#endif
/*
* for flush operations
*/
struct blk_flush_queue *fq;
struct list_head flush_list;
/*
* Protects against I/O scheduler switching, particularly when updating
* q->elevator. Since the elevator update code path may also modify q->
* nr_requests and wbt latency, this lock also protects the sysfs attrs
* nr_requests and wbt_lat_usec. Additionally the nr_hw_queues update
* may modify hctx tags, reserved-tags and cpumask, so this lock also
* helps protect the hctx sysfs/debugfs attrs. To ensure proper locking
* order during an elevator or nr_hw_queue update, first freeze the
* queue, then acquire ->elevator_lock.
*/
struct mutex elevator_lock;
struct mutex sysfs_lock;
/*
* Protects queue limits and also sysfs attribute read_ahead_kb.
*/
struct mutex limits_lock;
/*
* for reusing dead hctx instance in case of updating
* nr_hw_queues
*/
struct list_head unused_hctx_list;
spinlock_t unused_hctx_lock;
int mq_freeze_depth;
#ifdef CONFIG_BLK_DEV_THROTTLING
/* Throttle data */
struct throtl_data *td;
#endif
struct rcu_head rcu_head;
#ifdef CONFIG_LOCKDEP
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
/*
- * Records disk & queue state in current context, used in unfreeze
+ * Records lockdep locks acquired in owner context, used in unfreeze
* queue
*/
- bool mq_freeze_disk_dead;
- bool mq_freeze_queue_dying;
+ unsigned int mq_freeze_lock_mask;
#endif
wait_queue_head_t mq_freeze_wq;
/*
* Protect concurrent access to q_usage_counter by
* percpu_ref_kill() and percpu_ref_reinit().
*/
struct mutex mq_freeze_lock;
struct blk_mq_tag_set *tag_set;
struct list_head tag_set_list;
struct dentry *debugfs_dir;
struct dentry *sched_debugfs_dir;
struct dentry *rqos_debugfs_dir;
/*
* Serializes all debugfs metadata operations using the above dentries.
*/
struct mutex debugfs_mutex;
};
/* Keep blk_queue_flag_name[] in sync with the definitions below */
]
|
| 522/4 |
2026/11/03 22:10 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 75219
output: 1209
thoughts: 3762
Thoughts: **Refactoring the Block Layer Freeze/Unfreeze Mechanism**
Okay, here's the breakdown of what I've just reviewed. This patch refactors the block layer's freeze/unfreeze mechanism, specifically focusing on the lockdep integration for request queues. The core of this change involves shifting from using boolean flags to track freeze state to using an `unsigned int` bitmask called `mq_freeze_lock_mask`. This bitmask indicates which locks are held during a freeze operation, which is a significant improvement because it makes the intention of the code much clearer.
First, the `struct request_queue` now includes this `mq_freeze_lock_mask` instead of individual boolean flags like `mq_freeze_disk_dead` and `mq_freeze_queue_dying`. This streamlines the logic.
Second, the freeze/unfreeze functions (`__blk_freeze_queue_start`, `__blk_mq_unfreeze_queue`, `blk_queue_start_drain`, and `__blk_mark_disk_dead`) have their return types changed to `unsigned int`. The returned `lock_mask` indicates which locks should be acquired or released. Crucially, the old boolean return value which was intended to indicate if the queue was frozen or unfrozen is now discarded and the lock mask carries this state.
Third, `blk_freeze_acquire_lock` and `blk_unfreeze_release_lock` now accept the `lock_mask` as an argument. The original functions acquired/released locks based on the state of the flags on the queue object, but with the lock mask the operations are performed according to the intentions of the freeze/unfreeze operation. This makes the code much cleaner and less prone to errors.
The `blk_freeze_set_owner` and `blk_unfreeze_check_owner` functions also return and use the `lock_mask` respectively. The logic is updated to check the queue's state and set bits in the `lock_mask` appropriately.
Finally, all the callers of the modified functions, including critical ones like `blk_mq_unfreeze_queue_nomemrestore`, `__del_gendisk`, `blk_queue_start_drain` and `blk_freeze_queue_start`, have been updated to properly handle the new return values and pass the lock mask to the appropriate lock functions.
In summary, it's a well-structured refactoring that addresses the bug and significantly improves the maintainability and clarity of the freeze/unfreeze code, especially concerning lockdep. The use of the lock mask is a smart approach for representing lock acquisition and release intentions during freeze/unfreeze operations.
|
| 523/3 |
2026/11/03 22:11 |
action |
test-patch |
24m
Results: map[PatchDiff:diff --git a/block/blk-core.c b/block/blk-core.c
index 8836c7028..fc3ab62e8 100644
--- a/block/blk-core.c
+++ b/block/blk-core.c
@@ -324,20 +324,21 @@ void blk_put_queue(struct request_queue *q)
}
EXPORT_SYMBOL(blk_put_queue);
-bool blk_queue_start_drain(struct request_queue *q)
+unsigned int blk_queue_start_drain(struct request_queue *q)
{
/*
* When queue DYING flag is set, we need to block new req
* entering queue, so we call blk_freeze_queue_start() to
* prevent I/O from crossing blk_queue_enter().
*/
- bool freeze = __blk_freeze_queue_start(q, current);
+ unsigned int lock_mask = __blk_freeze_queue_start(q,
+ blk_queue_dying(q) ? NULL : current);
if (queue_is_mq(q))
blk_mq_wake_waiters(q);
/* Make blk_queue_enter() reexamine the DYING flag. */
wake_up_all(&q->mq_freeze_wq);
- return freeze;
+ return lock_mask;
}
/**
diff --git a/block/blk-mq.c b/block/blk-mq.c
index d9ab295be..3f64a59e5 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -113,60 +113,64 @@ void blk_mq_in_driver_rw(struct block_device *part, unsigned int inflight[2])
}
#ifdef CONFIG_LOCKDEP
-static bool blk_freeze_set_owner(struct request_queue *q,
- struct task_struct *owner)
+static unsigned int blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
{
+ unsigned int lock_mask = 0;
+
if (!owner)
- return false;
+ return 0;
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
- q->mq_freeze_disk_dead = !q->disk ||
- test_bit(GD_DEAD, &q->disk->state) ||
- !blk_queue_registered(q);
- q->mq_freeze_queue_dying = blk_queue_dying(q);
- return true;
+ if (q->disk && !test_bit(GD_DEAD, &q->disk->state) &&
+ blk_queue_registered(q))
+ lock_mask |= BLK_FREEZE_LOCK_IO;
+ if (!blk_queue_dying(q))
+ lock_mask |= BLK_FREEZE_LOCK_QUEUE;
+ q->mq_freeze_lock_mask = lock_mask;
+ return lock_mask;
}
if (owner == q->mq_freeze_owner)
q->mq_freeze_owner_depth += 1;
- return false;
+ return 0;
}
/* verify the last unfreeze in owner context */
-static bool blk_unfreeze_check_owner(struct request_queue *q)
+static unsigned int blk_unfreeze_check_owner(struct request_queue *q)
{
if (q->mq_freeze_owner != current)
- return false;
+ return 0;
if (--q->mq_freeze_owner_depth == 0) {
q->mq_freeze_owner = NULL;
- return true;
+ return q->mq_freeze_lock_mask;
}
- return false;
+ return 0;
}
#else
-static bool blk_freeze_set_owner(struct request_queue *q,
- struct task_struct *owner)
+static unsigned int blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
{
- return false;
+ return 0;
}
-static bool blk_unfreeze_check_owner(struct request_queue *q)
+static unsigned int blk_unfreeze_check_owner(struct request_queue *q)
{
- return false;
+ return 0;
}
#endif
-bool __blk_freeze_queue_start(struct request_queue *q,
- struct task_struct *owner)
+unsigned int __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner)
{
- bool freeze;
+ unsigned int lock_mask;
mutex_lock(&q->mq_freeze_lock);
- freeze = blk_freeze_set_owner(q, owner);
+ lock_mask = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
@@ -176,13 +180,14 @@ bool __blk_freeze_queue_start(struct request_queue *q,
mutex_unlock(&q->mq_freeze_lock);
}
- return freeze;
+ return lock_mask;
}
void blk_freeze_queue_start(struct request_queue *q)
{
- if (__blk_freeze_queue_start(q, current))
- blk_freeze_acquire_lock(q);
+ unsigned int lock_mask = __blk_freeze_queue_start(q, current);
+
+ blk_freeze_acquire_lock(q, lock_mask);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -208,9 +213,9 @@ void blk_mq_freeze_queue_nomemsave(struct request_queue *q)
}
EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_nomemsave);
-bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
+unsigned int __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
- bool unfreeze;
+ unsigned int lock_mask;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
@@ -221,16 +226,17 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
}
- unfreeze = blk_unfreeze_check_owner(q);
+ lock_mask = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
- return unfreeze;
+ return lock_mask;
}
void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
{
- if (__blk_mq_unfreeze_queue(q, false))
- blk_unfreeze_release_lock(q);
+ unsigned int lock_mask = __blk_mq_unfreeze_queue(q, false);
+
+ blk_unfreeze_release_lock(q, lock_mask);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_nomemrestore);
diff --git a/block/blk.h b/block/blk.h
index ed2172472..2c4d5ee7d 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -55,10 +55,11 @@ const char *blk_status_to_tag(blk_status_t status);
blk_status_t tag_to_blk_status(const char *tag);
enum req_op str_to_blk_op(const char *op);
-bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
-bool blk_queue_start_drain(struct request_queue *q);
-bool __blk_freeze_queue_start(struct request_queue *q,
- struct task_struct *owner);
+unsigned int __blk_mq_unfreeze_queue(struct request_queue *q,
+ bool force_atomic);
+unsigned int blk_queue_start_drain(struct request_queue *q);
+unsigned int __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner);
int __bio_queue_enter(struct request_queue *q, struct bio *bio);
void submit_bio_noacct_nocheck(struct bio *bio, bool split);
int bio_submit_or_kill(struct bio *bio, unsigned int flags);
@@ -777,27 +778,36 @@ blk_status_t bio_integrity_verify(struct bio *bio,
void blk_integrity_prepare(struct request *rq);
void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
+enum {
+ BLK_FREEZE_LOCK_IO = (1 << 0),
+ BLK_FREEZE_LOCK_QUEUE = (1 << 1),
+};
+
#ifdef CONFIG_LOCKDEP
-static inline void blk_freeze_acquire_lock(struct request_queue *q)
+static inline void blk_freeze_acquire_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
- if (!q->mq_freeze_disk_dead)
+ if (lock_mask & BLK_FREEZE_LOCK_IO)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
- if (!q->mq_freeze_queue_dying)
+ if (lock_mask & BLK_FREEZE_LOCK_QUEUE)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q)
+static inline void blk_unfreeze_release_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
- if (!q->mq_freeze_queue_dying)
+ if (lock_mask & BLK_FREEZE_LOCK_QUEUE)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
- if (!q->mq_freeze_disk_dead)
+ if (lock_mask & BLK_FREEZE_LOCK_IO)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
#else
-static inline void blk_freeze_acquire_lock(struct request_queue *q)
+static inline void blk_freeze_acquire_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q)
+static inline void blk_unfreeze_release_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
}
#endif
diff --git a/block/genhd.c b/block/genhd.c
index 10ca8b4d6..e73349b74 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -657,13 +657,13 @@ static void blk_report_disk_dead(struct gendisk *disk, bool surprise)
rcu_read_unlock();
}
-static bool __blk_mark_disk_dead(struct gendisk *disk)
+static unsigned int __blk_mark_disk_dead(struct gendisk *disk)
{
/*
* Fail any new I/O.
*/
if (test_and_set_bit(GD_DEAD, &disk->state))
- return false;
+ return 0;
if (test_bit(GD_OWNS_QUEUE, &disk->state))
blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
@@ -699,7 +699,7 @@ static void __del_gendisk(struct gendisk *disk)
struct request_queue *q = disk->queue;
struct block_device *part;
unsigned long idx;
- bool start_drain;
+ unsigned int lock_mask;
might_sleep();
@@ -727,9 +727,8 @@ static void __del_gendisk(struct gendisk *disk)
* Drop all partitions now that the disk is marked dead.
*/
mutex_lock(&disk->open_mutex);
- start_drain = __blk_mark_disk_dead(disk);
- if (start_drain)
- blk_freeze_acquire_lock(q);
+ lock_mask = __blk_mark_disk_dead(disk);
+ blk_freeze_acquire_lock(q, lock_mask);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
@@ -777,8 +776,7 @@ static void __del_gendisk(struct gendisk *disk)
else if (queue_is_mq(q))
blk_mq_exit_queue(q);
- if (start_drain)
- blk_unfreeze_release_lock(q);
+ blk_unfreeze_release_lock(q, lock_mask);
}
static void disable_elv_switch(struct request_queue *q)
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 0c2010230..32a8e93c4 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -637,11 +637,10 @@ struct request_queue {
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
/*
- * Records disk & queue state in current context, used in unfreeze
+ * Records lockdep locks acquired in owner context, used in unfreeze
* queue
*/
- bool mq_freeze_disk_dead;
- bool mq_freeze_queue_dying;
+ unsigned int mq_freeze_lock_mask;
#endif
wait_queue_head_t mq_freeze_wq;
/*
TestError:]
|
| 524/3 |
2026/11/03 22:36 |
action |
If |
5m
Args:
|
| 525/4 |
2026/11/03 22:36 |
agent |
patch-reviewer |
5m
Model:
Results: map[ReviewApproved:true ReviewComments:[]]
Instruction:
Review a proposed Linux kernel patch that compiles and passes reproducer tests.
Evaluate the patch diff against the crash report, root cause, and the architectural design guidelines below.
Scope Constraint (Single-Patch Submissions):
We only generate single, standalone patches (not patch series). If a comprehensive architectural redesign would
require a multi-patch series touching many files, accept a localized single-patch fix as long as it correctly
fixes the bug, does not introduce new issues, and avoids sentinel band-aids within its local scope.
Evaluation:
- Set ReviewApproved=true (and leave ReviewComments empty) if the patch is acceptable for upstream submission
as a single-patch fix.
- Set ReviewApproved=false and list concise, actionable feedback in ReviewComments if the patch contains
fixable "Kernel Architectural Design & Maintainer Taste" violations.
Don't make assumptions about the kernel source code (it may be different from what you assume it is).
Extensively use the provided code access tools (codesearch-*, git-*, grepper, etc)
to examine the actual source code, and confirm any assumptions.
---
# Kernel Architectural Design & Maintainer Taste
Evaluate kernel patches and fix proposals beyond binary bug presence. Enforce **maintainer taste**, **lifecycle symmetry**, **typestate soundness**, and **topological graph simplicity**.
---
## 1. Core Philosophy: Band-Aid vs. Architectural Design
Naive patches often introduce **defensive sentinel guards** (e.g., ad-hoc `if (!ptr) return;` checks, status flags, or suppressed warnings) directly at the point of failure. While locally avoiding crashes, they degrade subsystem architecture by leaving uninitialized states reachable.
Maintainer "good taste" solves the root cause by **shifting invariants** (making invalid states unrepresentable) and moving dynamic runtime checks into static typestate guarantees.
```
HACKY BAND-AID FIX (Monolithic Cleanup) ARCHITECTURAL DESIGN (Scoped RAII / Invariant Shift)
βββββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββββββ
[ Init / Entry ] [ Init / Entry ]
β β
(Register Global Cleanup) (Allocate Resource A)
β β
[ Init Sub-B ] ββfailβββ [ Init Sub-B ] ββfailβββ
β (success) β β (success) β
βΌ β βΌ βΌ
[ Setup Complete ] β (Arm B Cleanup / RAII) (Unwind A Only:
β β β B never armed)
(Deferred Teardown) β βΌ β
β β [ Setup Complete ] βΌ
βΌ βΌ β [ Error Exit ]
[ release_all ] βββββββββ (LIFO Scope Teardown)
β β
(if (!ctx->b) return;) <-- Defensive guard! βΌ
β [ Clean Destruction ]
[ Unsafe State ] (Zero sentinel checks needed)
```
```c
// ANTI-PATTERN (Defensive Sentinel Guard): Teardown called on partial init -> callee needs guard
void driver_cleanup(struct ctx *ctx) {
if (!ctx->buf) return; // <-- Sentinel band-aid
free_buffer(ctx->buf);
}
// CANONICAL SHIFT (Granular Scoped Action): Registered only upon complete initialization
ctx->buf = alloc_buffer();
if (!ctx->buf) return -ENOMEM;
devm_add_action_or_reset(dev, free_buffer_action, ctx->buf);
```
---
## 2. Maintainer Taste as Graph Topology & Structural Simplicity
Software design quality maps directly to graph-theoretic properties across the Control-Flow Graph (CFG), Data-Flow Graph (DFG), and Object Lifecycle DAG:
### A. Control-Flow Graph (CFG) Simplification
* **Branch Minimization & Path Explosion (McCabe 1976):** Every defensive check added to a compound destructor or callback (`if (!ctx->buffer) return;`) adds a predicate node ($\pi$), increases cyclomatic complexity $v(G) = |E| - |V| + 2$, causes exponential path explosion ($O(2^k)$ paths), and enlarges explicit state spaces ($|S| = \prod |D_i|$). Good taste eliminates the branch by guaranteeing destructors are invoked only on initialized typestates. *(Note: Standard idempotent leaf deallocators like `kfree(NULL)` and public API input sanitizers are exempt).*
* **Single-Entry Single-Exit (SESE) Symmetry (Ferrante 1987, Johnson 1994, Dijkstra 1972):** Resource acquisition and release must form strict **nested dominator trees**. If resource $R_i$ is acquired at node $A$, the set of release actions $\{B_1, \dots, B_m\}$ must form a strict **post-dominating cut** relative to $A$ across all maximal exit paths.
* **Pointer Uniformity (Linus's "Good Taste" Rule):** Eliminate special-case conditional branches by operating on address indirection (e.g., indirect pointers `**curr` in linked list unlinking) to unify edge and interior cases into a branchless invariant.
* **Lexical Scope Invariants & Affine Lifecycles (Wadler 1990, RAII):** Enforce SESE symmetry and "consumed exactly once" affine invariants using compiler-backed scoped cleanup (`<linux/cleanup.h>` `guard()`, `scoped_guard()`, `__free()`).
### B. Ownership & Lifetime DAGs
* **Acyclic Lifecycles & Topological Teardown (Tarjan 1972, Kahn 1962):** Resource ownership must form a strict Directed Acyclic Graph (DAG) $G = (R, E)$. Teardown order must strictly follow reverse topological sort $\text{toposort}(G)^R$. Mixing conflicting lifetime paradigms (e.g., embedding a dynamic refcounted `kref`/socket struct inside a device-managed `devres` buffer or parent container) violates DAG acyclicity, creating synchronous blocking hacks (`wait_for_completion`), circular pins, and Use-After-Free hazards.
* **Three-Phase Concurrent Quiescence:** Multi-threaded and asynchronous teardown (networking, block layer, RCU) must strictly sequence: (1) **Deactivation/Delisting** (make unreachable) -> (2) **Quiescence & Draining** (`synchronize_rcu()`, `cancel_work_sync()`, `napi_disable()`) -> (3) **Physical Reclamation** (`kfree()`, `kmem_cache_destroy()`).
* **Typestate Validity (Strom & Yemini 1986, Aldrich et al. 2009):** A struct with $N$ fields should not use runtime boolean flags (`ctx->is_initialized`) to model incomplete typestates. Sub-resources must transition as a deterministic typestate automaton ($S_{uninit} \xrightarrow{\text{alloc}} S_{init} \xrightarrow{\text{publish}} S_{registered}$), and registration functions must accept only fully initialized typestates.
---
## 3. Deterministic Decision Trigger Matrix
| Code Symptom / Trigger (When you see X) | Anti-Pattern Band-Aid (DO NOT DO Z) | Canonical Invariant Shift (DO Y) |
| :--- | :--- | :--- |
| **Null deref in compound destructor / cleanup callback** | Add `if (!priv->buf) return;` in composite cleanup handler | Register granular cleanup immediately upon allocation via `devm_add_action_or_reset()`, `<linux/cleanup.h>` `__free()`, or discrete reverse LIFO labels |
| **UAF on dynamic object after container unbind** | Allocate with `devm_kzalloc()` and block on `wait_for_completion()` | Allocate with `kzalloc()`, manage lifetime via `kref_get()`/`kref_put()`, call unbind/delist on unbind, free in `kref` release callback |
| **Goto ladder lock leaks on early error exit** | Sprinkle manual `mutex_unlock()` across error returns | Use `guard(mutex)(&lock)` or `scoped_guard(spinlock, &lock)` from `<linux/cleanup.h>` |
| **Callback / IRQ / timer fires before full init** | Add `if (!priv->ready)` check inside IRQ/timer handler | Move `request_irq()`, `timer_setup()`, or `napi_enable()` strictly to the end of setup after all state structures are fully initialized |
| **Multi-step setup failure leaks resources** | Route all errors to a single `err:` label calling a monolithic `cleanup(priv)` with NULL checks | Use `cleanup.h` RAII, granular `devm` actions, or a strict reverse LIFO goto ladder (`err_free_b:` -> `err_free_a:`) |
| **Mixed ownership / asymmetric refcount drops** | Conditionally call `kref_put()` in caller based on error code | Enforce unconditional callee-cleans or caller-cleans ownership convention across all paths |
| **Ad-hoc state flag polling during teardown** | Add `priv->stopping = true` and spin/poll in callbacks | Use atomic typestate transitions and synchronous flush/drain APIs (`cancel_work_sync()`, `drain_workqueue()`) |
---
## 4. The Architectural Review Checklist
Before finalizing any kernel fix or review, audit against the following four criteria:
1. **The Sentinel Test (Caller vs. Callee Responsibility):**
* *Smell:* Adding a defensive guard (`if (!ptr)` or `if (flags & INITIALIZED)`) inside a compound teardown callback or destructor to mask partial initialization.
* *Invariant:* If a destructor executes on uninitialized data, the defect is at the **caller's registration/invocation point**, not the callee.
* *Note:* Standard C allocator no-ops (`kfree(NULL)`) and public API parameter validators (`if (WARN_ON(!ptr)) return -EINVAL;`) are exempt; this rule targets *internal subsystem lifecycle pipelines and teardown paths*.
* *Action:* Move registration to the point of complete initialization (`devm_add_action_or_reset()`, RAII/`__free()`, or discrete caller unwinding).
2. **LIFO Stack Unwinding Symmetry:**
* *Smell:* Releasing resources in arbitrary order or invoking destructors for partially initialized subsystems.
* *Invariant:* Resource release must strictly mirror acquisition order in reverse (LIFO) without monolithic cleanup guards.
* *Action:* Verify that partial setup/initialization failures (e.g., `probe()`, `mount()`, `open()`, `alloc_pool()`) unwind only already-allocated resources in reverse order via strict LIFO labels or `cleanup.h` scope exit.
3. **Ownership Decoupling:**
* *Smell:* Embedding dynamically refcounted objects (`kref`, `struct sock`, `struct inode`, `struct file`) directly inside hardware device-bound allocations (`devres`) or parent containers (`super_block`, `net_device`).
* *Invariant:* Dynamic consumer references must outlive parent unregistration without use-after-free, circular pins, or blocking hacks.
* *Action:* Decouple the refcounted core object from the container binding; container teardown must unbind/delist the object, but memory is freed exclusively by the final `kref_put()`.
4. **Codebase Idiom Alignment:**
* *Smell:* Using legacy custom rollback ladders, ad-hoc state flags, or manual lock unlocking on error paths.
* *Invariant:* Prefer standard, modern kernel abstractions with compiler-enforced safety guarantees.
* *Action (Modern >= 6.6):* Replace manual boilerplate with `cleanup.h` (`guard()`, `scoped_guard()`, `__free()`), `devm_add_action_or_reset()`, `refcount_t`, and standard `kref` helpers.
* *Action (Legacy / LTS / No-RAII Subsystems):* Enforce clean, branchless reverse LIFO goto ladders (`err_free_b:` -> `err_free_a:`).
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt:
Bug title:
WARNING: lock held when returning to user space in elevator_change
The crash report:
device-mapper: ioctl: device has been removed from the dev hash table.
================================================
WARNING: lock held when returning to user space!
syzkaller #1 Not tainted
------------------------------------------------
syz.3.1525/11804 is leaving the kernel with locks still held!
locks held by syz.3.1525/11804: 1, last CPU#0:
#0: ffff88805abdd468 (&q->q_usage_counter(queue)#52){+.+.}-{0:0}, at: blk_mq_freeze_queue include/linux/blk-mq.h:959 [inline]
#0: ffff88805abdd468 (&q->q_usage_counter(queue)#52){+.+.}-{0:0}, at: elevator_change+0x194/0x480 block/elevator.c:668
The root cause explanation:
### Root Cause Analysis
#### Summary
The `WARNING: lock held when returning to user space!` for `&q->q_usage_counter(queue)` (which is the lockdep map `q->q_lockdep_map` acquired at `elevator_change+0x194/0x480`, `block/elevator.c:668`) is caused by a race condition between:
1. **`DM_TABLE_LOAD` (`table_load`)** initializing and registering the request-based DM queue/gendisk (`dm_setup_md_queue()` -> `add_disk()` -> `blk_register_queue()` -> `elevator_set_default()` -> `elevator_change()`), and
2. **`DM_DEV_REMOVE` (`dev_remove`)** concurrently destroying the same DM device (`dm_destroy()` -> `__dm_destroy()` -> `blk_mark_disk_dead()`), which marks the queue dying and starts draining/freezing the queue.
Specifically, in the block layer's queue-freeze lockdep tracking (`block/blk-mq.c` and `block/blk.h`), the flags `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead` are stored as per-`request_queue` fields protected by `q->mq_freeze_lock` when `q->mq_freeze_depth == 0`, **but `blk_unfreeze_release_lock(q)` reads them outside `q->mq_freeze_lock` after `q->mq_freeze_depth` has already been decremented to `0`**. When `blk_mark_disk_dead()` races with `blk_mq_unfreeze_queue()`, `q->mq_freeze_queue_dying` is overwritten from `false` to `true` before `blk_unfreeze_release_lock(q)` runs, causing `blk_unfreeze_release_lock(q)` to skip releasing `q->q_lockdep_map`.
---
#### Detailed Mechanism
##### 1. Lockdep modeling of `blk_mq_freeze_queue()` / `blk_mq_unfreeze_queue()`
In `block/blk-core.c:500`, `q->q_lockdep_map` is initialized with the name `"&q->q_usage_counter(queue)"`:
```c
lockdep_init_map(&q->q_lockdep_map, "&q->q_usage_counter(queue)",
&q->q_lock_cls_key, 0);
```
In `block/blk-mq.c`, when a task freezes a queue via `blk_mq_freeze_queue(q)` -> `blk_freeze_queue_start(q)`:
```c
static bool blk_freeze_set_owner(struct request_queue *q,
struct task_struct *owner)
{
if (!owner)
return false;
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
q->mq_freeze_disk_dead = !q->disk ||
test_bit(GD_DEAD, &q->disk->state) ||
!blk_queue_registered(q);
q->mq_freeze_queue_dying = blk_queue_dying(q);
return true;
}
if (owner == q->mq_freeze_owner)
q->mq_freeze_owner_depth += 1;
return false;
}
```
```c
bool __blk_freeze_queue_start(struct request_queue *q,
struct task_struct *owner)
{
bool freeze;
mutex_lock(&q->mq_freeze_lock);
freeze = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
if (queue_is_mq(q))
blk_mq_run_hw_queues(q, false);
} else {
mutex_unlock(&q->mq_freeze_lock);
}
return freeze;
}
void blk_freeze_queue_start(struct request_queue *q)
{
if (__blk_freeze_queue_start(q, current))
blk_freeze_acquire_lock(q);
}
```
And in `block/blk.h:715-728`:
```c
static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
if (!q->mq_freeze_queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
```
When the owner task unfreezes the queue via `blk_mq_unfreeze_queue(q, memflags)` -> `blk_mq_unfreeze_queue_nomemrestore(q)` (`block/blk-mq.c:211-235`):
```c
bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
bool unfreeze;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
q->q_usage_counter.data->force_atomic = true;
q->mq_freeze_depth--;
WARN_ON_ONCE(q->mq_freeze_depth < 0);
if (!q->mq_freeze_depth) {
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
}
unfreeze = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
return unfreeze;
}
void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
{
if (__blk_mq_unfreeze_queue(q, false))
blk_unfreeze_release_lock(q);
}
```
Notice the bug here:
1. Inside `__blk_mq_unfreeze_queue()`, `q->mq_freeze_depth` is decremented to `0` and `q->mq_freeze_owner` is cleared to `NULL`, and then `mutex_unlock(&q->mq_freeze_lock)` is called.
2. Only **after** `q->mq_freeze_lock` is released does `blk_mq_unfreeze_queue_nomemrestore()` call `blk_unfreeze_release_lock(q)`, which inspects `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead`.
3. Because `q->mq_freeze_depth` is already `0` and `q->mq_freeze_lock` is unlocked, another thread calling `__blk_freeze_queue_start()` can immediately acquire `q->mq_freeze_lock`, see `!q->mq_freeze_depth`, and overwrite `q->mq_freeze_queue_dying` (and `q->mq_freeze_disk_dead`) in `blk_freeze_set_owner()`.
##### 2. How Device Mapper triggers this race
In the reproducer:
1. `ioctl(DM_DEV_CREATE)` creates a DM device `md` (`md->type == DM_TYPE_NONE`, with `md->disk` allocated via `blk_alloc_disk()`).
2. **Thread 1 (`syz.3.1525/11804`)** calls `ioctl(DM_TABLE_LOAD)` (`table_load()` in `drivers/md/dm-ioctl.c:1622`) with a request-based `"multipath"` target:
- `find_device(param)` looks up `md` under `_hash_lock`, increments `md->holders` (`dm_get(md)`), and drops `_hash_lock`.
- `populate_table()` parses the `"multipath"` target, setting the table type to `DM_TYPE_REQUEST_BASED`.
- Since `dm_get_md_type(md) == DM_TYPE_NONE`, `table_load()` calls `dm_setup_md_queue(md, t)` (`drivers/md/dm.c:2606`):
- `dm_mq_init_request_queue(md, t)` initializes `md->queue` as a `blk-mq` queue.
- `add_disk(md->disk)` -> `device_add_disk()` -> `add_disk_fwnode()` -> `__add_disk()` -> `blk_register_queue(md->disk)` (`block/blk-sysfs.c:991`):
```c
if (queue_is_mq(q))
elevator_set_default(q);
```
- `elevator_set_default(q)` calls `elevator_change(q, &ctx)` (`block/elevator.c:653`).
3. Concurrently, **Thread 2** calls `ioctl(DM_DEV_REMOVE)` (`dev_remove()` in `drivers/md/dm-ioctl.c:1063`):
- Under `_hash_lock`, `dm_lock_for_deletion(md, ...)` succeeds because it only checks `dm_open_count(md)` (`0`), **not** `md->holders`.
- `__hash_remove(hc)` removes `hc` from the hash table and clears `md->interface_ptr` (`dm_set_mdptr(md, NULL)`).
- `dev_remove()` drops `_hash_lock`, calls `dm_put(md)`, and calls `dm_destroy(md)` -> `__dm_destroy(md, true)` (`drivers/md/dm.c:2726`):
```c
blk_mark_disk_dead(md->disk);
...
if (wait)
while (atomic_read(&md->holders))
fsleep(1000);
```
- Notice that `__dm_destroy()` calls `blk_mark_disk_dead(md->disk)` **before** waiting for `md->holders` to drop to `0`.
##### 3. Exact Race Sequence
1. **Thread 1 (`table_load`)** enters `elevator_change()` (`block/elevator.c:668`):
```c
memflags = blk_mq_freeze_queue(q);
```
- `q->mq_freeze_depth` is `0`.
- `blk_freeze_set_owner(q, Thread_1)` sets:
- `q->mq_freeze_owner = Thread_1`
- `q->mq_freeze_owner_depth = 1`
- `q->mq_freeze_disk_dead = true` (since `QUEUE_FLAG_REGISTERED` is not set yet)
- `q->mq_freeze_queue_dying = false` (since `QUEUE_FLAG_DYING` is not set yet)
- `q->mq_freeze_depth` becomes `1`.
- `blk_freeze_acquire_lock(q)` sees `!q->mq_freeze_queue_dying == true` and calls:
```c
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
```
2. **Thread 1 (`table_load`)** finishes `elevator_switch()` and calls `blk_mq_unfreeze_queue(q, memflags)` at `block/elevator.c:683`:
- Inside `__blk_mq_unfreeze_queue(q, false)` (`block/blk-mq.c:211`):
- `q->mq_freeze_depth` is decremented from `1` to `0`.
- `blk_unfreeze_check_owner(q)` decrements `q->mq_freeze_owner_depth` to `0`, sets `q->mq_freeze_owner = NULL`, and returns `true`.
- `mutex_unlock(&q->mq_freeze_lock)` unlocks `q->mq_freeze_lock`.
3. **Thread 2 (`dev_remove`)** executes `blk_mark_disk_dead(md->disk)` (`block/genhd.c:689`):
```c
void blk_mark_disk_dead(struct gendisk *disk)
{
blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
__blk_mark_disk_dead(disk);
blk_report_disk_dead(disk, true);
}
```
- `blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue)` sets `QUEUE_FLAG_DYING` on `q`.
- `__blk_mark_disk_dead(disk)` calls `blk_queue_start_drain(disk->queue)` -> `__blk_freeze_queue_start(q, Thread_2)`.
- Right after Thread 1 unlocks `q->mq_freeze_lock` in step 2 (e.g., when woken from `q->mq_freeze_lock` wait_list during `mutex_unlock`), Thread 2 acquires `q->mq_freeze_lock`.
- Because `q->mq_freeze_depth` is `0`, `blk_freeze_set_owner(q, Thread_2)` runs and sets:
```c
q->mq_freeze_queue_dying = blk_queue_dying(q); /* true! */
```
4. **Thread 1 (`table_load`)** now executes `blk_unfreeze_release_lock(q)` (`block/blk-mq.c:233` -> `block/blk.h:722`):
```c
static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
```
Because `q->mq_freeze_queue_dying` was overwritten with `true` by Thread 2 in step 3, `!q->mq_freeze_queue_dying` evaluates to `false`, and **`rwsem_release(&q->q_lockdep_map, _RET_IP_)` is skipped**.
5. **Thread 1 (`table_load`)** finishes `dm_setup_md_queue()`, acquires `_hash_lock` in `table_load()` (`drivers/md/dm-ioctl.c:1678`), sees `hc = dm_get_mdptr(md)` is `NULL`, logs:
```
device-mapper: ioctl: device has been removed from the dev hash table.
```
cleans up `t`, drops `md->holders` (`dm_put(md)`), and returns `-ENXIO` to user space with `q->q_lockdep_map` (`&q->q_usage_counter(queue)`) still held in lockdep, triggering the warning.
---
#### How to Fix
1. **In the block layer (`block/blk-mq.c`, `block/blk.h`, `block/genhd.c`)**:
`blk_freeze_acquire_lock(q)` and `blk_unfreeze_release_lock(q)` must not read mutable per-queue `q->mq_freeze_queue_dying` / `q->mq_freeze_disk_dead` fields outside `q->mq_freeze_lock` after `q->mq_freeze_depth` has dropped to `0` (where another task starting a new freeze can overwrite them). Either:
- Perform the lockdep release (`blk_unfreeze_release_lock(q)`) / state consumption under `q->mq_freeze_lock` before `q->mq_freeze_depth` is decremented / unlocked (or pass the saved `disk_dead` and `queue_dying` booleans out of `__blk_mq_unfreeze_queue()` by value while still holding `q->mq_freeze_lock`), and similarly pass/snapshot them under `q->mq_freeze_lock` in `__blk_freeze_queue_start()`.
2. **In Device Mapper (`drivers/md/dm.c`)**:
In `__dm_destroy()`, `blk_mark_disk_dead(md->disk)` should not be called while another thread holds `md->holders` and may still be in `dm_setup_md_queue()` / `add_disk(md->disk)` initializing and registering the disk/queue (i.e., wait for `atomic_read(&md->holders)` or serialize against `md->type_lock` before marking the disk dead).
The proposed patch diff:
diff --git a/block/blk-core.c b/block/blk-core.c
index 8836c7028..fc3ab62e8 100644
--- a/block/blk-core.c
+++ b/block/blk-core.c
@@ -324,20 +324,21 @@ void blk_put_queue(struct request_queue *q)
}
EXPORT_SYMBOL(blk_put_queue);
-bool blk_queue_start_drain(struct request_queue *q)
+unsigned int blk_queue_start_drain(struct request_queue *q)
{
/*
* When queue DYING flag is set, we need to block new req
* entering queue, so we call blk_freeze_queue_start() to
* prevent I/O from crossing blk_queue_enter().
*/
- bool freeze = __blk_freeze_queue_start(q, current);
+ unsigned int lock_mask = __blk_freeze_queue_start(q,
+ blk_queue_dying(q) ? NULL : current);
if (queue_is_mq(q))
blk_mq_wake_waiters(q);
/* Make blk_queue_enter() reexamine the DYING flag. */
wake_up_all(&q->mq_freeze_wq);
- return freeze;
+ return lock_mask;
}
/**
diff --git a/block/blk-mq.c b/block/blk-mq.c
index d9ab295be..3f64a59e5 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -113,60 +113,64 @@ void blk_mq_in_driver_rw(struct block_device *part, unsigned int inflight[2])
}
#ifdef CONFIG_LOCKDEP
-static bool blk_freeze_set_owner(struct request_queue *q,
- struct task_struct *owner)
+static unsigned int blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
{
+ unsigned int lock_mask = 0;
+
if (!owner)
- return false;
+ return 0;
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
- q->mq_freeze_disk_dead = !q->disk ||
- test_bit(GD_DEAD, &q->disk->state) ||
- !blk_queue_registered(q);
- q->mq_freeze_queue_dying = blk_queue_dying(q);
- return true;
+ if (q->disk && !test_bit(GD_DEAD, &q->disk->state) &&
+ blk_queue_registered(q))
+ lock_mask |= BLK_FREEZE_LOCK_IO;
+ if (!blk_queue_dying(q))
+ lock_mask |= BLK_FREEZE_LOCK_QUEUE;
+ q->mq_freeze_lock_mask = lock_mask;
+ return lock_mask;
}
if (owner == q->mq_freeze_owner)
q->mq_freeze_owner_depth += 1;
- return false;
+ return 0;
}
/* verify the last unfreeze in owner context */
-static bool blk_unfreeze_check_owner(struct request_queue *q)
+static unsigned int blk_unfreeze_check_owner(struct request_queue *q)
{
if (q->mq_freeze_owner != current)
- return false;
+ return 0;
if (--q->mq_freeze_owner_depth == 0) {
q->mq_freeze_owner = NULL;
- return true;
+ return q->mq_freeze_lock_mask;
}
- return false;
+ return 0;
}
#else
-static bool blk_freeze_set_owner(struct request_queue *q,
- struct task_struct *owner)
+static unsigned int blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
{
- return false;
+ return 0;
}
-static bool blk_unfreeze_check_owner(struct request_queue *q)
+static unsigned int blk_unfreeze_check_owner(struct request_queue *q)
{
- return false;
+ return 0;
}
#endif
-bool __blk_freeze_queue_start(struct request_queue *q,
- struct task_struct *owner)
+unsigned int __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner)
{
- bool freeze;
+ unsigned int lock_mask;
mutex_lock(&q->mq_freeze_lock);
- freeze = blk_freeze_set_owner(q, owner);
+ lock_mask = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
@@ -176,13 +180,14 @@ bool __blk_freeze_queue_start(struct request_queue *q,
mutex_unlock(&q->mq_freeze_lock);
}
- return freeze;
+ return lock_mask;
}
void blk_freeze_queue_start(struct request_queue *q)
{
- if (__blk_freeze_queue_start(q, current))
- blk_freeze_acquire_lock(q);
+ unsigned int lock_mask = __blk_freeze_queue_start(q, current);
+
+ blk_freeze_acquire_lock(q, lock_mask);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -208,9 +213,9 @@ void blk_mq_freeze_queue_nomemsave(struct request_queue *q)
}
EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_nomemsave);
-bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
+unsigned int __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
- bool unfreeze;
+ unsigned int lock_mask;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
@@ -221,16 +226,17 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
}
- unfreeze = blk_unfreeze_check_owner(q);
+ lock_mask = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
- return unfreeze;
+ return lock_mask;
}
void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
{
- if (__blk_mq_unfreeze_queue(q, false))
- blk_unfreeze_release_lock(q);
+ unsigned int lock_mask = __blk_mq_unfreeze_queue(q, false);
+
+ blk_unfreeze_release_lock(q, lock_mask);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_nomemrestore);
diff --git a/block/blk.h b/block/blk.h
index ed2172472..2c4d5ee7d 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -55,10 +55,11 @@ const char *blk_status_to_tag(blk_status_t status);
blk_status_t tag_to_blk_status(const char *tag);
enum req_op str_to_blk_op(const char *op);
-bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
-bool blk_queue_start_drain(struct request_queue *q);
-bool __blk_freeze_queue_start(struct request_queue *q,
- struct task_struct *owner);
+unsigned int __blk_mq_unfreeze_queue(struct request_queue *q,
+ bool force_atomic);
+unsigned int blk_queue_start_drain(struct request_queue *q);
+unsigned int __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner);
int __bio_queue_enter(struct request_queue *q, struct bio *bio);
void submit_bio_noacct_nocheck(struct bio *bio, bool split);
int bio_submit_or_kill(struct bio *bio, unsigned int flags);
@@ -777,27 +778,36 @@ blk_status_t bio_integrity_verify(struct bio *bio,
void blk_integrity_prepare(struct request *rq);
void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
+enum {
+ BLK_FREEZE_LOCK_IO = (1 << 0),
+ BLK_FREEZE_LOCK_QUEUE = (1 << 1),
+};
+
#ifdef CONFIG_LOCKDEP
-static inline void blk_freeze_acquire_lock(struct request_queue *q)
+static inline void blk_freeze_acquire_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
- if (!q->mq_freeze_disk_dead)
+ if (lock_mask & BLK_FREEZE_LOCK_IO)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
- if (!q->mq_freeze_queue_dying)
+ if (lock_mask & BLK_FREEZE_LOCK_QUEUE)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q)
+static inline void blk_unfreeze_release_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
- if (!q->mq_freeze_queue_dying)
+ if (lock_mask & BLK_FREEZE_LOCK_QUEUE)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
- if (!q->mq_freeze_disk_dead)
+ if (lock_mask & BLK_FREEZE_LOCK_IO)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
#else
-static inline void blk_freeze_acquire_lock(struct request_queue *q)
+static inline void blk_freeze_acquire_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q)
+static inline void blk_unfreeze_release_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
}
#endif
diff --git a/block/genhd.c b/block/genhd.c
index 10ca8b4d6..e73349b74 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -657,13 +657,13 @@ static void blk_report_disk_dead(struct gendisk *disk, bool surprise)
rcu_read_unlock();
}
-static bool __blk_mark_disk_dead(struct gendisk *disk)
+static unsigned int __blk_mark_disk_dead(struct gendisk *disk)
{
/*
* Fail any new I/O.
*/
if (test_and_set_bit(GD_DEAD, &disk->state))
- return false;
+ return 0;
if (test_bit(GD_OWNS_QUEUE, &disk->state))
blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
@@ -699,7 +699,7 @@ static void __del_gendisk(struct gendisk *disk)
struct request_queue *q = disk->queue;
struct block_device *part;
unsigned long idx;
- bool start_drain;
+ unsigned int lock_mask;
might_sleep();
@@ -727,9 +727,8 @@ static void __del_gendisk(struct gendisk *disk)
* Drop all partitions now that the disk is marked dead.
*/
mutex_lock(&disk->open_mutex);
- start_drain = __blk_mark_disk_dead(disk);
- if (start_drain)
- blk_freeze_acquire_lock(q);
+ lock_mask = __blk_mark_disk_dead(disk);
+ blk_freeze_acquire_lock(q, lock_mask);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
@@ -777,8 +776,7 @@ static void __del_gendisk(struct gendisk *disk)
else if (queue_is_mq(q))
blk_mq_exit_queue(q);
- if (start_drain)
- blk_unfreeze_release_lock(q);
+ blk_unfreeze_release_lock(q, lock_mask);
}
static void disable_elv_switch(struct request_queue *q)
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 0c2010230..32a8e93c4 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -637,11 +637,10 @@ struct request_queue {
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
/*
- * Records disk & queue state in current context, used in unfreeze
+ * Records lockdep locks acquired in owner context, used in unfreeze
* queue
*/
- bool mq_freeze_disk_dead;
- bool mq_freeze_queue_dying;
+ unsigned int mq_freeze_lock_mask;
#endif
wait_queue_head_t mq_freeze_wq;
/*
Review this patch diff against the crash report, root cause explanation, and kernel architectural design guidelines.
|
| 526/5 |
2026/11/03 22:36 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 14669
output: 215
thoughts: 128
Thoughts: Okay, let's dive into this proposed patch. **Deep Dive into Block Layer Concurrency and Deadlock Prevention**
Alright, I need to methodically dissect this. First, I'm going to meticulously analyze the patch itself, the crash report (if we have one, otherwise let's imagine the likely scenario), the root cause explanation (assuming there is a good one, otherwise, I'll need to reconstruct it), and the surrounding code in the kernel's block layer. It's time to get surgical.
The initial step? A comprehensive audit using my favorite tools. I'll need to comb through all instances of `blk_freeze_acquire_lock`, `blk_unfreeze_release_lock`, `blk_queue_start_drain`, `__blk_freeze_queue_start`, `__blk_mq_unfreeze_queue`, `mq_freeze_disk_dead`, `mq_freeze_queue_dying`, `__blk_mark_disk_dead`, and `blk_mark_disk_dead`. Any and all related functions and macros within the relevant areas are going to need a hard look. I'm going to look for any hidden dependencies, subtle interactions, and potential race conditions. This is where the devil lives, and I need to smoke him out.
|
| 527/5 |
2026/11/03 22:36 |
tool |
codesearch-find-references |
0m
Args: map[IncludeSnippetLines:30 Name:blk_freeze_acquire_lock]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__del_gendisk SourceFile:block/genhd.c SourceLine:732 SourceSnippet: 702: bool start_drain;
703:
704: might_sleep();
705:
706: if (WARN_ON_ONCE(!disk_live(disk) && !(disk->flags & GENHD_FL_HIDDEN)))
707: return;
708:
709: disk_del_events(disk);
710:
711: /*
712: * Prevent new openers by unlinked the bdev inode.
713: */
714: mutex_lock(&disk->open_mutex);
715: xa_for_each(&disk->part_tbl, idx, part)
716: bdev_unhash(part);
717: mutex_unlock(&disk->open_mutex);
718:
719: /*
720: * Tell the file system to write back all dirty data and shut down if
721: * it hasn't been notified earlier.
722: */
723: if (!test_bit(GD_DEAD, &disk->state))
724: blk_report_disk_dead(disk, false);
725:
726: /*
727: * Drop all partitions now that the disk is marked dead.
728: */
729: mutex_lock(&disk->open_mutex);
730: start_drain = __blk_mark_disk_dead(disk);
731: if (start_drain)
732: blk_freeze_acquire_lock(q);
733: xa_for_each_start(&disk->part_tbl, idx, part, 1)
734: drop_partition(part);
735: mutex_unlock(&disk->open_mutex);
736:
737: if (!(disk->flags & GENHD_FL_HIDDEN)) {
738: sysfs_remove_link(&disk_to_dev(disk)->kobj, "bdi");
739:
740: /*
741: * Unregister bdi before releasing device numbers (as they can
742: * get reused and we'd get clashes in sysfs).
743: */
744: bdi_unregister(disk->bdi);
745: }
746:
747: blk_unregister_queue(disk);
748:
749: kobject_put(disk->part0->bd_holder_dir);
750: kobject_put(disk->slave_dir);
751: disk->slave_dir = NULL;
752:
753: part_stat_set_all(disk->part0, 0);
754: disk->part0->bd_stamp = 0;
755: sysfs_remove_link(block_depr, dev_name(disk_to_dev(disk)));
756: pm_runtime_set_memalloc_noio(disk_to_dev(disk), false);
757: device_del(disk_to_dev(disk));
758:
759: blk_mq_freeze_queue_wait(q);
760:
761: blk_throtl_cancel_bios(disk);
762:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_freeze_queue_start SourceFile:block/blk-mq.c SourceLine:185 SourceSnippet: 182: void blk_freeze_queue_start(struct request_queue *q)
183: {
184: if (__blk_freeze_queue_start(q, current))
185: blk_freeze_acquire_lock(q);
186: }
]] TruncatedOutput:false]
|
| 528/5 |
2026/11/03 22:36 |
tool |
codesearch-find-references |
0m
Args: map[IncludeSnippetLines:30 Name:blk_unfreeze_release_lock]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__del_gendisk SourceFile:block/genhd.c SourceLine:781 SourceSnippet: 751: disk->slave_dir = NULL;
752:
753: part_stat_set_all(disk->part0, 0);
754: disk->part0->bd_stamp = 0;
755: sysfs_remove_link(block_depr, dev_name(disk_to_dev(disk)));
756: pm_runtime_set_memalloc_noio(disk_to_dev(disk), false);
757: device_del(disk_to_dev(disk));
758:
759: blk_mq_freeze_queue_wait(q);
760:
761: blk_throtl_cancel_bios(disk);
762:
763: blk_sync_queue(q);
764: blk_flush_integrity();
765:
766: if (queue_is_mq(q))
767: blk_mq_cancel_work_sync(q);
768:
769: rq_qos_exit(q);
770:
771: /*
772: * If the disk does not own the queue, allow using passthrough requests
773: * again. Else leave the queue frozen to fail all I/O.
774: */
775: if (!test_bit(GD_OWNS_QUEUE, &disk->state))
776: __blk_mq_unfreeze_queue(q, true);
777: else if (queue_is_mq(q))
778: blk_mq_exit_queue(q);
779:
780: if (start_drain)
781: blk_unfreeze_release_lock(q);
782: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_mq_unfreeze_queue_nomemrestore SourceFile:block/blk-mq.c SourceLine:233 SourceSnippet: 230: void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
231: {
232: if (__blk_mq_unfreeze_queue(q, false))
233: blk_unfreeze_release_lock(q);
234: }
]] TruncatedOutput:false]
|
| 529/5 |
2026/11/03 22:36 |
tool |
codesearch-find-references |
0m
Args: map[IncludeSnippetLines:30 Name:blk_queue_start_drain]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__blk_mark_disk_dead SourceFile:block/genhd.c SourceLine:679 SourceSnippet: 660: static bool __blk_mark_disk_dead(struct gendisk *disk)
661: {
662: /*
663: * Fail any new I/O.
664: */
665: if (test_and_set_bit(GD_DEAD, &disk->state))
666: return false;
667:
668: if (test_bit(GD_OWNS_QUEUE, &disk->state))
669: blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
670:
671: /*
672: * Stop buffered writers from dirtying pages that can't be written out.
673: */
674: set_capacity(disk, 0);
675:
676: /*
677: * Prevent new I/O from crossing bio_queue_enter().
678: */
679: return blk_queue_start_drain(disk->queue);
680: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_mq_destroy_queue SourceFile:block/blk-mq.c SourceLine:4491 SourceSnippet:4473: /**
4474: * blk_mq_destroy_queue - shutdown a request queue
4475: * @q: request queue to shutdown
4476: *
4477: * This shuts down a request queue allocated by blk_mq_alloc_queue(). All future
4478: * requests will be failed with -ENODEV. The caller is responsible for dropping
4479: * the reference from blk_mq_alloc_queue() by calling blk_put_queue().
4480: *
4481: * Context: can sleep
4482: */
4483: void blk_mq_destroy_queue(struct request_queue *q)
4484: {
4485: WARN_ON_ONCE(!queue_is_mq(q));
4486: WARN_ON_ONCE(blk_queue_registered(q));
4487:
4488: might_sleep();
4489:
4490: blk_queue_flag_set(QUEUE_FLAG_DYING, q);
4491: blk_queue_start_drain(q);
4492: blk_mq_freeze_queue_wait(q);
4493:
4494: blk_sync_queue(q);
4495: blk_mq_cancel_work_sync(q);
4496: blk_mq_exit_queue(q);
4497: }
]] TruncatedOutput:false]
|
| 530/5 |
2026/11/03 22:36 |
tool |
codesearch-find-references |
0m
Args: map[IncludeSnippetLines:30 Name:__blk_freeze_queue_start]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_freeze_queue_start SourceFile:block/blk-mq.c SourceLine:184 SourceSnippet: 182: void blk_freeze_queue_start(struct request_queue *q)
183: {
184: if (__blk_freeze_queue_start(q, current))
185: blk_freeze_acquire_lock(q);
186: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_freeze_queue_start_non_owner SourceFile:block/blk-mq.c SourceLine:246 SourceSnippet: 237: /*
238: * non_owner variant of blk_freeze_queue_start
239: *
240: * Unlike blk_freeze_queue_start, the queue doesn't need to be unfrozen
241: * by the same task. This is fragile and should not be used if at all
242: * possible.
243: */
244: void blk_freeze_queue_start_non_owner(struct request_queue *q)
245: {
246: __blk_freeze_queue_start(q, NULL);
247: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_queue_start_drain SourceFile:block/blk-core.c SourceLine:334 SourceSnippet: 327: bool blk_queue_start_drain(struct request_queue *q)
328: {
329: /*
330: * When queue DYING flag is set, we need to block new req
331: * entering queue, so we call blk_freeze_queue_start() to
332: * prevent I/O from crossing blk_queue_enter().
333: */
334: bool freeze = __blk_freeze_queue_start(q, current);
335: if (queue_is_mq(q))
336: blk_mq_wake_waiters(q);
337: /* Make blk_queue_enter() reexamine the DYING flag. */
338: wake_up_all(&q->mq_freeze_wq);
339:
340: return freeze;
341: }
]] TruncatedOutput:false]
|
| 531/5 |
2026/11/03 22:37 |
tool |
codesearch-find-references |
0m
Args: map[IncludeSnippetLines:30 Name:__blk_mq_unfreeze_queue]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__del_gendisk SourceFile:block/genhd.c SourceLine:776 SourceSnippet: 746:
747: blk_unregister_queue(disk);
748:
749: kobject_put(disk->part0->bd_holder_dir);
750: kobject_put(disk->slave_dir);
751: disk->slave_dir = NULL;
752:
753: part_stat_set_all(disk->part0, 0);
754: disk->part0->bd_stamp = 0;
755: sysfs_remove_link(block_depr, dev_name(disk_to_dev(disk)));
756: pm_runtime_set_memalloc_noio(disk_to_dev(disk), false);
757: device_del(disk_to_dev(disk));
758:
759: blk_mq_freeze_queue_wait(q);
760:
761: blk_throtl_cancel_bios(disk);
762:
763: blk_sync_queue(q);
764: blk_flush_integrity();
765:
766: if (queue_is_mq(q))
767: blk_mq_cancel_work_sync(q);
768:
769: rq_qos_exit(q);
770:
771: /*
772: * If the disk does not own the queue, allow using passthrough requests
773: * again. Else leave the queue frozen to fail all I/O.
774: */
775: if (!test_bit(GD_OWNS_QUEUE, &disk->state))
776: __blk_mq_unfreeze_queue(q, true);
777: else if (queue_is_mq(q))
778: blk_mq_exit_queue(q);
779:
780: if (start_drain)
781: blk_unfreeze_release_lock(q);
782: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_mq_unfreeze_queue_nomemrestore SourceFile:block/blk-mq.c SourceLine:232 SourceSnippet: 230: void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
231: {
232: if (__blk_mq_unfreeze_queue(q, false))
233: blk_unfreeze_release_lock(q);
234: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:blk_mq_unfreeze_queue_non_owner SourceFile:block/blk-mq.c SourceLine:253 SourceSnippet: 250: /* non_owner variant of blk_mq_unfreeze_queue */
251: void blk_mq_unfreeze_queue_non_owner(struct request_queue *q)
252: {
253: __blk_mq_unfreeze_queue(q, false);
254: }
]] TruncatedOutput:false]
|
| 532/5 |
2026/11/03 22:37 |
tool |
git-log |
0m
Args: map[CodeRegexp:mq_freeze_disk_dead Count:5 PathPrefix:block/]
Results: map[Output:6f491a8d4b92 block: track disk DEAD state automatically for modeling queue freeze lockdep
]
|
| 533/5 |
2026/11/03 22:37 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 19309
output: 100
thoughts: 60
Thoughts: Here's my analysis of what I'm looking at, from a low-level perspective:
**Diving Deep into Disk Death Handling**
Alright, let's get down to brass tacks. I need to understand how the system reacts to a potential disk failure, and that means zeroing in on the commit `6f491a8d4b92` and its neighbors. Specifically, I want to trace the evolution of the code related to marking a disk as "dead." I'm expecting this commit to be significant in that aspect and related to it.
To do this properly, I'm going straight to the source. I'm focusing on the `block/genhd.c` file. This is the heart of generic hard drive management, and I anticipate that the functions `__blk_mark_disk_dead` and `blk_mark_disk_dead` are central to this process. I'm going to carefully read the code surrounding those function calls to see how the system is designed to react to this unfortunate event. I want to understand:
* What triggers the marking?
* What data structures are being updated?
* What subsequent actions are initiated because of this "disk death" declaration?
* What other pieces of the code does this affect?
I'm expecting to see things like error handling, block device state transitions, and likely some I/O queue management involved. Time to go hunting for the root cause and understand the recovery procedure. I'm going to look at the surrounding code to determine how this action fits into the overall scheme of things.
|
| 534/5 |
2026/11/03 22:37 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 6f491a8d4b92d1a840fd9209cba783c84437d0b7
Author: Ming Lei <ming.lei@redhat.com>
Date: Wed Nov 27 21:51:28 2024 +0800
block: track disk DEAD state automatically for modeling queue freeze lockdep
Now we only verify the outmost freeze & unfreeze in current context in case
that !q->mq_freeze_depth, so it is reliable to save disk DEAD state when
we want to lock the freeze queue since the state is one per-task variable
now.
Doing this way can kill lots of false positive when freeze queue is
called before adding disk[1].
[1] https://lore.kernel.org/linux-block/6741f6b2.050a0220.1cc393.0017.GAE@google.com/
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241127135133.3952153-3-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 60f457f62913..0c6a319fb936 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -131,6 +131,9 @@ static bool blk_freeze_set_owner(struct request_queue *q,
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
+ q->mq_freeze_disk_dead = !q->disk ||
+ test_bit(GD_DEAD, &q->disk->state) ||
+ !blk_queue_registered(q);
return true;
}
@@ -187,7 +190,7 @@ bool __blk_freeze_queue_start(struct request_queue *q,
void blk_freeze_queue_start(struct request_queue *q)
{
if (__blk_freeze_queue_start(q, current))
- blk_freeze_acquire_lock(q, false, false);
+ blk_freeze_acquire_lock(q, false);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -235,7 +238,7 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
void blk_mq_unfreeze_queue(struct request_queue *q)
{
if (__blk_mq_unfreeze_queue(q, false))
- blk_unfreeze_release_lock(q, false, false);
+ blk_unfreeze_release_lock(q, false);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
diff --git a/block/blk.h b/block/blk.h
index 2c26abf505b8..8708168d50e4 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -720,22 +720,29 @@ void blk_integrity_verify(struct bio *bio);
void blk_integrity_prepare(struct request *rq);
void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
-static inline void blk_freeze_acquire_lock(struct request_queue *q, bool
- disk_dead, bool queue_dying)
+#ifdef CONFIG_LOCKDEP
+static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
{
- if (!disk_dead)
+ if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
if (!queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q, bool
- disk_dead, bool queue_dying)
+static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
{
if (!queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
- if (!disk_dead)
+ if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
+#else
+static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
+{
+}
+static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
+{
+}
+#endif
#endif /* BLK_INTERNAL_H */
diff --git a/block/elevator.c b/block/elevator.c
index 7c3ba80e5ff4..ca0a74369f1c 100644
--- a/block/elevator.c
+++ b/block/elevator.c
@@ -602,14 +602,14 @@ void elevator_init_mq(struct request_queue *q)
* Disk isn't added yet, so verifying queue lock only manually.
*/
blk_freeze_queue_start_non_owner(q);
- blk_freeze_acquire_lock(q, true, false);
+ blk_freeze_acquire_lock(q, false);
blk_mq_freeze_queue_wait(q);
blk_mq_cancel_work_sync(q);
err = blk_mq_init_sched(q, e);
- blk_unfreeze_release_lock(q, true, false);
+ blk_unfreeze_release_lock(q, false);
blk_mq_unfreeze_queue_non_owner(q);
if (err) {
diff --git a/block/genhd.c b/block/genhd.c
index 79230c109fca..59ac299909b3 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -692,7 +692,7 @@ void del_gendisk(struct gendisk *disk)
start_drain = __blk_mark_disk_dead(disk);
queue_dying = blk_queue_dying(q);
if (start_drain)
- blk_freeze_acquire_lock(q, true, queue_dying);
+ blk_freeze_acquire_lock(q, queue_dying);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
@@ -748,7 +748,7 @@ void del_gendisk(struct gendisk *disk)
blk_mq_exit_queue(q);
if (start_drain)
- blk_unfreeze_release_lock(q, true, queue_dying);
+ blk_unfreeze_release_lock(q, queue_dying);
}
EXPORT_SYMBOL(del_gendisk);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 378d3a1a22fc..522cf8eef66c 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -581,6 +581,8 @@ struct request_queue {
#ifdef CONFIG_LOCKDEP
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
+ /* Records disk state in current context, used in unfreeze queue */
+ bool mq_freeze_disk_dead;
#endif
wait_queue_head_t mq_freeze_wq;
/*
]
|
| 535/5 |
2026/11/03 22:37 |
tool |
read-file |
0m
Args: map[File:block/genhd.c FirstLine:655 LineCount:135]
Results: map[Contents: 655: rcu_read_lock();
656: }
657: rcu_read_unlock();
658: }
659:
660: static bool __blk_mark_disk_dead(struct gendisk *disk)
661: {
662: /*
663: * Fail any new I/O.
664: */
665: if (test_and_set_bit(GD_DEAD, &disk->state))
666: return false;
667:
668: if (test_bit(GD_OWNS_QUEUE, &disk->state))
669: blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
670:
671: /*
672: * Stop buffered writers from dirtying pages that can't be written out.
673: */
674: set_capacity(disk, 0);
675:
676: /*
677: * Prevent new I/O from crossing bio_queue_enter().
678: */
679: return blk_queue_start_drain(disk->queue);
680: }
681:
682: /**
683: * blk_mark_disk_dead - mark a disk as dead
684: * @disk: disk to mark as dead
685: *
686: * Mark as disk as dead (e.g. surprise removed) and don't accept any new I/O
687: * to this disk.
688: */
689: void blk_mark_disk_dead(struct gendisk *disk)
690: {
691: blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
692: __blk_mark_disk_dead(disk);
693: blk_report_disk_dead(disk, true);
694: }
695: EXPORT_SYMBOL_GPL(blk_mark_disk_dead);
696:
697: static void __del_gendisk(struct gendisk *disk)
698: {
699: struct request_queue *q = disk->queue;
700: struct block_device *part;
701: unsigned long idx;
702: bool start_drain;
703:
704: might_sleep();
705:
706: if (WARN_ON_ONCE(!disk_live(disk) && !(disk->flags & GENHD_FL_HIDDEN)))
707: return;
708:
709: disk_del_events(disk);
710:
711: /*
712: * Prevent new openers by unlinked the bdev inode.
713: */
714: mutex_lock(&disk->open_mutex);
715: xa_for_each(&disk->part_tbl, idx, part)
716: bdev_unhash(part);
717: mutex_unlock(&disk->open_mutex);
718:
719: /*
720: * Tell the file system to write back all dirty data and shut down if
721: * it hasn't been notified earlier.
722: */
723: if (!test_bit(GD_DEAD, &disk->state))
724: blk_report_disk_dead(disk, false);
725:
726: /*
727: * Drop all partitions now that the disk is marked dead.
728: */
729: mutex_lock(&disk->open_mutex);
730: start_drain = __blk_mark_disk_dead(disk);
731: if (start_drain)
732: blk_freeze_acquire_lock(q);
733: xa_for_each_start(&disk->part_tbl, idx, part, 1)
734: drop_partition(part);
735: mutex_unlock(&disk->open_mutex);
736:
737: if (!(disk->flags & GENHD_FL_HIDDEN)) {
738: sysfs_remove_link(&disk_to_dev(disk)->kobj, "bdi");
739:
740: /*
741: * Unregister bdi before releasing device numbers (as they can
742: * get reused and we'd get clashes in sysfs).
743: */
744: bdi_unregister(disk->bdi);
745: }
746:
747: blk_unregister_queue(disk);
748:
749: kobject_put(disk->part0->bd_holder_dir);
750: kobject_put(disk->slave_dir);
751: disk->slave_dir = NULL;
752:
753: part_stat_set_all(disk->part0, 0);
754: disk->part0->bd_stamp = 0;
]
|
| 536/5 |
2026/11/03 22:37 |
tool |
git-log |
0m
Args: map[Count:10 PathPrefix:block/blk-mq.c]
Results: map[Output:4fcc499ea9bc blk-mq: set up a queue under tag_list_lock
89a2381482d8 blk-mq: exit the hctxs of a queue under tag_list_lock
71ec3c7d6db8 blk-mq: quiesce a queue that joins a quiesced tag set
0db9f8968a89 blk-mq: don't forget a timer the driver has restarted
9531230ee1fc blk-mq: don't bring back flags of a completed request
620cfc7a6642 blk-mq: keep sharing tags fairly after a queue update
24974185999f blk-mq: don't trust the cookie in blk_mq_poll()
afc1de47a7ab blk-mq: clear stale inactive flag on hctx reuse
5f702d4bd61b blk-mq: drop the tag_set argument from blk_mq_free_rq_map/tags
e1c51edd6a57 blk-mq: share one tags_srcu instance across all tag sets
]
|
| 537/5 |
2026/11/03 22:37 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 23319
output: 79
thoughts: 21
Thoughts: Okay, let's dive into this. Here's my thought process on this:
**Digging Deeper into the `mq_freeze_queue_dying` Commit**
Alright, I see this function, `mq_freeze_queue_dying`, and it seems significant enough to warrant a closer look. I'm already pretty familiar with message queues, the intricacies of their management, and potential race conditions, but this is new. Given the context, I need to understand why this was introduced. So, my immediate instinct is to pinpoint the exact commit where this function was added. That commit should provide the crucial context: the problem it was designed to solve, the reasoning behind the solution, and any potential side effects considered by the developer. By examining that specific change, I expect to understand the core motivation and the architectural changes involved. This level of detail is critical to a full understanding. Let's see what that commit holds.
|
| 538/5 |
2026/11/03 22:38 |
tool |
git-log |
0m
Args: map[CodeRegexp:mq_freeze_queue_dying Count:5 PathPrefix:block/]
Results: map[Output:f6661b1d0525 block: track queue dying state automatically for modeling queue freeze lockdep
]
|
| 539/5 |
2026/11/03 22:38 |
tool |
git-log |
0m
Args: map[CodeRegexp:blk_freeze_set_owner Count:5 PathPrefix:block/]
Results: map[Output:6a78699838a0 block: always verify unfreeze lock on the owner task
]
|
| 540/5 |
2026/11/03 22:38 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 23503
output: 62
thoughts: 34
Thoughts: Okay, here's my take on those commits, framed as my internal thought process, assuming I'm an expert in this field:
**Diving into the Details: Commit Inspection**
Alright, time to get my hands dirty. Let's see what these commits, `f6661b1d0525` and `6a78699838a0`, are all about. Based on the hashes alone, I'm expecting some specific work, hopefully related to [insert your field here - e.g., "the recent performance regressions I flagged," or "the data pipeline refactor we discussed," or "the security vulnerabilities identified in the audit"]. Just glancing at the commit message won't tell me everything, of course, so I'll be digging deep. I'm going to start by pulling up the diffs, focusing on the context changes. I'll need to look carefully at the context of those two commit hashes. Depending on the changes, I'll need to identify any performance bottlenecks, potential errors, or security vulnerabilities as well. Any testing needed to ensure correct behavior post-commit will be identified as well.
|
| 541/5 |
2026/11/03 22:38 |
tool |
git-show |
0m
Args:
Results: map[Output:commit f6661b1d0525f3764596a1b65eeed9e75aecafa7
Author: Ming Lei <ming.lei@redhat.com>
Date: Wed Nov 27 21:51:30 2024 +0800
block: track queue dying state automatically for modeling queue freeze lockdep
Now we only verify the outmost freeze & unfreeze in current context in case
that !q->mq_freeze_depth, so it is reliable to save queue lying state when
we want to lock the freeze queue since the state is one per-task variable
now.
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241127135133.3952153-5-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 0c6a319fb936..fca2ec64a06b 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -134,6 +134,7 @@ static bool blk_freeze_set_owner(struct request_queue *q,
q->mq_freeze_disk_dead = !q->disk ||
test_bit(GD_DEAD, &q->disk->state) ||
!blk_queue_registered(q);
+ q->mq_freeze_queue_dying = blk_queue_dying(q);
return true;
}
@@ -190,7 +191,7 @@ bool __blk_freeze_queue_start(struct request_queue *q,
void blk_freeze_queue_start(struct request_queue *q)
{
if (__blk_freeze_queue_start(q, current))
- blk_freeze_acquire_lock(q, false);
+ blk_freeze_acquire_lock(q);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -238,7 +239,7 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
void blk_mq_unfreeze_queue(struct request_queue *q)
{
if (__blk_mq_unfreeze_queue(q, false))
- blk_unfreeze_release_lock(q, false);
+ blk_unfreeze_release_lock(q);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
diff --git a/block/blk.h b/block/blk.h
index 8708168d50e4..cbf6a676ffe9 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -721,26 +721,26 @@ void blk_integrity_prepare(struct request *rq);
void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
#ifdef CONFIG_LOCKDEP
-static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
- if (!queue_dying)
+ if (!q->mq_freeze_queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
- if (!queue_dying)
+ if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
#else
-static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
}
#endif
diff --git a/block/genhd.c b/block/genhd.c
index 59ac299909b3..5678194b6b1a 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -661,7 +661,7 @@ void del_gendisk(struct gendisk *disk)
struct request_queue *q = disk->queue;
struct block_device *part;
unsigned long idx;
- bool start_drain, queue_dying;
+ bool start_drain;
might_sleep();
@@ -690,9 +690,8 @@ void del_gendisk(struct gendisk *disk)
*/
mutex_lock(&disk->open_mutex);
start_drain = __blk_mark_disk_dead(disk);
- queue_dying = blk_queue_dying(q);
if (start_drain)
- blk_freeze_acquire_lock(q, queue_dying);
+ blk_freeze_acquire_lock(q);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
@@ -748,7 +747,7 @@ void del_gendisk(struct gendisk *disk)
blk_mq_exit_queue(q);
if (start_drain)
- blk_unfreeze_release_lock(q, queue_dying);
+ blk_unfreeze_release_lock(q);
}
EXPORT_SYMBOL(del_gendisk);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 522cf8eef66c..5d40af2ef971 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -581,8 +581,12 @@ struct request_queue {
#ifdef CONFIG_LOCKDEP
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
- /* Records disk state in current context, used in unfreeze queue */
+ /*
+ * Records disk & queue state in current context, used in unfreeze
+ * queue
+ */
bool mq_freeze_disk_dead;
+ bool mq_freeze_queue_dying;
#endif
wait_queue_head_t mq_freeze_wq;
/*
]
|
| 542/5 |
2026/11/03 22:38 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 6a78699838a0ddeed3620ddf50c1521f1fe1e811
Author: Ming Lei <ming.lei@redhat.com>
Date: Thu Oct 31 21:37:19 2024 +0800
block: always verify unfreeze lock on the owner task
commit f1be1788a32e ("block: model freeze & enter queue as lock for
supporting lockdep") tries to apply lockdep for verifying freeze &
unfreeze. However, the verification is only done the outmost freeze and
unfreeze. This way is actually not correct because q->mq_freeze_depth
still may drop to zero on other task instead of the freeze owner task.
Fix this issue by always verifying the last unfreeze lock on the owner
task context, and make sure both the outmost freeze & unfreeze are
verified in the current task.
Fixes: f1be1788a32e ("block: model freeze & enter queue as lock for supporting lockdep")
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241031133723.303835-4-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-core.c b/block/blk-core.c
index 09d10bb95fda..4f791a3114a1 100644
--- a/block/blk-core.c
+++ b/block/blk-core.c
@@ -287,7 +287,7 @@ bool blk_queue_start_drain(struct request_queue *q)
* entering queue, so we call blk_freeze_queue_start() to
* prevent I/O from crossing blk_queue_enter().
*/
- bool freeze = __blk_freeze_queue_start(q);
+ bool freeze = __blk_freeze_queue_start(q, current);
if (queue_is_mq(q))
blk_mq_wake_waiters(q);
/* Make blk_queue_enter() reexamine the DYING flag. */
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 5f4496220432..5e240a4b6be0 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -120,20 +120,66 @@ void blk_mq_in_flight_rw(struct request_queue *q, struct block_device *part,
inflight[1] = mi.inflight[1];
}
-bool __blk_freeze_queue_start(struct request_queue *q)
+#ifdef CONFIG_LOCKDEP
+static bool blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
{
- int freeze;
+ if (!owner)
+ return false;
+
+ if (!q->mq_freeze_depth) {
+ q->mq_freeze_owner = owner;
+ q->mq_freeze_owner_depth = 1;
+ return true;
+ }
+
+ if (owner == q->mq_freeze_owner)
+ q->mq_freeze_owner_depth += 1;
+ return false;
+}
+
+/* verify the last unfreeze in owner context */
+static bool blk_unfreeze_check_owner(struct request_queue *q)
+{
+ if (!q->mq_freeze_owner)
+ return false;
+ if (q->mq_freeze_owner != current)
+ return false;
+ if (--q->mq_freeze_owner_depth == 0) {
+ q->mq_freeze_owner = NULL;
+ return true;
+ }
+ return false;
+}
+
+#else
+
+static bool blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
+{
+ return false;
+}
+
+static bool blk_unfreeze_check_owner(struct request_queue *q)
+{
+ return false;
+}
+#endif
+
+bool __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner)
+{
+ bool freeze;
mutex_lock(&q->mq_freeze_lock);
+ freeze = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
if (queue_is_mq(q))
blk_mq_run_hw_queues(q, false);
- freeze = true;
} else {
mutex_unlock(&q->mq_freeze_lock);
- freeze = false;
}
return freeze;
@@ -141,7 +187,7 @@ bool __blk_freeze_queue_start(struct request_queue *q)
void blk_freeze_queue_start(struct request_queue *q)
{
- if (__blk_freeze_queue_start(q))
+ if (__blk_freeze_queue_start(q, current))
blk_freeze_acquire_lock(q, false, false);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -170,7 +216,7 @@ EXPORT_SYMBOL_GPL(blk_mq_freeze_queue);
bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
- int unfreeze = false;
+ bool unfreeze;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
@@ -180,8 +226,8 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
if (!q->mq_freeze_depth) {
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
- unfreeze = true;
}
+ unfreeze = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
return unfreeze;
@@ -203,7 +249,7 @@ EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
*/
void blk_freeze_queue_start_non_owner(struct request_queue *q)
{
- __blk_freeze_queue_start(q);
+ __blk_freeze_queue_start(q, NULL);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start_non_owner);
diff --git a/block/blk.h b/block/blk.h
index ac48b79cbf80..57fc035620d6 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -37,7 +37,8 @@ void blk_free_flush_queue(struct blk_flush_queue *q);
bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
bool blk_queue_start_drain(struct request_queue *q);
-bool __blk_freeze_queue_start(struct request_queue *q);
+bool __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner);
int __bio_queue_enter(struct request_queue *q, struct bio *bio);
void submit_bio_noacct_nocheck(struct bio *bio);
void bio_await_chain(struct bio *bio);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 93551772c1d6..1b51a7c92e9b 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -575,6 +575,10 @@ struct request_queue {
struct throtl_data *td;
#endif
struct rcu_head rcu_head;
+#ifdef CONFIG_LOCKDEP
+ struct task_struct *mq_freeze_owner;
+ int mq_freeze_owner_depth;
+#endif
wait_queue_head_t mq_freeze_wq;
/*
* Protect concurrent access to q_usage_counter by
]
|
| 543/5 |
2026/11/03 22:38 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 27692
output: 75
thoughts: 1613
Thoughts: **Deep Dive into Block Queue Freezing and Disk Death**
Okay, let's dissect this patch meticulously. My initial focus is on the `blk_queue_start_drain()` function and its call sites. First up, `blk_mq_destroy_queue()`. It's immediately clear that this function sets the `QUEUE_FLAG_DYING` flag and calls `blk_queue_start_drain()` β but it never unfreezes the queue! That's a red flag.
Next, I'm examining `__blk_mark_disk_dead()` within the `block/genhd.c` file. This is called from `blk_mark_disk_dead()`. This sets the `QUEUE_FLAG_DYING` and then calls `blk_queue_start_drain()`. Now, I need to understand what happens if `blk_mark_disk_dead()` is invoked when the freeze depth is zero *before* this patch. Pre-patch, `blk_queue_start_drain()` would call `__blk_freeze_queue_start()` and in this scenario would set the owner and depth for the queue. Importantly, `blk_mark_disk_dead()` never calls `blk_freeze_acquire_lock()` nor does it unfreeze the queue. It seems that unless `__del_gendisk` runs later, there's a good chance this queue gets frozen forever!
Thinking further, if `QUEUE_FLAG_DYING` is set during any of these calls (`blk_mark_disk_dead()`, `blk_mq_destroy_queue()`, or even in `__del_gendisk()`), and `GD_OWNS_QUEUE` is set, the queue is basically trapped in a frozen state. Let's look at the change in `blk_queue_start_drain()` to try and clarify this. The intent of the change is clear β to block new requests from entering the queue by calling `__blk_freeze_queue_start()` when the dying flag is set.
Now, let's carefully trace what happens in `__del_gendisk()` under two conditions; when `GD_OWNS_QUEUE` is set and when it is not.
First, let's examine what happens when `GD_OWNS_QUEUE` *is* set, as it almost always is. Inside `__blk_mark_disk_dead()`: First, the `GD_DEAD` bit is set, and *then* the `QUEUE_FLAG_DYING` flag is set. Now both flags are set! It then calls `blk_queue_start_drain()`.
Before this patch, `blk_queue_start_drain()` would invoke `__blk_freeze_queue_start(q, current)`. The result of this action inside `blk_freeze_set_owner()` would be that, since both `GD_DEAD` and `QUEUE_FLAG_DYING` were set, `q->mq_freeze_disk_dead` and `q->mq_freeze_queue_dying` become true. Consequently, `blk_freeze_acquire_lock()` did nothing because both conditions are true! Furthermore, the check at the end of `__del_gendisk()` would be FALSE, so `__blk_mq_unfreeze_queue()` would *not* be called. `blk_unfreeze_release_lock(q)` would then do nothing as both `mq_freeze_disk_dead` and `mq_freeze_queue_dying` were true.
A critical question is if, *before* the patch, and while inside `__del_gendisk()` and between the call to `__blk_mark_disk_dead()` and the very end of the function, something like `blk_unregister_queue()` might result in a call to both `blk_mq_freeze_queue()` and `blk_mq_unfreeze_queue()`. Let's verify whether anything within `__del_gendisk()` itself (or in any function called by it) attempts to freeze and unfreeze the queue. I need to read through `block/genhd.c` and `block/blk-sysfs.c` (particularly the `blk_unregister_queue()` function) to be absolutely sure.
|
| 544/5 |
2026/11/03 22:39 |
tool |
read-file |
0m
Args: map[File:block/blk-sysfs.c FirstLine:990 LineCount:70]
Results: map[Contents: 990:
991: if (queue_is_mq(q))
992: elevator_set_default(q);
993:
994: blk_queue_flag_set(QUEUE_FLAG_REGISTERED, q);
995: wbt_init_enable_default(disk);
996:
997: /* Now everything is ready and send out KOBJ_ADD uevent */
998: kobject_uevent(&disk->queue_kobj, KOBJ_ADD);
999: if (q->elevator)
1000: kobject_uevent(&q->elevator->kobj, KOBJ_ADD);
1001: mutex_unlock(&q->sysfs_lock);
1002:
1003: /*
1004: * SCSI probing may synchronously create and destroy a lot of
1005: * request_queues for non-existent devices. Shutting down a fully
1006: * functional queue takes measureable wallclock time as RCU grace
1007: * periods are involved. To avoid excessive latency in these
1008: * cases, a request_queue starts out in a degraded mode which is
1009: * faster to shut down and is made fully functional here as
1010: * request_queues for non-existent devices never get registered.
1011: */
1012: blk_queue_flag_set(QUEUE_FLAG_INIT_DONE, q);
1013: percpu_ref_switch_to_percpu(&q->q_usage_counter);
1014:
1015: return ret;
1016:
1017: out_unregister_ia_ranges:
1018: disk_unregister_independent_access_ranges(disk);
1019: out_debugfs_remove:
1020: blk_debugfs_remove(disk);
1021: mutex_unlock(&q->sysfs_lock);
1022: if (queue_is_mq(q))
1023: blk_mq_sysfs_unregister(disk);
1024: out_del_queue_kobj:
1025: kobject_del(&disk->queue_kobj);
1026: return ret;
1027: }
1028:
1029: /**
1030: * blk_unregister_queue - counterpart of blk_register_queue()
1031: * @disk: Disk of which the request queue should be unregistered from sysfs.
1032: *
1033: * Note: the caller is responsible for guaranteeing that this function is called
1034: * after blk_register_queue() has finished.
1035: */
1036: void blk_unregister_queue(struct gendisk *disk)
1037: {
1038: struct request_queue *q = disk->queue;
1039:
1040: if (WARN_ON(!q))
1041: return;
1042:
1043: /* Return early if disk->queue was never registered. */
1044: if (!blk_queue_registered(q))
1045: return;
1046:
1047: /*
1048: * Since sysfs_remove_dir() prevents adding new directory entries
1049: * before removal of existing entries starts, protect against
1050: * concurrent elv_iosched_store() calls.
1051: */
1052: mutex_lock(&q->sysfs_lock);
1053: blk_queue_flag_clear(QUEUE_FLAG_REGISTERED, q);
1054: mutex_unlock(&q->sysfs_lock);
1055:
1056: /*
1057: * Remove the sysfs attributes before unregistering the queue data
1058: * structures that can be modified through sysfs.
1059: */
]
|
| 545/5 |
2026/11/03 22:39 |
tool |
codesearch-find-references |
0m
Error:
Args: map[IncludeSnippetLines:20 Name:GD_OWNS_QUEUE]
Results: map[References:<nil> TruncatedOutput:false]
|
| 546/5 |
2026/11/03 22:39 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 30472
output: 65
thoughts: 36
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Analyzing `blk_unregister_queue` and Ownership Flags**
Alright, let's dive back into this block layer stuff. My immediate thought is, "Right, `blk_unregister_queue`. That function's the key. Let's make sure we've got a comprehensive understanding of what's happening when a queue goes away." I need to understand all the implications, especially concerning resource management, since this is a critical spot.
Now, I'm thinking, "Let's read through the implementation of `blk_unregister_queue` in `block/blk-sysfs.c`." I'm not going to just skim it; I need to really *understand* its execution path. I'm looking for where we're releasing resources, unregistering sysfs entries, and generally cleaning up. I'm particularly interested in anything that interacts with device ownership.
And that brings me to the next key point: the `GD_OWNS_QUEUE` flag. We know that's a key attribute. So, let's now reach for grep and search the whole codebase to find all instances where `GD_OWNS_QUEUE` is used in relationship to `blk_unregister_queue`. I want to see if and how ownership is transferred or released during unregistration and ensure we aren't creating race conditions. I need to make sure we're handling all possible scenarios gracefully, especially regarding multi-queue setups and dynamic device additions/removals. That flag is usually the point where things get complicated. I need a clear mental model of how this flag interacts with the other data structures involved.
Basically, I want to map the code execution and understand the ownership of block queues.
|
| 547/5 |
2026/11/03 22:39 |
tool |
read-file |
0m
Args: map[File:block/blk-sysfs.c FirstLine:1055 LineCount:50]
Results: map[Contents:1055:
1056: /*
1057: * Remove the sysfs attributes before unregistering the queue data
1058: * structures that can be modified through sysfs.
1059: */
1060: if (queue_is_mq(q))
1061: blk_mq_sysfs_unregister(disk);
1062: blk_crypto_sysfs_unregister(disk);
1063:
1064: mutex_lock(&q->sysfs_lock);
1065: disk_unregister_independent_access_ranges(disk);
1066: mutex_unlock(&q->sysfs_lock);
1067:
1068: /* Now that we've deleted all child objects, we can delete the queue. */
1069: kobject_uevent(&disk->queue_kobj, KOBJ_REMOVE);
1070: kobject_del(&disk->queue_kobj);
1071:
1072: if (queue_is_mq(q))
1073: elevator_set_none(q);
1074:
1075: blk_debugfs_remove(disk);
1076: }
]
|
| 548/5 |
2026/11/03 22:39 |
tool |
grepper |
0m
Args: map[Expression:GD_OWNS_QUEUE]
Results: map[Output:block/blk-mq.c=4500=struct gendisk *__blk_mq_alloc_disk(struct blk_mq_tag_set *set,
--
block/blk-mq.c-4516- }
block/blk-mq.c:4517: set_bit(GD_OWNS_QUEUE, &disk->state);
block/blk-mq.c-4518- return disk;
--
block/genhd.c=660=static bool __blk_mark_disk_dead(struct gendisk *disk)
--
block/genhd.c-667-
block/genhd.c:668: if (test_bit(GD_OWNS_QUEUE, &disk->state))
block/genhd.c-669- blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
--
block/genhd.c=697=static void __del_gendisk(struct gendisk *disk)
--
block/genhd.c-774- */
block/genhd.c:775: if (!test_bit(GD_OWNS_QUEUE, &disk->state))
block/genhd.c-776- __blk_mq_unfreeze_queue(q, true);
--
block/genhd.c=1280=static void disk_release(struct device *dev)
--
block/genhd.c-1297- if (queue_is_mq(disk->queue) &&
block/genhd.c:1298: test_bit(GD_OWNS_QUEUE, &disk->state) &&
block/genhd.c-1299- !test_bit(GD_ADDED, &disk->state)) {
--
block/genhd.c=1520=struct gendisk *__blk_alloc_disk(struct queue_limits *lim, int node,
--
block/genhd.c-1535- }
block/genhd.c:1536: set_bit(GD_OWNS_QUEUE, &disk->state);
block/genhd.c-1537- return disk;
--
include/linux/blkdev.h=144=struct gendisk {
--
include/linux/blkdev.h-174-#define GD_SUPPRESS_PART_SCAN 5
include/linux/blkdev.h:175:#define GD_OWNS_QUEUE 6
include/linux/blkdev.h-176-#define GD_ZONE_APPEND_USED 7
]
|
| 549/5 |
2026/11/03 22:39 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 31552
output: 39
thoughts: 1192
Thoughts: **Analyzing the Context of `blk_queue_start_drain()`**
Okay, so I'm diving into the change in `blk_queue_start_drain()` where we now pass `blk_queue_dying(q) ? NULL : current` and want to understand why. It seems we're really looking at a subtle but important change in how we manage queue freezing and unfreezing.
My immediate focus is on when `blk_queue_start_drain(q)` is called. There are three primary paths: `blk_mq_destroy_queue(q)`, `blk_mark_disk_dead(disk)`, and `__del_gendisk(disk)`. The critical thing here is the state of `blk_queue_dying(q)` and whether or not the queue will ever be unfrozen.
In the `blk_mq_destroy_queue` case, `blk_queue_dying(q)` *is* true, and crucially, the queue is *never* unfrozen within this function. This means the freeze is permanent, a non-owner freeze, and passing `NULL` to `blk_freeze_queue_start` makes perfect sense. This avoids setting the `mq_freeze_owner` since there will never be a corresponding unfreeze to release it.
`blk_mark_disk_dead(disk)` is similar. Again, `blk_queue_dying(q)` is true, and the freeze isn't explicitly released by the same task. This is another situation where a non-owner freeze is the intention. The `NULL` parameter aligns perfectly with this. However, the `GD_OWNS_QUEUE` flag is interesting. If `!GD_OWNS_QUEUE`, the unfreeze *might* happen in a different task context, so the non-owner freeze is the only safe option here.
The most complex case is `__del_gendisk(disk)`. Here, we see `blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue)` being called if `GD_OWNS_QUEUE` is true. If `!GD_OWNS_QUEUE`, `__blk_mq_unfreeze_queue(q, true)` is *not* called at the end! This is another permanent freeze scenario. The `lock_mask` will be 0, and the queue stays frozen forever. I need to dig deeper into the relationship between `blk_unregister_queue(disk)`, `elevator_set_none(q)`, and `disable_elv_switch(q)` to fully grasp the ramifications. The elevator setup here is important to assess this scenario.
|
| 550/5 |
2026/11/03 22:39 |
tool |
read-file |
0m
Args: map[File:block/elevator.c FirstLine:630 LineCount:90]
Results: map[Contents: 630: int ret = 0;
631:
632: if (ctx->old) {
633: struct elevator_resources res = {
634: .et = ctx->old->et,
635: .data = ctx->old->elevator_data
636: };
637:
638: elv_unregister_queue(q, ctx->old);
639: blk_mq_free_sched_res(&res, ctx->old->type, q->tag_set);
640: kobject_put(&ctx->old->kobj);
641: }
642: if (ctx->new) {
643: ret = elv_register_queue(q, ctx->new, !ctx->no_uevent);
644: if (ret)
645: elv_exit_and_release(ctx, q);
646: }
647: return ret;
648: }
649:
650: /*
651: * Switch this queue to the given IO scheduler.
652: */
653: static int elevator_change(struct request_queue *q, struct elv_change_ctx *ctx)
654: {
655: unsigned int memflags;
656: struct blk_mq_tag_set *set = q->tag_set;
657: int ret = 0;
658:
659: lockdep_assert_held(&set->update_nr_hwq_lock);
660:
661: if (strncmp(ctx->name, "none", 4)) {
662: ret = blk_mq_alloc_sched_res(q, ctx->type, &ctx->res,
663: set->nr_hw_queues);
664: if (ret)
665: return ret;
666: }
667:
668: memflags = blk_mq_freeze_queue(q);
669: /*
670: * May be called before adding disk, when there isn't any FS I/O,
671: * so freezing queue plus canceling dispatch work is enough to
672: * drain any dispatch activities originated from passthrough
673: * requests, then no need to quiesce queue which may add long boot
674: * latency, especially when lots of disks are involved.
675: *
676: * Disk isn't added yet, so verifying queue lock only manually.
677: */
678: blk_mq_cancel_work_sync(q);
679: mutex_lock(&q->elevator_lock);
680: if (!(q->elevator && elevator_match(q->elevator->type, ctx->name)))
681: ret = elevator_switch(q, ctx);
682: mutex_unlock(&q->elevator_lock);
683: blk_mq_unfreeze_queue(q, memflags);
684: if (!ret)
685: ret = elevator_change_done(q, ctx);
686:
687: /*
688: * Free sched resource if it's allocated but we couldn't switch elevator.
689: */
690: if (!ctx->new)
691: blk_mq_free_sched_res(&ctx->res, ctx->type, set);
692:
693: return ret;
694: }
695:
696: /*
697: * The I/O scheduler depends on the number of hardware queues, this forces a
698: * reattachment when nr_hw_queues changes.
699: */
700: void elv_update_nr_hw_queues(struct request_queue *q,
701: struct elv_change_ctx *ctx)
702: {
703: struct blk_mq_tag_set *set = q->tag_set;
704: int ret = -ENODEV;
705:
706: WARN_ON_ONCE(q->mq_freeze_depth == 0);
707:
708: if (ctx->type && !blk_queue_dying(q) && blk_queue_registered(q)) {
709: mutex_lock(&q->elevator_lock);
710: /* force to reattach elevator after nr_hw_queue is updated */
711: ret = elevator_switch(q, ctx);
712: mutex_unlock(&q->elevator_lock);
713: }
714: blk_mq_unfreeze_queue_nomemrestore(q);
715: if (!ret)
716: WARN_ON_ONCE(elevator_change_done(q, ctx));
717:
718: /*
719: * Free sched resource if it's allocated but we couldn't switch elevator.
]
|
| 551/5 |
2026/11/03 22:39 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 34170
output: 39
thoughts: 22
Thoughts: Here's a summary of my thought process, as requested:
**Diving into `block/elevator.c`**
Alright, let's get down to brass tacks. I've got a hunch about the current behavior and I think I can trace the issue to the elevator block's code. To pinpoint the problem, I'm going to focus on a specific segment, lines 720 to 780 of `block/elevator.c`. That range should give me a good, focused view of the relevant logic without overwhelming me with the entire file. I want to see how the elevator's internal mechanics are being handled within that block of code. I'm expecting to find the key to understanding the specific problem at hand there. Let's see what that snippet reveals.
|
| 552/5 |
2026/11/03 22:39 |
tool |
read-file |
0m
Args: map[File:block/elevator.c FirstLine:720 LineCount:70]
Results: map[Contents: 720: */
721: if (!ctx->new)
722: blk_mq_free_sched_res(&ctx->res, ctx->type, set);
723: }
724:
725: /*
726: * Use the default elevator settings. If the chosen elevator initialization
727: * fails, fall back to the "none" elevator (no elevator).
728: */
729: void elevator_set_default(struct request_queue *q)
730: {
731: struct elv_change_ctx ctx = {
732: .name = "mq-deadline",
733: .no_uevent = true,
734: };
735: int err;
736:
737: /* now we allow to switch elevator */
738: blk_queue_flag_clear(QUEUE_FLAG_NO_ELV_SWITCH, q);
739:
740: if (q->tag_set->flags & BLK_MQ_F_NO_SCHED_BY_DEFAULT)
741: return;
742:
743: /*
744: * For single queue devices, default to using mq-deadline. If we
745: * have multiple queues or mq-deadline is not available, default
746: * to "none".
747: */
748: ctx.type = elevator_find_get(ctx.name);
749: if (!ctx.type)
750: return;
751:
752: if ((q->nr_hw_queues == 1 ||
753: blk_mq_is_shared_tags(q->tag_set->flags))) {
754: err = elevator_change(q, &ctx);
755: if (err < 0)
756: pr_warn("\"%s\" elevator initialization, failed %d, falling back to \"none\"\n",
757: ctx.name, err);
758: }
759: elevator_put(ctx.type);
760: }
761:
762: void elevator_set_none(struct request_queue *q)
763: {
764: struct elv_change_ctx ctx = {
765: .name = "none",
766: };
767: int err;
768:
769: err = elevator_change(q, &ctx);
770: if (err < 0)
771: pr_warn("%s: set none elevator failed %d\n", __func__, err);
772: }
773:
774: static void elv_iosched_load_module(const char *elevator_name)
775: {
776: struct elevator_type *found;
777:
778: spin_lock(&elv_list_lock);
779: found = __elevator_find(elevator_name);
780: spin_unlock(&elv_list_lock);
781:
782: if (!found)
783: request_module("%s-iosched", elevator_name);
784: }
785:
786: ssize_t elv_iosched_store(struct gendisk *disk, const char *buf,
787: size_t count)
788: {
789: char elevator_name[ELV_NAME_MAX];
]
|
| 553/5 |
2026/11/03 22:39 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 35232
output: 40
thoughts: 46
Thoughts: Here's my summary, as if I were thinking these thoughts:
**Analyzing `del_gendisk` in `block/genhd.c`**
Alright, given the context, I think we should definitely take a look at the `del_gendisk` function. Specifically, my hunch is that the implementation in `block/genhd.c` is going to be relevant. Let's start by looking around lines 780 to 840 in that file. That should give me a good handle on how the code is structured and where potential issues might be lurking related to the disk cleanup process. I suspect we'll find some crucial details there on how the generic disk device is handled during removal.
|
| 554/5 |
2026/11/03 22:40 |
tool |
read-file |
0m
Args: map[File:block/genhd.c FirstLine:780 LineCount:65]
Results: map[Contents: 780: if (start_drain)
781: blk_unfreeze_release_lock(q);
782: }
783:
784: static void disable_elv_switch(struct request_queue *q)
785: {
786: struct blk_mq_tag_set *set = q->tag_set;
787: WARN_ON_ONCE(!queue_is_mq(q));
788:
789: down_write(&set->update_nr_hwq_lock);
790: blk_queue_flag_set(QUEUE_FLAG_NO_ELV_SWITCH, q);
791: up_write(&set->update_nr_hwq_lock);
792: }
793:
794: /**
795: * del_gendisk - remove the gendisk
796: * @disk: the struct gendisk to remove
797: *
798: * Removes the gendisk and all its associated resources. This deletes the
799: * partitions associated with the gendisk, and unregisters the associated
800: * request_queue.
801: *
802: * This is the counter to the respective device_add_disk() call.
803: *
804: * The final removal of the struct gendisk happens when its refcount reaches 0
805: * with put_disk(), which should be called after del_gendisk(), if
806: * device_add_disk() was used.
807: *
808: * Drivers exist which depend on the release of the gendisk to be synchronous,
809: * it should not be deferred.
810: *
811: * Context: can sleep
812: */
813: void del_gendisk(struct gendisk *disk)
814: {
815: struct blk_mq_tag_set *set;
816: unsigned int memflags;
817:
818: if (!queue_is_mq(disk->queue)) {
819: __del_gendisk(disk);
820: } else {
821: set = disk->queue->tag_set;
822:
823: disable_elv_switch(disk->queue);
824:
825: memflags = memalloc_noio_save();
826: down_read(&set->update_nr_hwq_lock);
827: __del_gendisk(disk);
828: up_read(&set->update_nr_hwq_lock);
829: memalloc_noio_restore(memflags);
830: }
831: }
832: EXPORT_SYMBOL(del_gendisk);
833:
834: /**
835: * invalidate_disk - invalidate the disk
836: * @disk: the struct gendisk to invalidate
837: *
838: * A helper to invalidates the disk. It will clean the disk's associated
839: * buffer/page caches and reset its internal states so that the disk
840: * can be reused by the drivers.
841: *
842: * Context: can sleep
843: */
844: void invalidate_disk(struct gendisk *disk)
]
|
| 555/5 |
2026/11/03 22:40 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 36275
output: 26
thoughts: 4167
Thoughts: **Analyzing blk_queue_start_drain and __del_gendisk for Proper Queue Freezing/Unfreezing**
Okay, let's dissect this carefully. My immediate concern is ensuring that the queue freezing and unfreezing mechanisms work correctly, especially in the context of disk removal with `__del_gendisk()`. The key is tracing how `blk_queue_start_drain()` interacts with `__blk_mark_disk_dead()` and how this impacts the ownership and depth of the freeze. The primary issue I'm examining is the potential for stale freeze owners or incorrect lock acquisition, particularly with Multi-Queue (MQ) devices, and specifically focusing on `QUEUE_FLAG_DYING` and how it changes the logic for freeze ownership.
I see that `__del_gendisk()` first calls `__blk_mark_disk_dead()`. This sets the `GD_DEAD` flag and potentially sets `QUEUE_FLAG_DYING` if the disk *owns* the queue (`GD_OWNS_QUEUE`). If `GD_OWNS_QUEUE` is set, `blk_queue_start_drain()` is called, which then uses the function `__blk_freeze_queue_start()` to trigger the freeze.
Now here's the patch's crucial alteration. If `blk_queue_dying(q)` is true, meaning `QUEUE_FLAG_DYING` is set (likely because `GD_OWNS_QUEUE` is set during device teardown), then the call is now `__blk_freeze_queue_start(q, NULL)`. This is a significant change! Before the patch, the *current* process would have been set as the owner. Now, passing NULL means a non-owner freeze. This non-owner freeze is *permanent* and never unfrozen. Why is this? Because when the device is dying, we don't want to get in a situation of needing to wait for a specific task to unfreeze the queue. It could exit or get stuck.
However, if the queue *isn't* owned by the disk, like a shared SCSI queue, `QUEUE_FLAG_DYING` won't be set so we'd call `__blk_freeze_queue_start(q, current)`. This acquires the lock and marks the current process as the freeze *owner*. This sets `q->mq_freeze_owner = current` and increments the freeze depth. The interesting part is what happens later in `__del_gendisk`. If the queue is *not* owned by the disk, we call `__blk_mq_unfreeze_queue()`, which reduces the depth, and releases the lock.
But here is where the problem creeps in: what if the depth was already > 0 before the entry to `__del_gendisk()`, or if another process called `blk_unregister_queue()` *while* `__del_gendisk()` is running. If this is the case, `q->mq_freeze_owner_depth` will get incremented, and then later decremented, leading to a race and a missed release! Let's examine this in more detail. In this scenario with `!GD_OWNS_QUEUE`, calling `blk_unregister_queue()` in `__del_gendisk()` will double the `mq_freeze_depth` because `blk_mq_freeze_queue` is called internally by `blk_unregister_queue`. Then, after that call has happened, line 776 will call `__blk_mq_unfreeze_queue` which decrements the `q->mq_freeze_depth` and the `q->mq_freeze_owner_depth`. And finally, at line 779 `blk_unfreeze_release_lock()`releases the lock, but only if the depth is now 0.
My immediate red flag is that if the queue *was* already frozen (depth > 0) before `__del_gendisk()`, the existing owner and depth will be bumped during disk death, and then decremented when calling unfreeze later in the function.
Now, let's shift to the case where the disk *does* own the queue (`GD_OWNS_QUEUE` is set). This is the *critical* scenario, and where the patch's impact is most pronounced. BEFORE the patch, the code would set the *current* process as the freeze owner, with depth 1. Then at the end, it did *not* unfreeze the queue because `GD_OWNS_QUEUE` is set, leaving `q->mq_freeze_owner` still pointing to a potentially exited task. THIS IS A BUG! The queue is left in a permanently frozen state owned by a task that could exit at any time!
However, AFTER the patch,
|
| 556/5 |
2026/11/03 22:40 |
tool |
grepper |
0m
Args: map[Expression:QUEUE_FLAG_DYING]
Results: map[Output:block/blk-mq.c=4483=void blk_mq_destroy_queue(struct request_queue *q)
--
block/blk-mq.c-4489-
block/blk-mq.c:4490: blk_queue_flag_set(QUEUE_FLAG_DYING, q);
block/blk-mq.c-4491- blk_queue_start_drain(q);
--
block/genhd.c=660=static bool __blk_mark_disk_dead(struct gendisk *disk)
--
block/genhd.c-668- if (test_bit(GD_OWNS_QUEUE, &disk->state))
block/genhd.c:669: blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
block/genhd.c-670-
--
block/genhd.c=689=void blk_mark_disk_dead(struct gendisk *disk)
block/genhd.c-690-{
block/genhd.c:691: blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
block/genhd.c-692- __blk_mark_disk_dead(disk);
--
drivers/scsi/scsi_lib.c=488=static void scsi_starved_list_run(struct Scsi_Host *shost)
--
drivers/scsi/scsi_lib.c-529- * function then blk_run_queue() will return immediately since
drivers/scsi/scsi_lib.c:530: * blk_mq_destroy_queue() marks the queue with QUEUE_FLAG_DYING.
drivers/scsi/scsi_lib.c-531- */
--
include/linux/blkdev.h=666=enum {
include/linux/blkdev.h:667: QUEUE_FLAG_DYING, /* queue being torn down */
include/linux/blkdev.h-668- QUEUE_FLAG_NOMERGES, /* disable merge attempts */
--
include/linux/blkdev.h=691=void blk_queue_flag_clear(unsigned int flag, struct request_queue *q);
include/linux/blkdev.h-692-
include/linux/blkdev.h:693:#define blk_queue_dying(q) test_bit(QUEUE_FLAG_DYING, &(q)->queue_flags)
include/linux/blkdev.h-694-#define blk_queue_init_done(q) test_bit(QUEUE_FLAG_INIT_DONE, &(q)->queue_flags)
]
|
| 557/5 |
2026/11/03 22:41 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 41129
output: 38
thoughts: 2083
Thoughts: **Analyzing the Disk Queue Dying Process**
Okay, let's break this down. I see three primary locations where `QUEUE_FLAG_DYING` gets set, and it's essential to understand the implications of `blk_queue_start_drain(q)` in each case.
First, in `blk_mq_destroy_queue(q)`, `QUEUE_FLAG_DYING` is set, and then `blk_queue_start_drain(q)` is called. No matching unfreeze. Got it.
Second, `__blk_mark_disk_dead(disk)`: Here too, before calling `blk_queue_start_drain(q)`, `QUEUE_FLAG_DYING` is set. There's no counterpart for this, no matching `blk_freeze_acquire_lock` or `blk_unfreeze_release_lock`. This is where it gets interesting, especially when considering scenarios where `GD_OWNS_QUEUE` might *not* be set.
Third, `blk_mark_disk_dead(disk)` within `__del_gendisk(disk)` β this is the crucial point of analysis. The critical factor is whether `GD_OWNS_QUEUE` is set. When `GD_OWNS_QUEUE` is true, the process is very similar to the previous case: `QUEUE_FLAG_DYING` is set, `blk_queue_start_drain(q)` is called, but there's no corresponding `__blk_mq_unfreeze_queue(q, true)`. However, when `GD_OWNS_QUEUE` is false, `QUEUE_FLAG_DYING` is *not* set before calling `blk_queue_start_drain(q)`. Now, there *is* a matching `__blk_mq_unfreeze_queue(q, true)` at the end of `__del_gendisk`, which means the drain freeze is paired, and things are handled properly with lock release.
Hold on a minute... What if `blk_mark_disk_dead` has been called *before* `del_gendisk` when `!GD_OWNS_QUEUE`? That introduces a wrinkle. I need to trace the call paths to be sure.
The crux of the matter is `blk_queue_start_drain(q)`. The critical check `blk_queue_dying(q) ? NULL : current` is crucial. If this were not in place, and `blk_mark_disk_dead` were called with `q->mq_freeze_depth` already at 0, here's the problematic scenario. If `blk_queue_start_drain` did *not* do this check, then `blk_freeze_set_owner` would set `q->mq_freeze_owner` to the current thread, and `q->mq_freeze_owner_depth` to 1, and so on. Now, if the thread calling `blk_mark_disk_dead` had *already* frozen the queue, we have a problem. The depth would get incremented during the mark-dead process and never properly decremented when calling unfreeze, triggering a lock held when returning to user space warning, which is bad news.
Consider this: Thread A calls `blk_mq_freeze_queue(q)`. Then Thread A calls `blk_mark_disk_dead(disk)`. And then Thread A calls `blk_mq_unfreeze_queue(q)`. Now, if `blk_queue_start_drain` had no check, and the current thread were passed, the owner depth would increase, but the matching unfreeze would not be performed, meaning the freeze depth is never decremented to 0. This results in the locks never being released properly, leading to the warning!
So, the key insight here is that `blk_queue_dying(q) ? NULL : current` is essential. When the queue is dying, it enforces a non-owner freeze that *must not* set the freeze owner or increment the owner depth. When it isn't dying, the lock acquisition and release are handled by `__del_gendisk`.
Thus, with `blk_queue_dying(q) ? NULL : current` in `blk_queue_start_drain(q)`:
- Because `QUEUE_FLAG_DYING` is set in `blk_mark_disk_dead` (and in `__blk_mark_disk_dead` when `GD_OWNS_QUEUE` is set, and in `blk_mq_destroy_queue`), the drain freeze is NEVER unfrozen!
- Because that drain freeze is NEVER unfrozen, it MUST NOT increment `q->mq_freeze_owner_depth` (and MUST NOT set `q->mq_freeze_owner
|
| 558/5 |
2026/11/03 22:41 |
tool |
codesearch-find-references |
0m
Args: map[IncludeSnippetLines:10 Name:blk_mark_disk_dead]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__dm_destroy SourceFile:drivers/md/dm.c SourceLine:2738 SourceSnippet:2728: struct dm_table *map;
2729: int srcu_idx;
2730:
2731: might_sleep();
2732:
2733: spin_lock(&_minor_lock);
2734: idr_replace(&_minor_idr, MINOR_ALLOCED, MINOR(disk_devt(dm_disk(md))));
2735: set_bit(DMF_FREEING, &md->flags);
2736: spin_unlock(&_minor_lock);
2737:
2738: blk_mark_disk_dead(md->disk);
2739:
2740: /*
2741: * Take suspend_lock so that presuspend and postsuspend methods
2742: * do not race with internal suspend.
2743: */
2744: mutex_lock(&md->suspend_lock);
2745: map = dm_get_live_table(md, &srcu_idx);
2746: if (!dm_suspended_md(md)) {
2747: dm_table_presuspend_targets(map);
2748: set_bit(DMF_SUSPENDED, &md->flags);
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:nvme_mark_namespaces_dead SourceFile:drivers/nvme/host/core.c SourceLine:5354 SourceSnippet:5345: /* let I/O to all namespaces fail in preparation for surprise removal */
5346: void nvme_mark_namespaces_dead(struct nvme_ctrl *ctrl)
5347: {
5348: struct nvme_ns *ns;
5349: int srcu_idx;
5350:
5351: srcu_idx = srcu_read_lock(&ctrl->srcu);
5352: list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
5353: srcu_read_lock_held(&ctrl->srcu))
5354: blk_mark_disk_dead(ns->disk);
5355: srcu_read_unlock(&ctrl->srcu, srcu_idx);
5356: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:sd_remove SourceFile:drivers/scsi/sd.c SourceLine:4279 SourceSnippet:4269: struct scsi_disk *sdkp = dev_get_drvdata(dev);
4270:
4271: /*
4272: * If runtime resume fails, e.g. because the device was unplugged
4273: * while runtime suspended, the request queue stays in the pm-only
4274: * state and any I/O submitted by del_gendisk(), e.g. from
4275: * sync_filesystem(), would wait forever in __bio_queue_enter().
4276: * Prevent this by marking the disk dead.
4277: */
4278: if (scsi_autopm_get_device(sdkp->device) < 0)
4279: blk_mark_disk_dead(sdkp->disk);
4280:
4281: device_del(&sdkp->disk_dev);
4282: del_gendisk(sdkp->disk);
4283: if (!sdkp->suspended)
4284: sd_shutdown(sdp);
4285:
4286: put_disk(sdkp->disk);
4287:
4288: if (sdp->sector_size > PAGE_SIZE)
4289: sd_large_pool_destroy();
] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__UNIQUE_ID_addressable_blk_mark_disk_dead_1047 SourceFile:block/genhd.c SourceLine:695 SourceSnippet: 695: EXPORT_SYMBOL_GPL(blk_mark_disk_dead);
] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__gendwarfksyms_ptr_blk_mark_disk_dead SourceFile:block/genhd.c SourceLine:695 SourceSnippet: 695: EXPORT_SYMBOL_GPL(blk_mark_disk_dead);
] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:__gendwarfksyms_ptr_blk_mark_disk_dead SourceFile:block/genhd.c SourceLine:695 SourceSnippet: 695: EXPORT_SYMBOL_GPL(blk_mark_disk_dead);
]] TruncatedOutput:false]
|
| 559/5 |
2026/11/03 22:41 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 44595
output: 36
thoughts: 72
Thoughts: Here's my summary, as I see it:
**Investigating SCSI Disk Device Allocation and Ownership**
Right, okay, let's dive into this. My initial thought is to zero in on `sd_remove` function in `drivers/scsi/sd.c`. I need to understand the device removal process here, particularly how the device is ultimately cleaned up. But before I go too far, I need to back up a bit and nail down the core data structures. Specifically, I'm concerned with how `sdkp->disk` is allocated within that file, `sd.c`. That's critical. I need to be sure I understand the memory lifecycle of that data structure before I look to see how it is destroyed.
Next, I need to know if `sdkp->disk` has `GD_OWNS_QUEUE` set. This is a crucial detail that informs the queue management and resource ownership. It will influence what happens when the device is removed. Knowing that flag's state is fundamental.
Okay, time to pull up the source code for `drivers/scsi/sd.c` and start digging! Let's get to it.
|
| 560/5 |
2026/11/03 22:41 |
tool |
grepper |
0m
Args: map[Expression:alloc_disk PathPrefixes:[drivers/scsi/sd.c]]
Results: map[Output:drivers/scsi/sd.c=4008=static int sd_probe(struct scsi_device *sdp)
--
drivers/scsi/sd.c-4037-
drivers/scsi/sd.c:4038: gd = blk_mq_alloc_disk_for_queue(sdp->request_queue,
drivers/scsi/sd.c-4039- &sd_bio_compl_lkclass);
]
|
| 561/5 |
2026/11/03 22:41 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 44823
output: 42
thoughts: 1246
Thoughts: **Analyzing the blk-mq Freeze/Unfreeze Logic in `sd_remove`**
Okay, let's break this down. My focus is on the `sd_remove` function in `drivers/scsi/sd.c` and how it interacts with the block layer's freeze/unfreeze mechanisms, particularly in the context of `blk-mq`. I've been digging into how the `GD_OWNS_QUEUE` flag is handled and the potential implications of the patch.
First, I see that the `sdkp->disk` structure is allocated using `blk_mq_alloc_disk_for_queue`, but critically, *it doesn't set* `GD_OWNS_QUEUE`. This is important. Then, if `scsi_autopm_get_device` fails in `sd_remove`, we call `blk_mark_disk_dead`, `device_del`, and `del_gendisk`. The real fun is inside `blk_mark_disk_dead` and `del_gendisk`, especially pre and post-patch.
**Before the Patch (Problematic Scenario):**
Before the patch, if `scsi_autopm_get_device` fails, `blk_mark_disk_dead` sets `QUEUE_FLAG_DYING` and starts a drain. `__blk_freeze_queue_start` is then called, and the freeze owner is set to the current task. `blk_mark_disk_dead` *didn't* call `blk_freeze_acquire_lock`. Then, `del_gendisk` comes into play. `blk_unregister_queue` and its internal functions triggered a *double* increment of the freeze depth. The first increment happened inside `elevator_change` with `blk_mq_freeze_queue`, the second increment happened in `__del_gendisk`. And because `GD_OWNS_QUEUE` was not set, `__blk_mq_unfreeze_queue` decremented the depth *twice* due to the missing flag and the freeze state. This could lead to a race condition with other callers of `blk_mq_freeze_queue`. Critically, `blk_unfreeze_release_lock` was *not* called because the drain was already started by the earlier `blk_mark_disk_dead`.
**After the Patch (Improved Scenario):**
The patch changes this. The `blk_mark_disk_dead` now calls `__blk_freeze_queue_start` with a `NULL` owner when dying. The freeze depth increments as before, through `blk_mq_freeze_queue` from `elevator_change`. And at the end of the unregister process, because the `GD_OWNS_QUEUE` is not set, `__blk_mq_unfreeze_queue` decrements the depth. Because the freeze owner is `NULL` no lock is released.
**In Summary:**
The pre-patch code was problematic. The patch is intended to fix this by ensuring a more consistent freeze/unfreeze sequence. Now, even if `scsi_autopm_get_device` fails, the queue is marked as dying, the depth increments correctly through `blk_mq_freeze_queue` and the `__blk_mq_unfreeze_queue` correctly decrements. This prevents the depth imbalance. The lack of `GD_OWNS_QUEUE` is still an interesting point and the patch addresses the race condition that this implied.
Now, I should expand this review to include the context of those freeze/unfreeze functions. Let's look through `blk/blk-mq.c` lines 110 to 270 and other related files as an extra layer of caution.
|
| 562/5 |
2026/11/03 22:42 |
tool |
read-file |
0m
Args: map[File:block/blk-mq.c FirstLine:110 LineCount:160]
Results: map[Contents: 110: &mi);
111: inflight[READ] = mi.inflight[READ];
112: inflight[WRITE] = mi.inflight[WRITE];
113: }
114:
115: #ifdef CONFIG_LOCKDEP
116: static bool blk_freeze_set_owner(struct request_queue *q,
117: struct task_struct *owner)
118: {
119: if (!owner)
120: return false;
121:
122: if (!q->mq_freeze_depth) {
123: q->mq_freeze_owner = owner;
124: q->mq_freeze_owner_depth = 1;
125: q->mq_freeze_disk_dead = !q->disk ||
126: test_bit(GD_DEAD, &q->disk->state) ||
127: !blk_queue_registered(q);
128: q->mq_freeze_queue_dying = blk_queue_dying(q);
129: return true;
130: }
131:
132: if (owner == q->mq_freeze_owner)
133: q->mq_freeze_owner_depth += 1;
134: return false;
135: }
136:
137: /* verify the last unfreeze in owner context */
138: static bool blk_unfreeze_check_owner(struct request_queue *q)
139: {
140: if (q->mq_freeze_owner != current)
141: return false;
142: if (--q->mq_freeze_owner_depth == 0) {
143: q->mq_freeze_owner = NULL;
144: return true;
145: }
146: return false;
147: }
148:
149: #else
150:
151: static bool blk_freeze_set_owner(struct request_queue *q,
152: struct task_struct *owner)
153: {
154: return false;
155: }
156:
157: static bool blk_unfreeze_check_owner(struct request_queue *q)
158: {
159: return false;
160: }
161: #endif
162:
163: bool __blk_freeze_queue_start(struct request_queue *q,
164: struct task_struct *owner)
165: {
166: bool freeze;
167:
168: mutex_lock(&q->mq_freeze_lock);
169: freeze = blk_freeze_set_owner(q, owner);
170: if (++q->mq_freeze_depth == 1) {
171: percpu_ref_kill(&q->q_usage_counter);
172: mutex_unlock(&q->mq_freeze_lock);
173: if (queue_is_mq(q))
174: blk_mq_run_hw_queues(q, false);
175: } else {
176: mutex_unlock(&q->mq_freeze_lock);
177: }
178:
179: return freeze;
180: }
181:
182: void blk_freeze_queue_start(struct request_queue *q)
183: {
184: if (__blk_freeze_queue_start(q, current))
185: blk_freeze_acquire_lock(q);
186: }
187: EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
188:
189: void blk_mq_freeze_queue_wait(struct request_queue *q)
190: {
191: wait_event(q->mq_freeze_wq, percpu_ref_is_zero(&q->q_usage_counter));
192: }
193: EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait);
194:
195: int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
196: unsigned long timeout)
197: {
198: return wait_event_timeout(q->mq_freeze_wq,
199: percpu_ref_is_zero(&q->q_usage_counter),
200: timeout);
201: }
202: EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait_timeout);
203:
204: void blk_mq_freeze_queue_nomemsave(struct request_queue *q)
205: {
206: blk_freeze_queue_start(q);
207: blk_mq_freeze_queue_wait(q);
208: }
209: EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_nomemsave);
]
|
| 563/5 |
2026/11/03 22:42 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 47560
output: 25
thoughts: 958
Thoughts: **Deep Dive into Block Layer Concurrency and Lockdep**
Okay, let's dissect this patch. I need to understand the interaction between disk ownership and queue freezing, specifically around lines 770-782 in `block/genhd.c`. The core logic is clear: if the disk *doesn't* own the queue, we unfreeze it; otherwise, if it's an MQ queue, we exit it. But I need to trace a specific scenario.
What happens if `GD_OWNS_QUEUE` isn't set, and we're in `__del_gendisk`? Let me walk through it. First, `__blk_mark_disk_dead` is called to generate `lock_mask`, setting `q->mq_freeze_owner` to current, `q->mq_freeze_owner_depth` to `1`, and `q->mq_freeze_lock_mask` to `BLK_FREEZE_LOCK_QUEUE`. Then, `blk_freeze_acquire_lock` grabs `q_lockdep_map`. Crucially, line 776 triggers `__blk_mq_unfreeze_queue`. This decrements `q->mq_freeze_owner_depth` to zero, sets `q->mq_freeze_owner` to NULL, and crucially, *returns* `BLK_FREEZE_LOCK_QUEUE`. Then, `blk_unfreeze_release_lock` releases `q_lockdep_map`.
Now I see the subtlety: why are `blk_freeze_acquire_lock` and `blk_unfreeze_release_lock` inline functions? The answer is lockdep. Because they use `_RET_IP_` in `rwsem_acquire` and `rwsem_release`, lockdep tracks the caller of those lock operations. The reason for their existence and usage lies in passing lockdep state by value: the acquisition/release sites are properly recorded by returning the `lock_mask` by value from `__blk_freeze_queue_start` and `__blk_mq_unfreeze_queue`, which are computed and read inside `q->mq_freeze_lock`. This avoids reading mutable fields of `struct request_queue *q` outside the necessary locks. Very clean.
Alright, let's step back and apply the Architectural Review Checklist.
1. **Sentinel Test:** No sentinel band-aids here, it's a replacement. It takes mutable shared state reads outside of a lock (`q->mq_freeze_disk_dead`, `q->mq_freeze_queue_dying`) and transforms it into a bitmask (`lock_mask`). The bitmask is computed/retrieved under the required lock, and ensures dying queue drain freezes, don't claim lockdep ownership (`blk_queue_dying(q) ? NULL : current`). Excellent.
2. **LIFO Stack Unwinding Symmetry:** The acquire/release lockdep modeling is strictly symmetric, via that `lock_mask`. Perfect.
3. **Ownership Decoupling:** The ownership modeling within `blk_freeze_set_owner` and `blk_unfreeze_check_owner` is clean.
4. **Codebase Idiom Alignment:** This is very clean and idiomatic block layer code.
I'm satisfied. This patch directly addresses the root cause in a well-designed and minimal way. Time to call `set-results` with `ReviewApproved=true`.
|
| 564/5 |
2026/11/03 22:42 |
tool |
set-results |
0m
Args: map[ReviewApproved:true ReviewComments:[]]
Results: map[ReviewApproved:true ReviewComments:[]]
|
| 565/4 |
2026/11/03 22:42 |
action |
evaluate-patch-review |
0m
Results: map[NeedsIteration:false ReviewFeedback:]
|
| 566/1 |
2026/11/03 22:42 |
action |
apply-patch |
0m
Results:
|
| 567/1 |
2026/11/03 22:42 |
action |
init-style-items |
0m
Results:
|
| 568/1 |
2026/11/03 22:42 |
action |
run-checkpatch |
0m
Results: map[CheckpatchOutput:total: 0 errors, 0 warnings, 274 lines checked
Your patch has no obvious style problems and is ready for submission.
]
|
| 569/1 |
2026/11/03 22:42 |
loop |
|
2m
|
| 570/2 |
2026/11/03 22:42 |
iteration |
0 |
2m
|
| 571/3 |
2026/11/03 22:42 |
agent |
checkpatch-arbiter |
2m
Model:
Results:
Instruction:
You are an expert Linux kernel maintainer acting as a code style arbiter.
Your task is to review scripts/checkpatch.pl output and reviewer style requests for a proposed patch.
Determine which reported issues are genuine, actionable formatting/style defects (e.g. indentation, whitespace,
naming, syntax style) and should be fixed. List them in ActionableIssues.
Ignore issues that are false positives, intentional constructs (e.g. BUG_ON/XA_BUG_ON in test files, macros,
subsystem conventions), or unfixable without breaking code logic or tests. If no issues should be changed,
leave ActionableIssues empty.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt:
The patch diff is:
diff --git a/block/blk-core.c b/block/blk-core.c
index 8836c7028..fc3ab62e8 100644
--- a/block/blk-core.c
+++ b/block/blk-core.c
@@ -324,20 +324,21 @@ void blk_put_queue(struct request_queue *q)
}
EXPORT_SYMBOL(blk_put_queue);
-bool blk_queue_start_drain(struct request_queue *q)
+unsigned int blk_queue_start_drain(struct request_queue *q)
{
/*
* When queue DYING flag is set, we need to block new req
* entering queue, so we call blk_freeze_queue_start() to
* prevent I/O from crossing blk_queue_enter().
*/
- bool freeze = __blk_freeze_queue_start(q, current);
+ unsigned int lock_mask = __blk_freeze_queue_start(q,
+ blk_queue_dying(q) ? NULL : current);
if (queue_is_mq(q))
blk_mq_wake_waiters(q);
/* Make blk_queue_enter() reexamine the DYING flag. */
wake_up_all(&q->mq_freeze_wq);
- return freeze;
+ return lock_mask;
}
/**
diff --git a/block/blk-mq.c b/block/blk-mq.c
index d9ab295be..3f64a59e5 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -113,60 +113,64 @@ void blk_mq_in_driver_rw(struct block_device *part, unsigned int inflight[2])
}
#ifdef CONFIG_LOCKDEP
-static bool blk_freeze_set_owner(struct request_queue *q,
- struct task_struct *owner)
+static unsigned int blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
{
+ unsigned int lock_mask = 0;
+
if (!owner)
- return false;
+ return 0;
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
- q->mq_freeze_disk_dead = !q->disk ||
- test_bit(GD_DEAD, &q->disk->state) ||
- !blk_queue_registered(q);
- q->mq_freeze_queue_dying = blk_queue_dying(q);
- return true;
+ if (q->disk && !test_bit(GD_DEAD, &q->disk->state) &&
+ blk_queue_registered(q))
+ lock_mask |= BLK_FREEZE_LOCK_IO;
+ if (!blk_queue_dying(q))
+ lock_mask |= BLK_FREEZE_LOCK_QUEUE;
+ q->mq_freeze_lock_mask = lock_mask;
+ return lock_mask;
}
if (owner == q->mq_freeze_owner)
q->mq_freeze_owner_depth += 1;
- return false;
+ return 0;
}
/* verify the last unfreeze in owner context */
-static bool blk_unfreeze_check_owner(struct request_queue *q)
+static unsigned int blk_unfreeze_check_owner(struct request_queue *q)
{
if (q->mq_freeze_owner != current)
- return false;
+ return 0;
if (--q->mq_freeze_owner_depth == 0) {
q->mq_freeze_owner = NULL;
- return true;
+ return q->mq_freeze_lock_mask;
}
- return false;
+ return 0;
}
#else
-static bool blk_freeze_set_owner(struct request_queue *q,
- struct task_struct *owner)
+static unsigned int blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
{
- return false;
+ return 0;
}
-static bool blk_unfreeze_check_owner(struct request_queue *q)
+static unsigned int blk_unfreeze_check_owner(struct request_queue *q)
{
- return false;
+ return 0;
}
#endif
-bool __blk_freeze_queue_start(struct request_queue *q,
- struct task_struct *owner)
+unsigned int __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner)
{
- bool freeze;
+ unsigned int lock_mask;
mutex_lock(&q->mq_freeze_lock);
- freeze = blk_freeze_set_owner(q, owner);
+ lock_mask = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
@@ -176,13 +180,14 @@ bool __blk_freeze_queue_start(struct request_queue *q,
mutex_unlock(&q->mq_freeze_lock);
}
- return freeze;
+ return lock_mask;
}
void blk_freeze_queue_start(struct request_queue *q)
{
- if (__blk_freeze_queue_start(q, current))
- blk_freeze_acquire_lock(q);
+ unsigned int lock_mask = __blk_freeze_queue_start(q, current);
+
+ blk_freeze_acquire_lock(q, lock_mask);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -208,9 +213,9 @@ void blk_mq_freeze_queue_nomemsave(struct request_queue *q)
}
EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_nomemsave);
-bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
+unsigned int __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
- bool unfreeze;
+ unsigned int lock_mask;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
@@ -221,16 +226,17 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
}
- unfreeze = blk_unfreeze_check_owner(q);
+ lock_mask = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
- return unfreeze;
+ return lock_mask;
}
void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
{
- if (__blk_mq_unfreeze_queue(q, false))
- blk_unfreeze_release_lock(q);
+ unsigned int lock_mask = __blk_mq_unfreeze_queue(q, false);
+
+ blk_unfreeze_release_lock(q, lock_mask);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_nomemrestore);
diff --git a/block/blk.h b/block/blk.h
index ed2172472..2c4d5ee7d 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -55,10 +55,11 @@ const char *blk_status_to_tag(blk_status_t status);
blk_status_t tag_to_blk_status(const char *tag);
enum req_op str_to_blk_op(const char *op);
-bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
-bool blk_queue_start_drain(struct request_queue *q);
-bool __blk_freeze_queue_start(struct request_queue *q,
- struct task_struct *owner);
+unsigned int __blk_mq_unfreeze_queue(struct request_queue *q,
+ bool force_atomic);
+unsigned int blk_queue_start_drain(struct request_queue *q);
+unsigned int __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner);
int __bio_queue_enter(struct request_queue *q, struct bio *bio);
void submit_bio_noacct_nocheck(struct bio *bio, bool split);
int bio_submit_or_kill(struct bio *bio, unsigned int flags);
@@ -777,27 +778,36 @@ blk_status_t bio_integrity_verify(struct bio *bio,
void blk_integrity_prepare(struct request *rq);
void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
+enum {
+ BLK_FREEZE_LOCK_IO = (1 << 0),
+ BLK_FREEZE_LOCK_QUEUE = (1 << 1),
+};
+
#ifdef CONFIG_LOCKDEP
-static inline void blk_freeze_acquire_lock(struct request_queue *q)
+static inline void blk_freeze_acquire_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
- if (!q->mq_freeze_disk_dead)
+ if (lock_mask & BLK_FREEZE_LOCK_IO)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
- if (!q->mq_freeze_queue_dying)
+ if (lock_mask & BLK_FREEZE_LOCK_QUEUE)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q)
+static inline void blk_unfreeze_release_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
- if (!q->mq_freeze_queue_dying)
+ if (lock_mask & BLK_FREEZE_LOCK_QUEUE)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
- if (!q->mq_freeze_disk_dead)
+ if (lock_mask & BLK_FREEZE_LOCK_IO)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
#else
-static inline void blk_freeze_acquire_lock(struct request_queue *q)
+static inline void blk_freeze_acquire_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q)
+static inline void blk_unfreeze_release_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
}
#endif
diff --git a/block/genhd.c b/block/genhd.c
index 10ca8b4d6..e73349b74 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -657,13 +657,13 @@ static void blk_report_disk_dead(struct gendisk *disk, bool surprise)
rcu_read_unlock();
}
-static bool __blk_mark_disk_dead(struct gendisk *disk)
+static unsigned int __blk_mark_disk_dead(struct gendisk *disk)
{
/*
* Fail any new I/O.
*/
if (test_and_set_bit(GD_DEAD, &disk->state))
- return false;
+ return 0;
if (test_bit(GD_OWNS_QUEUE, &disk->state))
blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
@@ -699,7 +699,7 @@ static void __del_gendisk(struct gendisk *disk)
struct request_queue *q = disk->queue;
struct block_device *part;
unsigned long idx;
- bool start_drain;
+ unsigned int lock_mask;
might_sleep();
@@ -727,9 +727,8 @@ static void __del_gendisk(struct gendisk *disk)
* Drop all partitions now that the disk is marked dead.
*/
mutex_lock(&disk->open_mutex);
- start_drain = __blk_mark_disk_dead(disk);
- if (start_drain)
- blk_freeze_acquire_lock(q);
+ lock_mask = __blk_mark_disk_dead(disk);
+ blk_freeze_acquire_lock(q, lock_mask);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
@@ -777,8 +776,7 @@ static void __del_gendisk(struct gendisk *disk)
else if (queue_is_mq(q))
blk_mq_exit_queue(q);
- if (start_drain)
- blk_unfreeze_release_lock(q);
+ blk_unfreeze_release_lock(q, lock_mask);
}
static void disable_elv_switch(struct request_queue *q)
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 0c2010230..32a8e93c4 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -637,11 +637,10 @@ struct request_queue {
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
/*
- * Records disk & queue state in current context, used in unfreeze
+ * Records lockdep locks acquired in owner context, used in unfreeze
* queue
*/
- bool mq_freeze_disk_dead;
- bool mq_freeze_queue_dying;
+ unsigned int mq_freeze_lock_mask;
#endif
wait_queue_head_t mq_freeze_wq;
/*
The checkpatch.pl output is:
total: 0 errors, 0 warnings, 274 lines checked
Your patch has no obvious style problems and is ready for submission.
Carefully evaluate each issue and populate ActionableIssues.
|
| 572/4 |
2026/11/03 22:42 |
llm |
checkpatch-arbiter |
2m
Model:
Tokens:
input: 4191
output: 15
thoughts: 1651
Thoughts: **Reviewing the Patch for Subtle Style Issues**
Okay, so I'm taking a look at this patch. `checkpatch.pl` reports zero errors and zero warnings, and there aren't any reviewer comments to work with. My initial instinct is to dig deeper. Even with a clean `checkpatch` run, there can still be subtle style discrepancies that are worth catching. The goal is to ensure a consistently high standard.
I'm specifically focused on the indentation of the added `lock_mask` parameter within `blk_unfreeze_release_lock`. Let's see... `static inline void blk_unfreeze_release_lock(` is 45 characters. The tab stops are at multiples of 8. Therefore, 5 tabs gives you 40 spaces. It appears that the code is indented five tabs (40 spaces) and then four spaces, making a total of 44. I believe it should be five spaces, for proper alignment!
On a related note, looking at the line above, `static inline void blk_freeze_acquire_lock(` has 43 chars. Here there are five tabs and three spaces, making it a total of 43 spaces.
Hmm... Let's count again: `static inline void blk_unfreeze_release_lock(` which is 45 chars! And `static inline void blk_freeze_acquire_lock(` which is 43 chars. With five tabs, we have 40 spaces. Thus, the indentation in the diff of `blk_unfreeze_release_lock` is off by one space.
Okay, I need to focus on what the task is *actually* asking. Am I looking for problems? No. The instructions are very specific: "Determine *which reported issues* are genuine, actionable...". Notice the word "reported". There are *no reported issues*. `checkpatch` found nothing, and there are no reviewer comments. The text explicitly says, "If no issues should be changed, leave ActionableIssues empty."
Therefore, since there are *no* reported issues to fix, the `ActionableIssues` list must be empty. It is a very clear direction! Time to call `set-results` with `ActionableIssues: []`.
|
| 573/4 |
2026/11/03 22:45 |
tool |
set-results |
0m
Args:
Results:
|
| 574/3 |
2026/11/03 22:45 |
action |
evaluate-checkpatch-arbiter |
0m
Results: map[NeedRefinement:false]
|
| 575/3 |
2026/11/03 22:45 |
action |
If |
0m
Args: map[NeedRefinement:false]
|
| 576/1 |
2026/11/03 22:45 |
agent |
fixes-finder |
1h03m
Model:
Results: map[FixesHash:f6661b1d0525f3764596a1b65eeed9e75aecafa7]
Instruction:
You are an experienced Linux kernel developer tasked with identifying the commit
that introduced the bug being fixed. Identifying the correct buggy commit is crucial
for proper kernel maintenance (backporting to stable trees, etc.).
Your investigation strategy:
1. Examine the patch that fixes the bug. Use git tools (like git-log or git-blame)
to trace the history of the lines or functions modified by the patch.
2. Analyze the stack trace in the crash report. Identify the key files and functions
involved in the crash and investigate their history to see when the problematic
logic was introduced.
3. Compare the bug explanation with the commit history to find the point where
the described logic error first appeared.
A bug is typically introduced when a piece of code is first written, or when
a refactoring changed its logic in a way that introduced the bug.
Trace the history of relevant symbols or find when specific code patterns were introduced/removed.
You must provide exactly one bug-introducing commit hash.
If you are unable to confidently determine the bug-introducing commit after investigation,
return an empty string rather than guessing.
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt:
The crash is:
device-mapper: ioctl: device has been removed from the dev hash table.
================================================
WARNING: lock held when returning to user space!
syzkaller #1 Not tainted
------------------------------------------------
syz.3.1525/11804 is leaving the kernel with locks still held!
locks held by syz.3.1525/11804: 1, last CPU#0:
#0: ffff88805abdd468 (&q->q_usage_counter(queue)#52){+.+.}-{0:0}, at: blk_mq_freeze_queue include/linux/blk-mq.h:959 [inline]
#0: ffff88805abdd468 (&q->q_usage_counter(queue)#52){+.+.}-{0:0}, at: elevator_change+0x194/0x480 block/elevator.c:668
The explanation of the root cause is:
### Root Cause Analysis
#### Summary
The `WARNING: lock held when returning to user space!` for `&q->q_usage_counter(queue)` (which is the lockdep map `q->q_lockdep_map` acquired at `elevator_change+0x194/0x480`, `block/elevator.c:668`) is caused by a race condition between:
1. **`DM_TABLE_LOAD` (`table_load`)** initializing and registering the request-based DM queue/gendisk (`dm_setup_md_queue()` -> `add_disk()` -> `blk_register_queue()` -> `elevator_set_default()` -> `elevator_change()`), and
2. **`DM_DEV_REMOVE` (`dev_remove`)** concurrently destroying the same DM device (`dm_destroy()` -> `__dm_destroy()` -> `blk_mark_disk_dead()`), which marks the queue dying and starts draining/freezing the queue.
Specifically, in the block layer's queue-freeze lockdep tracking (`block/blk-mq.c` and `block/blk.h`), the flags `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead` are stored as per-`request_queue` fields protected by `q->mq_freeze_lock` when `q->mq_freeze_depth == 0`, **but `blk_unfreeze_release_lock(q)` reads them outside `q->mq_freeze_lock` after `q->mq_freeze_depth` has already been decremented to `0`**. When `blk_mark_disk_dead()` races with `blk_mq_unfreeze_queue()`, `q->mq_freeze_queue_dying` is overwritten from `false` to `true` before `blk_unfreeze_release_lock(q)` runs, causing `blk_unfreeze_release_lock(q)` to skip releasing `q->q_lockdep_map`.
---
#### Detailed Mechanism
##### 1. Lockdep modeling of `blk_mq_freeze_queue()` / `blk_mq_unfreeze_queue()`
In `block/blk-core.c:500`, `q->q_lockdep_map` is initialized with the name `"&q->q_usage_counter(queue)"`:
```c
lockdep_init_map(&q->q_lockdep_map, "&q->q_usage_counter(queue)",
&q->q_lock_cls_key, 0);
```
In `block/blk-mq.c`, when a task freezes a queue via `blk_mq_freeze_queue(q)` -> `blk_freeze_queue_start(q)`:
```c
static bool blk_freeze_set_owner(struct request_queue *q,
struct task_struct *owner)
{
if (!owner)
return false;
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
q->mq_freeze_disk_dead = !q->disk ||
test_bit(GD_DEAD, &q->disk->state) ||
!blk_queue_registered(q);
q->mq_freeze_queue_dying = blk_queue_dying(q);
return true;
}
if (owner == q->mq_freeze_owner)
q->mq_freeze_owner_depth += 1;
return false;
}
```
```c
bool __blk_freeze_queue_start(struct request_queue *q,
struct task_struct *owner)
{
bool freeze;
mutex_lock(&q->mq_freeze_lock);
freeze = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
if (queue_is_mq(q))
blk_mq_run_hw_queues(q, false);
} else {
mutex_unlock(&q->mq_freeze_lock);
}
return freeze;
}
void blk_freeze_queue_start(struct request_queue *q)
{
if (__blk_freeze_queue_start(q, current))
blk_freeze_acquire_lock(q);
}
```
And in `block/blk.h:715-728`:
```c
static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
if (!q->mq_freeze_queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
```
When the owner task unfreezes the queue via `blk_mq_unfreeze_queue(q, memflags)` -> `blk_mq_unfreeze_queue_nomemrestore(q)` (`block/blk-mq.c:211-235`):
```c
bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
bool unfreeze;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
q->q_usage_counter.data->force_atomic = true;
q->mq_freeze_depth--;
WARN_ON_ONCE(q->mq_freeze_depth < 0);
if (!q->mq_freeze_depth) {
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
}
unfreeze = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
return unfreeze;
}
void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
{
if (__blk_mq_unfreeze_queue(q, false))
blk_unfreeze_release_lock(q);
}
```
Notice the bug here:
1. Inside `__blk_mq_unfreeze_queue()`, `q->mq_freeze_depth` is decremented to `0` and `q->mq_freeze_owner` is cleared to `NULL`, and then `mutex_unlock(&q->mq_freeze_lock)` is called.
2. Only **after** `q->mq_freeze_lock` is released does `blk_mq_unfreeze_queue_nomemrestore()` call `blk_unfreeze_release_lock(q)`, which inspects `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead`.
3. Because `q->mq_freeze_depth` is already `0` and `q->mq_freeze_lock` is unlocked, another thread calling `__blk_freeze_queue_start()` can immediately acquire `q->mq_freeze_lock`, see `!q->mq_freeze_depth`, and overwrite `q->mq_freeze_queue_dying` (and `q->mq_freeze_disk_dead`) in `blk_freeze_set_owner()`.
##### 2. How Device Mapper triggers this race
In the reproducer:
1. `ioctl(DM_DEV_CREATE)` creates a DM device `md` (`md->type == DM_TYPE_NONE`, with `md->disk` allocated via `blk_alloc_disk()`).
2. **Thread 1 (`syz.3.1525/11804`)** calls `ioctl(DM_TABLE_LOAD)` (`table_load()` in `drivers/md/dm-ioctl.c:1622`) with a request-based `"multipath"` target:
- `find_device(param)` looks up `md` under `_hash_lock`, increments `md->holders` (`dm_get(md)`), and drops `_hash_lock`.
- `populate_table()` parses the `"multipath"` target, setting the table type to `DM_TYPE_REQUEST_BASED`.
- Since `dm_get_md_type(md) == DM_TYPE_NONE`, `table_load()` calls `dm_setup_md_queue(md, t)` (`drivers/md/dm.c:2606`):
- `dm_mq_init_request_queue(md, t)` initializes `md->queue` as a `blk-mq` queue.
- `add_disk(md->disk)` -> `device_add_disk()` -> `add_disk_fwnode()` -> `__add_disk()` -> `blk_register_queue(md->disk)` (`block/blk-sysfs.c:991`):
```c
if (queue_is_mq(q))
elevator_set_default(q);
```
- `elevator_set_default(q)` calls `elevator_change(q, &ctx)` (`block/elevator.c:653`).
3. Concurrently, **Thread 2** calls `ioctl(DM_DEV_REMOVE)` (`dev_remove()` in `drivers/md/dm-ioctl.c:1063`):
- Under `_hash_lock`, `dm_lock_for_deletion(md, ...)` succeeds because it only checks `dm_open_count(md)` (`0`), **not** `md->holders`.
- `__hash_remove(hc)` removes `hc` from the hash table and clears `md->interface_ptr` (`dm_set_mdptr(md, NULL)`).
- `dev_remove()` drops `_hash_lock`, calls `dm_put(md)`, and calls `dm_destroy(md)` -> `__dm_destroy(md, true)` (`drivers/md/dm.c:2726`):
```c
blk_mark_disk_dead(md->disk);
...
if (wait)
while (atomic_read(&md->holders))
fsleep(1000);
```
- Notice that `__dm_destroy()` calls `blk_mark_disk_dead(md->disk)` **before** waiting for `md->holders` to drop to `0`.
##### 3. Exact Race Sequence
1. **Thread 1 (`table_load`)** enters `elevator_change()` (`block/elevator.c:668`):
```c
memflags = blk_mq_freeze_queue(q);
```
- `q->mq_freeze_depth` is `0`.
- `blk_freeze_set_owner(q, Thread_1)` sets:
- `q->mq_freeze_owner = Thread_1`
- `q->mq_freeze_owner_depth = 1`
- `q->mq_freeze_disk_dead = true` (since `QUEUE_FLAG_REGISTERED` is not set yet)
- `q->mq_freeze_queue_dying = false` (since `QUEUE_FLAG_DYING` is not set yet)
- `q->mq_freeze_depth` becomes `1`.
- `blk_freeze_acquire_lock(q)` sees `!q->mq_freeze_queue_dying == true` and calls:
```c
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
```
2. **Thread 1 (`table_load`)** finishes `elevator_switch()` and calls `blk_mq_unfreeze_queue(q, memflags)` at `block/elevator.c:683`:
- Inside `__blk_mq_unfreeze_queue(q, false)` (`block/blk-mq.c:211`):
- `q->mq_freeze_depth` is decremented from `1` to `0`.
- `blk_unfreeze_check_owner(q)` decrements `q->mq_freeze_owner_depth` to `0`, sets `q->mq_freeze_owner = NULL`, and returns `true`.
- `mutex_unlock(&q->mq_freeze_lock)` unlocks `q->mq_freeze_lock`.
3. **Thread 2 (`dev_remove`)** executes `blk_mark_disk_dead(md->disk)` (`block/genhd.c:689`):
```c
void blk_mark_disk_dead(struct gendisk *disk)
{
blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
__blk_mark_disk_dead(disk);
blk_report_disk_dead(disk, true);
}
```
- `blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue)` sets `QUEUE_FLAG_DYING` on `q`.
- `__blk_mark_disk_dead(disk)` calls `blk_queue_start_drain(disk->queue)` -> `__blk_freeze_queue_start(q, Thread_2)`.
- Right after Thread 1 unlocks `q->mq_freeze_lock` in step 2 (e.g., when woken from `q->mq_freeze_lock` wait_list during `mutex_unlock`), Thread 2 acquires `q->mq_freeze_lock`.
- Because `q->mq_freeze_depth` is `0`, `blk_freeze_set_owner(q, Thread_2)` runs and sets:
```c
q->mq_freeze_queue_dying = blk_queue_dying(q); /* true! */
```
4. **Thread 1 (`table_load`)** now executes `blk_unfreeze_release_lock(q)` (`block/blk-mq.c:233` -> `block/blk.h:722`):
```c
static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
```
Because `q->mq_freeze_queue_dying` was overwritten with `true` by Thread 2 in step 3, `!q->mq_freeze_queue_dying` evaluates to `false`, and **`rwsem_release(&q->q_lockdep_map, _RET_IP_)` is skipped**.
5. **Thread 1 (`table_load`)** finishes `dm_setup_md_queue()`, acquires `_hash_lock` in `table_load()` (`drivers/md/dm-ioctl.c:1678`), sees `hc = dm_get_mdptr(md)` is `NULL`, logs:
```
device-mapper: ioctl: device has been removed from the dev hash table.
```
cleans up `t`, drops `md->holders` (`dm_put(md)`), and returns `-ENXIO` to user space with `q->q_lockdep_map` (`&q->q_usage_counter(queue)`) still held in lockdep, triggering the warning.
---
#### How to Fix
1. **In the block layer (`block/blk-mq.c`, `block/blk.h`, `block/genhd.c`)**:
`blk_freeze_acquire_lock(q)` and `blk_unfreeze_release_lock(q)` must not read mutable per-queue `q->mq_freeze_queue_dying` / `q->mq_freeze_disk_dead` fields outside `q->mq_freeze_lock` after `q->mq_freeze_depth` has dropped to `0` (where another task starting a new freeze can overwrite them). Either:
- Perform the lockdep release (`blk_unfreeze_release_lock(q)`) / state consumption under `q->mq_freeze_lock` before `q->mq_freeze_depth` is decremented / unlocked (or pass the saved `disk_dead` and `queue_dying` booleans out of `__blk_mq_unfreeze_queue()` by value while still holding `q->mq_freeze_lock`), and similarly pass/snapshot them under `q->mq_freeze_lock` in `__blk_freeze_queue_start()`.
2. **In Device Mapper (`drivers/md/dm.c`)**:
In `__dm_destroy()`, `blk_mark_disk_dead(md->disk)` should not be called while another thread holds `md->holders` and may still be in `dm_setup_md_queue()` / `add_disk(md->disk)` initializing and registering the disk/queue (i.e., wait for `atomic_read(&md->holders)` or serialize against `md->type_lock` before marking the disk dead).
The patch that fixes the bug is:
diff --git a/block/blk-core.c b/block/blk-core.c
index 8836c7028..fc3ab62e8 100644
--- a/block/blk-core.c
+++ b/block/blk-core.c
@@ -324,20 +324,21 @@ void blk_put_queue(struct request_queue *q)
}
EXPORT_SYMBOL(blk_put_queue);
-bool blk_queue_start_drain(struct request_queue *q)
+unsigned int blk_queue_start_drain(struct request_queue *q)
{
/*
* When queue DYING flag is set, we need to block new req
* entering queue, so we call blk_freeze_queue_start() to
* prevent I/O from crossing blk_queue_enter().
*/
- bool freeze = __blk_freeze_queue_start(q, current);
+ unsigned int lock_mask = __blk_freeze_queue_start(q,
+ blk_queue_dying(q) ? NULL : current);
if (queue_is_mq(q))
blk_mq_wake_waiters(q);
/* Make blk_queue_enter() reexamine the DYING flag. */
wake_up_all(&q->mq_freeze_wq);
- return freeze;
+ return lock_mask;
}
/**
diff --git a/block/blk-mq.c b/block/blk-mq.c
index d9ab295be..3f64a59e5 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -113,60 +113,64 @@ void blk_mq_in_driver_rw(struct block_device *part, unsigned int inflight[2])
}
#ifdef CONFIG_LOCKDEP
-static bool blk_freeze_set_owner(struct request_queue *q,
- struct task_struct *owner)
+static unsigned int blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
{
+ unsigned int lock_mask = 0;
+
if (!owner)
- return false;
+ return 0;
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
- q->mq_freeze_disk_dead = !q->disk ||
- test_bit(GD_DEAD, &q->disk->state) ||
- !blk_queue_registered(q);
- q->mq_freeze_queue_dying = blk_queue_dying(q);
- return true;
+ if (q->disk && !test_bit(GD_DEAD, &q->disk->state) &&
+ blk_queue_registered(q))
+ lock_mask |= BLK_FREEZE_LOCK_IO;
+ if (!blk_queue_dying(q))
+ lock_mask |= BLK_FREEZE_LOCK_QUEUE;
+ q->mq_freeze_lock_mask = lock_mask;
+ return lock_mask;
}
if (owner == q->mq_freeze_owner)
q->mq_freeze_owner_depth += 1;
- return false;
+ return 0;
}
/* verify the last unfreeze in owner context */
-static bool blk_unfreeze_check_owner(struct request_queue *q)
+static unsigned int blk_unfreeze_check_owner(struct request_queue *q)
{
if (q->mq_freeze_owner != current)
- return false;
+ return 0;
if (--q->mq_freeze_owner_depth == 0) {
q->mq_freeze_owner = NULL;
- return true;
+ return q->mq_freeze_lock_mask;
}
- return false;
+ return 0;
}
#else
-static bool blk_freeze_set_owner(struct request_queue *q,
- struct task_struct *owner)
+static unsigned int blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
{
- return false;
+ return 0;
}
-static bool blk_unfreeze_check_owner(struct request_queue *q)
+static unsigned int blk_unfreeze_check_owner(struct request_queue *q)
{
- return false;
+ return 0;
}
#endif
-bool __blk_freeze_queue_start(struct request_queue *q,
- struct task_struct *owner)
+unsigned int __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner)
{
- bool freeze;
+ unsigned int lock_mask;
mutex_lock(&q->mq_freeze_lock);
- freeze = blk_freeze_set_owner(q, owner);
+ lock_mask = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
@@ -176,13 +180,14 @@ bool __blk_freeze_queue_start(struct request_queue *q,
mutex_unlock(&q->mq_freeze_lock);
}
- return freeze;
+ return lock_mask;
}
void blk_freeze_queue_start(struct request_queue *q)
{
- if (__blk_freeze_queue_start(q, current))
- blk_freeze_acquire_lock(q);
+ unsigned int lock_mask = __blk_freeze_queue_start(q, current);
+
+ blk_freeze_acquire_lock(q, lock_mask);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -208,9 +213,9 @@ void blk_mq_freeze_queue_nomemsave(struct request_queue *q)
}
EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_nomemsave);
-bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
+unsigned int __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
- bool unfreeze;
+ unsigned int lock_mask;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
@@ -221,16 +226,17 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
}
- unfreeze = blk_unfreeze_check_owner(q);
+ lock_mask = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
- return unfreeze;
+ return lock_mask;
}
void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
{
- if (__blk_mq_unfreeze_queue(q, false))
- blk_unfreeze_release_lock(q);
+ unsigned int lock_mask = __blk_mq_unfreeze_queue(q, false);
+
+ blk_unfreeze_release_lock(q, lock_mask);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_nomemrestore);
diff --git a/block/blk.h b/block/blk.h
index ed2172472..2c4d5ee7d 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -55,10 +55,11 @@ const char *blk_status_to_tag(blk_status_t status);
blk_status_t tag_to_blk_status(const char *tag);
enum req_op str_to_blk_op(const char *op);
-bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
-bool blk_queue_start_drain(struct request_queue *q);
-bool __blk_freeze_queue_start(struct request_queue *q,
- struct task_struct *owner);
+unsigned int __blk_mq_unfreeze_queue(struct request_queue *q,
+ bool force_atomic);
+unsigned int blk_queue_start_drain(struct request_queue *q);
+unsigned int __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner);
int __bio_queue_enter(struct request_queue *q, struct bio *bio);
void submit_bio_noacct_nocheck(struct bio *bio, bool split);
int bio_submit_or_kill(struct bio *bio, unsigned int flags);
@@ -777,27 +778,36 @@ blk_status_t bio_integrity_verify(struct bio *bio,
void blk_integrity_prepare(struct request *rq);
void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
+enum {
+ BLK_FREEZE_LOCK_IO = (1 << 0),
+ BLK_FREEZE_LOCK_QUEUE = (1 << 1),
+};
+
#ifdef CONFIG_LOCKDEP
-static inline void blk_freeze_acquire_lock(struct request_queue *q)
+static inline void blk_freeze_acquire_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
- if (!q->mq_freeze_disk_dead)
+ if (lock_mask & BLK_FREEZE_LOCK_IO)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
- if (!q->mq_freeze_queue_dying)
+ if (lock_mask & BLK_FREEZE_LOCK_QUEUE)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q)
+static inline void blk_unfreeze_release_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
- if (!q->mq_freeze_queue_dying)
+ if (lock_mask & BLK_FREEZE_LOCK_QUEUE)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
- if (!q->mq_freeze_disk_dead)
+ if (lock_mask & BLK_FREEZE_LOCK_IO)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
#else
-static inline void blk_freeze_acquire_lock(struct request_queue *q)
+static inline void blk_freeze_acquire_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q)
+static inline void blk_unfreeze_release_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
}
#endif
diff --git a/block/genhd.c b/block/genhd.c
index 10ca8b4d6..e73349b74 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -657,13 +657,13 @@ static void blk_report_disk_dead(struct gendisk *disk, bool surprise)
rcu_read_unlock();
}
-static bool __blk_mark_disk_dead(struct gendisk *disk)
+static unsigned int __blk_mark_disk_dead(struct gendisk *disk)
{
/*
* Fail any new I/O.
*/
if (test_and_set_bit(GD_DEAD, &disk->state))
- return false;
+ return 0;
if (test_bit(GD_OWNS_QUEUE, &disk->state))
blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
@@ -699,7 +699,7 @@ static void __del_gendisk(struct gendisk *disk)
struct request_queue *q = disk->queue;
struct block_device *part;
unsigned long idx;
- bool start_drain;
+ unsigned int lock_mask;
might_sleep();
@@ -727,9 +727,8 @@ static void __del_gendisk(struct gendisk *disk)
* Drop all partitions now that the disk is marked dead.
*/
mutex_lock(&disk->open_mutex);
- start_drain = __blk_mark_disk_dead(disk);
- if (start_drain)
- blk_freeze_acquire_lock(q);
+ lock_mask = __blk_mark_disk_dead(disk);
+ blk_freeze_acquire_lock(q, lock_mask);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
@@ -777,8 +776,7 @@ static void __del_gendisk(struct gendisk *disk)
else if (queue_is_mq(q))
blk_mq_exit_queue(q);
- if (start_drain)
- blk_unfreeze_release_lock(q);
+ blk_unfreeze_release_lock(q, lock_mask);
}
static void disable_elv_switch(struct request_queue *q)
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 0c2010230..32a8e93c4 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -637,11 +637,10 @@ struct request_queue {
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
/*
- * Records disk & queue state in current context, used in unfreeze
+ * Records lockdep locks acquired in owner context, used in unfreeze
* queue
*/
- bool mq_freeze_disk_dead;
- bool mq_freeze_queue_dying;
+ unsigned int mq_freeze_lock_mask;
#endif
wait_queue_head_t mq_freeze_wq;
/*
Search for the commit(s) that introduced this bug.
|
| 577/2 |
2026/11/03 22:45 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 12178
output: 24
thoughts: 403
Thoughts: **Finding the Bug's Genesis**
Okay, I've got the crash report, root cause analysis, and the fix. My immediate task is to pinpoint the exact commit that introduced this regression. Let's dig in.
First, I need to understand the fix itself. I'll meticulously review the patch. It seems we're dealing with modifications across several core block layer files: `block/blk-core.c`, `block/blk-mq.c`, `block/blk.h`, `block/genhd.c`, and `include/linux/blkdev.h`. This spans functions like `blk_queue_start_drain`, various freezing/unfreezing routines (`blk_freeze_set_owner`, `__blk_freeze_queue_start`, `blk_mq_unfreeze_queue_nomemrestore`, etc.), and related locking mechanisms. Specifically, the patch touches on related constants, and replaces `mq_freeze_disk_dead` and `mq_freeze_queue_dying` with a new `mq_freeze_lock_mask`.
Now I need to understand the pre-existing code to understand the changes. What was there before this? `mq_freeze_disk_dead`, `mq_freeze_queue_dying`, and the freeze owner and lock functions.
Given this context, I'll leverage `git-log` or `git-blame` to trace back the origins of either `mq_freeze_disk_dead` or `blk_freeze_set_owner`. I'll focus these tools using CodeRegexp or MessageRegexps to focus on the changes that matter.
|
| 578/2 |
2026/11/03 22:45 |
tool |
git-log |
10m
Error:
Args: map[CodeRegexp:mq_freeze_disk_dead]
Results:
|
| 579/2 |
2026/11/03 22:55 |
llm |
fixes-finder |
2m
Model:
Tokens:
input: 12988
output: 31
thoughts: 10
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Adding a Path Prefix: "block/"**
Alright, so I'm considering adding a `PathPrefix="block/"`. The context is implied, but I'm assuming we're dealing with routing or URI management, likely in a web server or API gateway configuration. The immediate thought is, what's the rationale? Why the `block/` prefix specifically? Are we trying to segregate a particular set of routes or resources? Is this for internal tooling, a staging area, or a versioning strategy? It's important to consider the implications on existing routes. Does this introduce conflicts? Will it break anything in production?
I need to quickly assess the impact on downstream systems. This will involve understanding the current routing logic, looking for hardcoded URIs, and considering how the change affects internal services or clients. How is this prefix going to affect reverse proxies or load balancers, if any are involved?
We should determine what aspects of the existing requests need to be accounted for, to prevent unexpected errors. Will we need to modify the request path, or will the routing logic simply strip off the `block/` portion? Do we have logging in place to trace these requests and the change? If not, we should determine whether such features should be deployed.
In summary, before I make a decision, I need to know the why, and thoroughly analyze the what and the how. A quick addition like this could have rippling effects, so a careful impact assessment and testing plan is paramount.
|
| 580/2 |
2026/11/03 22:58 |
tool |
git-log |
0m
Args: map[CodeRegexp:mq_freeze_disk_dead PathPrefix:block]
Results: map[Output:6f491a8d4b92 block: track disk DEAD state automatically for modeling queue freeze lockdep
]
|
| 581/2 |
2026/11/03 22:58 |
llm |
fixes-finder |
2m
Model:
Tokens:
input: 13396
output: 27
thoughts: 72
Thoughts: Okay, let me think this through.
**Analyzing Potential Root Causes**
Hmm, only a single commit references `mq_freeze_disk_dead` within this `block` context? That seems unusual. Before jumping to conclusions, let's broaden the net. I should also investigate `mq_freeze_queue_dying`, as that could be related to the same underlying issue. Or, perhaps there's a different commit that covers this area. It's best to be thorough.
Let's go back and check commit `6f491a8d4b92` in particular. This may contain the key information I need.
|
| 582/2 |
2026/11/03 23:00 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 6f491a8d4b92d1a840fd9209cba783c84437d0b7
Author: Ming Lei <ming.lei@redhat.com>
Date: Wed Nov 27 21:51:28 2024 +0800
block: track disk DEAD state automatically for modeling queue freeze lockdep
Now we only verify the outmost freeze & unfreeze in current context in case
that !q->mq_freeze_depth, so it is reliable to save disk DEAD state when
we want to lock the freeze queue since the state is one per-task variable
now.
Doing this way can kill lots of false positive when freeze queue is
called before adding disk[1].
[1] https://lore.kernel.org/linux-block/6741f6b2.050a0220.1cc393.0017.GAE@google.com/
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241127135133.3952153-3-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 60f457f62913..0c6a319fb936 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -131,6 +131,9 @@ static bool blk_freeze_set_owner(struct request_queue *q,
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
+ q->mq_freeze_disk_dead = !q->disk ||
+ test_bit(GD_DEAD, &q->disk->state) ||
+ !blk_queue_registered(q);
return true;
}
@@ -187,7 +190,7 @@ bool __blk_freeze_queue_start(struct request_queue *q,
void blk_freeze_queue_start(struct request_queue *q)
{
if (__blk_freeze_queue_start(q, current))
- blk_freeze_acquire_lock(q, false, false);
+ blk_freeze_acquire_lock(q, false);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -235,7 +238,7 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
void blk_mq_unfreeze_queue(struct request_queue *q)
{
if (__blk_mq_unfreeze_queue(q, false))
- blk_unfreeze_release_lock(q, false, false);
+ blk_unfreeze_release_lock(q, false);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
diff --git a/block/blk.h b/block/blk.h
index 2c26abf505b8..8708168d50e4 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -720,22 +720,29 @@ void blk_integrity_verify(struct bio *bio);
void blk_integrity_prepare(struct request *rq);
void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
-static inline void blk_freeze_acquire_lock(struct request_queue *q, bool
- disk_dead, bool queue_dying)
+#ifdef CONFIG_LOCKDEP
+static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
{
- if (!disk_dead)
+ if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
if (!queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q, bool
- disk_dead, bool queue_dying)
+static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
{
if (!queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
- if (!disk_dead)
+ if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
+#else
+static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
+{
+}
+static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
+{
+}
+#endif
#endif /* BLK_INTERNAL_H */
diff --git a/block/elevator.c b/block/elevator.c
index 7c3ba80e5ff4..ca0a74369f1c 100644
--- a/block/elevator.c
+++ b/block/elevator.c
@@ -602,14 +602,14 @@ void elevator_init_mq(struct request_queue *q)
* Disk isn't added yet, so verifying queue lock only manually.
*/
blk_freeze_queue_start_non_owner(q);
- blk_freeze_acquire_lock(q, true, false);
+ blk_freeze_acquire_lock(q, false);
blk_mq_freeze_queue_wait(q);
blk_mq_cancel_work_sync(q);
err = blk_mq_init_sched(q, e);
- blk_unfreeze_release_lock(q, true, false);
+ blk_unfreeze_release_lock(q, false);
blk_mq_unfreeze_queue_non_owner(q);
if (err) {
diff --git a/block/genhd.c b/block/genhd.c
index 79230c109fca..59ac299909b3 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -692,7 +692,7 @@ void del_gendisk(struct gendisk *disk)
start_drain = __blk_mark_disk_dead(disk);
queue_dying = blk_queue_dying(q);
if (start_drain)
- blk_freeze_acquire_lock(q, true, queue_dying);
+ blk_freeze_acquire_lock(q, queue_dying);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
@@ -748,7 +748,7 @@ void del_gendisk(struct gendisk *disk)
blk_mq_exit_queue(q);
if (start_drain)
- blk_unfreeze_release_lock(q, true, queue_dying);
+ blk_unfreeze_release_lock(q, queue_dying);
}
EXPORT_SYMBOL(del_gendisk);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 378d3a1a22fc..522cf8eef66c 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -581,6 +581,8 @@ struct request_queue {
#ifdef CONFIG_LOCKDEP
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
+ /* Records disk state in current context, used in unfreeze queue */
+ bool mq_freeze_disk_dead;
#endif
wait_queue_head_t mq_freeze_wq;
/*
]
|
| 583/2 |
2026/11/03 23:00 |
llm |
fixes-finder |
3m
Model:
Tokens:
input: 15787
output: 32
thoughts: 79
Thoughts: Okay, let's dive into this code.
**Investigating a Recent Kernel Change**
Alright, I need to understand what's happening with commit `6f491a8d4b92`. Interesting. But hang on, I also see this `mq_freeze_queue_dying` function call was introduced around the same time. This suggests a potential connection, so I can't just isolate one change. It's almost certain there's a reason for it!
Given the commit ID, I'll focus my attention on examining the changes around `6f491a8d4b92` that were submitted by Ming Lei. It's likely that his work holds the key to the context for this addition.
To be thorough, and to get a broader view, I will search the git-log to see the other commits related to `mq_freeze_queue_dying`. This search should highlight other dependent commits and give context to understand the motivation behind the addition. This should give me the broader understanding I need to continue my work.
|
| 584/2 |
2026/11/03 23:04 |
tool |
git-log |
0m
Args: map[CodeRegexp:mq_freeze_queue_dying PathPrefix:block]
Results: map[Output:f6661b1d0525 block: track queue dying state automatically for modeling queue freeze lockdep
]
|
| 585/2 |
2026/11/03 23:05 |
llm |
fixes-finder |
2m
Model:
Tokens:
input: 16165
output: 27
thoughts: 36
Thoughts: Okay, here's my interpretation of those thoughts, tailored for an expert audience, and delivered as a first-person internal monologue:
**Commit Inspection: `f6661b1d0525`**
Right, that's it. Time to push `f6661b1d0525`! I've confirmed everything locally, ran the quick checks, and it's time to merge this. Let's get this integration tested and deployed! Now, let's take a look at `f6661b1d0525`. Gotta be sure it all looks good. I want to dive into the specifics of this commit and ensure there are no surprises before I sign off. I need to make sure I completely understand the change, its potential impact, and if there are any subtle side effects I haven't yet considered. Time to review the diff carefully, line by line.
|
| 586/2 |
2026/11/03 23:07 |
tool |
git-show |
0m
Args:
Results: map[Output:commit f6661b1d0525f3764596a1b65eeed9e75aecafa7
Author: Ming Lei <ming.lei@redhat.com>
Date: Wed Nov 27 21:51:30 2024 +0800
block: track queue dying state automatically for modeling queue freeze lockdep
Now we only verify the outmost freeze & unfreeze in current context in case
that !q->mq_freeze_depth, so it is reliable to save queue lying state when
we want to lock the freeze queue since the state is one per-task variable
now.
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241127135133.3952153-5-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 0c6a319fb936..fca2ec64a06b 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -134,6 +134,7 @@ static bool blk_freeze_set_owner(struct request_queue *q,
q->mq_freeze_disk_dead = !q->disk ||
test_bit(GD_DEAD, &q->disk->state) ||
!blk_queue_registered(q);
+ q->mq_freeze_queue_dying = blk_queue_dying(q);
return true;
}
@@ -190,7 +191,7 @@ bool __blk_freeze_queue_start(struct request_queue *q,
void blk_freeze_queue_start(struct request_queue *q)
{
if (__blk_freeze_queue_start(q, current))
- blk_freeze_acquire_lock(q, false);
+ blk_freeze_acquire_lock(q);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -238,7 +239,7 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
void blk_mq_unfreeze_queue(struct request_queue *q)
{
if (__blk_mq_unfreeze_queue(q, false))
- blk_unfreeze_release_lock(q, false);
+ blk_unfreeze_release_lock(q);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
diff --git a/block/blk.h b/block/blk.h
index 8708168d50e4..cbf6a676ffe9 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -721,26 +721,26 @@ void blk_integrity_prepare(struct request *rq);
void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
#ifdef CONFIG_LOCKDEP
-static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
- if (!queue_dying)
+ if (!q->mq_freeze_queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
- if (!queue_dying)
+ if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
#else
-static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
}
#endif
diff --git a/block/genhd.c b/block/genhd.c
index 59ac299909b3..5678194b6b1a 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -661,7 +661,7 @@ void del_gendisk(struct gendisk *disk)
struct request_queue *q = disk->queue;
struct block_device *part;
unsigned long idx;
- bool start_drain, queue_dying;
+ bool start_drain;
might_sleep();
@@ -690,9 +690,8 @@ void del_gendisk(struct gendisk *disk)
*/
mutex_lock(&disk->open_mutex);
start_drain = __blk_mark_disk_dead(disk);
- queue_dying = blk_queue_dying(q);
if (start_drain)
- blk_freeze_acquire_lock(q, queue_dying);
+ blk_freeze_acquire_lock(q);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
@@ -748,7 +747,7 @@ void del_gendisk(struct gendisk *disk)
blk_mq_exit_queue(q);
if (start_drain)
- blk_unfreeze_release_lock(q, queue_dying);
+ blk_unfreeze_release_lock(q);
}
EXPORT_SYMBOL(del_gendisk);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 522cf8eef66c..5d40af2ef971 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -581,8 +581,12 @@ struct request_queue {
#ifdef CONFIG_LOCKDEP
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
- /* Records disk state in current context, used in unfreeze queue */
+ /*
+ * Records disk & queue state in current context, used in unfreeze
+ * queue
+ */
bool mq_freeze_disk_dead;
+ bool mq_freeze_queue_dying;
#endif
wait_queue_head_t mq_freeze_wq;
/*
]
|
| 587/2 |
2026/11/03 23:07 |
llm |
fixes-finder |
1m
Model:
Tokens:
input: 18317
output: 35
thoughts: 200
Thoughts: Okay, let's dive into this. Here's my thought process on this commit analysis:
**Analyzing Potential Regression in Block Layer**
Alright, that commit `f6661b1d0525` is flagged. My first instinct is to immediately dig deeper. I'm not just going to take this commit in isolation. I need the full context β the entire series of patches that led up to it. So, I'm going to run a `git-blame` on the relevant section and get the bigger picture. I'll need to use either git-blame or gather the entire series of commits around that one.
Okay, let's see. The commit itself, `f6661b1d0525`, is titled "block: track queue dying state automatically for modeling queue freeze lockdep" and the link points to a lore.kernel.org thread. This screams something to do with block device queue management and lockdep, which means concurrency issues and potential deadlocks. This sounds interesting.
I need the surrounding commits, now. I'll need to pull up git-log, perhaps with a date range like "Since=2024-11-20" or something and a regex based on the message content. That will give me the entire commit series and hopefully reveal the original problem, the proposed solution, and any potential side effects. Getting all the commits in the series will paint the bigger picture. Then I can determine where the regression might have come from.
|
| 588/2 |
2026/11/03 23:09 |
tool |
git-log |
0m
Args: map[Count:10 PathPrefix:block/blk-mq.c Since:6 months]
Results: map[Output:4fcc499ea9bc blk-mq: set up a queue under tag_list_lock
89a2381482d8 blk-mq: exit the hctxs of a queue under tag_list_lock
71ec3c7d6db8 blk-mq: quiesce a queue that joins a quiesced tag set
0db9f8968a89 blk-mq: don't forget a timer the driver has restarted
9531230ee1fc blk-mq: don't bring back flags of a completed request
620cfc7a6642 blk-mq: keep sharing tags fairly after a queue update
24974185999f blk-mq: don't trust the cookie in blk_mq_poll()
afc1de47a7ab blk-mq: clear stale inactive flag on hctx reuse
5f702d4bd61b blk-mq: drop the tag_set argument from blk_mq_free_rq_map/tags
e1c51edd6a57 blk-mq: share one tags_srcu instance across all tag sets
]
|
| 589/2 |
2026/11/03 23:09 |
llm |
fixes-finder |
2m
Model:
Tokens:
input: 19167
output: 43
thoughts: 23
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Analyzing the Commit Log**
Alright, my internal process is focusing in. I need to drill down into the commit log, centering on that particular SHA: `f6661b1d0525`. My initial aim is to understand the *what*, the *why*, and the *implications* of the changes introduced at that point. I'm not just looking for the diff; I'm trying to reconstruct the development context. I'll be sifting through the surrounding commits as well, of course, to see the chronological flow and surrounding decisions that led to that specific point. I'm looking for clues about the original intent, any potential bugs introduced, and how that commit fits into the overall architecture. I'll need to assess its impact on any relevant dependencies and consider its effect on any existing operational parameters. My expertise lets me analyze the context behind this and understand the ripple effect.
|
| 590/2 |
2026/11/03 23:11 |
tool |
git-log |
0m
Error:
Args: map[Count:10 PathPrefix:block/blk-mq.c Since:2024-11-20]
Results:
|
| 591/2 |
2026/11/03 23:11 |
llm |
fixes-finder |
2m
Model:
Tokens:
input: 19474
output: 37
thoughts: 48
Thoughts: Here's my analysis of the request, assuming I'm an expert:
**Investigating Block Layer Freezing Behavior**
Okay, so I need to dig into the `blk-mq.c` file within the block layer, specifically around commit `f6661b1d0525`. The key here is to understand the changes related to the "blk_freeze_set_owner" function, and I'm asking for a look back at the commit log with a limited scope. My intent is clear: I want the last 10 commits, identified by `Count=10`, around that specific commit ID. The filtering criteria is precise. I'm using `CodeRegexp="blk_freeze_set_owner"` to focus the output on code changes which include that function name. This means I want to see the introduction, modification, or removal of *that specific function* as it relates to freezing operations within the block multi-queue (blk-mq) subsystem. I anticipate this will reveal context around the freezing logic, likely highlighting how the ownership for freezing blocks is handled. This is likely related to debugging a freezing or deadlock issue. It's a targeted query to understand the recent history of this crucial function.
|
| 592/2 |
2026/11/03 23:14 |
tool |
git-log |
0m
Args: map[CodeRegexp:blk_freeze_set_owner PathPrefix:block/blk-mq.c]
Results: map[Output:6a78699838a0 block: always verify unfreeze lock on the owner task
]
|
| 593/2 |
2026/11/03 23:14 |
llm |
fixes-finder |
3m
Model:
Tokens:
input: 19855
output: 27
thoughts: 38
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:
**Initializing a Git Checkpoint**
Right, let's nail down this version. I'm going to commit this particular state; `6a78699838a0` it is. No mucking about, just commit it. I trust the state is good.
Now, before moving on, I need to verify what this checkpoint actually *is*. Let's quickly double-check that commit with `git-show 6a78699838a0`. Itβs a habit. I need to be absolutely certain I understand the context, the changes in that snapshot, before I go any further, especially if I'm planning to base anything else on it. A quick `git-show` will refresh my memory, confirm the files affected, the commit message, and any parent commits. Make sure it's the right one.
|
| 594/2 |
2026/11/03 23:17 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 6a78699838a0ddeed3620ddf50c1521f1fe1e811
Author: Ming Lei <ming.lei@redhat.com>
Date: Thu Oct 31 21:37:19 2024 +0800
block: always verify unfreeze lock on the owner task
commit f1be1788a32e ("block: model freeze & enter queue as lock for
supporting lockdep") tries to apply lockdep for verifying freeze &
unfreeze. However, the verification is only done the outmost freeze and
unfreeze. This way is actually not correct because q->mq_freeze_depth
still may drop to zero on other task instead of the freeze owner task.
Fix this issue by always verifying the last unfreeze lock on the owner
task context, and make sure both the outmost freeze & unfreeze are
verified in the current task.
Fixes: f1be1788a32e ("block: model freeze & enter queue as lock for supporting lockdep")
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241031133723.303835-4-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-core.c b/block/blk-core.c
index 09d10bb95fda..4f791a3114a1 100644
--- a/block/blk-core.c
+++ b/block/blk-core.c
@@ -287,7 +287,7 @@ bool blk_queue_start_drain(struct request_queue *q)
* entering queue, so we call blk_freeze_queue_start() to
* prevent I/O from crossing blk_queue_enter().
*/
- bool freeze = __blk_freeze_queue_start(q);
+ bool freeze = __blk_freeze_queue_start(q, current);
if (queue_is_mq(q))
blk_mq_wake_waiters(q);
/* Make blk_queue_enter() reexamine the DYING flag. */
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 5f4496220432..5e240a4b6be0 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -120,20 +120,66 @@ void blk_mq_in_flight_rw(struct request_queue *q, struct block_device *part,
inflight[1] = mi.inflight[1];
}
-bool __blk_freeze_queue_start(struct request_queue *q)
+#ifdef CONFIG_LOCKDEP
+static bool blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
{
- int freeze;
+ if (!owner)
+ return false;
+
+ if (!q->mq_freeze_depth) {
+ q->mq_freeze_owner = owner;
+ q->mq_freeze_owner_depth = 1;
+ return true;
+ }
+
+ if (owner == q->mq_freeze_owner)
+ q->mq_freeze_owner_depth += 1;
+ return false;
+}
+
+/* verify the last unfreeze in owner context */
+static bool blk_unfreeze_check_owner(struct request_queue *q)
+{
+ if (!q->mq_freeze_owner)
+ return false;
+ if (q->mq_freeze_owner != current)
+ return false;
+ if (--q->mq_freeze_owner_depth == 0) {
+ q->mq_freeze_owner = NULL;
+ return true;
+ }
+ return false;
+}
+
+#else
+
+static bool blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
+{
+ return false;
+}
+
+static bool blk_unfreeze_check_owner(struct request_queue *q)
+{
+ return false;
+}
+#endif
+
+bool __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner)
+{
+ bool freeze;
mutex_lock(&q->mq_freeze_lock);
+ freeze = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
if (queue_is_mq(q))
blk_mq_run_hw_queues(q, false);
- freeze = true;
} else {
mutex_unlock(&q->mq_freeze_lock);
- freeze = false;
}
return freeze;
@@ -141,7 +187,7 @@ bool __blk_freeze_queue_start(struct request_queue *q)
void blk_freeze_queue_start(struct request_queue *q)
{
- if (__blk_freeze_queue_start(q))
+ if (__blk_freeze_queue_start(q, current))
blk_freeze_acquire_lock(q, false, false);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -170,7 +216,7 @@ EXPORT_SYMBOL_GPL(blk_mq_freeze_queue);
bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
- int unfreeze = false;
+ bool unfreeze;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
@@ -180,8 +226,8 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
if (!q->mq_freeze_depth) {
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
- unfreeze = true;
}
+ unfreeze = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
return unfreeze;
@@ -203,7 +249,7 @@ EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
*/
void blk_freeze_queue_start_non_owner(struct request_queue *q)
{
- __blk_freeze_queue_start(q);
+ __blk_freeze_queue_start(q, NULL);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start_non_owner);
diff --git a/block/blk.h b/block/blk.h
index ac48b79cbf80..57fc035620d6 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -37,7 +37,8 @@ void blk_free_flush_queue(struct blk_flush_queue *q);
bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
bool blk_queue_start_drain(struct request_queue *q);
-bool __blk_freeze_queue_start(struct request_queue *q);
+bool __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner);
int __bio_queue_enter(struct request_queue *q, struct bio *bio);
void submit_bio_noacct_nocheck(struct bio *bio);
void bio_await_chain(struct bio *bio);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 93551772c1d6..1b51a7c92e9b 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -575,6 +575,10 @@ struct request_queue {
struct throtl_data *td;
#endif
struct rcu_head rcu_head;
+#ifdef CONFIG_LOCKDEP
+ struct task_struct *mq_freeze_owner;
+ int mq_freeze_owner_depth;
+#endif
wait_queue_head_t mq_freeze_wq;
/*
* Protect concurrent access to q_usage_counter by
]
|
| 595/2 |
2026/11/03 23:17 |
llm |
fixes-finder |
1m
Model:
Tokens:
input: 22384
output: 41
thoughts: 134
Thoughts: **Investigating the Commit History**
Okay, so I need to understand the evolution of this code. My first thought is to pinpoint specific commits to get a sense of the changes β specifically, 6a78699838a0, 6f491a8d4b92, and f6661b1d0525. I want to see a snapshot before that first commit, and then examine the specific impact of the other two.
However, I think it will be more efficient and illuminating to understand the scope of changes more broadly. I think it would be smarter to analyze the commit history *between* 6a78699838a0 and f6661b1d0525. My plan is to use `git log` to get a condensed, one-line view of the commits within that range. Specifically, I'll leverage the `..` range operator with the `--oneline` flag for a concise overview. The command I'll execute is `git log 6a78699838a0^..f6661b1d0525 --oneline`. This should provide the information I need to understand the intervening changes.
|
| 596/2 |
2026/11/03 23:19 |
tool |
git-log |
0m
Args: map[CodeRegexp:.* Count:20 PathPrefix:block/blk.h Since:2 years]
Results: map[Output:9531230ee1fc blk-mq: don't bring back flags of a completed request
0687c9c346ac block: fail zone management operations to read-only and offline zones
b539aeacf8cc block: rename bi_bvec_done
691b052139c9 block: fix race in blk_time_get_ns() returning 0
3dd63dba8f9c block: avoid potential deadlock on zone revalidation failure
9b0c3673c885 block: check bio split for unaligned bvec
d39a63ead381 block: add a str_to_blk_op helper
ce351560b714 block: add a "tag" for block status codes
5bdb8ec58b54 block: propagate in_flight to whole disk on partition I/O
131f14125a18 block/blk-mq-debugfs: Improve lock context annotations
82aaa55a3162 block: unexport blk_status_to_str
41c665aae2b5 block: relax pgmap check in bio_add_page for compatible zone device pages
13920e4b7b78 block: add pgmap check to biovec_phys_mergeable
92c3737a2473 block: add a bio_submit_or_kill helper
fed406f3c1c2 block: mark bvec_{alloc,free} static
3f00626832a9 block: prepare generation / verification helpers for fs usage
dfe48ea17973 blk-mq: use NOIO context to prevent deadlock during debugfs creation
ee81212f74a5 block: decouple secure erase size limit from discard size limit
301f5356521e block: remove bio_release_page
f7ba87dfa8e4 block: account for bi_bvec_done in bio_may_need_split()
]
|
| 597/2 |
2026/11/03 23:19 |
llm |
fixes-finder |
1m
Model:
Tokens:
input: 23328
output: 33
thoughts: 85
Thoughts: Here's my thought process, as it stands:
**Exploring Git History for Relevant Commit Information**
Okay, so I'm thinking about the most efficient way to dig into the history of this particular commit, `f6661b1d0525`. My immediate instincts lean toward leveraging the power of `git-log` with some `MessageRegexps` to extract what I need. That's usually my go-to for filtering and finding patterns within commit messages.
But, I also know I can navigate parent commits directly using `git-show`. This is often easier for a quick check. I'll probably want to see the immediate parents of `f6661b1d0525`: `f6661b1d0525~1`, then potentially further back to `f6661b1d0525~2`, and so on, depending on the context. I'll weigh the options of regex filtering within `git-log` vs. the more direct approach of iterative `git-show` calls to quickly get the data I need. The right approach depends on the depth of the history I need to explore, and the specificity of the search criteria.
|
| 598/2 |
2026/11/03 23:21 |
tool |
git-show |
0m
Args: map[Commit:f6661b1d0525~1 Stat:true]
Results: map[Output:commit b9d4eee7e04b9cfb0b4bcd748fe6b3ec517171d9
Author: Ming Lei <ming.lei@redhat.com>
Date: Wed Nov 27 21:51:29 2024 +0800
block: don't verify queue freeze manually in elevator_init_mq()
Now blk_freeze_queue_start() can track disk state automatically, and
it isn't necessary to verify queue freeze manually in elevator_init_mq()
any more.
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241127135133.3952153-4-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
block/elevator.c | 7 ++-----
1 file changed, 2 insertions(+), 5 deletions(-)
]
|
| 599/2 |
2026/11/03 23:21 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 23975
output: 33
thoughts: 274
Thoughts: **Analyzing a Kernel Patch Series**
Okay, let's take a look at this series. Here's the link: [https://lore.kernel.org/r/20241127135133.3952153-5-ming.lei@redhat.com]. I need to quickly get a sense of what's going on. First, I'll identify the commits associated with the individual patches.
Alright, patch 5 is `f6661b1d0525` and it corresponds to the message "20241127135133.3952153-5-ming.lei@redhat.com".
Patch 4 is `b9d4eee7e04b` and its commit message is "20241127135133.3952153-4-ming.lei@redhat.com".
We've got Patch 3 as `6f491a8d4b92` and its message, "20241127135133.3952153-3-ming.lei@redhat.com".
To get the context, I'll need to look at patches 1 and 2, which are the ones before the one I started with. I'll get those by going back two and three commits from the fifth patch. That's `f6661b1d0525~3` and `f6661b1d0525~4`. Now I have a complete picture of the patchset's evolution.
|
| 600/2 |
2026/11/03 23:22 |
tool |
git-show |
0m
Args: map[Commit:f6661b1d0525~3 Stat:true]
Results: map[Output:commit aff09dc1fd3a165289011ab23cc3b46978ec741c
Author: Ming Lei <ming.lei@redhat.com>
Date: Wed Nov 27 21:51:27 2024 +0800
block: remove unnecessary check in blk_unfreeze_check_owner()
The following check of 'q->mq_freeze_owner != current' covers the
previous one, so remove the unnecessary check.
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241127135133.3952153-2-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
block/blk-mq.c | 2 --
1 file changed, 2 deletions(-)
]
|
| 601/2 |
2026/11/03 23:22 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 24912
output: 33
thoughts: 20
Thoughts: Okay, here's my interpretation of "Let's see `f6661b1d0525~4`", tailored for an expert audience, as if it were my thought process:
**Decoding the Identifier**
Alright, that's interesting. "Let's see `f6661b1d0525~4`". My immediate assumption, given the context, is that we're dealing with a unique identifier of some kind. The structure strongly suggests a common pattern I've encountered countless times. The alphanumeric sequence "f6661b1d0525" likely represents a hash, UUID, or a similar cryptographic fingerprint. The "~4" trailing bit seems highly suggestive. Could be a version number, revision, counter, or an offset depending on what the hash maps to.
My mind immediately begins to parse potential contexts. Is it a database record ID? A commit hash in a version control system? A file identifier within a content-addressable storage system? A key within a distributed ledger? The specific application strongly influences the interpretation.
I'd want to understand the system it derives from to understand its meaning. Is it associated with any metadata or documentation? Is there a known algorithm or structure? Can I assume it's an MD5, SHA-256, or something else entirely? Could the trailing "~4" be significant for deduplication or partial retrieval? I'm already formulating questions to understand this object's place in the broader landscape. I'd love to examine the surrounding text, the system it resides in, and any context or metadata that may shed light on its meaning.
|
| 602/2 |
2026/11/03 23:22 |
tool |
git-show |
0m
Args: map[Commit:f6661b1d0525~4 Stat:true]
Results: map[Output:commit 4bbf9020becbfd8fc2c3da790855b7042fad455b
Author: Linus Torvalds <torvalds@linux-foundation.org>
Date: Sun Dec 22 13:22:21 2024 -0800
Linux 6.13-rc4
Makefile | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
]
|
| 603/2 |
2026/11/03 23:22 |
llm |
fixes-finder |
1m
Model:
Tokens:
input: 25440
output: 30
thoughts: 109
Thoughts: **Tracking Down a Specific Patch**
Okay, so `f6661b1d0525`... that's patch number 5 in that sequence, right? Gotta be sure. Hmm, did a patch 6 exist? Let's figure this out. I need to see what happened after `f6661b1d0525` up to `HEAD`. I'll use `git log` and see if I can spot any related commits, checking the children of that commit might work too. Oh wait, thinking about this... I need a more reliable way to identify it: let me try a `git log` with MessageRegexps based on that commit message, specifically looking for commits that include "3952153-". That should narrow it down quickly.
|
| 604/2 |
2026/11/03 23:23 |
tool |
git-log |
0m
Args: map[Count:10 MessageRegexps:[3952153-]]
Results: map[Output:f6661b1d0525 block: track queue dying state automatically for modeling queue freeze lockdep
b9d4eee7e04b block: don't verify queue freeze manually in elevator_init_mq()
6f491a8d4b92 block: track disk DEAD state automatically for modeling queue freeze lockdep
aff09dc1fd3a block: remove unnecessary check in blk_unfreeze_check_owner()
]
|
| 605/2 |
2026/11/03 23:24 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 25868
output: 30
thoughts: 240
Thoughts: **Analyzing a Patch Series**
Okay, first things first, I need to figure out where we're at in this patch series. Hold on... where's the initial patch, patch 1? Or was the first one some sort of cover letter, maybe? Hmm, let's see... looking at the Message-ID, specifically `20241127135133.3952153-1-...`, yeah, that confirms it: the `-1` indicates this is probably the cover letter. And if I recall correctly, `3952153-2` would be patch 1.
Alright, so the commits, in order are: patch 2: `aff09dc1fd3a`, patch 3: `6f491a8d4b92`, patch 4: `b9d4eee7e04b`, and patch 5: `f6661b1d0525`. Got it.
But hold on, before I dive into these, let's see what *followed* patch 5, just to get a broader context of what changes might have landed after this series. Let's see... I'll check commits that modify `block/blk-mq.c` after `f6661b1d0525`. And while I'm at it, I'll search for commits with "freeze" or "lockdep" in the `block/` directory to see if there are related changes. That could give me some valuable insight into potential conflicts or interactions.
|
| 606/2 |
2026/11/03 23:24 |
tool |
git-log |
0m
Args: map[Count:20 MessageRegexps:[freeze] PathPrefix:block]
Results: map[Output:c84de57efe88 super: convert to plain hashtable
e14c3379be86 block: Fix the thaw_bdev reference in bdev_freeze() kernel-doc
4ff58d6bc9dd block: serialize elevator changes for the same queue using a writer lock
3dd63dba8f9c block: avoid potential deadlock on zone revalidation failure
822d87bc520f block: split bdev_yield_claim() out of bdev_fput()
ea4e4cc26301 block: allow making a block device unfreezable
dc278e9bf2b9 blk-mq: pop cached request if it is usable
539d1b47e935 block: break pcpu_alloc_mutex dependency on freeze_lock
07a1bc5c14c9 block: Fix an error path in disk_update_zone_resources()
59e25ef2b413 block: Use RCU in blk_mq_[un]quiesce_tagset() instead of set->tag_list_lock
89e1fb7ceffd blk-mq: fix potential uaf for 'queue_hw_ctx'
935a20d1bebf block: Remove queue freezing from several sysfs store callbacks
d4c3ef56a161 block: define alloc_sched_data and free_sched_data methods for kyber
0315476e78c0 block: use {alloc|free}_sched data methods
61019afdf6ac block: introduce alloc_sched_data and free_sched_data elevator methods
bba4322e3f30 block: freeze queue when updating zone resources
5d726c4dbeed blk-cgroup: fix possible deadlock while configuring policy
b86433721f46 blk-mq: fix potential deadlock while nr_requests grown
626ff4f8ebcb blk-mq: convert to serialize updating nr_requests with update_nr_hwq_lock
8bd7195fea6d blk-mq: remove useless checkings in blk_mq_update_nr_requests()
]
|
| 607/2 |
2026/11/03 23:25 |
llm |
fixes-finder |
1m
Model:
Tokens:
input: 27016
output: 32
thoughts: 27
Thoughts: Here's my thought process, summarized as you requested:
**Investigating Block Device Freeze/Unfreeze Behavior**
Okay, so I need to dig into the recent changes related to block device freezing and unfreezing. Specifically, I'm interested in understanding how `blk_unfreeze_release_lock` and `blk_freeze_acquire_lock` are being used and potentially how they've changed. This likely indicates where contention or other issues might be. Given my expertise, I suspect this line of investigation might lead me to performance bottlenecks, subtle locking bugs, or potential race conditions within the block layer's freeze/thaw mechanisms. Therefore, let's start by searching the commit history for any code modifications touching those specific functions. This should give me a good jumping-off point.
|
| 608/2 |
2026/11/03 23:26 |
tool |
git-log |
0m
Args: map[CodeRegexp:blk_unfreeze_release_lock PathPrefix:block]
Results: map[Output:f6661b1d0525 block: track queue dying state automatically for modeling queue freeze lockdep
b9d4eee7e04b block: don't verify queue freeze manually in elevator_init_mq()
6f491a8d4b92 block: track disk DEAD state automatically for modeling queue freeze lockdep
357e1b7f730b block: don't verify IO lock for freeze/unfreeze in elevator_init_mq()
f1be1788a32e block: model freeze & enter queue as lock for supporting lockdep
]
|
| 609/2 |
2026/11/03 23:26 |
llm |
fixes-finder |
1m
Model:
Tokens:
input: 27391
output: 31
thoughts: 199
Thoughts: Okay, let's see. I need to get a handle on the recent changes related to `blk_unfreeze_release_lock`. Right, let's use `git log` and find all commits matching that string. Aha, I see five relevant commits: `f6661b1d0525`, `b9d4eee7e04b`, `6f491a8d4b92`, `357e1b7f730b`, and `f1be1788a32e`. These seem to be addressing various aspects of queue freezing and unlocking, likely related to lockdep and proper state tracking. I'm seeing changes around automatic state tracking for queue dying and disk DEAD states, and removal of some manual verifications of the freeze/unfreeze state, likely for performance and conciseness. `f1be1788a32e` is interesting; it mentions modeling freeze and queue entry as a lock. This sounds like an important step in improving the locking model.
**Next Steps and Further Investigation**
Hold on, I should probably also examine the commits related to `blk_queue_start_drain` in `block/blk-core.c`. Let's run a `git log` on that file with a CodeRegexp search for that specific function. This would give me a wider view of related changes. Understanding that function is probably going to be important to seeing the overall picture.
|
| 610/2 |
2026/11/03 23:27 |
tool |
git-log |
0m
Args: map[CodeRegexp:blk_queue_start_drain PathPrefix:block]
Results: map[Output:f1be1788a32e block: model freeze & enter queue as lock for supporting lockdep
66fddc25fe18 block: consolidate the shutdown logic in blk_mark_disk_dead and del_gendisk
6f8191fdf41d block: simplify disk shutdown
7a5428dcb790 block: fix surprise removal for drivers calling blk_set_queue_dying
8e141f9eb803 block: drain file system I/O on del_gendisk
]
|
| 611/2 |
2026/11/03 23:27 |
llm |
fixes-finder |
1m
Model:
Tokens:
input: 28076
output: 26
thoughts: 4093
Thoughts: **Root Cause Analysis and the Evolution of Queue Freeze Lock Handling**
Okay, let's break this down. My initial instinct is to dig into the code, starting with those commit IDs (`f6661b1d0525`, `6f491a8d4b92`, `6a78699838a0`, and `f1be1788a32e`). The core of the problem, as I understand it from the description, centers around how the block layer handles queue freezing and lockdep tracking, specifically in relation to device removal and concurrent operations. I see it mentions a `WARNING: lock held when returning to user space!`, specifically related to the `q->q_usage_counter(queue)` which is the lockdep map `q->q_lockdep_map`. This is triggered by a race between DM_TABLE_LOAD, initializing a request-based DM queue/gendisk, and DM_DEV_REMOVE, destroying the same DM device. The root cause is a race condition in the block layer's queue-freeze lockdep tracking. I need to understand why this is happening.
Let's read the explanation again. It emphasizes that flags like `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead` are stored as per-`request_queue` fields, protected by `q->mq_freeze_lock` when the freeze depth is 0. The crux of the issue lies in `blk_unfreeze_release_lock(q)` potentially reading these flags *outside* the protection of `q->mq_freeze_lock` after the depth has already been decremented to zero. This race condition leads to `blk_unfreeze_release_lock(q)` skipping the release of `q->q_lockdep_map`.
Now I need to understand the evolution of this code. What were the calls to `blk_freeze_acquire_lock` and `blk_unfreeze_release_lock` before commit `f6661b1d0525`? I suspect there's a key difference there. Let's look at the diff between `6f491a8d4b92` and `f6661b1d0525`.
Looking at `6f491a8d4b92`, I see that `blk_freeze_acquire_lock` and `blk_unfreeze_release_lock` took a `queue_dying` parameter. In `blk_freeze_queue_start`, `blk_freeze_acquire_lock(q, false)` was called. And in `blk_mq_unfreeze_queue`, `blk_unfreeze_release_lock(q, false)` was called! The `queue_dying` parameter was hardcoded to `false` in `blk_mq_unfreeze_queue`, which I believe is key to my analysis. It means this function did not even look at `q->mq_freeze_queue_dying`! And I need to verify that `q->mq_freeze_queue_dying` did not exist before `f6661b1d0525`.
Checking the diff of `f6661b1d0525` confirms it. `q->mq_freeze_queue_dying` was *introduced* in this commit. Before it only had `mq_freeze_disk_dead`, which was introduced in `6f491a8d4b92`.
Okay, now let's think about that specific crash in light of this information. The description says that `q->mq_freeze_queue_dying` is overwritten from `false` to `true` *before* `blk_unfreeze_release_lock(q)` runs, causing the lock release to be skipped. Could this have happened *before* `f6661b1d0525`? In the prior version, `blk_unfreeze_release_lock(q, false)` *always* released the lock as the `queue_dying` parameter was always false. Only `mq_freeze_disk_dead` had an influence. It could never be skipped, because the `queue_dying` parameter was always false. This confirms that the bug *cannot* be present before `f6661b1d0525`, because the code in `6f491a8d4b92` would always release the `q_lockdep_map`. This confirms the core of my assessment, this commit had an adverse effect.
I believe I see what Ming Lei was thinking when he wrote the commit message for `f66
|
| 612/2 |
2026/11/03 23:29 |
tool |
git-log |
0m
Args: map[Count:5 MessageRegexps:[freeze_lock_mask]]
Results:
|
| 613/2 |
2026/11/03 23:30 |
llm |
fixes-finder |
1m
Model:
Tokens:
input: 33233
output: 38
thoughts: 30
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:
**Investigating the Code with `git log` and a Specific Regex**
Alright, before diving too deep into this issue, I need to verify something quickly. I have a suspicion about this "mq_freeze_lock_mask" fix. I'm going to leverage `git log` to pinpoint when and where this was addressed. The goal is a quick audit to confirm the code fix I suspect is in place. Using `git log` with the CodeRegexp "mq_freeze_lock_mask" as a filter seems like the most direct approach. This should give me a concise list of commits that touch that specific piece of code and let me quickly determine if the commit is present. I'm after a rapid confirmation or denial of its inclusion in the codebase.
|
| 614/2 |
2026/11/03 23:31 |
tool |
git-log |
0m
Args: map[CodeRegexp:mq_freeze_lock_mask PathPrefix:include/linux/blkdev.h]
Results:
|
| 615/2 |
2026/11/03 23:31 |
llm |
fixes-finder |
1m
Model:
Tokens:
input: 33499
output: 36
thoughts: 47
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Analyzing the Proposed Bug Fix**
Right, so the fix isn't hidden away in some mysterious revision of the kernel tree itself β we're given the patch directly, which is *fantastic*. This means we can focus our energies on understanding the logic of the patch and where it's best applied in the source.
My immediate thought is to check the current code in `include/linux/blkdev.h`, specifically around line 637. That's a likely starting point because, given the context, that's almost certainly where the offending code β or at least its immediate context β resides. I need to understand the function definitions, data structures, and any surrounding conditional logic to fully grasp how this patch alters the behavior. This will let me assess its impact and potential side-effects with a degree of confidence. I'll be looking for interactions with any relevant struct members or function calls nearby. Let's dig in.
|
| 616/2 |
2026/11/03 23:32 |
tool |
read-file |
0m
Args: map[File:include/linux/blkdev.h FirstLine:630 LineCount:20]
Results: map[Contents: 630:
631: #ifdef CONFIG_BLK_DEV_THROTTLING
632: /* Throttle data */
633: struct throtl_data *td;
634: #endif
635: struct rcu_head rcu_head;
636: #ifdef CONFIG_LOCKDEP
637: struct task_struct *mq_freeze_owner;
638: int mq_freeze_owner_depth;
639: /*
640: * Records disk & queue state in current context, used in unfreeze
641: * queue
642: */
643: bool mq_freeze_disk_dead;
644: bool mq_freeze_queue_dying;
645: #endif
646: wait_queue_head_t mq_freeze_wq;
647: /*
648: * Protect concurrent access to q_usage_counter by
649: * percpu_ref_kill() and percpu_ref_reinit().
]
|
| 617/2 |
2026/11/03 23:32 |
llm |
fixes-finder |
1m
Model:
Tokens:
input: 34098
output: 36
thoughts: 31
Thoughts: Okay, let's dive into it.
**Examining `blkdev.h` with `git-blame`**
Alright, I need to understand the history of this particular section of the block device header. I'm going to pull up `git-blame` and focus on lines 640 to 645 in `include/linux/blkdev.h`. Knowing the specific lines I'm interested in allows me to immediately zoom in on the relevant code. This way I can determine who made the changes and, more importantly, *why* these lines exist in their current form. Was there a bug fix? An optimization? A feature addition? Understanding the context behind these lines will provide insight into the design decisions made within the block layer. Let's see what `git-blame` tells us!
|
| 618/2 |
2026/11/03 23:34 |
tool |
git-blame |
0m
Args: map[End:645 File:include/linux/blkdev.h Start:640]
Results: map[Output:f6661b1d0525f 640) * Records disk & queue state in current context, used in unfreeze
f6661b1d0525f 641) * queue
f6661b1d0525f 642) */
6f491a8d4b92d 643) bool mq_freeze_disk_dead;
f6661b1d0525f 644) bool mq_freeze_queue_dying;
6a78699838a0d 645) #endif
]
|
| 619/2 |
2026/11/03 23:34 |
llm |
fixes-finder |
1m
Model:
Tokens:
input: 34518
output: 35
thoughts: 133
Thoughts: Okay, let's break this down.
**Analyzing Recent Code Changes Related to Block Device Freezing**
I see, line 643, `mq_freeze_disk_dead`, and line 644, `mq_freeze_queue_dying`, were added. The first in commit `6f491a8d4b92d`, and the second in `f6661b1d0525f`. That's a clear starting point. Now, to understand the *implications* of these flags and how they interact with the freeze/unfreeze mechanisms, I need to delve into the core logic. Specifically, I'll need to examine where those flags are actually *used*.
My next step is to run a `git blame` on `block/blk-mq.c`, since that's where I know `blk_freeze_set_owner`, `__blk_mq_unfreeze_queue`, and `blk_unfreeze_release_lock` are defined. Those functions are the key to the freeze and unfreeze operations. I need to trace the call paths and understand what conditions trigger those functions. I'll need to see how these newly added flags, `mq_freeze_disk_dead` and `mq_freeze_queue_dying`, influence the freeze state and, most importantly, the system's resilience under disk failure scenarios.
|
| 620/2 |
2026/11/03 23:36 |
tool |
read-file |
0m
Args: map[File:block/blk-mq.c FirstLine:115 LineCount:40]
Results: map[Contents: 115: #ifdef CONFIG_LOCKDEP
116: static bool blk_freeze_set_owner(struct request_queue *q,
117: struct task_struct *owner)
118: {
119: if (!owner)
120: return false;
121:
122: if (!q->mq_freeze_depth) {
123: q->mq_freeze_owner = owner;
124: q->mq_freeze_owner_depth = 1;
125: q->mq_freeze_disk_dead = !q->disk ||
126: test_bit(GD_DEAD, &q->disk->state) ||
127: !blk_queue_registered(q);
128: q->mq_freeze_queue_dying = blk_queue_dying(q);
129: return true;
130: }
131:
132: if (owner == q->mq_freeze_owner)
133: q->mq_freeze_owner_depth += 1;
134: return false;
135: }
136:
137: /* verify the last unfreeze in owner context */
138: static bool blk_unfreeze_check_owner(struct request_queue *q)
139: {
140: if (q->mq_freeze_owner != current)
141: return false;
142: if (--q->mq_freeze_owner_depth == 0) {
143: q->mq_freeze_owner = NULL;
144: return true;
145: }
146: return false;
147: }
148:
149: #else
150:
151: static bool blk_freeze_set_owner(struct request_queue *q,
152: struct task_struct *owner)
153: {
154: return false;
]
|
| 621/2 |
2026/11/03 23:36 |
llm |
fixes-finder |
1m
Model:
Tokens:
input: 35555
output: 35
thoughts: 30
Thoughts: Here's a summary of my thought process, as requested:
**Diving into `blk-mq.c` with `git-blame`**
Okay, time to get my hands dirty with this `blk-mq.c` issue. I'm going to start by zeroing in on lines 115-148. That specific range suggests a particular area of concern, and `git-blame` is the perfect tool for unraveling the history there. I want to see who touched that code last, what their reasoning was at the time, and if any related commits or discussions shed light on the current behavior I'm observing. Getting the context from the commit messages is crucial to understand the "why" behind the code. I'm hoping to quickly identify the source of the problem, any relevant design decisions, and maybe even find clues to an existing workaround or fix within the commit history. Let's see what `git-blame` has to tell us.
|
| 622/2 |
2026/11/03 23:38 |
tool |
git-blame |
0m
Args: map[End:148 File:block/blk-mq.c Start:115]
Results: map[Output:6a78699838a0d 115) #ifdef CONFIG_LOCKDEP
6a78699838a0d 116) static bool blk_freeze_set_owner(struct request_queue *q,
6a78699838a0d 117) struct task_struct *owner)
43a5e4e21964a 118) {
6a78699838a0d 119) if (!owner)
6a78699838a0d 120) return false;
6a78699838a0d 121)
6a78699838a0d 122) if (!q->mq_freeze_depth) {
6a78699838a0d 123) q->mq_freeze_owner = owner;
6a78699838a0d 124) q->mq_freeze_owner_depth = 1;
6f491a8d4b92d 125) q->mq_freeze_disk_dead = !q->disk ||
6f491a8d4b92d 126) test_bit(GD_DEAD, &q->disk->state) ||
6f491a8d4b92d 127) !blk_queue_registered(q);
f6661b1d0525f 128) q->mq_freeze_queue_dying = blk_queue_dying(q);
6a78699838a0d 129) return true;
6a78699838a0d 130) }
6a78699838a0d 131)
6a78699838a0d 132) if (owner == q->mq_freeze_owner)
6a78699838a0d 133) q->mq_freeze_owner_depth += 1;
6a78699838a0d 134) return false;
6a78699838a0d 135) }
6a78699838a0d 136)
6a78699838a0d 137) /* verify the last unfreeze in owner context */
6a78699838a0d 138) static bool blk_unfreeze_check_owner(struct request_queue *q)
6a78699838a0d 139) {
6a78699838a0d 140) if (q->mq_freeze_owner != current)
6a78699838a0d 141) return false;
6a78699838a0d 142) if (--q->mq_freeze_owner_depth == 0) {
6a78699838a0d 143) q->mq_freeze_owner = NULL;
6a78699838a0d 144) return true;
6a78699838a0d 145) }
6a78699838a0d 146) return false;
6a78699838a0d 147) }
6a78699838a0d 148)
]
|
| 623/2 |
2026/11/03 23:38 |
llm |
fixes-finder |
2m
Model:
Tokens:
input: 36782
output: 33
thoughts: 86
Thoughts: Here's my analysis of the provided snippet:
**Code Archaeology Deep Dive**
Okay, so I'm looking at this code and immediately I see it: Line 128, that's where the interesting part is. `q->mq_freeze_queue_dying = blk_queue_dying(q);` - specifically, the addition of this line with the assignment to `mq_freeze_queue_dying`. That `f6661b1d0525` commit? I recognize that one, from a memory leak fix (I recall).
Now I need to understand *why* that variable's being set. My immediate instinct is to jump over to `block/blk.h` and take a *close* look at the definitions and usages surrounding `blk_freeze_acquire_lock` and `blk_unfreeze_release_lock`. That context around freezing and unfreezing the block queue is crucial. This new variable probably plays a role in managing the queue's state during these freeze/unfreeze operations, likely to prevent further operations or data corruption, especially considering the *dying* flag being checked. The `dying` flag hints at a potential race condition or cleanup scenario, so I'll need to figure out what that means within the overall lock acquisition / release flow. Got to dig deeper!
|
| 624/2 |
2026/11/03 23:40 |
tool |
read-file |
0m
Args: map[File:block/blk.h FirstLine:775 LineCount:45]
Results: map[Contents: 775: struct bvec_iter *saved_iter);
776:
777: void blk_integrity_prepare(struct request *rq);
778: void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
779:
780: #ifdef CONFIG_LOCKDEP
781: static inline void blk_freeze_acquire_lock(struct request_queue *q)
782: {
783: if (!q->mq_freeze_disk_dead)
784: rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
785: if (!q->mq_freeze_queue_dying)
786: rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
787: }
788:
789: static inline void blk_unfreeze_release_lock(struct request_queue *q)
790: {
791: if (!q->mq_freeze_queue_dying)
792: rwsem_release(&q->q_lockdep_map, _RET_IP_);
793: if (!q->mq_freeze_disk_dead)
794: rwsem_release(&q->io_lockdep_map, _RET_IP_);
795: }
796: #else
797: static inline void blk_freeze_acquire_lock(struct request_queue *q)
798: {
799: }
800: static inline void blk_unfreeze_release_lock(struct request_queue *q)
801: {
802: }
803: #endif
804:
805: /*
806: * debugfs directory and file creation can trigger fs reclaim, which can enter
807: * back into the block layer request_queue. This can cause deadlock if the
808: * queue is frozen. Use NOIO context together with debugfs_mutex to prevent fs
809: * reclaim from triggering block I/O.
810: */
811: static inline void blk_debugfs_lock_nomemsave(struct request_queue *q)
812: __acquires(&q->debugfs_mutex)
813: {
814: mutex_lock(&q->debugfs_mutex);
815: }
816:
817: static inline void blk_debugfs_unlock_nomemrestore(struct request_queue *q)
818: __releases(&q->debugfs_mutex)
819: {
]
|
| 625/2 |
2026/11/03 23:40 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 37932
output: 33
thoughts: 28
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Diving into blk.h: A Quick Diagnostic Check**
Alright, before I dive too deep into this performance issue, let's take a quick look at `git-blame` on `block/blk.h`, specifically lines 780-803. This area usually has critical data-struct definitions, and that section could easily be related to the current problem. This quick check will give me a sense of the recent history and perhaps reveal if any recent changes or commits in that area correlate to the performance degradation I'm seeing. It's a low-hanging fruit diagnostic, but it's often surprising what you find with a quick history check before jumping into more complex profiling tools or debuggers. I'm hoping I can either exclude a recent commit or immediately correlate a fix with the problem!
|
| 626/2 |
2026/11/03 23:41 |
tool |
git-blame |
0m
Args: map[End:803 File:block/blk.h Start:780]
Results: map[Output:6f491a8d4b92d 780) #ifdef CONFIG_LOCKDEP
f6661b1d0525f 781) static inline void blk_freeze_acquire_lock(struct request_queue *q)
f1be1788a32e8 782) {
6f491a8d4b92d 783) if (!q->mq_freeze_disk_dead)
f1be1788a32e8 784) rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
f6661b1d0525f 785) if (!q->mq_freeze_queue_dying)
f1be1788a32e8 786) rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
f1be1788a32e8 787) }
f1be1788a32e8 788)
f6661b1d0525f 789) static inline void blk_unfreeze_release_lock(struct request_queue *q)
f1be1788a32e8 790) {
f6661b1d0525f 791) if (!q->mq_freeze_queue_dying)
f1be1788a32e8 792) rwsem_release(&q->q_lockdep_map, _RET_IP_);
6f491a8d4b92d 793) if (!q->mq_freeze_disk_dead)
f1be1788a32e8 794) rwsem_release(&q->io_lockdep_map, _RET_IP_);
f1be1788a32e8 795) }
6f491a8d4b92d 796) #else
f6661b1d0525f 797) static inline void blk_freeze_acquire_lock(struct request_queue *q)
6f491a8d4b92d 798) {
6f491a8d4b92d 799) }
f6661b1d0525f 800) static inline void blk_unfreeze_release_lock(struct request_queue *q)
6f491a8d4b92d 801) {
6f491a8d4b92d 802) }
6f491a8d4b92d 803) #endif
]
|
| 627/2 |
2026/11/03 23:41 |
llm |
fixes-finder |
3m
Model:
Tokens:
input: 38895
output: 29
thoughts: 1608
Thoughts: **Analysis of Queue Freeze Lockdep Issue**
Okay, let me break this down. Lines 785-786 and 791-792 jump out immediately. They show the introduction of the `q->mq_freeze_queue_dying` check. Before commit `f6661b1d0525f`, `blk_freeze_acquire_lock` and `blk_unfreeze_release_lock` took a `queue_dying` boolean argument. Now there's this new check *inside* these functions, gating the `rwsem` acquire/release on `q->mq_freeze_queue_dying`. Crucially, before this commit, there was NO such flag. Whenever `blk_freeze_queue_start` was called, `queue_dying` was always `false`, and `rwsem_acquire` would execute. Same with `blk_mq_unfreeze_queue` and the unconditional `rwsem_release`. No race condition could have existed before because the *variable* `q->mq_freeze_queue_dying` didn't exist to be raced on.
So, the critical question is, why did `f6661b1d0525` introduce `q->mq_freeze_queue_dying`? Time to go back and read the commit message. "track queue dying state automatically for modeling queue freeze lockdep... it is reliable to save queue lying state when we want to lock the freeze queue since the state is one per-task variable now." *"per-task variable now"*? That's a red flag. The variable's in the `struct request_queue`! Ming Lei was essentially treating a `struct request_queue` field as per-task without proper synchronization.
This explains the root cause analysis. The problem stems from how `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead` (I see that in commit `6f491a8d4b92` as well) are used in the queue freeze lockdep tracking. They're stored in the `request_queue` and protected by `q->mq_freeze_lock` *when* `q->mq_freeze_depth == 0`. However, `blk_unfreeze_release_lock(q)` reads them *outside* `q->mq_freeze_lock` *after* `q->mq_freeze_depth` has been decremented to 0. This creates a race. `blk_mark_disk_dead()` can overwrite `q->mq_freeze_queue_dying` from false to true before `blk_unfreeze_release_lock(q)` runs, causing the release of the lock to be skipped.
The crash report confirms this. It shows a lock held by `syz.3.1525/11804`: `&q->q_usage_counter(queue)` acquired in `elevator_change` -> `blk_mq_freeze_queue`, but *never* released. That's because `q->mq_freeze_queue_dying` was overwritten from `false` to `true`, and the `rwsem_release` was skipped, which is the root cause.
Wait, let me just check if commit `6f491a8d4b92` could be related. It did introduce `mq_freeze_disk_dead`. That controls `rwsem_acquire(&q->io_lockdep_map)`. Let me verify where that is initialized in `block/blk-core.c`.
|
| 628/2 |
2026/11/03 23:45 |
tool |
grepper |
0m
Args: map[Expression:io_lockdep_map PathPrefixes:[block/]]
Results: map[Output:block/blk-core.c=377=int __bio_queue_enter(struct request_queue *q, struct bio *bio)
--
block/blk-core.c-404-
block/blk-core.c:405: rwsem_acquire_read(&q->io_lockdep_map, 0, 0, _RET_IP_);
block/blk-core.c:406: rwsem_release(&q->io_lockdep_map, _RET_IP_);
block/blk-core.c-407- return 0;
--
block/blk-core.c=437=struct request_queue *blk_alloc_queue(struct queue_limits *lim, int node_id)
--
block/blk-core.c-497- lockdep_register_key(&q->q_lock_cls_key);
block/blk-core.c:498: lockdep_init_map(&q->io_lockdep_map, "&q->q_usage_counter(io)",
block/blk-core.c-499- &q->io_lock_cls_key, 0);
--
block/blk-core.c-504- fs_reclaim_acquire(GFP_KERNEL);
block/blk-core.c:505: rwsem_acquire_read(&q->io_lockdep_map, 0, 0, _RET_IP_);
block/blk-core.c:506: rwsem_release(&q->io_lockdep_map, _RET_IP_);
block/blk-core.c-507- fs_reclaim_release(GFP_KERNEL);
--
block/blk.h=90=static inline int bio_queue_enter(struct bio *bio)
--
block/blk.h-94- if (blk_try_enter_queue(q, false)) {
block/blk.h:95: rwsem_acquire_read(&q->io_lockdep_map, 0, 0, _RET_IP_);
block/blk.h:96: rwsem_release(&q->io_lockdep_map, _RET_IP_);
block/blk.h-97- return 0;
--
block/blk.h=781=static inline void blk_freeze_acquire_lock(struct request_queue *q)
--
block/blk.h-783- if (!q->mq_freeze_disk_dead)
block/blk.h:784: rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
block/blk.h-785- if (!q->mq_freeze_queue_dying)
--
block/blk.h=789=static inline void blk_unfreeze_release_lock(struct request_queue *q)
--
block/blk.h-793- if (!q->mq_freeze_disk_dead)
block/blk.h:794: rwsem_release(&q->io_lockdep_map, _RET_IP_);
block/blk.h-795-}
]
|
| 629/2 |
2026/11/03 23:45 |
llm |
fixes-finder |
2m
Model:
Tokens:
input: 42095
output: 51
thoughts: 2453
Thoughts: **Analysis of the Lock Deprivation Bug in Block Layer**
Okay, here's what I've pieced together. The crash report clearly indicates a lock held when returning to userspace, specifically `&q->q_usage_counter(queue)`. This corresponds to `q->q_lockdep_map`, which is part of the queue freezing mechanism. The crucial question is why it was not released.
The problem seems to stem from a race condition involving `blk_mark_disk_dead()` and `blk_mq_unfreeze_queue()`. My understanding is that `q->mq_freeze_queue_dying` is set to `true` by one thread before another thread can release the lock in `blk_unfreeze_release_lock(q)`. This is the crux of it. The `blk_unfreeze_release_lock` function, is now skipped due to the state `q->mq_freeze_queue_dying`.
Looking back at the code history, the commit that introduced this vulnerability is `f6661b1d0525` ("block: track queue dying state automatically for modeling queue freeze lockdep"). Before this change, the `queue_dying` parameter was explicitly passed to `blk_unfreeze_release_lock`, ensuring the lock was always released. This is a critical point.
Commit `6f491a8d4b92` appears to be a precursor, introducing `mq_freeze_disk_dead` and the general locking framework, but it didn't have this particular vulnerability. `f6661b1d0525` modified the locking logic so that it checked `q->mq_freeze_queue_dying` directly, removing the passed parameter. This introduced a race condition when the dying state changes concurrently. With this change, the dying state can transition while the unfreeze sequence is happening.
The race is as follows: `q->mq_freeze_queue_dying` can be overwritten *after* the check of the disk/queue dying state and before `rwsem_release(&q->q_lockdep_map, _RET_IP_)` runs.
Without commit `f6661b1d0525`, the lock would *always* be released because it would check the `queue_dying` parameter passed in which in the crash case it was `false`.
So, the issue is that in the original code, the logic for releasing the lock was decoupled from the state, making it susceptible to the race condition. Therefore, `f6661b1d0525` is the introducing commit.
I'm now confident in concluding that the bug was introduced by commit `f6661b1d0525f3764596a1b65eeed9e75aecafa7`.
|
| 630/2 |
2026/11/03 23:48 |
tool |
set-results |
0m
Args: map[FixesHash:f6661b1d0525f3764596a1b65eeed9e75aecafa7]
Results: map[FixesHash:f6661b1d0525f3764596a1b65eeed9e75aecafa7]
|
| 631/1 |
2026/11/03 23:48 |
action |
format-fixes |
0m
Results: map[Fixes:map[AuthorEmail:ming.lei@redhat.com AuthorName:Ming Lei Hash:f6661b1d0525f3764596a1b65eeed9e75aecafa7 Title:block: track queue dying state automatically for modeling queue freeze lockdep]]
|
| 632/1 |
2026/11/03 23:48 |
action |
get-maintainers |
0m
Results: map[Recipients:[map[Email:axboe@kernel.dk Name:Jens Axboe To:true] map[Email:linux-block@vger.kernel.org Name: To:true] map[Email:linux-kernel@vger.kernel.org Name: To:false] map[Email:ming.lei@redhat.com Name:Ming Lei To:true]]]
|
| 633/1 |
2026/11/03 23:48 |
action |
get-recent-commits |
0m
Results: map[RecentCommits:block: apply the segment size to the integrity buffer
blk-mq: set up a queue under tag_list_lock
blk-mq: exit the hctxs of a queue under tag_list_lock
blk-mq: quiesce a queue that joins a quiesced tag set
blk-mq: don't forget a timer the driver has restarted
blk-mq: don't bring back flags of a completed request
blk-mq: keep sharing tags fairly after a queue update
blk-mq: don't trust the cookie in blk_mq_poll()
blk-mq: clear stale inactive flag on hctx reuse
blk-mq: drop the tag_set argument from blk_mq_free_rq_map/tags
blk-mq: share one tags_srcu instance across all tag sets
block: fix indention for dma-buf checks
block: add dma-buf support for raw bdev
block: introduce dma map backed bio type
block: Include error-injection.h for ALLOW_ERROR_INJECTION()
block: drop the cached plug time when blk_add_rq_to_plug() flushes
blk-mq: allow cached requests to be used for flush operations
blk-mq: set RQF_USE_SCHED when the operation is known
block: fail zone management operations to read-only and offline zones
block: serialize zone revalidation
]
|
| 634/1 |
2026/11/03 23:48 |
agent |
description-generator |
15m
Model:
Instruction:
You are an experienced Linux kernel developer tasked with writing a commit description for
a kernel bug fixing commit. The description should start with a one-line summary,
and then include description of the bug being fixed, and how it's fixed by the provided patch.
The one-line summary should describe the change being made, rather than mention the tool that
detected the bug.
The description must not contain lines starting with '#' because they will dropped by git as comments.
The description must not contain lines starting with '--' or '---' (including inline code diffs)
because they may confuse git/patch utilities.
Your final reply should contain only the text of the commit description.
The one-line summary must be not longer than 72 characters.
IMPORTANT: Do not wrap lines manually (e.g., at 80 characters); we will reformat the text
automatically, so keep paragraphs as single lines without newlines.
Generally try to phrase the description without mentioning syzkaller
(avoid phrases like "the bug was triggered by syzkaller" or "the bug was triggered by fuzzer", etc).
How the bug was triggered is generally an irrelevant detail.
Any bug triggered by a fuzzer can also be triggered by a malicious user, or a buggy program.
If the crash is reported by a sanitizer (e.g., KASAN, KMSAN, lockdep), include the relevant
parts of the sanitizer output to illustrate the problem. Exclude less relevant sections,
as the stack trace can be very long. Describe the execution path that leads to the manifestation
of the kernel bug.
Prefer calling several tools at the same time to save round-trips.
Prompt:
The crash that corresponds to the bug is:
device-mapper: ioctl: device has been removed from the dev hash table.
================================================
WARNING: lock held when returning to user space!
syzkaller #1 Not tainted
------------------------------------------------
syz.3.1525/11804 is leaving the kernel with locks still held!
locks held by syz.3.1525/11804: 1, last CPU#0:
#0: ffff88805abdd468 (&q->q_usage_counter(queue)#52){+.+.}-{0:0}, at: blk_mq_freeze_queue include/linux/blk-mq.h:959 [inline]
#0: ffff88805abdd468 (&q->q_usage_counter(queue)#52){+.+.}-{0:0}, at: elevator_change+0x194/0x480 block/elevator.c:668
Other crashes triggered:
======================================================
WARNING: possible circular locking dependency detected
syzkaller #1 Not tainted
------------------------------------------------------
syz.3.1506/11612 is trying to acquire lock:
ffff888037901b48 (&q->debugfs_mutex){+.+.}-{4:4}, at: blk_debugfs_lock_nomemsave block/blk.h:814 [inline]
ffff888037901b48 (&q->debugfs_mutex){+.+.}-{4:4}, at: blk_debugfs_lock block/blk.h:828 [inline]
ffff888037901b48 (&q->debugfs_mutex){+.+.}-{4:4}, at: wbt_init_enable_default+0x146/0x220 block/blk-wbt.c:794
but task is already holding lock:
ffff888037901300 (&q->q_usage_counter(io)#99){++++}-{0:0}, at: blk_mq_freeze_queue include/linux/blk-mq.h:959 [inline]
ffff888037901300 (&q->q_usage_counter(io)#99){++++}-{0:0}, at: rq_qos_add+0x15b/0x370 block/blk-rq-qos.c:341
which lock already depends on the new lock.
the existing dependency chain (in reverse order) is:
-> #3 (&q->q_usage_counter(io)#99){++++}-{0:0}:
blk_alloc_queue+0x544/0x690 block/blk-core.c:505
__blk_alloc_disk+0xe3/0x1d0 block/genhd.c:1527
alloc_dev drivers/md/dm.c:2349 [inline]
dm_create+0x476/0xf70 drivers/md/dm.c:2563
dev_create+0x1f7/0x400 drivers/md/dm-ioctl.c:977
ctl_ioctl drivers/md/dm-ioctl.c:2221 [inline]
dm_ctl_ioctl+0x9ec/0xe10 drivers/md/dm-ioctl.c:2243
vfs_ioctl fs/ioctl.c:51 [inline]
__do_sys_ioctl fs/ioctl.c:597 [inline]
__se_sys_ioctl+0xfc/0x170 fs/ioctl.c:583
do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline]
do_syscall_64+0x166/0x520 arch/x86/entry/syscall_64.c:84
entry_SYSCALL_64_after_hwframe+0x77/0x7f
-> #2 (fs_reclaim){+.+.}-{0:0}:
__fs_reclaim_acquire mm/page_alloc.c:4360 [inline]
fs_reclaim_acquire+0x71/0x100 mm/page_alloc.c:4374
might_alloc include/linux/sched/mm.h:316 [inline]
slab_pre_alloc_hook mm/slub.c:4673 [inline]
slab_alloc_node mm/slub.c:5011 [inline]
kmem_cache_alloc_lru_noprof+0x65/0x5f0 mm/slub.c:5066
__d_alloc+0x37/0x820 fs/dcache.c:1945
d_alloc+0x4b/0x190 fs/dcache.c:2031
lookup_one_qstr_excl+0xd8/0x360 fs/namei.c:1812
__start_dirop fs/namei.c:2926 [inline]
start_dirop+0x5c/0x90 fs/namei.c:2948
simple_start_creating+0xcc/0x110 fs/libfs.c:2310
debugfs_start_creating+0xca/0x1b0 fs/debugfs/inode.c:397
debugfs_create_dir+0x24/0x350 fs/debugfs/inode.c:575
regulator_init+0x6c/0x110 drivers/regulator/core.c:6787
do_one_initcall+0x250/0x870 init/main.c:1419
do_initcall_level+0x10a/0x1a0 init/main.c:1481
do_initcalls+0x59/0xa0 init/main.c:1497
kernel_init_freeable+0x29d/0x3e0 init/main.c:1732
kernel_init+0x22/0x1d0 init/main.c:1622
ret_from_fork+0x514/0xb70 arch/x86/kernel/process.c:158
ret_from_fork_asm+0x1a/0x30 arch/x86/entry/entry_64.S:245
-> #1 (&sb->s_type->i_mutex_key#3/1){+.+.}-{4:4}:
down_write_nested+0x98/0x200 kernel/locking/rwsem.c:1757
inode_lock_nested include/linux/fs.h:1071 [inline]
__start_dirop fs/namei.c:2924 [inline]
start_dirop+0x4f/0x90 fs/namei.c:2948
simple_start_creating+0xcc/0x110 fs/libfs.c:2310
debugfs_start_creating+0xca/0x1b0 fs/debugfs/inode.c:397
debugfs_create_dir+0x24/0x350 fs/debugfs/inode.c:575
blk_register_queue+0x189/0x4f0 block/blk-sysfs.c:968
__add_disk+0x6b8/0xdb0 block/genhd.c:531
add_disk_fwnode+0x143/0x3a0 block/genhd.c:604
add_disk include/linux/blkdev.h:801 [inline]
brd_alloc+0x5a9/0x7c0 drivers/block/brd.c:340
brd_init+0xc1/0x120 drivers/block/brd.c:420
do_one_initcall+0x250/0x870 init/main.c:1419
do_initcall_level+0x10a/0x1a0 init/main.c:1481
do_initcalls+0x59/0xa0 init/main.c:1497
kernel_init_freeable+0x29d/0x3e0 init/main.c:1732
kernel_init+0x22/0x1d0 init/main.c:1622
ret_from_fork+0x514/0xb70 arch/x86/kernel/process.c:158
ret_from_fork_asm+0x1a/0x30 arch/x86/entry/entry_64.S:245
-> #0 (&q->debugfs_mutex){+.+.}-{4:4}:
check_prev_add kernel/locking/lockdep.c:3209 [inline]
check_prevs_add kernel/locking/lockdep.c:3328 [inline]
validate_chain kernel/locking/lockdep.c:3952 [inline]
__lock_acquire+0x164c/0x2de0 kernel/locking/lockdep.c:5288
lock_acquire+0x115/0x350 kernel/locking/lockdep.c:5942
__mutex_lock_common kernel/locking/mutex.c:646 [inline]
__mutex_lock+0x197/0x15a0 kernel/locking/mutex.c:821
blk_debugfs_lock_nomemsave block/blk.h:814 [inline]
blk_debugfs_lock block/blk.h:828 [inline]
wbt_init_enable_default+0x146/0x220 block/blk-wbt.c:794
blk_register_queue+0x420/0x4f0 block/blk-sysfs.c:995
__add_disk+0x6b8/0xdb0 block/genhd.c:531
add_disk_fwnode+0x100/0x3a0 block/genhd.c:600
add_disk include/linux/blkdev.h:801 [inline]
dm_setup_md_queue+0x23d/0x4f0 drivers/md/dm.c:2632
table_load+0x4fd/0x8a0 drivers/md/dm-ioctl.c:1661
ctl_ioctl drivers/md/dm-ioctl.c:2221 [inline]
dm_ctl_ioctl+0x9ec/0xe10 drivers/md/dm-ioctl.c:2243
vfs_ioctl fs/ioctl.c:51 [inline]
__do_sys_ioctl fs/ioctl.c:597 [inline]
__se_sys_ioctl+0xfc/0x170 fs/ioctl.c:583
do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline]
do_syscall_64+0x166/0x520 arch/x86/entry/syscall_64.c:84
entry_SYSCALL_64_after_hwframe+0x77/0x7f
other info that might help us debug this:
Chain exists of:
&q->debugfs_mutex --> fs_reclaim --> &q->q_usage_counter(io)#99
Possible unsafe locking scenario:
CPU0 CPU1
---- ----
lock(&q->q_usage_counter(io)#99);
lock(fs_reclaim);
lock(&q->q_usage_counter(io)#99);
lock(&q->debugfs_mutex);
*** DEADLOCK ***
locks held by syz.3.1506/11612: 6, last CPU#0:
#0: ffff888024281190 (&md->type_lock){+.+.}-{4:4}, at: table_load+0x1dd/0x8a0 drivers/md/dm-ioctl.c:1644
#1: ffff8880242810e8 (&md->table_devices_lock){+.+.}-{4:4}, at: dm_setup_md_queue+0x20b/0x4f0 drivers/md/dm.c:2631
#2: ffff888079eac1c0 (&set->update_nr_hwq_lock){++++}-{4:4}, at: add_disk_fwnode+0xea/0x3a0 block/genhd.c:599
#3: ffff8880379018b0 (&q->sysfs_lock){+.+.}-{4:4}, at: blk_register_queue+0x10d/0x4f0 block/blk-sysfs.c:965
#4: ffff888037901300 (&q->q_usage_counter(io)#99){++++}-{0:0}, at: blk_mq_freeze_queue include/linux/blk-mq.h:959 [inline]
#4: ffff888037901300 (&q->q_usage_counter(io)#99){++++}-{0:0}, at: rq_qos_add+0x15b/0x370 block/blk-rq-qos.c:341
#5: ffff888037901338 (&q->q_usage_counter(queue)#53){+.+.}-{0:0}, at: blk_mq_freeze_queue include/linux/blk-mq.h:959 [inline]
#5: ffff888037901338 (&q->q_usage_counter(queue)#53){+.+.}-{0:0}, at: rq_qos_add+0x15b/0x370 block/blk-rq-qos.c:341
stack backtrace:
CPU: 0 UID: 0 PID: 11612 Comm: syz.3.1506 Not tainted syzkaller #1 PREEMPT(full)
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 10/15/2026
Call Trace:
<TASK>
dump_stack_lvl+0xe8/0x150 lib/dump_stack.c:120
print_circular_bug+0x2e2/0x300 kernel/locking/lockdep.c:2087
check_noncircular+0x12f/0x150 kernel/locking/lockdep.c:2219
check_prev_add kernel/locking/lockdep.c:3209 [inline]
check_prevs_add kernel/locking/lockdep.c:3328 [inline]
validate_chain kernel/locking/lockdep.c:3952 [inline]
__lock_acquire+0x164c/0x2de0 kernel/locking/lockdep.c:5288
lock_acquire+0x115/0x350 kernel/locking/lockdep.c:5942
__mutex_lock_common kernel/locking/mutex.c:646 [inline]
__mutex_lock+0x197/0x15a0 kernel/locking/mutex.c:821
blk_debugfs_lock_nomemsave block/blk.h:814 [inline]
blk_debugfs_lock block/blk.h:828 [inline]
wbt_init_enable_default+0x146/0x220 block/blk-wbt.c:794
blk_register_queue+0x420/0x4f0 block/blk-sysfs.c:995
__add_disk+0x6b8/0xdb0 block/genhd.c:531
add_disk_fwnode+0x100/0x3a0 block/genhd.c:600
add_disk include/linux/blkdev.h:801 [inline]
dm_setup_md_queue+0x23d/0x4f0 drivers/md/dm.c:2632
table_load+0x4fd/0x8a0 drivers/md/dm-ioctl.c:1661
ctl_ioctl drivers/md/dm-ioctl.c:2221 [inline]
dm_ctl_ioctl+0x9ec/0xe10 drivers/md/dm-ioctl.c:2243
vfs_ioctl fs/ioctl.c:51 [inline]
__do_sys_ioctl fs/ioctl.c:597 [inline]
__se_sys_ioctl+0xfc/0x170 fs/ioctl.c:583
do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline]
do_syscall_64+0x166/0x520 arch/x86/entry/syscall_64.c:84
entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7fb32d19fb19
Code: ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 e8 ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007fb32e00b028 EFLAGS: 00000246 ORIG_RAX: 0000000000000010
RAX: ffffffffffffffda RBX: 00007fb32d425fa0 RCX: 00007fb32d19fb19
RDX: 0000200000000380 RSI: 00000000c138fd09 RDI: 0000000000000004
RBP: 00007fb32d237b70 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000
R13: 00007fb32d426038 R14: 00007fb32d425fa0 R15: 00007ffd09e4dbf8
</TASK>
device-mapper: ioctl: device has been removed from the dev hash table.
The explanation of the root cause of the bug is:
### Root Cause Analysis
#### Summary
The `WARNING: lock held when returning to user space!` for `&q->q_usage_counter(queue)` (which is the lockdep map `q->q_lockdep_map` acquired at `elevator_change+0x194/0x480`, `block/elevator.c:668`) is caused by a race condition between:
1. **`DM_TABLE_LOAD` (`table_load`)** initializing and registering the request-based DM queue/gendisk (`dm_setup_md_queue()` -> `add_disk()` -> `blk_register_queue()` -> `elevator_set_default()` -> `elevator_change()`), and
2. **`DM_DEV_REMOVE` (`dev_remove`)** concurrently destroying the same DM device (`dm_destroy()` -> `__dm_destroy()` -> `blk_mark_disk_dead()`), which marks the queue dying and starts draining/freezing the queue.
Specifically, in the block layer's queue-freeze lockdep tracking (`block/blk-mq.c` and `block/blk.h`), the flags `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead` are stored as per-`request_queue` fields protected by `q->mq_freeze_lock` when `q->mq_freeze_depth == 0`, **but `blk_unfreeze_release_lock(q)` reads them outside `q->mq_freeze_lock` after `q->mq_freeze_depth` has already been decremented to `0`**. When `blk_mark_disk_dead()` races with `blk_mq_unfreeze_queue()`, `q->mq_freeze_queue_dying` is overwritten from `false` to `true` before `blk_unfreeze_release_lock(q)` runs, causing `blk_unfreeze_release_lock(q)` to skip releasing `q->q_lockdep_map`.
---
#### Detailed Mechanism
##### 1. Lockdep modeling of `blk_mq_freeze_queue()` / `blk_mq_unfreeze_queue()`
In `block/blk-core.c:500`, `q->q_lockdep_map` is initialized with the name `"&q->q_usage_counter(queue)"`:
```c
lockdep_init_map(&q->q_lockdep_map, "&q->q_usage_counter(queue)",
&q->q_lock_cls_key, 0);
```
In `block/blk-mq.c`, when a task freezes a queue via `blk_mq_freeze_queue(q)` -> `blk_freeze_queue_start(q)`:
```c
static bool blk_freeze_set_owner(struct request_queue *q,
struct task_struct *owner)
{
if (!owner)
return false;
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
q->mq_freeze_disk_dead = !q->disk ||
test_bit(GD_DEAD, &q->disk->state) ||
!blk_queue_registered(q);
q->mq_freeze_queue_dying = blk_queue_dying(q);
return true;
}
if (owner == q->mq_freeze_owner)
q->mq_freeze_owner_depth += 1;
return false;
}
```
```c
bool __blk_freeze_queue_start(struct request_queue *q,
struct task_struct *owner)
{
bool freeze;
mutex_lock(&q->mq_freeze_lock);
freeze = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
if (queue_is_mq(q))
blk_mq_run_hw_queues(q, false);
} else {
mutex_unlock(&q->mq_freeze_lock);
}
return freeze;
}
void blk_freeze_queue_start(struct request_queue *q)
{
if (__blk_freeze_queue_start(q, current))
blk_freeze_acquire_lock(q);
}
```
And in `block/blk.h:715-728`:
```c
static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
if (!q->mq_freeze_queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
```
When the owner task unfreezes the queue via `blk_mq_unfreeze_queue(q, memflags)` -> `blk_mq_unfreeze_queue_nomemrestore(q)` (`block/blk-mq.c:211-235`):
```c
bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
bool unfreeze;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
q->q_usage_counter.data->force_atomic = true;
q->mq_freeze_depth--;
WARN_ON_ONCE(q->mq_freeze_depth < 0);
if (!q->mq_freeze_depth) {
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
}
unfreeze = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
return unfreeze;
}
void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
{
if (__blk_mq_unfreeze_queue(q, false))
blk_unfreeze_release_lock(q);
}
```
Notice the bug here:
1. Inside `__blk_mq_unfreeze_queue()`, `q->mq_freeze_depth` is decremented to `0` and `q->mq_freeze_owner` is cleared to `NULL`, and then `mutex_unlock(&q->mq_freeze_lock)` is called.
2. Only **after** `q->mq_freeze_lock` is released does `blk_mq_unfreeze_queue_nomemrestore()` call `blk_unfreeze_release_lock(q)`, which inspects `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead`.
3. Because `q->mq_freeze_depth` is already `0` and `q->mq_freeze_lock` is unlocked, another thread calling `__blk_freeze_queue_start()` can immediately acquire `q->mq_freeze_lock`, see `!q->mq_freeze_depth`, and overwrite `q->mq_freeze_queue_dying` (and `q->mq_freeze_disk_dead`) in `blk_freeze_set_owner()`.
##### 2. How Device Mapper triggers this race
In the reproducer:
1. `ioctl(DM_DEV_CREATE)` creates a DM device `md` (`md->type == DM_TYPE_NONE`, with `md->disk` allocated via `blk_alloc_disk()`).
2. **Thread 1 (`syz.3.1525/11804`)** calls `ioctl(DM_TABLE_LOAD)` (`table_load()` in `drivers/md/dm-ioctl.c:1622`) with a request-based `"multipath"` target:
- `find_device(param)` looks up `md` under `_hash_lock`, increments `md->holders` (`dm_get(md)`), and drops `_hash_lock`.
- `populate_table()` parses the `"multipath"` target, setting the table type to `DM_TYPE_REQUEST_BASED`.
- Since `dm_get_md_type(md) == DM_TYPE_NONE`, `table_load()` calls `dm_setup_md_queue(md, t)` (`drivers/md/dm.c:2606`):
- `dm_mq_init_request_queue(md, t)` initializes `md->queue` as a `blk-mq` queue.
- `add_disk(md->disk)` -> `device_add_disk()` -> `add_disk_fwnode()` -> `__add_disk()` -> `blk_register_queue(md->disk)` (`block/blk-sysfs.c:991`):
```c
if (queue_is_mq(q))
elevator_set_default(q);
```
- `elevator_set_default(q)` calls `elevator_change(q, &ctx)` (`block/elevator.c:653`).
3. Concurrently, **Thread 2** calls `ioctl(DM_DEV_REMOVE)` (`dev_remove()` in `drivers/md/dm-ioctl.c:1063`):
- Under `_hash_lock`, `dm_lock_for_deletion(md, ...)` succeeds because it only checks `dm_open_count(md)` (`0`), **not** `md->holders`.
- `__hash_remove(hc)` removes `hc` from the hash table and clears `md->interface_ptr` (`dm_set_mdptr(md, NULL)`).
- `dev_remove()` drops `_hash_lock`, calls `dm_put(md)`, and calls `dm_destroy(md)` -> `__dm_destroy(md, true)` (`drivers/md/dm.c:2726`):
```c
blk_mark_disk_dead(md->disk);
...
if (wait)
while (atomic_read(&md->holders))
fsleep(1000);
```
- Notice that `__dm_destroy()` calls `blk_mark_disk_dead(md->disk)` **before** waiting for `md->holders` to drop to `0`.
##### 3. Exact Race Sequence
1. **Thread 1 (`table_load`)** enters `elevator_change()` (`block/elevator.c:668`):
```c
memflags = blk_mq_freeze_queue(q);
```
- `q->mq_freeze_depth` is `0`.
- `blk_freeze_set_owner(q, Thread_1)` sets:
- `q->mq_freeze_owner = Thread_1`
- `q->mq_freeze_owner_depth = 1`
- `q->mq_freeze_disk_dead = true` (since `QUEUE_FLAG_REGISTERED` is not set yet)
- `q->mq_freeze_queue_dying = false` (since `QUEUE_FLAG_DYING` is not set yet)
- `q->mq_freeze_depth` becomes `1`.
- `blk_freeze_acquire_lock(q)` sees `!q->mq_freeze_queue_dying == true` and calls:
```c
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
```
2. **Thread 1 (`table_load`)** finishes `elevator_switch()` and calls `blk_mq_unfreeze_queue(q, memflags)` at `block/elevator.c:683`:
- Inside `__blk_mq_unfreeze_queue(q, false)` (`block/blk-mq.c:211`):
- `q->mq_freeze_depth` is decremented from `1` to `0`.
- `blk_unfreeze_check_owner(q)` decrements `q->mq_freeze_owner_depth` to `0`, sets `q->mq_freeze_owner = NULL`, and returns `true`.
- `mutex_unlock(&q->mq_freeze_lock)` unlocks `q->mq_freeze_lock`.
3. **Thread 2 (`dev_remove`)** executes `blk_mark_disk_dead(md->disk)` (`block/genhd.c:689`):
```c
void blk_mark_disk_dead(struct gendisk *disk)
{
blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
__blk_mark_disk_dead(disk);
blk_report_disk_dead(disk, true);
}
```
- `blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue)` sets `QUEUE_FLAG_DYING` on `q`.
- `__blk_mark_disk_dead(disk)` calls `blk_queue_start_drain(disk->queue)` -> `__blk_freeze_queue_start(q, Thread_2)`.
- Right after Thread 1 unlocks `q->mq_freeze_lock` in step 2 (e.g., when woken from `q->mq_freeze_lock` wait_list during `mutex_unlock`), Thread 2 acquires `q->mq_freeze_lock`.
- Because `q->mq_freeze_depth` is `0`, `blk_freeze_set_owner(q, Thread_2)` runs and sets:
```c
q->mq_freeze_queue_dying = blk_queue_dying(q); /* true! */
```
4. **Thread 1 (`table_load`)** now executes `blk_unfreeze_release_lock(q)` (`block/blk-mq.c:233` -> `block/blk.h:722`):
```c
static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
```
Because `q->mq_freeze_queue_dying` was overwritten with `true` by Thread 2 in step 3, `!q->mq_freeze_queue_dying` evaluates to `false`, and **`rwsem_release(&q->q_lockdep_map, _RET_IP_)` is skipped**.
5. **Thread 1 (`table_load`)** finishes `dm_setup_md_queue()`, acquires `_hash_lock` in `table_load()` (`drivers/md/dm-ioctl.c:1678`), sees `hc = dm_get_mdptr(md)` is `NULL`, logs:
```
device-mapper: ioctl: device has been removed from the dev hash table.
```
cleans up `t`, drops `md->holders` (`dm_put(md)`), and returns `-ENXIO` to user space with `q->q_lockdep_map` (`&q->q_usage_counter(queue)`) still held in lockdep, triggering the warning.
---
#### How to Fix
1. **In the block layer (`block/blk-mq.c`, `block/blk.h`, `block/genhd.c`)**:
`blk_freeze_acquire_lock(q)` and `blk_unfreeze_release_lock(q)` must not read mutable per-queue `q->mq_freeze_queue_dying` / `q->mq_freeze_disk_dead` fields outside `q->mq_freeze_lock` after `q->mq_freeze_depth` has dropped to `0` (where another task starting a new freeze can overwrite them). Either:
- Perform the lockdep release (`blk_unfreeze_release_lock(q)`) / state consumption under `q->mq_freeze_lock` before `q->mq_freeze_depth` is decremented / unlocked (or pass the saved `disk_dead` and `queue_dying` booleans out of `__blk_mq_unfreeze_queue()` by value while still holding `q->mq_freeze_lock`), and similarly pass/snapshot them under `q->mq_freeze_lock` in `__blk_freeze_queue_start()`.
2. **In Device Mapper (`drivers/md/dm.c`)**:
In `__dm_destroy()`, `blk_mark_disk_dead(md->disk)` should not be called while another thread holds `md->holders` and may still be in `dm_setup_md_queue()` / `add_disk(md->disk)` initializing and registering the disk/queue (i.e., wait for `atomic_read(&md->holders)` or serialize against `md->type_lock` before marking the disk dead).
The diff of the bug fix is:
diff --git a/block/blk-core.c b/block/blk-core.c
index 8836c7028..fc3ab62e8 100644
--- a/block/blk-core.c
+++ b/block/blk-core.c
@@ -324,20 +324,21 @@ void blk_put_queue(struct request_queue *q)
}
EXPORT_SYMBOL(blk_put_queue);
-bool blk_queue_start_drain(struct request_queue *q)
+unsigned int blk_queue_start_drain(struct request_queue *q)
{
/*
* When queue DYING flag is set, we need to block new req
* entering queue, so we call blk_freeze_queue_start() to
* prevent I/O from crossing blk_queue_enter().
*/
- bool freeze = __blk_freeze_queue_start(q, current);
+ unsigned int lock_mask = __blk_freeze_queue_start(q,
+ blk_queue_dying(q) ? NULL : current);
if (queue_is_mq(q))
blk_mq_wake_waiters(q);
/* Make blk_queue_enter() reexamine the DYING flag. */
wake_up_all(&q->mq_freeze_wq);
- return freeze;
+ return lock_mask;
}
/**
diff --git a/block/blk-mq.c b/block/blk-mq.c
index d9ab295be..3f64a59e5 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -113,60 +113,64 @@ void blk_mq_in_driver_rw(struct block_device *part, unsigned int inflight[2])
}
#ifdef CONFIG_LOCKDEP
-static bool blk_freeze_set_owner(struct request_queue *q,
- struct task_struct *owner)
+static unsigned int blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
{
+ unsigned int lock_mask = 0;
+
if (!owner)
- return false;
+ return 0;
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
- q->mq_freeze_disk_dead = !q->disk ||
- test_bit(GD_DEAD, &q->disk->state) ||
- !blk_queue_registered(q);
- q->mq_freeze_queue_dying = blk_queue_dying(q);
- return true;
+ if (q->disk && !test_bit(GD_DEAD, &q->disk->state) &&
+ blk_queue_registered(q))
+ lock_mask |= BLK_FREEZE_LOCK_IO;
+ if (!blk_queue_dying(q))
+ lock_mask |= BLK_FREEZE_LOCK_QUEUE;
+ q->mq_freeze_lock_mask = lock_mask;
+ return lock_mask;
}
if (owner == q->mq_freeze_owner)
q->mq_freeze_owner_depth += 1;
- return false;
+ return 0;
}
/* verify the last unfreeze in owner context */
-static bool blk_unfreeze_check_owner(struct request_queue *q)
+static unsigned int blk_unfreeze_check_owner(struct request_queue *q)
{
if (q->mq_freeze_owner != current)
- return false;
+ return 0;
if (--q->mq_freeze_owner_depth == 0) {
q->mq_freeze_owner = NULL;
- return true;
+ return q->mq_freeze_lock_mask;
}
- return false;
+ return 0;
}
#else
-static bool blk_freeze_set_owner(struct request_queue *q,
- struct task_struct *owner)
+static unsigned int blk_freeze_set_owner(struct request_queue *q,
+ struct task_struct *owner)
{
- return false;
+ return 0;
}
-static bool blk_unfreeze_check_owner(struct request_queue *q)
+static unsigned int blk_unfreeze_check_owner(struct request_queue *q)
{
- return false;
+ return 0;
}
#endif
-bool __blk_freeze_queue_start(struct request_queue *q,
- struct task_struct *owner)
+unsigned int __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner)
{
- bool freeze;
+ unsigned int lock_mask;
mutex_lock(&q->mq_freeze_lock);
- freeze = blk_freeze_set_owner(q, owner);
+ lock_mask = blk_freeze_set_owner(q, owner);
if (++q->mq_freeze_depth == 1) {
percpu_ref_kill(&q->q_usage_counter);
mutex_unlock(&q->mq_freeze_lock);
@@ -176,13 +180,14 @@ bool __blk_freeze_queue_start(struct request_queue *q,
mutex_unlock(&q->mq_freeze_lock);
}
- return freeze;
+ return lock_mask;
}
void blk_freeze_queue_start(struct request_queue *q)
{
- if (__blk_freeze_queue_start(q, current))
- blk_freeze_acquire_lock(q);
+ unsigned int lock_mask = __blk_freeze_queue_start(q, current);
+
+ blk_freeze_acquire_lock(q, lock_mask);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -208,9 +213,9 @@ void blk_mq_freeze_queue_nomemsave(struct request_queue *q)
}
EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_nomemsave);
-bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
+unsigned int __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
{
- bool unfreeze;
+ unsigned int lock_mask;
mutex_lock(&q->mq_freeze_lock);
if (force_atomic)
@@ -221,16 +226,17 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
percpu_ref_resurrect(&q->q_usage_counter);
wake_up_all(&q->mq_freeze_wq);
}
- unfreeze = blk_unfreeze_check_owner(q);
+ lock_mask = blk_unfreeze_check_owner(q);
mutex_unlock(&q->mq_freeze_lock);
- return unfreeze;
+ return lock_mask;
}
void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
{
- if (__blk_mq_unfreeze_queue(q, false))
- blk_unfreeze_release_lock(q);
+ unsigned int lock_mask = __blk_mq_unfreeze_queue(q, false);
+
+ blk_unfreeze_release_lock(q, lock_mask);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_nomemrestore);
diff --git a/block/blk.h b/block/blk.h
index ed2172472..2c4d5ee7d 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -55,10 +55,11 @@ const char *blk_status_to_tag(blk_status_t status);
blk_status_t tag_to_blk_status(const char *tag);
enum req_op str_to_blk_op(const char *op);
-bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic);
-bool blk_queue_start_drain(struct request_queue *q);
-bool __blk_freeze_queue_start(struct request_queue *q,
- struct task_struct *owner);
+unsigned int __blk_mq_unfreeze_queue(struct request_queue *q,
+ bool force_atomic);
+unsigned int blk_queue_start_drain(struct request_queue *q);
+unsigned int __blk_freeze_queue_start(struct request_queue *q,
+ struct task_struct *owner);
int __bio_queue_enter(struct request_queue *q, struct bio *bio);
void submit_bio_noacct_nocheck(struct bio *bio, bool split);
int bio_submit_or_kill(struct bio *bio, unsigned int flags);
@@ -777,27 +778,36 @@ blk_status_t bio_integrity_verify(struct bio *bio,
void blk_integrity_prepare(struct request *rq);
void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
+enum {
+ BLK_FREEZE_LOCK_IO = (1 << 0),
+ BLK_FREEZE_LOCK_QUEUE = (1 << 1),
+};
+
#ifdef CONFIG_LOCKDEP
-static inline void blk_freeze_acquire_lock(struct request_queue *q)
+static inline void blk_freeze_acquire_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
- if (!q->mq_freeze_disk_dead)
+ if (lock_mask & BLK_FREEZE_LOCK_IO)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
- if (!q->mq_freeze_queue_dying)
+ if (lock_mask & BLK_FREEZE_LOCK_QUEUE)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q)
+static inline void blk_unfreeze_release_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
- if (!q->mq_freeze_queue_dying)
+ if (lock_mask & BLK_FREEZE_LOCK_QUEUE)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
- if (!q->mq_freeze_disk_dead)
+ if (lock_mask & BLK_FREEZE_LOCK_IO)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
#else
-static inline void blk_freeze_acquire_lock(struct request_queue *q)
+static inline void blk_freeze_acquire_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q)
+static inline void blk_unfreeze_release_lock(struct request_queue *q,
+ unsigned int lock_mask)
{
}
#endif
diff --git a/block/genhd.c b/block/genhd.c
index 10ca8b4d6..e73349b74 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -657,13 +657,13 @@ static void blk_report_disk_dead(struct gendisk *disk, bool surprise)
rcu_read_unlock();
}
-static bool __blk_mark_disk_dead(struct gendisk *disk)
+static unsigned int __blk_mark_disk_dead(struct gendisk *disk)
{
/*
* Fail any new I/O.
*/
if (test_and_set_bit(GD_DEAD, &disk->state))
- return false;
+ return 0;
if (test_bit(GD_OWNS_QUEUE, &disk->state))
blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
@@ -699,7 +699,7 @@ static void __del_gendisk(struct gendisk *disk)
struct request_queue *q = disk->queue;
struct block_device *part;
unsigned long idx;
- bool start_drain;
+ unsigned int lock_mask;
might_sleep();
@@ -727,9 +727,8 @@ static void __del_gendisk(struct gendisk *disk)
* Drop all partitions now that the disk is marked dead.
*/
mutex_lock(&disk->open_mutex);
- start_drain = __blk_mark_disk_dead(disk);
- if (start_drain)
- blk_freeze_acquire_lock(q);
+ lock_mask = __blk_mark_disk_dead(disk);
+ blk_freeze_acquire_lock(q, lock_mask);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
@@ -777,8 +776,7 @@ static void __del_gendisk(struct gendisk *disk)
else if (queue_is_mq(q))
blk_mq_exit_queue(q);
- if (start_drain)
- blk_unfreeze_release_lock(q);
+ blk_unfreeze_release_lock(q, lock_mask);
}
static void disable_elv_switch(struct request_queue *q)
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 0c2010230..32a8e93c4 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -637,11 +637,10 @@ struct request_queue {
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
/*
- * Records disk & queue state in current context, used in unfreeze
+ * Records lockdep locks acquired in owner context, used in unfreeze
* queue
*/
- bool mq_freeze_disk_dead;
- bool mq_freeze_queue_dying;
+ unsigned int mq_freeze_lock_mask;
#endif
wait_queue_head_t mq_freeze_wq;
/*
Additional description of the patch:
### Analysis and Explanation of the Fix
#### Root Cause
The `WARNING: lock held when returning to user space!` warning on `&q->q_usage_counter(queue)` (`q->q_lockdep_map`) occurred because of a race between:
1. A thread performing `elevator_change()` (e.g., during table loading of a request-based device mapper target via `dm_setup_md_queue()` -> `add_disk()` -> `blk_register_queue()` -> `elevator_set_default()`), which calls `blk_mq_freeze_queue()` followed by `blk_mq_unfreeze_queue()`.
2. A concurrent thread calling `blk_mark_disk_dead()` (e.g., during device removal via `dm_destroy()`), which sets `QUEUE_FLAG_DYING` and starts queue draining via `__blk_freeze_queue_start()`.
Previously, the lockdep tracking for queue freeze/unfreeze stored `q->mq_freeze_queue_dying` and `q->mq_freeze_disk_dead` directly in `struct request_queue`, protected by `q->mq_freeze_lock` only during freeze initiation when `!q->mq_freeze_depth`. On unfreeze, `__blk_mq_unfreeze_queue()` decremented `q->mq_freeze_depth` to `0`, cleared `q->mq_freeze_owner = NULL`, and dropped `q->mq_freeze_lock`. Only **after** unlocking did `blk_mq_unfreeze_queue_nomemrestore()` invoke `blk_unfreeze_release_lock(q)`.
Because `q->mq_freeze_lock` was dropped while depth was 0, a concurrent call to `blk_mark_disk_dead()` could acquire `q->mq_freeze_lock`, see `!q->mq_freeze_depth`, and overwrite `q->mq_freeze_queue_dying = true` before `blk_unfreeze_release_lock(q)` executed on the unfreezing thread. As a result, `blk_unfreeze_release_lock()` evaluated `!q->mq_freeze_queue_dying` as `false` and skipped releasing `q->q_lockdep_map`, leaking the held lockdep lock back to user space.
Furthermore, `blk_queue_start_drain()` previously passed `current` as the freeze owner to `__blk_freeze_queue_start()`. When `QUEUE_FLAG_DYING` was set, queue draining is permanent and does not release lockdep maps; setting or incrementing freeze ownership on dying queues could corrupt owner tracking if called in contexts already holding an outer freeze.
---
#### Implementation Details
1. **Per-Queue State Replaced with a Snapshotted Lock Mask:**
- In `struct request_queue` (`include/linux/blkdev.h`), replaced `bool mq_freeze_disk_dead` and `bool mq_freeze_queue_dying` with `unsigned int mq_freeze_lock_mask`.
- Defined `BLK_FREEZE_LOCK_IO` and `BLK_FREEZE_LOCK_QUEUE` bit flags in `block/blk.h`.
- Updated `blk_freeze_acquire_lock()` and `blk_unfreeze_release_lock()` to accept `unsigned int lock_mask` by value, removing all unlocked reads of mutable `request_queue` lockdep fields. Lock release order (`BLK_FREEZE_LOCK_QUEUE` followed by `BLK_FREEZE_LOCK_IO`) preserves strict LIFO ordering relative to lock acquisition.
2. **Snapshotting Lock Masks Under `q->mq_freeze_lock`:**
- In `block/blk-mq.c`, `blk_freeze_set_owner()` computes and records the applicable lock mask (`q->mq_freeze_lock_mask`) only on the outermost freeze (`!q->mq_freeze_depth`) under `q->mq_freeze_lock`, and returns it by value. Nested freezes return 0.
- `blk_unfreeze_check_owner()` returns `q->mq_freeze_lock_mask` by value when `mq_freeze_owner_depth` reaches 0 under `q->mq_freeze_lock`.
- `__blk_freeze_queue_start()` and `__blk_mq_unfreeze_queue()` return this `unsigned int lock_mask` from within their `q->mq_freeze_lock` critical sections.
- Callers (`blk_freeze_queue_start()` and `blk_mq_unfreeze_queue_nomemrestore()`) pass the returned `lock_mask` into `blk_freeze_acquire_lock()` and `blk_unfreeze_release_lock()` respectively. Because the unfreezing thread holds its own copy of `lock_mask` on the stack, concurrent freezes modifying `request_queue` fields can no longer corrupt the unfreeze lockdep release.
3. **Queue Draining Ownership Handling:**
- In `blk_queue_start_drain()` (`block/blk-core.c`), pass `blk_queue_dying(q) ? NULL : current` to `__blk_freeze_queue_start()` so that permanent dying drains do not claim or increment freeze owner depth.
- Updated `__blk_mark_disk_dead()` and `__del_gendisk()` (`block/genhd.c`) to propagate and consume the `unsigned int lock_mask` when acquiring and releasing queue freeze locks across partition drop and gendisk teardown.
Here are summaries of recent commits that touched the same files.
Format the summary line consistently with these, look how prefixes
are specified, letter capitalization, style, etc.
block: apply the segment size to the integrity buffer
blk-mq: set up a queue under tag_list_lock
blk-mq: exit the hctxs of a queue under tag_list_lock
blk-mq: quiesce a queue that joins a quiesced tag set
blk-mq: don't forget a timer the driver has restarted
blk-mq: don't bring back flags of a completed request
blk-mq: keep sharing tags fairly after a queue update
blk-mq: don't trust the cookie in blk_mq_poll()
blk-mq: clear stale inactive flag on hctx reuse
blk-mq: drop the tag_set argument from blk_mq_free_rq_map/tags
blk-mq: share one tags_srcu instance across all tag sets
block: fix indention for dma-buf checks
block: add dma-buf support for raw bdev
block: introduce dma map backed bio type
block: Include error-injection.h for ALLOW_ERROR_INJECTION()
block: drop the cached plug time when blk_add_rq_to_plug() flushes
blk-mq: allow cached requests to be used for flush operations
blk-mq: set RQF_USE_SCHED when the operation is known
block: fail zone management operations to read-only and offline zones
block: serialize zone revalidation
Reply: block: snapshot lock mask to fix queue freeze lockdep race
A race between queue freeze/unfreeze operations and concurrent queue death
or draining can cause lockdep to report a lock held when returning to user
space:
================================================
WARNING: lock held when returning to user space!
...
task is leaving the kernel with locks still held!
locks held:
(&q->q_usage_counter(queue)){+.+.}-{0:0}, at: elevator_change+0x194/0x480
block/elevator.c:668
The lockdep tracking for queue freeze and unfreeze previously stored
mq_freeze_queue_dying and mq_freeze_disk_dead directly in struct
request_queue. These fields were initialized under q->mq_freeze_lock on the
outermost freeze (when !q->mq_freeze_depth). During unfreeze,
__blk_mq_unfreeze_queue() decremented q->mq_freeze_depth to 0, cleared
q->mq_freeze_owner, and released q->mq_freeze_lock. Only after releasing
the mutex did blk_mq_unfreeze_queue_nomemrestore() call
blk_unfreeze_release_lock(q), which inspected q->mq_freeze_queue_dying and
q->mq_freeze_disk_dead without holding q->mq_freeze_lock.
If another thread concurrently initiates queue draining or marks the queue
dying (such as during device destruction via blk_mark_disk_dead()), it sets
QUEUE_FLAG_DYING and calls __blk_freeze_queue_start(). Because
q->mq_freeze_depth has already dropped to 0 and q->mq_freeze_lock is
unlocked, the second thread acquires q->mq_freeze_lock, sees depth 0, and
overwrites q->mq_freeze_queue_dying with true. When the unfreezing thread
subsequently executes blk_unfreeze_release_lock(), it observes
q->mq_freeze_queue_dying as true, skips releasing q->q_lockdep_map, and
exits back to user space with the lockdep map still held.
Additionally, blk_queue_start_drain() unconditionally passed current as the
freeze owner to __blk_freeze_queue_start(). Because draining a dying queue
is permanent and does not release lockdep maps, tracking freeze ownership
on dying queues can corrupt owner tracking if called in contexts that
already hold an outer freeze.
Fix these issues by replacing the mutable per-queue boolean flags with a
snapshotted lock mask returned by value. Define BLK_FREEZE_LOCK_IO and
BLK_FREEZE_LOCK_QUEUE bit flags and store unsigned int mq_freeze_lock_mask
in struct request_queue. In blk_freeze_set_owner() and
blk_unfreeze_check_owner(), compute and retrieve the lock mask while
holding q->mq_freeze_lock, returning it by value from
__blk_freeze_queue_start() and __blk_mq_unfreeze_queue(). Pass the lock
mask by value to blk_freeze_acquire_lock() and blk_unfreeze_release_lock(),
avoiding unlocked reads of mutable request_queue fields after dropping
q->mq_freeze_lock. In blk_queue_start_drain(), pass NULL as owner to
__blk_freeze_queue_start() when blk_queue_dying(q) is true, preventing
permanent dying drains from claiming freeze ownership. Finally, propagate
and consume the lock mask in __blk_mark_disk_dead() and __del_gendisk().
|
| 635/2 |
2026/11/03 23:48 |
llm |
description-generator |
1m
Model:
Tokens:
input: 18357
output: 29
thoughts: 272
Thoughts: **Crafting a Precise Kernel Patch Commit Description**
Okay, so I need to create a commit description for a kernel patch that fixes a bug. The goal here is a clean, informative description, and I need to make it as concise as possible. First, the one-line summary has to be under 72 characters, keeping with the established format β something like `blk-mq: ...` or `block: ...` β but I need to focus on *what* the change does, not just the testing tool used. The body of the commit is key. I'll need to clearly explain the bug itself and how my patch resolves it, sticking to single-line paragraphs to maintain readability. I will ensure no lines start with `#`, `--`, or `---`. I must avoid any language that points to the triggering mechanism, whether a fuzzer or specific tools were used. If this crash was flagged by a sanitizer, such as a lockdep warning, I'll incorporate the important pieces of its output, but I'll skip the irrelevant bits and detail the execution path that leads to the bug's manifestation. Finally, the response *must* contain only the commit description text. Before I proceed, I need to check the Git history of `block/blk-mq.c`, `block/blk.h`, and `block/blk-core.c` around lockdep freeze tracking to see how similar commits have been formatted.
|
| 636/2 |
2026/11/03 23:49 |
tool |
git-log |
10m
Error:
Args: map[CodeRegexp:mq_freeze_queue_dying Count:5]
Results:
|
| 637/2 |
2026/11/03 23:59 |
llm |
description-generator |
0m
Model:
Tokens:
input: 18991
output: 36
thoughts: 10
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Adding a Path Prefix: "block/"**
Alright, so the architecture currently stands as it is, but I'm thinking about a minor tweak here, a sort of organizational refinement, really. Let's introduce a `PathPrefix="block/"`. It's a small change, but strategically, it could offer a few advantages down the line. I'm visualizing this as a way to clearly delineate a specific area or service within the larger system. Perhaps we're anticipating adding functionality or handling a particular data stream in that section, "block/", making it a logical container. Or maybe it's purely for routing purposes, to improve the readability and maintainability of our configuration files. It's essentially about creating a dedicated namespace, preventing potential collisions with other paths. I'll need to consider how this prefix impacts the existing routing logic, of course, ensuring that everything integrates seamlessly, but conceptually, "block/" feels right for this. I'll have to see how it looks.
|
| 638/2 |
2026/11/04 00:00 |
tool |
git-log |
0m
Args: map[CodeRegexp:mq_freeze_queue_dying Count:5 PathPrefix:block]
Results: map[Output:f6661b1d0525 block: track queue dying state automatically for modeling queue freeze lockdep
]
|
| 639/2 |
2026/11/04 00:00 |
llm |
description-generator |
0m
Model:
Tokens:
input: 19299
output: 27
thoughts: 25
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Analyzing Commit f6661b1d0525 with git-show**
Alright, let's dive in. I need to take a look at the details of commit `f6661b1d0525`. My initial approach is going to be `git show`. It's a fundamental tool, but perfectly adequate for a quick overview. I'm expecting this will give me the commit message, author, date, and, crucially, the diff. Based on that information, I'll start to form an understanding of the nature of this particular commit. Depending on what I see, I might start speculating on the why's and how's of the change. Is it a bug fix? A new feature? Refactoring? The diff will be the key to answering those questions. I'll be looking specifically at the context of the code, so I can see what was changed. I will be looking for patterns, or unusual code constructions. From the context, I will also be trying to infer the impact of those changes. If it is substantial, I'll need to check the codebase to assess the impact of those changes. If it is minor, I'll look for similar structures to identify possible issues.
|
| 640/2 |
2026/11/04 00:00 |
tool |
git-show |
0m
Args:
Results: map[Output:commit f6661b1d0525f3764596a1b65eeed9e75aecafa7
Author: Ming Lei <ming.lei@redhat.com>
Date: Wed Nov 27 21:51:30 2024 +0800
block: track queue dying state automatically for modeling queue freeze lockdep
Now we only verify the outmost freeze & unfreeze in current context in case
that !q->mq_freeze_depth, so it is reliable to save queue lying state when
we want to lock the freeze queue since the state is one per-task variable
now.
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241127135133.3952153-5-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 0c6a319fb936..fca2ec64a06b 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -134,6 +134,7 @@ static bool blk_freeze_set_owner(struct request_queue *q,
q->mq_freeze_disk_dead = !q->disk ||
test_bit(GD_DEAD, &q->disk->state) ||
!blk_queue_registered(q);
+ q->mq_freeze_queue_dying = blk_queue_dying(q);
return true;
}
@@ -190,7 +191,7 @@ bool __blk_freeze_queue_start(struct request_queue *q,
void blk_freeze_queue_start(struct request_queue *q)
{
if (__blk_freeze_queue_start(q, current))
- blk_freeze_acquire_lock(q, false);
+ blk_freeze_acquire_lock(q);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -238,7 +239,7 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
void blk_mq_unfreeze_queue(struct request_queue *q)
{
if (__blk_mq_unfreeze_queue(q, false))
- blk_unfreeze_release_lock(q, false);
+ blk_unfreeze_release_lock(q);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
diff --git a/block/blk.h b/block/blk.h
index 8708168d50e4..cbf6a676ffe9 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -721,26 +721,26 @@ void blk_integrity_prepare(struct request *rq);
void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
#ifdef CONFIG_LOCKDEP
-static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
- if (!queue_dying)
+ if (!q->mq_freeze_queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
- if (!queue_dying)
+ if (!q->mq_freeze_queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
#else
-static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_freeze_acquire_lock(struct request_queue *q)
{
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
+static inline void blk_unfreeze_release_lock(struct request_queue *q)
{
}
#endif
diff --git a/block/genhd.c b/block/genhd.c
index 59ac299909b3..5678194b6b1a 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -661,7 +661,7 @@ void del_gendisk(struct gendisk *disk)
struct request_queue *q = disk->queue;
struct block_device *part;
unsigned long idx;
- bool start_drain, queue_dying;
+ bool start_drain;
might_sleep();
@@ -690,9 +690,8 @@ void del_gendisk(struct gendisk *disk)
*/
mutex_lock(&disk->open_mutex);
start_drain = __blk_mark_disk_dead(disk);
- queue_dying = blk_queue_dying(q);
if (start_drain)
- blk_freeze_acquire_lock(q, queue_dying);
+ blk_freeze_acquire_lock(q);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
@@ -748,7 +747,7 @@ void del_gendisk(struct gendisk *disk)
blk_mq_exit_queue(q);
if (start_drain)
- blk_unfreeze_release_lock(q, queue_dying);
+ blk_unfreeze_release_lock(q);
}
EXPORT_SYMBOL(del_gendisk);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 522cf8eef66c..5d40af2ef971 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -581,8 +581,12 @@ struct request_queue {
#ifdef CONFIG_LOCKDEP
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
- /* Records disk state in current context, used in unfreeze queue */
+ /*
+ * Records disk & queue state in current context, used in unfreeze
+ * queue
+ */
bool mq_freeze_disk_dead;
+ bool mq_freeze_queue_dying;
#endif
wait_queue_head_t mq_freeze_wq;
/*
]
|
| 641/2 |
2026/11/04 00:00 |
llm |
description-generator |
0m
Model:
Tokens:
input: 21520
output: 26
thoughts: 14
Thoughts: Okay, here's my attempt at summarizing that thought process, keeping in mind the expert user and the first-person perspective:
**Delving Deeper: Contextual Commit Exploration**
Alright, I need to understand this series or related commits better. Simply looking at this single commit isn't enough to grasp the broader picture. My instinct is to expand my investigation. Let's not just limit ourselves to this specific change. I'm thinking, "Let's also see other commits around that series or related commits." I need to see the surrounding context, the history, and the evolution that led to this point. I need to uncover the dependencies and the reasoning behind these modifications. That context is crucial for a complete understanding.
|
| 642/2 |
2026/11/04 00:01 |
tool |
git-log |
0m
Args: map[Count:5 MessageRegexps:[modeling queue freeze lockdep]]
Results: map[Output:f6661b1d0525 block: track queue dying state automatically for modeling queue freeze lockdep
6f491a8d4b92 block: track disk DEAD state automatically for modeling queue freeze lockdep
]
|
| 643/2 |
2026/11/04 00:01 |
llm |
description-generator |
0m
Model:
Tokens:
input: 21776
output: 27
thoughts: 19
Thoughts: Okay, here's my attempt at summarizing the thought process, tailored for an expert audience, and written in the first person:
**Analyzing the Relevant Artifact**
Right, let's take a look at this. Immediately, my mental radar flags `6f491a8d4b92`. I recognize that this identifier likely points to a critical piece of the puzzle. I can't ignore it. Itβs either a configuration setting, a specific data record, a function, a module...the structure alone tells me there's something to investigate further.
Now, my focus shifts to what that specific segment *means* within the larger context. Given what I'm dealing with, I'm expecting this artifact to provide some crucial insight. I will now examine that piece.
|
| 644/2 |
2026/11/04 00:02 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 6f491a8d4b92d1a840fd9209cba783c84437d0b7
Author: Ming Lei <ming.lei@redhat.com>
Date: Wed Nov 27 21:51:28 2024 +0800
block: track disk DEAD state automatically for modeling queue freeze lockdep
Now we only verify the outmost freeze & unfreeze in current context in case
that !q->mq_freeze_depth, so it is reliable to save disk DEAD state when
we want to lock the freeze queue since the state is one per-task variable
now.
Doing this way can kill lots of false positive when freeze queue is
called before adding disk[1].
[1] https://lore.kernel.org/linux-block/6741f6b2.050a0220.1cc393.0017.GAE@google.com/
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Link: https://lore.kernel.org/r/20241127135133.3952153-3-ming.lei@redhat.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/block/blk-mq.c b/block/blk-mq.c
index 60f457f62913..0c6a319fb936 100644
--- a/block/blk-mq.c
+++ b/block/blk-mq.c
@@ -131,6 +131,9 @@ static bool blk_freeze_set_owner(struct request_queue *q,
if (!q->mq_freeze_depth) {
q->mq_freeze_owner = owner;
q->mq_freeze_owner_depth = 1;
+ q->mq_freeze_disk_dead = !q->disk ||
+ test_bit(GD_DEAD, &q->disk->state) ||
+ !blk_queue_registered(q);
return true;
}
@@ -187,7 +190,7 @@ bool __blk_freeze_queue_start(struct request_queue *q,
void blk_freeze_queue_start(struct request_queue *q)
{
if (__blk_freeze_queue_start(q, current))
- blk_freeze_acquire_lock(q, false, false);
+ blk_freeze_acquire_lock(q, false);
}
EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
@@ -235,7 +238,7 @@ bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
void blk_mq_unfreeze_queue(struct request_queue *q)
{
if (__blk_mq_unfreeze_queue(q, false))
- blk_unfreeze_release_lock(q, false, false);
+ blk_unfreeze_release_lock(q, false);
}
EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
diff --git a/block/blk.h b/block/blk.h
index 2c26abf505b8..8708168d50e4 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -720,22 +720,29 @@ void blk_integrity_verify(struct bio *bio);
void blk_integrity_prepare(struct request *rq);
void blk_integrity_complete(struct request *rq, unsigned int nr_bytes);
-static inline void blk_freeze_acquire_lock(struct request_queue *q, bool
- disk_dead, bool queue_dying)
+#ifdef CONFIG_LOCKDEP
+static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
{
- if (!disk_dead)
+ if (!q->mq_freeze_disk_dead)
rwsem_acquire(&q->io_lockdep_map, 0, 1, _RET_IP_);
if (!queue_dying)
rwsem_acquire(&q->q_lockdep_map, 0, 1, _RET_IP_);
}
-static inline void blk_unfreeze_release_lock(struct request_queue *q, bool
- disk_dead, bool queue_dying)
+static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
{
if (!queue_dying)
rwsem_release(&q->q_lockdep_map, _RET_IP_);
- if (!disk_dead)
+ if (!q->mq_freeze_disk_dead)
rwsem_release(&q->io_lockdep_map, _RET_IP_);
}
+#else
+static inline void blk_freeze_acquire_lock(struct request_queue *q, bool queue_dying)
+{
+}
+static inline void blk_unfreeze_release_lock(struct request_queue *q, bool queue_dying)
+{
+}
+#endif
#endif /* BLK_INTERNAL_H */
diff --git a/block/elevator.c b/block/elevator.c
index 7c3ba80e5ff4..ca0a74369f1c 100644
--- a/block/elevator.c
+++ b/block/elevator.c
@@ -602,14 +602,14 @@ void elevator_init_mq(struct request_queue *q)
* Disk isn't added yet, so verifying queue lock only manually.
*/
blk_freeze_queue_start_non_owner(q);
- blk_freeze_acquire_lock(q, true, false);
+ blk_freeze_acquire_lock(q, false);
blk_mq_freeze_queue_wait(q);
blk_mq_cancel_work_sync(q);
err = blk_mq_init_sched(q, e);
- blk_unfreeze_release_lock(q, true, false);
+ blk_unfreeze_release_lock(q, false);
blk_mq_unfreeze_queue_non_owner(q);
if (err) {
diff --git a/block/genhd.c b/block/genhd.c
index 79230c109fca..59ac299909b3 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -692,7 +692,7 @@ void del_gendisk(struct gendisk *disk)
start_drain = __blk_mark_disk_dead(disk);
queue_dying = blk_queue_dying(q);
if (start_drain)
- blk_freeze_acquire_lock(q, true, queue_dying);
+ blk_freeze_acquire_lock(q, queue_dying);
xa_for_each_start(&disk->part_tbl, idx, part, 1)
drop_partition(part);
mutex_unlock(&disk->open_mutex);
@@ -748,7 +748,7 @@ void del_gendisk(struct gendisk *disk)
blk_mq_exit_queue(q);
if (start_drain)
- blk_unfreeze_release_lock(q, true, queue_dying);
+ blk_unfreeze_release_lock(q, queue_dying);
}
EXPORT_SYMBOL(del_gendisk);
diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h
index 378d3a1a22fc..522cf8eef66c 100644
--- a/include/linux/blkdev.h
+++ b/include/linux/blkdev.h
@@ -581,6 +581,8 @@ struct request_queue {
#ifdef CONFIG_LOCKDEP
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
+ /* Records disk state in current context, used in unfreeze queue */
+ bool mq_freeze_disk_dead;
#endif
wait_queue_head_t mq_freeze_wq;
/*
]
|
| 645/2 |
2026/11/04 00:02 |
llm |
description-generator |
1m
Model:
Tokens:
input: 24142
output: 768
thoughts: 12334
Thoughts: **block: snapshot lock mask to fix queue freeze lockdep race**
|