dm_cache_metadata_close() drops the reference with
refcount_dec_and_test() and only then takes table_lock to unlink the
object from the shared table. In between, a concurrent
dm_cache_metadata_open() on the same metadata device can find the
object in the table and call refcount_inc() on a zero refcount:

  refcount_t: addition on 0; use-after-free.
  WARNING: lib/refcount.c:34 at refcount_warn_saturate+0xc0/0xe0
  Call Trace:
   lookup+0xa9/0xc0
   dm_cache_metadata_open+0x104a/0x1560
   cache_ctr+0x145f/0x37b0
   dm_table_add_target
   table_load
   ctl_ioctl

The closing thread then destroys and frees the object, leaving the
opener holding a dangling pointer.

Use refcount_dec_and_mutex_lock() so the final decrement and the
list_del() happen atomically with respect to lookup().

Fixes: 9b1cc9f251af ("dm cache: share cache-metadata object across inactive and 
active DM tables")
Reported-by: [email protected]
Closes: https://syzkaller.appspot.com/bug?extid=dbad68398c8646e5a382
Signed-off-by: Nguyen Ngoc Thang <[email protected]>
---
Tested in QEMU (x86_64, 4 vCPUs, KASAN + lockdep) with the syzbot C
reproducer (4 threads racing DM_TABLE_LOAD of a cache target on the
same metadata device):
  - unpatched: "refcount_t: addition on 0" in lookup() in 3 of 5 boots
  - patched:   0 hits in 4 boots x 8 runs x 25s, no other warnings

 drivers/md/dm-cache-metadata.c | 17 +++++++++--------
 1 file changed, 9 insertions(+), 8 deletions(-)

diff --git a/drivers/md/dm-cache-metadata.c b/drivers/md/dm-cache-metadata.c
index 461044dca367a..04140e6b1fb92 100644
--- a/drivers/md/dm-cache-metadata.c
+++ b/drivers/md/dm-cache-metadata.c
@@ -877,15 +877,16 @@ struct dm_cache_metadata *dm_cache_metadata_open(struct 
block_device *bdev,
 
 void dm_cache_metadata_close(struct dm_cache_metadata *cmd)
 {
-       if (refcount_dec_and_test(&cmd->ref_count)) {
-               mutex_lock(&table_lock);
-               list_del(&cmd->list);
-               mutex_unlock(&table_lock);
+       /* Drop the last ref under table_lock so lookup() never sees it at 0. */
+       if (!refcount_dec_and_mutex_lock(&cmd->ref_count, &table_lock))
+               return;
 
-               if (!cmd->fail_io)
-                       __destroy_persistent_data_objects(cmd, true);
-               kfree(cmd);
-       }
+       list_del(&cmd->list);
+       mutex_unlock(&table_lock);
+
+       if (!cmd->fail_io)
+               __destroy_persistent_data_objects(cmd, true);
+       kfree(cmd);
 }
 
 /*
-- 
2.43.0


Reply via email to