1 // SPDX-License-Identifier: GPL-2.0+
3 * Copyright (C) Nelson Integration, LLC 2016
12 #include <linux/ctype.h>
13 #include <linux/list.h>
15 struct block_cache_node {
26 static LIST_HEAD(block_cache);
28 static struct list_head block_cache;
31 static struct block_cache_stats _stats = {
32 .max_blocks_per_entry = 8,
37 int blkcache_init(void)
39 INIT_LIST_HEAD(&block_cache);
45 static struct block_cache_node *cache_find(int iftype, int devnum,
46 lbaint_t start, lbaint_t blkcnt,
49 struct block_cache_node *node;
51 list_for_each_entry(node, &block_cache, lh)
52 if ((node->iftype == iftype) &&
53 (node->devnum == devnum) &&
54 (node->blksz == blksz) &&
55 (node->start <= start) &&
56 (node->start + node->blkcnt >= start + blkcnt)) {
57 if (block_cache.next != &node->lh) {
58 /* maintain MRU ordering */
60 list_add(&node->lh, &block_cache);
67 int blkcache_read(int iftype, int devnum,
68 lbaint_t start, lbaint_t blkcnt,
69 unsigned long blksz, void *buffer)
71 struct block_cache_node *node = cache_find(iftype, devnum, start,
74 const char *src = node->cache + (start - node->start) * blksz;
75 memcpy(buffer, src, blksz * blkcnt);
76 debug("hit: start " LBAF ", count " LBAFU "\n",
82 debug("miss: start " LBAF ", count " LBAFU "\n",
88 void blkcache_fill(int iftype, int devnum,
89 lbaint_t start, lbaint_t blkcnt,
90 unsigned long blksz, void const *buffer)
93 struct block_cache_node *node;
95 /* don't cache big stuff */
96 if (blkcnt > _stats.max_blocks_per_entry)
99 if (_stats.max_entries == 0)
102 bytes = blksz * blkcnt;
103 if (_stats.max_entries <= _stats.entries) {
105 node = (struct block_cache_node *)block_cache.prev;
108 debug("drop: start " LBAF ", count " LBAFU "\n",
109 node->start, node->blkcnt);
110 if (node->blkcnt * node->blksz < bytes) {
115 node = malloc(sizeof(*node));
122 node->cache = malloc(bytes);
129 debug("fill: start " LBAF ", count " LBAFU "\n",
132 node->iftype = iftype;
133 node->devnum = devnum;
135 node->blkcnt = blkcnt;
137 memcpy(node->cache, buffer, bytes);
138 list_add(&node->lh, &block_cache);
142 void blkcache_invalidate(int iftype, int devnum)
144 struct list_head *entry, *n;
145 struct block_cache_node *node;
147 list_for_each_safe(entry, n, &block_cache) {
148 node = (struct block_cache_node *)entry;
149 if ((node->iftype == iftype) &&
150 (node->devnum == devnum)) {
159 void blkcache_configure(unsigned blocks, unsigned entries)
161 struct block_cache_node *node;
162 if ((blocks != _stats.max_blocks_per_entry) ||
163 (entries != _stats.max_entries)) {
164 /* invalidate cache */
165 while (!list_empty(&block_cache)) {
166 node = (struct block_cache_node *)block_cache.next;
174 _stats.max_blocks_per_entry = blocks;
175 _stats.max_entries = entries;
181 void blkcache_stats(struct block_cache_stats *stats)
183 memcpy(stats, &_stats, sizeof(*stats));