[PATCH] fscache: Convert from atomic_t to refcount_t on fscache_cache_tag->usage

From: Xiyu Yang
Date: Mon Jul 19 2021 - 02:00:36 EST


refcount_t type and corresponding API can protect refcounters from
accidental underflow and overflow and further use-after-free situations.

Signed-off-by: Xiyu Yang <xiyuyang19@xxxxxxxxxxxx>
Signed-off-by: Xin Tan <tanxin.ctf@xxxxxxxxx>
---
fs/fscache/cache.c | 8 ++++----
include/linux/fscache-cache.h | 3 ++-
2 files changed, 6 insertions(+), 5 deletions(-)

diff --git a/fs/fscache/cache.c b/fs/fscache/cache.c
index fcc136361415..a17faaae3668 100644
--- a/fs/fscache/cache.c
+++ b/fs/fscache/cache.c
@@ -29,7 +29,7 @@ struct fscache_cache_tag *__fscache_lookup_cache_tag(const char *name)

list_for_each_entry(tag, &fscache_cache_tag_list, link) {
if (strcmp(tag->name, name) == 0) {
- atomic_inc(&tag->usage);
+ refcount_inc(&tag->usage);
up_read(&fscache_addremove_sem);
return tag;
}
@@ -43,7 +43,7 @@ struct fscache_cache_tag *__fscache_lookup_cache_tag(const char *name)
/* return a dummy tag if out of memory */
return ERR_PTR(-ENOMEM);

- atomic_set(&xtag->usage, 1);
+ refcount_set(&xtag->usage, 1);
strcpy(xtag->name, name);

/* write lock, search again and add if still not present */
@@ -51,7 +51,7 @@ struct fscache_cache_tag *__fscache_lookup_cache_tag(const char *name)

list_for_each_entry(tag, &fscache_cache_tag_list, link) {
if (strcmp(tag->name, name) == 0) {
- atomic_inc(&tag->usage);
+ refcount_inc(&tag->usage);
up_write(&fscache_addremove_sem);
kfree(xtag);
return tag;
@@ -71,7 +71,7 @@ void __fscache_release_cache_tag(struct fscache_cache_tag *tag)
if (tag != ERR_PTR(-ENOMEM)) {
down_write(&fscache_addremove_sem);

- if (atomic_dec_and_test(&tag->usage))
+ if (refcount_dec_and_test(&tag->usage))
list_del_init(&tag->link);
else
tag = NULL;
diff --git a/include/linux/fscache-cache.h b/include/linux/fscache-cache.h
index 3235ddbdcc09..d3c609cfd762 100644
--- a/include/linux/fscache-cache.h
+++ b/include/linux/fscache-cache.h
@@ -14,6 +14,7 @@
#ifndef _LINUX_FSCACHE_CACHE_H
#define _LINUX_FSCACHE_CACHE_H

+#include <linux/refcount.h>
#include <linux/fscache.h>
#include <linux/sched.h>
#include <linux/workqueue.h>
@@ -45,7 +46,7 @@ struct fscache_cache_tag {
struct fscache_cache *cache; /* cache referred to by this tag */
unsigned long flags;
#define FSCACHE_TAG_RESERVED 0 /* T if tag is reserved for a cache */
- atomic_t usage;
+ refcount_t usage;
char name[]; /* tag name */
};

--
2.7.4