1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 2009-2011 Red Hat, Inc.
5 * Author: Mikulas Patocka <mpatocka@redhat.com>
7 * This file is released under the GPL.
10 #include <linux/dm-bufio.h>
12 #include <linux/device-mapper.h>
13 #include <linux/dm-io.h>
14 #include <linux/slab.h>
15 #include <linux/sched/mm.h>
16 #include <linux/jiffies.h>
17 #include <linux/vmalloc.h>
18 #include <linux/shrinker.h>
19 #include <linux/module.h>
20 #include <linux/rbtree.h>
21 #include <linux/stacktrace.h>
22 #include <linux/jump_label.h>
26 #define DM_MSG_PREFIX "bufio"
29 * Memory management policy:
30 * Limit the number of buffers to DM_BUFIO_MEMORY_PERCENT of main memory
31 * or DM_BUFIO_VMALLOC_PERCENT of vmalloc memory (whichever is lower).
32 * Always allocate at least DM_BUFIO_MIN_BUFFERS buffers.
33 * Start background writeback when there are DM_BUFIO_WRITEBACK_PERCENT
36 #define DM_BUFIO_MIN_BUFFERS 8
38 #define DM_BUFIO_MEMORY_PERCENT 2
39 #define DM_BUFIO_VMALLOC_PERCENT 25
40 #define DM_BUFIO_WRITEBACK_RATIO 3
41 #define DM_BUFIO_LOW_WATERMARK_RATIO 16
44 * The nr of bytes of cached data to keep around.
46 #define DM_BUFIO_DEFAULT_RETAIN_BYTES (256 * 1024)
49 * Align buffer writes to this boundary.
50 * Tests show that SSDs have the highest IOPS when using 4k writes.
52 #define DM_BUFIO_WRITE_ALIGN 4096
55 * dm_buffer->list_mode
61 #define SCAN_RESCHED_CYCLE 16
63 /*--------------------------------------------------------------*/
66 * Rather than use an LRU list, we use a clock algorithm where entries
67 * are held in a circular list. When an entry is 'hit' a reference bit
68 * is set. The least recently used entry is approximated by running a
69 * cursor around the list selecting unreferenced entries. Referenced
70 * entries have their reference bit cleared as the cursor passes them.
73 struct list_head list;
79 struct list_head list;
80 struct lru_entry *stop;
85 struct list_head *cursor;
88 struct list_head iterators;
93 static void lru_init(struct lru *lru)
97 INIT_LIST_HEAD(&lru->iterators);
100 static void lru_destroy(struct lru *lru)
102 WARN_ON_ONCE(lru->cursor);
103 WARN_ON_ONCE(!list_empty(&lru->iterators));
107 * Insert a new entry into the lru.
109 static void lru_insert(struct lru *lru, struct lru_entry *le)
112 * Don't be tempted to set to 1, makes the lru aspect
115 atomic_set(&le->referenced, 0);
118 list_add_tail(&le->list, lru->cursor);
120 INIT_LIST_HEAD(&le->list);
121 lru->cursor = &le->list;
129 * Convert a list_head pointer to an lru_entry pointer.
131 static inline struct lru_entry *to_le(struct list_head *l)
133 return container_of(l, struct lru_entry, list);
137 * Initialize an lru_iter and add it to the list of cursors in the lru.
139 static void lru_iter_begin(struct lru *lru, struct lru_iter *it)
142 it->stop = lru->cursor ? to_le(lru->cursor->prev) : NULL;
143 it->e = lru->cursor ? to_le(lru->cursor) : NULL;
144 list_add(&it->list, &lru->iterators);
148 * Remove an lru_iter from the list of cursors in the lru.
150 static inline void lru_iter_end(struct lru_iter *it)
155 /* Predicate function type to be used with lru_iter_next */
156 typedef bool (*iter_predicate)(struct lru_entry *le, void *context);
159 * Advance the cursor to the next entry that passes the
160 * predicate, and return that entry. Returns NULL if the
161 * iteration is complete.
163 static struct lru_entry *lru_iter_next(struct lru_iter *it,
164 iter_predicate pred, void *context)
171 /* advance the cursor */
172 if (it->e == it->stop)
175 it->e = to_le(it->e->list.next);
177 if (pred(e, context))
185 * Invalidate a specific lru_entry and update all cursors in
186 * the lru accordingly.
188 static void lru_iter_invalidate(struct lru *lru, struct lru_entry *e)
192 list_for_each_entry(it, &lru->iterators, list) {
193 /* Move c->e forwards if necc. */
195 it->e = to_le(it->e->list.next);
200 /* Move it->stop backwards if necc. */
202 it->stop = to_le(it->stop->list.prev);
212 * Remove a specific entry from the lru.
214 static void lru_remove(struct lru *lru, struct lru_entry *le)
216 lru_iter_invalidate(lru, le);
217 if (lru->count == 1) {
220 if (lru->cursor == &le->list)
221 lru->cursor = lru->cursor->next;
228 * Mark as referenced.
230 static inline void lru_reference(struct lru_entry *le)
232 atomic_set(&le->referenced, 1);
238 * Remove the least recently used entry (approx), that passes the predicate.
239 * Returns NULL on failure.
244 ER_STOP, /* stop looking for something to evict */
247 typedef enum evict_result (*le_predicate)(struct lru_entry *le, void *context);
249 static struct lru_entry *lru_evict(struct lru *lru, le_predicate pred, void *context, bool no_sleep)
251 unsigned long tested = 0;
252 struct list_head *h = lru->cursor;
253 struct lru_entry *le;
258 * In the worst case we have to loop around twice. Once to clear
259 * the reference flags, and then again to discover the predicate
260 * fails for all entries.
262 while (tested < lru->count) {
263 le = container_of(h, struct lru_entry, list);
265 if (atomic_read(&le->referenced)) {
266 atomic_set(&le->referenced, 0);
269 switch (pred(le, context)) {
272 * Adjust the cursor, so we start the next
275 lru->cursor = le->list.next;
283 lru->cursor = le->list.next;
297 /*--------------------------------------------------------------*/
307 * Describes how the block was allocated:
308 * kmem_cache_alloc(), __get_free_pages() or vmalloc().
309 * See the comment at alloc_buffer_data.
313 DATA_MODE_KMALLOC = 1,
314 DATA_MODE_GET_FREE_PAGES = 2,
315 DATA_MODE_VMALLOC = 3,
320 /* protected by the locks in dm_buffer_cache */
323 /* immutable, so don't need protecting */
326 unsigned char data_mode; /* DATA_MODE_* */
329 * These two fields are used in isolation, so do not need
330 * a surrounding lock.
333 unsigned long last_accessed;
336 * Everything else is protected by the mutex in
340 struct lru_entry lru;
341 unsigned char list_mode; /* LIST_* */
342 blk_status_t read_error;
343 blk_status_t write_error;
344 unsigned int dirty_start;
345 unsigned int dirty_end;
346 unsigned int write_start;
347 unsigned int write_end;
348 struct list_head write_list;
349 struct dm_bufio_client *c;
350 void (*end_io)(struct dm_buffer *b, blk_status_t bs);
351 #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
353 unsigned int stack_len;
354 unsigned long stack_entries[MAX_STACK];
358 /*--------------------------------------------------------------*/
361 * The buffer cache manages buffers, particularly:
362 * - inc/dec of holder count
363 * - setting the last_accessed field
364 * - maintains clean/dirty state along with lru
365 * - selecting buffers that match predicates
367 * It does *not* handle:
368 * - allocation/freeing of buffers.
370 * - Eviction or cache sizing.
372 * cache_get() and cache_put() are threadsafe, you do not need to
373 * protect these calls with a surrounding mutex. All the other
374 * methods are not threadsafe; they do use locking primitives, but
375 * only enough to ensure get/put are threadsafe.
380 struct rw_semaphore lock;
384 } ____cacheline_aligned_in_smp;
386 struct dm_buffer_cache {
387 struct lru lru[LIST_SIZE];
389 * We spread entries across multiple trees to reduce contention
392 unsigned int num_locks;
394 struct buffer_tree trees[];
397 static DEFINE_STATIC_KEY_FALSE(no_sleep_enabled);
399 static inline unsigned int cache_index(sector_t block, unsigned int num_locks)
401 return dm_hash_locks_index(block, num_locks);
404 static inline void cache_read_lock(struct dm_buffer_cache *bc, sector_t block)
406 if (static_branch_unlikely(&no_sleep_enabled) && bc->no_sleep)
407 read_lock_bh(&bc->trees[cache_index(block, bc->num_locks)].u.spinlock);
409 down_read(&bc->trees[cache_index(block, bc->num_locks)].u.lock);
412 static inline void cache_read_unlock(struct dm_buffer_cache *bc, sector_t block)
414 if (static_branch_unlikely(&no_sleep_enabled) && bc->no_sleep)
415 read_unlock_bh(&bc->trees[cache_index(block, bc->num_locks)].u.spinlock);
417 up_read(&bc->trees[cache_index(block, bc->num_locks)].u.lock);
420 static inline void cache_write_lock(struct dm_buffer_cache *bc, sector_t block)
422 if (static_branch_unlikely(&no_sleep_enabled) && bc->no_sleep)
423 write_lock_bh(&bc->trees[cache_index(block, bc->num_locks)].u.spinlock);
425 down_write(&bc->trees[cache_index(block, bc->num_locks)].u.lock);
428 static inline void cache_write_unlock(struct dm_buffer_cache *bc, sector_t block)
430 if (static_branch_unlikely(&no_sleep_enabled) && bc->no_sleep)
431 write_unlock_bh(&bc->trees[cache_index(block, bc->num_locks)].u.spinlock);
433 up_write(&bc->trees[cache_index(block, bc->num_locks)].u.lock);
437 * Sometimes we want to repeatedly get and drop locks as part of an iteration.
438 * This struct helps avoid redundant drop and gets of the same lock.
440 struct lock_history {
441 struct dm_buffer_cache *cache;
443 unsigned int previous;
444 unsigned int no_previous;
447 static void lh_init(struct lock_history *lh, struct dm_buffer_cache *cache, bool write)
451 lh->no_previous = cache->num_locks;
452 lh->previous = lh->no_previous;
455 static void __lh_lock(struct lock_history *lh, unsigned int index)
458 if (static_branch_unlikely(&no_sleep_enabled) && lh->cache->no_sleep)
459 write_lock_bh(&lh->cache->trees[index].u.spinlock);
461 down_write(&lh->cache->trees[index].u.lock);
463 if (static_branch_unlikely(&no_sleep_enabled) && lh->cache->no_sleep)
464 read_lock_bh(&lh->cache->trees[index].u.spinlock);
466 down_read(&lh->cache->trees[index].u.lock);
470 static void __lh_unlock(struct lock_history *lh, unsigned int index)
473 if (static_branch_unlikely(&no_sleep_enabled) && lh->cache->no_sleep)
474 write_unlock_bh(&lh->cache->trees[index].u.spinlock);
476 up_write(&lh->cache->trees[index].u.lock);
478 if (static_branch_unlikely(&no_sleep_enabled) && lh->cache->no_sleep)
479 read_unlock_bh(&lh->cache->trees[index].u.spinlock);
481 up_read(&lh->cache->trees[index].u.lock);
486 * Make sure you call this since it will unlock the final lock.
488 static void lh_exit(struct lock_history *lh)
490 if (lh->previous != lh->no_previous) {
491 __lh_unlock(lh, lh->previous);
492 lh->previous = lh->no_previous;
497 * Named 'next' because there is no corresponding
498 * 'up/unlock' call since it's done automatically.
500 static void lh_next(struct lock_history *lh, sector_t b)
502 unsigned int index = cache_index(b, lh->no_previous); /* no_previous is num_locks */
504 if (lh->previous != lh->no_previous) {
505 if (lh->previous != index) {
506 __lh_unlock(lh, lh->previous);
507 __lh_lock(lh, index);
508 lh->previous = index;
511 __lh_lock(lh, index);
512 lh->previous = index;
516 static inline struct dm_buffer *le_to_buffer(struct lru_entry *le)
518 return container_of(le, struct dm_buffer, lru);
521 static struct dm_buffer *list_to_buffer(struct list_head *l)
523 struct lru_entry *le = list_entry(l, struct lru_entry, list);
525 return le_to_buffer(le);
528 static void cache_init(struct dm_buffer_cache *bc, unsigned int num_locks, bool no_sleep)
532 bc->num_locks = num_locks;
533 bc->no_sleep = no_sleep;
535 for (i = 0; i < bc->num_locks; i++) {
537 rwlock_init(&bc->trees[i].u.spinlock);
539 init_rwsem(&bc->trees[i].u.lock);
540 bc->trees[i].root = RB_ROOT;
543 lru_init(&bc->lru[LIST_CLEAN]);
544 lru_init(&bc->lru[LIST_DIRTY]);
547 static void cache_destroy(struct dm_buffer_cache *bc)
551 for (i = 0; i < bc->num_locks; i++)
552 WARN_ON_ONCE(!RB_EMPTY_ROOT(&bc->trees[i].root));
554 lru_destroy(&bc->lru[LIST_CLEAN]);
555 lru_destroy(&bc->lru[LIST_DIRTY]);
561 * not threadsafe, or racey depending how you look at it
563 static inline unsigned long cache_count(struct dm_buffer_cache *bc, int list_mode)
565 return bc->lru[list_mode].count;
568 static inline unsigned long cache_total(struct dm_buffer_cache *bc)
570 return cache_count(bc, LIST_CLEAN) + cache_count(bc, LIST_DIRTY);
576 * Gets a specific buffer, indexed by block.
577 * If the buffer is found then its holder count will be incremented and
578 * lru_reference will be called.
582 static struct dm_buffer *__cache_get(const struct rb_root *root, sector_t block)
584 struct rb_node *n = root->rb_node;
588 b = container_of(n, struct dm_buffer, node);
590 if (b->block == block)
593 n = block < b->block ? n->rb_left : n->rb_right;
599 static void __cache_inc_buffer(struct dm_buffer *b)
601 atomic_inc(&b->hold_count);
602 WRITE_ONCE(b->last_accessed, jiffies);
605 static struct dm_buffer *cache_get(struct dm_buffer_cache *bc, sector_t block)
609 cache_read_lock(bc, block);
610 b = __cache_get(&bc->trees[cache_index(block, bc->num_locks)].root, block);
612 lru_reference(&b->lru);
613 __cache_inc_buffer(b);
615 cache_read_unlock(bc, block);
623 * Returns true if the hold count hits zero.
626 static bool cache_put(struct dm_buffer_cache *bc, struct dm_buffer *b)
630 cache_read_lock(bc, b->block);
631 BUG_ON(!atomic_read(&b->hold_count));
632 r = atomic_dec_and_test(&b->hold_count);
633 cache_read_unlock(bc, b->block);
640 typedef enum evict_result (*b_predicate)(struct dm_buffer *, void *);
643 * Evicts a buffer based on a predicate. The oldest buffer that
644 * matches the predicate will be selected. In addition to the
645 * predicate the hold_count of the selected buffer will be zero.
647 struct evict_wrapper {
648 struct lock_history *lh;
654 * Wraps the buffer predicate turning it into an lru predicate. Adds
655 * extra test for hold_count.
657 static enum evict_result __evict_pred(struct lru_entry *le, void *context)
659 struct evict_wrapper *w = context;
660 struct dm_buffer *b = le_to_buffer(le);
662 lh_next(w->lh, b->block);
664 if (atomic_read(&b->hold_count))
665 return ER_DONT_EVICT;
667 return w->pred(b, w->context);
670 static struct dm_buffer *__cache_evict(struct dm_buffer_cache *bc, int list_mode,
671 b_predicate pred, void *context,
672 struct lock_history *lh)
674 struct evict_wrapper w = {.lh = lh, .pred = pred, .context = context};
675 struct lru_entry *le;
678 le = lru_evict(&bc->lru[list_mode], __evict_pred, &w, bc->no_sleep);
682 b = le_to_buffer(le);
683 /* __evict_pred will have locked the appropriate tree. */
684 rb_erase(&b->node, &bc->trees[cache_index(b->block, bc->num_locks)].root);
689 static struct dm_buffer *cache_evict(struct dm_buffer_cache *bc, int list_mode,
690 b_predicate pred, void *context)
693 struct lock_history lh;
695 lh_init(&lh, bc, true);
696 b = __cache_evict(bc, list_mode, pred, context, &lh);
705 * Mark a buffer as clean or dirty. Not threadsafe.
707 static void cache_mark(struct dm_buffer_cache *bc, struct dm_buffer *b, int list_mode)
709 cache_write_lock(bc, b->block);
710 if (list_mode != b->list_mode) {
711 lru_remove(&bc->lru[b->list_mode], &b->lru);
712 b->list_mode = list_mode;
713 lru_insert(&bc->lru[b->list_mode], &b->lru);
715 cache_write_unlock(bc, b->block);
721 * Runs through the lru associated with 'old_mode', if the predicate matches then
722 * it moves them to 'new_mode'. Not threadsafe.
724 static void __cache_mark_many(struct dm_buffer_cache *bc, int old_mode, int new_mode,
725 b_predicate pred, void *context, struct lock_history *lh)
727 struct lru_entry *le;
729 struct evict_wrapper w = {.lh = lh, .pred = pred, .context = context};
732 le = lru_evict(&bc->lru[old_mode], __evict_pred, &w, bc->no_sleep);
736 b = le_to_buffer(le);
737 b->list_mode = new_mode;
738 lru_insert(&bc->lru[b->list_mode], &b->lru);
742 static void cache_mark_many(struct dm_buffer_cache *bc, int old_mode, int new_mode,
743 b_predicate pred, void *context)
745 struct lock_history lh;
747 lh_init(&lh, bc, true);
748 __cache_mark_many(bc, old_mode, new_mode, pred, context, &lh);
755 * Iterates through all clean or dirty entries calling a function for each
756 * entry. The callback may terminate the iteration early. Not threadsafe.
760 * Iterator functions should return one of these actions to indicate
761 * how the iteration should proceed.
768 typedef enum it_action (*iter_fn)(struct dm_buffer *b, void *context);
770 static void __cache_iterate(struct dm_buffer_cache *bc, int list_mode,
771 iter_fn fn, void *context, struct lock_history *lh)
773 struct lru *lru = &bc->lru[list_mode];
774 struct lru_entry *le, *first;
779 first = le = to_le(lru->cursor);
781 struct dm_buffer *b = le_to_buffer(le);
783 lh_next(lh, b->block);
785 switch (fn(b, context)) {
794 le = to_le(le->list.next);
795 } while (le != first);
798 static void cache_iterate(struct dm_buffer_cache *bc, int list_mode,
799 iter_fn fn, void *context)
801 struct lock_history lh;
803 lh_init(&lh, bc, false);
804 __cache_iterate(bc, list_mode, fn, context, &lh);
811 * Passes ownership of the buffer to the cache. Returns false if the
812 * buffer was already present (in which case ownership does not pass).
813 * eg, a race with another thread.
815 * Holder count should be 1 on insertion.
819 static bool __cache_insert(struct rb_root *root, struct dm_buffer *b)
821 struct rb_node **new = &root->rb_node, *parent = NULL;
822 struct dm_buffer *found;
825 found = container_of(*new, struct dm_buffer, node);
827 if (found->block == b->block)
831 new = b->block < found->block ?
832 &found->node.rb_left : &found->node.rb_right;
835 rb_link_node(&b->node, parent, new);
836 rb_insert_color(&b->node, root);
841 static bool cache_insert(struct dm_buffer_cache *bc, struct dm_buffer *b)
845 if (WARN_ON_ONCE(b->list_mode >= LIST_SIZE))
848 cache_write_lock(bc, b->block);
849 BUG_ON(atomic_read(&b->hold_count) != 1);
850 r = __cache_insert(&bc->trees[cache_index(b->block, bc->num_locks)].root, b);
852 lru_insert(&bc->lru[b->list_mode], &b->lru);
853 cache_write_unlock(bc, b->block);
861 * Removes buffer from cache, ownership of the buffer passes back to the caller.
862 * Fails if the hold_count is not one (ie. the caller holds the only reference).
866 static bool cache_remove(struct dm_buffer_cache *bc, struct dm_buffer *b)
870 cache_write_lock(bc, b->block);
872 if (atomic_read(&b->hold_count) != 1) {
876 rb_erase(&b->node, &bc->trees[cache_index(b->block, bc->num_locks)].root);
877 lru_remove(&bc->lru[b->list_mode], &b->lru);
880 cache_write_unlock(bc, b->block);
887 typedef void (*b_release)(struct dm_buffer *);
889 static struct dm_buffer *__find_next(struct rb_root *root, sector_t block)
891 struct rb_node *n = root->rb_node;
893 struct dm_buffer *best = NULL;
896 b = container_of(n, struct dm_buffer, node);
898 if (b->block == block)
901 if (block <= b->block) {
912 static void __remove_range(struct dm_buffer_cache *bc,
913 struct rb_root *root,
914 sector_t begin, sector_t end,
915 b_predicate pred, b_release release)
922 b = __find_next(root, begin);
923 if (!b || (b->block >= end))
926 begin = b->block + 1;
928 if (atomic_read(&b->hold_count))
931 if (pred(b, NULL) == ER_EVICT) {
932 rb_erase(&b->node, root);
933 lru_remove(&bc->lru[b->list_mode], &b->lru);
939 static void cache_remove_range(struct dm_buffer_cache *bc,
940 sector_t begin, sector_t end,
941 b_predicate pred, b_release release)
945 BUG_ON(bc->no_sleep);
946 for (i = 0; i < bc->num_locks; i++) {
947 down_write(&bc->trees[i].u.lock);
948 __remove_range(bc, &bc->trees[i].root, begin, end, pred, release);
949 up_write(&bc->trees[i].u.lock);
953 /*----------------------------------------------------------------*/
956 * Linking of buffers:
957 * All buffers are linked to buffer_cache with their node field.
959 * Clean buffers that are not being written (B_WRITING not set)
960 * are linked to lru[LIST_CLEAN] with their lru_list field.
962 * Dirty and clean buffers that are being written are linked to
963 * lru[LIST_DIRTY] with their lru_list field. When the write
964 * finishes, the buffer cannot be relinked immediately (because we
965 * are in an interrupt context and relinking requires process
966 * context), so some clean-not-writing buffers can be held on
967 * dirty_lru too. They are later added to lru in the process
970 struct dm_bufio_client {
971 struct block_device *bdev;
972 unsigned int block_size;
973 s8 sectors_per_block_bits;
979 int async_write_error;
981 void (*alloc_callback)(struct dm_buffer *buf);
982 void (*write_callback)(struct dm_buffer *buf);
983 struct kmem_cache *slab_buffer;
984 struct kmem_cache *slab_cache;
985 struct dm_io_client *dm_io;
987 struct list_head reserved_buffers;
988 unsigned int need_reserved_buffers;
990 unsigned int minimum_buffers;
994 struct shrinker *shrinker;
995 struct work_struct shrink_work;
996 atomic_long_t need_shrink;
998 wait_queue_head_t free_buffer_wait;
1000 struct list_head client_list;
1003 * Used by global_cleanup to sort the clients list.
1005 unsigned long oldest_buffer;
1007 struct dm_buffer_cache cache; /* must be last member */
1010 /*----------------------------------------------------------------*/
1012 #define dm_bufio_in_request() (!!current->bio_list)
1014 static void dm_bufio_lock(struct dm_bufio_client *c)
1016 if (static_branch_unlikely(&no_sleep_enabled) && c->no_sleep)
1017 spin_lock_bh(&c->spinlock);
1019 mutex_lock_nested(&c->lock, dm_bufio_in_request());
1022 static void dm_bufio_unlock(struct dm_bufio_client *c)
1024 if (static_branch_unlikely(&no_sleep_enabled) && c->no_sleep)
1025 spin_unlock_bh(&c->spinlock);
1027 mutex_unlock(&c->lock);
1030 /*----------------------------------------------------------------*/
1033 * Default cache size: available memory divided by the ratio.
1035 static unsigned long dm_bufio_default_cache_size;
1038 * Total cache size set by the user.
1040 static unsigned long dm_bufio_cache_size;
1043 * A copy of dm_bufio_cache_size because dm_bufio_cache_size can change
1044 * at any time. If it disagrees, the user has changed cache size.
1046 static unsigned long dm_bufio_cache_size_latch;
1048 static DEFINE_SPINLOCK(global_spinlock);
1050 static unsigned int dm_bufio_max_age; /* No longer does anything */
1052 static unsigned long dm_bufio_retain_bytes = DM_BUFIO_DEFAULT_RETAIN_BYTES;
1054 static unsigned long dm_bufio_peak_allocated;
1055 static unsigned long dm_bufio_allocated_kmem_cache;
1056 static unsigned long dm_bufio_allocated_kmalloc;
1057 static unsigned long dm_bufio_allocated_get_free_pages;
1058 static unsigned long dm_bufio_allocated_vmalloc;
1059 static unsigned long dm_bufio_current_allocated;
1061 /*----------------------------------------------------------------*/
1064 * The current number of clients.
1066 static int dm_bufio_client_count;
1069 * The list of all clients.
1071 static LIST_HEAD(dm_bufio_all_clients);
1074 * This mutex protects dm_bufio_cache_size_latch and dm_bufio_client_count
1076 static DEFINE_MUTEX(dm_bufio_clients_lock);
1078 static struct workqueue_struct *dm_bufio_wq;
1079 static struct work_struct dm_bufio_replacement_work;
1082 #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
1083 static void buffer_record_stack(struct dm_buffer *b)
1085 b->stack_len = stack_trace_save(b->stack_entries, MAX_STACK, 2);
1089 /*----------------------------------------------------------------*/
1091 static void adjust_total_allocated(struct dm_buffer *b, bool unlink)
1093 unsigned char data_mode;
1096 static unsigned long * const class_ptr[DATA_MODE_LIMIT] = {
1097 &dm_bufio_allocated_kmem_cache,
1098 &dm_bufio_allocated_kmalloc,
1099 &dm_bufio_allocated_get_free_pages,
1100 &dm_bufio_allocated_vmalloc,
1103 data_mode = b->data_mode;
1104 diff = (long)b->c->block_size;
1108 spin_lock(&global_spinlock);
1110 *class_ptr[data_mode] += diff;
1112 dm_bufio_current_allocated += diff;
1114 if (dm_bufio_current_allocated > dm_bufio_peak_allocated)
1115 dm_bufio_peak_allocated = dm_bufio_current_allocated;
1118 if (dm_bufio_current_allocated > dm_bufio_cache_size)
1119 queue_work(dm_bufio_wq, &dm_bufio_replacement_work);
1122 spin_unlock(&global_spinlock);
1126 * Change the number of clients and recalculate per-client limit.
1128 static void __cache_size_refresh(void)
1130 if (WARN_ON(!mutex_is_locked(&dm_bufio_clients_lock)))
1132 if (WARN_ON(dm_bufio_client_count < 0))
1135 dm_bufio_cache_size_latch = READ_ONCE(dm_bufio_cache_size);
1138 * Use default if set to 0 and report the actual cache size used.
1140 if (!dm_bufio_cache_size_latch) {
1141 (void)cmpxchg(&dm_bufio_cache_size, 0,
1142 dm_bufio_default_cache_size);
1143 dm_bufio_cache_size_latch = dm_bufio_default_cache_size;
1148 * Allocating buffer data.
1150 * Small buffers are allocated with kmem_cache, to use space optimally.
1152 * For large buffers, we choose between get_free_pages and vmalloc.
1153 * Each has advantages and disadvantages.
1155 * __get_free_pages can randomly fail if the memory is fragmented.
1156 * __vmalloc won't randomly fail, but vmalloc space is limited (it may be
1157 * as low as 128M) so using it for caching is not appropriate.
1159 * If the allocation may fail we use __get_free_pages. Memory fragmentation
1160 * won't have a fatal effect here, but it just causes flushes of some other
1161 * buffers and more I/O will be performed. Don't use __get_free_pages if it
1162 * always fails (i.e. order > MAX_PAGE_ORDER).
1164 * If the allocation shouldn't fail we use __vmalloc. This is only for the
1165 * initial reserve allocation, so there's no risk of wasting all vmalloc
1168 static void *alloc_buffer_data(struct dm_bufio_client *c, gfp_t gfp_mask,
1169 unsigned char *data_mode)
1171 if (unlikely(c->slab_cache != NULL)) {
1172 *data_mode = DATA_MODE_SLAB;
1173 return kmem_cache_alloc(c->slab_cache, gfp_mask);
1176 if (unlikely(c->block_size < PAGE_SIZE)) {
1177 *data_mode = DATA_MODE_KMALLOC;
1178 return kmalloc(c->block_size, gfp_mask | __GFP_RECLAIMABLE);
1181 if (c->block_size <= KMALLOC_MAX_SIZE &&
1182 gfp_mask & __GFP_NORETRY) {
1183 *data_mode = DATA_MODE_GET_FREE_PAGES;
1184 return (void *)__get_free_pages(gfp_mask,
1185 c->sectors_per_block_bits - (PAGE_SHIFT - SECTOR_SHIFT));
1188 *data_mode = DATA_MODE_VMALLOC;
1190 return __vmalloc(c->block_size, gfp_mask);
1194 * Free buffer's data.
1196 static void free_buffer_data(struct dm_bufio_client *c,
1197 void *data, unsigned char data_mode)
1199 switch (data_mode) {
1200 case DATA_MODE_SLAB:
1201 kmem_cache_free(c->slab_cache, data);
1204 case DATA_MODE_KMALLOC:
1208 case DATA_MODE_GET_FREE_PAGES:
1209 free_pages((unsigned long)data,
1210 c->sectors_per_block_bits - (PAGE_SHIFT - SECTOR_SHIFT));
1213 case DATA_MODE_VMALLOC:
1218 DMCRIT("dm_bufio_free_buffer_data: bad data mode: %d",
1225 * Allocate buffer and its data.
1227 static struct dm_buffer *alloc_buffer(struct dm_bufio_client *c, gfp_t gfp_mask)
1229 struct dm_buffer *b = kmem_cache_alloc(c->slab_buffer, gfp_mask);
1236 b->data = alloc_buffer_data(c, gfp_mask, &b->data_mode);
1238 kmem_cache_free(c->slab_buffer, b);
1241 adjust_total_allocated(b, false);
1243 #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
1250 * Free buffer and its data.
1252 static void free_buffer(struct dm_buffer *b)
1254 struct dm_bufio_client *c = b->c;
1256 adjust_total_allocated(b, true);
1257 free_buffer_data(c, b->data, b->data_mode);
1258 kmem_cache_free(c->slab_buffer, b);
1262 *--------------------------------------------------------------------------
1263 * Submit I/O on the buffer.
1265 * Bio interface is faster but it has some problems:
1266 * the vector list is limited (increasing this limit increases
1267 * memory-consumption per buffer, so it is not viable);
1269 * the memory must be direct-mapped, not vmalloced;
1271 * If the buffer is small enough (up to DM_BUFIO_INLINE_VECS pages) and
1272 * it is not vmalloced, try using the bio interface.
1274 * If the buffer is big, if it is vmalloced or if the underlying device
1275 * rejects the bio because it is too large, use dm-io layer to do the I/O.
1276 * The dm-io layer splits the I/O into multiple requests, avoiding the above
1278 *--------------------------------------------------------------------------
1282 * dm-io completion routine. It just calls b->bio.bi_end_io, pretending
1283 * that the request was handled directly with bio interface.
1285 static void dmio_complete(unsigned long error, void *context)
1287 struct dm_buffer *b = context;
1289 b->end_io(b, unlikely(error != 0) ? BLK_STS_IOERR : 0);
1292 static void use_dmio(struct dm_buffer *b, enum req_op op, sector_t sector,
1293 unsigned int n_sectors, unsigned int offset,
1294 unsigned short ioprio)
1297 struct dm_io_request io_req = {
1299 .notify.fn = dmio_complete,
1300 .notify.context = b,
1301 .client = b->c->dm_io,
1303 struct dm_io_region region = {
1309 if (b->data_mode != DATA_MODE_VMALLOC) {
1310 io_req.mem.type = DM_IO_KMEM;
1311 io_req.mem.ptr.addr = (char *)b->data + offset;
1313 io_req.mem.type = DM_IO_VMA;
1314 io_req.mem.ptr.vma = (char *)b->data + offset;
1317 r = dm_io(&io_req, 1, ®ion, NULL, ioprio);
1319 b->end_io(b, errno_to_blk_status(r));
1322 static void bio_complete(struct bio *bio)
1324 struct dm_buffer *b = bio->bi_private;
1325 blk_status_t status = bio->bi_status;
1329 b->end_io(b, status);
1332 static void use_bio(struct dm_buffer *b, enum req_op op, sector_t sector,
1333 unsigned int n_sectors, unsigned int offset,
1334 unsigned short ioprio)
1340 bio = bio_kmalloc(1, GFP_NOWAIT | __GFP_NORETRY | __GFP_NOWARN);
1342 use_dmio(b, op, sector, n_sectors, offset, ioprio);
1345 bio_init(bio, b->c->bdev, bio->bi_inline_vecs, 1, op);
1346 bio->bi_iter.bi_sector = sector;
1347 bio->bi_end_io = bio_complete;
1348 bio->bi_private = b;
1349 bio->bi_ioprio = ioprio;
1351 ptr = (char *)b->data + offset;
1352 len = n_sectors << SECTOR_SHIFT;
1354 bio_add_virt_nofail(bio, ptr, len);
1359 static inline sector_t block_to_sector(struct dm_bufio_client *c, sector_t block)
1363 if (likely(c->sectors_per_block_bits >= 0))
1364 sector = block << c->sectors_per_block_bits;
1366 sector = block * (c->block_size >> SECTOR_SHIFT);
1372 static void submit_io(struct dm_buffer *b, enum req_op op, unsigned short ioprio,
1373 void (*end_io)(struct dm_buffer *, blk_status_t))
1375 unsigned int n_sectors;
1377 unsigned int offset, end;
1381 sector = block_to_sector(b->c, b->block);
1383 if (op != REQ_OP_WRITE) {
1384 n_sectors = b->c->block_size >> SECTOR_SHIFT;
1387 if (b->c->write_callback)
1388 b->c->write_callback(b);
1389 offset = b->write_start;
1391 offset &= -DM_BUFIO_WRITE_ALIGN;
1392 end += DM_BUFIO_WRITE_ALIGN - 1;
1393 end &= -DM_BUFIO_WRITE_ALIGN;
1394 if (unlikely(end > b->c->block_size))
1395 end = b->c->block_size;
1397 sector += offset >> SECTOR_SHIFT;
1398 n_sectors = (end - offset) >> SECTOR_SHIFT;
1401 if (b->data_mode != DATA_MODE_VMALLOC)
1402 use_bio(b, op, sector, n_sectors, offset, ioprio);
1404 use_dmio(b, op, sector, n_sectors, offset, ioprio);
1408 *--------------------------------------------------------------
1409 * Writing dirty buffers
1410 *--------------------------------------------------------------
1414 * The endio routine for write.
1416 * Set the error, clear B_WRITING bit and wake anyone who was waiting on
1419 static void write_endio(struct dm_buffer *b, blk_status_t status)
1421 b->write_error = status;
1422 if (unlikely(status)) {
1423 struct dm_bufio_client *c = b->c;
1425 (void)cmpxchg(&c->async_write_error, 0,
1426 blk_status_to_errno(status));
1429 BUG_ON(!test_bit(B_WRITING, &b->state));
1431 smp_mb__before_atomic();
1432 clear_bit(B_WRITING, &b->state);
1433 smp_mb__after_atomic();
1435 wake_up_bit(&b->state, B_WRITING);
1439 * Initiate a write on a dirty buffer, but don't wait for it.
1441 * - If the buffer is not dirty, exit.
1442 * - If there some previous write going on, wait for it to finish (we can't
1443 * have two writes on the same buffer simultaneously).
1444 * - Submit our write and don't wait on it. We set B_WRITING indicating
1445 * that there is a write in progress.
1447 static void __write_dirty_buffer(struct dm_buffer *b,
1448 struct list_head *write_list)
1450 if (!test_bit(B_DIRTY, &b->state))
1453 clear_bit(B_DIRTY, &b->state);
1454 wait_on_bit_lock_io(&b->state, B_WRITING, TASK_UNINTERRUPTIBLE);
1456 b->write_start = b->dirty_start;
1457 b->write_end = b->dirty_end;
1460 submit_io(b, REQ_OP_WRITE, IOPRIO_DEFAULT, write_endio);
1462 list_add_tail(&b->write_list, write_list);
1465 static void __flush_write_list(struct list_head *write_list)
1467 struct blk_plug plug;
1469 blk_start_plug(&plug);
1470 while (!list_empty(write_list)) {
1471 struct dm_buffer *b =
1472 list_entry(write_list->next, struct dm_buffer, write_list);
1473 list_del(&b->write_list);
1474 submit_io(b, REQ_OP_WRITE, IOPRIO_DEFAULT, write_endio);
1477 blk_finish_plug(&plug);
1481 * Wait until any activity on the buffer finishes. Possibly write the
1482 * buffer if it is dirty. When this function finishes, there is no I/O
1483 * running on the buffer and the buffer is not dirty.
1485 static void __make_buffer_clean(struct dm_buffer *b)
1487 BUG_ON(atomic_read(&b->hold_count));
1489 /* smp_load_acquire() pairs with read_endio()'s smp_mb__before_atomic() */
1490 if (!smp_load_acquire(&b->state)) /* fast case */
1493 wait_on_bit_io(&b->state, B_READING, TASK_UNINTERRUPTIBLE);
1494 __write_dirty_buffer(b, NULL);
1495 wait_on_bit_io(&b->state, B_WRITING, TASK_UNINTERRUPTIBLE);
1498 static enum evict_result is_clean(struct dm_buffer *b, void *context)
1500 struct dm_bufio_client *c = context;
1502 /* These should never happen */
1503 if (WARN_ON_ONCE(test_bit(B_WRITING, &b->state)))
1504 return ER_DONT_EVICT;
1505 if (WARN_ON_ONCE(test_bit(B_DIRTY, &b->state)))
1506 return ER_DONT_EVICT;
1507 if (WARN_ON_ONCE(b->list_mode != LIST_CLEAN))
1508 return ER_DONT_EVICT;
1510 if (static_branch_unlikely(&no_sleep_enabled) && c->no_sleep &&
1511 unlikely(test_bit(B_READING, &b->state)))
1512 return ER_DONT_EVICT;
1517 static enum evict_result is_dirty(struct dm_buffer *b, void *context)
1519 /* These should never happen */
1520 if (WARN_ON_ONCE(test_bit(B_READING, &b->state)))
1521 return ER_DONT_EVICT;
1522 if (WARN_ON_ONCE(b->list_mode != LIST_DIRTY))
1523 return ER_DONT_EVICT;
1529 * Find some buffer that is not held by anybody, clean it, unlink it and
1532 static struct dm_buffer *__get_unclaimed_buffer(struct dm_bufio_client *c)
1534 struct dm_buffer *b;
1536 b = cache_evict(&c->cache, LIST_CLEAN, is_clean, c);
1538 /* this also waits for pending reads */
1539 __make_buffer_clean(b);
1543 if (static_branch_unlikely(&no_sleep_enabled) && c->no_sleep)
1546 b = cache_evict(&c->cache, LIST_DIRTY, is_dirty, NULL);
1548 __make_buffer_clean(b);
1556 * Wait until some other threads free some buffer or release hold count on
1559 * This function is entered with c->lock held, drops it and regains it
1562 static void __wait_for_free_buffer(struct dm_bufio_client *c)
1564 DECLARE_WAITQUEUE(wait, current);
1566 add_wait_queue(&c->free_buffer_wait, &wait);
1567 set_current_state(TASK_UNINTERRUPTIBLE);
1571 * It's possible to miss a wake up event since we don't always
1572 * hold c->lock when wake_up is called. So we have a timeout here,
1575 io_schedule_timeout(5 * HZ);
1577 remove_wait_queue(&c->free_buffer_wait, &wait);
1590 * Allocate a new buffer. If the allocation is not possible, wait until
1591 * some other thread frees a buffer.
1593 * May drop the lock and regain it.
1595 static struct dm_buffer *__alloc_buffer_wait_no_callback(struct dm_bufio_client *c, enum new_flag nf)
1597 struct dm_buffer *b;
1598 bool tried_noio_alloc = false;
1601 * dm-bufio is resistant to allocation failures (it just keeps
1602 * one buffer reserved in cases all the allocations fail).
1603 * So set flags to not try too hard:
1604 * GFP_NOWAIT: don't wait; if we need to sleep we'll release our
1605 * mutex and wait ourselves.
1606 * __GFP_NORETRY: don't retry and rather return failure
1607 * __GFP_NOMEMALLOC: don't use emergency reserves
1608 * __GFP_NOWARN: don't print a warning in case of failure
1610 * For debugging, if we set the cache size to 1, no new buffers will
1614 if (dm_bufio_cache_size_latch != 1) {
1615 b = alloc_buffer(c, GFP_NOWAIT | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
1620 if (nf == NF_PREFETCH)
1623 if (dm_bufio_cache_size_latch != 1 && !tried_noio_alloc) {
1625 b = alloc_buffer(c, GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
1629 tried_noio_alloc = true;
1632 if (!list_empty(&c->reserved_buffers)) {
1633 b = list_to_buffer(c->reserved_buffers.next);
1634 list_del(&b->lru.list);
1635 c->need_reserved_buffers++;
1640 b = __get_unclaimed_buffer(c);
1644 __wait_for_free_buffer(c);
1648 static struct dm_buffer *__alloc_buffer_wait(struct dm_bufio_client *c, enum new_flag nf)
1650 struct dm_buffer *b = __alloc_buffer_wait_no_callback(c, nf);
1655 if (c->alloc_callback)
1656 c->alloc_callback(b);
1662 * Free a buffer and wake other threads waiting for free buffers.
1664 static void __free_buffer_wake(struct dm_buffer *b)
1666 struct dm_bufio_client *c = b->c;
1669 if (!c->need_reserved_buffers)
1672 list_add(&b->lru.list, &c->reserved_buffers);
1673 c->need_reserved_buffers--;
1677 * We hold the bufio lock here, so no one can add entries to the
1678 * wait queue anyway.
1680 if (unlikely(waitqueue_active(&c->free_buffer_wait)))
1681 wake_up(&c->free_buffer_wait);
1684 static enum evict_result cleaned(struct dm_buffer *b, void *context)
1686 if (WARN_ON_ONCE(test_bit(B_READING, &b->state)))
1687 return ER_DONT_EVICT; /* should never happen */
1689 if (test_bit(B_DIRTY, &b->state) || test_bit(B_WRITING, &b->state))
1690 return ER_DONT_EVICT;
1695 static void __move_clean_buffers(struct dm_bufio_client *c)
1697 cache_mark_many(&c->cache, LIST_DIRTY, LIST_CLEAN, cleaned, NULL);
1700 struct write_context {
1702 struct list_head *write_list;
1705 static enum it_action write_one(struct dm_buffer *b, void *context)
1707 struct write_context *wc = context;
1709 if (wc->no_wait && test_bit(B_WRITING, &b->state))
1712 __write_dirty_buffer(b, wc->write_list);
1716 static void __write_dirty_buffers_async(struct dm_bufio_client *c, int no_wait,
1717 struct list_head *write_list)
1719 struct write_context wc = {.no_wait = no_wait, .write_list = write_list};
1721 __move_clean_buffers(c);
1722 cache_iterate(&c->cache, LIST_DIRTY, write_one, &wc);
1726 * Check if we're over watermark.
1727 * If we are over threshold_buffers, start freeing buffers.
1728 * If we're over "limit_buffers", block until we get under the limit.
1730 static void __check_watermark(struct dm_bufio_client *c,
1731 struct list_head *write_list)
1733 if (cache_count(&c->cache, LIST_DIRTY) >
1734 cache_count(&c->cache, LIST_CLEAN) * DM_BUFIO_WRITEBACK_RATIO)
1735 __write_dirty_buffers_async(c, 1, write_list);
1739 *--------------------------------------------------------------
1741 *--------------------------------------------------------------
1744 static void cache_put_and_wake(struct dm_bufio_client *c, struct dm_buffer *b)
1747 * Relying on waitqueue_active() is racey, but we sleep
1748 * with schedule_timeout anyway.
1750 if (cache_put(&c->cache, b) &&
1751 unlikely(waitqueue_active(&c->free_buffer_wait)))
1752 wake_up(&c->free_buffer_wait);
1756 * This assumes you have already checked the cache to see if the buffer
1757 * is already present (it will recheck after dropping the lock for allocation).
1759 static struct dm_buffer *__bufio_new(struct dm_bufio_client *c, sector_t block,
1760 enum new_flag nf, int *need_submit,
1761 struct list_head *write_list)
1763 struct dm_buffer *b, *new_b = NULL;
1767 /* This can't be called with NF_GET */
1768 if (WARN_ON_ONCE(nf == NF_GET))
1771 new_b = __alloc_buffer_wait(c, nf);
1776 * We've had a period where the mutex was unlocked, so need to
1777 * recheck the buffer tree.
1779 b = cache_get(&c->cache, block);
1781 __free_buffer_wake(new_b);
1785 __check_watermark(c, write_list);
1788 atomic_set(&b->hold_count, 1);
1789 WRITE_ONCE(b->last_accessed, jiffies);
1793 b->list_mode = LIST_CLEAN;
1798 b->state = 1 << B_READING;
1803 * We mustn't insert into the cache until the B_READING state
1804 * is set. Otherwise another thread could get it and use
1805 * it before it had been read.
1807 cache_insert(&c->cache, b);
1812 if (nf == NF_PREFETCH) {
1813 cache_put_and_wake(c, b);
1818 * Note: it is essential that we don't wait for the buffer to be
1819 * read if dm_bufio_get function is used. Both dm_bufio_get and
1820 * dm_bufio_prefetch can be used in the driver request routine.
1821 * If the user called both dm_bufio_prefetch and dm_bufio_get on
1822 * the same buffer, it would deadlock if we waited.
1824 if (nf == NF_GET && unlikely(test_bit_acquire(B_READING, &b->state))) {
1825 cache_put_and_wake(c, b);
1833 * The endio routine for reading: set the error, clear the bit and wake up
1834 * anyone waiting on the buffer.
1836 static void read_endio(struct dm_buffer *b, blk_status_t status)
1838 b->read_error = status;
1840 BUG_ON(!test_bit(B_READING, &b->state));
1842 smp_mb__before_atomic();
1843 clear_bit(B_READING, &b->state);
1844 smp_mb__after_atomic();
1846 wake_up_bit(&b->state, B_READING);
1850 * A common routine for dm_bufio_new and dm_bufio_read. Operation of these
1851 * functions is similar except that dm_bufio_new doesn't read the
1852 * buffer from the disk (assuming that the caller overwrites all the data
1853 * and uses dm_bufio_mark_buffer_dirty to write new data back).
1855 static void *new_read(struct dm_bufio_client *c, sector_t block,
1856 enum new_flag nf, struct dm_buffer **bp,
1857 unsigned short ioprio)
1859 int need_submit = 0;
1860 struct dm_buffer *b;
1862 LIST_HEAD(write_list);
1867 * Fast path, hopefully the block is already in the cache. No need
1868 * to get the client lock for this.
1870 b = cache_get(&c->cache, block);
1872 if (nf == NF_PREFETCH) {
1873 cache_put_and_wake(c, b);
1878 * Note: it is essential that we don't wait for the buffer to be
1879 * read if dm_bufio_get function is used. Both dm_bufio_get and
1880 * dm_bufio_prefetch can be used in the driver request routine.
1881 * If the user called both dm_bufio_prefetch and dm_bufio_get on
1882 * the same buffer, it would deadlock if we waited.
1884 if (nf == NF_GET && unlikely(test_bit_acquire(B_READING, &b->state))) {
1885 cache_put_and_wake(c, b);
1895 b = __bufio_new(c, block, nf, &need_submit, &write_list);
1899 #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
1900 if (b && (atomic_read(&b->hold_count) == 1))
1901 buffer_record_stack(b);
1904 __flush_write_list(&write_list);
1910 submit_io(b, REQ_OP_READ, ioprio, read_endio);
1912 if (nf != NF_GET) /* we already tested this condition above */
1913 wait_on_bit_io(&b->state, B_READING, TASK_UNINTERRUPTIBLE);
1915 if (b->read_error) {
1916 int error = blk_status_to_errno(b->read_error);
1918 dm_bufio_release(b);
1920 return ERR_PTR(error);
1928 void *dm_bufio_get(struct dm_bufio_client *c, sector_t block,
1929 struct dm_buffer **bp)
1931 return new_read(c, block, NF_GET, bp, IOPRIO_DEFAULT);
1933 EXPORT_SYMBOL_GPL(dm_bufio_get);
1935 static void *__dm_bufio_read(struct dm_bufio_client *c, sector_t block,
1936 struct dm_buffer **bp, unsigned short ioprio)
1938 if (WARN_ON_ONCE(dm_bufio_in_request()))
1939 return ERR_PTR(-EINVAL);
1941 return new_read(c, block, NF_READ, bp, ioprio);
1944 void *dm_bufio_read(struct dm_bufio_client *c, sector_t block,
1945 struct dm_buffer **bp)
1947 return __dm_bufio_read(c, block, bp, IOPRIO_DEFAULT);
1949 EXPORT_SYMBOL_GPL(dm_bufio_read);
1951 void *dm_bufio_read_with_ioprio(struct dm_bufio_client *c, sector_t block,
1952 struct dm_buffer **bp, unsigned short ioprio)
1954 return __dm_bufio_read(c, block, bp, ioprio);
1956 EXPORT_SYMBOL_GPL(dm_bufio_read_with_ioprio);
1958 void *dm_bufio_new(struct dm_bufio_client *c, sector_t block,
1959 struct dm_buffer **bp)
1961 if (WARN_ON_ONCE(dm_bufio_in_request()))
1962 return ERR_PTR(-EINVAL);
1964 return new_read(c, block, NF_FRESH, bp, IOPRIO_DEFAULT);
1966 EXPORT_SYMBOL_GPL(dm_bufio_new);
1968 static void __dm_bufio_prefetch(struct dm_bufio_client *c,
1969 sector_t block, unsigned int n_blocks,
1970 unsigned short ioprio)
1972 struct blk_plug plug;
1974 LIST_HEAD(write_list);
1976 if (WARN_ON_ONCE(dm_bufio_in_request()))
1977 return; /* should never happen */
1979 blk_start_plug(&plug);
1981 for (; n_blocks--; block++) {
1983 struct dm_buffer *b;
1985 b = cache_get(&c->cache, block);
1987 /* already in cache */
1988 cache_put_and_wake(c, b);
1993 b = __bufio_new(c, block, NF_PREFETCH, &need_submit,
1995 if (unlikely(!list_empty(&write_list))) {
1997 blk_finish_plug(&plug);
1998 __flush_write_list(&write_list);
1999 blk_start_plug(&plug);
2002 if (unlikely(b != NULL)) {
2006 submit_io(b, REQ_OP_READ, ioprio, read_endio);
2007 dm_bufio_release(b);
2019 blk_finish_plug(&plug);
2022 void dm_bufio_prefetch(struct dm_bufio_client *c, sector_t block, unsigned int n_blocks)
2024 return __dm_bufio_prefetch(c, block, n_blocks, IOPRIO_DEFAULT);
2026 EXPORT_SYMBOL_GPL(dm_bufio_prefetch);
2028 void dm_bufio_prefetch_with_ioprio(struct dm_bufio_client *c, sector_t block,
2029 unsigned int n_blocks, unsigned short ioprio)
2031 return __dm_bufio_prefetch(c, block, n_blocks, ioprio);
2033 EXPORT_SYMBOL_GPL(dm_bufio_prefetch_with_ioprio);
2035 void dm_bufio_release(struct dm_buffer *b)
2037 struct dm_bufio_client *c = b->c;
2040 * If there were errors on the buffer, and the buffer is not
2041 * to be written, free the buffer. There is no point in caching
2044 if ((b->read_error || b->write_error) &&
2045 !test_bit_acquire(B_READING, &b->state) &&
2046 !test_bit(B_WRITING, &b->state) &&
2047 !test_bit(B_DIRTY, &b->state)) {
2050 /* cache remove can fail if there are other holders */
2051 if (cache_remove(&c->cache, b)) {
2052 __free_buffer_wake(b);
2060 cache_put_and_wake(c, b);
2062 EXPORT_SYMBOL_GPL(dm_bufio_release);
2064 void dm_bufio_mark_partial_buffer_dirty(struct dm_buffer *b,
2065 unsigned int start, unsigned int end)
2067 struct dm_bufio_client *c = b->c;
2069 BUG_ON(start >= end);
2070 BUG_ON(end > b->c->block_size);
2074 BUG_ON(test_bit(B_READING, &b->state));
2076 if (!test_and_set_bit(B_DIRTY, &b->state)) {
2077 b->dirty_start = start;
2079 cache_mark(&c->cache, b, LIST_DIRTY);
2081 if (start < b->dirty_start)
2082 b->dirty_start = start;
2083 if (end > b->dirty_end)
2089 EXPORT_SYMBOL_GPL(dm_bufio_mark_partial_buffer_dirty);
2091 void dm_bufio_mark_buffer_dirty(struct dm_buffer *b)
2093 dm_bufio_mark_partial_buffer_dirty(b, 0, b->c->block_size);
2095 EXPORT_SYMBOL_GPL(dm_bufio_mark_buffer_dirty);
2097 void dm_bufio_write_dirty_buffers_async(struct dm_bufio_client *c)
2099 LIST_HEAD(write_list);
2101 if (WARN_ON_ONCE(dm_bufio_in_request()))
2102 return; /* should never happen */
2105 __write_dirty_buffers_async(c, 0, &write_list);
2107 __flush_write_list(&write_list);
2109 EXPORT_SYMBOL_GPL(dm_bufio_write_dirty_buffers_async);
2112 * For performance, it is essential that the buffers are written asynchronously
2113 * and simultaneously (so that the block layer can merge the writes) and then
2116 * Finally, we flush hardware disk cache.
2118 static bool is_writing(struct lru_entry *e, void *context)
2120 struct dm_buffer *b = le_to_buffer(e);
2122 return test_bit(B_WRITING, &b->state);
2125 int dm_bufio_write_dirty_buffers(struct dm_bufio_client *c)
2128 unsigned long nr_buffers;
2129 struct lru_entry *e;
2132 LIST_HEAD(write_list);
2135 __write_dirty_buffers_async(c, 0, &write_list);
2137 __flush_write_list(&write_list);
2140 nr_buffers = cache_count(&c->cache, LIST_DIRTY);
2141 lru_iter_begin(&c->cache.lru[LIST_DIRTY], &it);
2142 while ((e = lru_iter_next(&it, is_writing, c))) {
2143 struct dm_buffer *b = le_to_buffer(e);
2144 __cache_inc_buffer(b);
2146 BUG_ON(test_bit(B_READING, &b->state));
2151 wait_on_bit_io(&b->state, B_WRITING, TASK_UNINTERRUPTIBLE);
2154 wait_on_bit_io(&b->state, B_WRITING, TASK_UNINTERRUPTIBLE);
2157 if (!test_bit(B_DIRTY, &b->state) && !test_bit(B_WRITING, &b->state))
2158 cache_mark(&c->cache, b, LIST_CLEAN);
2160 cache_put_and_wake(c, b);
2166 wake_up(&c->free_buffer_wait);
2169 a = xchg(&c->async_write_error, 0);
2170 f = dm_bufio_issue_flush(c);
2176 EXPORT_SYMBOL_GPL(dm_bufio_write_dirty_buffers);
2179 * Use dm-io to send an empty barrier to flush the device.
2181 int dm_bufio_issue_flush(struct dm_bufio_client *c)
2183 struct dm_io_request io_req = {
2184 .bi_opf = REQ_OP_WRITE | REQ_PREFLUSH | REQ_SYNC,
2185 .mem.type = DM_IO_KMEM,
2186 .mem.ptr.addr = NULL,
2189 struct dm_io_region io_reg = {
2195 if (WARN_ON_ONCE(dm_bufio_in_request()))
2198 return dm_io(&io_req, 1, &io_reg, NULL, IOPRIO_DEFAULT);
2200 EXPORT_SYMBOL_GPL(dm_bufio_issue_flush);
2203 * Use dm-io to send a discard request to flush the device.
2205 int dm_bufio_issue_discard(struct dm_bufio_client *c, sector_t block, sector_t count)
2207 struct dm_io_request io_req = {
2208 .bi_opf = REQ_OP_DISCARD | REQ_SYNC,
2209 .mem.type = DM_IO_KMEM,
2210 .mem.ptr.addr = NULL,
2213 struct dm_io_region io_reg = {
2215 .sector = block_to_sector(c, block),
2216 .count = block_to_sector(c, count),
2219 if (WARN_ON_ONCE(dm_bufio_in_request()))
2220 return -EINVAL; /* discards are optional */
2222 return dm_io(&io_req, 1, &io_reg, NULL, IOPRIO_DEFAULT);
2224 EXPORT_SYMBOL_GPL(dm_bufio_issue_discard);
2226 static void forget_buffer(struct dm_bufio_client *c, sector_t block)
2228 struct dm_buffer *b;
2230 b = cache_get(&c->cache, block);
2232 if (likely(!smp_load_acquire(&b->state))) {
2233 if (cache_remove(&c->cache, b))
2234 __free_buffer_wake(b);
2236 cache_put_and_wake(c, b);
2238 cache_put_and_wake(c, b);
2244 * Free the given buffer.
2246 * This is just a hint, if the buffer is in use or dirty, this function
2249 void dm_bufio_forget(struct dm_bufio_client *c, sector_t block)
2252 forget_buffer(c, block);
2255 EXPORT_SYMBOL_GPL(dm_bufio_forget);
2257 static enum evict_result idle(struct dm_buffer *b, void *context)
2259 return b->state ? ER_DONT_EVICT : ER_EVICT;
2262 void dm_bufio_forget_buffers(struct dm_bufio_client *c, sector_t block, sector_t n_blocks)
2265 cache_remove_range(&c->cache, block, block + n_blocks, idle, __free_buffer_wake);
2268 EXPORT_SYMBOL_GPL(dm_bufio_forget_buffers);
2270 void dm_bufio_set_minimum_buffers(struct dm_bufio_client *c, unsigned int n)
2272 c->minimum_buffers = n;
2274 EXPORT_SYMBOL_GPL(dm_bufio_set_minimum_buffers);
2276 unsigned int dm_bufio_get_block_size(struct dm_bufio_client *c)
2278 return c->block_size;
2280 EXPORT_SYMBOL_GPL(dm_bufio_get_block_size);
2282 sector_t dm_bufio_get_device_size(struct dm_bufio_client *c)
2284 sector_t s = bdev_nr_sectors(c->bdev);
2290 if (likely(c->sectors_per_block_bits >= 0))
2291 s >>= c->sectors_per_block_bits;
2293 sector_div(s, c->block_size >> SECTOR_SHIFT);
2296 EXPORT_SYMBOL_GPL(dm_bufio_get_device_size);
2298 struct dm_io_client *dm_bufio_get_dm_io_client(struct dm_bufio_client *c)
2302 EXPORT_SYMBOL_GPL(dm_bufio_get_dm_io_client);
2304 sector_t dm_bufio_get_block_number(struct dm_buffer *b)
2308 EXPORT_SYMBOL_GPL(dm_bufio_get_block_number);
2310 void *dm_bufio_get_block_data(struct dm_buffer *b)
2314 EXPORT_SYMBOL_GPL(dm_bufio_get_block_data);
2316 void *dm_bufio_get_aux_data(struct dm_buffer *b)
2320 EXPORT_SYMBOL_GPL(dm_bufio_get_aux_data);
2322 struct dm_bufio_client *dm_bufio_get_client(struct dm_buffer *b)
2326 EXPORT_SYMBOL_GPL(dm_bufio_get_client);
2328 static enum it_action warn_leak(struct dm_buffer *b, void *context)
2330 bool *warned = context;
2332 WARN_ON(!(*warned));
2334 DMERR("leaked buffer %llx, hold count %u, list %d",
2335 (unsigned long long)b->block, atomic_read(&b->hold_count), b->list_mode);
2336 #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
2337 stack_trace_print(b->stack_entries, b->stack_len, 1);
2338 /* mark unclaimed to avoid WARN_ON at end of drop_buffers() */
2339 atomic_set(&b->hold_count, 0);
2344 static void drop_buffers(struct dm_bufio_client *c)
2347 struct dm_buffer *b;
2349 if (WARN_ON(dm_bufio_in_request()))
2350 return; /* should never happen */
2353 * An optimization so that the buffers are not written one-by-one.
2355 dm_bufio_write_dirty_buffers_async(c);
2359 while ((b = __get_unclaimed_buffer(c)))
2360 __free_buffer_wake(b);
2362 for (i = 0; i < LIST_SIZE; i++) {
2363 bool warned = false;
2365 cache_iterate(&c->cache, i, warn_leak, &warned);
2368 #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
2369 while ((b = __get_unclaimed_buffer(c)))
2370 __free_buffer_wake(b);
2373 for (i = 0; i < LIST_SIZE; i++)
2374 WARN_ON(cache_count(&c->cache, i));
2379 static unsigned long get_retain_buffers(struct dm_bufio_client *c)
2381 unsigned long retain_bytes = READ_ONCE(dm_bufio_retain_bytes);
2383 if (likely(c->sectors_per_block_bits >= 0))
2384 retain_bytes >>= c->sectors_per_block_bits + SECTOR_SHIFT;
2386 retain_bytes /= c->block_size;
2388 return retain_bytes;
2391 static void __scan(struct dm_bufio_client *c)
2394 struct dm_buffer *b;
2395 unsigned long freed = 0;
2396 unsigned long retain_target = get_retain_buffers(c);
2397 unsigned long count = cache_total(&c->cache);
2399 for (l = 0; l < LIST_SIZE; l++) {
2401 if (count - freed <= retain_target)
2402 atomic_long_set(&c->need_shrink, 0);
2403 if (!atomic_long_read(&c->need_shrink))
2406 b = cache_evict(&c->cache, l,
2407 l == LIST_CLEAN ? is_clean : is_dirty, c);
2411 __make_buffer_clean(b);
2412 __free_buffer_wake(b);
2414 atomic_long_dec(&c->need_shrink);
2417 if (unlikely(freed % SCAN_RESCHED_CYCLE == 0)) {
2426 static void shrink_work(struct work_struct *w)
2428 struct dm_bufio_client *c = container_of(w, struct dm_bufio_client, shrink_work);
2435 static unsigned long dm_bufio_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
2437 struct dm_bufio_client *c;
2439 c = shrink->private_data;
2440 atomic_long_add(sc->nr_to_scan, &c->need_shrink);
2441 queue_work(dm_bufio_wq, &c->shrink_work);
2443 return sc->nr_to_scan;
2446 static unsigned long dm_bufio_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
2448 struct dm_bufio_client *c = shrink->private_data;
2449 unsigned long count = cache_total(&c->cache);
2450 unsigned long retain_target = get_retain_buffers(c);
2451 unsigned long queued_for_cleanup = atomic_long_read(&c->need_shrink);
2453 if (unlikely(count < retain_target))
2456 count -= retain_target;
2458 if (unlikely(count < queued_for_cleanup))
2461 count -= queued_for_cleanup;
2467 * Create the buffering interface
2469 struct dm_bufio_client *dm_bufio_client_create(struct block_device *bdev, unsigned int block_size,
2470 unsigned int reserved_buffers, unsigned int aux_size,
2471 void (*alloc_callback)(struct dm_buffer *),
2472 void (*write_callback)(struct dm_buffer *),
2476 unsigned int num_locks;
2477 struct dm_bufio_client *c;
2479 static atomic_t seqno = ATOMIC_INIT(0);
2481 if (!block_size || block_size & ((1 << SECTOR_SHIFT) - 1)) {
2482 DMERR("%s: block size not specified or is not multiple of 512b", __func__);
2487 num_locks = dm_num_hash_locks();
2488 c = kzalloc(sizeof(*c) + (num_locks * sizeof(struct buffer_tree)), GFP_KERNEL);
2493 cache_init(&c->cache, num_locks, (flags & DM_BUFIO_CLIENT_NO_SLEEP) != 0);
2496 c->block_size = block_size;
2497 if (is_power_of_2(block_size))
2498 c->sectors_per_block_bits = __ffs(block_size) - SECTOR_SHIFT;
2500 c->sectors_per_block_bits = -1;
2502 c->alloc_callback = alloc_callback;
2503 c->write_callback = write_callback;
2505 if (flags & DM_BUFIO_CLIENT_NO_SLEEP) {
2507 static_branch_inc(&no_sleep_enabled);
2510 mutex_init(&c->lock);
2511 spin_lock_init(&c->spinlock);
2512 INIT_LIST_HEAD(&c->reserved_buffers);
2513 c->need_reserved_buffers = reserved_buffers;
2515 dm_bufio_set_minimum_buffers(c, DM_BUFIO_MIN_BUFFERS);
2517 init_waitqueue_head(&c->free_buffer_wait);
2518 c->async_write_error = 0;
2520 c->dm_io = dm_io_client_create();
2521 if (IS_ERR(c->dm_io)) {
2522 r = PTR_ERR(c->dm_io);
2526 if (block_size <= KMALLOC_MAX_SIZE && !is_power_of_2(block_size)) {
2527 unsigned int align = min(1U << __ffs(block_size), (unsigned int)PAGE_SIZE);
2529 snprintf(slab_name, sizeof(slab_name), "dm_bufio_cache-%u-%u",
2530 block_size, atomic_inc_return(&seqno));
2531 c->slab_cache = kmem_cache_create(slab_name, block_size, align,
2532 SLAB_RECLAIM_ACCOUNT, NULL);
2533 if (!c->slab_cache) {
2539 snprintf(slab_name, sizeof(slab_name), "dm_bufio_buffer-%u-%u",
2540 aux_size, atomic_inc_return(&seqno));
2542 snprintf(slab_name, sizeof(slab_name), "dm_bufio_buffer-%u",
2543 atomic_inc_return(&seqno));
2544 c->slab_buffer = kmem_cache_create(slab_name, sizeof(struct dm_buffer) + aux_size,
2545 0, SLAB_RECLAIM_ACCOUNT, NULL);
2546 if (!c->slab_buffer) {
2551 while (c->need_reserved_buffers) {
2552 struct dm_buffer *b = alloc_buffer(c, GFP_KERNEL);
2558 __free_buffer_wake(b);
2561 INIT_WORK(&c->shrink_work, shrink_work);
2562 atomic_long_set(&c->need_shrink, 0);
2564 c->shrinker = shrinker_alloc(0, "dm-bufio:(%u:%u)",
2565 MAJOR(bdev->bd_dev), MINOR(bdev->bd_dev));
2571 c->shrinker->count_objects = dm_bufio_shrink_count;
2572 c->shrinker->scan_objects = dm_bufio_shrink_scan;
2573 c->shrinker->seeks = 1;
2574 c->shrinker->batch = 0;
2575 c->shrinker->private_data = c;
2577 shrinker_register(c->shrinker);
2579 mutex_lock(&dm_bufio_clients_lock);
2580 dm_bufio_client_count++;
2581 list_add(&c->client_list, &dm_bufio_all_clients);
2582 __cache_size_refresh();
2583 mutex_unlock(&dm_bufio_clients_lock);
2588 while (!list_empty(&c->reserved_buffers)) {
2589 struct dm_buffer *b = list_to_buffer(c->reserved_buffers.next);
2591 list_del(&b->lru.list);
2594 kmem_cache_destroy(c->slab_cache);
2595 kmem_cache_destroy(c->slab_buffer);
2596 dm_io_client_destroy(c->dm_io);
2598 mutex_destroy(&c->lock);
2600 static_branch_dec(&no_sleep_enabled);
2605 EXPORT_SYMBOL_GPL(dm_bufio_client_create);
2608 * Free the buffering interface.
2609 * It is required that there are no references on any buffers.
2611 void dm_bufio_client_destroy(struct dm_bufio_client *c)
2617 shrinker_free(c->shrinker);
2618 flush_work(&c->shrink_work);
2620 mutex_lock(&dm_bufio_clients_lock);
2622 list_del(&c->client_list);
2623 dm_bufio_client_count--;
2624 __cache_size_refresh();
2626 mutex_unlock(&dm_bufio_clients_lock);
2628 WARN_ON(c->need_reserved_buffers);
2630 while (!list_empty(&c->reserved_buffers)) {
2631 struct dm_buffer *b = list_to_buffer(c->reserved_buffers.next);
2633 list_del(&b->lru.list);
2637 for (i = 0; i < LIST_SIZE; i++)
2638 if (cache_count(&c->cache, i))
2639 DMERR("leaked buffer count %d: %lu", i, cache_count(&c->cache, i));
2641 for (i = 0; i < LIST_SIZE; i++)
2642 WARN_ON(cache_count(&c->cache, i));
2644 cache_destroy(&c->cache);
2645 kmem_cache_destroy(c->slab_cache);
2646 kmem_cache_destroy(c->slab_buffer);
2647 dm_io_client_destroy(c->dm_io);
2648 mutex_destroy(&c->lock);
2650 static_branch_dec(&no_sleep_enabled);
2653 EXPORT_SYMBOL_GPL(dm_bufio_client_destroy);
2655 void dm_bufio_client_reset(struct dm_bufio_client *c)
2658 flush_work(&c->shrink_work);
2660 EXPORT_SYMBOL_GPL(dm_bufio_client_reset);
2662 void dm_bufio_set_sector_offset(struct dm_bufio_client *c, sector_t start)
2666 EXPORT_SYMBOL_GPL(dm_bufio_set_sector_offset);
2668 /*--------------------------------------------------------------*/
2671 * Global cleanup tries to evict the oldest buffers from across _all_
2672 * the clients. It does this by repeatedly evicting a few buffers from
2673 * the client that holds the oldest buffer. It's approximate, but hopefully
2676 static struct dm_bufio_client *__pop_client(void)
2678 struct list_head *h;
2680 if (list_empty(&dm_bufio_all_clients))
2683 h = dm_bufio_all_clients.next;
2685 return container_of(h, struct dm_bufio_client, client_list);
2689 * Inserts the client in the global client list based on its
2690 * 'oldest_buffer' field.
2692 static void __insert_client(struct dm_bufio_client *new_client)
2694 struct dm_bufio_client *c;
2695 struct list_head *h = dm_bufio_all_clients.next;
2697 while (h != &dm_bufio_all_clients) {
2698 c = container_of(h, struct dm_bufio_client, client_list);
2699 if (time_after_eq(c->oldest_buffer, new_client->oldest_buffer))
2704 list_add_tail(&new_client->client_list, h);
2707 static enum evict_result select_for_evict(struct dm_buffer *b, void *context)
2709 /* In no-sleep mode, we cannot wait on IO. */
2710 if (static_branch_unlikely(&no_sleep_enabled) && b->c->no_sleep) {
2711 if (test_bit_acquire(B_READING, &b->state) ||
2712 test_bit(B_WRITING, &b->state) ||
2713 test_bit(B_DIRTY, &b->state))
2714 return ER_DONT_EVICT;
2719 static unsigned long __evict_a_few(unsigned long nr_buffers)
2721 struct dm_bufio_client *c;
2722 unsigned long oldest_buffer = jiffies;
2723 unsigned long last_accessed;
2724 unsigned long count;
2725 struct dm_buffer *b;
2733 for (count = 0; count < nr_buffers; count++) {
2734 b = cache_evict(&c->cache, LIST_CLEAN, select_for_evict, NULL);
2738 last_accessed = READ_ONCE(b->last_accessed);
2739 if (time_after_eq(oldest_buffer, last_accessed))
2740 oldest_buffer = last_accessed;
2742 __make_buffer_clean(b);
2743 __free_buffer_wake(b);
2751 c->oldest_buffer = oldest_buffer;
2757 static void check_watermarks(void)
2759 LIST_HEAD(write_list);
2760 struct dm_bufio_client *c;
2762 mutex_lock(&dm_bufio_clients_lock);
2763 list_for_each_entry(c, &dm_bufio_all_clients, client_list) {
2765 __check_watermark(c, &write_list);
2768 mutex_unlock(&dm_bufio_clients_lock);
2770 __flush_write_list(&write_list);
2773 static void evict_old(void)
2775 unsigned long threshold = dm_bufio_cache_size -
2776 dm_bufio_cache_size / DM_BUFIO_LOW_WATERMARK_RATIO;
2778 mutex_lock(&dm_bufio_clients_lock);
2779 while (dm_bufio_current_allocated > threshold) {
2780 if (!__evict_a_few(64))
2784 mutex_unlock(&dm_bufio_clients_lock);
2787 static void do_global_cleanup(struct work_struct *w)
2794 *--------------------------------------------------------------
2796 *--------------------------------------------------------------
2800 * This is called only once for the whole dm_bufio module.
2801 * It initializes memory limit.
2803 static int __init dm_bufio_init(void)
2807 dm_bufio_allocated_kmem_cache = 0;
2808 dm_bufio_allocated_kmalloc = 0;
2809 dm_bufio_allocated_get_free_pages = 0;
2810 dm_bufio_allocated_vmalloc = 0;
2811 dm_bufio_current_allocated = 0;
2813 mem = (__u64)mult_frac(totalram_pages() - totalhigh_pages(),
2814 DM_BUFIO_MEMORY_PERCENT, 100) << PAGE_SHIFT;
2816 if (mem > ULONG_MAX)
2820 if (mem > mult_frac(VMALLOC_TOTAL, DM_BUFIO_VMALLOC_PERCENT, 100))
2821 mem = mult_frac(VMALLOC_TOTAL, DM_BUFIO_VMALLOC_PERCENT, 100);
2824 dm_bufio_default_cache_size = mem;
2826 mutex_lock(&dm_bufio_clients_lock);
2827 __cache_size_refresh();
2828 mutex_unlock(&dm_bufio_clients_lock);
2830 dm_bufio_wq = alloc_workqueue("dm_bufio_cache", WQ_MEM_RECLAIM, 0);
2834 INIT_WORK(&dm_bufio_replacement_work, do_global_cleanup);
2840 * This is called once when unloading the dm_bufio module.
2842 static void __exit dm_bufio_exit(void)
2846 destroy_workqueue(dm_bufio_wq);
2848 if (dm_bufio_client_count) {
2849 DMCRIT("%s: dm_bufio_client_count leaked: %d",
2850 __func__, dm_bufio_client_count);
2854 if (dm_bufio_current_allocated) {
2855 DMCRIT("%s: dm_bufio_current_allocated leaked: %lu",
2856 __func__, dm_bufio_current_allocated);
2860 if (dm_bufio_allocated_get_free_pages) {
2861 DMCRIT("%s: dm_bufio_allocated_get_free_pages leaked: %lu",
2862 __func__, dm_bufio_allocated_get_free_pages);
2866 if (dm_bufio_allocated_vmalloc) {
2867 DMCRIT("%s: dm_bufio_vmalloc leaked: %lu",
2868 __func__, dm_bufio_allocated_vmalloc);
2872 WARN_ON(bug); /* leaks are not worth crashing the system */
2875 module_init(dm_bufio_init)
2876 module_exit(dm_bufio_exit)
2878 module_param_named(max_cache_size_bytes, dm_bufio_cache_size, ulong, 0644);
2879 MODULE_PARM_DESC(max_cache_size_bytes, "Size of metadata cache");
2881 module_param_named(max_age_seconds, dm_bufio_max_age, uint, 0644);
2882 MODULE_PARM_DESC(max_age_seconds, "No longer does anything");
2884 module_param_named(retain_bytes, dm_bufio_retain_bytes, ulong, 0644);
2885 MODULE_PARM_DESC(retain_bytes, "Try to keep at least this many bytes cached in memory");
2887 module_param_named(peak_allocated_bytes, dm_bufio_peak_allocated, ulong, 0644);
2888 MODULE_PARM_DESC(peak_allocated_bytes, "Tracks the maximum allocated memory");
2890 module_param_named(allocated_kmem_cache_bytes, dm_bufio_allocated_kmem_cache, ulong, 0444);
2891 MODULE_PARM_DESC(allocated_kmem_cache_bytes, "Memory allocated with kmem_cache_alloc");
2893 module_param_named(allocated_kmalloc_bytes, dm_bufio_allocated_kmalloc, ulong, 0444);
2894 MODULE_PARM_DESC(allocated_kmalloc_bytes, "Memory allocated with kmalloc_alloc");
2896 module_param_named(allocated_get_free_pages_bytes, dm_bufio_allocated_get_free_pages, ulong, 0444);
2897 MODULE_PARM_DESC(allocated_get_free_pages_bytes, "Memory allocated with get_free_pages");
2899 module_param_named(allocated_vmalloc_bytes, dm_bufio_allocated_vmalloc, ulong, 0444);
2900 MODULE_PARM_DESC(allocated_vmalloc_bytes, "Memory allocated with vmalloc");
2902 module_param_named(current_allocated_bytes, dm_bufio_current_allocated, ulong, 0444);
2903 MODULE_PARM_DESC(current_allocated_bytes, "Memory currently used by the cache");
2905 MODULE_AUTHOR("Mikulas Patocka <dm-devel@lists.linux.dev>");
2906 MODULE_DESCRIPTION(DM_NAME " buffered I/O library");
2907 MODULE_LICENSE("GPL");