Bug Analysis and Technical Explanation
Involved Files, Functions, and Data Structures
- Source File:
drivers/md/dm-cache-metadata.c
- Functions:
- Data Structures and Synchronization Primitives:
static LIST_HEAD(table); (global list tracking active dm_cache_metadata instances by underlying block device)
static DEFINE_MUTEX(table_lock); (mutex protecting lookups and modifications to table)
struct dm_cache_metadata (drivers/md/dm-cache-metadata.c:104):
refcount_t ref_count;
struct list_head list;
struct block_device *bdev;
Root Cause and Trigger Mechanism
To prevent multiple cache target instances from opening separate dm-bufio clients on the same metadata device when reload occurs before suspend, dm-cache-metadata.c caches open metadata instances in a global linked list table, synchronized by table_lock.
In lookup():
static struct dm_cache_metadata *lookup(struct block_device *bdev)
{
struct dm_cache_metadata *cmd;
list_for_each_entry(cmd, &table, list)
if (cmd->bdev == bdev) {
refcount_inc(&cmd->ref_count);
return cmd;
}
return NULL;
}
lookup() is called with table_lock held. If a matching entry is found, it unconditionally calls refcount_inc(&cmd->ref_count) to take a reference before returning cmd.
However, dm_cache_metadata_close() manages the object teardown as follows:
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);
if (!cmd->fail_io)
__destroy_persistent_data_objects(cmd, true);
kfree(cmd);
}
}
The bug is that refcount_dec_and_test(&cmd->ref_count) at line 880 is performed outside table_lock.
When Thread A closes the metadata structure when cmd->ref_count == 1:
- Thread A executes
refcount_dec_and_test(&cmd->ref_count). The refcount transitions from 1 to 0, and the function returns true.
- Before Thread A can acquire
mutex_lock(&table_lock) at line 881, Thread B enters lookup_or_open() (triggered via dm_ctl_ioctl -> table_load -> cache_ctr -> dm_cache_metadata_open).
- Thread B acquires
table_lock and runs lookup(bdev).
- Because Thread A has not yet called
list_del(&cmd->list), cmd is still present in table.
- Thread B matches
cmd->bdev == bdev and calls refcount_inc(&cmd->ref_count).
- Since
cmd->ref_count is already 0, refcount_inc() detects an increment from 0 (REFCOUNT_ADD_UAF) and triggers refcount_warn_saturate():
refcount_t: addition on 0; use-after-free.
kernel BUG at lib/refcount.c:34!
To avoid this race condition, dm_cache_metadata_close() must ensure the refcount cannot drop to 0 while the object remains visible to lookup(), for instance by decrementing under table_lock (or via refcount_dec_and_mutex_lock(&cmd->ref_count, &table_lock)).