Skip to contentSkip to conversation

general protection fault in lo_rw_aio

syzbot Superseded syzbot 14 participants 78 messages Apr 18 – Sep 5

Subsystems (4)
lore
Share & tools
lore

syzbot

author syzbot
#0 lore raw

Hello,

syzbot found the following issue on:

HEAD commit:    43cfbdda5af6 Merge tag 'for-linus-iommufd' of git://git.ke..
git tree:       upstream
console output: https://syzkaller.appspot.com/x/log.txt?x=101e4702580000
kernel config:  https://syzkaller.appspot.com/x/.config?x=4660d1ff2985517b
dashboard link: https://syzkaller.appspot.com/bug?extid=cd8a9a308e879a4e2c28
compiler:       Debian clang version 21.1.8 (++20251221033036+2078da43e25a-1~exp1~20251221153213.50), Debian LLD 21.1.8

Unfortunately, I don't have any reproducer for this issue yet.

Downloadable assets:
disk image: https://storage.googleapis.com/syzbot-assets/0867fa0b89e8/disk-43cfbdda.raw.xz
vmlinux: https://storage.googleapis.com/syzbot-assets/754859270006/vmlinux-43cfbdda.xz
kernel image: https://storage.googleapis.com/syzbot-assets/cd6cca8d06c9/bzImage-43cfbdda.xz

IMPORTANT: if you fix the issue, please add the following tag to the commit:

Reported-by [email protected]
Oops: general protection fault, probably for non-canonical address 0xdffffc0000000014: 0000 [#1] SMP KASAN PTI
KASAN: null-ptr-deref in range [0x00000000000000a0-0x00000000000000a7]
CPU: 1 UID: 0 PID: 1174 Comm: kworker/u8:8 Not tainted syzkaller #0 PREEMPT_{RT,(full)} 
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 03/18/2026
Workqueue: loop2 loop_workfn
RIP: 0010:file_inode include/linux/fs.h:1353 [inline]
RIP: 0010:kiocb_start_write include/linux/fs.h:2763 [inline]
RIP: 0010:lo_rw_aio+0xaa9/0xf00 drivers/block/loop.c:401
Code: 89 33 31 ff 8b 5c 24 44 89 de e8 32 2b 3f fc 85 db 0f 84 ca 00 00 00 48 8b 44 24 58 48 8d 98 a0 00 00 00 48 89 d8 48 c1 e8 03 <42> 80 3c 28 00 74 08 48 89 df e8 e8 ae a5 fc 4c 89 7c 24 10 48 8b
RSP: 0018:ffffc9000655f620 EFLAGS: 00010206
RAX: 0000000000000014 RBX: 00000000000000a0 RCX: ffff888029649ec0
RDX: 0000000000000000 RSI: 0000000000000001 RDI: 0000000000000000
RBP: ffffc9000655f790 R08: 0000000000000000 R09: 0000000000000000
R10: ffffc9000655f6e3 R11: fffff52000cabede R12: ffff888026c9b090
R13: dffffc0000000000 R14: 0000000000000000 R15: ffff888026c9b0b0
FS:  0000000000000000(0000) GS:ffff88812620f000(0000) knlGS:0000000000000000
CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 0000555591947a68 CR3: 000000005515a000 CR4: 00000000003526f0
Call Trace:
 <TASK>
 do_req_filebacked drivers/block/loop.c:433 [inline]
 loop_handle_cmd drivers/block/loop.c:1925 [inline]
 loop_process_work+0x637/0x11b0 drivers/block/loop.c:1960
 process_one_work kernel/workqueue.c:3302 [inline]
 process_scheduled_works+0xb5d/0x1860 kernel/workqueue.c:3385
 worker_thread+0xa53/0xfc0 kernel/workqueue.c:3466
 kthread+0x388/0x470 kernel/kthread.c:436
 ret_from_fork+0x514/0xb70 arch/x86/kernel/process.c:158
 ret_from_fork_asm+0x1a/0x30 arch/x86/entry/entry_64.S:245
 </TASK>
Modules linked in:
---[ end trace 0000000000000000 ]---
RIP: 0010:file_inode include/linux/fs.h:1353 [inline]
RIP: 0010:kiocb_start_write include/linux/fs.h:2763 [inline]
RIP: 0010:lo_rw_aio+0xaa9/0xf00 drivers/block/loop.c:401
Code: 89 33 31 ff 8b 5c 24 44 89 de e8 32 2b 3f fc 85 db 0f 84 ca 00 00 00 48 8b 44 24 58 48 8d 98 a0 00 00 00 48 89 d8 48 c1 e8 03 <42> 80 3c 28 00 74 08 48 89 df e8 e8 ae a5 fc 4c 89 7c 24 10 48 8b
RSP: 0018:ffffc9000655f620 EFLAGS: 00010206
RAX: 0000000000000014 RBX: 00000000000000a0 RCX: ffff888029649ec0
RDX: 0000000000000000 RSI: 0000000000000001 RDI: 0000000000000000
RBP: ffffc9000655f790 R08: 0000000000000000 R09: 0000000000000000
R10: ffffc9000655f6e3 R11: fffff52000cabede R12: ffff888026c9b090
R13: dffffc0000000000 R14: 0000000000000000 R15: ffff888026c9b0b0
FS:  0000000000000000(0000) GS:ffff88812620f000(0000) knlGS:0000000000000000
CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 0000555591947a68 CR3: 000000005515a000 CR4: 00000000003526f0
----------------
Code disassembly (best guess):
   0:	89 33                	mov    %esi,(%rbx)
   2:	31 ff                	xor    %edi,%edi
   4:	8b 5c 24 44          	mov    0x44(%rsp),%ebx
   8:	89 de                	mov    %ebx,%esi
   a:	e8 32 2b 3f fc       	call   0xfc3f2b41
   f:	85 db                	test   %ebx,%ebx
  11:	0f 84 ca 00 00 00    	je     0xe1
  17:	48 8b 44 24 58       	mov    0x58(%rsp),%rax
  1c:	48 8d 98 a0 00 00 00 	lea    0xa0(%rax),%rbx
  23:	48 89 d8             	mov    %rbx,%rax
  26:	48 c1 e8 03          	shr    $0x3,%rax
* 2a:	42 80 3c 28 00       	cmpb   $0x0,(%rax,%r13,1) <-- trapping instruction
  2f:	74 08                	je     0x39
  31:	48 89 df             	mov    %rbx,%rdi
  34:	e8 e8 ae a5 fc       	call   0xfca5af21
  39:	4c 89 7c 24 10       	mov    %r15,0x10(%rsp)
  3e:	48                   	rex.W
  3f:	8b                   	.byte 0x8b

---
This report is generated by a bot. It may contain errors. See https://goo.gl/tpsmEJ for more information about syzbot. syzbot engineers can be reached at [email protected].

syzbot will keep track of this issue. See:
https://goo.gl/tpsmEJ#status for how to communicate with syzbot.

If the report is already addressed, let syzbot know by replying with:
#syz fix: exact-commit-title

If you want to overwrite report's subsystems, reply with:
#syz set subsystems: new-subsystem
(See the list of subsystem names on the web dashboard)

If the report is a duplicate of another one, reply with:
#syz dup: exact-subject-of-another-report

If you want to undo deduplication, reply with:
#syz undup

#1 lore raw

I confirmed that this NULL pointer dereference is triggered by __loop_clr_fd() clearing lo->lo_backing_file before aio request is processed. A debug printk() patch at
https://git.kernel.org/pub/scm/linux/kernel/git/next/linux-next.git/commit/drivers/block/loop.c?h=next-20260420&id=7454b88731fd320e7dbfbf1ea72f25705c3befc0
generated the following output.

file == NULL
Last __loop_clr_fd() call was 5 jiffies ago by udevd (16676)

     lo_release+0x35b/0x9d0
     blkdev_release+0x15/0x20 block/fops.c:705
     __fput+0x461/0xa70 fs/file_table.c:510
     fput_close_sync+0x11f/0x240 fs/file_table.c:615
     __do_sys_close fs/open.c:1507 [inline]
     __se_sys_close fs/open.c:1492 [inline]
     __x64_sys_close+0x7e/0x110 fs/open.c:1492
     do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
     do_syscall_64+0x15f/0xf80 arch/x86/entry/syscall_64.c:94
     entry_SYSCALL_64_after_hwframe+0x77/0x7f
Oops: general protection fault, probably for non-canonical address 0xdffffc0000000014: 0000 [#1] SMP KASAN PTI
KASAN: null-ptr-deref in range [0x00000000000000a0-0x00000000000000a7]
CPU: 0 UID: 0 PID: 180 Comm: kworker/u8:6 Tainted: G             L      syzkaller #0 PREEMPT_{RT,(full)} 
Tainted: [L]=SOFTLOCKUP
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 03/18/2026
Workqueue: loop4 loop_workfn
RIP: 0010:file_inode include/linux/fs.h:1353 [inline]
RIP: 0010:kiocb_start_write include/linux/fs.h:2756 [inline]
RIP: 0010:lo_rw_aio+0xb88/0x1190 drivers/block/loop.c:429
Code: 1e d8 34 fc 45 85 e4 0f 84 d8 00 00 00 48 8b 44 24 58 48 8d 98 a0 00 00 00 48 89 d8 48 c1 e8 03 48 b9 00 00 00 00 00 fc ff df <80> 3c 08 00 74 08 48 89 df e8 8a 4c 9e fc 48 8b 1b 48 83 c3 28 49
RSP: 0018:ffffc90003907660 EFLAGS: 00010206
RAX: 0000000000000014 RBX: 00000000000000a0 RCX: dffffc0000000000
RDX: 0000000000000000 RSI: 0000000000000001 RDI: 0000000000000000
RBP: ffffc900039077d0 R08: 0000000000000000 R09: 0000000000000000
R10: ffffc90003907723 R11: fffff52000720ee6 R12: 0000000000000001
R13: ffff888026ca2c90 R14: 0000000000000000 R15: dffffc0000000000
FS:  0000000000000000(0000) GS:ffff888125eb7000(0000) knlGS:0000000000000000
CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 000055555b199a28 CR3: 000000003a2c0000 CR4: 00000000003526f0
Call Trace:
 <TASK>
 do_req_filebacked drivers/block/loop.c:461 [inline]
 loop_handle_cmd drivers/block/loop.c:1960 [inline]
 loop_process_work+0x647/0x1560 drivers/block/loop.c:1995
 process_one_work+0x9a3/0x1710 kernel/workqueue.c:3312
 process_scheduled_works kernel/workqueue.c:3403 [inline]
 worker_thread+0xba8/0x11e0 kernel/workqueue.c:3489
 kthread+0x388/0x470 kernel/kthread.c:436
 ret_from_fork+0x514/0xb70 arch/x86/kernel/process.c:158
 ret_from_fork_asm+0x1a/0x30 arch/x86/entry/entry_64.S:245
 </TASK>
Modules linked in:
---[ end trace 0000000000000000 ]---
RIP: 0010:file_inode include/linux/fs.h:1353 [inline]
RIP: 0010:kiocb_start_write include/linux/fs.h:2756 [inline]
RIP: 0010:lo_rw_aio+0xb88/0x1190 drivers/block/loop.c:429
Code: 1e d8 34 fc 45 85 e4 0f 84 d8 00 00 00 48 8b 44 24 58 48 8d 98 a0 00 00 00 48 89 d8 48 c1 e8 03 48 b9 00 00 00 00 00 fc ff df <80> 3c 08 00 74 08 48 89 df e8 8a 4c 9e fc 48 8b 1b 48 83 c3 28 49
RSP: 0018:ffffc90003907660 EFLAGS: 00010206
RAX: 0000000000000014 RBX: 00000000000000a0 RCX: dffffc0000000000
RDX: 0000000000000000 RSI: 0000000000000001 RDI: 0000000000000000
RBP: ffffc900039077d0 R08: 0000000000000000 R09: 0000000000000000
R10: ffffc90003907723 R11: fffff52000720ee6 R12: 0000000000000001
R13: ffff888026ca2c90 R14: 0000000000000000 R15: dffffc0000000000
FS:  0000000000000000(0000) GS:ffff888125eb7000(0000) knlGS:0000000000000000
CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 000055555b199a28 CR3: 000000003a2c0000 CR4: 00000000003526f0

Either fput() is called without corresponding fget(), or some recent changes has changed timing of start processing aio request?

Since this problem started after the merge window opened, the culprit commit might be in between commit a028739a4330 ("Merge tag 'block-7.0-20260305' of
git://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux") and commit 7fe6ac157b7e ("Merge tag 'for-7.1/block-20260411' of
git://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux").
Also, syzbot was not testing changes in linux-next since next-20260403, and found this problem in next-20260413.

#2 lore raw

PATCH 1/1 loop: Fix NULL pointer dereference by synchronizing lo_release and loop_queue_rq

Summary:
This patch addresses a NULL pointer dereference in lo_rw_aio() by introducing SRCU-based synchronization and explicit workqueue draining during device release. This race appears to have been exacerbated or introduced by recent changes in the block layer's request completion and freezing logic.

Problem Description:
A NULL pointer dereference was reported by syzbot. The crash occurs when lo_rw_aio() access lo->lo_backing_file which has already been cleared by __loop_clr_fd().

The investigation suggests a gap between loop_queue_rq() and the driver's internal workqueue. Even when the block layer attempts to freeze the queue, requests that have already passed the loop_queue_rq() state check but have not yet been queued to lo->workqueue can "leak" and execute after lo_release() has proceeded to teardown the device.

Suspicious Commits and Behavioral Changes:
We suspect this race became visible due to behavioral changes in how the block layer handles request completion and synchronization, specifically:

1. Commit 65565ca5f99b ("block: unify the synchronous bi_end_io callbacks"): This unified completion path might have altered the timing or the visibility of in-flight requests during a queue freeze, allowing lo_release() to proceed before the loop driver's internal asynchronous work has been fully accounted for.

2. Changes in blk_mq_freeze_queue(): In older kernels, the freeze mechanism might have more effectively covered the window between queue_rq and the driver's execution of that request. The current behavior seems to allow __loop_clr_fd() to run while loop_queue_rq() is still in the middle of scheduling work.

Stability and Backporting:
Because the underlying cause is tied to recent block layer refactoring, this patch should not be backported to older stable kernels without careful verification, as it may be unnecessary or lead to performance regressions due to the added SRCU overhead.

Solution:
The patch closes the race window using SRCU:

* loop_queue_rq: Wrapped in srcu_read_lock() to ensure that once a request passes the Lo_bound check, the corresponding queue_work() must complete before the teardown path can finish its synchronization.

* lo_release: Calls synchronize_srcu() followed by drain_workqueue(). This sequence ensures:
* No new work can be scheduled (lo_state change).
* All ongoing scheduling calls have finished (synchronize_srcu).
* All scheduled work has finished executing (drain_workqueue).
* Finally, it is safe to clear lo_backing_file.

Trace Evidence:
Console logs with debug printk() patch confirm that __loop_clr_fd() has cleared the file for loop3 between multiple lo_rw_aio() requests.

  [  122.956248][ T6148] loop3: detected capacity change from 0 to 32768
  [  122.958217][ T6142] lo_rw_aio(loop3) starting read with raw_refcnt=0x0, refcnt=1
  (...snipped...)
  [  123.234786][   T44] lo_rw_aio(loop3) starting read with raw_refcnt=0x0, refcnt=1
  [  123.254716][ T6148] __loop_clr_fd(loop3) clearing lo_backing_file with raw_refcnt=0x0, refcnt=1
  [  123.265134][  T180] lo_rw_aio(loop3) starting write with NULL file (already cleared?)
  [  123.265221][  T180] Oops: general protection fault, probably for non-canonical address 0xdffffc0000000014: 0000 [#1] SMP KASAN PTI
  [  123.265238][  T180] KASAN: null-ptr-deref in range [0x00000000000000a0-0x00000000000000a7]
  [  123.265255][  T180] CPU: 0 UID: 0 PID: 180 Comm: kworker/u8:7 Not tainted syzkaller #0 PREEMPT_{RT,(full)} 
  [  123.265276][  T180] Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 04/18/2026
  [  123.265287][  T180] Workqueue: loop3 loop_workfn
  [  123.265320][  T180] RIP: 0010:lo_rw_aio+0xd1d/0x1170
Reported-by [email protected]
Analyzed-by AI Mode in Google Search (no mail address)

---
Since this race condition is difficult to reproduce, we can't do bisection. I hope you can figure out what has changed in the block layer for this merge window. You might want to revert instead of modifying the loop driver.

 drivers/block/loop.c | 21 +++++++++++++++++++--
 1 file changed, 19 insertions(+), 2 deletions(-)
drivers/block/loop.c +19 -2
index 0000913f7efc..9be47ce97dab 100644
@@ -93,6 +93,7 @@ struct loop_cmd {
 static DEFINE_IDR(loop_index_idr);
 static DEFINE_MUTEX(loop_ctl_mutex);
 static DEFINE_MUTEX(loop_validate_mutex);
+DEFINE_SRCU(loop_io_srcu);
 
 /**
  * loop_global_lock_killable() - take locks for safe loop_validate_file() test
@@ -1747,8 +1748,19 @@ static void lo_release(struct gendisk *disk)
 	need_clear = (lo->lo_state == Lo_rundown);
 	mutex_unlock(&lo->lo_mutex);
 
-	if (need_clear)
+	if (need_clear) {
+		/*
+		 * Now that loop_queue_rq() sees lo->lo_state != Lo_bound,
+		 * wait for already started loop_queue_rq() to complete.
+		 */
+		synchronize_srcu(&loop_io_srcu);
+		/*
+		 * Now that no more works are scheduled by loop_queue_rq(),
+		 * wait for already scheduled works to complete.
+		 */
+		drain_workqueue(lo->workqueue);
 		__loop_clr_fd(lo);
+	}
 }
 
 static void lo_free_disk(struct gendisk *disk)
@@ -1854,11 +1866,15 @@ static blk_status_t loop_queue_rq(struct blk_mq_hw_ctx *hctx,
 	struct request *rq = bd->rq;
 	struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
 	struct loop_device *lo = rq->q->queuedata;
+	int idx;
 
 	blk_mq_start_request(rq);
 
-	if (data_race(READ_ONCE(lo->lo_state)) != Lo_bound)
+	idx = srcu_read_lock(&loop_io_srcu);
+	if (data_race(READ_ONCE(lo->lo_state)) != Lo_bound) {
+		srcu_read_unlock(&loop_io_srcu, idx);
 		return BLK_STS_IOERR;
+	}
 
 	switch (req_op(rq)) {
 	case REQ_OP_FLUSH:
@@ -1888,6 +1904,7 @@ static blk_status_t loop_queue_rq(struct blk_mq_hw_ctx *hctx,
 #endif
 	loop_queue_work(lo, cmd);
 
+	srcu_read_unlock(&loop_io_srcu, idx);
 	return BLK_STS_OK;
 }
 
Signature · 1 line
2.54.0
#3 lore raw

Re: [PATCH] loop: Fix NULL pointer dereference by synchronizing lo_release and loop_queue_rq

Quoted 21 lines · Tetsuo Handa
drivers/block/loop.c +5 -1
index 0000913f7efc..9be47ce97dab 100644
@@ -93,6 +93,7 @@ struct loop_cmd {
  static DEFINE_IDR(loop_index_idr);
  static DEFINE_MUTEX(loop_ctl_mutex);
  static DEFINE_MUTEX(loop_validate_mutex);
+DEFINE_SRCU(loop_io_srcu);
 
  /**
   * loop_global_lock_killable() - take locks for safe loop_validate_file() test
@@ -1747,8 +1748,19 @@ static void lo_release(struct gendisk *disk)
  	need_clear = (lo->lo_state == Lo_rundown);
  	mutex_unlock(&lo->lo_mutex);
 
-	if (need_clear)
+	if (need_clear) {
+		/*
+		 * Now that loop_queue_rq() sees lo->lo_state != Lo_bound,
+		 * wait for already started loop_queue_rq() to complete.

drivers/block/loop.c static void lo_release(struct gendisk *disk) · line 1764

Quoted 10 lines
drivers/block/loop.c +8 -0
+		 */
+		synchronize_srcu(&loop_io_srcu);
+		/*
+		 * Now that no more works are scheduled by loop_queue_rq(),
+		 * wait for already scheduled works to complete.
+		 */
+		drain_workqueue(lo->workqueue);
  		__loop_clr_fd(lo);
+	}
  }

There is already a mechanism in the block layer to wait for pending .queue_rq() calls to complete. Please take a look at blk_mq_quiesce_queue().

Quoted 19 lines
drivers/block/loop.c +5 -1
  static void lo_free_disk(struct gendisk *disk)
@@ -1854,11 +1866,15 @@ static blk_status_t loop_queue_rq(struct blk_mq_hw_ctx *hctx,
  	struct request *rq = bd->rq;
  	struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
  	struct loop_device *lo = rq->q->queuedata;
+	int idx;
 
  	blk_mq_start_request(rq);
 
-	if (data_race(READ_ONCE(lo->lo_state)) != Lo_bound)
+	idx = srcu_read_lock(&loop_io_srcu);
+	if (data_race(READ_ONCE(lo->lo_state)) != Lo_bound) {
+		srcu_read_unlock(&loop_io_srcu, idx);
  		return BLK_STS_IOERR;
+	}
 
  	switch (req_op(rq)) {
  	case REQ_OP_FLUSH:

drivers/block/loop.c static blk_status_t loop_queue_rq(struct blk_mq_hw_ctx *hctx, · line 1909

Quoted 6 lines
drivers/block/loop.c +1 -0
@@ -1888,6 +1904,7 @@ static blk_status_t loop_queue_rq(struct blk_mq_hw_ctx *hctx,
  #endif
  	loop_queue_work(lo, cmd);
 
+	srcu_read_unlock(&loop_io_srcu, idx);
  	return BLK_STS_OK;
  }

Why SRCU instead of RCU? The loop driver doesn't set BLK_MQ_F_BLOCKING and hence must not sleep inside loop_queue_rq(). Additionally, the block layer already holds an RCU lock around all loop_queue_rq() calls. From block/blk-mq.h:

/* run the code block in @dispatch_ops with rcu/srcu read lock held */
#define __blk_mq_run_dispatch_ops(q, check_sleep, dispatch_ops) \

do {								\
	if ((q)->tag_set->flags & BLK_MQ_F_BLOCKING) {		\
		struct blk_mq_tag_set *__tag_set = (q)->tag_set; \
		int srcu_idx;					\
								\
		might_sleep_if(check_sleep);			\
		srcu_idx = srcu_read_lock(__tag_set->srcu);	\
		(dispatch_ops);					\
		srcu_read_unlock(__tag_set->srcu, srcu_idx);	\
	} else {						\
		rcu_read_lock();				\
		(dispatch_ops);					\
		rcu_read_unlock();				\
	}							\
} while (0)

Thanks,

Bart.

#4 lore raw

Re: [PATCH] loop: Fix NULL pointer dereference by synchronizing lo_release and loop_queue_rq

Thank you for responding.

Given it is protected by RCU, this might be yet another manifestation of
"is trying to release lock (rcu_read_lock) at:" + "but there are no more locks to release!"-type of hidden RCU imbalance bugs recently introduced? Andrew, was any progress made for RCU imbalance bugs?

Quoted 7 lines · Tetsuo Handa

Since this problem started after the merge window opened, the culprit commit might be in between commit a028739a4330 ("Merge tag 'block-7.0-20260305' of
git://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux") and commit 7fe6ac157b7e ("Merge tag 'for-7.1/block-20260411' of
git://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux").
Also, syzbot was not testing changes in linux-next since next-20260403, and found this problem in next-20260413.

Quoted 22 lines · Bart Van Assche

Why SRCU instead of RCU? The loop driver doesn't set BLK_MQ_F_BLOCKING and hence must not sleep inside loop_queue_rq(). Additionally, the block layer already holds an RCU lock around all loop_queue_rq() calls. From block/blk-mq.h:

/* run the code block in @dispatch_ops with rcu/srcu read lock held */ #define __blk_mq_run_dispatch_ops(q, check_sleep, dispatch_ops)    \
do {                                \
    if ((q)->tag_set->flags & BLK_MQ_F_BLOCKING) {        \
        struct blk_mq_tag_set *__tag_set = (q)->tag_set; \
        int srcu_idx;                    \
                                \
        might_sleep_if(check_sleep);            \
        srcu_idx = srcu_read_lock(__tag_set->srcu);    \
        (dispatch_ops);                    \
        srcu_read_unlock(__tag_set->srcu, srcu_idx);    \
    } else {                        \
        rcu_read_lock();                \
        (dispatch_ops);                    \
        rcu_read_unlock();                \
    }                            \
} while (0)

#5 lore raw

Re: [PATCH] loop: Fix NULL pointer dereference by synchronizing lo_release and loop_queue_rq

Commit 99ebc509eef5 ("mm: memcontrol: fix rcu unbalance in get_non_dying_memcg_end()") fixed RCU imbalance bug, and it seems that so far only trees without that commit is reproducing RCU imbalance bug.

But since this NULL pointer dereference bug was reproduced in linux-next-20260508 which already includes that commit, I suspect that some change in the block layer broke protection by RCU synchronization or flushing of lo->workqueue.

Can you check that there was no commit that might break protection by RCU synchronization or flushing of lo->workqueue?

Quoted 38 lines · Tetsuo Handa

Thank you for responding.

Given it is protected by RCU, this might be yet another manifestation of
"is trying to release lock (rcu_read_lock) at:" + "but there are no more locks to release!"-type of hidden RCU imbalance bugs recently introduced? Andrew, was any progress made for RCU imbalance bugs?

Quoted 7 lines · Tetsuo Handa

Since this problem started after the merge window opened, the culprit commit might be in between commit a028739a4330 ("Merge tag 'block-7.0-20260305' of
git://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux") and commit 7fe6ac157b7e ("Merge tag 'for-7.1/block-20260411' of
git://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux").
Also, syzbot was not testing changes in linux-next since next-20260403, and found this problem in next-20260413.

Quoted 22 lines · Bart Van Assche

Why SRCU instead of RCU? The loop driver doesn't set BLK_MQ_F_BLOCKING and hence must not sleep inside loop_queue_rq(). Additionally, the block layer already holds an RCU lock around all loop_queue_rq() calls. From block/blk-mq.h:

/* run the code block in @dispatch_ops with rcu/srcu read lock held */ #define __blk_mq_run_dispatch_ops(q, check_sleep, dispatch_ops)    \
do {                                \
    if ((q)->tag_set->flags & BLK_MQ_F_BLOCKING) {        \
        struct blk_mq_tag_set *__tag_set = (q)->tag_set; \
        int srcu_idx;                    \
                                \
        might_sleep_if(check_sleep);            \
        srcu_idx = srcu_read_lock(__tag_set->srcu);    \
        (dispatch_ops);                    \
        srcu_read_unlock(__tag_set->srcu, srcu_idx);    \
    } else {                        \
        rcu_read_lock();                \
        (dispatch_ops);                    \
        rcu_read_unlock();                \
    }                            \
} while (0)

#6 lore raw

PATCH v2 1/1 loop: Fix NULL pointer dereference by synchronizing lo_release and loop_queue_rq

The loop driver relies on lo_release() to automatically clear the loop device via __loop_clr_fd() when the last file descriptor is closed (LO_FLAGS_AUTOCLEAR). Although the backing file structure itself remains allocated in memory thanks to proper file reference counting (f_count is not zero), a severe race condition exists regarding the visibility of the lo->lo_backing_file pointer.

This race window was exposed by commit 65565ca5f99b ("block: unify the synchronous bi_end_io callbacks"). By unifying and optimizing the synchronous I/O completion path, the timing and scheduling behavior of the block layer altered significantly.
As a result, a highly-concurrent execution pipeline emerged where lo_release() can progress to __loop_clr_fd() and nullify lo->lo_backing_file while an already-scheduled asynchronous I/O work (lo_rw_aio) is just about to be executed by a kworker thread.

Since the kworker enters lo_rw_aio() after lo->lo_backing_file has been cleared, it attempts to dereference the now-NULL pointer when initializing the kiocb, leading to the reported NULL pointer dereference bug.

To close this race safely without introducing heavy fast-path checks, we must ensure that any running or scheduled dispatch threads have completed before we nullify the pointer. Since loop_queue_rq() operates within the block layer's RCU read-side critical section, invoke synchronize_rcu() and drain_workqueue() in __loop_clr_fd() prior to clearing lo->lo_backing_file.

---
 drivers/block/loop.c | 11 +++++++++++
 1 file changed, 11 insertions(+)
drivers/block/loop.c +11 -0
index 0000913f7efc..ff117f340b2f 100644
@@ -1118,6 +1118,17 @@ static void __loop_clr_fd(struct loop_device *lo)
 	struct file *filp;
 	gfp_t gfp = lo->old_gfp_mask;
 
+	/*
+	 * Now that loop_queue_rq() sees lo->lo_state != Lo_bound,
+	 * wait for already started loop_queue_rq() to complete.
+	 */
+	synchronize_rcu();
+	/*
+	 * Now that no more works are scheduled by loop_queue_rq(),
+	 * wait for already scheduled works to complete.
+	 */
+	drain_workqueue(lo->workqueue);
+
 	spin_lock_irq(&lo->lo_lock);
 	filp = lo->lo_backing_file;
 	lo->lo_backing_file = NULL;
Signature · 1 line
2.54.0
#7 lore raw

Re: [PATCH v2] loop: Fix NULL pointer dereference by synchronizing lo_release and loop_queue_rq

Quoted 20 lines · On Fri, 15 May 2026 10:38:36 +0900 Tetsuo Handa…

The loop driver relies on lo_release() to automatically clear the loop device via __loop_clr_fd() when the last file descriptor is closed (LO_FLAGS_AUTOCLEAR). Although the backing file structure itself remains allocated in memory thanks to proper file reference counting (f_count is not zero), a severe race condition exists regarding the visibility of the lo->lo_backing_file pointer.

This race window was exposed by commit 65565ca5f99b ("block: unify the synchronous bi_end_io callbacks"). By unifying and optimizing the synchronous I/O completion path, the timing and scheduling behavior of the block layer altered significantly.
As a result, a highly-concurrent execution pipeline emerged where lo_release() can progress to __loop_clr_fd() and nullify lo->lo_backing_file while an already-scheduled asynchronous I/O work (lo_rw_aio) is just about to be executed by a kworker thread.

Since the kworker enters lo_rw_aio() after lo->lo_backing_file has been cleared, it attempts to dereference the now-NULL pointer when initializing the kiocb, leading to the reported NULL pointer dereference bug.

Quoted 6 lines

To close this race safely without introducing heavy fast-path checks, we must ensure that any running or scheduled dispatch threads have completed before we nullify the pointer. Since loop_queue_rq() operates within the block layer's RCU read-side critical section, invoke synchronize_rcu() and drain_workqueue() in __loop_clr_fd() prior to clearing lo->lo_backing_file.

AI review asked a couple of questions:

	https://sashiko.dev/#/patchset/[email protected]
#8 lore raw

Re: [PATCH v2] loop: Fix NULL pointer dereference by synchronizing lo_release and loop_queue_rq

Quoted 2 lines · Andrew Morton

AI review asked a couple of questions:

	https://sashiko.dev/#/patchset/[email protected]

To: gemini/gemini-3.1-pro-preview

Thank you for your valuable feedback. Your point about asynchronous I/O completing after drain_workqueue() and potentially causing a UAF at file_inode() from kiocb_end_write() from lo_rw_aio_do_completion() is correct. The drain_workqueue() alone does not wait for in-flight AIOs that have already returned -EIOCBQUEUED. However, I'm not convinced that use of blk_mq_freeze_queue() inside __loop_clr_fd() where disk->open_mutex was already held by bdev_release() is absolutely deadlock-free.

1. VFS and Block Layer Lock Contention:
__loop_clr_fd() is exclusively invoked from the lo_release() path during the final close of the device. At this stage, the block layer is holding disk->open_mutex. If we call blk_mq_freeze_queue() here, it will synchronously wait for all in-flight AIOs to complete. However, the completion paths of those in-flight AIOs (or subsequent metadata processing in the underlying filesystem) may attempt to acquire resources or execute code paths that depend on the very same device state or open/close status. This creates a circular dependency, leading to an unrecoverable hang.

2. Memory Reclaim Deadlock:
blk_mq_freeze_queue() blocks until the queue's usage counter drops to zero. If an in-flight AIO requires memory allocation for metadata updates upon completion, and the system is under heavy memory pressure, it can trigger direct memory reclaim. If the reclaim path attempts to sync other buffers or interact with the frozen loop device/queue, a circular deadlock occurs.

Therefore, I would like to choose SRCU-based synchronization instead of blk_mq_freeze_queue().

* Locking: We call srcu_read_lock(&loop_io_srcu) only for asynchronous paths (cmd->use_aio) immediately before submitting the I/O to the underlying filesystem in lo_rw_aio().

* Unlocking: The reader lock is released via srcu_read_unlock() at the very end of the AIO completion handler (lo_rw_aio_do_completion()).

* Synchronization: We place synchronize_srcu(&loop_io_srcu) immediately after drain_workqueue() in __loop_clr_fd().

I think that this guarantees that __loop_clr_fd() safely blocks until all pending AIO callbacks are 100% completed, fully eliminating the UAF risk and ensuring the safety of the subsequent mapping_set_gfp_mask() and fput(), while remaining entirely deadlock-free.

What do you think about this approach?

 drivers/block/loop.c | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)
drivers/block/loop.c +21 -0
index 0000913f7efc..7c3961f3cbc9 100644
@@ -80,6 +80,7 @@ struct loop_cmd {
 	struct list_head list_entry;
 	bool use_aio; /* use AIO interface to handle I/O */
 	atomic_t ref; /* only for aio */
+	int srcu_idx;
 	long ret;
 	struct kiocb iocb;
 	struct bio_vec *bvec;
@@ -93,6 +94,7 @@ struct loop_cmd {
 static DEFINE_IDR(loop_index_idr);
 static DEFINE_MUTEX(loop_ctl_mutex);
 static DEFINE_MUTEX(loop_validate_mutex);
+DEFINE_SRCU(loop_io_srcu);
 
 /**
  * loop_global_lock_killable() - take locks for safe loop_validate_file() test
@@ -327,6 +329,8 @@ static void lo_rw_aio_do_completion(struct loop_cmd *cmd)
 		kiocb_end_write(&cmd->iocb);
 	if (likely(!blk_should_fake_timeout(rq->q)))
 		blk_mq_complete_request(rq);
+	if (cmd->use_aio)
+		srcu_read_unlock(&loop_io_srcu, cmd->srcu_idx);
 }
 
 static void lo_rw_aio_complete(struct kiocb *iocb, long ret)
@@ -392,6 +396,7 @@ static int lo_rw_aio(struct loop_device *lo, struct loop_cmd *cmd,
 	if (cmd->use_aio) {
 		cmd->iocb.ki_complete = lo_rw_aio_complete;
 		cmd->iocb.ki_flags = IOCB_DIRECT;
+		cmd->srcu_idx = srcu_read_lock(&loop_io_srcu);
 	} else {
 		cmd->iocb.ki_complete = NULL;
 		cmd->iocb.ki_flags = 0;
@@ -1118,6 +1123,22 @@ static void __loop_clr_fd(struct loop_device *lo)
 	struct file *filp;
 	gfp_t gfp = lo->old_gfp_mask;
 
+	/*
+	 * Now that loop_queue_rq() sees lo->lo_state != Lo_bound,
+	 * wait for already started loop_queue_rq() to complete.
+	 */
+	synchronize_rcu();
+	/*
+	 * Now that no more works are scheduled by loop_queue_rq(),
+	 * wait for already scheduled works to complete.
+	 */
+	drain_workqueue(lo->workqueue);
+	/*
+	 * Now that no more AIO requests are scheduled by lo_rw_aio(),
+	 * wait for already started AIO to complete.
+	 */
+	synchronize_srcu(&loop_io_srcu);
+
 	spin_lock_irq(&lo->lo_lock);
 	filp = lo->lo_backing_file;
 	lo->lo_backing_file = NULL;
#9 lore raw

Re: [PATCH v2] loop: Fix NULL pointer dereference by synchronizing lo_release and loop_queue_rq

Quoted 91 lines · Tetsuo Handa
Quoted 2 lines · Andrew Morton

AI review asked a couple of questions:

	https://sashiko.dev/#/patchset/[email protected]

To: gemini/gemini-3.1-pro-preview

Thank you for your valuable feedback. Your point about asynchronous I/O completing after drain_workqueue() and potentially causing a UAF at file_inode() from kiocb_end_write() from lo_rw_aio_do_completion() is correct. The drain_workqueue() alone does not wait for in-flight AIOs that have already returned -EIOCBQUEUED. However, I'm not convinced that use of blk_mq_freeze_queue() inside __loop_clr_fd() where disk->open_mutex was already held by bdev_release() is absolutely deadlock-free.

1. VFS and Block Layer Lock Contention:
__loop_clr_fd() is exclusively invoked from the lo_release() path during the final close of the device. At this stage, the block layer is holding disk->open_mutex. If we call blk_mq_freeze_queue() here, it will synchronously wait for all in-flight AIOs to complete. However, the completion paths of those in-flight AIOs (or subsequent metadata processing in the underlying filesystem) may attempt to acquire resources or execute code paths that depend on the very same device state or open/close status. This creates a circular dependency, leading to an unrecoverable hang.

2. Memory Reclaim Deadlock:
blk_mq_freeze_queue() blocks until the queue's usage counter drops to zero. If an in-flight AIO requires memory allocation for metadata updates upon completion, and the system is under heavy memory pressure, it can trigger direct memory reclaim. If the reclaim path attempts to sync other buffers or interact with the frozen loop device/queue, a circular deadlock occurs.

Therefore, I would like to choose SRCU-based synchronization instead of blk_mq_freeze_queue().

* Locking: We call srcu_read_lock(&loop_io_srcu) only for asynchronous paths (cmd->use_aio) immediately before submitting the I/O to the underlying filesystem in lo_rw_aio().

* Unlocking: The reader lock is released via srcu_read_unlock() at the very end of the AIO completion handler (lo_rw_aio_do_completion()).

* Synchronization: We place synchronize_srcu(&loop_io_srcu) immediately after drain_workqueue() in __loop_clr_fd().

I think that this guarantees that __loop_clr_fd() safely blocks until all pending AIO callbacks are 100% completed, fully eliminating the UAF risk and ensuring the safety of the subsequent mapping_set_gfp_mask() and fput(), while remaining entirely deadlock-free.

What do you think about this approach?

 drivers/block/loop.c | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)
drivers/block/loop.c +10 -0
index 0000913f7efc..7c3961f3cbc9 100644
@@ -80,6 +80,7 @@ struct loop_cmd {
 	struct list_head list_entry;
 	bool use_aio; /* use AIO interface to handle I/O */
 	atomic_t ref; /* only for aio */
+	int srcu_idx;
 	long ret;
 	struct kiocb iocb;
 	struct bio_vec *bvec;
@@ -93,6 +94,7 @@ struct loop_cmd {
 static DEFINE_IDR(loop_index_idr);
 static DEFINE_MUTEX(loop_ctl_mutex);
 static DEFINE_MUTEX(loop_validate_mutex);
+DEFINE_SRCU(loop_io_srcu);
 
 /**
  * loop_global_lock_killable() - take locks for safe loop_validate_file() test
@@ -327,6 +329,8 @@ static void lo_rw_aio_do_completion(struct loop_cmd *cmd)
 		kiocb_end_write(&cmd->iocb);
 	if (likely(!blk_should_fake_timeout(rq->q)))
 		blk_mq_complete_request(rq);
+	if (cmd->use_aio)
+		srcu_read_unlock(&loop_io_srcu, cmd->srcu_idx);
 }
 
 static void lo_rw_aio_complete(struct kiocb *iocb, long ret)
@@ -392,6 +396,7 @@ static int lo_rw_aio(struct loop_device *lo, struct loop_cmd *cmd,
 	if (cmd->use_aio) {
 		cmd->iocb.ki_complete = lo_rw_aio_complete;
 		cmd->iocb.ki_flags = IOCB_DIRECT;
+		cmd->srcu_idx = srcu_read_lock(&loop_io_srcu);
 	} else {
 		cmd->iocb.ki_complete = NULL;
 		cmd->iocb.ki_flags = 0;
@@ -1118,6 +1123,22 @@ static void __loop_clr_fd(struct loop_device *lo)
 	struct file *filp;
 	gfp_t gfp = lo->old_gfp_mask;
 
+	/*
+	 * Now that loop_queue_rq() sees lo->lo_state != Lo_bound,
+	 * wait for already started loop_queue_rq() to complete.
+	 */
+	synchronize_rcu();

drivers/block/loop.c static void __loop_clr_fd(struct loop_device *lo) · line 1140

Quoted 10 lines
drivers/block/loop.c +10 -0
+	/*
+	 * Now that no more works are scheduled by loop_queue_rq(),
+	 * wait for already scheduled works to complete.
+	 */
+	drain_workqueue(lo->workqueue);
+	/*
+	 * Now that no more AIO requests are scheduled by lo_rw_aio(),
+	 * wait for already started AIO to complete.
+	 */
+	synchronize_srcu(&loop_io_srcu);

The IO after close(loop) should be from writeback. rcu/sruc isn't necessary, please see the patch posted in another thread:

https://lore.kernel.org/linux-block/agxJdUf1b0JSDAux@fedora/

in which the check on lo->lo_state is moved to loop_handle_cmd(), meantime drain_workqueue() is added for draining in-flight workers.

Thanks,
Ming

#10 lore raw

Re: [PATCH v2] loop: Fix NULL pointer dereference by synchronizing lo_release and loop_queue_rq

Quoted 1 line · Ming Lei

The IO after close(loop) should be from writeback. rcu/sruc isn't necessary,

Gemini's comment is that drain_workqueue() is not sufficient for waiting for do_req_filebacked(REQ_OP_WRITE) requests with cmd->use_aio == true case to complete.

We could remove synchronize_rcu() prior to drain_workqueue() if we defer lo->lo_state != Lo_bound check to workqueue context (or recheck in workqueue context).

But I still think that we need to guarantee that all "cmd->use_aio == true" requests (including ones which had been issued before hitting "WRITE_ONCE(lo->lo_state, Lo_rundown);") have completed before doing "lo->lo_backing_file = NULL;".

And I don't know whether it is safe to use "blk_mq_unfreeze_queue(lo->lo_queue, blk_mq_freeze_queue(lo->lo_queue));" immediately after drain_workqueue() because we are holding disk->open_mutex.

#11 lore raw

Re: [PATCH v2] loop: Fix NULL pointer dereference by synchronizing lo_release and loop_queue_rq

Quoted 5 lines · Tetsuo Handa
Quoted 1 line · Ming Lei

The IO after close(loop) should be from writeback. rcu/sruc isn't necessary,

Gemini's comment is that drain_workqueue() is not sufficient for waiting for do_req_filebacked(REQ_OP_WRITE) requests with cmd->use_aio == true case to complete.

Anything cleared in __loop_clr_fd() is not used by lo_rw_aio_complete() & lo_complete_rq().

So why isn't drain_workqueue() enough for cmd->use_aio?

Thanks,
Ming

#12 lore raw

Re: [PATCH v2] loop: Fix NULL pointer dereference by synchronizing lo_release and loop_queue_rq

Quoted 8 lines · Ming Lei
Quoted 5 lines · Tetsuo Handa
Quoted 1 line · Ming Lei

The IO after close(loop) should be from writeback. rcu/sruc isn't necessary,

Gemini's comment is that drain_workqueue() is not sufficient for waiting for do_req_filebacked(REQ_OP_WRITE) requests with cmd->use_aio == true case to complete.

Anything cleared in __loop_clr_fd() is not used by lo_rw_aio_complete() & lo_complete_rq().

"struct inode *inode = file_inode(iocb->ki_filp);" in kiocb_end_write() from lo_rw_aio_do_completion() can dereference "struct file *" with refcount == 0 (UAF) because fput() in __loop_clr_fd() can be the last reference to that file.

Quoted 2 lines

So why isn't drain_workqueue() enough for cmd->use_aio?

In addition to possible UAF above, the assumption at
https://elixir.bootlin.com/linux/v7.1-rc4/source/drivers/block/loop.c#L1134
is currently broken due to this race problem.

#13 lore raw

Re: [PATCH v2] loop: Fix NULL pointer dereference by synchronizing lo_release and loop_queue_rq

Quoted 5 lines · Tetsuo Handa
Quoted 4 lines · Ming Lei
Quoted 3 lines · Tetsuo Handa
Quoted 1 line · Ming Lei

The IO after close(loop) should be from writeback. rcu/sruc isn't necessary,

Quoted 8 lines
Quoted 4 lines
Quoted 2 lines

Gemini's comment is that drain_workqueue() is not sufficient for waiting for do_req_filebacked(REQ_OP_WRITE) requests with cmd->use_aio == true case to complete.

Anything cleared in __loop_clr_fd() is not used by lo_rw_aio_complete() & lo_complete_rq().

"struct inode *inode = file_inode(iocb->ki_filp);" in kiocb_end_write() from lo_rw_aio_do_completion() can dereference "struct file *" with refcount == 0 (UAF) because fput() in __loop_clr_fd() can be the last reference to that file.

OK, you are right.

It can be handled by adding sync_blockdev(lo->lo_device) in __loop_clr_fd() because IO can be from writeback only when loop disk is closed.

Please feel free to test the following change:

drivers/block/loop.c +2 -0
index 0000913f7efc..bbd15974a082 100644
@@ -1118,6 +1118,8 @@ static void __loop_clr_fd(struct loop_device *lo)
        struct file *filp;
        gfp_t gfp = lo->old_gfp_mask;
 
+       sync_blockdev(lo->lo_device);
+
        spin_lock_irq(&lo->lo_lock);
        filp = lo->lo_backing_file;
        lo->lo_backing_file = NULL;
Quoted 6 lines
Quoted 2 lines

So why isn't drain_workqueue() enough for cmd->use_aio?

In addition to possible UAF above, the assumption at
https://elixir.bootlin.com/linux/v7.1-rc4/source/drivers/block/loop.c#L1134
is currently broken due to this race problem.

That shouldn't be one issue otherwise bio based driver can't work with updating limits.

Thanks,
Ming

#14 lore raw

PATCH v3 1/1 loop: Fix NULL pointer dereference in lo_rw_aio()

Some commit which was merged in the merge window for 7.1 broke the loop driver; a race window where lo_release() clears the backing file via __loop_clr_fd() despite some I/O requests are pending was introduced [1][2].

The exact commit which changed the behavior is not known due to lack of reproducer and timing dependent behavior, but it seems that we need to solve this problem in the loop driver despite there was no change for the loop driver during this merge window.

To close this race, try to flush pending I/O requests. However, calling drain_workqueue() from __loop_clr_fd() with disk->open_mutex held causes lockdep warnings [3][4]. We need to flush pending I/O requests without disk->open_mutex held.

In the past, commit 322c4293ecc5 ("loop: make autoclear operation asynchronous") has tried to defer __loop_clr_fd() to WQ context. But it was reverted by commit bf23747ee053 ("loop: revert "make autoclear operation asynchronous"") because userspace might be expecting that fput() on the backing file is processed before lo_release() from close() returns to user mode.

Therefore, this patch tries to defer __loop_clr_fd() to task work context. __loop_clr_fd() is split into three steps:

Step 1: Flush pending I/O requests without holding disk->open_mutex.

Step 2: Do what __loop_clr_fd() from lo_release() was doing with

          disk->open_mutex held.

Step 3: Drop refcounts without holding disk->open_mutex.

A potential side effect of this approach is that a userspace program who issued open() request before __loop_clr_fd() completes might be confused by observing -ENXIO because lo_open() can be called before __loop_clr_fd() completes.

Except for the side effect above, I expect this patch to work by the following reasons.

- The existing Lo_rundown state safely guarantees that any subsequent lo_open() attempts will immediately fail with -ENXIO, preventing races even after disk->open_mutex is temporarily released.

- Since returning from lo_release() normally allows the block layer to immediately drop module and device references, this patch explicitly increments the refcounts (__module_get() and get_device()) before deferring the work, and safely releases them at the end of Step 3 inside __loop_clr_fd().

- It prefers task_work so that userspace processes expecting immediate completion (such as fput() side-effects) receive a deterministic behavior before returning from close(). It falls back to schedule_work() if the current context is a kernel thread (PF_KTHREAD) or if task_work_add() fails.

---
 drivers/block/loop.c | 86 ++++++++++++++++++++++++++++++++++++--------
 kernel/task_work.c   |  1 +
 2 files changed, 73 insertions(+), 14 deletions(-)
drivers/block/loop.c +72 -14
index 0000913f7efc..d97aa2c209e3 100644
@@ -36,6 +36,7 @@
 #include <linux/blk-mq.h>
 #include <linux/spinlock.h>
 #include <uapi/linux/loop.h>
+#include <linux/task_work.h>
 
 /* Possible states of device */
 enum {
@@ -74,6 +75,10 @@ struct loop_device {
 	struct gendisk		*lo_disk;
 	struct mutex		lo_mutex;
 	bool			idr_visible;
+	union {
+		struct callback_head lo_clr_task_work;
+		struct work_struct lo_clr_work;
+	};
 };
 
 struct loop_cmd {
@@ -1112,12 +1117,34 @@ static int loop_configure(struct loop_device *lo, blk_mode_t mode,
 	return error;
 }
 
-static void __loop_clr_fd(struct loop_device *lo)
+static void __loop_clr_fd(struct callback_head *callback)
 {
+	struct loop_device *lo = container_of(callback, struct loop_device, lo_clr_task_work);
 	struct queue_limits lim;
 	struct file *filp;
 	gfp_t gfp = lo->old_gfp_mask;
 
+	/* Step 1: Flush all outstanding I/O, without open_mutex held. */
+
+	/*
+	 * Now that loop_queue_rq() sees lo->lo_state != Lo_bound,
+	 * wait for already started loop_queue_rq() to complete.
+	 */
+	synchronize_rcu();
+	/*
+	 * Now that no more works are scheduled by loop_queue_rq(),
+	 * wait for already scheduled works to complete.
+	 */
+	drain_workqueue(lo->workqueue);
+	/*
+	 * Now that no more AIO requests are scheduled by lo_rw_aio(),
+	 * wait for already started AIO to complete.
+	 */
+	blk_mq_unfreeze_queue(lo->lo_queue, blk_mq_freeze_queue(lo->lo_queue));
+
+	/* Step 2: Perform remaining cleanup, with open_mutex held. */
+	mutex_lock(&lo->lo_disk->open_mutex);
+
 	spin_lock_irq(&lo->lo_lock);
 	filp = lo->lo_backing_file;
 	lo->lo_backing_file = NULL;
@@ -1128,12 +1155,7 @@ static void __loop_clr_fd(struct loop_device *lo)
 	lo->lo_sizelimit = 0;
 	memset(lo->lo_file_name, 0, LO_NAME_SIZE);
 
-	/*
-	 * Reset the block size to the default.
-	 *
-	 * No queue freezing needed because this is called from the final
-	 * ->release call only, so there can't be any outstanding I/O.
-	 */
+	/* Reset the block size to the default. */
 	lim = queue_limits_start_update(lo->lo_queue);
 	lim.logical_block_size = SECTOR_SIZE;
 	lim.physical_block_size = SECTOR_SIZE;
@@ -1145,8 +1167,6 @@ static void __loop_clr_fd(struct loop_device *lo)
 	/* let user-space know about this change */
 	kobject_uevent(&disk_to_dev(lo->lo_disk)->kobj, KOBJ_CHANGE);
 	mapping_set_gfp_mask(filp->f_mapping, gfp);
-	/* This is safe: open() is still holding a reference. */
-	module_put(THIS_MODULE);
 
 	disk_force_media_change(lo->lo_disk);
 
@@ -1154,9 +1174,6 @@ static void __loop_clr_fd(struct loop_device *lo)
 		int err;
 
 		/*
-		 * open_mutex has been held already in release path, so don't
-		 * acquire it if this function is called in such case.
-		 *
 		 * If the reread partition isn't from release path, lo_refcnt
 		 * must be at least one and it can only become zero when the
 		 * current holder is released.
@@ -1181,12 +1198,31 @@ static void __loop_clr_fd(struct loop_device *lo)
 	WRITE_ONCE(lo->lo_state, Lo_unbound);
 	mutex_unlock(&lo->lo_mutex);
 
+	/* Step 3: Drop refcounts, without open_mutex held. */
+	mutex_unlock(&lo->lo_disk->open_mutex);
+
 	/*
 	 * Need not hold lo_mutex to fput backing file. Calling fput holding
 	 * lo_mutex triggers a circular lock dependency possibility warning as
 	 * fput can take open_mutex which is usually taken before lo_mutex.
 	 */
 	fput(filp);
+
+	/*
+	 * Drop all references that would have been dropped as soon as
+	 * returning from lo_release() and releasing disk->open_mutex.
+	 */
+	module_put(lo->lo_disk->fops->owner);
+	put_device(disk_to_dev(lo->lo_disk));
+
+	module_put(THIS_MODULE);
+}
+
+static void loop_clr_work(struct work_struct *work)
+{
+	struct loop_device *lo = container_of(work, struct loop_device, lo_clr_work);
+
+	__loop_clr_fd(&lo->lo_clr_task_work);
 }
 
 static int loop_clr_fd(struct loop_device *lo)
@@ -1747,8 +1783,30 @@ static void lo_release(struct gendisk *disk)
 	need_clear = (lo->lo_state == Lo_rundown);
 	mutex_unlock(&lo->lo_mutex);
 
-	if (need_clear)
-		__loop_clr_fd(lo);
+	/*
+	 * In order to flush pending I/O requests before clearing the backing device,
+	 * defer __loop_clr_fd() to task work context or normal workqueue context.
+	 * The Lo_rundown state guarantees that lo_open() will fail with -ENXIO.
+	 */
+	if (need_clear) {
+		/*
+		 * Grab all references that will be dropped as soon as returning from
+		 * lo_release() and releasing disk->open_mutex.
+		 */
+		get_device(disk_to_dev(disk));
+		__module_get(disk->fops->owner);
+		/*
+		 * Prefer task work, for userspace might be expecting that fput()
+		 * on the backing file is processed before lo_release() from close()
+		 * returns to user mode.
+		 */
+		init_task_work(&lo->lo_clr_task_work, __loop_clr_fd);
+		if ((current->flags & PF_KTHREAD) ||
+		    task_work_add(current, &lo->lo_clr_task_work, TWA_RESUME)) {
+			INIT_WORK(&lo->lo_clr_work, loop_clr_work);
+			schedule_work(&lo->lo_clr_work);
+		}
+	}
 }
 
 static void lo_free_disk(struct gendisk *disk)
kernel/task_work.c +1 -0
index 0f7519f8e7c9..45fd146b85df 100644
@@ -102,6 +102,7 @@ int task_work_add(struct task_struct *task, struct callback_head *work,
 
 	return 0;
 }
+EXPORT_SYMBOL_GPL(task_work_add);
 
 /**
  * task_work_cancel_match - cancel a pending work added by task_work_add()
Signature · 1 line
2.54.0
#15 lore raw

Re: [PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 9 lines · Tetsuo Handa

Some commit which was merged in the merge window for 7.1 broke the loop driver; a race window where lo_release() clears the backing file via __loop_clr_fd() despite some I/O requests are pending was introduced [1][2].

The exact commit which changed the behavior is not known due to lack of reproducer and timing dependent behavior, but it seems that we need to solve this problem in the loop driver despite there was no change for the loop driver during this merge window.

Quoted 4 lines

To close this race, try to flush pending I/O requests. However, calling drain_workqueue() from __loop_clr_fd() with disk->open_mutex held causes lockdep warnings [3][4]. We need to flush pending I/O requests without disk->open_mutex held.

No, please don't workaround before root cause.

No proof shows that the issue is in block layer or loop driver, the IO isn't expected, you need to figure out why btrfs still issues IO after this loop disk is closed by everyone and writeback is done.

https://syzkaller.appspot.com/x/log.txt?x=101e4702580000

Thanks,
Ming

#16 lore raw

Re: [PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 15 lines · Ming Lei
Quoted 9 lines · Tetsuo Handa

Some commit which was merged in the merge window for 7.1 broke the loop driver; a race window where lo_release() clears the backing file via __loop_clr_fd() despite some I/O requests are pending was introduced [1][2].

The exact commit which changed the behavior is not known due to lack of reproducer and timing dependent behavior, but it seems that we need to solve this problem in the loop driver despite there was no change for the loop driver during this merge window.

Quoted 4 lines

To close this race, try to flush pending I/O requests. However, calling drain_workqueue() from __loop_clr_fd() with disk->open_mutex held causes lockdep warnings [3][4]. We need to flush pending I/O requests without disk->open_mutex held.

Quoted 8 lines

No, please don't workaround before root cause.

No proof shows that the issue is in block layer or loop driver, the IO isn't expected, you need to figure out why btrfs still issues IO after this loop disk is closed by everyone and writeback is done.

https://syzkaller.appspot.com/x/log.txt?x=101e4702580000

Of course we should try to figure out the root cause first, but how can we do?

Absolute fact:

This problem started happening no later than next-20260413 in the linux-next.git tree. ( syzbot was unable to test next-202604{03,06,07,08,09,10} due to a different bug. )

This problem is still happening as of v7.1-rc5 in the linux.git tree.

No one has succeeded establishing steps to reproduce this problem.

No one has identified the exact commit that is causing this problem.

Likely fact:

Since this problem did not happen using next-20260402 in the linux-next.git tree until 2026/04/13 16:31, this problem did not exist until next-20260402 in the linux-next.git tree.

Since this problem did not happen until v7.0, this problem did not exist until v7.0. (Although last minute changes for v7.0-rc{6,7} or v7.0 could become the culprit,
the merge window which accepts big changes for v7.1 is more likely.)

My guess:

The culprit commit is in between commit a028739a4330 ("Merge tag 'block-7.0-20260305' of
git://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux") and commit 7fe6ac157b7e ("Merge tag 'for-7.1/block-20260411' of git://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux"), for changes related to bio handling are merged in this period.

"git log --oneline block/ drivers/block/" between next-20260402 and next-20260413 shows the following diff:

--------------------
-da93b347876b Merge branch 'master' of https://git.kernel.org/pub/scm/linux/kernel/git/tip/tip.git
-9b75c6e054b7 Merge branch 'for-next' of https://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux.git
-265720725a47 Merge branch 'fs-next' of linux-next
-ac9e99118030 Merge branch into tip/master: 'x86/cleanups'
-8ea5c0750d36 zram: do not forget to endio for partial discard requests
-0476d2e93477 zram: change scan_slots to return void
-1207420afea8 zram: propagate read_from_bdev_async() errors
-aafa569edb41 zram: optimize LZ4 dictionary compression performance
-24c76a259819 Merge branch 'for-7.1/block' into for-next
-eca714c0aac1 Merge branch 'vfs-7.1.bh.metadata' into vfs.all
+7d8d908556ca Merge branch 'master' of https://git.kernel.org/pub/scm/linux/kernel/git/tip/tip.git
+4391dc7df11d Merge branch 'for-next' of https://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux.git
+18c6a4c24187 Merge branch 'fs-next' of linux-next
+7f828a86cfef Merge branch into tip/master: 'x86/cleanups'
+716aa108c5bb zram: reject unrecognized type= values in recompress_store() +3470a1d34f40 zram: do not forget to endio for partial discard requests
+88a57e158619 Merge branch 'for-7.1/block' into for-next
+36446de0c30c ublk: fix tautological comparison warning in ublk_ctrl_reg_buf +f2bab85781e8 Merge branch 'vfs-7.1.bh.metadata' into vfs.all
+9357dc97533a Merge branch 'vfs-7.1.integrity' into vfs.all
+e0b15707598c Merge branch 'for-7.1/block' into for-next
+539fb773a3f7 block: refactor blkdev_zone_mgmt_ioctl
+ddc1dfffcbea Merge branch 'for-7.1/block' into for-next
+365ea7cc6244 ublk: allow buffer registration before device is started
+5e864438e285 ublk: replace xarray with IDA for shmem buffer index allocation +8ea8566a9aee ublk: simplify PFN range loop in __ublk_ctrl_reg_buf
+211ff1602b67 ublk: verify all pages in multi-page bvec fall within registered range +23b3b6f0b584 ublk: widen ublk_shmem_buf_reg.len to __u64 for 4GB buffer support +cb793ff1353d Merge branch 'for-7.1/block' into for-next
+92c3737a2473 block: add a bio_submit_or_kill helper
+6fa747550e35 block: factor out a bio_await helper
+65565ca5f99b block: unify the synchronous bi_end_io callbacks
+cc91702dedc5 Merge branch 'for-7.1/block' into for-next
+8a34e88769f6 ublk: eliminate permanent pages[] array from struct ublk_buf +08677040a911 ublk: enable UBLK_F_SHMEM_ZC feature flag
+4d4a512a1f87 ublk: add PFN-based buffer matching in I/O path
+2fb0ded237bb ublk: add UBLK_U_CMD_REG_BUF/UNREG_BUF control commands
+dec615fa43c3 Merge branch 'for-7.1/block' into for-next
+fa0cac9a5158 drbd: use get_random_u64() where appropriate
+0b581d2fb4cf Merge branch 'for-7.1/block' into for-next
+a9c4b1d37622 drbd: remove DRBD_GENLA_F_MANDATORY flag handling
+d436cfb3a259 Merge branch 'for-7.1/block' into for-next
+e9b004ff8306 blk-wbt: remove WARN_ON_ONCE from wbt_init_enable_default()
+09ebc43b5edc Merge branch 'for-7.1/block' into for-next
+0842186d2c4e ublk: reset per-IO canceled flag on each fetch
+cba82993308d zram: change scan_slots to return void
+bf989ade270d zram: propagate read_from_bdev_async() errors
+f0f6f7871430 zram: optimize LZ4 dictionary compression performance
+301f39220096 zram: unify and harden algo/priority params handling
+cedfa028b54e zram: remove chained recompression
+5004a27edba5 zram: drop ->num_active_comps
+ed19b9d5504f zram: do not autocorrect bad recompression parameters
+241f9005b1c8 zram: do not permit params change after init
+c09fb53d293a zram: use statically allocated compression algorithm names
+6030f93e5c71 Merge branch 'for-7.1/io_uring-fuse' into for-next
+29ebfdd7db89 io_uring/rsrc: rename io_buffer_register_bvec()/io_buffer_unregister_bvec() +6568edbea553 Merge branch 'for-7.1/block' into for-next
+a175ee827331 block: use sysfs_emit in sysfs show functions
+c691e4b0d80b bio: fix kmemleak false positives from percpu bio alloc cache
f91ffe89b201 blk-iocost: fix busy_level reset when no IOs complete
23308af722fe blk-cgroup: fix disk reference leak in blkcg_maybe_throttle_current() b2a78fec344e zloop: add max_open_zones option
2a2f520fda82 block: fix zones_cond memory leak on zone revalidation error paths 267ec4d7223a loop: fix partition scan race between udev and loop_reread_partitions() 499d2d2f4cf9 sed-opal: Add STACK_RESET command
-c61825bb46bc Merge branch 'vfs-7.1.integrity' into vfs.all
-fc2093641448 zram: unify and harden algo/priority params handling
-4fd453f16446 zram: remove chained recompression
-e2b717936d1a zram: drop ->num_active_comps
-3578bb37f7d1 zram: do not autocorrect bad recompression parameters
-5331373bfebd zram: do not permit params change after init
2b31e86387e6 drbd: Balance RCU calls in drbd_adm_dump_devices()
f9480ecf939d bdev: Drop pointless invalidate_inode_buffers() call
-b00ff1b25f85 zram: use statically allocated compression algorithm names
630bbba45cfd drbd: use genl pre_doit/post_doit
829def1e35ca zloop: forget write cache on force removal
eff8d1656e83 zloop: refactor zloop_rw
--------------------

    "git log --oneline block/" between next-20260402 and next-20260413 shows the following diff:

--------------------
-9b75c6e054b7 Merge branch 'for-next' of https://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux.git
-eca714c0aac1 Merge branch 'vfs-7.1.bh.metadata' into vfs.all
+4391dc7df11d Merge branch 'for-next' of https://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux.git
+f2bab85781e8 Merge branch 'vfs-7.1.bh.metadata' into vfs.all
+539fb773a3f7 block: refactor blkdev_zone_mgmt_ioctl
+92c3737a2473 block: add a bio_submit_or_kill helper
+6fa747550e35 block: factor out a bio_await helper
+65565ca5f99b block: unify the synchronous bi_end_io callbacks
+e9b004ff8306 blk-wbt: remove WARN_ON_ONCE from wbt_init_enable_default()
+a175ee827331 block: use sysfs_emit in sysfs show functions
+c691e4b0d80b bio: fix kmemleak false positives from percpu bio alloc cache
f91ffe89b201 blk-iocost: fix busy_level reset when no IOs complete
23308af722fe blk-cgroup: fix disk reference leak in blkcg_maybe_throttle_current() 2a2f520fda82 block: fix zones_cond memory leak on zone revalidation error paths
--------------------

Possible approaches for finding the exact commit that is causing this problem:

(a) Revert all changes in the block layer from linux.git and monitor for one week for whether this problem is still happening (because linux.git is more frequently hitting this problem than linux-next.git ).

(b) Revert all changes in the block layer from linux-next.git and monitor for two weeks for whether this problem is still happening (less reliable than linux.git but a candidate).

(c) Let sashiko review all changes between v7.0 and v7.1 that may cause this problem. (Human developers have no time to review. But is investigation with moving baseline commit possible for sashiko ?)

(d) Any ideas?

P.S. Since the loop driver is a critical infrastructure for testing filesystems by syzbot, I want this problem be addressed before 7.1 is released.

#17 lore raw

Re: [PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 18 lines · Tetsuo Handa
Quoted 17 lines · Ming Lei
Quoted 9 lines · Tetsuo Handa

Some commit which was merged in the merge window for 7.1 broke the loop driver; a race window where lo_release() clears the backing file via __loop_clr_fd() despite some I/O requests are pending was introduced [1][2].

The exact commit which changed the behavior is not known due to lack of reproducer and timing dependent behavior, but it seems that we need to solve this problem in the loop driver despite there was no change for the loop driver during this merge window.

Quoted 4 lines

To close this race, try to flush pending I/O requests. However, calling drain_workqueue() from __loop_clr_fd() with disk->open_mutex held causes lockdep warnings [3][4]. We need to flush pending I/O requests without disk->open_mutex held.

No, please don't workaround before root cause.

Quoted 8 lines
Quoted 6 lines

No proof shows that the issue is in block layer or loop driver, the IO isn't expected, you need to figure out why btrfs still issues IO after this loop disk is closed by everyone and writeback is done.

https://syzkaller.appspot.com/x/log.txt?x=101e4702580000

Of course we should try to figure out the root cause first, but how can we do?

Definitely unexpected write IO(after umount & loop closed) from btrfs is more serious, which may cause data loss, so CC btrfs list and maintainer.

...

Quoted 9 lines

Possible approaches for finding the exact commit that is causing this problem:

(a) Revert all changes in the block layer from linux.git and monitor for one week for whether this problem is still happening (because linux.git is more frequently hitting this problem than linux-next.git ).

(b) Revert all changes in the block layer from linux-next.git and monitor for two weeks for whether this problem is still happening (less reliable than linux.git but a candidate).

Quoted 8 lines

(c) Let sashiko review all changes between v7.0 and v7.1 that may cause this problem. (Human developers have no time to review. But is investigation with moving baseline commit possible for sashiko ?)

(d) Any ideas?

P.S. Since the loop driver is a critical infrastructure for testing filesystems by syzbot, I want this problem be addressed before 7.1 is released.

syzbot is for finding real problem, here the real trouble is unexpected write IO from btrfs.

So please do not try to paper over real bug by 'fixing' loop.

Thanks,
Ming

#18 lore raw

Re: [PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 4 lines · Ming Lei
Quoted 1 line

Of course we should try to figure out the root cause first, but how can we do?

Definitely unexpected write IO(after umount & loop closed) from btrfs is more serious, which may cause data loss, so CC btrfs list and maintainer.

Why do you assume that the culprit is btrfs?

https://syzkaller.appspot.com/bug?extid=bc273027d5643e48e5b3 indicated that this similar race is also happening with jfs.

[  678.816570][ T1038] read_mapping_page failed!
[  678.816584][ T1038] ERROR: (device loop3): txCommit: 
[  678.816584][ T1038] 
[  678.816633][ T1038] jfs_write_inode: jfs_commit_inode failed!
[  678.895688][ T2183] lo_rw_aio(loop3) starting write with raw_refcnt=0x0, refcnt=1
[  678.956225][ T2183] lo_rw_aio(loop3) starting write with raw_refcnt=0x0, refcnt=1
[  678.970652][   T12] lo_rw_aio(loop3) starting write with raw_refcnt=0x0, refcnt=1
[  679.102838][ T4281] lo_rw_aio(loop3) starting write with raw_refcnt=0x0, refcnt=1
[  679.104701][ T4281] lo_rw_aio(loop3) starting write with raw_refcnt=0x0, refcnt=1
[  679.121329][ T2183] lo_rw_aio(loop3) starting write with raw_refcnt=0x0, refcnt=1
[  679.122119][ T2183] lo_rw_aio(loop3) starting write with raw_refcnt=0x0, refcnt=1
[  679.199283][ T2183] lo_rw_aio(loop3) starting read with raw_refcnt=0x0, refcnt=1
[  679.200014][ T2183] lo_rw_aio(loop3) starting write with raw_refcnt=0x0, refcnt=1
[  679.275613][ T5615] __loop_clr_fd(loop3) clearing lo_backing_file with raw_refcnt=0x0, refcnt=1
[  679.397358][   T13] bridge_slave_1: left allmulticast mode
[  679.397399][   T13] bridge_slave_1: left promiscuous mode
[  679.410004][   T13] bridge0: port 2(bridge_slave_1) entered disabled state
[  679.433576][ T2183] ------------[ cut here ]------------
[  679.433592][ T2183] d_inode(dentry) != file_inode(file)
[  679.433617][ T2183] WARNING: ./include/linux/fs.h:1368 at file_remove_privs_flags+0x58c/0x640, CPU#0: kworker/u8:12/2183
[  679.433676][ T2183] Modules linked in:
[  679.433695][ T2183] CPU: 0 UID: 0 PID: 2183 Comm: kworker/u8:12 Not tainted syzkaller #0 PREEMPT_{RT,(full)} 
[  679.433720][ T2183] Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 04/18/2026
[  679.433739][ T2183] Workqueue: loop3 loop_workfn
[  679.433805][ T2183] RIP: 0010:file_remove_privs_flags+0x58c/0x640
[  679.433848][ T2183] Code: 00 75 4d 44 89 e8 48 8d 65 d8 5b 41 5c 41 5d 41 5e 41 5f 5d c3 cc cc cc cc cc e8 5f d4 80 ff e9 90 fe ff ff e8 55 d4 80 ff 90 <0f> 0b 90 e9 85 fb ff ff 44 89 f1 80 e1 07 80 c1 03 38 c1 0f 8c b7
[  679.433867][ T2183] RSP: 0018:ffffc90007e374e0 EFLAGS: 00010293
[  679.433885][ T2183] RAX: ffffffff8243f7cb RBX: ffff888036fa8ca0 RCX: ffff88802c0abd80
[  679.433902][ T2183] RDX: 0000000000000000 RSI: 0000000000000000 RDI: 0000000000000000
[  679.433933][ T2183] RBP: ffffc90007e37638 R08: 0000000000000000 R09: 0000000000000000
[  679.433946][ T2183] R10: dffffc0000000000 R11: fffffbfff1f1597f R12: ffff888063726220
[  679.433962][ T2183] R13: 1ffff11006df5194 R14: 0000000000000000 R15: 1ffff1100c6e4c44
[  679.433978][ T2183] FS:  0000000000000000(0000) GS:ffff888125f1f000(0000) knlGS:0000000000000000
[  679.433998][ T2183] CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[  679.434016][ T2183] CR2: 00007f22e1be7dac CR3: 000000003e332000 CR4: 00000000003526f0
[  679.434038][ T2183] Call Trace:
[  679.434049][ T2183]  <TASK>
[  679.434072][ T2183]  ? __pfx_file_remove_privs_flags+0x10/0x10
[  679.434118][ T2183]  ? rt_mutex_post_schedule+0xd1/0x1c0
[  679.434172][ T2183]  ? generic_write_checks_count+0x449/0x550
[  679.434212][ T2183]  ? generic_write_checks+0xc8/0x110
[  679.434249][ T2183]  shmem_file_write_iter+0xaa/0x120
[  679.434286][ T2183]  lo_rw_aio+0xef0/0x1170
[  679.434349][ T2183]  ? __pfx_lo_rw_aio+0x10/0x10
[  679.434401][ T2183]  ? kthread_associate_blkcg+0x490/0x600
[  679.434432][ T2183]  ? rt_spin_unlock+0x160/0x200
[  679.434476][ T2183]  loop_process_work+0x637/0x11b0
[  679.434539][ T2183]  ? __pfx_loop_process_work+0x10/0x10
[  679.434582][ T2183]  ? look_up_lock_class+0x57/0x110
[  679.434626][ T2183]  ? register_lock_class+0x31/0x2e0
[  679.434661][ T2183]  ? __lock_acquire+0x6b5/0x2d10
[  679.434741][ T2183]  ? do_raw_spin_lock+0x12b/0x2f0
[  679.434785][ T2183]  ? __pfx_do_raw_spin_lock+0x10/0x10
[  679.434830][ T2183]  ? process_one_work+0x8be/0x1630
[  679.434870][ T2183]  ? process_one_work+0x8be/0x1630
[  679.434922][ T2183]  ? process_one_work+0x8be/0x1630
[  679.434959][ T2183]  process_one_work+0x98b/0x1630
[  679.435026][ T2183]  ? __pfx_process_one_work+0x10/0x10
[  679.435060][ T2183]  ? do_raw_spin_lock+0x12b/0x2f0
[  679.435128][ T2183]  worker_thread+0xb49/0x1140
[  679.435202][ T2183]  kthread+0x388/0x470
[  679.435233][ T2183]  ? __pfx_worker_thread+0x10/0x10
[  679.435276][ T2183]  ? __pfx_kthread+0x10/0x10
[  679.435309][ T2183]  ret_from_fork+0x514/0xb70
[  679.435348][ T2183]  ? __pfx_ret_from_fork+0x10/0x10
[  679.435382][ T2183]  ? __switch_to+0xc79/0x1410
[  679.435415][ T2183]  ? __pfx_kthread+0x10/0x10
[  679.435447][ T2183]  ret_from_fork_asm+0x1a/0x30
[  679.435517][ T2183]  </TASK>
#19 lore raw

Re: [PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 10 lines · Tetsuo Handa
Quoted 4 lines · Ming Lei
Quoted 1 line

Of course we should try to figure out the root cause first, but how can we do?

Definitely unexpected write IO(after umount & loop closed) from btrfs is more serious, which may cause data loss, so CC btrfs list and maintainer.

Why do you assume that the culprit is btrfs?

https://syzkaller.appspot.com/bug?extid=bc273027d5643e48e5b3 indicated that this similar race is also happening with jfs.

I just didn't see the above report on jfs.

It doesn't change anything, the same question still stands: unexpected write IO is issued or crosses umount & last closing of loop disk.

Thanks,
Ming

#20 lore raw

Re: [PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 7 lines · Ming Lei
Quoted 6 lines · Tetsuo Handa
Quoted 4 lines · Ming Lei
Quoted 1 line

Of course we should try to figure out the root cause first, but how can we do?

Definitely unexpected write IO(after umount & loop closed) from btrfs is more serious, which may cause data loss, so CC btrfs list and maintainer.

I had a conversation with Google AI mode, and received the following response.

--------------------------------------------------------------------------------
Technical Analysis: lo_rw_aio Null Pointer Dereference / UAF since v7.1-rc1

1. The Root Cause of the Timing Shift

This regression was introduced during the v7.1-rc1 merge window, primarily exposed by Commit 65565ca5f99b ("block: unify the synchronous bi_end_io callbacks"), along with helper refactorings like Commit 92c3737a2473 ("block: add a bio_submit_or_kill helper").

Prior to v7.0, the synchronous I/O completion path inherently contained execution lags (due to serialized completion handling and context switches) before notifying upper layers. This latency accidentally acted as a natural safety barrier. It ensured that by the time a file system completed its final sync_filesystem() and initiated umount, the loop driver's internal workqueue (lo_rw_aio) had already finished processing everything.

In v7.1, the unification and optimization of bi_end_io significantly minimized this latency. The filesystem now learns of "I/O completion" much faster. Consequently, highly-concurrent execution pipelines like btrfs or jfs proceed rapidly through kill_sb() and blkdev_put(), ultimately invoking lo_release() -> __loop_clr_fd() while the loop driver's backend kworker is still in the middle of executing the last sub-millisecond asynchronous file-backed I/O request.

2. Why the Block Layer's Built-in Quiesce/Freeze Fails

There is an implicit assumption that standard block layer freeze mechanisms (blk_mq_freeze_queue()) protect the device lifetime during release. However, the v7.1 BIO helper refactoring introduced a synchronization gap:

1. The filesystem triggers its final metadata or journal updates (e.g., txCommit in jfs or delayed refcount updates in btrfs) right during the unmount/close boundary.
2. Due to the optimized execution path, these requests bypass the block layer's active request-tracking metrics at the exact moment blk_mq_freeze_queue() or state validation checks evaluated them as zero.
3. The block layer assumes the queue is safe and silent, allowing __loop_clr_fd() to

     progress and nullify lo->lo_backing_file (or trigger fput()).

4. The leaked asynchronous kworker wakes up a fraction of a millisecond too late, attempts to access lo->lo_backing_file or invokes kiocb_end_write() -> file_inode(), leading to either a general protection fault (Null pointer dereference) or a Use-After-Free (UAF).

3. Why This Isn't Just an "Unexpected FS Bug"

While the write I/O originates from file systems like btrfs and jfs post-close, blaming the file systems entirely ignores the underlying infrastructure change. The core issue is that the block layer altered its synchronization behavior, breaking the barrier contract that VFS and file systems historically relied on during the device release path.

Papering over this inside individual file systems would require adding heavy, duplicated barriers inside every single filesystem's unmount path.

#21 lore raw

Re: [PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 55 lines · Tetsuo Handa
Quoted 7 lines · Ming Lei
Quoted 6 lines · Tetsuo Handa
Quoted 4 lines · Ming Lei
Quoted 1 line

Of course we should try to figure out the root cause first, but how can we do?

Definitely unexpected write IO(after umount & loop closed) from btrfs is more serious, which may cause data loss, so CC btrfs list and maintainer.

I had a conversation with Google AI mode, and received the following response.

--------------------------------------------------------------------------------
Technical Analysis: lo_rw_aio Null Pointer Dereference / UAF since v7.1-rc1

1. The Root Cause of the Timing Shift

This regression was introduced during the v7.1-rc1 merge window, primarily exposed by Commit 65565ca5f99b ("block: unify the synchronous bi_end_io callbacks"), along with helper refactorings like Commit 92c3737a2473 ("block: add a bio_submit_or_kill helper").

Prior to v7.0, the synchronous I/O completion path inherently contained execution lags (due to serialized completion handling and context switches) before notifying upper layers. This latency accidentally acted as a natural safety barrier. It ensured that by the time a file system completed its final sync_filesystem() and initiated umount, the loop driver's internal workqueue (lo_rw_aio) had already finished processing everything.

In v7.1, the unification and optimization of bi_end_io significantly minimized this latency. The filesystem now learns of "I/O completion" much faster. Consequently, highly-concurrent execution pipelines like btrfs or jfs proceed rapidly through kill_sb() and blkdev_put(), ultimately invoking lo_release() -> __loop_clr_fd() while the loop driver's backend kworker is still in the middle of executing the last sub-millisecond asynchronous file-backed I/O request.

2. Why the Block Layer's Built-in Quiesce/Freeze Fails

There is an implicit assumption that standard block layer freeze mechanisms (blk_mq_freeze_queue()) protect the device lifetime during release. However, the v7.1 BIO helper refactoring introduced a synchronization gap:

1. The filesystem triggers its final metadata or journal updates (e.g., txCommit in jfs or delayed refcount updates in btrfs) right during the unmount/close boundary.
2. Due to the optimized execution path, these requests bypass the block layer's active request-tracking metrics at the exact moment blk_mq_freeze_queue() or state validation checks evaluated them as zero.
3. The block layer assumes the queue is safe and silent, allowing __loop_clr_fd() to

     progress and nullify lo->lo_backing_file (or trigger fput()).

4. The leaked asynchronous kworker wakes up a fraction of a millisecond too late, attempts to access lo->lo_backing_file or invokes kiocb_end_write() -> file_inode(), leading to either a general protection fault (Null pointer dereference) or a Use-After-Free (UAF).

3. Why This Isn't Just an "Unexpected FS Bug"

Quoted 7 lines

While the write I/O originates from file systems like btrfs and jfs post-close, blaming the file systems entirely ignores the underlying infrastructure change. The core issue is that the block layer altered its synchronization behavior, breaking the barrier contract that VFS and file systems historically relied on during the device release path.

Papering over this inside individual file systems would require adding heavy, duplicated barriers inside every single filesystem's unmount path.

It sounds like the VFS unmount call needs to have something that waits for sync() to complete. Though, it really feels very strange that an FS can complete unmount without itself ensuring that there are no more IOs in flight. The generic VFS layer cannot know what the FS needs to flush on unmount, so waiting on a generic sync might not be enough.

It really feels like this is a btrfs and jfs issue, unless the same can be reproduced with any file system (XFS, ext4, f2fs, ...).

Just my 2 cents.

Signature · 2 lines
Damien Le Moal
Western Digital Research
#33 lore raw

Re: [PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()

In reply to Ming Lei
Quoted 9 lines · On Tue, 26 May 2026 22:00:49 -0500 Ming Lei wrote:
Quoted 8 lines · Tetsuo Handa
Quoted 4 lines · Ming Lei
Quoted 1 line

Of course we should try to figure out the root cause first, but how can we do?

Definitely unexpected write IO(after umount & loop closed) from btrfs is more serious, which may cause data loss, so CC btrfs list and maintainer.

Why do you assume that the culprit is btrfs?

Quoted 8 lines
Quoted 2 lines

https://syzkaller.appspot.com/bug?extid=bc273027d5643e48e5b3 indicated that this similar race is also happening with jfs.

I just didn't see the above report on jfs.

It doesn't change anything, the same question still stands: unexpected write IO is issued or crosses umount & last closing of loop disk.

Given the loop workqueue that triggered the jfs warning, can you specify the reason why the workqueue in question is NOT flushed while closing disk?

#22 lore raw

Re: [PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()

In reply to Damien Le Moal
Quoted 2 lines · Damien Le Moal

It sounds like the VFS unmount call needs to have something that waits for sync() to complete. Though, it really feels very strange that an FS can complete

I don't think this is the VFS-controlled VFS file data writeback, which we wait on, but some kind of fs controlled metadata. And yes, it looks like those file systems are buggy in that area. We definitively had such bugs in XFS before and fixed them.

e.g. 9c7504aa72b6 ("xfs: track and serialize in-flight async buffers against unmount")

#23 lore raw

Re: [PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 11 lines · Christoph Hellwig
Quoted 2 lines · Damien Le Moal

It sounds like the VFS unmount call needs to have something that waits for sync() to complete. Though, it really feels very strange that an FS can complete

I don't think this is the VFS-controlled VFS file data writeback, which we wait on, but some kind of fs controlled metadata. And yes, it looks like those file systems are buggy in that area. We definitively had such bugs in XFS before and fixed them.

e.g. 9c7504aa72b6 ("xfs: track and serialize in-flight async buffers against unmount")

Considering the xfs fix is pretty old, it's before the fix hint thus no such mention in fstests.

Do you happen to know which test case is for that fix? I'd like to adapt it for btrfs as a reproducer.

This syzbot report doesn't provide a reproducer.

Another thing is, if it's some btrfs bios on-the-fly after close_ctree(), the most common symptom should be NULL pointer dereference inside various btrfs endio functions. As all those end_bbio_*() functions are referring to either fs_info or inode/eb, thus if the fs is unmounted before the bio finished, they should all cause use-after-free.

The only exception is discard, which is using blkdev_issue_discard() thus has no such reference to btrfs internal structure, but that's out of my understanding.

Thanks,
Qu

#34 lore raw

Re: [PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()

In reply to Hillf Danton
Quoted 13 lines · On Thu, 28 May 2026 13:43:31 +0800 Hillf Danton wrote:
Quoted 12 lines · On Tue, 26 May 2026 22:00:49 -0500 Ming Lei wrote:
Quoted 10 lines · Tetsuo Handa
Quoted 4 lines · Ming Lei
Quoted 1 line

Of course we should try to figure out the root cause first, but how can we do?

Definitely unexpected write IO(after umount & loop closed) from btrfs is more serious, which may cause data loss, so CC btrfs list and maintainer.

Why do you assume that the culprit is btrfs?

https://syzkaller.appspot.com/bug?extid=bc273027d5643e48e5b3 indicated that this similar race is also happening with jfs.

Quoted 8 lines
Quoted 5 lines

I just didn't see the above report on jfs.

It doesn't change anything, the same question still stands: unexpected write IO is issued or crosses umount & last closing of loop disk.

Given the loop workqueue that triggered the jfs warning, can you specify the reason why the workqueue in question is NOT flushed while closing disk?

Got it, the loop workqueue is NOT flushed to avoid deadlock, see d292dc80686a ("loop: don't destroy lo->workqueue in __loop_clr_fd") for detail. And the deadlock can be reproduced by flushing the loop workqueue with disk->open_mutex held [1].

[1] Subject: Re: [syzbot] possible deadlock in blkdev_put (3)
https://lore.kernel.org/lkml/[email protected]/

#35 lore raw

Re: [PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 10 lines · Hillf Danton
Quoted 3 lines

Given the loop workqueue that triggered the jfs warning, can you specify the reason why the workqueue in question is NOT flushed while closing disk?

Got it, the loop workqueue is NOT flushed to avoid deadlock, see d292dc80686a ("loop: don't destroy lo->workqueue in __loop_clr_fd") for detail. And the deadlock can be reproduced by flushing the loop workqueue with disk->open_mutex held [1].

[1] Subject: Re: [syzbot] possible deadlock in blkdev_put (3)
https://lore.kernel.org/lkml/[email protected]/

We can avoid the following lockdep warnings (including [1] you mentioned)

https://syzkaller.appspot.com/bug?extid=2f62807dc3239b8f584e
https://syzkaller.appspot.com/bug?extid=c4e9d077bcc86bee08dc
https://syzkaller.appspot.com/bug?extid=0f427123ae84b3ba6dc7
https://syzkaller.appspot.com/bug?extid=4feabfc9641267769c97
https://syzkaller.appspot.com/bug?extid=fb0ff9bfe34ad282ebd4

caused by "drain_workqueue() with disk->open_mutex held" if we assign caller-specific lockdep class to disk->open_mutex

https://sourceforge.net/p/tomoyo/tomoyo.git/ci/c2245c765ebeba9dcb924d9171d8d470a9ac41c8/

.

Also, we can avoid lockdep warning caused by "drain_workqueue() with disk->open_mutex held" + "holding system_transition_mutex" if we forbid binding to pseudo files as backing file in the loop driver

https://lkml.kernel.org/r/[email protected]

which we can reproduce with

echo 7:0 > /sys/power/resume
losetup /dev/loop0 /sys/power/resume
cat /dev/loop0 > /dev/null
losetup -d /dev/loop0

.

Therefore, I think we can address this problem by "drain_workqueue() with disk->open_mutex held" in the loop driver side.

However, the possibility that the last milli-second writeback request (which runs during unmount operation) from filesystem fails due to

    if (data_race(READ_ONCE(lo->lo_state)) != Lo_bound)
        return BLK_STS_IOERR;

check in loop_queue_rq() will remain. Therefore, addressing this problem within individual filesystem will be more strict solution. But guessing from the pace jfs fixes bugs, it would take long time before we stop seeing this problem...

#36 lore raw

Re: [PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 40 lines · On Fri, 29 May 2026 09:14:47 +0900 Tetsuo Handa wrote:
Quoted 10 lines · Hillf Danton
Quoted 3 lines

Given the loop workqueue that triggered the jfs warning, can you specify the reason why the workqueue in question is NOT flushed while closing disk?

Got it, the loop workqueue is NOT flushed to avoid deadlock, see d292dc80686a ("loop: don't destroy lo->workqueue in __loop_clr_fd") for detail. And the deadlock can be reproduced by flushing the loop workqueue with disk->open_mutex held [1].

[1] Subject: Re: [syzbot] possible deadlock in blkdev_put (3)
https://lore.kernel.org/lkml/[email protected]/

We can avoid the following lockdep warnings (including [1] you mentioned)

https://syzkaller.appspot.com/bug?extid=2f62807dc3239b8f584e
https://syzkaller.appspot.com/bug?extid=c4e9d077bcc86bee08dc
https://syzkaller.appspot.com/bug?extid=0f427123ae84b3ba6dc7
https://syzkaller.appspot.com/bug?extid=4feabfc9641267769c97
https://syzkaller.appspot.com/bug?extid=fb0ff9bfe34ad282ebd4

caused by "drain_workqueue() with disk->open_mutex held" if we assign caller-specific lockdep class to disk->open_mutex

https://sourceforge.net/p/tomoyo/tomoyo.git/ci/c2245c765ebeba9dcb924d9171d8d470a9ac41c8/

.

Also, we can avoid lockdep warning caused by "drain_workqueue() with disk->open_mutex held" + "holding system_transition_mutex" if we forbid binding to pseudo files as backing file in the loop driver

https://lkml.kernel.org/r/[email protected]

which we can reproduce with

echo 7:0 > /sys/power/resume
losetup /dev/loop0 /sys/power/resume
cat /dev/loop0 > /dev/null
losetup -d /dev/loop0

Quoted 5 lines

.

Therefore, I think we can address this problem by "drain_workqueue() with disk->open_mutex held" in the loop driver side.

Good news.

Quoted 9 lines

However, the possibility that the last milli-second writeback request (which runs during unmount operation) from filesystem fails due to

   if (data_race(READ_ONCE(lo->lo_state)) != Lo_bound)
       return BLK_STS_IOERR;

check in loop_queue_rq() will remain.

This conflicts with "There is no need to destroy the workqueue when clearing unbinding a loop device from a backing file." in d292dc80686a

Quoted 2 lines

Therefore, addressing this problem
within individual filesystem will be more strict solution. But guessing from

Conflicts with "Another thing is, if it's some btrfs bios on-the-fly after close_ctree(), the most common symptom should be NULL pointer dereference inside various btrfs endio functions." [2] once more.

And you need to pay the fs guys more than two cents I think for cooking a FIX.

[2] Subject: Re: [PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()
https://lore.kernel.org/lkml/[email protected]/

Quoted 2 lines

the pace jfs fixes bugs, it would take long time before we stop seeing this problem...

#37 lore raw

Re: [PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 41 lines · On Fri, 29 May 2026 15:04:10 +0800 Hillf Danton wrote:
Quoted 40 lines · On Fri, 29 May 2026 09:14:47 +0900 Tetsuo Handa wrote:
Quoted 10 lines · Hillf Danton
Quoted 3 lines

Given the loop workqueue that triggered the jfs warning, can you specify the reason why the workqueue in question is NOT flushed while closing disk?

Got it, the loop workqueue is NOT flushed to avoid deadlock, see d292dc80686a ("loop: don't destroy lo->workqueue in __loop_clr_fd") for detail. And the deadlock can be reproduced by flushing the loop workqueue with disk->open_mutex held [1].

[1] Subject: Re: [syzbot] possible deadlock in blkdev_put (3)
https://lore.kernel.org/lkml/[email protected]/

We can avoid the following lockdep warnings (including [1] you mentioned)

https://syzkaller.appspot.com/bug?extid=2f62807dc3239b8f584e
https://syzkaller.appspot.com/bug?extid=c4e9d077bcc86bee08dc
https://syzkaller.appspot.com/bug?extid=0f427123ae84b3ba6dc7
https://syzkaller.appspot.com/bug?extid=4feabfc9641267769c97
https://syzkaller.appspot.com/bug?extid=fb0ff9bfe34ad282ebd4

caused by "drain_workqueue() with disk->open_mutex held" if we assign caller-specific lockdep class to disk->open_mutex

https://sourceforge.net/p/tomoyo/tomoyo.git/ci/c2245c765ebeba9dcb924d9171d8d470a9ac41c8/

.

Also, we can avoid lockdep warning caused by "drain_workqueue() with disk->open_mutex held" + "holding system_transition_mutex" if we forbid binding to pseudo files as backing file in the loop driver

https://lkml.kernel.org/r/[email protected]

which we can reproduce with

echo 7:0 > /sys/power/resume
losetup /dev/loop0 /sys/power/resume
cat /dev/loop0 > /dev/null
losetup -d /dev/loop0

Quoted 7 lines
Quoted 5 lines

.

Therefore, I think we can address this problem by "drain_workqueue() with disk->open_mutex held" in the loop driver side.

Good news.

Bad news: Subject: [syzbot] [block?] possible deadlock in loop_process_work
[3] https://lore.kernel.org/lkml/[email protected]/

syzbot found the following issue on:

HEAD commit:    c1ecb239fa34 Add linux-next specific files for 20260522
git tree:       linux-next
console output: https://syzkaller.appspot.com/x/log.txt?x=12fa6336580000
kernel config:  https://syzkaller.appspot.com/x/.config?x=77a9211ff284de54
dashboard link: https://syzkaller.appspot.com/bug?extid=78ad2c6a58c0a1faa5f5
compiler:       Debian clang version 21.1.8 (++20251221033036+2078da43e25a-1~exp1~20251221153213.50), Debian LLD 21.1.8

Unfortunately, I don't have any reproducer for this issue yet.

Downloadable assets:
disk image: https://storage.googleapis.com/syzbot-assets/4cb88c910144/disk-c1ecb239.raw.xz
vmlinux: https://storage.googleapis.com/syzbot-assets/4a9bc938cf88/vmlinux-c1ecb239.xz
kernel image: https://storage.googleapis.com/syzbot-assets/684f1e33f264/bzImage-c1ecb239.xz

IMPORTANT: if you fix the issue, please add the following tag to the commit:

Reported-by [email protected]

======================================================
WARNING: possible circular locking dependency detected
syzkaller #0 Tainted: G L
------------------------------------------------------
kworker/u8:15/1491 is trying to acquire lock:
ffff88805e1a6480 (sb_writers#5){.+.+}-{0:0}, at: do_req_filebacked drivers/block/loop.c:433 [inline] ffff88805e1a6480 (sb_writers#5){.+.+}-{0:0}, at: loop_handle_cmd drivers/block/loop.c:1941 [inline] ffff88805e1a6480 (sb_writers#5){.+.+}-{0:0}, at: loop_process_work+0x637/0x11b0 drivers/block/loop.c:1976

but task is already holding lock:
ffffc90006e27c40 ((work_completion)(&worker->work)){+.+.}-{0:0}, at: process_one_work+0x8be/0x1630 kernel/workqueue.c:3294

which lock already depends on the new lock.

the existing dependency chain (in reverse order) is:

-> #7 ((work_completion)(&worker->work)){+.+.}-{0:0}:

       process_one_work+0x8d7/0x1630 kernel/workqueue.c:3294
       process_scheduled_works kernel/workqueue.c:3401 [inline]
       worker_thread+0xb49/0x1140 kernel/workqueue.c:3482
       kthread+0x388/0x470 kernel/kthread.c:436
       ret_from_fork+0x514/0xb70 arch/x86/kernel/process.c:158
       ret_from_fork_asm+0x1a/0x30 arch/x86/entry/entry_64.S:245

-> #6 ((wq_completion)loop4){+.+.}-{0:0}:

       touch_wq_lockdep_map+0xcb/0x180 kernel/workqueue.c:4033
       __flush_workqueue+0x14b/0x14f0 kernel/workqueue.c:4075
       drain_workqueue+0xd3/0x390 kernel/workqueue.c:4239
       __loop_clr_fd drivers/block/loop.c:1130 [inline]
       lo_release+0x287/0x8f0 drivers/block/loop.c:1767
       bdev_release+0x541/0x660 block/bdev.c:-1
       blkdev_release+0x15/0x20 block/fops.c:705
       __fput+0x461/0xa70 fs/file_table.c:510
       fput_close_sync+0x11f/0x240 fs/file_table.c:615
       __do_sys_close fs/open.c:1511 [inline]
       __se_sys_close fs/open.c:1496 [inline]
       __x64_sys_close+0x7e/0x110 fs/open.c:1496
       do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
       do_syscall_64+0x15f/0x560 arch/x86/entry/syscall_64.c:94
       entry_SYSCALL_64_after_hwframe+0x77/0x7f

-> #5 (&disk->open_mutex){+.+.}-{4:4}:

       __mutex_lock_common kernel/locking/rtmutex_api.c:559 [inline]
       mutex_lock_nested+0x5a/0x1d0 kernel/locking/rtmutex_api.c:578
       __del_gendisk+0x127/0x980 block/genhd.c:710
       del_gendisk+0xe7/0x160 block/genhd.c:823
       nbd_dev_remove drivers/block/nbd.c:268 [inline]
       nbd_dev_remove_work+0x47/0xe0 drivers/block/nbd.c:284
       process_one_work+0x98b/0x1630 kernel/workqueue.c:3318
       process_scheduled_works kernel/workqueue.c:3401 [inline]
       worker_thread+0xb49/0x1140 kernel/workqueue.c:3482
       kthread+0x388/0x470 kernel/kthread.c:436
       ret_from_fork+0x514/0xb70 arch/x86/kernel/process.c:158
       ret_from_fork_asm+0x1a/0x30 arch/x86/entry/entry_64.S:245

-> #4 (&set->update_nr_hwq_lock){++++}-{4:4}:

       down_read+0x97/0x200 kernel/locking/rwsem.c:1568
       add_disk_fwnode+0xe7/0x480 block/genhd.c:596
       add_disk include/linux/blkdev.h:794 [inline]
       nbd_dev_add+0x72c/0xb50 drivers/block/nbd.c:1984
       nbd_genl_connect+0x965/0x1c80 drivers/block/nbd.c:2125
       genl_family_rcv_msg_doit+0x22a/0x330 net/netlink/genetlink.c:1114
       genl_family_rcv_msg net/netlink/genetlink.c:1194 [inline]
       genl_rcv_msg+0x61c/0x7a0 net/netlink/genetlink.c:1209
       netlink_rcv_skb+0x232/0x4b0 net/netlink/af_netlink.c:2551
       genl_rcv+0x28/0x40 net/netlink/genetlink.c:1218
       netlink_unicast_kernel net/netlink/af_netlink.c:1319 [inline]
       netlink_unicast+0x780/0x920 net/netlink/af_netlink.c:1345
       netlink_sendmsg+0x813/0xb40 net/netlink/af_netlink.c:1895
       sock_sendmsg_nosec+0x112/0x150 net/socket.c:797
       __sock_sendmsg net/socket.c:812 [inline]
       ____sys_sendmsg+0x55c/0x870 net/socket.c:2716
       ___sys_sendmsg+0x2a5/0x360 net/socket.c:2770
       __sys_sendmsg net/socket.c:2802 [inline]
       __do_sys_sendmsg net/socket.c:2807 [inline]
       __se_sys_sendmsg net/socket.c:2805 [inline]
       __x64_sys_sendmsg+0x1c3/0x2a0 net/socket.c:2805
       do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
       do_syscall_64+0x15f/0x560 arch/x86/entry/syscall_64.c:94
       entry_SYSCALL_64_after_hwframe+0x77/0x7f

-> #3 (genl_mutex){+.+.}-{4:4}:

       __mutex_lock_common kernel/locking/rtmutex_api.c:559 [inline]
       mutex_lock_nested+0x5a/0x1d0 kernel/locking/rtmutex_api.c:578
       genl_lock net/netlink/genetlink.c:35 [inline]
       genl_lock_all net/netlink/genetlink.c:48 [inline]
       genl_register_family+0x7b9/0x17b0 net/netlink/genetlink.c:784
       vdpa_init+0x39/0x70 drivers/vdpa/vdpa.c:1565
       do_one_initcall+0x250/0x870 init/main.c:1347
       do_initcall_level+0x104/0x190 init/main.c:1409
       do_initcalls+0x59/0xa0 init/main.c:1425
       kernel_init_freeable+0x2a6/0x3e0 init/main.c:1658
       kernel_init+0x1d/0x1d0 init/main.c:1548
       ret_from_fork+0x514/0xb70 arch/x86/kernel/process.c:158
       ret_from_fork_asm+0x1a/0x30 arch/x86/entry/entry_64.S:245

-> #2 (cb_lock){++++}-{4:4}:

       down_read+0x97/0x200 kernel/locking/rwsem.c:1568
       genl_rcv+0x19/0x40 net/netlink/genetlink.c:1217
       netlink_unicast_kernel net/netlink/af_netlink.c:1319 [inline]
       netlink_unicast+0x780/0x920 net/netlink/af_netlink.c:1345
       netlink_sendmsg+0x813/0xb40 net/netlink/af_netlink.c:1895
       sock_sendmsg_nosec+0x112/0x150 net/socket.c:797
       __sock_sendmsg net/socket.c:812 [inline]
       sock_sendmsg+0x1ca/0x2d0 net/socket.c:835
       splice_to_socket+0xae5/0x11f0 fs/splice.c:884
       do_splice_from fs/splice.c:936 [inline]
       do_splice+0xef8/0x1940 fs/splice.c:1349
       __do_splice fs/splice.c:1431 [inline]
       __do_sys_splice fs/splice.c:1634 [inline]
       __se_sys_splice+0x353/0x490 fs/splice.c:1616
       do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
       do_syscall_64+0x15f/0x560 arch/x86/entry/syscall_64.c:94
       entry_SYSCALL_64_after_hwframe+0x77/0x7f

-> #1 (&pipe->mutex){+.+.}-{4:4}:

       __mutex_lock_common kernel/locking/rtmutex_api.c:559 [inline]
       mutex_lock_nested+0x5a/0x1d0 kernel/locking/rtmutex_api.c:578
       iter_file_splice_write+0x1f3/0x10f0 fs/splice.c:682
       do_splice_from fs/splice.c:936 [inline]
       do_splice+0xef8/0x1940 fs/splice.c:1349
       __do_splice fs/splice.c:1431 [inline]
       __do_sys_splice fs/splice.c:1634 [inline]
       __se_sys_splice+0x353/0x490 fs/splice.c:1616
       do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
       do_syscall_64+0x15f/0x560 arch/x86/entry/syscall_64.c:94
       entry_SYSCALL_64_after_hwframe+0x77/0x7f

-> #0 (sb_writers#5){.+.+}-{0:0}:

       check_prev_add kernel/locking/lockdep.c:3167 [inline]
       check_prevs_add kernel/locking/lockdep.c:3286 [inline]
       validate_chain kernel/locking/lockdep.c:3910 [inline]
       __lock_acquire+0x15a5/0x2d10 kernel/locking/lockdep.c:5239
       lock_acquire+0x106/0x350 kernel/locking/lockdep.c:5870
       percpu_down_read_internal include/linux/percpu-rwsem.h:53 [inline]
       percpu_down_read_freezable include/linux/percpu-rwsem.h:83 [inline]
       __sb_start_write include/linux/fs/super.h:19 [inline]
       sb_start_write include/linux/fs/super.h:125 [inline]
       kiocb_start_write include/linux/fs.h:2767 [inline]
       lo_rw_aio+0xb1b/0xf00 drivers/block/loop.c:401
       do_req_filebacked drivers/block/loop.c:433 [inline]
       loop_handle_cmd drivers/block/loop.c:1941 [inline]
       loop_process_work+0x637/0x11b0 drivers/block/loop.c:1976
       process_one_work+0x98b/0x1630 kernel/workqueue.c:3318
       process_scheduled_works kernel/workqueue.c:3401 [inline]
       worker_thread+0xb49/0x1140 kernel/workqueue.c:3482
       kthread+0x388/0x470 kernel/kthread.c:436
       ret_from_fork+0x514/0xb70 arch/x86/kernel/process.c:158
       ret_from_fork_asm+0x1a/0x30 arch/x86/entry/entry_64.S:245

other info that might help us debug this:

Chain exists of:
  sb_writers#5 --> (wq_completion)loop4 --> (work_completion)(&worker->work)

 Possible unsafe locking scenario:
       CPU0                    CPU1
       ----                    ----
  lock((work_completion)(&worker->work));
                               lock((wq_completion)loop4);
                               lock((work_completion)(&worker->work));

rlock(sb_writers#5);

*** DEADLOCK ***

#38 lore raw

Re: [PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 8 lines · Hillf Danton
Quoted 5 lines
Quoted 3 lines

Therefore, I think we can address this problem by "drain_workqueue() with disk->open_mutex held" in the loop driver side.

Good news.

Bad news: Subject: [syzbot] [block?] possible deadlock in loop_process_work
[3] https://lore.kernel.org/lkml/[email protected]/

OK. I sent two patches

https://lkml.kernel.org/r/[email protected]
https://lkml.kernel.org/r/[email protected]

as a preparation for evaluating the possibility of calling drain_workqueue() from __loop_clr_fd(). But as far as syzbot has tested using linux-next tree

https://syzkaller.appspot.com/bug?extid=c4e9d077bcc86bee08dc
https://syzkaller.appspot.com/bug?extid=4feabfc9641267769c97

seems to remain even if we applied above patches.

Therefore, I think that we need to call drain_workqueue() from __loop_clr_fd() without holding disk->open_mutex (if we address this NULL pointer dereference problem by updating the loop driver).

"[PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()" was an attempt to call drain_workqueue() from __loop_clr_fd() without holding disk->open_mutex, but Sashiko's review ( https://sashiko.dev/#/patchset/fda8abc8-6aa2-463b-bf72-865f6b838034%40I-love.SAKURA.ne.jp ) mentioned that the "module_put(THIS_MODULE);" executed as the last step of __loop_clr_fd() has a race window of concurrently triggering module unload operation because module refcount of the loop driver can become 0 due to this module_put(THIS_MODULE) call. In other words, we cannot safely manage refcount of the loop module without a support by the caller of lo_release() (i.e. bdev_release()).

  void bdev_release(struct file *bdev_file)
  {
  (...snipped...)
  	if (bdev_is_partition(bdev))
  		blkdev_put_part(bdev);
  	else
  		blkdev_put_whole(bdev);
  	mutex_unlock(&disk->open_mutex); // <= Keeping holding disk->open_mutex until __loop_clr_fd() completes causes circular locking problem.
  
  	module_put(disk->fops->owner); // <= Calling after __loop_clr_fd() completed is required for managing module refcount safely.
  put_no_open:
  	blkdev_put_no_open(bdev);
  }

Therefore, I think that the only robust and safe approach is, although you won't be happy to see layering violation / tricky code, either

(a) allow __loop_clr_fd() to temporarily drop disk->open_mutex

or

(b) add a new callback for the loop driver which is called between mutex_unlock(&disk->open_mutex) and module_put(disk->fops->owner)

. Jens, what do you think?

One might argue that this problem should be fixed on the filesystem side by ensuring all filesystems wait for I/O requests safely. However, from the perspective of defensive programming, the loop driver should be robust enough to handle incomplete I/O serialization from underlying layers to prevent GPF. Furthermore, without adding noisy debug printk() messages, it is extremely difficult to pinpoint which specific layer or filesystem failed to wait for the I/O requests.

#24 lore raw

Re: [PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()

In reply to Qu Wenruo
Quoted 7 lines · Qu Wenruo
Quoted 2 lines

e.g. 9c7504aa72b6 ("xfs: track and serialize in-flight async buffers against unmount")

Considering the xfs fix is pretty old, it's before the fix hint thus no such mention in fstests.

Do you happen to know which test case is for that fix? I'd like to adapt it for btrfs as a reproducer.

No. Adding Brian who authored that commit.

#27 lore raw

Re: [PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()

In reply to Qu Wenruo
Quoted 31 lines · Qu Wenruo
Quoted 11 lines · Christoph Hellwig
Quoted 2 lines · Damien Le Moal

It sounds like the VFS unmount call needs to have something that waits for sync() to complete. Though, it really feels very strange that an FS can complete

I don't think this is the VFS-controlled VFS file data writeback, which we wait on, but some kind of fs controlled metadata. And yes, it looks like those file systems are buggy in that area. We definitively had such bugs in XFS before and fixed them.

e.g. 9c7504aa72b6 ("xfs: track and serialize in-flight async buffers against unmount")

Considering the xfs fix is pretty old, it's before the fix hint thus no such mention in fstests.

Do you happen to know which test case is for that fix? I'd like to adapt it for btrfs as a reproducer.

This syzbot report doesn't provide a reproducer.

Another thing is, if it's some btrfs bios on-the-fly after close_ctree(), the most common symptom should be NULL pointer dereference inside various btrfs endio functions.
As all those end_bbio_*() functions are referring to either fs_info or inode/eb, thus if the fs is unmounted before the bio finished, they should all cause use-after-free.

Quoted 3 lines

The only exception is discard, which is using blkdev_issue_discard() thus has no such reference to btrfs internal structure, but that's out of my understanding.

syzbot log shows the null-ptr-deref is on WRITE, instead of DISCARD.

https://syzkaller.appspot.com/bug?extid=cd8a9a308e879a4e2c28

Adding WARN_ON(!lo->lo_backing_file) in loop_queue_rq() might capture this bio submission context if this req isn't issued via wq.

Thanks,
Ming Lei

#25 lore raw

Re: [PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()

In reply to Christoph Hellwig
Quoted 11 lines · Christoph Hellwig
Quoted 7 lines · Qu Wenruo
Quoted 2 lines

e.g. 9c7504aa72b6 ("xfs: track and serialize in-flight async buffers against unmount")

Considering the xfs fix is pretty old, it's before the fix hint thus no such mention in fstests.

Do you happen to know which test case is for that fix? I'd like to adapt it for btrfs as a reproducer.

No. Adding Brian who authored that commit.

I haven't followed through the full thread here... But if you're just looking for an existing test case associated with the commit above on XFS, I did some quick digging and xfs/311 is the original reproducer for that one.

Brian

#28 lore raw

Re: [PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()

In reply to Ming Lei
Quoted 33 lines · On Mon, 1 Jun 2026 10:29:25 -0500 Ming Lei wrote:
Quoted 28 lines · Qu Wenruo
Quoted 11 lines · Christoph Hellwig
Quoted 2 lines · Damien Le Moal

It sounds like the VFS unmount call needs to have something that waits for sync() to complete. Though, it really feels very strange that an FS can complete

I don't think this is the VFS-controlled VFS file data writeback, which we wait on, but some kind of fs controlled metadata. And yes, it looks like those file systems are buggy in that area. We definitively had such bugs in XFS before and fixed them.

e.g. 9c7504aa72b6 ("xfs: track and serialize in-flight async buffers against unmount")

Considering the xfs fix is pretty old, it's before the fix hint thus no such mention in fstests.

Do you happen to know which test case is for that fix? I'd like to adapt it for btrfs as a reproducer.

This syzbot report doesn't provide a reproducer.

Another thing is, if it's some btrfs bios on-the-fly after close_ctree(), the most common symptom should be NULL pointer dereference inside various btrfs endio functions.
As all those end_bbio_*() functions are referring to either fs_info or inode/eb, thus if the fs is unmounted before the bio finished, they should all cause use-after-free.

Quoted 3 lines

The only exception is discard, which is using blkdev_issue_discard() thus has no such reference to btrfs internal structure, but that's out of my understanding.

Quoted 7 lines

syzbot log shows the null-ptr-deref is on WRITE, instead of DISCARD.

https://syzkaller.appspot.com/bug?extid=cd8a9a308e879a4e2c28

Adding WARN_ON(!lo->lo_backing_file) in loop_queue_rq() might capture this bio submission context if this req isn't issued via wq.

I suspect this makes $.02 sense given the check of Lo_bound upon queuing rq.

static blk_status_t loop_queue_rq(struct blk_mq_hw_ctx *hctx,
const struct blk_mq_queue_data *bd)

{
	struct request *rq = bd->rq;
	struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
	struct loop_device *lo = rq->q->queuedata;

	blk_mq_start_request(rq);

	if (data_race(READ_ONCE(lo->lo_state)) != Lo_bound)
		return BLK_STS_IOERR;
#29 lore raw

Re: [PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 34 lines · Hillf Danton
Quoted 33 lines · On Mon, 1 Jun 2026 10:29:25 -0500 Ming Lei wrote:
Quoted 31 lines · Qu Wenruo
Quoted 11 lines · Christoph Hellwig
Quoted 2 lines · Damien Le Moal

It sounds like the VFS unmount call needs to have something that waits for sync() to complete. Though, it really feels very strange that an FS can complete

I don't think this is the VFS-controlled VFS file data writeback, which we wait on, but some kind of fs controlled metadata. And yes, it looks like those file systems are buggy in that area. We definitively had such bugs in XFS before and fixed them.

e.g. 9c7504aa72b6 ("xfs: track and serialize in-flight async buffers against unmount")

Considering the xfs fix is pretty old, it's before the fix hint thus no such mention in fstests.

Do you happen to know which test case is for that fix? I'd like to adapt it for btrfs as a reproducer.

This syzbot report doesn't provide a reproducer.

Another thing is, if it's some btrfs bios on-the-fly after close_ctree(), the most common symptom should be NULL pointer dereference inside various btrfs endio functions.
As all those end_bbio_*() functions are referring to either fs_info or inode/eb, thus if the fs is unmounted before the bio finished, they should all cause use-after-free.

The only exception is discard, which is using blkdev_issue_discard() thus has no such reference to btrfs internal structure, but that's out of my understanding.

Quoted 8 lines
Quoted 7 lines

syzbot log shows the null-ptr-deref is on WRITE, instead of DISCARD.

https://syzkaller.appspot.com/bug?extid=cd8a9a308e879a4e2c28

Adding WARN_ON(!lo->lo_backing_file) in loop_queue_rq() might capture this bio submission context if this req isn't issued via wq.

I suspect this makes $.02 sense given the check of Lo_bound upon queuing rq.

Can't lo->lo_state be updated after the check? It is totally lockless...

Thanks,
Ming

#26 lore raw

Re: [PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()

In reply to Brian Foster
Quoted 10 lines · Brian Foster
Quoted 9 lines · Christoph Hellwig
Quoted 7 lines · Qu Wenruo
Quoted 2 lines

e.g. 9c7504aa72b6 ("xfs: track and serialize in-flight async buffers against unmount")

Considering the xfs fix is pretty old, it's before the fix hint thus no such mention in fstests.

Do you happen to know which test case is for that fix? I'd like to adapt it for btrfs as a reproducer.

Quoted 7 lines
Quoted 2 lines

No. Adding Brian who authored that commit.

I haven't followed through the full thread here... But if you're just looking for an existing test case associated with the commit above on XFS, I did some quick digging and xfs/311 is the original reproducer for that one.

Thanks a lot! I'll use the same delayed umount to verify the behavior of btrfs.

Thanks,
Qu

Quoted 3 lines

Brian

#30 lore raw

Re: [PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()

In reply to Ming Lei
Quoted 4 lines · On Mon, 1 Jun 2026 17:14:59 -0500 Ming Lei wrote:
Quoted 3 lines · Hillf Danton
Quoted 2 lines · On OnMon, 1 Jun 2026 10:29:25 -0500 Ming Lei wrote:

syzbot log shows the null-ptr-deref is on WRITE, instead of DISCARD.

Quoted 9 lines
Quoted 6 lines
Quoted 5 lines

https://syzkaller.appspot.com/bug?extid=cd8a9a308e879a4e2c28

Adding WARN_ON(!lo->lo_backing_file) in loop_queue_rq() might capture this bio submission context if this req isn't issued via wq.

I suspect this makes $.02 sense given the check of Lo_bound upon queuing rq.

Can't lo->lo_state be updated after the check? It is totally lockless...

Sounds good hm... do you mean it is UNWISE to not flush the loop workqueue when closing disk?

#31 lore raw

Re: [PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 10 lines · Hillf Danton
Quoted 9 lines · On Mon, 1 Jun 2026 17:14:59 -0500 Ming Lei wrote:
Quoted 8 lines · Hillf Danton
Quoted 7 lines · On OnMon, 1 Jun 2026 10:29:25 -0500 Ming Lei wrote:

syzbot log shows the null-ptr-deref is on WRITE, instead of DISCARD.

https://syzkaller.appspot.com/bug?extid=cd8a9a308e879a4e2c28

Adding WARN_ON(!lo->lo_backing_file) in loop_queue_rq() might capture this bio submission context if this req isn't issued via wq.

Quoted 6 lines
Quoted 4 lines
Quoted 1 line

I suspect this makes $.02 sense given the check of Lo_bound upon queuing rq.

Can't lo->lo_state be updated after the check? It is totally lockless...

Sounds good hm... do you mean it is UNWISE to not flush the loop workqueue when closing disk?

Quite the opposite, it is wise to not flush wq in __loop_clr_fd(), please see my previous comment.

Thanks,
Ming

#32 lore raw

Re: [PATCH v3] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 13 lines · on Mon, 1 Jun 2026 18:36:19 -0500 Ming Lei wrote:
Quoted 12 lines · Hillf Danton
Quoted 11 lines · On Mon, 1 Jun 2026 17:14:59 -0500 Ming Lei wrote:
Quoted 9 lines · Hillf Danton
Quoted 7 lines · On OnMon, 1 Jun 2026 10:29:25 -0500 Ming Lei wrote:

syzbot log shows the null-ptr-deref is on WRITE, instead of DISCARD.

https://syzkaller.appspot.com/bug?extid=cd8a9a308e879a4e2c28

Adding WARN_ON(!lo->lo_backing_file) in loop_queue_rq() might capture this bio submission context if this req isn't issued via wq.

I suspect this makes $.02 sense given the check of Lo_bound upon queuing rq.

Quoted 8 lines
Quoted 4 lines
Quoted 2 lines

Can't lo->lo_state be updated after the check? It is totally lockless...

Sounds good hm... do you mean it is UNWISE to not flush the loop workqueue when closing disk?

Quite the opposite, it is wise to not flush wq in __loop_clr_fd(), please see my previous comment.

When queuing rq, if lo_state is updated after checking Lo_bond, I see nothing that prevents syzbot from reporting null-ptr-deref exists. Can you tippoint why flush is NOT needed if you are right?

#39 lore raw

PATCH v4 1/1 loop: Fix NULL pointer dereference in lo_rw_aio()

In reply to Tetsuo Handa

syzbot is reporting NULL pointer dereference in lo_rw_aio() [1][2]. An analysis by the Gemini AI collaborator [3] considers that this problem is caused by a timing shift primarily exposed by commit 65565ca5f99b ("block: unify the synchronous bi_end_io callbacks"), along with helper refactorings like commit 92c3737a2473 ("block: add a bio_submit_or_kill helper").

But due to difficulty of reproducing this race, discussion about what is happening and how to fix this problem is stalling. Also, we haven't identified how many filesystems are subjected to this problem.

Therefore, this patch introduces a grace period for flushing pending I/O requests (which should be a good thing from the perspective of defensive programming) so that we won't hit NULL pointer dereference problem, and also emits BUG: message in order to help filesystem developers identify the caller of an I/O request that failed to wait for completion so that filesystem developers can fix such caller to wait for completion.

Note that emitting BUG: message is enabled only if CONFIG_KCOV=y, for this check is a waste of computation resources for almost all users.

---
 drivers/block/loop.c | 82 ++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 80 insertions(+), 2 deletions(-)
drivers/block/loop.c +80 -2
index 0000913f7efc..4ff254d8b623 100644
@@ -85,8 +85,26 @@ struct loop_cmd {
 	struct bio_vec *bvec;
 	struct cgroup_subsys_state *blkcg_css;
 	struct cgroup_subsys_state *memcg_css;
+#ifdef CONFIG_KCOV
+	unsigned long stack_entries[30];
+	int stack_nr;
+	pid_t pid;
+	char comm[TASK_COMM_LEN];
+#endif
 };
 
+static void loop_check_io_race(struct loop_device *lo, struct loop_cmd *cmd)
+{
+#ifdef CONFIG_KCOV
+	if (unlikely(data_race(READ_ONCE(lo->lo_state)) == Lo_rundown)) {
+		pr_err("BUG: %s/%u is doing I/O request on loop%d in Lo_rundown state.\n",
+		       cmd->comm, cmd->pid, lo->lo_number);
+		printk("Call trace:\n");
+		stack_trace_print(cmd->stack_entries, cmd->stack_nr, 4);
+	}
+#endif
+}
+
 #define LOOP_IDLE_WORKER_TIMEOUT (60 * HZ)
 #define LOOP_DEFAULT_HW_Q_DEPTH 128
 
@@ -1747,8 +1765,59 @@ static void lo_release(struct gendisk *disk)
 	need_clear = (lo->lo_state == Lo_rundown);
 	mutex_unlock(&lo->lo_mutex);
 
-	if (need_clear)
+	if (need_clear) {
+		/*
+		 * Temporarily release disk->open_mutex in order to flush pending I/O
+		 * requests before clearing the backing device.
+		 *
+		 * This is a layering violation. But since bdev->bd_disk->fops->release()
+		 * (which is mapped to lo_release()) is the final function which
+		 * blkdev_put_whole() from bdev_release() calls immediately before
+		 * releasing disk->open_mutex, this changes nothing except opens a new
+		 * race window for allowing disk->fops->open() (which is mapped to
+		 * lo_open()) to be called.
+		 *
+		 * Even if lo_open() is called from blkdev_get_whole() due to this race,
+		 * the Lo_rundown state guarantees that lo_open() will fail with -ENXIO.
+		 * Thus, there will be effectively no change caused by this violation.
+		 */
+		mutex_unlock(&lo->lo_disk->open_mutex);
+		/*
+		 * Now that loop_queue_rq() sees lo->lo_state != Lo_bound,
+		 * wait for already started loop_queue_rq() to complete.
+		 */
+		synchronize_rcu();
+		/*
+		 * Now that no more works are scheduled by loop_queue_rq(),
+		 * wait for already scheduled works to complete.
+		 */
+		drain_workqueue(lo->workqueue);
+		/*
+		 * Now that no more AIO requests are scheduled by lo_rw_aio(),
+		 * wait for already started AIO to complete.
+		 *
+		 * Due to synchronize_rcu() + drain_workqueue() sequence above,
+		 * calling blk_mq_unfreeze_queue() immediately after blk_mq_freeze_queue()
+		 * returns has to be safe, for loop_queue_rq() no longer schedules new
+		 * lo_rw_aio() works and lo_rw_aio() no longer submits new AIO requests.
+		 *
+		 * Deferring blk_mq_unfreeze_queue() does not help because we are about
+		 * to clear the backing device and drop the refcount for the backing device.
+		 * There is nothing we can do if blk_mq_freeze_queue() fails to flush.
+		 */
+		blk_mq_unfreeze_queue(lo->lo_queue, blk_mq_freeze_queue(lo->lo_queue));
+		/*
+		 * Perform remaining cleanup, with disk->open_mutex held.
+		 *
+		 * The lo->lo_state should remain Lo_rundown despite we temporarily
+		 * released disk->open_mutex, for I am the only and the last user of
+		 * this loop device because lo_open() cannot succeed.
+		 */
+		mutex_lock(&lo->lo_disk->open_mutex);
+		if (WARN_ON(data_race(READ_ONCE(lo->lo_state)) != Lo_rundown))
+			return;
 		__loop_clr_fd(lo);
+	}
 }
 
 static void lo_free_disk(struct gendisk *disk)
@@ -1855,10 +1924,18 @@ static blk_status_t loop_queue_rq(struct blk_mq_hw_ctx *hctx,
 	struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
 	struct loop_device *lo = rq->q->queuedata;
 
+#ifdef CONFIG_KCOV
+	cmd->stack_nr = stack_trace_save(cmd->stack_entries, ARRAY_SIZE(cmd->stack_entries), 0);
+	cmd->pid = current->pid;
+	get_task_comm(cmd->comm, current);
+#endif
+
 	blk_mq_start_request(rq);
 
-	if (data_race(READ_ONCE(lo->lo_state)) != Lo_bound)
+	if (data_race(READ_ONCE(lo->lo_state)) != Lo_bound) {
+		loop_check_io_race(lo, cmd);
 		return BLK_STS_IOERR;
+	}
 
 	switch (req_op(rq)) {
 	case REQ_OP_FLUSH:
@@ -1901,6 +1978,7 @@ static void loop_handle_cmd(struct loop_cmd *cmd)
 	int ret = 0;
 	struct mem_cgroup *old_memcg = NULL;
 
+	loop_check_io_race(lo, cmd);
 	if (write && (lo->lo_flags & LO_FLAGS_READ_ONLY)) {
 		ret = -EIO;
 		goto failed;
Signature · 1 line
2.47.3
maintainer
#40 lore raw

Re: [PATCH v4] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 18 lines · Tetsuo Handa

syzbot is reporting NULL pointer dereference in lo_rw_aio() [1][2]. An analysis by the Gemini AI collaborator [3] considers that this problem is caused by a timing shift primarily exposed by commit 65565ca5f99b ("block: unify the synchronous bi_end_io callbacks"), along with helper refactorings like commit 92c3737a2473 ("block: add a bio_submit_or_kill helper").

But due to difficulty of reproducing this race, discussion about what is happening and how to fix this problem is stalling. Also, we haven't identified how many filesystems are subjected to this problem.

Therefore, this patch introduces a grace period for flushing pending I/O requests (which should be a good thing from the perspective of defensive programming) so that we won't hit NULL pointer dereference problem, and also emits BUG: message in order to help filesystem developers identify the caller of an I/O request that failed to wait for completion so that filesystem developers can fix such caller to wait for completion.

Quoted 2 lines

Note that emitting BUG: message is enabled only if CONFIG_KCOV=y, for this check is a waste of computation resources for almost all users.

Still breaks xfs/259, same as the version in next-20260605...

#41 lore raw

Re: [PATCH v4] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 1 line · Al Viro

Still breaks xfs/259, same as the version in next-20260605...

I installed xfstests-dev and reproduced a "umount: /home/test: target is busy." problem which Al Viro is
experiencing with https://git.kernel.org/pub/scm/linux/kernel/git/next/linux-next.git/commit/?h=next-20260608&id=fb1d5846e99c8aa4ce8da7e6ee7643b01da25b8c .

--------------------------------------------------------------------------------
./check xfs/259

FSTYP         -- xfs (non-debug)
PLATFORM      -- Linux/x86_64 kvm1 7.1.0-rc7-next-20260608+ #72 SMP PREEMPT_DYNAMIC Tue Jun  9 18:27:54 EDT 2026
MKFS_OPTIONS  -- -f /dev/sdb2

MOUNT_OPTIONS -- /dev/sdb2 /home/scratch

xfs/259 3s ... umount: /home/test: target is busy. _check_xfs_filesystem: filesystem on /dev/sdb1 has dirty log (see /home/al/xfstests/results//xfs/259.full for details) _check_xfs_filesystem: filesystem on /dev/sdb1 is inconsistent (r) (see /home/al/xfstests/results//xfs/259.full for details)

Ran: xfs/259
Failures: xfs/259
Failed 1 of 1 tests
--------------------------------------------------------------------------------

Below I describe what I tried, but my opinion is that this "target is busy" problem should be addressed by xfstests side (i.e. retry umount after a short sleep when umount failed with "target is busy" error).

--------------------------------------------------------------------------------

# fdisk -l
Disk /dev/nvme0n1: 40 GiB, 42949672960 bytes, 83886080 sectors
Disk model: VMware Virtual NVMe Disk
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: 068F8BED-D8BE-4795-8ABD-47A089653C58

Device Start End Sectors Size Type
/dev/nvme0n1p1 2048 4095 2048 1M BIOS boot
/dev/nvme0n1p2 4096 83884031 83879936 40G Linux filesystem

Disk /dev/sda: 20 GiB, 21474836480 bytes, 41943040 sectors Disk model: VMware Virtual S
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disklabel type: dos
Disk identifier: 0x1c8e18a6

Device Boot Start End Sectors Size Id Type
/dev/sda1 2048 20970495 20968448 10G 83 Linux
/dev/sda2 20971520 41943039 20971520 10G 83 Linux
--------------------------------------------------------------------------------

--------------------------------------------------------------------------------
cd
git clone https://kernel.googlesource.com/pub/scm/linux/kernel/git/cem/xfstests-dev
cd xfstests-dev/
make -j10
make install
cd /var/lib/xfstests/
TEST_SZ=$(blockdev --getsz /dev/sda1)
SCRATCH_SZ=$(blockdev --getsz /dev/sda2)
dmsetup create delayed_test --table "0 $TEST_SZ delay /dev/sda1 0 10" dmsetup create delayed_scratch --table "0 $SCRATCH_SZ delay /dev/sda2 0 10" export FSTYP=xfs
export TEST_DEV=/dev/mapper/delayed_test
export TEST_DIR=/home/test
export SCRATCH_DEV=/dev/mapper/delayed_scratch
export SCRATCH_MNT=/home/scratch
mkdir -p $TEST_DIR $SCRATCH_MNT
cd /var/lib/xfstests/
./check xfs/259
--------------------------------------------------------------------------------

--------------------------------------------------------------------------------

FSTYP         -- xfs (non-debug)
PLATFORM      -- Linux/x86_64 localhost 7.1.0-rc7-next-20260608 #22 SMP PREEMPT_DYNAMIC Sat Jun 13 18:50:49 JST 2026
MKFS_OPTIONS  -- -f /dev/mapper/delayed_scratch

MOUNT_OPTIONS -- /dev/mapper/delayed_scratch /home/scratch

xfs/259 61s ... umount: /home/test: target is busy. _check_xfs_filesystem: filesystem on /dev/mapper/delayed_test has dirty log (see /var/lib/xfstests/results//xfs/259.full for details) _check_xfs_filesystem: filesystem on /dev/mapper/delayed_test is inconsistent (r) (see /var/lib/xfstests/results//xfs/259.full for details)
Trying to repair broken TEST_DEV file system
_repair_test_fs: failed, err=1
(see /var/lib/xfstests/results//xfs/259.full for details)

Ran: xfs/259
Failures: xfs/259
Failed 1 of 1 tests

--------------------------------------------------------------------------------

I initially suspected that the cause of "target is busy" error is that fput() from __loop_clr_fd() does not wait for completion before "losetup -d" completes. But a debug printk() patch shown below indicated a tendency:

(a) __loop_clr_fd() is called by "udev-worker" rather than "losetup" when this problem happens

(b) propagate_mount_busy()!=0 when do_umount() fails with -EBUSY

--------------------------------------------------------------------------------

drivers/block/loop.c +4 -0
index c3b607a3ddc4..7408f314a1fa 100644
@@ -1763,6 +1763,8 @@ static void lo_release(struct gendisk *disk)
 	mutex_unlock(&lo->lo_mutex);
 
 	if (need_clear) {
+		printk("Flush: task=%s[%d] dev=loop%d state=%d\n",
+		       current->comm, current->pid, lo->lo_number, lo->lo_state);
 		/*
 		 * Temporarily release disk->open_mutex in order to flush pending I/O
 		 * requests before clearing the backing device.
@@ -1813,6 +1815,8 @@ static void lo_release(struct gendisk *disk)
 		mutex_lock(&lo->lo_disk->open_mutex);
 		if (WARN_ON(data_race(READ_ONCE(lo->lo_state)) != Lo_rundown))
 			return;
+		printk("Teardown: task=%s[%d] dev=loop%d state=%d\n",
+		       current->comm, current->pid, lo->lo_number, lo->lo_state);
 		__loop_clr_fd(lo);
 	}
 }
fs/namespace.c +5 -0
index 09ab7fc72f86..9710460fb449 100644
@@ -1893,6 +1893,8 @@ static int do_umount(struct mount *mnt, int flags)
 		 */
 		lock_mount_hash();
 		if (!list_empty(&mnt->mnt_mounts) || mnt_get_count(mnt) != 2) {
+			printk("%s: task=%s[%d] !list_empty(&mnt->mnt_mounts)=%d mnt_get_count(mnt)=%d\n", __func__,
+			       current->comm, current->pid, !list_empty(&mnt->mnt_mounts), mnt_get_count(mnt));
 			unlock_mount_hash();
 			return -EBUSY;
 		}
@@ -1960,6 +1962,9 @@ static int do_umount(struct mount *mnt, int flags)
 		if (!propagate_mount_busy(mnt, 2)) {
 			umount_tree(mnt, UMOUNT_PROPAGATE|UMOUNT_SYNC);
 			retval = 0;
+		} else {
+			printk("%s: task=%s[%d] propagate_mount_busy()!=0\n", __func__,
+			       current->comm, current->pid);
 		}
 	}
 out:

--------------------------------------------------------------------------------

--------------------------------------------------------------------------------

[   77.754264] XFS (dm-0): Mounting V5 Filesystem a80d3f5c-f068-4b64-bfe4-543a811c5e93
[   78.161012] XFS (dm-0): Ending clean mount
[   79.882958] XFS (dm-1): Mounting V5 Filesystem f64fdceb-5dd4-489f-ae3f-f14289964a20
[   80.264828] XFS (dm-1): Ending clean mount
[   80.466146] XFS (dm-1): Unmounting Filesystem f64fdceb-5dd4-489f-ae3f-f14289964a20
[   80.547159] XFS (dm-0): Unmounting Filesystem a80d3f5c-f068-4b64-bfe4-543a811c5e93
[   81.477419] XFS (dm-0): Mounting V5 Filesystem a80d3f5c-f068-4b64-bfe4-543a811c5e93
[   81.871023] XFS (dm-0): Ending clean mount
[   82.008600] run fstests xfs/259 at 2026-06-13 19:39:59
[   83.218605] loop: module loaded
[   83.315929] loop0: detected capacity change from 0 to 8589934584
[   84.897469] loop1: detected capacity change from 0 to 8589934584
[   84.997221] Flush: task=(udev-worker)[1134] dev=loop0 state=2
[   85.014004] Teardown: task=(udev-worker)[1134] dev=loop0 state=2
[   86.354657] Flush: task=losetup[2016] dev=loop1 state=2
[   86.377065] Teardown: task=losetup[2016] dev=loop1 state=2
[   86.416717] loop0: detected capacity change from 0 to 8589934584
[   87.915638] loop1: detected capacity change from 0 to 8589934588
[   88.025704] Flush: task=(udev-worker)[1134] dev=loop0 state=2
[   88.039956] Teardown: task=(udev-worker)[1134] dev=loop0 state=2
[   89.404018] Flush: task=losetup[2048] dev=loop1 state=2
[   89.418144] Teardown: task=losetup[2048] dev=loop1 state=2
[   89.460259] loop0: detected capacity change from 0 to 8589934588
[   91.034214] loop1: detected capacity change from 0 to 8589934588
[   91.149505] Flush: task=(udev-worker)[1134] dev=loop0 state=2
[   91.162932] Teardown: task=(udev-worker)[1134] dev=loop0 state=2
[   92.626690] Flush: task=losetup[2078] dev=loop1 state=2
[   92.652036] Teardown: task=losetup[2078] dev=loop1 state=2
[   92.699585] loop0: detected capacity change from 0 to 8589934590
[   94.307750] loop1: detected capacity change from 0 to 8589934590
[   94.424337] Flush: task=(udev-worker)[1134] dev=loop0 state=2
[   94.441842] Teardown: task=(udev-worker)[1134] dev=loop0 state=2
[   95.869110] Flush: task=losetup[2108] dev=loop1 state=2
[   95.885815] Teardown: task=losetup[2108] dev=loop1 state=2
[   95.931349] loop0: detected capacity change from 0 to 8589934590
[   97.447354] do_umount: task=umount[2143] propagate_mount_busy()!=0
[   97.549813] Flush: task=(udev-worker)[1134] dev=loop0 state=2
[   97.567983] Teardown: task=(udev-worker)[1134] dev=loop0 state=2
[  138.284481] XFS (dm-1): Mounting V5 Filesystem c3b0a09a-f960-464f-a741-84be44d55da0
[  138.679732] XFS (dm-1): Ending clean mount
[  138.865274] XFS (dm-1): Unmounting Filesystem c3b0a09a-f960-464f-a741-84be44d55da0
[  138.944906] XFS (dm-0): Unmounting Filesystem a80d3f5c-f068-4b64-bfe4-543a811c5e93
[  139.833646] XFS (dm-0): Mounting V5 Filesystem a80d3f5c-f068-4b64-bfe4-543a811c5e93
[  140.213952] XFS (dm-0): Ending clean mount
[  140.342963] run fstests xfs/259 at 2026-06-13 19:40:58
[  141.549551] loop0: detected capacity change from 0 to 8589934584
[  143.112857] loop1: detected capacity change from 0 to 8589934584
[  143.219426] Flush: task=(udev-worker)[2502] dev=loop0 state=2
[  143.240186] Teardown: task=(udev-worker)[2502] dev=loop0 state=2
[  144.575984] Flush: task=losetup[3050] dev=loop1 state=2
[  144.593206] Teardown: task=losetup[3050] dev=loop1 state=2
[  144.631137] loop0: detected capacity change from 0 to 8589934584
[  146.114670] loop1: detected capacity change from 0 to 8589934588
[  146.229225] Flush: task=(udev-worker)[2502] dev=loop0 state=2
[  146.248066] Teardown: task=(udev-worker)[2502] dev=loop0 state=2
[  147.626517] Flush: task=losetup[3080] dev=loop1 state=2
[  147.644085] Teardown: task=losetup[3080] dev=loop1 state=2
[  147.679345] loop0: detected capacity change from 0 to 8589934588
[  149.172884] loop1: detected capacity change from 0 to 8589934588
[  149.296011] Flush: task=(udev-worker)[2502] dev=loop0 state=2
[  149.315040] Teardown: task=(udev-worker)[2502] dev=loop0 state=2
[  150.631328] Flush: task=losetup[3110] dev=loop1 state=2
[  150.650082] Teardown: task=losetup[3110] dev=loop1 state=2
[  150.686210] loop0: detected capacity change from 0 to 8589934590
[  152.186234] loop1: detected capacity change from 0 to 8589934590
[  152.308623] Flush: task=(udev-worker)[2502] dev=loop0 state=2
[  152.325972] Teardown: task=(udev-worker)[2502] dev=loop0 state=2
[  153.652919] Flush: task=losetup[3140] dev=loop1 state=2
[  153.681000] Teardown: task=losetup[3140] dev=loop1 state=2
[  153.716545] loop0: detected capacity change from 0 to 8589934590
[  155.235156] do_umount: task=umount[3175] propagate_mount_busy()!=0
[  155.337055] Flush: task=(udev-worker)[2502] dev=loop0 state=2
[  155.352014] Teardown: task=(udev-worker)[2502] dev=loop0 state=2
[  182.533057] XFS (dm-1): Mounting V5 Filesystem a101f7e1-a8bd-44e2-a49f-21985ce78a3b
[  182.915714] XFS (dm-1): Ending clean mount
[  183.114481] XFS (dm-1): Unmounting Filesystem a101f7e1-a8bd-44e2-a49f-21985ce78a3b
[  183.190809] XFS (dm-0): Unmounting Filesystem a80d3f5c-f068-4b64-bfe4-543a811c5e93
[  184.064717] XFS (dm-0): Mounting V5 Filesystem a80d3f5c-f068-4b64-bfe4-543a811c5e93
[  184.456110] XFS (dm-0): Ending clean mount
[  184.592063] run fstests xfs/259 at 2026-06-13 19:41:42
[  185.926189] loop0: detected capacity change from 0 to 8589934584
[  187.473922] loop1: detected capacity change from 0 to 8589934584
[  187.584471] Flush: task=(udev-worker)[3531] dev=loop0 state=2
[  187.603274] Teardown: task=(udev-worker)[3531] dev=loop0 state=2
[  188.961285] Flush: task=losetup[4079] dev=loop1 state=2
[  188.990308] Teardown: task=losetup[4079] dev=loop1 state=2
[  189.029614] loop0: detected capacity change from 0 to 8589934584
[  190.521249] loop1: detected capacity change from 0 to 8589934588
[  190.631200] Flush: task=(udev-worker)[4075] dev=loop0 state=2
[  190.645245] Teardown: task=(udev-worker)[4075] dev=loop0 state=2
[  192.023674] Flush: task=losetup[4109] dev=loop1 state=2
[  192.035269] Teardown: task=losetup[4109] dev=loop1 state=2
[  192.074917] loop0: detected capacity change from 0 to 8589934588
[  193.606595] loop1: detected capacity change from 0 to 8589934588
[  193.727944] Flush: task=(udev-worker)[4075] dev=loop0 state=2
[  193.747188] Teardown: task=(udev-worker)[4075] dev=loop0 state=2
[  195.075694] Flush: task=losetup[4140] dev=loop1 state=2
[  195.092257] Teardown: task=losetup[4140] dev=loop1 state=2
[  195.128969] loop0: detected capacity change from 0 to 8589934590
[  196.636772] loop1: detected capacity change from 0 to 8589934590
[  196.758941] Flush: task=(udev-worker)[4075] dev=loop0 state=2
[  196.779155] Teardown: task=(udev-worker)[4075] dev=loop0 state=2
[  198.105666] Flush: task=losetup[4170] dev=loop1 state=2
[  198.128203] Teardown: task=losetup[4170] dev=loop1 state=2
[  198.163723] loop0: detected capacity change from 0 to 8589934590
[  199.685651] do_umount: task=umount[4205] propagate_mount_busy()!=0
[  199.787468] Flush: task=(udev-worker)[4075] dev=loop0 state=2
[  199.804123] Teardown: task=(udev-worker)[4075] dev=loop0 state=2

--------------------------------------------------------------------------------

That is, if someone else (e.g. udev-worker) by chance has a file descriptor of a loop device when "losetup -d" called lo_release(), __loop_clr_fd() is not called by "losetup" due to commit 18048c1af783 ("loop: Fix a race between loop detach and loop open"). Therefore, I consider that this teardown operation is racy regardless of whether disk->open_mutex is temporarily released or not. Actually, I can reproduce this problem with below change (lockdep warning aside).

------------------------------------------------------------

drivers/block/loop.c +2 -2
index c3b607a3ddc4..076207efb1cc 100644
@@ -1778,7 +1778,7 @@ static void lo_release(struct gendisk *disk)
 		 * the Lo_rundown state guarantees that lo_open() will fail with -ENXIO.
 		 * Thus, there will be effectively no change caused by this violation.
 		 */
-		mutex_unlock(&lo->lo_disk->open_mutex);
+		//mutex_unlock(&lo->lo_disk->open_mutex);
 		/*
 		 * Now that loop_queue_rq() sees lo->lo_state != Lo_bound,
 		 * wait for already started loop_queue_rq() to complete.
@@ -1810,7 +1810,7 @@ static void lo_release(struct gendisk *disk)
 		 * released disk->open_mutex, for I am the only and the last user of
 		 * this loop device because lo_open() cannot succeed.
 		 */
-		mutex_lock(&lo->lo_disk->open_mutex);
+		//mutex_lock(&lo->lo_disk->open_mutex);
 		if (WARN_ON(data_race(READ_ONCE(lo->lo_state)) != Lo_rundown))
 			return;
 		__loop_clr_fd(lo);

------------------------------------------------------------

------------------------------------------------------------

FSTYP         -- xfs (non-debug)
PLATFORM      -- Linux/x86_64 localhost 7.1.0-rc7-next-20260608-dirty #23 SMP PREEMPT_DYNAMIC Sat Jun 13 19:19:37 JST 2026
MKFS_OPTIONS  -- -f /dev/mapper/delayed_scratch

MOUNT_OPTIONS -- /dev/mapper/delayed_scratch /home/scratch

xfs/259 61s ... umount: /home/test: target is busy. _check_xfs_filesystem: filesystem on /dev/mapper/delayed_test has dirty log (see /var/lib/xfstests/results//xfs/259.full for details) _check_xfs_filesystem: filesystem on /dev/mapper/delayed_test is inconsistent (r) (see /var/lib/xfstests/results//xfs/259.full for details)
Trying to repair broken TEST_DEV file system
_repair_test_fs: failed, err=1
(see /var/lib/xfstests/results//xfs/259.full for details)

Ran: xfs/259
Failures: xfs/259
Failed 1 of 1 tests

------------------------------------------------------------

Therefore, although commit fb1d5846e99c ("loop: Fix NULL pointer dereference in lo_rw_aio()") might have widened the race window, I think that this is a problem which should be addressed by updating the "umount" user.

#42 lore raw

Re: [PATCH v4] loop: Fix NULL pointer dereference in lo_rw_aio()

Sending this commit to linux.git will be the fastest way to identify who is issuing I/O requests too late. Therefore, I want to get a conclusion on xfs/259 breakage. Al, can you get the same result?

Quoted 6 lines · Tetsuo Handa
Quoted 1 line · Al Viro

Still breaks xfs/259, same as the version in next-20260605...

I installed xfstests-dev and reproduced a "umount: /home/test: target is busy." problem which Al Viro is
experiencing with https://git.kernel.org/pub/scm/linux/kernel/git/next/linux-next.git/commit/?h=next-20260608&id=fb1d5846e99c8aa4ce8da7e6ee7643b01da25b8c .

(...snipped...)

Quoted 56 lines

I initially suspected that the cause of "target is busy" error is that fput() from __loop_clr_fd() does not wait for completion before "losetup -d" completes. But a debug printk() patch shown below indicated a tendency:

(a) __loop_clr_fd() is called by "udev-worker" rather than "losetup" when this problem happens

(b) propagate_mount_busy()!=0 when do_umount() fails with -EBUSY

--------------------------------------------------------------------------------

drivers/block/loop.c +4 -0
index c3b607a3ddc4..7408f314a1fa 100644
@@ -1763,6 +1763,8 @@ static void lo_release(struct gendisk *disk)
 	mutex_unlock(&lo->lo_mutex);
 
 	if (need_clear) {
+		printk("Flush: task=%s[%d] dev=loop%d state=%d\n",
+		       current->comm, current->pid, lo->lo_number, lo->lo_state);
 		/*
 		 * Temporarily release disk->open_mutex in order to flush pending I/O
 		 * requests before clearing the backing device.
@@ -1813,6 +1815,8 @@ static void lo_release(struct gendisk *disk)
 		mutex_lock(&lo->lo_disk->open_mutex);
 		if (WARN_ON(data_race(READ_ONCE(lo->lo_state)) != Lo_rundown))
 			return;
+		printk("Teardown: task=%s[%d] dev=loop%d state=%d\n",
+		       current->comm, current->pid, lo->lo_number, lo->lo_state);
 		__loop_clr_fd(lo);
 	}
 }
fs/namespace.c +5 -1
index 09ab7fc72f86..9710460fb449 100644
@@ -1893,6 +1893,8 @@ static int do_umount(struct mount *mnt, int flags)
 		 */
 		lock_mount_hash();
 		if (!list_empty(&mnt->mnt_mounts) || mnt_get_count(mnt) != 2) {
+			printk("%s: task=%s[%d] !list_empty(&mnt->mnt_mounts)=%d mnt_get_count(mnt)=%d\n", __func__,
+			       current->comm, current->pid, !list_empty(&mnt->mnt_mounts), mnt_get_count(mnt));
 			unlock_mount_hash();
 			return -EBUSY;
 		}
@@ -1960,6 +1962,9 @@ static int do_umount(struct mount *mnt, int flags)
 		if (!propagate_mount_busy(mnt, 2)) {
 			umount_tree(mnt, UMOUNT_PROPAGATE|UMOUNT_SYNC);
 			retval = 0;
+		} else {
+			printk("%s: task=%s[%d] propagate_mount_busy()!=0\n", __func__,
+			       current->comm, current->pid);
 		}
 	}
 out:
--------------------------------------------------------------------------------
maintainer
#43 lore raw

Re: [PATCH v4] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 3 lines · Tetsuo Handa

Sending this commit to linux.git will be the fastest way to identify who is issuing I/O requests too late. Therefore, I want to get a conclusion on xfs/259 breakage. Al, can you get the same result?

Not a peep in the logs, breakage still there (with cherry-picked fb1d5846e99c8aa4ce and CONFIG_KCOV enabled, that is).

#44 lore raw

Re: [PATCH v4] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 7 lines · Al Viro
Quoted 3 lines · Tetsuo Handa

Sending this commit to linux.git will be the fastest way to identify who is issuing I/O requests too late. Therefore, I want to get a conclusion on xfs/259 breakage. Al, can you get the same result?

Not a peep in the logs, breakage still there (with cherry-picked fb1d5846e99c8aa4ce and CONFIG_KCOV enabled, that is).

Please test with debug printk() patch shown below. What messages do you get?

--------------------------------------------------------------------------------

drivers/block/loop.c +4 -0
index c3b607a3ddc4..7408f314a1fa 100644
@@ -1763,6 +1763,8 @@ static void lo_release(struct gendisk *disk)
 	mutex_unlock(&lo->lo_mutex);
 
 	if (need_clear) {
+		printk("Flush: task=%s[%d] dev=loop%d state=%d\n",
+		       current->comm, current->pid, lo->lo_number, lo->lo_state);
 		/*
 		 * Temporarily release disk->open_mutex in order to flush pending I/O
 		 * requests before clearing the backing device.
@@ -1813,6 +1815,8 @@ static void lo_release(struct gendisk *disk)
 		mutex_lock(&lo->lo_disk->open_mutex);
 		if (WARN_ON(data_race(READ_ONCE(lo->lo_state)) != Lo_rundown))
 			return;
+		printk("Teardown: task=%s[%d] dev=loop%d state=%d\n",
+		       current->comm, current->pid, lo->lo_number, lo->lo_state);
 		__loop_clr_fd(lo);
 	}
 }
fs/namespace.c +5 -0
index 09ab7fc72f86..9710460fb449 100644
@@ -1893,6 +1893,8 @@ static int do_umount(struct mount *mnt, int flags)
 		 */
 		lock_mount_hash();
 		if (!list_empty(&mnt->mnt_mounts) || mnt_get_count(mnt) != 2) {
+			printk("%s: task=%s[%d] !list_empty(&mnt->mnt_mounts)=%d mnt_get_count(mnt)=%d\n", __func__,
+			       current->comm, current->pid, !list_empty(&mnt->mnt_mounts), mnt_get_count(mnt));
 			unlock_mount_hash();
 			return -EBUSY;
 		}
@@ -1960,6 +1962,9 @@ static int do_umount(struct mount *mnt, int flags)
 		if (!propagate_mount_busy(mnt, 2)) {
 			umount_tree(mnt, UMOUNT_PROPAGATE|UMOUNT_SYNC);
 			retval = 0;
+		} else {
+			printk("%s: task=%s[%d] propagate_mount_busy()!=0\n", __func__,
+			       current->comm, current->pid);
 		}
 	}
 out:

--------------------------------------------------------------------------------

#45 lore raw

Re: [PATCH v4] loop: Fix NULL pointer dereference in lo_rw_aio()

In reply to Al Viro
Quoted 19 lines · On Tue, 9 Jun 2026 18:50:13 +0100 Al Viro wrote:
Quoted 18 lines · Tetsuo Handa

syzbot is reporting NULL pointer dereference in lo_rw_aio() [1][2]. An analysis by the Gemini AI collaborator [3] considers that this problem is caused by a timing shift primarily exposed by commit 65565ca5f99b ("block: unify the synchronous bi_end_io callbacks"), along with helper refactorings like commit 92c3737a2473 ("block: add a bio_submit_or_kill helper").

But due to difficulty of reproducing this race, discussion about what is happening and how to fix this problem is stalling. Also, we haven't identified how many filesystems are subjected to this problem.

Therefore, this patch introduces a grace period for flushing pending I/O requests (which should be a good thing from the perspective of defensive programming) so that we won't hit NULL pointer dereference problem, and also emits BUG: message in order to help filesystem developers identify the caller of an I/O request that failed to wait for completion so that filesystem developers can fix such caller to wait for completion.

Quoted 5 lines
Quoted 2 lines

Note that emitting BUG: message is enabled only if CONFIG_KCOV=y, for this check is a waste of computation resources for almost all users.

Still breaks xfs/259, same as the version in next-20260605...

And syzbot report [1]

[1] https://lore.kernel.org/lkml/[email protected]/

#46 lore raw

Re: [PATCH v4] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 20 lines · Hillf Danton
Quoted 19 lines · On Tue, 9 Jun 2026 18:50:13 +0100 Al Viro wrote:
Quoted 18 lines · Tetsuo Handa

syzbot is reporting NULL pointer dereference in lo_rw_aio() [1][2]. An analysis by the Gemini AI collaborator [3] considers that this problem is caused by a timing shift primarily exposed by commit 65565ca5f99b ("block: unify the synchronous bi_end_io callbacks"), along with helper refactorings like commit 92c3737a2473 ("block: add a bio_submit_or_kill helper").

But due to difficulty of reproducing this race, discussion about what is happening and how to fix this problem is stalling. Also, we haven't identified how many filesystems are subjected to this problem.

Therefore, this patch introduces a grace period for flushing pending I/O requests (which should be a good thing from the perspective of defensive programming) so that we won't hit NULL pointer dereference problem, and also emits BUG: message in order to help filesystem developers identify the caller of an I/O request that failed to wait for completion so that filesystem developers can fix such caller to wait for completion.

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

Note that emitting BUG: message is enabled only if CONFIG_KCOV=y, for this check is a waste of computation resources for almost all users.

Still breaks xfs/259, same as the version in next-20260605...

And syzbot report [1]

[1] https://lore.kernel.org/lkml/[email protected]/

No. This report is from upstream tree where "loop: Fix NULL pointer dereference in lo_rw_aio()" is not yet applied.

[  102.784602][ T5324] loop0: detected capacity change from 0 to 2048
[  102.837593][ T5324] Alternate GPT is invalid, using primary GPT.
[  102.841605][ T5324]  loop0: p2 p3 p7
[  102.939203][ T5285] I/O error, dev loop0, sector 408 op 0x0:(READ) flags 0x80700 phys_seg 1 prio class 2
[  102.947057][ T5324] loop0: detected capacity change from 0 to 512
[  102.951560][ T5287] I/O error, dev loop0, sector 208 op 0x0:(READ) flags 0x80700 phys_seg 1 prio class 2
[  102.964277][ T5287] I/O error, dev loop0, sector 208 op 0x0:(READ) flags 0x0 phys_seg 1 prio class 2
[  102.969633][ T5285] I/O error, dev loop0, sector 408 op 0x0:(READ) flags 0x0 phys_seg 1 prio class 2
[  102.979918][ T5285] Buffer I/O error on dev loop0p7, logical block 8, async page read
[  102.984620][ T5287] Buffer I/O error on dev loop0p3, logical block 8, async page read
[  103.009916][ T5287] udevd[5287]: inotify_add_watch(7, /dev/loop0p3, 10) failed: No such file or directory
[  103.014532][  T176] ==================================================================
[  103.018401][  T176] BUG: KASAN: slab-use-after-free in update_io_ticks+0xa9/0x280
[  103.022211][  T176] Read of size 8 at addr ffff88803236b9a8 by task kworker/u4:6/176
[  103.025664][  T176] 
[  103.026746][  T176] CPU: 0 UID: 0 PID: 176 Comm: kworker/u4:6 Not tainted syzkaller #0 PREEMPT(full) 
[  103.026761][  T176] Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
[  103.026768][  T176] Workqueue: loop0 loop_rootcg_workfn

Al, can you reproduce your xfs/259 breakage and share kernel messages with
https://git.kernel.org/pub/scm/linux/kernel/git/next/linux-next.git/commit/?id=d908729e7467462bce1db3bc1bffec2e2d1f6c81 ?

I'm floating this patch in linux-next tree, but syzbot hasn't succeeded to hit "BUG: %s/%u is doing I/O request on loop%d in Lo_rundown state.\n" message.
I think we need to send to upstream tree so that syzbot can hit this message within a few days. To do so, we need to agree that your xfs/259 breakage should be addressed on the xfstests side.

#47 lore raw

Re: [PATCH v4] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 24 lines · On Mon, 13 Jul 2026 20:02:52 +0900 Tetsuo Handa wrote:
Quoted 23 lines · Hillf Danton
Quoted 22 lines · On Tue, 9 Jun 2026 18:50:13 +0100 Al Viro wrote:
Quoted 20 lines · Tetsuo Handa

syzbot is reporting NULL pointer dereference in lo_rw_aio() [1][2]. An analysis by the Gemini AI collaborator [3] considers that this problem is caused by a timing shift primarily exposed by commit 65565ca5f99b ("block: unify the synchronous bi_end_io callbacks"), along with helper refactorings like commit 92c3737a2473 ("block: add a bio_submit_or_kill helper").

But due to difficulty of reproducing this race, discussion about what is happening and how to fix this problem is stalling. Also, we haven't identified how many filesystems are subjected to this problem.

Therefore, this patch introduces a grace period for flushing pending I/O requests (which should be a good thing from the perspective of defensive programming) so that we won't hit NULL pointer dereference problem, and also emits BUG: message in order to help filesystem developers identify the caller of an I/O request that failed to wait for completion so that filesystem developers can fix such caller to wait for completion.

Note that emitting BUG: message is enabled only if CONFIG_KCOV=y, for this check is a waste of computation resources for almost all users.

Quoted 9 lines
Quoted 5 lines
Quoted 2 lines

Still breaks xfs/259, same as the version in next-20260605...

And syzbot report [1]

[1] https://lore.kernel.org/lkml/[email protected]/

No. This report is from upstream tree where "loop: Fix NULL pointer dereference in lo_rw_aio()" is not yet applied.

The issue remains but this work stalls.

author syzbot
#77 lore raw
This crash does not have a reproducer. I cannot test it.
Quoted 1 line

#syz test: [email protected]:bvanassche/linux.git block-for-next

This crash does not have a reproducer. I cannot test it.

#48 lore raw

PATCH v5 1/1 loop: Fix NULL pointer dereference in lo_rw_aio()

In reply to Hillf Danton

syzbot is reporting NULL pointer dereference in lo_rw_aio() [1][2]. An analysis by the Gemini AI collaborator [3] considers that this problem is caused by a timing shift primarily exposed by commit 65565ca5f99b ("block: unify the synchronous bi_end_io callbacks"), along with helper refactorings like commit 92c3737a2473 ("block: add a bio_submit_or_kill helper").

But due to difficulty of reproducing this race, discussion about what is happening and how to fix this problem is stalling. Also, we haven't identified how many filesystems are subjected to this problem.

Therefore, this patch introduces a grace period for flushing pending I/O requests (which should be a good thing from the perspective of defensive programming) so that we won't hit NULL pointer dereference problem, and also emits BUG: message in order to help filesystem developers identify the caller of an I/O request that failed to wait for completion so that filesystem developers can fix such caller to wait for completion.

Note that emitting BUG: message is enabled only if CONFIG_KCOV=y, for this check is a waste of computation resources for almost all users.

---
syzbot has tested this patch (with debug printk() added) using linux-next, and I confirmed that this patch does not cause new problems for syzbot.

I was expecting that Al Viro can reproduce xfs/259 problem with debug printk(), but I have to remove this patch (with debug printk() added) from linux-next because the debug printk() causes performance problem for unmount stress tests ( https://lkml.kernel.org/r/[email protected] ).

Anyway, like I have explained in
https://lkml.kernel.org/r/[email protected] , I think that the xfs/259 problem should be addressed by updating the "umount" user, for the "target is busy" problem can be reproduced with 7.0 and 7.1 kernels if delay injection is used.

Therefore, I think that we should proceed to the next step; i.e. identify who is issuing I/O requests too late and fix such users. But I had to stop testing this patch using linux-next before syzbot succeeds to find such users.

We can't use "#syz test" because this problem has no reproducers. Since I can no longer continue floating debug printk() for this problem, sending this patch to upstream will become the only way to identify who is issuing I/O requests too late.

drivers/block/loop.c | 83 ++++++++++++++++++++++++++++++++++++++++++--

 1 file changed, 81 insertions(+), 2 deletions(-)
drivers/block/loop.c +81 -2
index 310de0463beb..c3b607a3ddc4 100644
@@ -85,8 +85,27 @@ struct loop_cmd {
 	struct bio_vec *bvec;
 	struct cgroup_subsys_state *blkcg_css;
 	struct cgroup_subsys_state *memcg_css;
+#ifdef CONFIG_KCOV
+	unsigned long stack_entries[30];
+	int stack_nr;
+	pid_t pid;
+	char comm[TASK_COMM_LEN];
+#endif
 };
 
+static void loop_check_io_race(struct loop_device *lo, struct loop_cmd *cmd)
+{
+#ifdef CONFIG_KCOV
+	if (unlikely(data_race(READ_ONCE(lo->lo_state)) == Lo_rundown &&
+		     disk_openers(lo->lo_disk) == 0)) {
+		pr_err("BUG: %s/%u is doing I/O request on loop%d in Lo_rundown state.\n",
+		       cmd->comm, cmd->pid, lo->lo_number);
+		printk("Call Trace:\n");
+		stack_trace_print(cmd->stack_entries, cmd->stack_nr, 4);
+	}
+#endif
+}
+
 #define LOOP_IDLE_WORKER_TIMEOUT (60 * HZ)
 #define LOOP_DEFAULT_HW_Q_DEPTH 128
 
@@ -1743,8 +1762,59 @@ static void lo_release(struct gendisk *disk)
 	need_clear = (lo->lo_state == Lo_rundown);
 	mutex_unlock(&lo->lo_mutex);
 
-	if (need_clear)
+	if (need_clear) {
+		/*
+		 * Temporarily release disk->open_mutex in order to flush pending I/O
+		 * requests before clearing the backing device.
+		 *
+		 * This is a layering violation. But since bdev->bd_disk->fops->release()
+		 * (which is mapped to lo_release()) is the final function which
+		 * blkdev_put_whole() from bdev_release() calls immediately before
+		 * releasing disk->open_mutex, this changes nothing except opens a new
+		 * race window for allowing disk->fops->open() (which is mapped to
+		 * lo_open()) to be called.
+		 *
+		 * Even if lo_open() is called from blkdev_get_whole() due to this race,
+		 * the Lo_rundown state guarantees that lo_open() will fail with -ENXIO.
+		 * Thus, there will be effectively no change caused by this violation.
+		 */
+		mutex_unlock(&lo->lo_disk->open_mutex);
+		/*
+		 * Now that loop_queue_rq() sees lo->lo_state != Lo_bound,
+		 * wait for already started loop_queue_rq() to complete.
+		 */
+		synchronize_rcu();
+		/*
+		 * Now that no more works are scheduled by loop_queue_rq(),
+		 * wait for already scheduled works to complete.
+		 */
+		drain_workqueue(lo->workqueue);
+		/*
+		 * Now that no more AIO requests are scheduled by lo_rw_aio(),
+		 * wait for already started AIO to complete.
+		 *
+		 * Due to synchronize_rcu() + drain_workqueue() sequence above,
+		 * calling blk_mq_unfreeze_queue() immediately after blk_mq_freeze_queue()
+		 * returns has to be safe, for loop_queue_rq() no longer schedules new
+		 * lo_rw_aio() works and lo_rw_aio() no longer submits new AIO requests.
+		 *
+		 * Deferring blk_mq_unfreeze_queue() does not help because we are about
+		 * to clear the backing device and drop the refcount for the backing device.
+		 * There is nothing we can do if blk_mq_freeze_queue() fails to flush.
+		 */
+		blk_mq_unfreeze_queue(lo->lo_queue, blk_mq_freeze_queue(lo->lo_queue));
+		/*
+		 * Perform remaining cleanup, with disk->open_mutex held.
+		 *
+		 * The lo->lo_state should remain Lo_rundown despite we temporarily
+		 * released disk->open_mutex, for I am the only and the last user of
+		 * this loop device because lo_open() cannot succeed.
+		 */
+		mutex_lock(&lo->lo_disk->open_mutex);
+		if (WARN_ON(data_race(READ_ONCE(lo->lo_state)) != Lo_rundown))
+			return;
 		__loop_clr_fd(lo);
+	}
 }
 
 static void lo_free_disk(struct gendisk *disk)
@@ -1851,10 +1921,18 @@ static blk_status_t loop_queue_rq(struct blk_mq_hw_ctx *hctx,
 	struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
 	struct loop_device *lo = rq->q->queuedata;
 
+#ifdef CONFIG_KCOV
+	cmd->stack_nr = stack_trace_save(cmd->stack_entries, ARRAY_SIZE(cmd->stack_entries), 0);
+	cmd->pid = current->pid;
+	get_task_comm(cmd->comm, current);
+#endif
+
 	blk_mq_start_request(rq);
 
-	if (data_race(READ_ONCE(lo->lo_state)) != Lo_bound)
+	if (data_race(READ_ONCE(lo->lo_state)) != Lo_bound) {
+		loop_check_io_race(lo, cmd);
 		return BLK_STS_IOERR;
+	}
 
 	switch (req_op(rq)) {
 	case REQ_OP_FLUSH:
@@ -1897,6 +1975,7 @@ static void loop_handle_cmd(struct loop_cmd *cmd)
 	int ret = 0;
 	struct mem_cgroup *old_memcg = NULL;
 
+	loop_check_io_race(lo, cmd);
 	if (write && (lo->lo_flags & LO_FLAGS_READ_ONLY)) {
 		ret = -EIO;
 		goto failed;
Signature · 1 line
2.52.0
#49 lore raw

PATCH v6 1/1 loop: Fix NULL pointer dereference in lo_rw_aio()

syzbot is reporting NULL pointer dereference in lo_rw_aio() [1][2]. An analysis by the Gemini AI collaborator [3] considers that this problem is caused by a timing shift primarily exposed by commit 65565ca5f99b ("block: unify the synchronous bi_end_io callbacks"), along with helper refactorings like commit 92c3737a2473 ("block: add a bio_submit_or_kill helper").

But due to difficulty of reproducing this race, discussion about what is happening and how to fix this problem is stalling. Also, we haven't identified how many filesystems are subjected to this problem.

Therefore, this patch introduces a grace period for flushing pending I/O requests (which should be a good thing from the perspective of defensive programming) so that we won't hit NULL pointer dereference problem.

---
Changes in v6:
Drop debug code for emitting BUG: message, which is intended for helping filesystem developers identify the caller of an I/O request that failed to wait for completion.

 drivers/block/loop.c | 53 +++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 52 insertions(+), 1 deletion(-)
drivers/block/loop.c +52 -1
index 6f12976035b0..feebc9999926 100644
@@ -1769,8 +1769,59 @@ static void lo_release(struct gendisk *disk)
 	need_clear = (lo->lo_state == Lo_rundown);
 	mutex_unlock(&lo->lo_mutex);
 
-	if (need_clear)
+	if (need_clear) {
+		/*
+		 * Temporarily release disk->open_mutex in order to flush pending I/O
+		 * requests before clearing the backing device.
+		 *
+		 * This is a layering violation. But since bdev->bd_disk->fops->release()
+		 * (which is mapped to lo_release()) is the final function which
+		 * blkdev_put_whole() from bdev_release() calls immediately before
+		 * releasing disk->open_mutex, this changes nothing except opens a new
+		 * race window for allowing disk->fops->open() (which is mapped to
+		 * lo_open()) to be called.
+		 *
+		 * Even if lo_open() is called from blkdev_get_whole() due to this race,
+		 * the Lo_rundown state guarantees that lo_open() will fail with -ENXIO.
+		 * Thus, there will be effectively no change caused by this violation.
+		 */
+		mutex_unlock(&lo->lo_disk->open_mutex);
+		/*
+		 * Now that loop_queue_rq() sees lo->lo_state != Lo_bound,
+		 * wait for already started loop_queue_rq() to complete.
+		 */
+		synchronize_rcu();
+		/*
+		 * Now that no more works are scheduled by loop_queue_rq(),
+		 * wait for already scheduled works to complete.
+		 */
+		drain_workqueue(lo->workqueue);
+		/*
+		 * Now that no more AIO requests are scheduled by lo_rw_aio(),
+		 * wait for already started AIO to complete.
+		 *
+		 * Due to synchronize_rcu() + drain_workqueue() sequence above,
+		 * calling blk_mq_unfreeze_queue() immediately after blk_mq_freeze_queue()
+		 * returns has to be safe, for loop_queue_rq() no longer schedules new
+		 * lo_rw_aio() works and lo_rw_aio() no longer submits new AIO requests.
+		 *
+		 * Deferring blk_mq_unfreeze_queue() does not help because we are about
+		 * to clear the backing device and drop the refcount for the backing device.
+		 * There is nothing we can do if blk_mq_freeze_queue() fails to flush.
+		 */
+		blk_mq_unfreeze_queue(lo->lo_queue, blk_mq_freeze_queue(lo->lo_queue));
+		/*
+		 * Perform remaining cleanup, with disk->open_mutex held.
+		 *
+		 * The lo->lo_state should remain Lo_rundown despite we temporarily
+		 * released disk->open_mutex, for I am the only and the last user of
+		 * this loop device because lo_open() cannot succeed.
+		 */
+		mutex_lock(&lo->lo_disk->open_mutex);
+		if (WARN_ON(data_race(READ_ONCE(lo->lo_state)) != Lo_rundown))
+			return;
 		__loop_clr_fd(lo);
+	}
 }
 
 static void lo_free_disk(struct gendisk *disk)
Signature · 1 line
2.52.0
#51 lore raw

Re: [PATCH v6] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 5 lines · Markus Elfring

…

Quoted 1 line

Therefore, this patch introduces a grace period for …

See also once more:
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/Documentation/process/submitting-patches.rst?h=v7.2#n94

OK. I can do "s/this patch introduces/introduce/".

sashiko did not find problems with my patch
( https://sashiko.dev/#/patchset/8dedfc40-9cae-44ff-9960-e0eb1825e963%40I-love.SAKURA.ne.jp ).

Bart did not like my proposed solution and is making a series, but
sashiko found problems with Bart's series
( https://sashiko.dev/#/patchset/[email protected] and
https://sashiko.dev/#/patchset/[email protected] ). I still cannot catch why Bart's approach can become safe without synchronize_rcu() and drain_workqueue().

#52 lore raw

Re: [PATCH v6] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 4 lines · Tetsuo Handa

but sashiko found problems with Bart's series ( https://sashiko.dev/
#/patchset/[email protected] and https://sashiko.dev/#/patchset/2efb1032-34b9-4c31-
[email protected] ).

Thanks, I had not yet seen this feedback from Sashiko. My conclusion is that two of the three Sashiko findings are wrong. I will fix the third one - the finding about the potential wait-die deadlock.

Quoted 2 lines

I still cannot catch why Bart's approach can become safe without synchronize_rcu() and drain_workqueue().

Agreed that drain_workqueue() or flush_workqueue() is necessary. I do not agree that an explicit synchronize_rcu() call is required. Waiting until the request queue is frozen includes this call implicitly. See also __percpu_ref_switch_to_atomic().

Thanks,

Bart.

#53 lore raw

Re: [PATCH v6] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 8 lines · Bart Van Assche
Quoted 2 lines · Tetsuo Handa

I still cannot catch why Bart's approach can become safe without synchronize_rcu() and drain_workqueue().

Agreed that drain_workqueue() or flush_workqueue() is necessary. I do not agree that an explicit synchronize_rcu() call is required. Waiting until the request queue is frozen includes this call implicitly. See also __percpu_ref_switch_to_atomic().

A correction: it is not safe to call drain_workqueue() nor to freeze the request queue in __loop_clr_fd(). I'm considering to modify the comment in that function as follows:

drivers/block/loop.c +7 -2
@@ -1203,8 +1203,13 @@ static void __loop_clr_fd(struct loop_device *lo)
        /*
         * Reset the block size to the default.
         *
-        * No queue freezing needed because this is called from the final
-        * ->release call only, so there can't be any outstanding I/O.
+        * Asynchronously submitted I/O may still be in progress. Freezing the
+        * request queue is not possible without triggering lock inversion.
+        * Freezing a request queue must happen between the
+        * queue_limits_start_update() and queue_limits_commit_update calls.  If
+        * the request queue would be frozen between these two calls, a deadlock
+        * can be triggered with the loop_clear_limits() call from the I/O path
+        * since loop_clear_limits() also calls queue_limits_start_update().
         */
 

Thanks,

Bart.

#54 lore raw

Re: [PATCH v6] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 10 lines · Bart Van Assche
Quoted 4 lines · Tetsuo Handa

but sashiko found problems with Bart's series ( https://sashiko.dev/
#/patchset/[email protected] and https://sashiko.dev/#/patchset/2efb1032-34b9-4c31-
[email protected] ).

Thanks, I had not yet seen this feedback from Sashiko. My conclusion is that two of the three Sashiko findings are wrong. I will fix the third one - the finding about the potential wait-die deadlock.

As of commit fe4c990e6a30 ("loop: Add __guarded_by() annotations") in block-loop branch,

modprobe loop
losetup /dev/loop0 testfile.img; losetup /dev/loop1 /dev/loop0; losetup -D sleep 1
losetup /dev/loop1 testfile.img; losetup /dev/loop0 /dev/loop1; losetup -D

causes lockdep warning. This is a false positive, but we need to avoid it anyway.

Quoted 7 lines
Quoted 2 lines

I still cannot catch why Bart's approach can become safe without synchronize_rcu() and drain_workqueue().

Agreed that drain_workqueue() or flush_workqueue() is necessary. I do not agree that an explicit synchronize_rcu() call is required. Waiting until the request queue is frozen includes this call implicitly. See also __percpu_ref_switch_to_atomic().

OK. You recognized that we need drain_workqueue() or flush_workqueue(), and

Quoted 5 lines · Bart Van Assche
Quoted 4 lines · Bart Van Assche
Quoted 2 lines · Tetsuo Handa

I still cannot catch why Bart's approach can become safe without synchronize_rcu() and drain_workqueue().

Quoted 8 lines
Quoted 4 lines

Agreed that drain_workqueue() or flush_workqueue() is necessary. I do not agree that an explicit synchronize_rcu() call is required. Waiting until the request queue is frozen includes this call implicitly. See also __percpu_ref_switch_to_atomic().

A correction: it is not safe to call drain_workqueue() nor to freeze the request queue in __loop_clr_fd(). I'm considering to modify the comment in that function as follows:

you also recognized that we can't call drain_workqueue() or flush_workqueue().

Therefore, I chose to temporarily drop lo->lo_disk->open_mutex in order to make it possible to safely perform drain_workqueue().

#55 lore raw

Re: [PATCH v6] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 8 lines · Tetsuo Handa

As of commit fe4c990e6a30 ("loop: Add __guarded_by() annotations") in block-loop branch,

modprobe loop
losetup /dev/loop0 testfile.img; losetup /dev/loop1 /dev/loop0; losetup -D sleep 1
losetup /dev/loop1 testfile.img; losetup /dev/loop0 /dev/loop1; losetup -D

causes lockdep warning. This is a false positive, but we need to avoid it anyway.

Thanks for having shared the above reproducer. I have dropped the patches that protect all lo_backing_file dereferences with lo_mutex. It is too tricky to get this right and at the same time to keep lockdep
happy.

Quoted 4 lines

you also recognized that we can't call drain_workqueue() or flush_workqueue().

Therefore, I chose to temporarily drop lo->lo_disk->open_mutex in order to make it possible to safely perform drain_workqueue().

There is another possibility: set QUEUE_FLAG_DYING in __loop_clr_fd() before modifying queue limits and clear it again after modifying queue limits has finished. Feedback on the patch below is welcome.

Thanks,

Bart.

drivers/block/loop.c +25 -8
index df72350cad15..2fb9dc8ea47e 100644
@@ -1153,11 +1153,30 @@ static int loop_configure(struct loop_device *lo, blk_mode_t mode,
 
 static void __loop_clr_fd(struct loop_device *lo)
 {
+	struct request_queue *q = lo->lo_queue;
 	struct queue_limits lim;
+	unsigned int memflags;
 	struct file *filp;
 	gfp_t gfp = lo->old_gfp_mask;
 	int err;
 
+	/*
+	 * Prevent that new asynchronous I/O is submitted while queue limits
+	 * are being modified.
+	 */
+	blk_queue_flag_set(QUEUE_FLAG_DYING, q);
+
+	/* Wait until asynchronous I/O has finished. */
+	memflags = blk_mq_freeze_queue(q);
+	blk_mq_unfreeze_queue(q, memflags);
+
+	/* Wait until I/O dispatching has finished. */
+	blk_mq_quiesce_queue(q);
+	blk_mq_unquiesce_queue(q);
+
+	/* Wait until all I/O-related work has finished. */
+	flush_workqueue(lo->workqueue);
+
 	mutex_lock(&lo->lo_mutex);
 	filp = lo->lo_backing_file;
 	lo->lo_backing_file = NULL;
@@ -1168,17 +1187,12 @@ static void __loop_clr_fd(struct loop_device *lo)
 	lo->lo_sizelimit = 0;
 	memset(lo->lo_file_name, 0, LO_NAME_SIZE);
 
-	/*
-	 * Reset the block size to the default.
-	 *
-	 * No queue freezing needed because this is called from the final
-	 * ->release call only, so there can't be any outstanding I/O.
-	 */
-	lim = queue_limits_start_update(lo->lo_queue);
+	/* Reset the block size to the default. */
+	lim = queue_limits_start_update(q);
 	lim.logical_block_size = SECTOR_SIZE;
 	lim.physical_block_size = SECTOR_SIZE;
 	lim.io_min = SECTOR_SIZE;
-	queue_limits_commit_update(lo->lo_queue, &lim);
+	queue_limits_commit_update(q, &lim);
 
 	invalidate_disk(lo->lo_disk);
 	loop_sysfs_exit(lo);
@@ -1216,6 +1230,9 @@ static void __loop_clr_fd(struct loop_device *lo)
 	WRITE_ONCE(lo->lo_state, Lo_unbound);
 	mutex_unlock(&lo->lo_mutex);
 
+	/* Reallow I/O. */
+	blk_queue_flag_clear(QUEUE_FLAG_DYING, q);
+
 	fput(filp);
 }
 
#57 lore raw

Re: [PATCH v6] loop: Fix NULL pointer dereference in lo_rw_aio()

In reply to Tetsuo Handa
Quoted 9 lines · Tetsuo Handa
Quoted 3 lines · Bart Van Assche

A correction: it is not safe to call drain_workqueue() nor to freeze the request queue in __loop_clr_fd(). I'm considering to modify the comment in that function as follows:

you also recognized that we can't call drain_workqueue() or flush_workqueue().

Therefore, I chose to temporarily drop lo->lo_disk->open_mutex in order to make it possible to safely perform drain_workqueue().

My sentence was incomplete: I should have written that it is not safe to call drain_workqueue() nor flush_workqueue() from __loop_clr_fd() while the request queue is frozen. It is not clear to me how draining or flushing the workqueue from inside __loop_clr_fd() could cause trouble if this happens with the queue unfrozen since disk->open_mutex is not acquired by the memory reclaim code?

Thanks,

Bart.

#56 lore raw

Re: [PATCH v6] loop: Fix NULL pointer dereference in lo_rw_aio()

In reply to Bart Van Assche
Quoted 8 lines · Bart Van Assche
Quoted 4 lines

you also recognized that we can't call drain_workqueue() or flush_workqueue().

Therefore, I chose to temporarily drop lo->lo_disk->open_mutex in order to make it possible to safely perform drain_workqueue().

There is another possibility: set QUEUE_FLAG_DYING in __loop_clr_fd() before modifying queue limits and clear it again after modifying queue limits has finished. Feedback on the patch below is welcome.

See https://lkml.kernel.org/r/[email protected] .

drivers/block/loop.c static int loop_configure(struct loop_device *lo, blk_mode_t mode, · line 1178

Quoted 2 lines
drivers/block/loop.c +2 -0
+    /* Wait until all I/O-related work has finished. */
+    flush_workqueue(lo->workqueue);

I don't know about QUEUE_FLAG_DYING manipulation, but we know we can't call flush_workqueue() while holding open_mutex.

Please post as a standalone patch (subject starting with "[PATCH" than "Re: [PATCH") that can be applied on current linux.git tree, so that sashiko can review your patch.

#58 lore raw

Re: [PATCH v6] loop: Fix NULL pointer dereference in lo_rw_aio()

In reply to Bart Van Assche
Quoted 11 lines · Bart Van Assche
Quoted 9 lines · Tetsuo Handa
Quoted 3 lines · Bart Van Assche

A correction: it is not safe to call drain_workqueue() nor to freeze the request queue in __loop_clr_fd(). I'm considering to modify the comment in that function as follows:

you also recognized that we can't call drain_workqueue() or flush_workqueue().

Therefore, I chose to temporarily drop lo->lo_disk->open_mutex in order to make it possible to safely perform drain_workqueue().

Quoted 6 lines

My sentence was incomplete: I should have written that it is not safe to call drain_workqueue() nor flush_workqueue() from __loop_clr_fd() while the request queue is frozen. It is not clear to me how draining or flushing the workqueue from inside __loop_clr_fd() could cause trouble if this happens with the queue unfrozen since disk->open_mutex is not acquired by the memory reclaim code?

I don't know how "since disk->open_mutex is not acquired by the memory reclaim code" is relevant...

Current situation is a result of what we had considered 4 years ago; we don't need to destroy workqueue (note that destroy_workqueue() implies drain_workqueue()) from __loop_clr_fd() ( https://lkml.kernel.org/r/[email protected] ).

Since there is a

  Chain exists of:
    (wq_completion)loop0 --> system_transition_mutex/1 --> &disk->open_mutex
  
   Possible unsafe locking scenario:
         CPU0                    CPU1
         ----                    ----
    lock(&disk->open_mutex);
                                 lock(system_transition_mutex/1);
                                 lock(&disk->open_mutex);
    lock((wq_completion)loop0);

dependency, but my proposal to forbid binding loop device to pseudo files ( https://lkml.kernel.org/r/[email protected] ) was rejected by Christoph, we are stuck in a

Draining workqueue with open_mutex held causes creating a complex lock dependency chain involving the global system_transition_mutex. (Maybe there are other paths that create similar dependency chain if we drain workqueue with open_mutex held.)

versus

Not draining workqueue causes NULL pointer dereference in lo_rw_aio().

collision. Therefore,

Draining workqueue *without open_mutex held* can avoid creating a complex lock dependency chain involving the global system_transition_mutex and can also avoid NULL pointer dereference in lo_rw_aio().

is my solution.

Can you agree with my solution?

#59 lore raw

Re: [PATCH v6] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 11 lines · Tetsuo Handa

Current situation is a result of what we had considered 4 years ago; we don't need to destroy workqueue (note that destroy_workqueue() implies drain_workqueue()) from __loop_clr_fd() ( https://lkml.kernel.org/r/[email protected] ).

Since there is a

   Chain exists of:
     (wq_completion)loop0 --> system_transition_mutex/1 --> &disk->open_mutex
   
    Possible unsafe locking scenario:
Quoted 6 lines
          CPU0                    CPU1
          ----                    ----
     lock(&disk->open_mutex);
                                  lock(system_transition_mutex/1);
                                  lock(&disk->open_mutex);
     lock((wq_completion)loop0);

This ABBA locking scenario can only be triggered if a loop device is bound to a sysfs attribute with read or write methods that lock system_transition_mutex, e.g. /sys/kernel/power, isn't it?

Quoted 12 lines

dependency, but my proposal to forbid binding loop device to pseudo files ( https://lkml.kernel.org/r/[email protected] ) was rejected by Christoph, we are stuck in a

Draining workqueue with open_mutex held causes creating a complex lock dependency chain involving the global system_transition_mutex. (Maybe there are other paths that create similar dependency chain if we drain workqueue with open_mutex held.)

versus

Not draining workqueue causes NULL pointer dereference in lo_rw_aio().

Quoted 7 lines

collision. Therefore,

Draining workqueue *without open_mutex held* can avoid creating a complex lock dependency chain involving the global system_transition_mutex and can also avoid NULL pointer dereference in lo_rw_aio().

is my solution.

Releasing and reacquiring disk->open_mutex from __loop_clr_fd() seems risky to me. There is plenty of code in block/bdev.c that assumes that disk->open_mutex is not released by lo_release().

I think there is another solution: instead of draining the workqueue from inside __loop_clr_fd(), postpone it until the next time the loop device is bound. See also the patch below.

Regarding your earlier request for a Sashiko review: I will look into configuring Sashiko such that I can run "sashiko review ${commit_id}" locally. The only part I'm missing right now is a Sashiko API key.

Thanks,

Bart.

loop: Serialize I/O and queue limits updates

drivers/block/loop.c +28 -8
index 119758b45e47..1406932fae93 100644
@@ -1086,6 +1086,12 @@ static int loop_configure(struct loop_device *lo, blk_mode_t mode,
 			error = -ENOMEM;
 			goto out_unlock;
 		}
+	} else {
+		/*
+		 * Wait until all work related to a previously bound file has
+		 * finished.
+		 */
+		flush_workqueue(lo->workqueue);
 	}
 
 	/* suppress uevents while reconfiguring the device */
@@ -1154,11 +1160,27 @@ static int loop_configure(struct loop_device *lo, blk_mode_t mode,
 static void __loop_clr_fd(struct gendisk *disk, struct loop_device *lo)
 	__must_hold(&disk->open_mutex)
 {
+	struct request_queue *q = lo->lo_queue;
 	struct queue_limits lim;
+	unsigned int memflags;
 	struct file *filp;
 	gfp_t gfp = lo->old_gfp_mask;
 	int err;
 
+	/*
+	 * Prevent that new asynchronous I/O is submitted while queue limits
+	 * are being modified.
+	 */
+	blk_queue_flag_set(QUEUE_FLAG_DYING, q);
+
+	/* Wait until asynchronous I/O has finished. */
+	memflags = blk_mq_freeze_queue(q);
+	blk_mq_unfreeze_queue(q, memflags);
+
+	/* Wait until I/O dispatching has finished. */
+	blk_mq_quiesce_queue(q);
+	blk_mq_unquiesce_queue(q);
+
 	mutex_lock(&lo->lo_mutex);
 	filp = lo->lo_backing_file;
 	lo->lo_backing_file = NULL;
@@ -1169,17 +1191,12 @@ static void __loop_clr_fd(struct gendisk *disk, struct loop_device *lo)
 	lo->lo_sizelimit = 0;
 	memset(lo->lo_file_name, 0, LO_NAME_SIZE);
 
-	/*
-	 * Reset the block size to the default.
-	 *
-	 * No queue freezing needed because this is called from the final
-	 * ->release call only, so there can't be any outstanding I/O.
-	 */
-	lim = queue_limits_start_update(lo->lo_queue);
+	/* Reset the block size to the default. */
+	lim = queue_limits_start_update(q);
 	lim.logical_block_size = SECTOR_SIZE;
 	lim.physical_block_size = SECTOR_SIZE;
 	lim.io_min = SECTOR_SIZE;
-	queue_limits_commit_update(lo->lo_queue, &lim);
+	queue_limits_commit_update(q, &lim);
 
 	invalidate_disk(disk);
 	loop_sysfs_exit(lo);
@@ -1217,6 +1234,9 @@ static void __loop_clr_fd(struct gendisk *disk, struct loop_device *lo)
 	WRITE_ONCE(lo->lo_state, Lo_unbound);
 	mutex_unlock(&lo->lo_mutex);
 
+	/* Reallow I/O. */
+	blk_queue_flag_clear(QUEUE_FLAG_DYING, q);
+
 	fput(filp);
 }
 
#60 lore raw

Re: [PATCH v6] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 3 lines · Bart Van Assche

Releasing and reacquiring disk->open_mutex from __loop_clr_fd() seems risky to me. There is plenty of code in block/bdev.c that assumes that disk->open_mutex is not released by lo_release().

sashiko's review did not find problems
( https://sashiko.dev/#/patchset/8dedfc40-9cae-44ff-9960-e0eb1825e963%40I-love.SAKURA.ne.jp ). This callback is the last code which is performed immediately before releasing disk->open_mutex.

Quoted 4 lines

I think there is another solution: instead of draining the workqueue from inside __loop_clr_fd(), postpone it until the next time the loop device is bound. See also the patch below.

That is too late to avoid NULL pointer dereference problem. We need to flush before setting lo->lo_backing_file to NULL.

Quoted 4 lines

Regarding your earlier request for a Sashiko review: I will look into configuring Sashiko such that I can run "sashiko review ${commit_id}" locally. The only part I'm missing right now is a Sashiko API key.

While Sashiko considers a static blk_mq_freeze_queue() sufficient to avoid the NULL pointer dereference, relying on freezing the queue inside __loop_clr_fd() while holding disk->open_mutex is a dangerous decision.

It is true that blk_mq_freeze_queue() alone is equivalent to synchronize_rcu() + drain_workqueue() + blk_mq_freeze_queue().

Although omitting drain_workqueue() causes lockdep to stop complaining, not using drain_workqueue() does not avoid the runtime deadlock situation shown below. As long as there is a possibility of an in-flight I/O holding or waiting on a lock that subsequently tries to acquire disk->open_mutex, the deadlock risk remains. Lockdep will remain silent here simply because it cannot inspect the wake-up conditions inside wait_event() during a queue freeze.

Here is the exact execution timeline that leads to the silent deadlock:

Thread 1: Thread 2: Thread 3:
========================================================================================
Holds a global lock (e.g., system_transition_mutex).

Block core increments q_usage_counter.

Block core holds disk->open_mutex.

lo_release() tries to wait for
q_usage_counter to reach 0
via blk_mq_freeze_queue()
=> BLOCKED by Thread 2.
loop_handle_cmd() tries
to hold the global lock
=> BLOCKED by Thread 3.
Tries to hold disk->open_mutex
=> BLOCKED by Thread 1.
========================================================================================

Since Thread 1 will never release disk->open_mutex, Thread 3 can never release the global lock, and Thread 2 can never reach blk_mq_end_request() to unblock Thread 1.

I've tried offloading __loop_clr_fd() entirely to task_work context in v3 patch, but it did not work due to module lifecycle restrictions
( https://sashiko.dev/#/patchset/[email protected] ).

Therefore, I consider that temporarily releasing disk->open_mutex within the process context to safely perform flushing/draining before clearing the backing file pointer is the most robust architectural solution to break this deadlock chain.

#61 lore raw

Re: [PATCH v6] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 41 lines · Tetsuo Handa

While Sashiko considers a static blk_mq_freeze_queue() sufficient to avoid the NULL pointer dereference, relying on freezing the queue inside __loop_clr_fd() while holding disk->open_mutex is a dangerous decision.

It is true that blk_mq_freeze_queue() alone is equivalent to synchronize_rcu() + drain_workqueue() + blk_mq_freeze_queue().

Although omitting drain_workqueue() causes lockdep to stop complaining, not using drain_workqueue() does not avoid the runtime deadlock situation shown below. As long as there is a possibility of an in-flight I/O holding or waiting on a lock that subsequently tries to acquire disk->open_mutex, the deadlock risk remains. Lockdep will remain silent here simply because it cannot inspect the wake-up conditions inside wait_event() during a queue freeze.

Here is the exact execution timeline that leads to the silent deadlock:

Thread 1: Thread 2: Thread 3:
========================================================================================
Holds a global lock (e.g., system_transition_mutex).

Block core increments q_usage_counter.

Block core holds disk->open_mutex.

lo_release() tries to wait for
q_usage_counter to reach 0
via blk_mq_freeze_queue()
=> BLOCKED by Thread 2.
loop_handle_cmd() tries
to hold the global lock
=> BLOCKED by Thread 3.
Tries to hold disk->open_mutex
=> BLOCKED by Thread 1.
========================================================================================

Since Thread 1 will never release disk->open_mutex, Thread 3 can never release the global lock, and Thread 2 can never reach blk_mq_end_request() to unblock Thread 1.

Quoted 7 lines

I've tried offloading __loop_clr_fd() entirely to task_work context in v3 patch, but it did not work due to module lifecycle restrictions
( https://sashiko.dev/#/patchset/[email protected] ).

Therefore, I consider that temporarily releasing disk->open_mutex within the process context to safely perform flushing/draining before clearing the backing file pointer is the most robust architectural solution to break this deadlock chain.

I'm going to drop patch "loop: Serialize I/O and queue limits updates" from my patch series and leave it to someone else to solve this issue since none of the proposed fixes that have been discussed so far make me enthusiast.

Thanks,

Bart.

#75 lore raw

PATCH 1/1 loop: Fix NULL pointer dereference in lo_rw_aio()

In reply to Tetsuo Handa

syzbot is reporting NULL pointer dereference in lo_rw_aio() [1][2]. An analysis by the Gemini AI collaborator [3] considers that this problem is caused by a timing shift primarily exposed by commit 65565ca5f99b ("block: unify the synchronous bi_end_io callbacks"), along with helper refactorings like commit 92c3737a2473 ("block: add a bio_submit_or_kill helper").

But due to difficulty of reproducing this race, discussion about what is happening and how to fix this problem is stalling. Also, we haven't identified how many filesystems are subjected to this problem.

Therefore, introduce a grace period for flushing pending I/O requests (which should be a good thing from the perspective of defensive programming) so that we won't hit NULL pointer dereference problem.

However, calling drain_workqueue() from __loop_clr_fd() with disk->open_mutex held causes lockdep warnings. We need to flush pending I/O requests without disk->open_mutex held. Therefore, defer __loop_clr_fd() to WQ context, like commit 322c4293ecc5 ("loop: make autoclear operation asynchronous") did.

The past attempt was reverted by commit bf23747ee053 ("loop: revert "make autoclear operation asynchronous"") for two reasons:

(1) Userspace might be expecting that fput() on the backing file is processed before lo_release() from close() returns to user mode. But a debug patch [4] suggested me that this teardown operation is racy regardless of whether disk->open_mutex is temporarily released or not, and therefore the xfs/259 breakage should be addressed on the xfstests side.

(2) Lockdep reported circular locking dependency caused by flushing system-wide WQs. But we no longer need to worry that dependency because all in-tree users no longer flush system-wide WQs.

Therefore, let's retry deferring __loop_clr_fd() to WQ context again.

---
 drivers/block/loop.c | 74 +++++++++++++++++++++++++++++++++++---------
 1 file changed, 59 insertions(+), 15 deletions(-)
drivers/block/loop.c +59 -15
index 6f12976035b0..e2703f0ee75d 100644
@@ -75,6 +75,7 @@ struct loop_device {
 	struct gendisk		*lo_disk;
 	struct mutex		lo_mutex;
 	bool			idr_visible;
+	struct work_struct	lo_clr_work;
 };
 
 struct loop_cmd {
@@ -1134,13 +1135,35 @@ static int loop_configure(struct loop_device *lo, blk_mode_t mode,
 	return error;
 }
 
-static void __loop_clr_fd(struct loop_device *lo)
+static void __loop_clr_fd(struct work_struct *work)
 {
+	struct loop_device *lo = container_of(work, struct loop_device, lo_clr_work);
+	struct gendisk *disk = lo->lo_disk;
 	struct queue_limits lim;
 	struct file *filp;
 	gfp_t gfp = lo->old_gfp_mask;
 	int err;
 
+	/* Step 1: Flush all outstanding I/O, without open_mutex held. */
+	/*
+	 * Now that loop_queue_rq() sees lo->lo_state != Lo_bound,
+	 * wait for already started loop_queue_rq() to complete.
+	 */
+	synchronize_rcu();
+	/*
+	 * Now that no more works are scheduled by loop_queue_rq(),
+	 * wait for already scheduled works to complete.
+	 */
+	drain_workqueue(lo->workqueue);
+	/*
+	 * Now that no more AIO requests are scheduled by lo_rw_aio(),
+	 * wait for already started AIO to complete.
+	 */
+	blk_mq_unfreeze_queue(lo->lo_queue, blk_mq_freeze_queue(lo->lo_queue));
+
+	/* Step 2: Perform remaining cleanup, with open_mutex held. */
+	mutex_lock(&disk->open_mutex);
+
 	spin_lock_irq(&lo->lo_lock);
 	filp = lo->lo_backing_file;
 	lo->lo_backing_file = NULL;
@@ -1151,12 +1174,7 @@ static void __loop_clr_fd(struct loop_device *lo)
 	lo->lo_sizelimit = 0;
 	memset(lo->lo_file_name, 0, LO_NAME_SIZE);
 
-	/*
-	 * Reset the block size to the default.
-	 *
-	 * No queue freezing needed because this is called from the final
-	 * ->release call only, so there can't be any outstanding I/O.
-	 */
+	/* Reset the block size to the default. */
 	lim = queue_limits_start_update(lo->lo_queue);
 	lim.logical_block_size = SECTOR_SIZE;
 	lim.physical_block_size = SECTOR_SIZE;
@@ -1168,8 +1186,6 @@ static void __loop_clr_fd(struct loop_device *lo)
 	/* let user-space know about this change */
 	kobject_uevent(&disk_to_dev(lo->lo_disk)->kobj, KOBJ_CHANGE);
 	mapping_set_gfp_mask(filp->f_mapping, gfp);
-	/* This is safe: open() is still holding a reference. */
-	module_put(THIS_MODULE);
 
 	disk_force_media_change(lo->lo_disk);
 
@@ -1199,12 +1215,24 @@ static void __loop_clr_fd(struct loop_device *lo)
 	WRITE_ONCE(lo->lo_state, Lo_unbound);
 	mutex_unlock(&lo->lo_mutex);
 
+	/* Step 3: Drop refcounts, without open_mutex held. */
+	mutex_unlock(&disk->open_mutex);
+
+	fput(filp);
+
 	/*
-	 * Need not hold lo_mutex to fput backing file. Calling fput holding
-	 * lo_mutex triggers a circular lock dependency possibility warning as
-	 * fput can take open_mutex which is usually taken before lo_mutex.
+	 * Drop all references that would have been dropped as soon as
+	 * returning from lo_release() and releasing disk->open_mutex.
 	 */
-	fput(filp);
+	module_put(disk->fops->owner);
+	put_device(disk_to_dev(disk));
+
+	/*
+	 * This is safe: flush_work() from loop_remove() from loop_exit() waits
+	 * until this function returns; effectively dropping the final module
+	 * references synchronously.
+	 */
+	module_put(THIS_MODULE);
 }
 
 static int loop_clr_fd(struct loop_device *lo)
@@ -1769,8 +1797,20 @@ static void lo_release(struct gendisk *disk)
 	need_clear = (lo->lo_state == Lo_rundown);
 	mutex_unlock(&lo->lo_mutex);
 
-	if (need_clear)
-		__loop_clr_fd(lo);
+	/*
+	 * In order to flush pending I/O requests before clearing the backing
+	 * device, defer __loop_clr_fd() to WQ context. The Lo_rundown state
+	 * guarantees that lo_open() will fail with -ENXIO.
+	 */
+	if (need_clear) {
+		/*
+		 * Grab all references that will be dropped as soon as
+		 * returning from lo_release() and releasing disk->open_mutex.
+		 */
+		get_device(disk_to_dev(disk));
+		__module_get(disk->fops->owner);
+		queue_work(system_long_wq, &lo->lo_clr_work);
+	}
 }
 
 static void lo_free_disk(struct gendisk *disk)
@@ -2034,6 +2074,7 @@ static int loop_add(int i)
 	lo = kzalloc_obj(*lo);
 	if (!lo)
 		goto out;
+	INIT_WORK(&lo->lo_clr_work, __loop_clr_fd);
 	lo->worker_tree = RB_ROOT;
 	INIT_LIST_HEAD(&lo->idle_worker_list);
 	timer_setup(&lo->timer, loop_free_idle_workers_timer, TIMER_DEFERRABLE);
@@ -2138,6 +2179,9 @@ static int loop_add(int i)
 
 static void loop_remove(struct loop_device *lo)
 {
+	/* Wait for __loop_clr_fd() to complete. */
+	flush_work(&lo->lo_clr_work);
+
 	/* Make this loop device unreachable from pathname. */
 	del_gendisk(lo->lo_disk);
 	blk_mq_free_tag_set(&lo->tag_set);
Signature · 1 line
2.55.0
#62 lore raw

PATCH v7 1/1 loop: Fix NULL pointer dereference in lo_rw_aio()

In reply to Bart Van Assche

syzbot is reporting NULL pointer dereference in lo_rw_aio() [1][2]. An analysis by the Gemini AI collaborator [3] considers that this problem is caused by a timing shift primarily exposed by commit 65565ca5f99b ("block: unify the synchronous bi_end_io callbacks"), along with helper refactorings like commit 92c3737a2473 ("block: add a bio_submit_or_kill helper").

But due to difficulty of reproducing this race, discussion about what is happening and how to fix this problem is stalling. Also, we haven't identified how many filesystems are subjected to this problem.

Therefore, introduce a grace period for flushing pending I/O requests (which should be a good thing from the perspective of defensive programming) so that we won't hit NULL pointer dereference problem.

However, calling drain_workqueue() from __loop_clr_fd() with disk->open_mutex held causes lockdep warnings. We need to flush pending I/O requests without disk->open_mutex held. Therefore, defer __loop_clr_fd() to WQ context, like commit 322c4293ecc5 ("loop: make autoclear operation asynchronous") did.

The past attempt was reverted by commit bf23747ee053 ("loop: revert "make autoclear operation asynchronous"") for two reasons:

(1) Userspace might be expecting that fput() on the backing file is processed before lo_release() from close() returns to user mode. But a debug patch [4] suggested me that this teardown operation is racy regardless of whether disk->open_mutex is temporarily released or not, and therefore the xfs/259 breakage should be addressed on the xfstests side.

(2) Lockdep reported circular locking dependency caused by flushing system-wide WQs. But we no longer need to worry that dependency because all in-tree users no longer flush system-wide WQs.

Therefore, let's retry deferring __loop_clr_fd() to WQ context again.

---
Sashiko reviewed this patch, and did not find problems
( https://sashiko.dev/#/patchset/5803da44-97c7-440e-a06b-d3cf4afff3c8%40I-love.SAKURA.ne.jp ). Can we try this approach?

 drivers/block/loop.c | 74 +++++++++++++++++++++++++++++++++++---------
 1 file changed, 59 insertions(+), 15 deletions(-)
drivers/block/loop.c +59 -15
index 6f12976035b0..e2703f0ee75d 100644
@@ -75,6 +75,7 @@ struct loop_device {
 	struct gendisk		*lo_disk;
 	struct mutex		lo_mutex;
 	bool			idr_visible;
+	struct work_struct	lo_clr_work;
 };
 
 struct loop_cmd {
@@ -1134,13 +1135,35 @@ static int loop_configure(struct loop_device *lo, blk_mode_t mode,
 	return error;
 }
 
-static void __loop_clr_fd(struct loop_device *lo)
+static void __loop_clr_fd(struct work_struct *work)
 {
+	struct loop_device *lo = container_of(work, struct loop_device, lo_clr_work);
+	struct gendisk *disk = lo->lo_disk;
 	struct queue_limits lim;
 	struct file *filp;
 	gfp_t gfp = lo->old_gfp_mask;
 	int err;
 
+	/* Step 1: Flush all outstanding I/O, without open_mutex held. */
+	/*
+	 * Now that loop_queue_rq() sees lo->lo_state != Lo_bound,
+	 * wait for already started loop_queue_rq() to complete.
+	 */
+	synchronize_rcu();
+	/*
+	 * Now that no more works are scheduled by loop_queue_rq(),
+	 * wait for already scheduled works to complete.
+	 */
+	drain_workqueue(lo->workqueue);
+	/*
+	 * Now that no more AIO requests are scheduled by lo_rw_aio(),
+	 * wait for already started AIO to complete.
+	 */
+	blk_mq_unfreeze_queue(lo->lo_queue, blk_mq_freeze_queue(lo->lo_queue));
+
+	/* Step 2: Perform remaining cleanup, with open_mutex held. */
+	mutex_lock(&disk->open_mutex);
+
 	spin_lock_irq(&lo->lo_lock);
 	filp = lo->lo_backing_file;
 	lo->lo_backing_file = NULL;
@@ -1151,12 +1174,7 @@ static void __loop_clr_fd(struct loop_device *lo)
 	lo->lo_sizelimit = 0;
 	memset(lo->lo_file_name, 0, LO_NAME_SIZE);
 
-	/*
-	 * Reset the block size to the default.
-	 *
-	 * No queue freezing needed because this is called from the final
-	 * ->release call only, so there can't be any outstanding I/O.
-	 */
+	/* Reset the block size to the default. */
 	lim = queue_limits_start_update(lo->lo_queue);
 	lim.logical_block_size = SECTOR_SIZE;
 	lim.physical_block_size = SECTOR_SIZE;
@@ -1168,8 +1186,6 @@ static void __loop_clr_fd(struct loop_device *lo)
 	/* let user-space know about this change */
 	kobject_uevent(&disk_to_dev(lo->lo_disk)->kobj, KOBJ_CHANGE);
 	mapping_set_gfp_mask(filp->f_mapping, gfp);
-	/* This is safe: open() is still holding a reference. */
-	module_put(THIS_MODULE);
 
 	disk_force_media_change(lo->lo_disk);
 
@@ -1199,12 +1215,24 @@ static void __loop_clr_fd(struct loop_device *lo)
 	WRITE_ONCE(lo->lo_state, Lo_unbound);
 	mutex_unlock(&lo->lo_mutex);
 
+	/* Step 3: Drop refcounts, without open_mutex held. */
+	mutex_unlock(&disk->open_mutex);
+
+	fput(filp);
+
 	/*
-	 * Need not hold lo_mutex to fput backing file. Calling fput holding
-	 * lo_mutex triggers a circular lock dependency possibility warning as
-	 * fput can take open_mutex which is usually taken before lo_mutex.
+	 * Drop all references that would have been dropped as soon as
+	 * returning from lo_release() and releasing disk->open_mutex.
 	 */
-	fput(filp);
+	module_put(disk->fops->owner);
+	put_device(disk_to_dev(disk));
+
+	/*
+	 * This is safe: flush_work() from loop_remove() from loop_exit() waits
+	 * until this function returns; effectively dropping the final module
+	 * references synchronously.
+	 */
+	module_put(THIS_MODULE);
 }
 
 static int loop_clr_fd(struct loop_device *lo)
@@ -1769,8 +1797,20 @@ static void lo_release(struct gendisk *disk)
 	need_clear = (lo->lo_state == Lo_rundown);
 	mutex_unlock(&lo->lo_mutex);
 
-	if (need_clear)
-		__loop_clr_fd(lo);
+	/*
+	 * In order to flush pending I/O requests before clearing the backing
+	 * device, defer __loop_clr_fd() to WQ context. The Lo_rundown state
+	 * guarantees that lo_open() will fail with -ENXIO.
+	 */
+	if (need_clear) {
+		/*
+		 * Grab all references that will be dropped as soon as
+		 * returning from lo_release() and releasing disk->open_mutex.
+		 */
+		get_device(disk_to_dev(disk));
+		__module_get(disk->fops->owner);
+		queue_work(system_long_wq, &lo->lo_clr_work);
+	}
 }
 
 static void lo_free_disk(struct gendisk *disk)
@@ -2034,6 +2074,7 @@ static int loop_add(int i)
 	lo = kzalloc_obj(*lo);
 	if (!lo)
 		goto out;
+	INIT_WORK(&lo->lo_clr_work, __loop_clr_fd);
 	lo->worker_tree = RB_ROOT;
 	INIT_LIST_HEAD(&lo->idle_worker_list);
 	timer_setup(&lo->timer, loop_free_idle_workers_timer, TIMER_DEFERRABLE);
@@ -2138,6 +2179,9 @@ static int loop_add(int i)
 
 static void loop_remove(struct loop_device *lo)
 {
+	/* Wait for __loop_clr_fd() to complete. */
+	flush_work(&lo->lo_clr_work);
+
 	/* Make this loop device unreachable from pathname. */
 	del_gendisk(lo->lo_disk);
 	blk_mq_free_tag_set(&lo->tag_set);
Signature · 1 line
2.55.0
#63 lore raw

Re: [PATCH v7] loop: Fix NULL pointer dereference in lo_rw_aio()

drivers/block/loop.c static int loop_configure(struct loop_device *lo, blk_mode_t mode, · line 1152

Quoted 3 lines · Tetsuo Handa
drivers/block/loop.c +3 -0
+	 * wait for already started loop_queue_rq() to complete.
+	 */
+	synchronize_rcu();

Calling synchronize_rcu() to wait for ongoing loop_queue_rq() calls to complete won't work if anyone would set BLK_MQ_F_BLOCKING for the request queues created by the loop driver. Please use the block-layer APIs instead of open-coding these. I'm referring to blk_mq_quiesce_queue() and blk_mq_wait_quiesce_done().

Freezing the request queue must happen before waiting for ongoing loop_queue_rq() calls to finish.

Calling synchronize_rcu() does not prevent new I/O to be submitted. What prevents io_uring to submit more I/O asynchronously, e.g. if a file descriptor that refers to a loop device instance has been registered in the fixed-file table?

drivers/block/loop.c static int loop_configure(struct loop_device *lo, blk_mode_t mode, · line 1162

Quoted 10 lines
drivers/block/loop.c +10 -0
+	/*
+	 * Now that no more works are scheduled by loop_queue_rq(),
+	 * wait for already scheduled works to complete.
+	 */
+	drain_workqueue(lo->workqueue);
+	/*
+	 * Now that no more AIO requests are scheduled by lo_rw_aio(),
+	 * wait for already started AIO to complete.
+	 */
+	blk_mq_unfreeze_queue(lo->lo_queue, blk_mq_freeze_queue(lo->lo_queue));

Freezing the request queue must happen before lo->workqueue is drained.

drivers/block/loop.c static int loop_configure(struct loop_device *lo, blk_mode_t mode, · line 1165

Quoted 2 lines
drivers/block/loop.c +2 -0
+	/* Step 2: Perform remaining cleanup, with open_mutex held. */
+	mutex_lock(&disk->open_mutex);

After having obtained disk->open_mutex, lease add something like the
following: WARN_ON_ONCE(lo->lo_state == Lo_bound). Even if this condition can't be triggered today, this may help with detecting bugs in future loop driver changes.

drivers/block/loop.c static void __loop_clr_fd(struct loop_device *lo) · line 1190

Quoted 8 lines
drivers/block/loop.c +0 -2
@@ -1168,8 +1186,6 @@ static void __loop_clr_fd(struct loop_device *lo)
  	/* let user-space know about this change */
  	kobject_uevent(&disk_to_dev(lo->lo_disk)->kobj, KOBJ_CHANGE);
  	mapping_set_gfp_mask(filp->f_mapping, gfp);
-	/* This is safe: open() is still holding a reference. */
-	module_put(THIS_MODULE);
 
  	disk_force_media_change(lo->lo_disk); 

I don't think that it's acceptable to invoke __loop_clr_fd() asynchronously in its entirety. I think at least the following code should be executed synchronously from lo_release():

	loop_sysfs_exit(lo);

	mutex_lock(&lo->lo_mutex);
	WRITE_ONCE(lo->lo_state, Lo_unbound);
	mutex_unlock(&lo->lo_mutex);
Quoted 11 lines
drivers/block/loop.c +5 -2
@@ -1769,8 +1797,20 @@ static void lo_release(struct gendisk *disk)
  	need_clear = (lo->lo_state == Lo_rundown);
  	mutex_unlock(&lo->lo_mutex);
 
-	if (need_clear)
-		__loop_clr_fd(lo);
+	/*
+	 * In order to flush pending I/O requests before clearing the backing
+	 * device, defer __loop_clr_fd() to WQ context. The Lo_rundown state
+	 * guarantees that lo_open() will fail with -ENXIO.
+	 */

drivers/block/loop.c static void lo_release(struct gendisk *disk) · line 1814

Quoted 10 lines
drivers/block/loop.c +9 -0
+	if (need_clear) {
+		/*
+		 * Grab all references that will be dropped as soon as
+		 * returning from lo_release() and releasing disk->open_mutex.
+		 */
+		get_device(disk_to_dev(disk));
+		__module_get(disk->fops->owner);
+		queue_work(system_long_wq, &lo->lo_clr_work);
+	}
  }

Please convert the above code to the "early return" style that is used elsewhere in the kernel.

Why system_long_wq instead of lo->workqueue?

Thanks,

Bart.

#64 lore raw

Re: [PATCH v7] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 8 lines · Bart Van Assche

drivers/block/loop.c static int loop_configure(struct loop_device *lo, blk_mode_t mode, · line 1152

Quoted 3 lines · Tetsuo Handa
drivers/block/loop.c +3 -0
+     * wait for already started loop_queue_rq() to complete.
+     */
+    synchronize_rcu();

Calling synchronize_rcu() to wait for ongoing loop_queue_rq() calls to complete won't work if anyone would set BLK_MQ_F_BLOCKING for the request queues created by the loop driver.

Excuse me, but this ordering is correct (reviewed by Gemini and sashiko).

Quoted 6 lines

Please use the block-layer
APIs instead of open-coding these. I'm referring to blk_mq_quiesce_queue() and blk_mq_wait_quiesce_done().

Freezing the request queue must happen before waiting for ongoing loop_queue_rq() calls to finish.

I and Gemini cannot catch what you want to say here.

Quoted 4 lines

Calling synchronize_rcu() does not prevent new I/O to be submitted. What prevents io_uring to submit more I/O asynchronously, e.g. if a file descriptor that refers to a loop device instance has been registered in the fixed-file table?

Calling synchronize_rcu() makes sure that no more queue_work() calls are made from loop_queue_work() from loop_queue_rq(). Since loop_queue_rq() is called with RCU read lock, subsequent loop_queue_rq() calls which are made after synchronize_rcu() returned shall see lo->lo_state != Lo_bound and return with BLK_STS_IOERR.

Quoted 12 lines

drivers/block/loop.c static int loop_configure(struct loop_device *lo, blk_mode_t mode, · line 1162

Quoted 11 lines
drivers/block/loop.c +10 -0
+    /*
+     * Now that no more works are scheduled by loop_queue_rq(),
+     * wait for already scheduled works to complete.
+     */
+    drain_workqueue(lo->workqueue);
+    /*
+     * Now that no more AIO requests are scheduled by lo_rw_aio(),
+     * wait for already started AIO to complete.
+     */
+    blk_mq_unfreeze_queue(lo->lo_queue, blk_mq_freeze_queue(lo->lo_queue));
Quoted 1 line

Freezing the request queue must happen before lo->workqueue is drained.

Again, I and Gemini cannot catch what you want to say here.

Calling drain_workqueue() after synchronize_rcu() makes sure that no more loop_handle_cmd() calls are made from loop_process_work() from loop_workfn() and loop_rootcg_workfn().

Calling blk_mq_freeze_queue() after drain_workqueue() after synchronize_rcu() does wait for completion of all pending I/O requests which has been scheduled via loop_queue_rq(), by waiting for q_usage_counter to reach 0. Also, this synchronize_rcu() => drain_workqueue() => blk_mq_freeze_queue() ordering guarantees that q_usage_counter won't be incremented again after it once reached 0, due to the lo->lo_state != Lo_bound check in loop_queue_rq(). This makes it possible to call blk_mq_unfreeze_queue() immediately after blk_mq_freeze_queue().

Quoted 8 lines

drivers/block/loop.c static int loop_configure(struct loop_device *lo, blk_mode_t mode, · line 1165

Quoted 3 lines
drivers/block/loop.c +2 -0
+    /* Step 2: Perform remaining cleanup, with open_mutex held. */
+    mutex_lock(&disk->open_mutex);

After having obtained disk->open_mutex, lease add something like the
following: WARN_ON_ONCE(lo->lo_state == Lo_bound). Even if this condition can't be triggered today, this may help with detecting bugs in future loop driver changes.

Did you mean WARN_ON_ONCE(lo->lo_state != Lo_rundown) ?

Quoted 13 lines

drivers/block/loop.c static void __loop_clr_fd(struct loop_device *lo) · line 1189

Quoted 8 lines
drivers/block/loop.c +0 -2
@@ -1168,8 +1186,6 @@ static void __loop_clr_fd(struct loop_device *lo)
      /* let user-space know about this change */
      kobject_uevent(&disk_to_dev(lo->lo_disk)->kobj, KOBJ_CHANGE);
      mapping_set_gfp_mask(filp->f_mapping, gfp);
-    /* This is safe: open() is still holding a reference. */
-    module_put(THIS_MODULE);
        disk_force_media_change(lo->lo_disk); 

I don't think that it's acceptable to invoke __loop_clr_fd() asynchronously in its entirety. I think at least the following code should be executed synchronously from lo_release():

Quoted 6 lines
    loop_sysfs_exit(lo);

    mutex_lock(&lo->lo_mutex);
    WRITE_ONCE(lo->lo_state, Lo_unbound);
    mutex_unlock(&lo->lo_mutex);

Doing so breaks the whole protection provided by the Lo_rundown state. As soon as lo->lo_state becomes Lo_unbound, lo_open() will succeed and loop_configure() will start changing an lo object before WQ context cleans up that lo object.

Quoted 15 lines
Quoted 15 lines
drivers/block/loop.c +10 -1
@@ -1769,8 +1797,20 @@ static void lo_release(struct gendisk *disk)
      need_clear = (lo->lo_state == Lo_rundown);
      mutex_unlock(&lo->lo_mutex);
  -    if (need_clear)
-        __loop_clr_fd(lo);
+    /*
+     * In order to flush pending I/O requests before clearing the backing
+     * device, defer __loop_clr_fd() to WQ context. The Lo_rundown state
+     * guarantees that lo_open() will fail with -ENXIO.
+     */
+    if (need_clear) {
+        /*
+         * Grab all references that will be dropped as soon as
+         * returning from lo_release() and releasing disk->open_mutex.
+         */
Quoted 8 lines

drivers/block/loop.c static void lo_release(struct gendisk *disk) · line 1814

Quoted 5 lines
drivers/block/loop.c +4 -0
+        get_device(disk_to_dev(disk));
+        __module_get(disk->fops->owner);
+        queue_work(system_long_wq, &lo->lo_clr_work);
+    }
  }

Please convert the above code to the "early return" style that is used elsewhere in the kernel.

That is OK. But after you agreed that my patch works as expected.

Quoted 2 lines

Why system_long_wq instead of lo->workqueue?

That is a deadlock. We can't flush a work in lo->workqueue from inside WQ callback function where that work is associated with.

#65 lore raw

Re: [PATCH v7] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 4 lines · Tetsuo Handa

Also, this
synchronize_rcu() => drain_workqueue() => blk_mq_freeze_queue() ordering guarantees that q_usage_counter won't be incremented again after it once reached 0, due to the lo->lo_state != Lo_bound check in loop_queue_rq().

Well, this part was inaccurate. Since q_usage_counter is incremented before loop_queue_rq() is called, it is possible that q_usage_counter itself can be incremented even after synchronize_rcu() => drain_workqueue() => blk_mq_freeze_queue() sequence.

But what makes this ordering safe are

(1) since we are in lo_release() with disk_openers(disk) == 0, the activity of incrementing/decrementing q_usage_counter (incremented before loop_queue_rq() is called, and decremented after loop_queue_rq() returned BLK_STS_IOERR)) will cease shortly

(2) since there is no pending work in lo->workqueue, no I/O will be made to backing file

.

#66 lore raw

Re: [PATCH v7] loop: Fix NULL pointer dereference in lo_rw_aio()

From: Tao Cui <[email protected]>

Hi Tetsuo, Bart,

drivers/block/loop.c static int loop_configure(struct loop_device *lo, blk_mode_t mode, · line 1152

Quoted 6 lines
drivers/block/loop.c +6 -0
+	/* Step 1: Flush all outstanding I/O, without open_mutex held. */
+	/*
+	 * Now that loop_queue_rq() sees lo->lo_state != Lo_bound,
+	 * wait for already started loop_queue_rq() to complete.
+	 */
+	synchronize_rcu();

Your reply to Bart says loop_queue_rq() is called with RCU read lock, but I don't see one. The two call sites of ->queue_rq() are blk_mq_dispatch_rq_list() and __blk_mq_issue_directly(), and neither is wrapped in rcu_read_lock(). Direct issue from blk_mq_submit_bio() runs in process context with no RCU read-side critical section, so synchronize_rcu() does not wait for a loop_queue_rq() that is already running there. Only the softirq dispatch path is an implicit RCU reader.

The window is still closed by the steps below, so this is not a correctness bug, but the synchronize_rcu() is not doing what the comment claims. blk_mq_quiesce_queue() + blk_mq_wait_quiesce_done(), as Bart suggested, would express the intent directly.

Quoted 5 lines
drivers/block/loop.c +5 -0
+	/*
+	 * Now that no more AIO requests are scheduled by lo_rw_aio(),
+	 * wait for already started AIO to complete.
+	 */
+	blk_mq_unfreeze_queue(lo->lo_queue, blk_mq_freeze_queue(lo->lo_queue));
Quoted 4 lines · in your follow-up you

(1) since we are in lo_release() with disk_openers(disk) == 0, the activity of incrementing/decrementing q_usage_counter (incremented before loop_queue_rq() is called, and decremented after loop_queue_rq() returned BLK_STS_IOERR)) will cease shortly

The decrement timing here is only true for the error path. For BLK_STS_OK the reference is held until the request is freed, which is what makes blk_mq_freeze_queue() wait for requests that already passed the state check, including the loop workqueue worker that completes them. That is the property step 1 relies on, and it is worth stating in the comment.

What is still open is Bart's question about io_uring fixed files:
if submissions can continue after the last close, "cease shortly" does not hold, and it is the freeze wait that actually drains them.

drivers/block/loop.c static void lo_release(struct gendisk *disk) · line 1813

Quoted 9 lines
drivers/block/loop.c +9 -0
+	if (need_clear) {
+		/*
+		 * Grab all references that will be dropped as soon as
+		 * returning from lo_release() and releasing disk->open_mutex.
+		 */
+		get_device(disk_to_dev(disk));
+		__module_get(disk->fops->owner);
+		queue_work(system_long_wq, &lo->lo_clr_work);
+	}

With teardown now asynchronous, between the last close() returning and the work item finishing, lo_open() and LOOP_CONFIGURE return -ENXIO. That is the same behavior change that led to the revert of the earlier attempt (bf23747ee053, xfs/259). Moving the xfstests side to the tests is one thing, but userspace that closes a loop device and immediately reconfigures it now needs to handle a transient -ENXIO. Is that acceptable, or should the retry happen in the kernel?

Thanks,
Tao

#67 lore raw

Re: [PATCH v7] loop: Fix NULL pointer dereference in lo_rw_aio()

Thank you for joining to this thread, Tao.

Quoted 4 lines · Tao Cui

From: Tao Cui <[email protected]>

Hi Tetsuo, Bart,

Quoted 15 lines

drivers/block/loop.c static int loop_configure(struct loop_device *lo, blk_mode_t mode, · line 1152

Quoted 6 lines
drivers/block/loop.c +6 -0
+	/* Step 1: Flush all outstanding I/O, without open_mutex held. */
+	/*
+	 * Now that loop_queue_rq() sees lo->lo_state != Lo_bound,
+	 * wait for already started loop_queue_rq() to complete.
+	 */
+	synchronize_rcu();

Your reply to Bart says loop_queue_rq() is called with RCU read lock, but I don't see one. The two call sites of ->queue_rq() are blk_mq_dispatch_rq_list() and __blk_mq_issue_directly(), and neither is wrapped in rcu_read_lock(). Direct issue from blk_mq_submit_bio() runs in process context with no RCU read-side critical section, so synchronize_rcu() does not wait for a loop_queue_rq() that is already running there. Only the softirq dispatch path is an implicit RCU reader.

You can read sashiko's raw logs at https://sashiko.dev/#/log/49552 .

Okay, let's break this down. My initial thought is to examine how the blk_mq_run_dispatch_ops macro is implemented. Specifically, how does it handle RCU read locks? It wraps the provided dispatch_ops in either rcu_read_lock() or srcu_read_lock(), depending on the BLK_MQ_F_BLOCKING flag. The loop device, however, is set up *without* this BLK_MQ_F_BLOCKING flag. Therefore, loop_queue_rq executes under the protection of rcu_read_lock().

Now, the critical question: Does the synchronize_rcu() call in __loop_clr_fd effectively address the potential race conditions? Since loop_queue_rq() is indeed RCU-protected, synchronize_rcu() will correctly wait for all currently executing instances of loop_queue_rq() to complete. Furthermore, the lo_state transition to Lo_rundown before calling __loop_clr_fd ensures that any *new* calls to loop_queue_rq() will see this state and return an error. This perfectly fences the execution of loop_queue_rq(). Moreover, drain_workqueue() then makes sure all queued works are completed, and these are scheduled by loop_queue_rq(). This is great; all scheduled works are completed before clearing lo->lo_backing_file.

Quoted 6 lines

The window is still closed by the steps below, so this is not a correctness bug, but the synchronize_rcu() is not doing what the comment claims. blk_mq_quiesce_queue() + blk_mq_wait_quiesce_done(), as Bart suggested, would express the intent directly.

synchronize_rcu() + drain_workqueue() can be implied by blk_mq_freeze_queue() + blk_mq_unfreeze_queue(). But why are you talking about blk_mq_quiesce_queue() + blk_mq_wait_quiesce_done() ?

Quoted 21 lines
Quoted 6 lines
drivers/block/loop.c +5 -0
+	/*
+	 * Now that no more AIO requests are scheduled by lo_rw_aio(),
+	 * wait for already started AIO to complete.
+	 */
+	blk_mq_unfreeze_queue(lo->lo_queue, blk_mq_freeze_queue(lo->lo_queue));
Quoted 4 lines · in your follow-up you

(1) since we are in lo_release() with disk_openers(disk) == 0, the activity of incrementing/decrementing q_usage_counter (incremented before loop_queue_rq() is called, and decremented after loop_queue_rq() returned BLK_STS_IOERR)) will cease shortly

The decrement timing here is only true for the error path. For BLK_STS_OK the reference is held until the request is freed, which is what makes blk_mq_freeze_queue() wait for requests that already passed the state check, including the loop workqueue worker that completes them. That is the property step 1 relies on, and it is worth stating in the comment.

Quoted 3 lines

What is still open is Bart's question about io_uring fixed files:
if submissions can continue after the last close, "cease shortly" does not hold, and it is the freeze wait that actually drains them.

If submissions can continue _forever_ despite disk_openers(disk) == 0, what mechanism was preventing this problem from occurring until Linux 7.0 ?

Quoted 11 lines

drivers/block/loop.c static void lo_release(struct gendisk *disk) · line 1813

Quoted 10 lines
drivers/block/loop.c +9 -0
+	if (need_clear) {
+		/*
+		 * Grab all references that will be dropped as soon as
+		 * returning from lo_release() and releasing disk->open_mutex.
+		 */
+		get_device(disk_to_dev(disk));
+		__module_get(disk->fops->owner);
+		queue_work(system_long_wq, &lo->lo_clr_work);
+	}
Quoted 8 lines

With teardown now asynchronous, between the last close() returning and the work item finishing, lo_open() and LOOP_CONFIGURE return -ENXIO. That is the same behavior change that led to the revert of the earlier attempt (bf23747ee053, xfs/259). Moving the xfstests side to the tests is one thing, but userspace that closes a loop device and immediately reconfigures it now needs to handle a transient -ENXIO. Is that acceptable, or should the retry happen in the kernel?

Does whether the teardown being synchronous or asynchronous matter so much?

I don't think we can control when e.g. udev-worker becomes the thread
who actually calls __loop_clr_fd()
( https://lkml.kernel.org/r/[email protected] ). Even if an existing user app calls close() immediately followed by open(), we can't prove that __loop_clr_fd() is synchronously called by that user app because udev-worker can jump in and udev-worker becomes the thread who actually calls __loop_clr_fd().

An user app udev-worker
----------- -----------
open()
close()
open() // => succeeds due to Lo_bound state
ioctl(LOOP_CONFIGURE) // => fails with -EBUSY due to Lo_bound state close() // <= gives up due to ioctl() failure
close() // => becomes Lo_rundown and __loop_clr_fd() is called

A claim that mentions that the kernel is unable to release forever due to a refcount leak bug is valid. But a claim that mentions that the kernel cannot prove that this -ENXIO or -EBUSY problem never happens is invalid. Programs that use the loop device have to be prepared for transient errors.

#69 lore raw

Re: [PATCH v7] loop: Fix NULL pointer dereference in lo_rw_aio()

In reply to Tao Cui
Quoted 4 lines · Tao Cui

From: Tao Cui <[email protected]>

Hi Tetsuo, Bart,

Quoted 9 lines

drivers/block/loop.c static int loop_configure(struct loop_device *lo, blk_mode_t mode, · line 1152

Quoted 6 lines
drivers/block/loop.c +6 -0
+	/* Step 1: Flush all outstanding I/O, without open_mutex held. */
+	/*
+	 * Now that loop_queue_rq() sees lo->lo_state != Lo_bound,
+	 * wait for already started loop_queue_rq() to complete.
+	 */
+	synchronize_rcu();

Your reply to Bart says loop_queue_rq() is called with RCU read lock, but I don't see one.

This is the code that protects .queue_rq() implementations like loop_queue_rq() with an rcu_read_lock() / rcu_read_unlock() pair:

/* run the code block in @dispatch_ops with rcu/srcu read lock held */
#define __blk_mq_run_dispatch_ops(q, check_sleep, dispatch_ops) \

do {								\
	if ((q)->tag_set->flags & BLK_MQ_F_BLOCKING) {		\
		struct blk_mq_tag_set *__tag_set = (q)->tag_set; \
		int srcu_idx;					\
								\
		might_sleep_if(check_sleep);			\
		srcu_idx = srcu_read_lock(__tag_set->srcu);	\
		(dispatch_ops);					\
		srcu_read_unlock(__tag_set->srcu, srcu_idx);	\
	} else {						\
		rcu_read_lock();				\
		(dispatch_ops);					\
		rcu_read_unlock();				\
	}							\
} while (0)

Bart.

#70 lore raw

Re: [PATCH v7] loop: Fix NULL pointer dereference in lo_rw_aio()

In reply to Tetsuo Handa
Quoted 5 lines · Tetsuo Handa

Calling synchronize_rcu() makes sure that no more queue_work() calls are made from loop_queue_work() from loop_queue_rq(). Since loop_queue_rq() is called with RCU read lock, subsequent loop_queue_rq() calls which are made after synchronize_rcu() returned shall see lo->lo_state != Lo_bound and return with BLK_STS_IOERR.

Please add a comment above the synchronize_rcu() call that explains the purpose of that call.

Quoted 1 line

That is OK. But after you agreed that my patch works as expected.

I appreciate your work and agree that this patch takes the right direction. But I would appreciate it if you would take another look at my review comments.

Thanks,

Bart.

#68 lore raw

Re: [PATCH v7] loop: Fix NULL pointer dereference in lo_rw_aio()

In reply to Tetsuo Handa

Hi Bart, Tetsuo,

Thanks for the detailed replies, and to Tetsuo for the sashiko log.

Quoted 40 lines · Tetsuo Handa

Thank you for joining to this thread, Tao.

Quoted 4 lines · Tao Cui

From: Tao Cui <[email protected]>

Hi Tetsuo, Bart,

Quoted 15 lines

drivers/block/loop.c static int loop_configure(struct loop_device *lo, blk_mode_t mode, · line 1152

Quoted 6 lines
drivers/block/loop.c +6 -0
+	/* Step 1: Flush all outstanding I/O, without open_mutex held. */
+	/*
+	 * Now that loop_queue_rq() sees lo->lo_state != Lo_bound,
+	 * wait for already started loop_queue_rq() to complete.
+	 */
+	synchronize_rcu();

Your reply to Bart says loop_queue_rq() is called with RCU read lock, but I don't see one. The two call sites of ->queue_rq() are blk_mq_dispatch_rq_list() and __blk_mq_issue_directly(), and neither is wrapped in rcu_read_lock(). Direct issue from blk_mq_submit_bio() runs in process context with no RCU read-side critical section, so synchronize_rcu() does not wait for a loop_queue_rq() that is already running there. Only the softirq dispatch path is an implicit RCU reader.

You can read sashiko's raw logs at https://sashiko.dev/#/log/49552 .

Okay, let's break this down. My initial thought is to examine how the blk_mq_run_dispatch_ops macro is implemented. Specifically, how does it handle RCU read locks? It wraps the provided dispatch_ops in either rcu_read_lock() or srcu_read_lock(), depending on the BLK_MQ_F_BLOCKING flag. The loop device, however, is set up *without* this BLK_MQ_F_BLOCKING flag. Therefore, loop_queue_rq executes under the protection of rcu_read_lock().

Now, the critical question: Does the synchronize_rcu() call in __loop_clr_fd effectively address the potential race conditions? Since loop_queue_rq() is indeed RCU-protected, synchronize_rcu() will correctly wait for all currently executing instances of loop_queue_rq() to complete. Furthermore, the lo_state transition to Lo_rundown before calling __loop_clr_fd ensures that any *new* calls to loop_queue_rq() will see this state and return an error. This perfectly fences the execution of loop_queue_rq(). Moreover, drain_workqueue() then makes sure all queued works are completed, and these are scheduled by loop_queue_rq(). This is great; all scheduled works are completed before clearing lo->lo_backing_file.

Quoted 6 lines · Bart, on 8/31 you wrote:

This is the code that protects .queue_rq() implementations like loop_queue_rq() with an rcu_read_lock() / rcu_read_unlock() pair:

/* run the code block in @dispatch_ops with rcu/srcu read lock held */
#define __blk_mq_run_dispatch_ops(q, check_sleep, dispatch_ops) \
...

Quoted 6 lines
	} else {						\
		rcu_read_lock();				\
		(dispatch_ops);					\
		rcu_read_unlock();				\
	}							\
} while (0)

You are both right and I was wrong. I stopped at __blk_mq_issue_directly() and blk_mq_dispatch_rq_list() and missed that every caller goes through this macro. So synchronize_rcu() does wait for a running loop_queue_rq() with the current loop setup. I withdraw that comment.

Quoted 10 lines
Quoted 6 lines

The window is still closed by the steps below, so this is not a correctness bug, but the synchronize_rcu() is not doing what the comment claims. blk_mq_quiesce_queue() + blk_mq_wait_quiesce_done(), as Bart suggested, would express the intent directly.

synchronize_rcu() + drain_workqueue() can be implied by blk_mq_freeze_queue() + blk_mq_unfreeze_queue(). But why are you talking about blk_mq_quiesce_queue() + blk_mq_wait_quiesce_done() ?

That was Bart's suggestion from his earlier review, and I passed it on while assuming the synchronize_rcu() was unfounded. With the RCU pairing confirmed, there is nothing left to replace and the quiesce suggestion is moot.

Quoted 21 lines
Quoted 21 lines
Quoted 6 lines
drivers/block/loop.c +5 -0
+	/*
+	 * Now that no more AIO requests are scheduled by lo_rw_aio(),
+	 * wait for already started AIO to complete.
+	 */
+	blk_mq_unfreeze_queue(lo->lo_queue, blk_mq_freeze_queue(lo->lo_queue));
Quoted 4 lines · in your follow-up you

(1) since we are in lo_release() with disk_openers(disk) == 0, the activity of incrementing/decrementing q_usage_counter (incremented before loop_queue_rq() is called, and decremented after loop_queue_rq() returned BLK_STS_IOERR)) will cease shortly

The decrement timing here is only true for the error path. For BLK_STS_OK the reference is held until the request is freed, which is what makes blk_mq_freeze_queue() wait for requests that already passed the state check, including the loop workqueue worker that completes them. That is the property step 1 relies on, and it is worth stating in the comment.

Quoted 4 lines
Quoted 3 lines

What is still open is Bart's question about io_uring fixed files:
if submissions can continue after the last close, "cease shortly" does not hold, and it is the freeze wait that actually drains them.

The decrement part I would still reword: for BLK_STS_OK the reference is held until the request is freed, and that is the property blk_mq_freeze_queue() relies on. But you are right that the activity ceases, and for a simpler reason than the freeze:

Quoted 3 lines

If submissions can continue _forever_ despite disk_openers(disk) == 0, what mechanism was preventing this problem from occurring until Linux 7.0 ?

An io_uring fixed file holds a reference to the struct file, so bd_openers never reaches zero and lo_release() does not start while such a submission path exists. Any submission needs an open block device file (or a mount holding it), so "openers == 0 but submissions continue" needs no additional mechanism. I'll drop the io_uring part.

Quoted 39 lines
Quoted 11 lines

drivers/block/loop.c static void lo_release(struct gendisk *disk) · line 1813

Quoted 10 lines
drivers/block/loop.c +9 -0
+	if (need_clear) {
+		/*
+		 * Grab all references that will be dropped as soon as
+		 * returning from lo_release() and releasing disk->open_mutex.
+		 */
+		get_device(disk_to_dev(disk));
+		__module_get(disk->fops->owner);
+		queue_work(system_long_wq, &lo->lo_clr_work);
+	}
Quoted 8 lines

With teardown now asynchronous, between the last close() returning and the work item finishing, lo_open() and LOOP_CONFIGURE return -ENXIO. That is the same behavior change that led to the revert of the earlier attempt (bf23747ee053, xfs/259). Moving the xfstests side to the tests is one thing, but userspace that closes a loop device and immediately reconfigures it now needs to handle a transient -ENXIO. Is that acceptable, or should the retry happen in the kernel?

Does whether the teardown being synchronous or asynchronous matter so much?

I don't think we can control when e.g. udev-worker becomes the thread
who actually calls __loop_clr_fd()
( https://lkml.kernel.org/r/[email protected] ). Even if an existing user app calls close() immediately followed by open(), we can't prove that __loop_clr_fd() is synchronously called by that user app because udev-worker can jump in and udev-worker becomes the thread who actually calls __loop_clr_fd().

An user app udev-worker
----------- -----------
open()
close()
open() // => succeeds due to Lo_bound state
ioctl(LOOP_CONFIGURE) // => fails with -EBUSY due to Lo_bound state close() // <= gives up due to ioctl() failure
close() // => becomes Lo_rundown and __loop_clr_fd() is called

Quoted 4 lines

A claim that mentions that the kernel is unable to release forever due to a refcount leak bug is valid. But a claim that mentions that the kernel cannot prove that this -ENXIO or -EBUSY problem never happens is invalid. Programs that use the loop device have to be prepared for transient errors.

Your udev-worker sequence shows that synchronous completion was never guaranteed and -EBUSY or -ENXIO transients were already possible. I accept that. The remaining difference is only that the window now exists after every close instead of requiring an interleaving close from another opener, and if programs must tolerate transient errors anyway, that is not a blocker.

Tao

#71 lore raw

PATCH 1/1 loop: Fix NULL pointer dereference in lo_rw_aio()

In reply to Bart Van Assche

syzbot is reporting NULL pointer dereference in lo_rw_aio() [1][2]. An analysis by the Gemini AI collaborator [3] considers that this problem is caused by a timing shift primarily exposed by commit 65565ca5f99b ("block: unify the synchronous bi_end_io callbacks"), along with helper refactorings like commit 92c3737a2473 ("block: add a bio_submit_or_kill helper").

But due to difficulty of reproducing this race, discussion about what is happening and how to fix this problem is stalling. Also, we haven't identified how many filesystems are subjected to this problem.

Therefore, introduce a grace period for flushing outstanding I/O (which should be a good thing from the perspective of defensive programming) so that we won't hit NULL pointer dereference problem.

However, calling drain_workqueue() from __loop_clr_fd() with disk->open_mutex held causes lockdep warnings. We need to flush outstanding I/O without disk->open_mutex held. Therefore, defer __loop_clr_fd() to WQ context, like commit 322c4293ecc5 ("loop: make autoclear operation asynchronous") did.

The past attempt was reverted by commit bf23747ee053 ("loop: revert "make autoclear operation asynchronous"") for two reasons:

(1) Userspace might be expecting that fput() on the backing file is processed before lo_release() from close() returns to user mode. But a debug patch [4] suggested me that this teardown operation is racy regardless of whether disk->open_mutex is temporarily released or not, and therefore the xfs/259 breakage should be addressed on the xfstests side.

(2) Lockdep reported circular locking dependency caused by flushing system-wide WQs. But we no longer need to worry that dependency because all in-tree users no longer flush system-wide WQs.

Therefore, let's retry deferring __loop_clr_fd() to WQ context.

---
What an AI coding assistant based on Gemini told Bart about the v7.1 patch:

1. Userspace ABI / Teardown Regression (Asynchronous Autoclear)

The Regression: When a loop device configured with LO_FLAGS_AUTOCLEAR is closed (such as during unmounting with umount -d or mount -o loop), userspace expects that close() synchronously tears down the device and releases the backing file (fput()) before returning to user mode.

Prior History: This exact asynchronous deferral was merged in commit 322c4293ecc5 ("loop: make autoclear operation asynchronous") and had to be reverted in commit bf23747ee053 ("loop: revert 'make autoclear operation asynchronous'") because standard filesystem unmount sequences (such as umount ext4_on_xfs; umount /xfs) broke with -EBUSY in xfstests (e.g., xfs/259).

Kernel Policy: Handwaving this in the commit log ("the xfs/259 breakage should be addressed on the xfstests side") is not acceptable. Breaking synchronous teardown semantics violates the core Linux kernel rule: never break userspace. Real-world container engines, test suites, and system utilities rely on fput() having completed when lo_release() / close() returns.

What Bart says about the v6 patch which does synchronous teardown:

Releasing and reacquiring disk->open_mutex from __loop_clr_fd() seems risky to me. There is plenty of code in block/bdev.c that assumes that disk->open_mutex is not released by lo_release().

Then, what direction can we go?

 drivers/block/loop.c | 74 +++++++++++++++++++++++++++++++++++---------
 1 file changed, 60 insertions(+), 14 deletions(-)
drivers/block/loop.c +60 -14
index 6f12976035b0..516118b3a16c 100644
@@ -75,6 +75,7 @@ struct loop_device {
 	struct gendisk		*lo_disk;
 	struct mutex		lo_mutex;
 	bool			idr_visible;
+	struct work_struct	lo_clr_work;
 };
 
 struct loop_cmd {
@@ -1134,13 +1135,42 @@ static int loop_configure(struct loop_device *lo, blk_mode_t mode,
 	return error;
 }
 
-static void __loop_clr_fd(struct loop_device *lo)
+static void __loop_clr_fd(struct work_struct *work)
 {
+	struct loop_device *lo = container_of(work, struct loop_device, lo_clr_work);
+	struct gendisk *disk = lo->lo_disk;
 	struct queue_limits lim;
 	struct file *filp;
 	gfp_t gfp = lo->old_gfp_mask;
 	int err;
 
+	/* Step 1: Flush all outstanding I/O, without open_mutex held. */
+	/*
+	 * Since loop_queue_rq() is called with RCU read lock, this synchronize_rcu()
+	 * makes sure that no more queue_work() calls are made from loop_queue_work()
+	 * from loop_queue_rq(). Subsequent loop_queue_rq() calls which are made after
+	 * this synchronize_rcu() returned shall see lo->lo_state != Lo_bound and
+	 * return with BLK_STS_IOERR.
+	 */
+	synchronize_rcu();
+	/*
+	 * This drain_workqueue() makes sure that no more loop_handle_cmd() calls are
+	 * made from loop_process_work() from loop_workfn()/loop_rootcg_workfn().
+	 */
+	drain_workqueue(lo->workqueue);
+	/*
+	 * This blk_mq_freeze_queue() waits for completion of all outstanding I/O
+	 * which has been scheduled via loop_queue_rq(), by waiting for q_usage_counter
+	 * to reach 0. Since the lo->lo_state != Lo_bound check in loop_queue_rq()
+	 * guarantees that no more new I/O requests are made, we can call
+	 * blk_mq_unfreeze_queue() immediately after blk_mq_freeze_queue() returns.
+	 */
+	blk_mq_unfreeze_queue(lo->lo_queue, blk_mq_freeze_queue(lo->lo_queue));
+
+	/* Step 2: Perform remaining cleanup, with open_mutex held. */
+	mutex_lock(&disk->open_mutex);
+	WARN_ON_ONCE(lo->lo_state != Lo_rundown);
+
 	spin_lock_irq(&lo->lo_lock);
 	filp = lo->lo_backing_file;
 	lo->lo_backing_file = NULL;
@@ -1151,12 +1181,7 @@ static void __loop_clr_fd(struct loop_device *lo)
 	lo->lo_sizelimit = 0;
 	memset(lo->lo_file_name, 0, LO_NAME_SIZE);
 
-	/*
-	 * Reset the block size to the default.
-	 *
-	 * No queue freezing needed because this is called from the final
-	 * ->release call only, so there can't be any outstanding I/O.
-	 */
+	/* Reset the block size to the default. */
 	lim = queue_limits_start_update(lo->lo_queue);
 	lim.logical_block_size = SECTOR_SIZE;
 	lim.physical_block_size = SECTOR_SIZE;
@@ -1168,8 +1193,6 @@ static void __loop_clr_fd(struct loop_device *lo)
 	/* let user-space know about this change */
 	kobject_uevent(&disk_to_dev(lo->lo_disk)->kobj, KOBJ_CHANGE);
 	mapping_set_gfp_mask(filp->f_mapping, gfp);
-	/* This is safe: open() is still holding a reference. */
-	module_put(THIS_MODULE);
 
 	disk_force_media_change(lo->lo_disk);
 
@@ -1199,11 +1222,18 @@ static void __loop_clr_fd(struct loop_device *lo)
 	WRITE_ONCE(lo->lo_state, Lo_unbound);
 	mutex_unlock(&lo->lo_mutex);
 
+	/* Step 3: Drop refcounts, without open_mutex held. */
+	mutex_unlock(&disk->open_mutex);
+
+	put_device(disk_to_dev(disk));
+
 	/*
-	 * Need not hold lo_mutex to fput backing file. Calling fput holding
-	 * lo_mutex triggers a circular lock dependency possibility warning as
-	 * fput can take open_mutex which is usually taken before lo_mutex.
+	 * This is safe: flush_work() from loop_remove() from loop_exit() waits
+	 * until this function returns; effectively dropping the final module
+	 * references synchronously.
 	 */
+	module_put(THIS_MODULE);
+
 	fput(filp);
 }
 
@@ -1769,8 +1799,20 @@ static void lo_release(struct gendisk *disk)
 	need_clear = (lo->lo_state == Lo_rundown);
 	mutex_unlock(&lo->lo_mutex);
 
-	if (need_clear)
-		__loop_clr_fd(lo);
+	if (!need_clear)
+		return;
+	/*
+	 * In order to flush outstanding I/O before clearing the backing
+	 * device, defer __loop_clr_fd() to WQ context. The Lo_rundown state
+	 * guarantees that lo_open() will fail with -ENXIO.
+	 *
+	 * Grab disk reference which will be dropped as soon as
+	 * returning from lo_release() and releasing disk->open_mutex.
+	 * We don't need to grab disk->fops->owner reference because
+	 * we are holding one obtained by loop_configure().
+	 */
+	get_device(disk_to_dev(disk));
+	queue_work(system_long_wq, &lo->lo_clr_work);
 }
 
 static void lo_free_disk(struct gendisk *disk)
@@ -2034,6 +2076,7 @@ static int loop_add(int i)
 	lo = kzalloc_obj(*lo);
 	if (!lo)
 		goto out;
+	INIT_WORK(&lo->lo_clr_work, __loop_clr_fd);
 	lo->worker_tree = RB_ROOT;
 	INIT_LIST_HEAD(&lo->idle_worker_list);
 	timer_setup(&lo->timer, loop_free_idle_workers_timer, TIMER_DEFERRABLE);
@@ -2138,6 +2181,9 @@ static int loop_add(int i)
 
 static void loop_remove(struct loop_device *lo)
 {
+	/* Wait for __loop_clr_fd() to complete. */
+	flush_work(&lo->lo_clr_work);
+
 	/* Make this loop device unreachable from pathname. */
 	del_gendisk(lo->lo_disk);
 	blk_mq_free_tag_set(&lo->tag_set);
Signature · 1 line
2.55.0
#72 lore raw

PATCH v8 1/1 loop: Fix NULL pointer dereference in lo_rw_aio()

syzbot is reporting NULL pointer dereference in lo_rw_aio() [1][2]. An analysis by the Gemini AI collaborator [3] considers that this problem is caused by a timing shift primarily exposed by commit 65565ca5f99b ("block: unify the synchronous bi_end_io callbacks"), along with helper refactorings like commit 92c3737a2473 ("block: add a bio_submit_or_kill helper").

But due to difficulty of reproducing this race, discussion about what is happening and how to fix this problem is stalling. Also, we haven't identified how many filesystems are subjected to this problem.

Therefore, introduce a grace period for flushing outstanding I/O (which should be a good thing from the perspective of defensive programming) so that we won't hit NULL pointer dereference problem.

However, calling drain_workqueue() from __loop_clr_fd() with disk->open_mutex held causes lockdep warnings. We need to flush outstanding I/O without disk->open_mutex held. But we can't use task work context, for there is no way to reliably wait for completion of a task work function inside a loadable module when module unloading code for that loadable module has started. We need to use a callback function which is embedded into a built-in module so that it can reliably wait for completion of synchronous teardown for the loop driver module.

Therefore, add a dedicated callback for the loop module to the block core layer, and invoke that callback immediately after disk->open_mutex is released. It is possible that multiple threads invoke that callback when a teardown work was scheduled because disk->open_mutex was already released, but concurrently calling flush_work() in order to wait for completion of an outstanding teardown work will be safe.

---
What this patch does is basically the same with the v6 patch. Can this be a possible alternative for Bart's

Releasing and reacquiring disk->open_mutex from __loop_clr_fd() seems risky to me. There is plenty of code in block/bdev.c that assumes that disk->open_mutex is not released by lo_release().

comment?

 block/bdev.c           |  2 ++
 drivers/block/loop.c   | 65 +++++++++++++++++++++++++++++++++---------
 include/linux/blkdev.h |  5 ++++
 3 files changed, 59 insertions(+), 13 deletions(-)
block/bdev.c +2 -0
index cd8323083740..7ce5acaacf43 100644
@@ -1188,6 +1188,8 @@ void bdev_release(struct file *bdev_file)
 	else
 		blkdev_put_whole(bdev);
 	mutex_unlock(&disk->open_mutex);
+	if (bdev->bd_disk->fops->post_release)
+		bdev->bd_disk->fops->post_release(bdev->bd_disk);
 
 	module_put(disk->fops->owner);
 put_no_open:
drivers/block/loop.c +52 -13

114 lines not on this page · raw message

include/linux/blkdev.h +5 -0
index 4f7905c3412b..5172d6bdd9e7 100644
@@ -1605,6 +1605,11 @@ struct block_device_operations {
 	 * driver.
 	 */
 	int (*alternative_gpt_sector)(struct gendisk *disk, sector_t *sector);
+	/*
+	 * Special callback for synchronous cleanup without open_mutex.
+	 * Needed by loop devices.
+	 */
+	void (*post_release)(struct gendisk *disk);
 };
 
 #ifdef CONFIG_COMPAT
Signature · 1 line
2.55.0
#73 lore raw

Re: [PATCH v8] loop: Fix NULL pointer dereference in lo_rw_aio()

Quoted 58 lines · On Fri, 4 Sep 2026 08:50:46 +0900 Tetsuo Handa wrote:

syzbot is reporting NULL pointer dereference in lo_rw_aio() [1][2]. An analysis by the Gemini AI collaborator [3] considers that this problem is caused by a timing shift primarily exposed by commit 65565ca5f99b ("block: unify the synchronous bi_end_io callbacks"), along with helper refactorings like commit 92c3737a2473 ("block: add a bio_submit_or_kill helper").

But due to difficulty of reproducing this race, discussion about what is happening and how to fix this problem is stalling. Also, we haven't identified how many filesystems are subjected to this problem.

Therefore, introduce a grace period for flushing outstanding I/O (which should be a good thing from the perspective of defensive programming) so that we won't hit NULL pointer dereference problem.

However, calling drain_workqueue() from __loop_clr_fd() with disk->open_mutex held causes lockdep warnings. We need to flush outstanding I/O without disk->open_mutex held. But we can't use task work context, for there is no way to reliably wait for completion of a task work function inside a loadable module when module unloading code for that loadable module has started. We need to use a callback function which is embedded into a built-in module so that it can reliably wait for completion of synchronous teardown for the loop driver module.

Therefore, add a dedicated callback for the loop module to the block core layer, and invoke that callback immediately after disk->open_mutex is released. It is possible that multiple threads invoke that callback when a teardown work was scheduled because disk->open_mutex was already released, but concurrently calling flush_work() in order to wait for completion of an outstanding teardown work will be safe.

---
What this patch does is basically the same with the v6 patch. Can this be a possible alternative for Bart's

Releasing and reacquiring disk->open_mutex from __loop_clr_fd() seems risky to me. There is plenty of code in block/bdev.c that assumes that disk->open_mutex is not released by lo_release().

comment?

 block/bdev.c           |  2 ++
 drivers/block/loop.c   | 65 +++++++++++++++++++++++++++++++++---------
 include/linux/blkdev.h |  5 ++++
 3 files changed, 59 insertions(+), 13 deletions(-)
block/bdev.c +0 -0
index cd8323083740..7ce5acaacf43 100644

block/bdev.c void bdev_release(struct file *bdev_file) · line 1193

Quoted 6 lines
block/bdev.c +2 -0
@@ -1188,6 +1188,8 @@ void bdev_release(struct file *bdev_file)
 	else
 		blkdev_put_whole(bdev);
 	mutex_unlock(&disk->open_mutex);
+	if (bdev->bd_disk->fops->post_release)
+		bdev->bd_disk->fops->post_release(bdev->bd_disk);
 

A great leap forward, I like this.

Quoted 8 lines
block/bdev.c +7 -0
+
+static void lo_post_release(struct gendisk *disk)
+{
+	struct loop_device *lo = disk->private_data;
+
+	/* Wait for __loop_clr_fd() to complete. */
+	flush_work(&lo->lo_clr_work);
 }
#74 lore raw

Re: [PATCH v8] loop: Fix NULL pointer dereference in lo_rw_aio()

In reply to Tetsuo Handa
kernel test robot noticed the following build errors:

Hi Tetsuo,

kernel test robot noticed the following build errors:

[auto build test ERROR on axboe/for-next]
[also build test ERROR on linus/master v7.3-rc1 next-20260904] [If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Tetsuo-Handa/loop-Fix-NULL-pointer-dereference-in-lo_rw_aio/20260904-085046
base:   https://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux.git for-next
patch link:    https://lore.kernel.org/r/dc2f1e00-5e10-4e02-9415-c6ecb2cbc6b3%40I-love.SAKURA.ne.jp
patch subject: [PATCH v8] loop: Fix NULL pointer dereference in lo_rw_aio()
config: arm64-allmodconfig (https://download.01.org/0day-ci/archive/20260905/[email protected]/config)
compiler: clang version 24.0.0git (https://github.com/llvm/llvm-project 0edd1b088cc36b4faee80358c925a91e16006258)
rustc: rustc 1.96.0 (ac68faa20 2026-05-25)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260905/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

>> error[E0063]: missing field `post_release` in initializer of `block_device_operations`

--> rust/kernel/block/mq/gen_disk.rs:128:58
|
128 | const TABLE: bindings::block_device_operations = bindings::block_device_operations {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing post_release

--
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki