1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 2009-2011 Red Hat, Inc.
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>
24 #define DM_MSG_PREFIX "bufio"
27 * Memory management policy:
28 * Limit the number of buffers to DM_BUFIO_MEMORY_PERCENT of main memory
29 * or DM_BUFIO_VMALLOC_PERCENT of vmalloc memory (whichever is lower).
30 * Always allocate at least DM_BUFIO_MIN_BUFFERS buffers.
31 * Start background writeback when there are DM_BUFIO_WRITEBACK_PERCENT
34 #define DM_BUFIO_MIN_BUFFERS 8
36 #define DM_BUFIO_MEMORY_PERCENT 2
37 #define DM_BUFIO_VMALLOC_PERCENT 25
38 #define DM_BUFIO_WRITEBACK_RATIO 3
39 #define DM_BUFIO_LOW_WATERMARK_RATIO 16
42 * Check buffer ages in this interval (seconds)
44 #define DM_BUFIO_WORK_TIMER_SECS 30
47 * Free buffers when they are older than this (seconds)
49 #define DM_BUFIO_DEFAULT_AGE_SECS 300
52 * The nr of bytes of cached data to keep around.
54 #define DM_BUFIO_DEFAULT_RETAIN_BYTES (256 * 1024)
57 * Align buffer writes to this boundary.
58 * Tests show that SSDs have the highest IOPS when using 4k writes.
60 #define DM_BUFIO_WRITE_ALIGN 4096
63 * dm_buffer->list_mode
71 * All buffers are linked to buffer_tree with their node field.
73 * Clean buffers that are not being written (B_WRITING not set)
74 * are linked to lru[LIST_CLEAN] with their lru_list field.
76 * Dirty and clean buffers that are being written are linked to
77 * lru[LIST_DIRTY] with their lru_list field. When the write
78 * finishes, the buffer cannot be relinked immediately (because we
79 * are in an interrupt context and relinking requires process
80 * context), so some clean-not-writing buffers can be held on
81 * dirty_lru too. They are later added to lru in the process
84 struct dm_bufio_client {
89 struct list_head lru[LIST_SIZE];
90 unsigned long n_buffers[LIST_SIZE];
92 struct block_device *bdev;
93 unsigned int block_size;
94 s8 sectors_per_block_bits;
95 void (*alloc_callback)(struct dm_buffer *buf);
96 void (*write_callback)(struct dm_buffer *buf);
97 struct kmem_cache *slab_buffer;
98 struct kmem_cache *slab_cache;
99 struct dm_io_client *dm_io;
101 struct list_head reserved_buffers;
102 unsigned int need_reserved_buffers;
104 unsigned int minimum_buffers;
106 struct rb_root buffer_tree;
107 wait_queue_head_t free_buffer_wait;
111 int async_write_error;
113 struct list_head client_list;
115 struct shrinker shrinker;
116 struct work_struct shrink_work;
117 atomic_long_t need_shrink;
128 * Describes how the block was allocated:
129 * kmem_cache_alloc(), __get_free_pages() or vmalloc().
130 * See the comment at alloc_buffer_data.
134 DATA_MODE_GET_FREE_PAGES = 1,
135 DATA_MODE_VMALLOC = 2,
141 struct list_head lru_list;
142 struct list_head global_list;
145 unsigned char data_mode; /* DATA_MODE_* */
146 unsigned char list_mode; /* LIST_* */
147 blk_status_t read_error;
148 blk_status_t write_error;
149 unsigned int accessed;
150 unsigned int hold_count;
152 unsigned long last_accessed;
153 unsigned int dirty_start;
154 unsigned int dirty_end;
155 unsigned int write_start;
156 unsigned int write_end;
157 struct dm_bufio_client *c;
158 struct list_head write_list;
159 void (*end_io)(struct dm_buffer *buf, blk_status_t stat);
160 #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
162 unsigned int stack_len;
163 unsigned long stack_entries[MAX_STACK];
167 static DEFINE_STATIC_KEY_FALSE(no_sleep_enabled);
169 /*----------------------------------------------------------------*/
171 #define dm_bufio_in_request() (!!current->bio_list)
173 static void dm_bufio_lock(struct dm_bufio_client *c)
175 if (static_branch_unlikely(&no_sleep_enabled) && c->no_sleep)
176 spin_lock_bh(&c->spinlock);
178 mutex_lock_nested(&c->lock, dm_bufio_in_request());
181 static int dm_bufio_trylock(struct dm_bufio_client *c)
183 if (static_branch_unlikely(&no_sleep_enabled) && c->no_sleep)
184 return spin_trylock_bh(&c->spinlock);
186 return mutex_trylock(&c->lock);
189 static void dm_bufio_unlock(struct dm_bufio_client *c)
191 if (static_branch_unlikely(&no_sleep_enabled) && c->no_sleep)
192 spin_unlock_bh(&c->spinlock);
194 mutex_unlock(&c->lock);
197 /*----------------------------------------------------------------*/
200 * Default cache size: available memory divided by the ratio.
202 static unsigned long dm_bufio_default_cache_size;
205 * Total cache size set by the user.
207 static unsigned long dm_bufio_cache_size;
210 * A copy of dm_bufio_cache_size because dm_bufio_cache_size can change
211 * at any time. If it disagrees, the user has changed cache size.
213 static unsigned long dm_bufio_cache_size_latch;
215 static DEFINE_SPINLOCK(global_spinlock);
217 static LIST_HEAD(global_queue);
219 static unsigned long global_num;
222 * Buffers are freed after this timeout
224 static unsigned int dm_bufio_max_age = DM_BUFIO_DEFAULT_AGE_SECS;
225 static unsigned long dm_bufio_retain_bytes = DM_BUFIO_DEFAULT_RETAIN_BYTES;
227 static unsigned long dm_bufio_peak_allocated;
228 static unsigned long dm_bufio_allocated_kmem_cache;
229 static unsigned long dm_bufio_allocated_get_free_pages;
230 static unsigned long dm_bufio_allocated_vmalloc;
231 static unsigned long dm_bufio_current_allocated;
233 /*----------------------------------------------------------------*/
236 * The current number of clients.
238 static int dm_bufio_client_count;
241 * The list of all clients.
243 static LIST_HEAD(dm_bufio_all_clients);
246 * This mutex protects dm_bufio_cache_size_latch and dm_bufio_client_count
248 static DEFINE_MUTEX(dm_bufio_clients_lock);
250 static struct workqueue_struct *dm_bufio_wq;
251 static struct delayed_work dm_bufio_cleanup_old_work;
252 static struct work_struct dm_bufio_replacement_work;
255 #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
256 static void buffer_record_stack(struct dm_buffer *b)
258 b->stack_len = stack_trace_save(b->stack_entries, MAX_STACK, 2);
263 *----------------------------------------------------------------
264 * A red/black tree acts as an index for all the buffers.
265 *----------------------------------------------------------------
267 static struct dm_buffer *__find(struct dm_bufio_client *c, sector_t block)
269 struct rb_node *n = c->buffer_tree.rb_node;
273 b = container_of(n, struct dm_buffer, node);
275 if (b->block == block)
278 n = block < b->block ? n->rb_left : n->rb_right;
284 static struct dm_buffer *__find_next(struct dm_bufio_client *c, sector_t block)
286 struct rb_node *n = c->buffer_tree.rb_node;
288 struct dm_buffer *best = NULL;
291 b = container_of(n, struct dm_buffer, node);
293 if (b->block == block)
296 if (block <= b->block) {
307 static void __insert(struct dm_bufio_client *c, struct dm_buffer *b)
309 struct rb_node **new = &c->buffer_tree.rb_node, *parent = NULL;
310 struct dm_buffer *found;
313 found = container_of(*new, struct dm_buffer, node);
315 if (found->block == b->block) {
321 new = b->block < found->block ?
322 &found->node.rb_left : &found->node.rb_right;
325 rb_link_node(&b->node, parent, new);
326 rb_insert_color(&b->node, &c->buffer_tree);
329 static void __remove(struct dm_bufio_client *c, struct dm_buffer *b)
331 rb_erase(&b->node, &c->buffer_tree);
334 /*----------------------------------------------------------------*/
336 static void adjust_total_allocated(struct dm_buffer *b, bool unlink)
338 unsigned char data_mode;
341 static unsigned long * const class_ptr[DATA_MODE_LIMIT] = {
342 &dm_bufio_allocated_kmem_cache,
343 &dm_bufio_allocated_get_free_pages,
344 &dm_bufio_allocated_vmalloc,
347 data_mode = b->data_mode;
348 diff = (long)b->c->block_size;
352 spin_lock(&global_spinlock);
354 *class_ptr[data_mode] += diff;
356 dm_bufio_current_allocated += diff;
358 if (dm_bufio_current_allocated > dm_bufio_peak_allocated)
359 dm_bufio_peak_allocated = dm_bufio_current_allocated;
364 list_add(&b->global_list, &global_queue);
366 if (dm_bufio_current_allocated > dm_bufio_cache_size)
367 queue_work(dm_bufio_wq, &dm_bufio_replacement_work);
369 list_del(&b->global_list);
373 spin_unlock(&global_spinlock);
377 * Change the number of clients and recalculate per-client limit.
379 static void __cache_size_refresh(void)
381 BUG_ON(!mutex_is_locked(&dm_bufio_clients_lock));
382 BUG_ON(dm_bufio_client_count < 0);
384 dm_bufio_cache_size_latch = READ_ONCE(dm_bufio_cache_size);
387 * Use default if set to 0 and report the actual cache size used.
389 if (!dm_bufio_cache_size_latch) {
390 (void)cmpxchg(&dm_bufio_cache_size, 0,
391 dm_bufio_default_cache_size);
392 dm_bufio_cache_size_latch = dm_bufio_default_cache_size;
397 * Allocating buffer data.
399 * Small buffers are allocated with kmem_cache, to use space optimally.
401 * For large buffers, we choose between get_free_pages and vmalloc.
402 * Each has advantages and disadvantages.
404 * __get_free_pages can randomly fail if the memory is fragmented.
405 * __vmalloc won't randomly fail, but vmalloc space is limited (it may be
406 * as low as 128M) so using it for caching is not appropriate.
408 * If the allocation may fail we use __get_free_pages. Memory fragmentation
409 * won't have a fatal effect here, but it just causes flushes of some other
410 * buffers and more I/O will be performed. Don't use __get_free_pages if it
411 * always fails (i.e. order >= MAX_ORDER).
413 * If the allocation shouldn't fail we use __vmalloc. This is only for the
414 * initial reserve allocation, so there's no risk of wasting all vmalloc
417 static void *alloc_buffer_data(struct dm_bufio_client *c, gfp_t gfp_mask,
418 unsigned char *data_mode)
420 if (unlikely(c->slab_cache != NULL)) {
421 *data_mode = DATA_MODE_SLAB;
422 return kmem_cache_alloc(c->slab_cache, gfp_mask);
425 if (c->block_size <= KMALLOC_MAX_SIZE &&
426 gfp_mask & __GFP_NORETRY) {
427 *data_mode = DATA_MODE_GET_FREE_PAGES;
428 return (void *)__get_free_pages(gfp_mask,
429 c->sectors_per_block_bits - (PAGE_SHIFT - SECTOR_SHIFT));
432 *data_mode = DATA_MODE_VMALLOC;
435 * __vmalloc allocates the data pages and auxiliary structures with
436 * gfp_flags that were specified, but pagetables are always allocated
437 * with GFP_KERNEL, no matter what was specified as gfp_mask.
439 * Consequently, we must set per-process flag PF_MEMALLOC_NOIO so that
440 * all allocations done by this process (including pagetables) are done
441 * as if GFP_NOIO was specified.
443 if (gfp_mask & __GFP_NORETRY) {
444 unsigned int noio_flag = memalloc_noio_save();
445 void *ptr = __vmalloc(c->block_size, gfp_mask);
447 memalloc_noio_restore(noio_flag);
451 return __vmalloc(c->block_size, gfp_mask);
455 * Free buffer's data.
457 static void free_buffer_data(struct dm_bufio_client *c,
458 void *data, unsigned char data_mode)
462 kmem_cache_free(c->slab_cache, data);
465 case DATA_MODE_GET_FREE_PAGES:
466 free_pages((unsigned long)data,
467 c->sectors_per_block_bits - (PAGE_SHIFT - SECTOR_SHIFT));
470 case DATA_MODE_VMALLOC:
475 DMCRIT("dm_bufio_free_buffer_data: bad data mode: %d",
482 * Allocate buffer and its data.
484 static struct dm_buffer *alloc_buffer(struct dm_bufio_client *c, gfp_t gfp_mask)
486 struct dm_buffer *b = kmem_cache_alloc(c->slab_buffer, gfp_mask);
493 b->data = alloc_buffer_data(c, gfp_mask, &b->data_mode);
495 kmem_cache_free(c->slab_buffer, b);
499 #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
506 * Free buffer and its data.
508 static void free_buffer(struct dm_buffer *b)
510 struct dm_bufio_client *c = b->c;
512 free_buffer_data(c, b->data, b->data_mode);
513 kmem_cache_free(c->slab_buffer, b);
517 * Link buffer to the buffer tree and clean or dirty queue.
519 static void __link_buffer(struct dm_buffer *b, sector_t block, int dirty)
521 struct dm_bufio_client *c = b->c;
523 c->n_buffers[dirty]++;
525 b->list_mode = dirty;
526 list_add(&b->lru_list, &c->lru[dirty]);
528 b->last_accessed = jiffies;
530 adjust_total_allocated(b, false);
534 * Unlink buffer from the buffer tree and dirty or clean queue.
536 static void __unlink_buffer(struct dm_buffer *b)
538 struct dm_bufio_client *c = b->c;
540 BUG_ON(!c->n_buffers[b->list_mode]);
542 c->n_buffers[b->list_mode]--;
544 list_del(&b->lru_list);
546 adjust_total_allocated(b, true);
550 * Place the buffer to the head of dirty or clean LRU queue.
552 static void __relink_lru(struct dm_buffer *b, int dirty)
554 struct dm_bufio_client *c = b->c;
558 BUG_ON(!c->n_buffers[b->list_mode]);
560 c->n_buffers[b->list_mode]--;
561 c->n_buffers[dirty]++;
562 b->list_mode = dirty;
563 list_move(&b->lru_list, &c->lru[dirty]);
564 b->last_accessed = jiffies;
568 *--------------------------------------------------------------------------
569 * Submit I/O on the buffer.
571 * Bio interface is faster but it has some problems:
572 * the vector list is limited (increasing this limit increases
573 * memory-consumption per buffer, so it is not viable);
575 * the memory must be direct-mapped, not vmalloced;
577 * If the buffer is small enough (up to DM_BUFIO_INLINE_VECS pages) and
578 * it is not vmalloced, try using the bio interface.
580 * If the buffer is big, if it is vmalloced or if the underlying device
581 * rejects the bio because it is too large, use dm-io layer to do the I/O.
582 * The dm-io layer splits the I/O into multiple requests, avoiding the above
584 *--------------------------------------------------------------------------
588 * dm-io completion routine. It just calls b->bio.bi_end_io, pretending
589 * that the request was handled directly with bio interface.
591 static void dmio_complete(unsigned long error, void *context)
593 struct dm_buffer *b = context;
595 b->end_io(b, unlikely(error != 0) ? BLK_STS_IOERR : 0);
598 static void use_dmio(struct dm_buffer *b, enum req_op op, sector_t sector,
599 unsigned int n_sectors, unsigned int offset)
602 struct dm_io_request io_req = {
604 .notify.fn = dmio_complete,
606 .client = b->c->dm_io,
608 struct dm_io_region region = {
614 if (b->data_mode != DATA_MODE_VMALLOC) {
615 io_req.mem.type = DM_IO_KMEM;
616 io_req.mem.ptr.addr = (char *)b->data + offset;
618 io_req.mem.type = DM_IO_VMA;
619 io_req.mem.ptr.vma = (char *)b->data + offset;
622 r = dm_io(&io_req, 1, ®ion, NULL);
624 b->end_io(b, errno_to_blk_status(r));
627 static void bio_complete(struct bio *bio)
629 struct dm_buffer *b = bio->bi_private;
630 blk_status_t status = bio->bi_status;
634 b->end_io(b, status);
637 static void use_bio(struct dm_buffer *b, enum req_op op, sector_t sector,
638 unsigned int n_sectors, unsigned int offset)
642 unsigned int vec_size, len;
644 vec_size = b->c->block_size >> PAGE_SHIFT;
645 if (unlikely(b->c->sectors_per_block_bits < PAGE_SHIFT - SECTOR_SHIFT))
648 bio = bio_kmalloc(vec_size, GFP_NOWAIT | __GFP_NORETRY | __GFP_NOWARN);
651 use_dmio(b, op, sector, n_sectors, offset);
654 bio_init(bio, b->c->bdev, bio->bi_inline_vecs, vec_size, op);
655 bio->bi_iter.bi_sector = sector;
656 bio->bi_end_io = bio_complete;
659 ptr = (char *)b->data + offset;
660 len = n_sectors << SECTOR_SHIFT;
663 unsigned int this_step = min((unsigned int)(PAGE_SIZE - offset_in_page(ptr)), len);
665 if (!bio_add_page(bio, virt_to_page(ptr), this_step,
666 offset_in_page(ptr))) {
678 static inline sector_t block_to_sector(struct dm_bufio_client *c, sector_t block)
682 if (likely(c->sectors_per_block_bits >= 0))
683 sector = block << c->sectors_per_block_bits;
685 sector = block * (c->block_size >> SECTOR_SHIFT);
691 static void submit_io(struct dm_buffer *b, enum req_op op,
692 void (*end_io)(struct dm_buffer *, blk_status_t))
694 unsigned int n_sectors;
696 unsigned int offset, end;
700 sector = block_to_sector(b->c, b->block);
702 if (op != REQ_OP_WRITE) {
703 n_sectors = b->c->block_size >> SECTOR_SHIFT;
706 if (b->c->write_callback)
707 b->c->write_callback(b);
708 offset = b->write_start;
710 offset &= -DM_BUFIO_WRITE_ALIGN;
711 end += DM_BUFIO_WRITE_ALIGN - 1;
712 end &= -DM_BUFIO_WRITE_ALIGN;
713 if (unlikely(end > b->c->block_size))
714 end = b->c->block_size;
716 sector += offset >> SECTOR_SHIFT;
717 n_sectors = (end - offset) >> SECTOR_SHIFT;
720 if (b->data_mode != DATA_MODE_VMALLOC)
721 use_bio(b, op, sector, n_sectors, offset);
723 use_dmio(b, op, sector, n_sectors, offset);
727 *--------------------------------------------------------------
728 * Writing dirty buffers
729 *--------------------------------------------------------------
733 * The endio routine for write.
735 * Set the error, clear B_WRITING bit and wake anyone who was waiting on
738 static void write_endio(struct dm_buffer *b, blk_status_t status)
740 b->write_error = status;
741 if (unlikely(status)) {
742 struct dm_bufio_client *c = b->c;
744 (void)cmpxchg(&c->async_write_error, 0,
745 blk_status_to_errno(status));
748 BUG_ON(!test_bit(B_WRITING, &b->state));
750 smp_mb__before_atomic();
751 clear_bit(B_WRITING, &b->state);
752 smp_mb__after_atomic();
754 wake_up_bit(&b->state, B_WRITING);
758 * Initiate a write on a dirty buffer, but don't wait for it.
760 * - If the buffer is not dirty, exit.
761 * - If there some previous write going on, wait for it to finish (we can't
762 * have two writes on the same buffer simultaneously).
763 * - Submit our write and don't wait on it. We set B_WRITING indicating
764 * that there is a write in progress.
766 static void __write_dirty_buffer(struct dm_buffer *b,
767 struct list_head *write_list)
769 if (!test_bit(B_DIRTY, &b->state))
772 clear_bit(B_DIRTY, &b->state);
773 wait_on_bit_lock_io(&b->state, B_WRITING, TASK_UNINTERRUPTIBLE);
775 b->write_start = b->dirty_start;
776 b->write_end = b->dirty_end;
779 submit_io(b, REQ_OP_WRITE, write_endio);
781 list_add_tail(&b->write_list, write_list);
784 static void __flush_write_list(struct list_head *write_list)
786 struct blk_plug plug;
788 blk_start_plug(&plug);
789 while (!list_empty(write_list)) {
790 struct dm_buffer *b =
791 list_entry(write_list->next, struct dm_buffer, write_list);
792 list_del(&b->write_list);
793 submit_io(b, REQ_OP_WRITE, write_endio);
796 blk_finish_plug(&plug);
800 * Wait until any activity on the buffer finishes. Possibly write the
801 * buffer if it is dirty. When this function finishes, there is no I/O
802 * running on the buffer and the buffer is not dirty.
804 static void __make_buffer_clean(struct dm_buffer *b)
806 BUG_ON(b->hold_count);
808 /* smp_load_acquire() pairs with read_endio()'s smp_mb__before_atomic() */
809 if (!smp_load_acquire(&b->state)) /* fast case */
812 wait_on_bit_io(&b->state, B_READING, TASK_UNINTERRUPTIBLE);
813 __write_dirty_buffer(b, NULL);
814 wait_on_bit_io(&b->state, B_WRITING, TASK_UNINTERRUPTIBLE);
818 * Find some buffer that is not held by anybody, clean it, unlink it and
821 static struct dm_buffer *__get_unclaimed_buffer(struct dm_bufio_client *c)
825 list_for_each_entry_reverse(b, &c->lru[LIST_CLEAN], lru_list) {
826 BUG_ON(test_bit(B_WRITING, &b->state));
827 BUG_ON(test_bit(B_DIRTY, &b->state));
829 if (static_branch_unlikely(&no_sleep_enabled) && c->no_sleep &&
830 unlikely(test_bit_acquire(B_READING, &b->state)))
833 if (!b->hold_count) {
834 __make_buffer_clean(b);
841 if (static_branch_unlikely(&no_sleep_enabled) && c->no_sleep)
844 list_for_each_entry_reverse(b, &c->lru[LIST_DIRTY], lru_list) {
845 BUG_ON(test_bit(B_READING, &b->state));
847 if (!b->hold_count) {
848 __make_buffer_clean(b);
859 * Wait until some other threads free some buffer or release hold count on
862 * This function is entered with c->lock held, drops it and regains it
865 static void __wait_for_free_buffer(struct dm_bufio_client *c)
867 DECLARE_WAITQUEUE(wait, current);
869 add_wait_queue(&c->free_buffer_wait, &wait);
870 set_current_state(TASK_UNINTERRUPTIBLE);
875 remove_wait_queue(&c->free_buffer_wait, &wait);
888 * Allocate a new buffer. If the allocation is not possible, wait until
889 * some other thread frees a buffer.
891 * May drop the lock and regain it.
893 static struct dm_buffer *__alloc_buffer_wait_no_callback(struct dm_bufio_client *c, enum new_flag nf)
896 bool tried_noio_alloc = false;
899 * dm-bufio is resistant to allocation failures (it just keeps
900 * one buffer reserved in cases all the allocations fail).
901 * So set flags to not try too hard:
902 * GFP_NOWAIT: don't wait; if we need to sleep we'll release our
903 * mutex and wait ourselves.
904 * __GFP_NORETRY: don't retry and rather return failure
905 * __GFP_NOMEMALLOC: don't use emergency reserves
906 * __GFP_NOWARN: don't print a warning in case of failure
908 * For debugging, if we set the cache size to 1, no new buffers will
912 if (dm_bufio_cache_size_latch != 1) {
913 b = alloc_buffer(c, GFP_NOWAIT | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
918 if (nf == NF_PREFETCH)
921 if (dm_bufio_cache_size_latch != 1 && !tried_noio_alloc) {
923 b = alloc_buffer(c, GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
927 tried_noio_alloc = true;
930 if (!list_empty(&c->reserved_buffers)) {
931 b = list_entry(c->reserved_buffers.next,
932 struct dm_buffer, lru_list);
933 list_del(&b->lru_list);
934 c->need_reserved_buffers++;
939 b = __get_unclaimed_buffer(c);
943 __wait_for_free_buffer(c);
947 static struct dm_buffer *__alloc_buffer_wait(struct dm_bufio_client *c, enum new_flag nf)
949 struct dm_buffer *b = __alloc_buffer_wait_no_callback(c, nf);
954 if (c->alloc_callback)
955 c->alloc_callback(b);
961 * Free a buffer and wake other threads waiting for free buffers.
963 static void __free_buffer_wake(struct dm_buffer *b)
965 struct dm_bufio_client *c = b->c;
967 if (!c->need_reserved_buffers)
970 list_add(&b->lru_list, &c->reserved_buffers);
971 c->need_reserved_buffers--;
974 wake_up(&c->free_buffer_wait);
977 static void __write_dirty_buffers_async(struct dm_bufio_client *c, int no_wait,
978 struct list_head *write_list)
980 struct dm_buffer *b, *tmp;
982 list_for_each_entry_safe_reverse(b, tmp, &c->lru[LIST_DIRTY], lru_list) {
983 BUG_ON(test_bit(B_READING, &b->state));
985 if (!test_bit(B_DIRTY, &b->state) &&
986 !test_bit(B_WRITING, &b->state)) {
987 __relink_lru(b, LIST_CLEAN);
991 if (no_wait && test_bit(B_WRITING, &b->state))
994 __write_dirty_buffer(b, write_list);
1000 * Check if we're over watermark.
1001 * If we are over threshold_buffers, start freeing buffers.
1002 * If we're over "limit_buffers", block until we get under the limit.
1004 static void __check_watermark(struct dm_bufio_client *c,
1005 struct list_head *write_list)
1007 if (c->n_buffers[LIST_DIRTY] > c->n_buffers[LIST_CLEAN] * DM_BUFIO_WRITEBACK_RATIO)
1008 __write_dirty_buffers_async(c, 1, write_list);
1012 *--------------------------------------------------------------
1014 *--------------------------------------------------------------
1017 static struct dm_buffer *__bufio_new(struct dm_bufio_client *c, sector_t block,
1018 enum new_flag nf, int *need_submit,
1019 struct list_head *write_list)
1021 struct dm_buffer *b, *new_b = NULL;
1025 b = __find(c, block);
1032 new_b = __alloc_buffer_wait(c, nf);
1037 * We've had a period where the mutex was unlocked, so need to
1038 * recheck the buffer tree.
1040 b = __find(c, block);
1042 __free_buffer_wake(new_b);
1046 __check_watermark(c, write_list);
1052 __link_buffer(b, block, LIST_CLEAN);
1054 if (nf == NF_FRESH) {
1059 b->state = 1 << B_READING;
1065 if (nf == NF_PREFETCH)
1068 * Note: it is essential that we don't wait for the buffer to be
1069 * read if dm_bufio_get function is used. Both dm_bufio_get and
1070 * dm_bufio_prefetch can be used in the driver request routine.
1071 * If the user called both dm_bufio_prefetch and dm_bufio_get on
1072 * the same buffer, it would deadlock if we waited.
1074 if (nf == NF_GET && unlikely(test_bit_acquire(B_READING, &b->state)))
1078 __relink_lru(b, test_bit(B_DIRTY, &b->state) ||
1079 test_bit(B_WRITING, &b->state));
1084 * The endio routine for reading: set the error, clear the bit and wake up
1085 * anyone waiting on the buffer.
1087 static void read_endio(struct dm_buffer *b, blk_status_t status)
1089 b->read_error = status;
1091 BUG_ON(!test_bit(B_READING, &b->state));
1093 smp_mb__before_atomic();
1094 clear_bit(B_READING, &b->state);
1095 smp_mb__after_atomic();
1097 wake_up_bit(&b->state, B_READING);
1101 * A common routine for dm_bufio_new and dm_bufio_read. Operation of these
1102 * functions is similar except that dm_bufio_new doesn't read the
1103 * buffer from the disk (assuming that the caller overwrites all the data
1104 * and uses dm_bufio_mark_buffer_dirty to write new data back).
1106 static void *new_read(struct dm_bufio_client *c, sector_t block,
1107 enum new_flag nf, struct dm_buffer **bp)
1110 struct dm_buffer *b;
1112 LIST_HEAD(write_list);
1115 b = __bufio_new(c, block, nf, &need_submit, &write_list);
1116 #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
1117 if (b && b->hold_count == 1)
1118 buffer_record_stack(b);
1122 __flush_write_list(&write_list);
1128 submit_io(b, REQ_OP_READ, read_endio);
1130 wait_on_bit_io(&b->state, B_READING, TASK_UNINTERRUPTIBLE);
1132 if (b->read_error) {
1133 int error = blk_status_to_errno(b->read_error);
1135 dm_bufio_release(b);
1137 return ERR_PTR(error);
1145 void *dm_bufio_get(struct dm_bufio_client *c, sector_t block,
1146 struct dm_buffer **bp)
1148 return new_read(c, block, NF_GET, bp);
1150 EXPORT_SYMBOL_GPL(dm_bufio_get);
1152 void *dm_bufio_read(struct dm_bufio_client *c, sector_t block,
1153 struct dm_buffer **bp)
1155 BUG_ON(dm_bufio_in_request());
1157 return new_read(c, block, NF_READ, bp);
1159 EXPORT_SYMBOL_GPL(dm_bufio_read);
1161 void *dm_bufio_new(struct dm_bufio_client *c, sector_t block,
1162 struct dm_buffer **bp)
1164 BUG_ON(dm_bufio_in_request());
1166 return new_read(c, block, NF_FRESH, bp);
1168 EXPORT_SYMBOL_GPL(dm_bufio_new);
1170 void dm_bufio_prefetch(struct dm_bufio_client *c,
1171 sector_t block, unsigned int n_blocks)
1173 struct blk_plug plug;
1175 LIST_HEAD(write_list);
1177 BUG_ON(dm_bufio_in_request());
1179 blk_start_plug(&plug);
1182 for (; n_blocks--; block++) {
1184 struct dm_buffer *b;
1186 b = __bufio_new(c, block, NF_PREFETCH, &need_submit,
1188 if (unlikely(!list_empty(&write_list))) {
1190 blk_finish_plug(&plug);
1191 __flush_write_list(&write_list);
1192 blk_start_plug(&plug);
1195 if (unlikely(b != NULL)) {
1199 submit_io(b, REQ_OP_READ, read_endio);
1200 dm_bufio_release(b);
1213 blk_finish_plug(&plug);
1215 EXPORT_SYMBOL_GPL(dm_bufio_prefetch);
1217 void dm_bufio_release(struct dm_buffer *b)
1219 struct dm_bufio_client *c = b->c;
1223 BUG_ON(!b->hold_count);
1226 if (!b->hold_count) {
1227 wake_up(&c->free_buffer_wait);
1230 * If there were errors on the buffer, and the buffer is not
1231 * to be written, free the buffer. There is no point in caching
1234 if ((b->read_error || b->write_error) &&
1235 !test_bit_acquire(B_READING, &b->state) &&
1236 !test_bit(B_WRITING, &b->state) &&
1237 !test_bit(B_DIRTY, &b->state)) {
1239 __free_buffer_wake(b);
1245 EXPORT_SYMBOL_GPL(dm_bufio_release);
1247 void dm_bufio_mark_partial_buffer_dirty(struct dm_buffer *b,
1248 unsigned int start, unsigned int end)
1250 struct dm_bufio_client *c = b->c;
1252 BUG_ON(start >= end);
1253 BUG_ON(end > b->c->block_size);
1257 BUG_ON(test_bit(B_READING, &b->state));
1259 if (!test_and_set_bit(B_DIRTY, &b->state)) {
1260 b->dirty_start = start;
1262 __relink_lru(b, LIST_DIRTY);
1264 if (start < b->dirty_start)
1265 b->dirty_start = start;
1266 if (end > b->dirty_end)
1272 EXPORT_SYMBOL_GPL(dm_bufio_mark_partial_buffer_dirty);
1274 void dm_bufio_mark_buffer_dirty(struct dm_buffer *b)
1276 dm_bufio_mark_partial_buffer_dirty(b, 0, b->c->block_size);
1278 EXPORT_SYMBOL_GPL(dm_bufio_mark_buffer_dirty);
1280 void dm_bufio_write_dirty_buffers_async(struct dm_bufio_client *c)
1282 LIST_HEAD(write_list);
1284 BUG_ON(dm_bufio_in_request());
1287 __write_dirty_buffers_async(c, 0, &write_list);
1289 __flush_write_list(&write_list);
1291 EXPORT_SYMBOL_GPL(dm_bufio_write_dirty_buffers_async);
1294 * For performance, it is essential that the buffers are written asynchronously
1295 * and simultaneously (so that the block layer can merge the writes) and then
1298 * Finally, we flush hardware disk cache.
1300 int dm_bufio_write_dirty_buffers(struct dm_bufio_client *c)
1303 unsigned long buffers_processed = 0;
1304 struct dm_buffer *b, *tmp;
1306 LIST_HEAD(write_list);
1309 __write_dirty_buffers_async(c, 0, &write_list);
1311 __flush_write_list(&write_list);
1315 list_for_each_entry_safe_reverse(b, tmp, &c->lru[LIST_DIRTY], lru_list) {
1316 int dropped_lock = 0;
1318 if (buffers_processed < c->n_buffers[LIST_DIRTY])
1319 buffers_processed++;
1321 BUG_ON(test_bit(B_READING, &b->state));
1323 if (test_bit(B_WRITING, &b->state)) {
1324 if (buffers_processed < c->n_buffers[LIST_DIRTY]) {
1328 wait_on_bit_io(&b->state, B_WRITING,
1329 TASK_UNINTERRUPTIBLE);
1333 wait_on_bit_io(&b->state, B_WRITING,
1334 TASK_UNINTERRUPTIBLE);
1337 if (!test_bit(B_DIRTY, &b->state) &&
1338 !test_bit(B_WRITING, &b->state))
1339 __relink_lru(b, LIST_CLEAN);
1344 * If we dropped the lock, the list is no longer consistent,
1345 * so we must restart the search.
1347 * In the most common case, the buffer just processed is
1348 * relinked to the clean list, so we won't loop scanning the
1349 * same buffer again and again.
1351 * This may livelock if there is another thread simultaneously
1352 * dirtying buffers, so we count the number of buffers walked
1353 * and if it exceeds the total number of buffers, it means that
1354 * someone is doing some writes simultaneously with us. In
1355 * this case, stop, dropping the lock.
1360 wake_up(&c->free_buffer_wait);
1363 a = xchg(&c->async_write_error, 0);
1364 f = dm_bufio_issue_flush(c);
1370 EXPORT_SYMBOL_GPL(dm_bufio_write_dirty_buffers);
1373 * Use dm-io to send an empty barrier to flush the device.
1375 int dm_bufio_issue_flush(struct dm_bufio_client *c)
1377 struct dm_io_request io_req = {
1378 .bi_opf = REQ_OP_WRITE | REQ_PREFLUSH | REQ_SYNC,
1379 .mem.type = DM_IO_KMEM,
1380 .mem.ptr.addr = NULL,
1383 struct dm_io_region io_reg = {
1389 BUG_ON(dm_bufio_in_request());
1391 return dm_io(&io_req, 1, &io_reg, NULL);
1393 EXPORT_SYMBOL_GPL(dm_bufio_issue_flush);
1396 * Use dm-io to send a discard request to flush the device.
1398 int dm_bufio_issue_discard(struct dm_bufio_client *c, sector_t block, sector_t count)
1400 struct dm_io_request io_req = {
1401 .bi_opf = REQ_OP_DISCARD | REQ_SYNC,
1402 .mem.type = DM_IO_KMEM,
1403 .mem.ptr.addr = NULL,
1406 struct dm_io_region io_reg = {
1408 .sector = block_to_sector(c, block),
1409 .count = block_to_sector(c, count),
1412 BUG_ON(dm_bufio_in_request());
1414 return dm_io(&io_req, 1, &io_reg, NULL);
1416 EXPORT_SYMBOL_GPL(dm_bufio_issue_discard);
1419 * We first delete any other buffer that may be at that new location.
1421 * Then, we write the buffer to the original location if it was dirty.
1423 * Then, if we are the only one who is holding the buffer, relink the buffer
1424 * in the buffer tree for the new location.
1426 * If there was someone else holding the buffer, we write it to the new
1427 * location but not relink it, because that other user needs to have the buffer
1428 * at the same place.
1430 void dm_bufio_release_move(struct dm_buffer *b, sector_t new_block)
1432 struct dm_bufio_client *c = b->c;
1433 struct dm_buffer *new;
1435 BUG_ON(dm_bufio_in_request());
1440 new = __find(c, new_block);
1442 if (new->hold_count) {
1443 __wait_for_free_buffer(c);
1448 * FIXME: Is there any point waiting for a write that's going
1449 * to be overwritten in a bit?
1451 __make_buffer_clean(new);
1452 __unlink_buffer(new);
1453 __free_buffer_wake(new);
1456 BUG_ON(!b->hold_count);
1457 BUG_ON(test_bit(B_READING, &b->state));
1459 __write_dirty_buffer(b, NULL);
1460 if (b->hold_count == 1) {
1461 wait_on_bit_io(&b->state, B_WRITING,
1462 TASK_UNINTERRUPTIBLE);
1463 set_bit(B_DIRTY, &b->state);
1465 b->dirty_end = c->block_size;
1467 __link_buffer(b, new_block, LIST_DIRTY);
1471 wait_on_bit_lock_io(&b->state, B_WRITING,
1472 TASK_UNINTERRUPTIBLE);
1474 * Relink buffer to "new_block" so that write_callback
1475 * sees "new_block" as a block number.
1476 * After the write, link the buffer back to old_block.
1477 * All this must be done in bufio lock, so that block number
1478 * change isn't visible to other threads.
1480 old_block = b->block;
1482 __link_buffer(b, new_block, b->list_mode);
1483 submit_io(b, REQ_OP_WRITE, write_endio);
1484 wait_on_bit_io(&b->state, B_WRITING,
1485 TASK_UNINTERRUPTIBLE);
1487 __link_buffer(b, old_block, b->list_mode);
1491 dm_bufio_release(b);
1493 EXPORT_SYMBOL_GPL(dm_bufio_release_move);
1495 static void forget_buffer_locked(struct dm_buffer *b)
1497 if (likely(!b->hold_count) && likely(!smp_load_acquire(&b->state))) {
1499 __free_buffer_wake(b);
1504 * Free the given buffer.
1506 * This is just a hint, if the buffer is in use or dirty, this function
1509 void dm_bufio_forget(struct dm_bufio_client *c, sector_t block)
1511 struct dm_buffer *b;
1515 b = __find(c, block);
1517 forget_buffer_locked(b);
1521 EXPORT_SYMBOL_GPL(dm_bufio_forget);
1523 void dm_bufio_forget_buffers(struct dm_bufio_client *c, sector_t block, sector_t n_blocks)
1525 struct dm_buffer *b;
1526 sector_t end_block = block + n_blocks;
1528 while (block < end_block) {
1531 b = __find_next(c, block);
1533 block = b->block + 1;
1534 forget_buffer_locked(b);
1544 EXPORT_SYMBOL_GPL(dm_bufio_forget_buffers);
1546 void dm_bufio_set_minimum_buffers(struct dm_bufio_client *c, unsigned int n)
1548 c->minimum_buffers = n;
1550 EXPORT_SYMBOL_GPL(dm_bufio_set_minimum_buffers);
1552 unsigned int dm_bufio_get_block_size(struct dm_bufio_client *c)
1554 return c->block_size;
1556 EXPORT_SYMBOL_GPL(dm_bufio_get_block_size);
1558 sector_t dm_bufio_get_device_size(struct dm_bufio_client *c)
1560 sector_t s = bdev_nr_sectors(c->bdev);
1566 if (likely(c->sectors_per_block_bits >= 0))
1567 s >>= c->sectors_per_block_bits;
1569 sector_div(s, c->block_size >> SECTOR_SHIFT);
1572 EXPORT_SYMBOL_GPL(dm_bufio_get_device_size);
1574 struct dm_io_client *dm_bufio_get_dm_io_client(struct dm_bufio_client *c)
1578 EXPORT_SYMBOL_GPL(dm_bufio_get_dm_io_client);
1580 sector_t dm_bufio_get_block_number(struct dm_buffer *b)
1584 EXPORT_SYMBOL_GPL(dm_bufio_get_block_number);
1586 void *dm_bufio_get_block_data(struct dm_buffer *b)
1590 EXPORT_SYMBOL_GPL(dm_bufio_get_block_data);
1592 void *dm_bufio_get_aux_data(struct dm_buffer *b)
1596 EXPORT_SYMBOL_GPL(dm_bufio_get_aux_data);
1598 struct dm_bufio_client *dm_bufio_get_client(struct dm_buffer *b)
1602 EXPORT_SYMBOL_GPL(dm_bufio_get_client);
1604 static void drop_buffers(struct dm_bufio_client *c)
1606 struct dm_buffer *b;
1608 bool warned = false;
1610 BUG_ON(dm_bufio_in_request());
1613 * An optimization so that the buffers are not written one-by-one.
1615 dm_bufio_write_dirty_buffers_async(c);
1619 while ((b = __get_unclaimed_buffer(c)))
1620 __free_buffer_wake(b);
1622 for (i = 0; i < LIST_SIZE; i++)
1623 list_for_each_entry(b, &c->lru[i], lru_list) {
1626 DMERR("leaked buffer %llx, hold count %u, list %d",
1627 (unsigned long long)b->block, b->hold_count, i);
1628 #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
1629 stack_trace_print(b->stack_entries, b->stack_len, 1);
1630 /* mark unclaimed to avoid BUG_ON below */
1635 #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
1636 while ((b = __get_unclaimed_buffer(c)))
1637 __free_buffer_wake(b);
1640 for (i = 0; i < LIST_SIZE; i++)
1641 BUG_ON(!list_empty(&c->lru[i]));
1647 * We may not be able to evict this buffer if IO pending or the client
1648 * is still using it. Caller is expected to know buffer is too old.
1650 * And if GFP_NOFS is used, we must not do any I/O because we hold
1651 * dm_bufio_clients_lock and we would risk deadlock if the I/O gets
1652 * rerouted to different bufio client.
1654 static bool __try_evict_buffer(struct dm_buffer *b, gfp_t gfp)
1656 if (!(gfp & __GFP_FS) ||
1657 (static_branch_unlikely(&no_sleep_enabled) && b->c->no_sleep)) {
1658 if (test_bit_acquire(B_READING, &b->state) ||
1659 test_bit(B_WRITING, &b->state) ||
1660 test_bit(B_DIRTY, &b->state))
1667 __make_buffer_clean(b);
1669 __free_buffer_wake(b);
1674 static unsigned long get_retain_buffers(struct dm_bufio_client *c)
1676 unsigned long retain_bytes = READ_ONCE(dm_bufio_retain_bytes);
1678 if (likely(c->sectors_per_block_bits >= 0))
1679 retain_bytes >>= c->sectors_per_block_bits + SECTOR_SHIFT;
1681 retain_bytes /= c->block_size;
1683 return retain_bytes;
1686 static void __scan(struct dm_bufio_client *c)
1689 struct dm_buffer *b, *tmp;
1690 unsigned long freed = 0;
1691 unsigned long count = c->n_buffers[LIST_CLEAN] +
1692 c->n_buffers[LIST_DIRTY];
1693 unsigned long retain_target = get_retain_buffers(c);
1695 for (l = 0; l < LIST_SIZE; l++) {
1696 list_for_each_entry_safe_reverse(b, tmp, &c->lru[l], lru_list) {
1697 if (count - freed <= retain_target)
1698 atomic_long_set(&c->need_shrink, 0);
1699 if (!atomic_long_read(&c->need_shrink))
1701 if (__try_evict_buffer(b, GFP_KERNEL)) {
1702 atomic_long_dec(&c->need_shrink);
1710 static void shrink_work(struct work_struct *w)
1712 struct dm_bufio_client *c = container_of(w, struct dm_bufio_client, shrink_work);
1719 static unsigned long dm_bufio_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
1721 struct dm_bufio_client *c;
1723 c = container_of(shrink, struct dm_bufio_client, shrinker);
1724 atomic_long_add(sc->nr_to_scan, &c->need_shrink);
1725 queue_work(dm_bufio_wq, &c->shrink_work);
1727 return sc->nr_to_scan;
1730 static unsigned long dm_bufio_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
1732 struct dm_bufio_client *c = container_of(shrink, struct dm_bufio_client, shrinker);
1733 unsigned long count = READ_ONCE(c->n_buffers[LIST_CLEAN]) +
1734 READ_ONCE(c->n_buffers[LIST_DIRTY]);
1735 unsigned long retain_target = get_retain_buffers(c);
1736 unsigned long queued_for_cleanup = atomic_long_read(&c->need_shrink);
1738 if (unlikely(count < retain_target))
1741 count -= retain_target;
1743 if (unlikely(count < queued_for_cleanup))
1746 count -= queued_for_cleanup;
1752 * Create the buffering interface
1754 struct dm_bufio_client *dm_bufio_client_create(struct block_device *bdev, unsigned int block_size,
1755 unsigned int reserved_buffers, unsigned int aux_size,
1756 void (*alloc_callback)(struct dm_buffer *),
1757 void (*write_callback)(struct dm_buffer *),
1761 struct dm_bufio_client *c;
1765 if (!block_size || block_size & ((1 << SECTOR_SHIFT) - 1)) {
1766 DMERR("%s: block size not specified or is not multiple of 512b", __func__);
1771 c = kzalloc(sizeof(*c), GFP_KERNEL);
1776 c->buffer_tree = RB_ROOT;
1779 c->block_size = block_size;
1780 if (is_power_of_2(block_size))
1781 c->sectors_per_block_bits = __ffs(block_size) - SECTOR_SHIFT;
1783 c->sectors_per_block_bits = -1;
1785 c->alloc_callback = alloc_callback;
1786 c->write_callback = write_callback;
1788 if (flags & DM_BUFIO_CLIENT_NO_SLEEP) {
1790 static_branch_inc(&no_sleep_enabled);
1793 for (i = 0; i < LIST_SIZE; i++) {
1794 INIT_LIST_HEAD(&c->lru[i]);
1795 c->n_buffers[i] = 0;
1798 mutex_init(&c->lock);
1799 spin_lock_init(&c->spinlock);
1800 INIT_LIST_HEAD(&c->reserved_buffers);
1801 c->need_reserved_buffers = reserved_buffers;
1803 dm_bufio_set_minimum_buffers(c, DM_BUFIO_MIN_BUFFERS);
1805 init_waitqueue_head(&c->free_buffer_wait);
1806 c->async_write_error = 0;
1808 c->dm_io = dm_io_client_create();
1809 if (IS_ERR(c->dm_io)) {
1810 r = PTR_ERR(c->dm_io);
1814 if (block_size <= KMALLOC_MAX_SIZE &&
1815 (block_size < PAGE_SIZE || !is_power_of_2(block_size))) {
1816 unsigned int align = min(1U << __ffs(block_size), (unsigned int)PAGE_SIZE);
1818 snprintf(slab_name, sizeof slab_name, "dm_bufio_cache-%u", block_size);
1819 c->slab_cache = kmem_cache_create(slab_name, block_size, align,
1820 SLAB_RECLAIM_ACCOUNT, NULL);
1821 if (!c->slab_cache) {
1827 snprintf(slab_name, sizeof slab_name, "dm_bufio_buffer-%u", aux_size);
1829 snprintf(slab_name, sizeof slab_name, "dm_bufio_buffer");
1830 c->slab_buffer = kmem_cache_create(slab_name, sizeof(struct dm_buffer) + aux_size,
1831 0, SLAB_RECLAIM_ACCOUNT, NULL);
1832 if (!c->slab_buffer) {
1837 while (c->need_reserved_buffers) {
1838 struct dm_buffer *b = alloc_buffer(c, GFP_KERNEL);
1844 __free_buffer_wake(b);
1847 INIT_WORK(&c->shrink_work, shrink_work);
1848 atomic_long_set(&c->need_shrink, 0);
1850 c->shrinker.count_objects = dm_bufio_shrink_count;
1851 c->shrinker.scan_objects = dm_bufio_shrink_scan;
1852 c->shrinker.seeks = 1;
1853 c->shrinker.batch = 0;
1854 r = register_shrinker(&c->shrinker, "dm-bufio:(%u:%u)",
1855 MAJOR(bdev->bd_dev), MINOR(bdev->bd_dev));
1859 mutex_lock(&dm_bufio_clients_lock);
1860 dm_bufio_client_count++;
1861 list_add(&c->client_list, &dm_bufio_all_clients);
1862 __cache_size_refresh();
1863 mutex_unlock(&dm_bufio_clients_lock);
1868 while (!list_empty(&c->reserved_buffers)) {
1869 struct dm_buffer *b = list_entry(c->reserved_buffers.next,
1870 struct dm_buffer, lru_list);
1871 list_del(&b->lru_list);
1874 kmem_cache_destroy(c->slab_cache);
1875 kmem_cache_destroy(c->slab_buffer);
1876 dm_io_client_destroy(c->dm_io);
1878 mutex_destroy(&c->lock);
1880 static_branch_dec(&no_sleep_enabled);
1885 EXPORT_SYMBOL_GPL(dm_bufio_client_create);
1888 * Free the buffering interface.
1889 * It is required that there are no references on any buffers.
1891 void dm_bufio_client_destroy(struct dm_bufio_client *c)
1897 unregister_shrinker(&c->shrinker);
1898 flush_work(&c->shrink_work);
1900 mutex_lock(&dm_bufio_clients_lock);
1902 list_del(&c->client_list);
1903 dm_bufio_client_count--;
1904 __cache_size_refresh();
1906 mutex_unlock(&dm_bufio_clients_lock);
1908 BUG_ON(!RB_EMPTY_ROOT(&c->buffer_tree));
1909 BUG_ON(c->need_reserved_buffers);
1911 while (!list_empty(&c->reserved_buffers)) {
1912 struct dm_buffer *b = list_entry(c->reserved_buffers.next,
1913 struct dm_buffer, lru_list);
1914 list_del(&b->lru_list);
1918 for (i = 0; i < LIST_SIZE; i++)
1919 if (c->n_buffers[i])
1920 DMERR("leaked buffer count %d: %ld", i, c->n_buffers[i]);
1922 for (i = 0; i < LIST_SIZE; i++)
1923 BUG_ON(c->n_buffers[i]);
1925 kmem_cache_destroy(c->slab_cache);
1926 kmem_cache_destroy(c->slab_buffer);
1927 dm_io_client_destroy(c->dm_io);
1928 mutex_destroy(&c->lock);
1930 static_branch_dec(&no_sleep_enabled);
1933 EXPORT_SYMBOL_GPL(dm_bufio_client_destroy);
1935 void dm_bufio_set_sector_offset(struct dm_bufio_client *c, sector_t start)
1939 EXPORT_SYMBOL_GPL(dm_bufio_set_sector_offset);
1941 static unsigned int get_max_age_hz(void)
1943 unsigned int max_age = READ_ONCE(dm_bufio_max_age);
1945 if (max_age > UINT_MAX / HZ)
1946 max_age = UINT_MAX / HZ;
1948 return max_age * HZ;
1951 static bool older_than(struct dm_buffer *b, unsigned long age_hz)
1953 return time_after_eq(jiffies, b->last_accessed + age_hz);
1956 static void __evict_old_buffers(struct dm_bufio_client *c, unsigned long age_hz)
1958 struct dm_buffer *b, *tmp;
1959 unsigned long retain_target = get_retain_buffers(c);
1960 unsigned long count;
1961 LIST_HEAD(write_list);
1965 __check_watermark(c, &write_list);
1966 if (unlikely(!list_empty(&write_list))) {
1968 __flush_write_list(&write_list);
1972 count = c->n_buffers[LIST_CLEAN] + c->n_buffers[LIST_DIRTY];
1973 list_for_each_entry_safe_reverse(b, tmp, &c->lru[LIST_CLEAN], lru_list) {
1974 if (count <= retain_target)
1977 if (!older_than(b, age_hz))
1980 if (__try_evict_buffer(b, 0))
1989 static void do_global_cleanup(struct work_struct *w)
1991 struct dm_bufio_client *locked_client = NULL;
1992 struct dm_bufio_client *current_client;
1993 struct dm_buffer *b;
1994 unsigned int spinlock_hold_count;
1995 unsigned long threshold = dm_bufio_cache_size -
1996 dm_bufio_cache_size / DM_BUFIO_LOW_WATERMARK_RATIO;
1997 unsigned long loops = global_num * 2;
1999 mutex_lock(&dm_bufio_clients_lock);
2004 spin_lock(&global_spinlock);
2005 if (unlikely(dm_bufio_current_allocated <= threshold))
2008 spinlock_hold_count = 0;
2012 if (unlikely(list_empty(&global_queue)))
2014 b = list_entry(global_queue.prev, struct dm_buffer, global_list);
2018 list_move(&b->global_list, &global_queue);
2019 if (likely(++spinlock_hold_count < 16))
2021 spin_unlock(&global_spinlock);
2025 current_client = b->c;
2026 if (unlikely(current_client != locked_client)) {
2028 dm_bufio_unlock(locked_client);
2030 if (!dm_bufio_trylock(current_client)) {
2031 spin_unlock(&global_spinlock);
2032 dm_bufio_lock(current_client);
2033 locked_client = current_client;
2037 locked_client = current_client;
2040 spin_unlock(&global_spinlock);
2042 if (unlikely(!__try_evict_buffer(b, GFP_KERNEL))) {
2043 spin_lock(&global_spinlock);
2044 list_move(&b->global_list, &global_queue);
2045 spin_unlock(&global_spinlock);
2049 spin_unlock(&global_spinlock);
2052 dm_bufio_unlock(locked_client);
2054 mutex_unlock(&dm_bufio_clients_lock);
2057 static void cleanup_old_buffers(void)
2059 unsigned long max_age_hz = get_max_age_hz();
2060 struct dm_bufio_client *c;
2062 mutex_lock(&dm_bufio_clients_lock);
2064 __cache_size_refresh();
2066 list_for_each_entry(c, &dm_bufio_all_clients, client_list)
2067 __evict_old_buffers(c, max_age_hz);
2069 mutex_unlock(&dm_bufio_clients_lock);
2072 static void work_fn(struct work_struct *w)
2074 cleanup_old_buffers();
2076 queue_delayed_work(dm_bufio_wq, &dm_bufio_cleanup_old_work,
2077 DM_BUFIO_WORK_TIMER_SECS * HZ);
2081 *--------------------------------------------------------------
2083 *--------------------------------------------------------------
2087 * This is called only once for the whole dm_bufio module.
2088 * It initializes memory limit.
2090 static int __init dm_bufio_init(void)
2094 dm_bufio_allocated_kmem_cache = 0;
2095 dm_bufio_allocated_get_free_pages = 0;
2096 dm_bufio_allocated_vmalloc = 0;
2097 dm_bufio_current_allocated = 0;
2099 mem = (__u64)mult_frac(totalram_pages() - totalhigh_pages(),
2100 DM_BUFIO_MEMORY_PERCENT, 100) << PAGE_SHIFT;
2102 if (mem > ULONG_MAX)
2106 if (mem > mult_frac(VMALLOC_TOTAL, DM_BUFIO_VMALLOC_PERCENT, 100))
2107 mem = mult_frac(VMALLOC_TOTAL, DM_BUFIO_VMALLOC_PERCENT, 100);
2110 dm_bufio_default_cache_size = mem;
2112 mutex_lock(&dm_bufio_clients_lock);
2113 __cache_size_refresh();
2114 mutex_unlock(&dm_bufio_clients_lock);
2116 dm_bufio_wq = alloc_workqueue("dm_bufio_cache", WQ_MEM_RECLAIM, 0);
2120 INIT_DELAYED_WORK(&dm_bufio_cleanup_old_work, work_fn);
2121 INIT_WORK(&dm_bufio_replacement_work, do_global_cleanup);
2122 queue_delayed_work(dm_bufio_wq, &dm_bufio_cleanup_old_work,
2123 DM_BUFIO_WORK_TIMER_SECS * HZ);
2129 * This is called once when unloading the dm_bufio module.
2131 static void __exit dm_bufio_exit(void)
2135 cancel_delayed_work_sync(&dm_bufio_cleanup_old_work);
2136 destroy_workqueue(dm_bufio_wq);
2138 if (dm_bufio_client_count) {
2139 DMCRIT("%s: dm_bufio_client_count leaked: %d",
2140 __func__, dm_bufio_client_count);
2144 if (dm_bufio_current_allocated) {
2145 DMCRIT("%s: dm_bufio_current_allocated leaked: %lu",
2146 __func__, dm_bufio_current_allocated);
2150 if (dm_bufio_allocated_get_free_pages) {
2151 DMCRIT("%s: dm_bufio_allocated_get_free_pages leaked: %lu",
2152 __func__, dm_bufio_allocated_get_free_pages);
2156 if (dm_bufio_allocated_vmalloc) {
2157 DMCRIT("%s: dm_bufio_vmalloc leaked: %lu",
2158 __func__, dm_bufio_allocated_vmalloc);
2165 module_init(dm_bufio_init)
2166 module_exit(dm_bufio_exit)
2168 module_param_named(max_cache_size_bytes, dm_bufio_cache_size, ulong, S_IRUGO | S_IWUSR);
2169 MODULE_PARM_DESC(max_cache_size_bytes, "Size of metadata cache");
2171 module_param_named(max_age_seconds, dm_bufio_max_age, uint, S_IRUGO | S_IWUSR);
2172 MODULE_PARM_DESC(max_age_seconds, "Max age of a buffer in seconds");
2174 module_param_named(retain_bytes, dm_bufio_retain_bytes, ulong, S_IRUGO | S_IWUSR);
2175 MODULE_PARM_DESC(retain_bytes, "Try to keep at least this many bytes cached in memory");
2177 module_param_named(peak_allocated_bytes, dm_bufio_peak_allocated, ulong, S_IRUGO | S_IWUSR);
2178 MODULE_PARM_DESC(peak_allocated_bytes, "Tracks the maximum allocated memory");
2180 module_param_named(allocated_kmem_cache_bytes, dm_bufio_allocated_kmem_cache, ulong, S_IRUGO);
2181 MODULE_PARM_DESC(allocated_kmem_cache_bytes, "Memory allocated with kmem_cache_alloc");
2183 module_param_named(allocated_get_free_pages_bytes, dm_bufio_allocated_get_free_pages, ulong, S_IRUGO);
2184 MODULE_PARM_DESC(allocated_get_free_pages_bytes, "Memory allocated with get_free_pages");
2186 module_param_named(allocated_vmalloc_bytes, dm_bufio_allocated_vmalloc, ulong, S_IRUGO);
2187 MODULE_PARM_DESC(allocated_vmalloc_bytes, "Memory allocated with vmalloc");
2189 module_param_named(current_allocated_bytes, dm_bufio_current_allocated, ulong, S_IRUGO);
2190 MODULE_PARM_DESC(current_allocated_bytes, "Memory currently used by the cache");
2193 MODULE_DESCRIPTION(DM_NAME " buffered I/O library");
2194 MODULE_LICENSE("GPL");