1 // SPDX-License-Identifier: GPL-2.0+
3 * Copyright (C) Nelson Integration, LLC 2016
11 #include <linux/ctype.h>
12 #include <linux/list.h>
14 struct block_cache_node {
25 static LIST_HEAD(block_cache);
27 static struct list_head block_cache;
30 static struct block_cache_stats _stats = {
31 .max_blocks_per_entry = 8,
36 int blkcache_init(void)
38 INIT_LIST_HEAD(&block_cache);
44 static struct block_cache_node *cache_find(int iftype, int devnum,
45 lbaint_t start, lbaint_t blkcnt,
48 struct block_cache_node *node;
50 list_for_each_entry(node, &block_cache, lh)
51 if ((node->iftype == iftype) &&
52 (node->devnum == devnum) &&
53 (node->blksz == blksz) &&
54 (node->start <= start) &&
55 (node->start + node->blkcnt >= start + blkcnt)) {
56 if (block_cache.next != &node->lh) {
57 /* maintain MRU ordering */
59 list_add(&node->lh, &block_cache);
66 int blkcache_read(int iftype, int devnum,
67 lbaint_t start, lbaint_t blkcnt,
68 unsigned long blksz, void *buffer)
70 struct block_cache_node *node = cache_find(iftype, devnum, start,
73 const char *src = node->cache + (start - node->start) * blksz;
74 memcpy(buffer, src, blksz * blkcnt);
75 debug("hit: start " LBAF ", count " LBAFU "\n",
81 debug("miss: start " LBAF ", count " LBAFU "\n",
87 void blkcache_fill(int iftype, int devnum,
88 lbaint_t start, lbaint_t blkcnt,
89 unsigned long blksz, void const *buffer)
92 struct block_cache_node *node;
94 /* don't cache big stuff */
95 if (blkcnt > _stats.max_blocks_per_entry)
98 if (_stats.max_entries == 0)
101 bytes = blksz * blkcnt;
102 if (_stats.max_entries <= _stats.entries) {
104 node = (struct block_cache_node *)block_cache.prev;
107 debug("drop: start " LBAF ", count " LBAFU "\n",
108 node->start, node->blkcnt);
109 if (node->blkcnt * node->blksz < bytes) {
114 node = malloc(sizeof(*node));
121 node->cache = malloc(bytes);
128 debug("fill: start " LBAF ", count " LBAFU "\n",
131 node->iftype = iftype;
132 node->devnum = devnum;
134 node->blkcnt = blkcnt;
136 memcpy(node->cache, buffer, bytes);
137 list_add(&node->lh, &block_cache);
141 void blkcache_invalidate(int iftype, int devnum)
143 struct list_head *entry, *n;
144 struct block_cache_node *node;
146 list_for_each_safe(entry, n, &block_cache) {
147 node = (struct block_cache_node *)entry;
148 if ((node->iftype == iftype) &&
149 (node->devnum == devnum)) {
158 void blkcache_configure(unsigned blocks, unsigned entries)
160 struct block_cache_node *node;
161 if ((blocks != _stats.max_blocks_per_entry) ||
162 (entries != _stats.max_entries)) {
163 /* invalidate cache */
164 while (!list_empty(&block_cache)) {
165 node = (struct block_cache_node *)block_cache.next;
173 _stats.max_blocks_per_entry = blocks;
174 _stats.max_entries = entries;
180 void blkcache_stats(struct block_cache_stats *stats)
182 memcpy(stats, &_stats, sizeof(*stats));