xref: /linux/drivers/md/dm-bufio.c (revision 17f7f7ef5dc2f4607ba8cdf486cb25cc564cd6f7)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2009-2011 Red Hat, Inc.
4  *
5  * Author: Mikulas Patocka <mpatocka@redhat.com>
6  *
7  * This file is released under the GPL.
8  */
9 
10 #include <linux/dm-bufio.h>
11 
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>
23 
24 #include "dm.h"
25 
26 #define DM_MSG_PREFIX "bufio"
27 
28 /*
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
34  *	dirty buffers.
35  */
36 #define DM_BUFIO_MIN_BUFFERS		8
37 
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
42 
43 /*
44  * The nr of bytes of cached data to keep around.
45  */
46 #define DM_BUFIO_DEFAULT_RETAIN_BYTES   (256 * 1024)
47 
48 /*
49  * Align buffer writes to this boundary.
50  * Tests show that SSDs have the highest IOPS when using 4k writes.
51  */
52 #define DM_BUFIO_WRITE_ALIGN		4096
53 
54 /*
55  * dm_buffer->list_mode
56  */
57 #define LIST_CLEAN	0
58 #define LIST_DIRTY	1
59 #define LIST_SIZE	2
60 
61 #define SCAN_RESCHED_CYCLE	16
62 
63 /*--------------------------------------------------------------*/
64 
65 /*
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.
71  */
72 struct lru_entry {
73 	struct list_head list;
74 	atomic_t referenced;
75 };
76 
77 struct lru_iter {
78 	struct lru *lru;
79 	struct list_head list;
80 	struct lru_entry *stop;
81 	struct lru_entry *e;
82 };
83 
84 struct lru {
85 	struct list_head *cursor;
86 	unsigned long count;
87 
88 	struct list_head iterators;
89 };
90 
91 /*--------------*/
92 
93 static void lru_init(struct lru *lru)
94 {
95 	lru->cursor = NULL;
96 	lru->count = 0;
97 	INIT_LIST_HEAD(&lru->iterators);
98 }
99 
100 static void lru_destroy(struct lru *lru)
101 {
102 	WARN_ON_ONCE(lru->cursor);
103 	WARN_ON_ONCE(!list_empty(&lru->iterators));
104 }
105 
106 /*
107  * Insert a new entry into the lru.
108  */
109 static void lru_insert(struct lru *lru, struct lru_entry *le)
110 {
111 	/*
112 	 * Don't be tempted to set to 1, makes the lru aspect
113 	 * perform poorly.
114 	 */
115 	atomic_set(&le->referenced, 0);
116 
117 	if (lru->cursor) {
118 		list_add_tail(&le->list, lru->cursor);
119 	} else {
120 		INIT_LIST_HEAD(&le->list);
121 		lru->cursor = &le->list;
122 	}
123 	lru->count++;
124 }
125 
126 /*--------------*/
127 
128 /*
129  * Convert a list_head pointer to an lru_entry pointer.
130  */
131 static inline struct lru_entry *to_le(struct list_head *l)
132 {
133 	return container_of(l, struct lru_entry, list);
134 }
135 
136 /*
137  * Initialize an lru_iter and add it to the list of cursors in the lru.
138  */
139 static void lru_iter_begin(struct lru *lru, struct lru_iter *it)
140 {
141 	it->lru = lru;
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);
145 }
146 
147 /*
148  * Remove an lru_iter from the list of cursors in the lru.
149  */
150 static inline void lru_iter_end(struct lru_iter *it)
151 {
152 	list_del(&it->list);
153 }
154 
155 /* Predicate function type to be used with lru_iter_next */
156 typedef bool (*iter_predicate)(struct lru_entry *le, void *context);
157 
158 /*
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.
162  */
163 static struct lru_entry *lru_iter_next(struct lru_iter *it,
164 				       iter_predicate pred, void *context)
165 {
166 	struct lru_entry *e;
167 
168 	while (it->e) {
169 		e = it->e;
170 
171 		/* advance the cursor */
172 		if (it->e == it->stop)
173 			it->e = NULL;
174 		else
175 			it->e = to_le(it->e->list.next);
176 
177 		if (pred(e, context))
178 			return e;
179 	}
180 
181 	return NULL;
182 }
183 
184 /*
185  * Invalidate a specific lru_entry and update all cursors in
186  * the lru accordingly.
187  */
188 static void lru_iter_invalidate(struct lru *lru, struct lru_entry *e)
189 {
190 	struct lru_iter *it;
191 
192 	list_for_each_entry(it, &lru->iterators, list) {
193 		/* Move c->e forwards if necc. */
194 		if (it->e == e) {
195 			it->e = to_le(it->e->list.next);
196 			if (it->e == e)
197 				it->e = NULL;
198 		}
199 
200 		/* Move it->stop backwards if necc. */
201 		if (it->stop == e) {
202 			it->stop = to_le(it->stop->list.prev);
203 			if (it->stop == e)
204 				it->stop = NULL;
205 		}
206 	}
207 }
208 
209 /*--------------*/
210 
211 /*
212  * Remove a specific entry from the lru.
213  */
214 static void lru_remove(struct lru *lru, struct lru_entry *le)
215 {
216 	lru_iter_invalidate(lru, le);
217 	if (lru->count == 1) {
218 		lru->cursor = NULL;
219 	} else {
220 		if (lru->cursor == &le->list)
221 			lru->cursor = lru->cursor->next;
222 		list_del(&le->list);
223 	}
224 	lru->count--;
225 }
226 
227 /*
228  * Mark as referenced.
229  */
230 static inline void lru_reference(struct lru_entry *le)
231 {
232 	atomic_set(&le->referenced, 1);
233 }
234 
235 /*--------------*/
236 
237 /*
238  * Remove the least recently used entry (approx), that passes the predicate.
239  * Returns NULL on failure.
240  */
241 enum evict_result {
242 	ER_EVICT,
243 	ER_DONT_EVICT,
244 	ER_STOP, /* stop looking for something to evict */
245 };
246 
247 typedef enum evict_result (*le_predicate)(struct lru_entry *le, void *context);
248 
249 static struct lru_entry *lru_evict(struct lru *lru, le_predicate pred, void *context, bool no_sleep)
250 {
251 	unsigned long tested = 0;
252 	struct list_head *h = lru->cursor;
253 	struct lru_entry *le;
254 
255 	if (!h)
256 		return NULL;
257 	/*
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.
261 	 */
262 	while (tested < lru->count) {
263 		le = container_of(h, struct lru_entry, list);
264 
265 		if (atomic_read(&le->referenced)) {
266 			atomic_set(&le->referenced, 0);
267 		} else {
268 			tested++;
269 			switch (pred(le, context)) {
270 			case ER_EVICT:
271 				/*
272 				 * Adjust the cursor, so we start the next
273 				 * search from here.
274 				 */
275 				lru->cursor = le->list.next;
276 				lru_remove(lru, le);
277 				return le;
278 
279 			case ER_DONT_EVICT:
280 				break;
281 
282 			case ER_STOP:
283 				lru->cursor = le->list.next;
284 				return NULL;
285 			}
286 		}
287 
288 		h = h->next;
289 
290 		if (!no_sleep)
291 			cond_resched();
292 	}
293 
294 	return NULL;
295 }
296 
297 /*--------------------------------------------------------------*/
298 
299 /*
300  * Buffer state bits.
301  */
302 #define B_READING	0
303 #define B_WRITING	1
304 #define B_DIRTY		2
305 
306 /*
307  * Describes how the block was allocated:
308  * kmem_cache_alloc(), __get_free_pages() or vmalloc().
309  * See the comment at alloc_buffer_data.
310  */
311 enum data_mode {
312 	DATA_MODE_SLAB = 0,
313 	DATA_MODE_KMALLOC = 1,
314 	DATA_MODE_GET_FREE_PAGES = 2,
315 	DATA_MODE_VMALLOC = 3,
316 	DATA_MODE_LIMIT = 4
317 };
318 
319 struct dm_buffer {
320 	/* protected by the locks in dm_buffer_cache */
321 	struct rb_node node;
322 
323 	/* immutable, so don't need protecting */
324 	sector_t block;
325 	void *data;
326 	unsigned char data_mode;		/* DATA_MODE_* */
327 
328 	/*
329 	 * These two fields are used in isolation, so do not need
330 	 * a surrounding lock.
331 	 */
332 	atomic_t hold_count;
333 	unsigned long last_accessed;
334 
335 	/*
336 	 * Everything else is protected by the mutex in
337 	 * dm_bufio_client
338 	 */
339 	unsigned long state;
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
352 #define MAX_STACK 10
353 	unsigned int stack_len;
354 	unsigned long stack_entries[MAX_STACK];
355 #endif
356 };
357 
358 /*--------------------------------------------------------------*/
359 
360 /*
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
366  *
367  * It does *not* handle:
368  *  - allocation/freeing of buffers.
369  *  - IO
370  *  - Eviction or cache sizing.
371  *
372  * cache_get() and cache_put_and_wake() are threadsafe, you do not need
373  * to 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.
376  */
377 
378 struct buffer_tree {
379 	union {
380 		struct rw_semaphore lock;
381 		rwlock_t spinlock;
382 	} u;
383 	struct rb_root root;
384 } ____cacheline_aligned_in_smp;
385 
386 struct dm_buffer_cache {
387 	struct lru lru[LIST_SIZE];
388 	/*
389 	 * We spread entries across multiple trees to reduce contention
390 	 * on the locks.
391 	 */
392 	unsigned int num_locks;
393 	bool no_sleep;
394 	struct buffer_tree trees[] __counted_by(num_locks);
395 };
396 
397 static DEFINE_STATIC_KEY_FALSE(no_sleep_enabled);
398 
399 static inline unsigned int cache_index(sector_t block, unsigned int num_locks)
400 {
401 	return dm_hash_locks_index(block, num_locks);
402 }
403 
404 /* Get the buffer tree in the cache for the given block.  Doesn't lock it. */
405 static inline struct buffer_tree *cache_get_tree(struct dm_buffer_cache *bc,
406 						 sector_t block)
407 {
408 	return &bc->trees[cache_index(block, bc->num_locks)];
409 }
410 
411 /* Lock the given buffer tree in the cache for reading. */
412 static inline void cache_read_lock(struct dm_buffer_cache *bc,
413 				   struct buffer_tree *tree)
414 {
415 	if (static_branch_unlikely(&no_sleep_enabled) && bc->no_sleep)
416 		read_lock_bh(&tree->u.spinlock);
417 	else
418 		down_read(&tree->u.lock);
419 }
420 
421 /* Unlock the given buffer tree in the cache for reading. */
422 static inline void cache_read_unlock(struct dm_buffer_cache *bc,
423 				     struct buffer_tree *tree)
424 {
425 	if (static_branch_unlikely(&no_sleep_enabled) && bc->no_sleep)
426 		read_unlock_bh(&tree->u.spinlock);
427 	else
428 		up_read(&tree->u.lock);
429 }
430 
431 /* Lock the given buffer tree in the cache for writing. */
432 static inline void cache_write_lock(struct dm_buffer_cache *bc,
433 				    struct buffer_tree *tree)
434 {
435 	if (static_branch_unlikely(&no_sleep_enabled) && bc->no_sleep)
436 		write_lock_bh(&tree->u.spinlock);
437 	else
438 		down_write(&tree->u.lock);
439 }
440 
441 /* Unlock the given buffer tree in the cache for writing. */
442 static inline void cache_write_unlock(struct dm_buffer_cache *bc,
443 				      struct buffer_tree *tree)
444 {
445 	if (static_branch_unlikely(&no_sleep_enabled) && bc->no_sleep)
446 		write_unlock_bh(&tree->u.spinlock);
447 	else
448 		up_write(&tree->u.lock);
449 }
450 
451 /*
452  * Sometimes we want to repeatedly get and drop locks as part of an iteration.
453  * This struct helps avoid redundant drop and gets of the same lock.
454  */
455 struct lock_history {
456 	struct dm_buffer_cache *cache;
457 	bool write;
458 	unsigned int previous;
459 	unsigned int no_previous;
460 };
461 
462 static void lh_init(struct lock_history *lh, struct dm_buffer_cache *cache, bool write)
463 {
464 	lh->cache = cache;
465 	lh->write = write;
466 	lh->no_previous = cache->num_locks;
467 	lh->previous = lh->no_previous;
468 }
469 
470 static void __lh_lock(struct lock_history *lh, unsigned int index)
471 {
472 	if (lh->write) {
473 		if (static_branch_unlikely(&no_sleep_enabled) && lh->cache->no_sleep)
474 			write_lock_bh(&lh->cache->trees[index].u.spinlock);
475 		else
476 			down_write(&lh->cache->trees[index].u.lock);
477 	} else {
478 		if (static_branch_unlikely(&no_sleep_enabled) && lh->cache->no_sleep)
479 			read_lock_bh(&lh->cache->trees[index].u.spinlock);
480 		else
481 			down_read(&lh->cache->trees[index].u.lock);
482 	}
483 }
484 
485 static void __lh_unlock(struct lock_history *lh, unsigned int index)
486 {
487 	if (lh->write) {
488 		if (static_branch_unlikely(&no_sleep_enabled) && lh->cache->no_sleep)
489 			write_unlock_bh(&lh->cache->trees[index].u.spinlock);
490 		else
491 			up_write(&lh->cache->trees[index].u.lock);
492 	} else {
493 		if (static_branch_unlikely(&no_sleep_enabled) && lh->cache->no_sleep)
494 			read_unlock_bh(&lh->cache->trees[index].u.spinlock);
495 		else
496 			up_read(&lh->cache->trees[index].u.lock);
497 	}
498 }
499 
500 /*
501  * Make sure you call this since it will unlock the final lock.
502  */
503 static void lh_exit(struct lock_history *lh)
504 {
505 	if (lh->previous != lh->no_previous) {
506 		__lh_unlock(lh, lh->previous);
507 		lh->previous = lh->no_previous;
508 	}
509 }
510 
511 /*
512  * Named 'next' because there is no corresponding
513  * 'up/unlock' call since it's done automatically.
514  */
515 static void lh_next(struct lock_history *lh, sector_t b)
516 {
517 	unsigned int index = cache_index(b, lh->no_previous); /* no_previous is num_locks */
518 
519 	if (lh->previous != lh->no_previous) {
520 		if (lh->previous != index) {
521 			__lh_unlock(lh, lh->previous);
522 			__lh_lock(lh, index);
523 			lh->previous = index;
524 		}
525 	} else {
526 		__lh_lock(lh, index);
527 		lh->previous = index;
528 	}
529 }
530 
531 static inline struct dm_buffer *le_to_buffer(struct lru_entry *le)
532 {
533 	return container_of(le, struct dm_buffer, lru);
534 }
535 
536 static struct dm_buffer *list_to_buffer(struct list_head *l)
537 {
538 	struct lru_entry *le = list_entry(l, struct lru_entry, list);
539 
540 	return le_to_buffer(le);
541 }
542 
543 static void cache_init(struct dm_buffer_cache *bc, unsigned int num_locks, bool no_sleep)
544 {
545 	unsigned int i;
546 
547 	bc->num_locks = num_locks;
548 	bc->no_sleep = no_sleep;
549 
550 	for (i = 0; i < bc->num_locks; i++) {
551 		if (no_sleep)
552 			rwlock_init(&bc->trees[i].u.spinlock);
553 		else
554 			init_rwsem(&bc->trees[i].u.lock);
555 		bc->trees[i].root = RB_ROOT;
556 	}
557 
558 	lru_init(&bc->lru[LIST_CLEAN]);
559 	lru_init(&bc->lru[LIST_DIRTY]);
560 }
561 
562 static void cache_destroy(struct dm_buffer_cache *bc)
563 {
564 	unsigned int i;
565 
566 	for (i = 0; i < bc->num_locks; i++)
567 		WARN_ON_ONCE(!RB_EMPTY_ROOT(&bc->trees[i].root));
568 
569 	lru_destroy(&bc->lru[LIST_CLEAN]);
570 	lru_destroy(&bc->lru[LIST_DIRTY]);
571 }
572 
573 /*--------------*/
574 
575 /*
576  * not threadsafe, or racey depending how you look at it
577  */
578 static inline unsigned long cache_count(struct dm_buffer_cache *bc, int list_mode)
579 {
580 	return bc->lru[list_mode].count;
581 }
582 
583 static inline unsigned long cache_total(struct dm_buffer_cache *bc)
584 {
585 	return cache_count(bc, LIST_CLEAN) + cache_count(bc, LIST_DIRTY);
586 }
587 
588 /*--------------*/
589 
590 /*
591  * Gets a specific buffer, indexed by block.
592  * If the buffer is found then its holder count will be incremented and
593  * lru_reference will be called.
594  *
595  * threadsafe
596  */
597 static struct dm_buffer *__cache_get(const struct rb_root *root, sector_t block)
598 {
599 	struct rb_node *n = root->rb_node;
600 	struct dm_buffer *b;
601 
602 	while (n) {
603 		b = container_of(n, struct dm_buffer, node);
604 
605 		if (b->block == block)
606 			return b;
607 
608 		n = block < b->block ? n->rb_left : n->rb_right;
609 	}
610 
611 	return NULL;
612 }
613 
614 static void __cache_inc_buffer(struct dm_buffer *b)
615 {
616 	atomic_inc(&b->hold_count);
617 	WRITE_ONCE(b->last_accessed, jiffies);
618 }
619 
620 static struct dm_buffer *cache_get(struct dm_buffer_cache *bc,
621 				   struct buffer_tree *tree, sector_t block)
622 {
623 	struct dm_buffer *b;
624 
625 	/* Assuming tree == cache_get_tree(bc, block) */
626 	cache_read_lock(bc, tree);
627 	b = __cache_get(&tree->root, block);
628 	if (b) {
629 		lru_reference(&b->lru);
630 		__cache_inc_buffer(b);
631 	}
632 	cache_read_unlock(bc, tree);
633 
634 	return b;
635 }
636 
637 /*--------------*/
638 
639 typedef enum evict_result (*b_predicate)(struct dm_buffer *, void *);
640 
641 /*
642  * Evicts a buffer based on a predicate.  The oldest buffer that
643  * matches the predicate will be selected.  In addition to the
644  * predicate the hold_count of the selected buffer will be zero.
645  */
646 struct evict_wrapper {
647 	struct lock_history *lh;
648 	b_predicate pred;
649 	void *context;
650 };
651 
652 /*
653  * Wraps the buffer predicate turning it into an lru predicate.  Adds
654  * extra test for hold_count.
655  */
656 static enum evict_result __evict_pred(struct lru_entry *le, void *context)
657 {
658 	struct evict_wrapper *w = context;
659 	struct dm_buffer *b = le_to_buffer(le);
660 
661 	lh_next(w->lh, b->block);
662 
663 	if (atomic_read(&b->hold_count))
664 		return ER_DONT_EVICT;
665 
666 	return w->pred(b, w->context);
667 }
668 
669 static struct dm_buffer *__cache_evict(struct dm_buffer_cache *bc, int list_mode,
670 				       b_predicate pred, void *context,
671 				       struct lock_history *lh)
672 {
673 	struct evict_wrapper w = {.lh = lh, .pred = pred, .context = context};
674 	struct lru_entry *le;
675 	struct dm_buffer *b;
676 
677 	le = lru_evict(&bc->lru[list_mode], __evict_pred, &w, bc->no_sleep);
678 	if (!le)
679 		return NULL;
680 
681 	b = le_to_buffer(le);
682 	/* __evict_pred will have locked the appropriate tree. */
683 	rb_erase(&b->node, &cache_get_tree(bc, b->block)->root);
684 
685 	return b;
686 }
687 
688 static struct dm_buffer *cache_evict(struct dm_buffer_cache *bc, int list_mode,
689 				     b_predicate pred, void *context)
690 {
691 	struct dm_buffer *b;
692 	struct lock_history lh;
693 
694 	lh_init(&lh, bc, true);
695 	b = __cache_evict(bc, list_mode, pred, context, &lh);
696 	lh_exit(&lh);
697 
698 	return b;
699 }
700 
701 /*--------------*/
702 
703 /*
704  * Mark a buffer as clean or dirty. Not threadsafe.
705  */
706 static void cache_mark(struct dm_buffer_cache *bc, struct buffer_tree *tree,
707 		       struct dm_buffer *b, int list_mode)
708 {
709 	/* Assuming tree == cache_get_tree(bc, b->block) */
710 	cache_write_lock(bc, tree);
711 	if (list_mode != b->list_mode) {
712 		lru_remove(&bc->lru[b->list_mode], &b->lru);
713 		b->list_mode = list_mode;
714 		lru_insert(&bc->lru[b->list_mode], &b->lru);
715 	}
716 	cache_write_unlock(bc, tree);
717 }
718 
719 /*--------------*/
720 
721 /*
722  * Runs through the lru associated with 'old_mode', if the predicate matches then
723  * it moves them to 'new_mode'.  Not threadsafe.
724  */
725 static void __cache_mark_many(struct dm_buffer_cache *bc, int old_mode, int new_mode,
726 			      b_predicate pred, void *context, struct lock_history *lh)
727 {
728 	struct lru_entry *le;
729 	struct dm_buffer *b;
730 	struct evict_wrapper w = {.lh = lh, .pred = pred, .context = context};
731 
732 	while (true) {
733 		le = lru_evict(&bc->lru[old_mode], __evict_pred, &w, bc->no_sleep);
734 		if (!le)
735 			break;
736 
737 		b = le_to_buffer(le);
738 		b->list_mode = new_mode;
739 		lru_insert(&bc->lru[b->list_mode], &b->lru);
740 	}
741 }
742 
743 static void cache_mark_many(struct dm_buffer_cache *bc, int old_mode, int new_mode,
744 			    b_predicate pred, void *context)
745 {
746 	struct lock_history lh;
747 
748 	lh_init(&lh, bc, true);
749 	__cache_mark_many(bc, old_mode, new_mode, pred, context, &lh);
750 	lh_exit(&lh);
751 }
752 
753 /*--------------*/
754 
755 /*
756  * Iterates through all clean or dirty entries calling a function for each
757  * entry.  The callback may terminate the iteration early.  Not threadsafe.
758  */
759 
760 /*
761  * Iterator functions should return one of these actions to indicate
762  * how the iteration should proceed.
763  */
764 enum it_action {
765 	IT_NEXT,
766 	IT_COMPLETE,
767 };
768 
769 typedef enum it_action (*iter_fn)(struct dm_buffer *b, void *context);
770 
771 static void __cache_iterate(struct dm_buffer_cache *bc, int list_mode,
772 			    iter_fn fn, void *context, struct lock_history *lh)
773 {
774 	struct lru *lru = &bc->lru[list_mode];
775 	struct lru_entry *le, *first;
776 
777 	if (!lru->cursor)
778 		return;
779 
780 	first = le = to_le(lru->cursor);
781 	do {
782 		struct dm_buffer *b = le_to_buffer(le);
783 
784 		lh_next(lh, b->block);
785 
786 		switch (fn(b, context)) {
787 		case IT_NEXT:
788 			break;
789 
790 		case IT_COMPLETE:
791 			return;
792 		}
793 		cond_resched();
794 
795 		le = to_le(le->list.next);
796 	} while (le != first);
797 }
798 
799 static void cache_iterate(struct dm_buffer_cache *bc, int list_mode,
800 			  iter_fn fn, void *context)
801 {
802 	struct lock_history lh;
803 
804 	lh_init(&lh, bc, false);
805 	__cache_iterate(bc, list_mode, fn, context, &lh);
806 	lh_exit(&lh);
807 }
808 
809 /*--------------*/
810 
811 /*
812  * Passes ownership of the buffer to the cache. Returns false if the
813  * buffer was already present (in which case ownership does not pass).
814  * eg, a race with another thread.
815  *
816  * Holder count should be 1 on insertion.
817  *
818  * Not threadsafe.
819  */
820 static bool __cache_insert(struct rb_root *root, struct dm_buffer *b)
821 {
822 	struct rb_node **new = &root->rb_node, *parent = NULL;
823 	struct dm_buffer *found;
824 
825 	while (*new) {
826 		found = container_of(*new, struct dm_buffer, node);
827 
828 		if (found->block == b->block)
829 			return false;
830 
831 		parent = *new;
832 		new = b->block < found->block ?
833 			&found->node.rb_left : &found->node.rb_right;
834 	}
835 
836 	rb_link_node(&b->node, parent, new);
837 	rb_insert_color(&b->node, root);
838 
839 	return true;
840 }
841 
842 static bool cache_insert(struct dm_buffer_cache *bc, struct buffer_tree *tree,
843 			 struct dm_buffer *b)
844 {
845 	bool r;
846 
847 	if (WARN_ON_ONCE(b->list_mode >= LIST_SIZE))
848 		return false;
849 
850 	/* Assuming tree == cache_get_tree(bc, b->block) */
851 	cache_write_lock(bc, tree);
852 	BUG_ON(atomic_read(&b->hold_count) != 1);
853 	r = __cache_insert(&tree->root, b);
854 	if (r)
855 		lru_insert(&bc->lru[b->list_mode], &b->lru);
856 	cache_write_unlock(bc, tree);
857 
858 	return r;
859 }
860 
861 /*--------------*/
862 
863 /*
864  * Removes buffer from cache, ownership of the buffer passes back to the caller.
865  * Fails if the hold_count is not one (ie. the caller holds the only reference).
866  *
867  * Not threadsafe.
868  */
869 static bool cache_remove(struct dm_buffer_cache *bc, struct buffer_tree *tree,
870 			 struct dm_buffer *b)
871 {
872 	bool r;
873 
874 	/* Assuming tree == cache_get_tree(bc, b->block) */
875 	cache_write_lock(bc, tree);
876 
877 	if (atomic_read(&b->hold_count) != 1) {
878 		r = false;
879 	} else {
880 		r = true;
881 		rb_erase(&b->node, &tree->root);
882 		lru_remove(&bc->lru[b->list_mode], &b->lru);
883 	}
884 
885 	cache_write_unlock(bc, tree);
886 
887 	return r;
888 }
889 
890 /*--------------*/
891 
892 typedef void (*b_release)(struct dm_buffer *);
893 
894 static struct dm_buffer *__find_next(struct rb_root *root, sector_t block)
895 {
896 	struct rb_node *n = root->rb_node;
897 	struct dm_buffer *b;
898 	struct dm_buffer *best = NULL;
899 
900 	while (n) {
901 		b = container_of(n, struct dm_buffer, node);
902 
903 		if (b->block == block)
904 			return b;
905 
906 		if (block <= b->block) {
907 			n = n->rb_left;
908 			best = b;
909 		} else {
910 			n = n->rb_right;
911 		}
912 	}
913 
914 	return best;
915 }
916 
917 static void __remove_range(struct dm_buffer_cache *bc,
918 			   struct rb_root *root,
919 			   sector_t begin, sector_t end,
920 			   b_predicate pred, b_release release)
921 {
922 	struct dm_buffer *b;
923 
924 	while (true) {
925 		cond_resched();
926 
927 		b = __find_next(root, begin);
928 		if (!b || (b->block >= end))
929 			break;
930 
931 		begin = b->block + 1;
932 
933 		if (atomic_read(&b->hold_count))
934 			continue;
935 
936 		if (pred(b, NULL) == ER_EVICT) {
937 			rb_erase(&b->node, root);
938 			lru_remove(&bc->lru[b->list_mode], &b->lru);
939 			release(b);
940 		}
941 	}
942 }
943 
944 static void cache_remove_range(struct dm_buffer_cache *bc,
945 			       sector_t begin, sector_t end,
946 			       b_predicate pred, b_release release)
947 {
948 	unsigned int i;
949 
950 	BUG_ON(bc->no_sleep);
951 	for (i = 0; i < bc->num_locks; i++) {
952 		down_write(&bc->trees[i].u.lock);
953 		__remove_range(bc, &bc->trees[i].root, begin, end, pred, release);
954 		up_write(&bc->trees[i].u.lock);
955 	}
956 }
957 
958 /*----------------------------------------------------------------*/
959 
960 /*
961  * Linking of buffers:
962  *	All buffers are linked to buffer_cache with their node field.
963  *
964  *	Clean buffers that are not being written (B_WRITING not set)
965  *	are linked to lru[LIST_CLEAN] with their lru_list field.
966  *
967  *	Dirty and clean buffers that are being written are linked to
968  *	lru[LIST_DIRTY] with their lru_list field. When the write
969  *	finishes, the buffer cannot be relinked immediately (because we
970  *	are in an interrupt context and relinking requires process
971  *	context), so some clean-not-writing buffers can be held on
972  *	dirty_lru too.  They are later added to lru in the process
973  *	context.
974  */
975 struct dm_bufio_client {
976 	struct block_device *bdev;
977 	unsigned int block_size;
978 	s8 sectors_per_block_bits;
979 
980 	bool no_sleep;
981 	struct mutex lock;
982 	spinlock_t spinlock;
983 
984 	int async_write_error;
985 
986 	void (*alloc_callback)(struct dm_buffer *buf);
987 	void (*write_callback)(struct dm_buffer *buf);
988 	struct kmem_cache *slab_buffer;
989 	struct kmem_cache *slab_cache;
990 	struct dm_io_client *dm_io;
991 
992 	struct list_head reserved_buffers;
993 	unsigned int need_reserved_buffers;
994 
995 	unsigned int minimum_buffers;
996 
997 	sector_t start;
998 
999 	struct shrinker *shrinker;
1000 	struct work_struct shrink_work;
1001 	atomic_long_t need_shrink;
1002 
1003 	wait_queue_head_t free_buffer_wait;
1004 
1005 	struct list_head client_list;
1006 
1007 	/*
1008 	 * Used by global_cleanup to sort the clients list.
1009 	 */
1010 	unsigned long oldest_buffer;
1011 
1012 	struct dm_buffer_cache cache; /* must be last member */
1013 };
1014 
1015 /*----------------------------------------------------------------*/
1016 
1017 #define dm_bufio_in_request()	(!!current->bio_list)
1018 
1019 static void dm_bufio_lock(struct dm_bufio_client *c)
1020 {
1021 	if (static_branch_unlikely(&no_sleep_enabled) && c->no_sleep)
1022 		spin_lock_bh(&c->spinlock);
1023 	else
1024 		mutex_lock_nested(&c->lock, dm_bufio_in_request());
1025 }
1026 
1027 static void dm_bufio_unlock(struct dm_bufio_client *c)
1028 {
1029 	if (static_branch_unlikely(&no_sleep_enabled) && c->no_sleep)
1030 		spin_unlock_bh(&c->spinlock);
1031 	else
1032 		mutex_unlock(&c->lock);
1033 }
1034 
1035 /*----------------------------------------------------------------*/
1036 
1037 /*
1038  * Default cache size: available memory divided by the ratio.
1039  */
1040 static unsigned long dm_bufio_default_cache_size;
1041 
1042 /*
1043  * Total cache size set by the user.
1044  */
1045 static unsigned long dm_bufio_cache_size;
1046 
1047 static DEFINE_SPINLOCK(global_spinlock);
1048 
1049 static unsigned int dm_bufio_max_age; /* No longer does anything */
1050 
1051 static unsigned long dm_bufio_retain_bytes = DM_BUFIO_DEFAULT_RETAIN_BYTES;
1052 
1053 static unsigned long dm_bufio_peak_allocated;
1054 static unsigned long dm_bufio_allocated_kmem_cache;
1055 static unsigned long dm_bufio_allocated_kmalloc;
1056 static unsigned long dm_bufio_allocated_get_free_pages;
1057 static unsigned long dm_bufio_allocated_vmalloc;
1058 static unsigned long dm_bufio_current_allocated;
1059 
1060 /*----------------------------------------------------------------*/
1061 
1062 /*
1063  * The current number of clients.
1064  */
1065 static int dm_bufio_client_count;
1066 
1067 /*
1068  * The list of all clients.
1069  */
1070 static LIST_HEAD(dm_bufio_all_clients);
1071 
1072 /*
1073  * This mutex protects dm_bufio_client_count
1074  */
1075 static DEFINE_MUTEX(dm_bufio_clients_lock);
1076 
1077 static struct workqueue_struct *dm_bufio_wq;
1078 static struct work_struct dm_bufio_replacement_work;
1079 
1080 
1081 #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
1082 static void buffer_record_stack(struct dm_buffer *b)
1083 {
1084 	b->stack_len = stack_trace_save(b->stack_entries, MAX_STACK, 2);
1085 }
1086 #endif
1087 
1088 /*----------------------------------------------------------------*/
1089 
1090 static unsigned long dm_budio_get_cache_size(void)
1091 {
1092 	unsigned long s = READ_ONCE(dm_bufio_cache_size);
1093 	if (unlikely(!s)) {
1094 		unsigned long d = dm_bufio_default_cache_size;
1095 		(void)cmpxchg(&dm_bufio_cache_size, 0, d);
1096 		s = d;
1097 	}
1098 	return s;
1099 }
1100 
1101 static void adjust_total_allocated(struct dm_buffer *b, bool unlink)
1102 {
1103 	unsigned char data_mode;
1104 	long diff;
1105 
1106 	static unsigned long * const class_ptr[DATA_MODE_LIMIT] = {
1107 		&dm_bufio_allocated_kmem_cache,
1108 		&dm_bufio_allocated_kmalloc,
1109 		&dm_bufio_allocated_get_free_pages,
1110 		&dm_bufio_allocated_vmalloc,
1111 	};
1112 
1113 	data_mode = b->data_mode;
1114 	diff = (long)b->c->block_size;
1115 	if (unlink)
1116 		diff = -diff;
1117 
1118 	spin_lock(&global_spinlock);
1119 
1120 	*class_ptr[data_mode] += diff;
1121 
1122 	dm_bufio_current_allocated += diff;
1123 
1124 	if (dm_bufio_current_allocated > dm_bufio_peak_allocated)
1125 		dm_bufio_peak_allocated = dm_bufio_current_allocated;
1126 
1127 	if (!unlink) {
1128 		if (dm_bufio_current_allocated > dm_budio_get_cache_size())
1129 			queue_work(dm_bufio_wq, &dm_bufio_replacement_work);
1130 	}
1131 
1132 	spin_unlock(&global_spinlock);
1133 }
1134 
1135 /*
1136  * Allocating buffer data.
1137  *
1138  * Small buffers are allocated with kmem_cache, to use space optimally.
1139  *
1140  * For large buffers, we choose between get_free_pages and vmalloc.
1141  * Each has advantages and disadvantages.
1142  *
1143  * __get_free_pages can randomly fail if the memory is fragmented.
1144  * __vmalloc won't randomly fail, but vmalloc space is limited (it may be
1145  * as low as 128M) so using it for caching is not appropriate.
1146  *
1147  * If the allocation may fail we use __get_free_pages. Memory fragmentation
1148  * won't have a fatal effect here, but it just causes flushes of some other
1149  * buffers and more I/O will be performed. Don't use __get_free_pages if it
1150  * always fails (i.e. order > MAX_PAGE_ORDER).
1151  *
1152  * If the allocation shouldn't fail we use __vmalloc. This is only for the
1153  * initial reserve allocation, so there's no risk of wasting all vmalloc
1154  * space.
1155  */
1156 static void *alloc_buffer_data(struct dm_bufio_client *c, gfp_t gfp_mask,
1157 			       unsigned char *data_mode)
1158 {
1159 	if (unlikely(c->slab_cache != NULL)) {
1160 		*data_mode = DATA_MODE_SLAB;
1161 		return kmem_cache_alloc(c->slab_cache, gfp_mask);
1162 	}
1163 
1164 	if (unlikely(c->block_size < PAGE_SIZE)) {
1165 		*data_mode = DATA_MODE_KMALLOC;
1166 		return kmalloc(c->block_size, gfp_mask | __GFP_RECLAIMABLE);
1167 	}
1168 
1169 	if (c->block_size <= KMALLOC_MAX_SIZE &&
1170 	    gfp_mask & __GFP_NORETRY) {
1171 		*data_mode = DATA_MODE_GET_FREE_PAGES;
1172 		return (void *)__get_free_pages(gfp_mask,
1173 						c->sectors_per_block_bits - (PAGE_SHIFT - SECTOR_SHIFT));
1174 	}
1175 
1176 	*data_mode = DATA_MODE_VMALLOC;
1177 
1178 	return __vmalloc(c->block_size, gfp_mask);
1179 }
1180 
1181 /*
1182  * Free buffer's data.
1183  */
1184 static void free_buffer_data(struct dm_bufio_client *c,
1185 			     void *data, unsigned char data_mode)
1186 {
1187 	switch (data_mode) {
1188 	case DATA_MODE_SLAB:
1189 		kmem_cache_free(c->slab_cache, data);
1190 		break;
1191 
1192 	case DATA_MODE_KMALLOC:
1193 		kfree(data);
1194 		break;
1195 
1196 	case DATA_MODE_GET_FREE_PAGES:
1197 		free_pages((unsigned long)data,
1198 			   c->sectors_per_block_bits - (PAGE_SHIFT - SECTOR_SHIFT));
1199 		break;
1200 
1201 	case DATA_MODE_VMALLOC:
1202 		vfree(data);
1203 		break;
1204 
1205 	default:
1206 		DMCRIT("dm_bufio_free_buffer_data: bad data mode: %d",
1207 		       data_mode);
1208 		BUG();
1209 	}
1210 }
1211 
1212 /*
1213  * Allocate buffer and its data.
1214  */
1215 static struct dm_buffer *alloc_buffer(struct dm_bufio_client *c, gfp_t gfp_mask)
1216 {
1217 	struct dm_buffer *b = kmem_cache_alloc(c->slab_buffer, gfp_mask);
1218 
1219 	if (!b)
1220 		return NULL;
1221 
1222 	b->c = c;
1223 
1224 	b->data = alloc_buffer_data(c, gfp_mask, &b->data_mode);
1225 	if (!b->data) {
1226 		kmem_cache_free(c->slab_buffer, b);
1227 		return NULL;
1228 	}
1229 	adjust_total_allocated(b, false);
1230 
1231 #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
1232 	b->stack_len = 0;
1233 #endif
1234 	return b;
1235 }
1236 
1237 /*
1238  * Free buffer and its data.
1239  */
1240 static void free_buffer(struct dm_buffer *b)
1241 {
1242 	struct dm_bufio_client *c = b->c;
1243 
1244 	adjust_total_allocated(b, true);
1245 	free_buffer_data(c, b->data, b->data_mode);
1246 	kmem_cache_free(c->slab_buffer, b);
1247 }
1248 
1249 /*
1250  *--------------------------------------------------------------------------
1251  * Submit I/O on the buffer.
1252  *
1253  * Bio interface is faster but it has some problems:
1254  *	the vector list is limited (increasing this limit increases
1255  *	memory-consumption per buffer, so it is not viable);
1256  *
1257  *	the memory must be direct-mapped, not vmalloced;
1258  *
1259  * If the buffer is small enough (up to DM_BUFIO_INLINE_VECS pages) and
1260  * it is not vmalloced, try using the bio interface.
1261  *
1262  * If the buffer is big, if it is vmalloced or if the underlying device
1263  * rejects the bio because it is too large, use dm-io layer to do the I/O.
1264  * The dm-io layer splits the I/O into multiple requests, avoiding the above
1265  * shortcomings.
1266  *--------------------------------------------------------------------------
1267  */
1268 
1269 /*
1270  * dm-io completion routine. It just calls b->bio.bi_end_io, pretending
1271  * that the request was handled directly with bio interface.
1272  */
1273 static void dmio_complete(unsigned long error, unsigned long unsup, void *context)
1274 {
1275 	struct dm_buffer *b = context;
1276 
1277 	b->end_io(b, unlikely(error != 0) ? BLK_STS_IOERR : unlikely(unsup != 0) ? BLK_STS_NOTSUPP : 0);
1278 }
1279 
1280 static void use_dmio(struct dm_buffer *b, enum req_op op, sector_t sector,
1281 		     unsigned int n_sectors, unsigned int offset,
1282 		     unsigned short ioprio)
1283 {
1284 	int r;
1285 	struct dm_io_request io_req = {
1286 		.bi_opf = op,
1287 		.notify.fn = dmio_complete,
1288 		.notify.context = b,
1289 		.client = b->c->dm_io,
1290 	};
1291 	struct dm_io_region region = {
1292 		.bdev = b->c->bdev,
1293 		.sector = sector,
1294 		.count = n_sectors,
1295 	};
1296 
1297 	if (b->data_mode != DATA_MODE_VMALLOC) {
1298 		io_req.mem.type = DM_IO_KMEM;
1299 		io_req.mem.ptr.addr = (char *)b->data + offset;
1300 	} else {
1301 		io_req.mem.type = DM_IO_VMA;
1302 		io_req.mem.ptr.vma = (char *)b->data + offset;
1303 	}
1304 
1305 	r = dm_io(&io_req, 1, &region, NULL, NULL, ioprio);
1306 	if (unlikely(r))
1307 		b->end_io(b, errno_to_blk_status(r));
1308 }
1309 
1310 static void bio_complete(struct bio *bio)
1311 {
1312 	struct dm_buffer *b = bio->bi_private;
1313 	blk_status_t status = bio->bi_status;
1314 
1315 	bio_uninit(bio);
1316 	kfree(bio);
1317 	b->end_io(b, status);
1318 }
1319 
1320 static void use_bio(struct dm_buffer *b, enum req_op op, sector_t sector,
1321 		    unsigned int n_sectors, unsigned int offset,
1322 		    unsigned short ioprio)
1323 {
1324 	struct bio *bio;
1325 	char *ptr;
1326 	unsigned int len;
1327 
1328 	bio = bio_kmalloc(1, GFP_NOWAIT);
1329 	if (!bio) {
1330 		use_dmio(b, op, sector, n_sectors, offset, ioprio);
1331 		return;
1332 	}
1333 	bio_init_inline(bio, b->c->bdev, 1, op);
1334 	bio->bi_iter.bi_sector = sector;
1335 	bio->bi_end_io = bio_complete;
1336 	bio->bi_private = b;
1337 	bio->bi_ioprio = ioprio;
1338 
1339 	ptr = (char *)b->data + offset;
1340 	len = n_sectors << SECTOR_SHIFT;
1341 
1342 	bio_add_virt_nofail(bio, ptr, len);
1343 
1344 	submit_bio(bio);
1345 }
1346 
1347 static inline sector_t block_to_sector(struct dm_bufio_client *c, sector_t block)
1348 {
1349 	sector_t sector;
1350 
1351 	if (likely(c->sectors_per_block_bits >= 0))
1352 		sector = block << c->sectors_per_block_bits;
1353 	else
1354 		sector = block * (c->block_size >> SECTOR_SHIFT);
1355 	sector += c->start;
1356 
1357 	return sector;
1358 }
1359 
1360 static void submit_io(struct dm_buffer *b, enum req_op op, unsigned short ioprio,
1361 		      void (*end_io)(struct dm_buffer *, blk_status_t))
1362 {
1363 	unsigned int n_sectors;
1364 	sector_t sector;
1365 	unsigned int offset, end, align;
1366 
1367 	b->end_io = end_io;
1368 
1369 	sector = block_to_sector(b->c, b->block);
1370 
1371 	if (op != REQ_OP_WRITE) {
1372 		n_sectors = b->c->block_size >> SECTOR_SHIFT;
1373 		offset = 0;
1374 	} else {
1375 		if (b->c->write_callback)
1376 			b->c->write_callback(b);
1377 		offset = b->write_start;
1378 		end = b->write_end;
1379 		align = max(DM_BUFIO_WRITE_ALIGN,
1380 			bdev_physical_block_size(b->c->bdev));
1381 		offset &= -align;
1382 		end += align - 1;
1383 		end &= -align;
1384 		if (unlikely(end > b->c->block_size))
1385 			end = b->c->block_size;
1386 
1387 		sector += offset >> SECTOR_SHIFT;
1388 		n_sectors = (end - offset) >> SECTOR_SHIFT;
1389 	}
1390 
1391 	if (b->data_mode != DATA_MODE_VMALLOC)
1392 		use_bio(b, op, sector, n_sectors, offset, ioprio);
1393 	else
1394 		use_dmio(b, op, sector, n_sectors, offset, ioprio);
1395 }
1396 
1397 /*
1398  *--------------------------------------------------------------
1399  * Writing dirty buffers
1400  *--------------------------------------------------------------
1401  */
1402 
1403 /*
1404  * The endio routine for write.
1405  *
1406  * Set the error, clear B_WRITING bit and wake anyone who was waiting on
1407  * it.
1408  */
1409 static void write_endio(struct dm_buffer *b, blk_status_t status)
1410 {
1411 	b->write_error = status;
1412 	if (unlikely(status)) {
1413 		struct dm_bufio_client *c = b->c;
1414 
1415 		(void)cmpxchg(&c->async_write_error, 0,
1416 				blk_status_to_errno(status));
1417 	}
1418 
1419 	BUG_ON(!test_bit(B_WRITING, &b->state));
1420 
1421 	smp_mb__before_atomic();
1422 	clear_bit(B_WRITING, &b->state);
1423 	smp_mb__after_atomic();
1424 
1425 	wake_up_bit(&b->state, B_WRITING);
1426 }
1427 
1428 /*
1429  * Initiate a write on a dirty buffer, but don't wait for it.
1430  *
1431  * - If the buffer is not dirty, exit.
1432  * - If there some previous write going on, wait for it to finish (we can't
1433  *   have two writes on the same buffer simultaneously).
1434  * - Submit our write and don't wait on it. We set B_WRITING indicating
1435  *   that there is a write in progress.
1436  */
1437 static void __write_dirty_buffer(struct dm_buffer *b,
1438 				 struct list_head *write_list)
1439 {
1440 	if (!test_bit(B_DIRTY, &b->state))
1441 		return;
1442 
1443 	clear_bit(B_DIRTY, &b->state);
1444 	wait_on_bit_lock_io(&b->state, B_WRITING, TASK_UNINTERRUPTIBLE);
1445 
1446 	b->write_start = b->dirty_start;
1447 	b->write_end = b->dirty_end;
1448 
1449 	if (!write_list)
1450 		submit_io(b, REQ_OP_WRITE, IOPRIO_DEFAULT, write_endio);
1451 	else
1452 		list_add_tail(&b->write_list, write_list);
1453 }
1454 
1455 static void __flush_write_list(struct list_head *write_list)
1456 {
1457 	struct blk_plug plug;
1458 
1459 	blk_start_plug(&plug);
1460 	while (!list_empty(write_list)) {
1461 		struct dm_buffer *b =
1462 			list_entry(write_list->next, struct dm_buffer, write_list);
1463 		list_del(&b->write_list);
1464 		submit_io(b, REQ_OP_WRITE, IOPRIO_DEFAULT, write_endio);
1465 		cond_resched();
1466 	}
1467 	blk_finish_plug(&plug);
1468 }
1469 
1470 /*
1471  * Wait until any activity on the buffer finishes.  Possibly write the
1472  * buffer if it is dirty.  When this function finishes, there is no I/O
1473  * running on the buffer and the buffer is not dirty.
1474  */
1475 static void __make_buffer_clean(struct dm_buffer *b)
1476 {
1477 	BUG_ON(atomic_read(&b->hold_count));
1478 
1479 	/* smp_load_acquire() pairs with read_endio()'s smp_mb__before_atomic() */
1480 	if (!smp_load_acquire(&b->state))	/* fast case */
1481 		return;
1482 
1483 	wait_on_bit_io(&b->state, B_READING, TASK_UNINTERRUPTIBLE);
1484 	__write_dirty_buffer(b, NULL);
1485 	wait_on_bit_io(&b->state, B_WRITING, TASK_UNINTERRUPTIBLE);
1486 }
1487 
1488 static enum evict_result is_clean(struct dm_buffer *b, void *context)
1489 {
1490 	struct dm_bufio_client *c = context;
1491 
1492 	/* These should never happen */
1493 	if (WARN_ON_ONCE(test_bit(B_WRITING, &b->state)))
1494 		return ER_DONT_EVICT;
1495 	if (WARN_ON_ONCE(test_bit(B_DIRTY, &b->state)))
1496 		return ER_DONT_EVICT;
1497 	if (WARN_ON_ONCE(b->list_mode != LIST_CLEAN))
1498 		return ER_DONT_EVICT;
1499 
1500 	if (static_branch_unlikely(&no_sleep_enabled) && c->no_sleep &&
1501 	    unlikely(test_bit(B_READING, &b->state)))
1502 		return ER_DONT_EVICT;
1503 
1504 	return ER_EVICT;
1505 }
1506 
1507 static enum evict_result is_dirty(struct dm_buffer *b, void *context)
1508 {
1509 	/* These should never happen */
1510 	if (WARN_ON_ONCE(test_bit(B_READING, &b->state)))
1511 		return ER_DONT_EVICT;
1512 	if (WARN_ON_ONCE(b->list_mode != LIST_DIRTY))
1513 		return ER_DONT_EVICT;
1514 
1515 	return ER_EVICT;
1516 }
1517 
1518 /*
1519  * Find some buffer that is not held by anybody, clean it, unlink it and
1520  * return it.
1521  */
1522 static struct dm_buffer *__get_unclaimed_buffer(struct dm_bufio_client *c)
1523 {
1524 	struct dm_buffer *b;
1525 
1526 	b = cache_evict(&c->cache, LIST_CLEAN, is_clean, c);
1527 	if (b) {
1528 		/* this also waits for pending reads */
1529 		__make_buffer_clean(b);
1530 		return b;
1531 	}
1532 
1533 	if (static_branch_unlikely(&no_sleep_enabled) && c->no_sleep)
1534 		return NULL;
1535 
1536 	b = cache_evict(&c->cache, LIST_DIRTY, is_dirty, NULL);
1537 	if (b) {
1538 		__make_buffer_clean(b);
1539 		return b;
1540 	}
1541 
1542 	return NULL;
1543 }
1544 
1545 /*
1546  * Wait until some other threads free some buffer or release hold count on
1547  * some buffer.
1548  *
1549  * This function is entered with c->lock held, drops it and regains it
1550  * before exiting.
1551  */
1552 static void __wait_for_free_buffer(struct dm_bufio_client *c)
1553 {
1554 	DECLARE_WAITQUEUE(wait, current);
1555 
1556 	add_wait_queue(&c->free_buffer_wait, &wait);
1557 	set_current_state(TASK_UNINTERRUPTIBLE);
1558 	dm_bufio_unlock(c);
1559 
1560 	/*
1561 	 * It's possible to miss a wake up event since we don't always
1562 	 * hold c->lock when wake_up is called.  So we have a timeout here,
1563 	 * just in case.
1564 	 */
1565 	io_schedule_timeout(5 * HZ);
1566 
1567 	remove_wait_queue(&c->free_buffer_wait, &wait);
1568 
1569 	dm_bufio_lock(c);
1570 }
1571 
1572 enum new_flag {
1573 	NF_FRESH = 0,
1574 	NF_READ = 1,
1575 	NF_GET = 2,
1576 	NF_PREFETCH = 3
1577 };
1578 
1579 /*
1580  * Allocate a new buffer. If the allocation is not possible, wait until
1581  * some other thread frees a buffer.
1582  *
1583  * May drop the lock and regain it.
1584  */
1585 static struct dm_buffer *__alloc_buffer_wait_no_callback(struct dm_bufio_client *c, enum new_flag nf)
1586 {
1587 	struct dm_buffer *b;
1588 	bool tried_noio_alloc = false;
1589 
1590 	/*
1591 	 * dm-bufio is resistant to allocation failures (it just keeps
1592 	 * one buffer reserved in cases all the allocations fail).
1593 	 * So set flags to not try too hard:
1594 	 *	GFP_NOWAIT: don't wait and don't print a warning in case of
1595 	 *		    failure; if we need to sleep we'll release our mutex
1596 	 *		    and wait ourselves.
1597 	 *	__GFP_NORETRY: don't retry and rather return failure
1598 	 *	__GFP_NOMEMALLOC: don't use emergency reserves
1599 	 *
1600 	 * For debugging, if we set the cache size to 1, no new buffers will
1601 	 * be allocated.
1602 	 */
1603 	while (1) {
1604 		if (dm_budio_get_cache_size() != 1) {
1605 			b = alloc_buffer(c, GFP_NOWAIT | __GFP_NORETRY | __GFP_NOMEMALLOC);
1606 			if (b)
1607 				return b;
1608 		}
1609 
1610 		if (nf == NF_PREFETCH)
1611 			return NULL;
1612 
1613 		if (dm_budio_get_cache_size() != 1 && !tried_noio_alloc) {
1614 			dm_bufio_unlock(c);
1615 			b = alloc_buffer(c, GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
1616 			dm_bufio_lock(c);
1617 			if (b)
1618 				return b;
1619 			tried_noio_alloc = true;
1620 		}
1621 
1622 		if (!list_empty(&c->reserved_buffers)) {
1623 			b = list_to_buffer(c->reserved_buffers.next);
1624 			list_del(&b->lru.list);
1625 			c->need_reserved_buffers++;
1626 
1627 			return b;
1628 		}
1629 
1630 		b = __get_unclaimed_buffer(c);
1631 		if (b)
1632 			return b;
1633 
1634 		__wait_for_free_buffer(c);
1635 	}
1636 }
1637 
1638 static struct dm_buffer *__alloc_buffer_wait(struct dm_bufio_client *c, enum new_flag nf)
1639 {
1640 	struct dm_buffer *b = __alloc_buffer_wait_no_callback(c, nf);
1641 
1642 	if (!b)
1643 		return NULL;
1644 
1645 	if (c->alloc_callback)
1646 		c->alloc_callback(b);
1647 
1648 	return b;
1649 }
1650 
1651 /*
1652  * Free a buffer and wake other threads waiting for free buffers.
1653  */
1654 static void __free_buffer_wake(struct dm_buffer *b)
1655 {
1656 	struct dm_bufio_client *c = b->c;
1657 
1658 	b->block = -1;
1659 	if (!c->need_reserved_buffers)
1660 		free_buffer(b);
1661 	else {
1662 		list_add(&b->lru.list, &c->reserved_buffers);
1663 		c->need_reserved_buffers--;
1664 	}
1665 
1666 	/*
1667 	 * We hold the bufio lock here, so no one can add entries to the
1668 	 * wait queue anyway.
1669 	 */
1670 	if (unlikely(waitqueue_active(&c->free_buffer_wait)))
1671 		wake_up(&c->free_buffer_wait);
1672 }
1673 
1674 static enum evict_result cleaned(struct dm_buffer *b, void *context)
1675 {
1676 	if (WARN_ON_ONCE(test_bit(B_READING, &b->state)))
1677 		return ER_DONT_EVICT; /* should never happen */
1678 
1679 	if (test_bit(B_DIRTY, &b->state) || test_bit(B_WRITING, &b->state))
1680 		return ER_DONT_EVICT;
1681 	else
1682 		return ER_EVICT;
1683 }
1684 
1685 static void __move_clean_buffers(struct dm_bufio_client *c)
1686 {
1687 	cache_mark_many(&c->cache, LIST_DIRTY, LIST_CLEAN, cleaned, NULL);
1688 }
1689 
1690 struct write_context {
1691 	int no_wait;
1692 	struct list_head *write_list;
1693 };
1694 
1695 static enum it_action write_one(struct dm_buffer *b, void *context)
1696 {
1697 	struct write_context *wc = context;
1698 
1699 	if (wc->no_wait && test_bit(B_WRITING, &b->state))
1700 		return IT_COMPLETE;
1701 
1702 	__write_dirty_buffer(b, wc->write_list);
1703 	return IT_NEXT;
1704 }
1705 
1706 static void __write_dirty_buffers_async(struct dm_bufio_client *c, int no_wait,
1707 					struct list_head *write_list)
1708 {
1709 	struct write_context wc = {.no_wait = no_wait, .write_list = write_list};
1710 
1711 	__move_clean_buffers(c);
1712 	cache_iterate(&c->cache, LIST_DIRTY, write_one, &wc);
1713 }
1714 
1715 /*
1716  * Check if we're over watermark.
1717  * If we are over threshold_buffers, start freeing buffers.
1718  * If we're over "limit_buffers", block until we get under the limit.
1719  */
1720 static void __check_watermark(struct dm_bufio_client *c,
1721 			      struct list_head *write_list)
1722 {
1723 	if (cache_count(&c->cache, LIST_DIRTY) >
1724 	    cache_count(&c->cache, LIST_CLEAN) * DM_BUFIO_WRITEBACK_RATIO)
1725 		__write_dirty_buffers_async(c, 1, write_list);
1726 }
1727 
1728 /*
1729  *--------------------------------------------------------------
1730  * Getting a buffer
1731  *--------------------------------------------------------------
1732  */
1733 
1734 static void cache_put_and_wake(struct dm_bufio_client *c,
1735 			       struct buffer_tree *tree, struct dm_buffer *b)
1736 {
1737 	bool wake;
1738 
1739 	/* Assuming tree == cache_get_tree(&c->cache, b->block) */
1740 	cache_read_lock(&c->cache, tree);
1741 	BUG_ON(!atomic_read(&b->hold_count));
1742 	wake = atomic_dec_and_test(&b->hold_count);
1743 	cache_read_unlock(&c->cache, tree);
1744 
1745 	/*
1746 	 * Relying on waitqueue_active() is racey, but we sleep
1747 	 * with schedule_timeout anyway.
1748 	 */
1749 	if (wake && unlikely(waitqueue_active(&c->free_buffer_wait)))
1750 		wake_up(&c->free_buffer_wait);
1751 }
1752 
1753 /*
1754  * This assumes you have already checked the cache to see if the buffer
1755  * is already present (it will recheck after dropping the lock for allocation).
1756  */
1757 static struct dm_buffer *__bufio_new(struct dm_bufio_client *c,
1758 				     struct buffer_tree *tree, sector_t block,
1759 				     enum new_flag nf, int *need_submit,
1760 				     struct list_head *write_list)
1761 {
1762 	struct dm_buffer *b, *new_b = NULL;
1763 
1764 	*need_submit = 0;
1765 
1766 	/* This can't be called with NF_GET */
1767 	if (WARN_ON_ONCE(nf == NF_GET))
1768 		return NULL;
1769 
1770 	new_b = __alloc_buffer_wait(c, nf);
1771 	if (!new_b)
1772 		return NULL;
1773 
1774 	/*
1775 	 * We've had a period where the mutex was unlocked, so need to
1776 	 * recheck the buffer tree.
1777 	 */
1778 	b = cache_get(&c->cache, tree, block);
1779 	if (b) {
1780 		__free_buffer_wake(new_b);
1781 		goto found_buffer;
1782 	}
1783 
1784 	__check_watermark(c, write_list);
1785 
1786 	b = new_b;
1787 	atomic_set(&b->hold_count, 1);
1788 	WRITE_ONCE(b->last_accessed, jiffies);
1789 	b->block = block;
1790 	b->read_error = 0;
1791 	b->write_error = 0;
1792 	b->list_mode = LIST_CLEAN;
1793 
1794 	if (nf == NF_FRESH)
1795 		b->state = 0;
1796 	else {
1797 		b->state = 1 << B_READING;
1798 		*need_submit = 1;
1799 	}
1800 
1801 	/*
1802 	 * We mustn't insert into the cache until the B_READING state
1803 	 * is set.  Otherwise another thread could get it and use
1804 	 * it before it had been read.
1805 	 */
1806 	cache_insert(&c->cache, tree, b);
1807 
1808 	return b;
1809 
1810 found_buffer:
1811 	if (nf == NF_PREFETCH) {
1812 		cache_put_and_wake(c, tree, b);
1813 		return NULL;
1814 	}
1815 
1816 	/*
1817 	 * Note: it is essential that we don't wait for the buffer to be
1818 	 * read if dm_bufio_get function is used. Both dm_bufio_get and
1819 	 * dm_bufio_prefetch can be used in the driver request routine.
1820 	 * If the user called both dm_bufio_prefetch and dm_bufio_get on
1821 	 * the same buffer, it would deadlock if we waited.
1822 	 */
1823 	if (nf == NF_GET && unlikely(test_bit_acquire(B_READING, &b->state))) {
1824 		cache_put_and_wake(c, tree, b);
1825 		return NULL;
1826 	}
1827 
1828 	return b;
1829 }
1830 
1831 /*
1832  * The endio routine for reading: set the error, clear the bit and wake up
1833  * anyone waiting on the buffer.
1834  */
1835 static void read_endio(struct dm_buffer *b, blk_status_t status)
1836 {
1837 	b->read_error = status;
1838 
1839 	BUG_ON(!test_bit(B_READING, &b->state));
1840 
1841 	smp_mb__before_atomic();
1842 	clear_bit(B_READING, &b->state);
1843 	smp_mb__after_atomic();
1844 
1845 	wake_up_bit(&b->state, B_READING);
1846 }
1847 
1848 /*
1849  * A common routine for dm_bufio_new and dm_bufio_read.  Operation of these
1850  * functions is similar except that dm_bufio_new doesn't read the
1851  * buffer from the disk (assuming that the caller overwrites all the data
1852  * and uses dm_bufio_mark_buffer_dirty to write new data back).
1853  */
1854 static void *new_read(struct dm_bufio_client *c, sector_t block,
1855 		      enum new_flag nf, struct dm_buffer **bp,
1856 		      unsigned short ioprio)
1857 {
1858 	struct buffer_tree *tree;
1859 	int need_submit = 0;
1860 	struct dm_buffer *b;
1861 
1862 	LIST_HEAD(write_list);
1863 
1864 	*bp = NULL;
1865 
1866 	/*
1867 	 * Fast path, hopefully the block is already in the cache.  No need
1868 	 * to get the client lock for this.
1869 	 */
1870 	tree = cache_get_tree(&c->cache, block);
1871 	b = cache_get(&c->cache, tree, block);
1872 	if (b) {
1873 		if (nf == NF_PREFETCH) {
1874 			cache_put_and_wake(c, tree, b);
1875 			return NULL;
1876 		}
1877 
1878 		/*
1879 		 * Note: it is essential that we don't wait for the buffer to be
1880 		 * read if dm_bufio_get function is used. Both dm_bufio_get and
1881 		 * dm_bufio_prefetch can be used in the driver request routine.
1882 		 * If the user called both dm_bufio_prefetch and dm_bufio_get on
1883 		 * the same buffer, it would deadlock if we waited.
1884 		 */
1885 		if (nf == NF_GET && unlikely(test_bit_acquire(B_READING, &b->state))) {
1886 			cache_put_and_wake(c, tree, b);
1887 			return NULL;
1888 		}
1889 	}
1890 
1891 	if (!b) {
1892 		if (nf == NF_GET)
1893 			return NULL;
1894 
1895 		dm_bufio_lock(c);
1896 		b = __bufio_new(c, tree, block, nf, &need_submit, &write_list);
1897 		dm_bufio_unlock(c);
1898 	}
1899 
1900 #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
1901 	if (b && (atomic_read(&b->hold_count) == 1))
1902 		buffer_record_stack(b);
1903 #endif
1904 
1905 	__flush_write_list(&write_list);
1906 
1907 	if (!b)
1908 		return NULL;
1909 
1910 	if (need_submit)
1911 		submit_io(b, REQ_OP_READ, ioprio, read_endio);
1912 
1913 	if (nf != NF_GET)	/* we already tested this condition above */
1914 		wait_on_bit_io(&b->state, B_READING, TASK_UNINTERRUPTIBLE);
1915 
1916 	if (b->read_error) {
1917 		int error = blk_status_to_errno(b->read_error);
1918 
1919 		dm_bufio_release(b);
1920 
1921 		return ERR_PTR(error);
1922 	}
1923 
1924 	*bp = b;
1925 
1926 	return b->data;
1927 }
1928 
1929 void *dm_bufio_get(struct dm_bufio_client *c, sector_t block,
1930 		   struct dm_buffer **bp)
1931 {
1932 	return new_read(c, block, NF_GET, bp, IOPRIO_DEFAULT);
1933 }
1934 EXPORT_SYMBOL_GPL(dm_bufio_get);
1935 
1936 static void *__dm_bufio_read(struct dm_bufio_client *c, sector_t block,
1937 			struct dm_buffer **bp, unsigned short ioprio)
1938 {
1939 	if (WARN_ON_ONCE(dm_bufio_in_request()))
1940 		return ERR_PTR(-EINVAL);
1941 
1942 	return new_read(c, block, NF_READ, bp, ioprio);
1943 }
1944 
1945 void *dm_bufio_read(struct dm_bufio_client *c, sector_t block,
1946 		    struct dm_buffer **bp)
1947 {
1948 	return __dm_bufio_read(c, block, bp, IOPRIO_DEFAULT);
1949 }
1950 EXPORT_SYMBOL_GPL(dm_bufio_read);
1951 
1952 void *dm_bufio_read_with_ioprio(struct dm_bufio_client *c, sector_t block,
1953 				struct dm_buffer **bp, unsigned short ioprio)
1954 {
1955 	return __dm_bufio_read(c, block, bp, ioprio);
1956 }
1957 EXPORT_SYMBOL_GPL(dm_bufio_read_with_ioprio);
1958 
1959 void *dm_bufio_new(struct dm_bufio_client *c, sector_t block,
1960 		   struct dm_buffer **bp)
1961 {
1962 	if (WARN_ON_ONCE(dm_bufio_in_request()))
1963 		return ERR_PTR(-EINVAL);
1964 
1965 	return new_read(c, block, NF_FRESH, bp, IOPRIO_DEFAULT);
1966 }
1967 EXPORT_SYMBOL_GPL(dm_bufio_new);
1968 
1969 static void __dm_bufio_prefetch(struct dm_bufio_client *c,
1970 			sector_t block, unsigned int n_blocks,
1971 			unsigned short ioprio)
1972 {
1973 	struct blk_plug plug;
1974 
1975 	LIST_HEAD(write_list);
1976 
1977 	if (WARN_ON_ONCE(dm_bufio_in_request()))
1978 		return; /* should never happen */
1979 
1980 	blk_start_plug(&plug);
1981 
1982 	for (; n_blocks--; block++) {
1983 		struct buffer_tree *tree;
1984 		struct dm_buffer *b;
1985 		int need_submit;
1986 
1987 		tree = cache_get_tree(&c->cache, block);
1988 		b = cache_get(&c->cache, tree, block);
1989 		if (b) {
1990 			/* already in cache */
1991 			cache_put_and_wake(c, tree, b);
1992 			continue;
1993 		}
1994 
1995 		dm_bufio_lock(c);
1996 		b = __bufio_new(c, tree, block, NF_PREFETCH, &need_submit,
1997 				&write_list);
1998 		if (unlikely(!list_empty(&write_list))) {
1999 			dm_bufio_unlock(c);
2000 			blk_finish_plug(&plug);
2001 			__flush_write_list(&write_list);
2002 			blk_start_plug(&plug);
2003 			dm_bufio_lock(c);
2004 		}
2005 		if (unlikely(b != NULL)) {
2006 			dm_bufio_unlock(c);
2007 
2008 			if (need_submit)
2009 				submit_io(b, REQ_OP_READ, ioprio, read_endio);
2010 			dm_bufio_release(b);
2011 
2012 			cond_resched();
2013 
2014 			if (!n_blocks)
2015 				goto flush_plug;
2016 			dm_bufio_lock(c);
2017 		}
2018 		dm_bufio_unlock(c);
2019 	}
2020 
2021 flush_plug:
2022 	blk_finish_plug(&plug);
2023 }
2024 
2025 void dm_bufio_prefetch(struct dm_bufio_client *c, sector_t block, unsigned int n_blocks)
2026 {
2027 	return __dm_bufio_prefetch(c, block, n_blocks, IOPRIO_DEFAULT);
2028 }
2029 EXPORT_SYMBOL_GPL(dm_bufio_prefetch);
2030 
2031 void dm_bufio_prefetch_with_ioprio(struct dm_bufio_client *c, sector_t block,
2032 				unsigned int n_blocks, unsigned short ioprio)
2033 {
2034 	return __dm_bufio_prefetch(c, block, n_blocks, ioprio);
2035 }
2036 EXPORT_SYMBOL_GPL(dm_bufio_prefetch_with_ioprio);
2037 
2038 void dm_bufio_release(struct dm_buffer *b)
2039 {
2040 	struct dm_bufio_client *c = b->c;
2041 	struct buffer_tree *tree = cache_get_tree(&c->cache, b->block);
2042 
2043 	/*
2044 	 * If there were errors on the buffer, and the buffer is not
2045 	 * to be written, free the buffer. There is no point in caching
2046 	 * invalid buffer.
2047 	 */
2048 	if ((b->read_error || b->write_error) &&
2049 	    !test_bit_acquire(B_READING, &b->state) &&
2050 	    !test_bit(B_WRITING, &b->state) &&
2051 	    !test_bit(B_DIRTY, &b->state)) {
2052 		dm_bufio_lock(c);
2053 
2054 		/* cache remove can fail if there are other holders */
2055 		if (cache_remove(&c->cache, tree, b)) {
2056 			__free_buffer_wake(b);
2057 			dm_bufio_unlock(c);
2058 			return;
2059 		}
2060 
2061 		dm_bufio_unlock(c);
2062 	}
2063 
2064 	cache_put_and_wake(c, tree, b);
2065 }
2066 EXPORT_SYMBOL_GPL(dm_bufio_release);
2067 
2068 void dm_bufio_mark_partial_buffer_dirty(struct dm_buffer *b,
2069 					unsigned int start, unsigned int end)
2070 {
2071 	struct dm_bufio_client *c = b->c;
2072 
2073 	BUG_ON(start >= end);
2074 	BUG_ON(end > b->c->block_size);
2075 
2076 	dm_bufio_lock(c);
2077 
2078 	BUG_ON(test_bit(B_READING, &b->state));
2079 
2080 	if (!test_and_set_bit(B_DIRTY, &b->state)) {
2081 		b->dirty_start = start;
2082 		b->dirty_end = end;
2083 		cache_mark(&c->cache, cache_get_tree(&c->cache, b->block), b,
2084 			   LIST_DIRTY);
2085 	} else {
2086 		if (start < b->dirty_start)
2087 			b->dirty_start = start;
2088 		if (end > b->dirty_end)
2089 			b->dirty_end = end;
2090 	}
2091 
2092 	dm_bufio_unlock(c);
2093 }
2094 EXPORT_SYMBOL_GPL(dm_bufio_mark_partial_buffer_dirty);
2095 
2096 void dm_bufio_mark_buffer_dirty(struct dm_buffer *b)
2097 {
2098 	dm_bufio_mark_partial_buffer_dirty(b, 0, b->c->block_size);
2099 }
2100 EXPORT_SYMBOL_GPL(dm_bufio_mark_buffer_dirty);
2101 
2102 void dm_bufio_write_dirty_buffers_async(struct dm_bufio_client *c)
2103 {
2104 	LIST_HEAD(write_list);
2105 
2106 	if (WARN_ON_ONCE(dm_bufio_in_request()))
2107 		return; /* should never happen */
2108 
2109 	dm_bufio_lock(c);
2110 	__write_dirty_buffers_async(c, 0, &write_list);
2111 	dm_bufio_unlock(c);
2112 	__flush_write_list(&write_list);
2113 }
2114 EXPORT_SYMBOL_GPL(dm_bufio_write_dirty_buffers_async);
2115 
2116 /*
2117  * For performance, it is essential that the buffers are written asynchronously
2118  * and simultaneously (so that the block layer can merge the writes) and then
2119  * waited upon.
2120  *
2121  * Finally, we flush hardware disk cache.
2122  */
2123 static bool is_writing(struct lru_entry *e, void *context)
2124 {
2125 	struct dm_buffer *b = le_to_buffer(e);
2126 
2127 	return test_bit(B_WRITING, &b->state);
2128 }
2129 
2130 int dm_bufio_write_dirty_buffers(struct dm_bufio_client *c)
2131 {
2132 	int a, f;
2133 	unsigned long nr_buffers;
2134 	struct lru_entry *e;
2135 	struct lru_iter it;
2136 
2137 	LIST_HEAD(write_list);
2138 
2139 	dm_bufio_lock(c);
2140 	__write_dirty_buffers_async(c, 0, &write_list);
2141 	dm_bufio_unlock(c);
2142 	__flush_write_list(&write_list);
2143 	dm_bufio_lock(c);
2144 
2145 	nr_buffers = cache_count(&c->cache, LIST_DIRTY);
2146 	lru_iter_begin(&c->cache.lru[LIST_DIRTY], &it);
2147 	while ((e = lru_iter_next(&it, is_writing, c))) {
2148 		struct dm_buffer *b = le_to_buffer(e);
2149 		struct buffer_tree *tree;
2150 		__cache_inc_buffer(b);
2151 
2152 		BUG_ON(test_bit(B_READING, &b->state));
2153 
2154 		if (nr_buffers) {
2155 			nr_buffers--;
2156 			dm_bufio_unlock(c);
2157 			wait_on_bit_io(&b->state, B_WRITING, TASK_UNINTERRUPTIBLE);
2158 			dm_bufio_lock(c);
2159 		} else {
2160 			wait_on_bit_io(&b->state, B_WRITING, TASK_UNINTERRUPTIBLE);
2161 		}
2162 
2163 		tree = cache_get_tree(&c->cache, b->block);
2164 
2165 		if (!test_bit(B_DIRTY, &b->state) && !test_bit(B_WRITING, &b->state))
2166 			cache_mark(&c->cache, tree, b, LIST_CLEAN);
2167 
2168 		cache_put_and_wake(c, tree, b);
2169 
2170 		cond_resched();
2171 	}
2172 	lru_iter_end(&it);
2173 
2174 	wake_up(&c->free_buffer_wait);
2175 	dm_bufio_unlock(c);
2176 
2177 	a = xchg(&c->async_write_error, 0);
2178 	f = dm_bufio_issue_flush(c);
2179 	if (a)
2180 		return a;
2181 
2182 	return f;
2183 }
2184 EXPORT_SYMBOL_GPL(dm_bufio_write_dirty_buffers);
2185 
2186 /*
2187  * Use dm-io to send an empty barrier to flush the device.
2188  */
2189 int dm_bufio_issue_flush(struct dm_bufio_client *c)
2190 {
2191 	struct dm_io_request io_req = {
2192 		.bi_opf = REQ_OP_WRITE | REQ_PREFLUSH | REQ_SYNC,
2193 		.mem.type = DM_IO_KMEM,
2194 		.mem.ptr.addr = NULL,
2195 		.client = c->dm_io,
2196 	};
2197 	struct dm_io_region io_reg = {
2198 		.bdev = c->bdev,
2199 		.sector = 0,
2200 		.count = 0,
2201 	};
2202 
2203 	if (WARN_ON_ONCE(dm_bufio_in_request()))
2204 		return -EINVAL;
2205 
2206 	return dm_io(&io_req, 1, &io_reg, NULL, NULL, IOPRIO_DEFAULT);
2207 }
2208 EXPORT_SYMBOL_GPL(dm_bufio_issue_flush);
2209 
2210 /*
2211  * Use dm-io to send a discard request to flush the device.
2212  */
2213 int dm_bufio_issue_discard(struct dm_bufio_client *c, sector_t block, sector_t count)
2214 {
2215 	struct dm_io_request io_req = {
2216 		.bi_opf = REQ_OP_DISCARD | REQ_SYNC,
2217 		.mem.type = DM_IO_KMEM,
2218 		.mem.ptr.addr = NULL,
2219 		.client = c->dm_io,
2220 	};
2221 	struct dm_io_region io_reg = {
2222 		.bdev = c->bdev,
2223 		.sector = block_to_sector(c, block),
2224 		.count = likely(c->sectors_per_block_bits >= 0) ?
2225 			count << c->sectors_per_block_bits :
2226 			count * (c->block_size >> SECTOR_SHIFT),
2227 	};
2228 
2229 	if (WARN_ON_ONCE(dm_bufio_in_request()))
2230 		return -EINVAL; /* discards are optional */
2231 
2232 	return dm_io(&io_req, 1, &io_reg, NULL, NULL, IOPRIO_DEFAULT);
2233 }
2234 EXPORT_SYMBOL_GPL(dm_bufio_issue_discard);
2235 
2236 static void forget_buffer(struct dm_bufio_client *c, sector_t block)
2237 {
2238 	struct buffer_tree *tree = cache_get_tree(&c->cache, block);
2239 	struct dm_buffer *b;
2240 
2241 	b = cache_get(&c->cache, tree, block);
2242 	if (b) {
2243 		if (likely(!smp_load_acquire(&b->state))) {
2244 			if (cache_remove(&c->cache, tree, b))
2245 				__free_buffer_wake(b);
2246 			else
2247 				cache_put_and_wake(c, tree, b);
2248 		} else {
2249 			cache_put_and_wake(c, tree, b);
2250 		}
2251 	}
2252 }
2253 
2254 /*
2255  * Free the given buffer.
2256  *
2257  * This is just a hint, if the buffer is in use or dirty, this function
2258  * does nothing.
2259  */
2260 void dm_bufio_forget(struct dm_bufio_client *c, sector_t block)
2261 {
2262 	dm_bufio_lock(c);
2263 	forget_buffer(c, block);
2264 	dm_bufio_unlock(c);
2265 }
2266 EXPORT_SYMBOL_GPL(dm_bufio_forget);
2267 
2268 static enum evict_result idle(struct dm_buffer *b, void *context)
2269 {
2270 	return b->state ? ER_DONT_EVICT : ER_EVICT;
2271 }
2272 
2273 void dm_bufio_forget_buffers(struct dm_bufio_client *c, sector_t block, sector_t n_blocks)
2274 {
2275 	dm_bufio_lock(c);
2276 	cache_remove_range(&c->cache, block, block + n_blocks, idle, __free_buffer_wake);
2277 	dm_bufio_unlock(c);
2278 }
2279 EXPORT_SYMBOL_GPL(dm_bufio_forget_buffers);
2280 
2281 void dm_bufio_set_minimum_buffers(struct dm_bufio_client *c, unsigned int n)
2282 {
2283 	c->minimum_buffers = n;
2284 }
2285 EXPORT_SYMBOL_GPL(dm_bufio_set_minimum_buffers);
2286 
2287 unsigned int dm_bufio_get_block_size(struct dm_bufio_client *c)
2288 {
2289 	return c->block_size;
2290 }
2291 EXPORT_SYMBOL_GPL(dm_bufio_get_block_size);
2292 
2293 sector_t dm_bufio_get_device_size(struct dm_bufio_client *c)
2294 {
2295 	sector_t s = bdev_nr_sectors(c->bdev);
2296 
2297 	if (s >= c->start)
2298 		s -= c->start;
2299 	else
2300 		s = 0;
2301 	if (likely(c->sectors_per_block_bits >= 0))
2302 		s >>= c->sectors_per_block_bits;
2303 	else
2304 		sector_div(s, c->block_size >> SECTOR_SHIFT);
2305 	return s;
2306 }
2307 EXPORT_SYMBOL_GPL(dm_bufio_get_device_size);
2308 
2309 struct dm_io_client *dm_bufio_get_dm_io_client(struct dm_bufio_client *c)
2310 {
2311 	return c->dm_io;
2312 }
2313 EXPORT_SYMBOL_GPL(dm_bufio_get_dm_io_client);
2314 
2315 sector_t dm_bufio_get_block_number(struct dm_buffer *b)
2316 {
2317 	return b->block;
2318 }
2319 EXPORT_SYMBOL_GPL(dm_bufio_get_block_number);
2320 
2321 void *dm_bufio_get_block_data(struct dm_buffer *b)
2322 {
2323 	return b->data;
2324 }
2325 EXPORT_SYMBOL_GPL(dm_bufio_get_block_data);
2326 
2327 void *dm_bufio_get_aux_data(struct dm_buffer *b)
2328 {
2329 	return b + 1;
2330 }
2331 EXPORT_SYMBOL_GPL(dm_bufio_get_aux_data);
2332 
2333 struct dm_bufio_client *dm_bufio_get_client(struct dm_buffer *b)
2334 {
2335 	return b->c;
2336 }
2337 EXPORT_SYMBOL_GPL(dm_bufio_get_client);
2338 
2339 static enum it_action warn_leak(struct dm_buffer *b, void *context)
2340 {
2341 	bool *warned = context;
2342 
2343 	WARN_ON(!(*warned));
2344 	*warned = true;
2345 	DMERR("leaked buffer %llx, hold count %u, list %d",
2346 	      (unsigned long long)b->block, atomic_read(&b->hold_count), b->list_mode);
2347 #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
2348 	stack_trace_print(b->stack_entries, b->stack_len, 1);
2349 	/* mark unclaimed to avoid WARN_ON at end of drop_buffers() */
2350 	atomic_set(&b->hold_count, 0);
2351 #endif
2352 	return IT_NEXT;
2353 }
2354 
2355 static void drop_buffers(struct dm_bufio_client *c)
2356 {
2357 	int i;
2358 	struct dm_buffer *b;
2359 
2360 	if (WARN_ON(dm_bufio_in_request()))
2361 		return; /* should never happen */
2362 
2363 	/*
2364 	 * An optimization so that the buffers are not written one-by-one.
2365 	 */
2366 	dm_bufio_write_dirty_buffers_async(c);
2367 
2368 	dm_bufio_lock(c);
2369 
2370 	while ((b = __get_unclaimed_buffer(c)))
2371 		__free_buffer_wake(b);
2372 
2373 	for (i = 0; i < LIST_SIZE; i++) {
2374 		bool warned = false;
2375 
2376 		cache_iterate(&c->cache, i, warn_leak, &warned);
2377 	}
2378 
2379 #ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
2380 	while ((b = __get_unclaimed_buffer(c)))
2381 		__free_buffer_wake(b);
2382 #endif
2383 
2384 	for (i = 0; i < LIST_SIZE; i++)
2385 		WARN_ON(cache_count(&c->cache, i));
2386 
2387 	dm_bufio_unlock(c);
2388 }
2389 
2390 static unsigned long get_retain_buffers(struct dm_bufio_client *c)
2391 {
2392 	unsigned long retain_bytes = READ_ONCE(dm_bufio_retain_bytes);
2393 
2394 	if (likely(c->sectors_per_block_bits >= 0))
2395 		retain_bytes >>= c->sectors_per_block_bits + SECTOR_SHIFT;
2396 	else
2397 		retain_bytes /= c->block_size;
2398 
2399 	return retain_bytes;
2400 }
2401 
2402 static void __scan(struct dm_bufio_client *c)
2403 {
2404 	int l;
2405 	struct dm_buffer *b;
2406 	unsigned long freed = 0;
2407 	unsigned long retain_target = get_retain_buffers(c);
2408 	unsigned long count = cache_total(&c->cache);
2409 
2410 	for (l = 0; l < LIST_SIZE; l++) {
2411 		while (true) {
2412 			if (count - freed <= retain_target) {
2413 				atomic_long_set(&c->need_shrink, 0);
2414 				break;
2415 			}
2416 			if (!atomic_long_read(&c->need_shrink))
2417 				break;
2418 
2419 			b = cache_evict(&c->cache, l,
2420 					l == LIST_CLEAN ? is_clean : is_dirty, c);
2421 			if (!b)
2422 				break;
2423 
2424 			__make_buffer_clean(b);
2425 			__free_buffer_wake(b);
2426 
2427 			atomic_long_dec(&c->need_shrink);
2428 			freed++;
2429 
2430 			if (unlikely(freed % SCAN_RESCHED_CYCLE == 0)) {
2431 				dm_bufio_unlock(c);
2432 				cond_resched();
2433 				dm_bufio_lock(c);
2434 			}
2435 		}
2436 	}
2437 }
2438 
2439 static void shrink_work(struct work_struct *w)
2440 {
2441 	struct dm_bufio_client *c = container_of(w, struct dm_bufio_client, shrink_work);
2442 
2443 	dm_bufio_lock(c);
2444 	__scan(c);
2445 	dm_bufio_unlock(c);
2446 }
2447 
2448 static unsigned long dm_bufio_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
2449 {
2450 	struct dm_bufio_client *c;
2451 
2452 	c = shrink->private_data;
2453 	atomic_long_add(sc->nr_to_scan, &c->need_shrink);
2454 	queue_work(dm_bufio_wq, &c->shrink_work);
2455 
2456 	return sc->nr_to_scan;
2457 }
2458 
2459 static unsigned long dm_bufio_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
2460 {
2461 	struct dm_bufio_client *c = shrink->private_data;
2462 	unsigned long count = cache_total(&c->cache);
2463 	unsigned long retain_target = get_retain_buffers(c);
2464 	unsigned long queued_for_cleanup = atomic_long_read(&c->need_shrink);
2465 
2466 	if (unlikely(count < retain_target))
2467 		count = 0;
2468 	else
2469 		count -= retain_target;
2470 
2471 	if (unlikely(count < queued_for_cleanup))
2472 		count = 0;
2473 	else
2474 		count -= queued_for_cleanup;
2475 
2476 	return count;
2477 }
2478 
2479 /*
2480  * Create the buffering interface
2481  */
2482 struct dm_bufio_client *dm_bufio_client_create(struct block_device *bdev, unsigned int block_size,
2483 					       unsigned int reserved_buffers, unsigned int aux_size,
2484 					       void (*alloc_callback)(struct dm_buffer *),
2485 					       void (*write_callback)(struct dm_buffer *),
2486 					       unsigned int flags)
2487 {
2488 	int r;
2489 	unsigned int num_locks;
2490 	struct dm_bufio_client *c;
2491 	char slab_name[64];
2492 	static atomic_t seqno = ATOMIC_INIT(0);
2493 
2494 	if (!block_size || block_size & ((1 << SECTOR_SHIFT) - 1)) {
2495 		DMERR("%s: block size not specified or is not multiple of 512b", __func__);
2496 		r = -EINVAL;
2497 		goto bad_client;
2498 	}
2499 
2500 	num_locks = dm_num_hash_locks();
2501 	c = kzalloc_flex(*c, cache.trees, num_locks);
2502 	if (!c) {
2503 		r = -ENOMEM;
2504 		goto bad_client;
2505 	}
2506 	cache_init(&c->cache, num_locks, (flags & DM_BUFIO_CLIENT_NO_SLEEP) != 0);
2507 
2508 	c->bdev = bdev;
2509 	c->block_size = block_size;
2510 	if (is_power_of_2(block_size))
2511 		c->sectors_per_block_bits = __ffs(block_size) - SECTOR_SHIFT;
2512 	else
2513 		c->sectors_per_block_bits = -1;
2514 
2515 	c->alloc_callback = alloc_callback;
2516 	c->write_callback = write_callback;
2517 
2518 	if (flags & DM_BUFIO_CLIENT_NO_SLEEP) {
2519 		c->no_sleep = true;
2520 		static_branch_inc(&no_sleep_enabled);
2521 	}
2522 
2523 	mutex_init(&c->lock);
2524 	spin_lock_init(&c->spinlock);
2525 	INIT_LIST_HEAD(&c->reserved_buffers);
2526 	c->need_reserved_buffers = reserved_buffers;
2527 
2528 	dm_bufio_set_minimum_buffers(c, DM_BUFIO_MIN_BUFFERS);
2529 
2530 	init_waitqueue_head(&c->free_buffer_wait);
2531 	c->async_write_error = 0;
2532 
2533 	/*
2534 	 * A client with no buffers yet is not holding the oldest buffer in
2535 	 * the system; leaving this zeroed would claim exactly that and keep
2536 	 * the client pinned at the front of dm_bufio_all_clients.
2537 	 */
2538 	c->oldest_buffer = jiffies;
2539 
2540 	c->dm_io = dm_io_client_create();
2541 	if (IS_ERR(c->dm_io)) {
2542 		r = PTR_ERR(c->dm_io);
2543 		goto bad_dm_io;
2544 	}
2545 
2546 	if (block_size <= KMALLOC_MAX_SIZE && !is_power_of_2(block_size)) {
2547 		unsigned int align = min(1U << __ffs(block_size), (unsigned int)PAGE_SIZE);
2548 
2549 		snprintf(slab_name, sizeof(slab_name), "dm_bufio_cache-%u-%u",
2550 					block_size, atomic_inc_return(&seqno));
2551 		c->slab_cache = kmem_cache_create(slab_name, block_size, align,
2552 						  SLAB_RECLAIM_ACCOUNT, NULL);
2553 		if (!c->slab_cache) {
2554 			r = -ENOMEM;
2555 			goto bad;
2556 		}
2557 	}
2558 	if (aux_size)
2559 		snprintf(slab_name, sizeof(slab_name), "dm_bufio_buffer-%u-%u",
2560 					aux_size, atomic_inc_return(&seqno));
2561 	else
2562 		snprintf(slab_name, sizeof(slab_name), "dm_bufio_buffer-%u",
2563 					atomic_inc_return(&seqno));
2564 	c->slab_buffer = kmem_cache_create(slab_name, sizeof(struct dm_buffer) + aux_size,
2565 					   0, SLAB_RECLAIM_ACCOUNT, NULL);
2566 	if (!c->slab_buffer) {
2567 		r = -ENOMEM;
2568 		goto bad;
2569 	}
2570 
2571 	while (c->need_reserved_buffers) {
2572 		struct dm_buffer *b = alloc_buffer(c, GFP_KERNEL);
2573 
2574 		if (!b) {
2575 			r = -ENOMEM;
2576 			goto bad;
2577 		}
2578 		__free_buffer_wake(b);
2579 	}
2580 
2581 	INIT_WORK(&c->shrink_work, shrink_work);
2582 	atomic_long_set(&c->need_shrink, 0);
2583 
2584 	c->shrinker = shrinker_alloc(0, "dm-bufio:(%u:%u)",
2585 				     MAJOR(bdev->bd_dev), MINOR(bdev->bd_dev));
2586 	if (!c->shrinker) {
2587 		r = -ENOMEM;
2588 		goto bad;
2589 	}
2590 
2591 	c->shrinker->count_objects = dm_bufio_shrink_count;
2592 	c->shrinker->scan_objects = dm_bufio_shrink_scan;
2593 	c->shrinker->seeks = 1;
2594 	c->shrinker->batch = 0;
2595 	c->shrinker->private_data = c;
2596 
2597 	shrinker_register(c->shrinker);
2598 
2599 	mutex_lock(&dm_bufio_clients_lock);
2600 	dm_bufio_client_count++;
2601 	list_add(&c->client_list, &dm_bufio_all_clients);
2602 	mutex_unlock(&dm_bufio_clients_lock);
2603 
2604 	return c;
2605 
2606 bad:
2607 	while (!list_empty(&c->reserved_buffers)) {
2608 		struct dm_buffer *b = list_to_buffer(c->reserved_buffers.next);
2609 
2610 		list_del(&b->lru.list);
2611 		free_buffer(b);
2612 	}
2613 	kmem_cache_destroy(c->slab_cache);
2614 	kmem_cache_destroy(c->slab_buffer);
2615 	dm_io_client_destroy(c->dm_io);
2616 bad_dm_io:
2617 	mutex_destroy(&c->lock);
2618 	if (c->no_sleep)
2619 		static_branch_dec(&no_sleep_enabled);
2620 	kfree(c);
2621 bad_client:
2622 	return ERR_PTR(r);
2623 }
2624 EXPORT_SYMBOL_GPL(dm_bufio_client_create);
2625 
2626 /*
2627  * Free the buffering interface.
2628  * It is required that there are no references on any buffers.
2629  */
2630 void dm_bufio_client_destroy(struct dm_bufio_client *c)
2631 {
2632 	unsigned int i;
2633 
2634 	drop_buffers(c);
2635 
2636 	shrinker_free(c->shrinker);
2637 	flush_work(&c->shrink_work);
2638 
2639 	mutex_lock(&dm_bufio_clients_lock);
2640 
2641 	list_del(&c->client_list);
2642 	dm_bufio_client_count--;
2643 
2644 	mutex_unlock(&dm_bufio_clients_lock);
2645 
2646 	WARN_ON(c->need_reserved_buffers);
2647 
2648 	while (!list_empty(&c->reserved_buffers)) {
2649 		struct dm_buffer *b = list_to_buffer(c->reserved_buffers.next);
2650 
2651 		list_del(&b->lru.list);
2652 		free_buffer(b);
2653 	}
2654 
2655 	for (i = 0; i < LIST_SIZE; i++)
2656 		if (cache_count(&c->cache, i))
2657 			DMERR("leaked buffer count %d: %lu", i, cache_count(&c->cache, i));
2658 
2659 	for (i = 0; i < LIST_SIZE; i++)
2660 		WARN_ON(cache_count(&c->cache, i));
2661 
2662 	cache_destroy(&c->cache);
2663 	kmem_cache_destroy(c->slab_cache);
2664 	kmem_cache_destroy(c->slab_buffer);
2665 	dm_io_client_destroy(c->dm_io);
2666 	mutex_destroy(&c->lock);
2667 	if (c->no_sleep)
2668 		static_branch_dec(&no_sleep_enabled);
2669 	kfree(c);
2670 }
2671 EXPORT_SYMBOL_GPL(dm_bufio_client_destroy);
2672 
2673 void dm_bufio_client_reset(struct dm_bufio_client *c)
2674 {
2675 	drop_buffers(c);
2676 	flush_work(&c->shrink_work);
2677 }
2678 EXPORT_SYMBOL_GPL(dm_bufio_client_reset);
2679 
2680 void dm_bufio_set_sector_offset(struct dm_bufio_client *c, sector_t start)
2681 {
2682 	c->start = start;
2683 }
2684 EXPORT_SYMBOL_GPL(dm_bufio_set_sector_offset);
2685 
2686 /*--------------------------------------------------------------*/
2687 
2688 /*
2689  * Global cleanup tries to evict the oldest buffers from across _all_
2690  * the clients.  It does this by repeatedly evicting a few buffers from
2691  * the client that holds the oldest buffer.  It's approximate, but hopefully
2692  * good enough.
2693  */
2694 static struct dm_bufio_client *__pop_client(void)
2695 {
2696 	struct list_head *h;
2697 
2698 	if (list_empty(&dm_bufio_all_clients))
2699 		return NULL;
2700 
2701 	h = dm_bufio_all_clients.next;
2702 	list_del(h);
2703 	return container_of(h, struct dm_bufio_client, client_list);
2704 }
2705 
2706 /*
2707  * Inserts the client in the global client list based on its
2708  * 'oldest_buffer' field.
2709  */
2710 static void __insert_client(struct dm_bufio_client *new_client)
2711 {
2712 	struct dm_bufio_client *c;
2713 	struct list_head *h = dm_bufio_all_clients.next;
2714 
2715 	while (h != &dm_bufio_all_clients) {
2716 		c = container_of(h, struct dm_bufio_client, client_list);
2717 		if (time_after_eq(c->oldest_buffer, new_client->oldest_buffer))
2718 			break;
2719 		h = h->next;
2720 	}
2721 
2722 	list_add_tail(&new_client->client_list, h);
2723 }
2724 
2725 static enum evict_result select_for_evict(struct dm_buffer *b, void *context)
2726 {
2727 	/* In no-sleep mode, we cannot wait on IO. */
2728 	if (static_branch_unlikely(&no_sleep_enabled) && b->c->no_sleep) {
2729 		if (test_bit_acquire(B_READING, &b->state) ||
2730 		    test_bit(B_WRITING, &b->state) ||
2731 		    test_bit(B_DIRTY, &b->state))
2732 			return ER_DONT_EVICT;
2733 	}
2734 	return ER_EVICT;
2735 }
2736 
2737 static unsigned long __evict_a_few(unsigned long nr_buffers)
2738 {
2739 	struct dm_bufio_client *c;
2740 	unsigned long oldest_buffer = jiffies;
2741 	unsigned long last_accessed;
2742 	unsigned long count;
2743 	struct dm_buffer *b;
2744 
2745 	c = __pop_client();
2746 	if (!c)
2747 		return 0;
2748 
2749 	dm_bufio_lock(c);
2750 
2751 	for (count = 0; count < nr_buffers; count++) {
2752 		b = cache_evict(&c->cache, LIST_CLEAN, select_for_evict, NULL);
2753 		if (!b)
2754 			break;
2755 
2756 		last_accessed = READ_ONCE(b->last_accessed);
2757 		if (time_after_eq(oldest_buffer, last_accessed))
2758 			oldest_buffer = last_accessed;
2759 
2760 		__make_buffer_clean(b);
2761 		__free_buffer_wake(b);
2762 
2763 		if (need_resched()) {
2764 			dm_bufio_unlock(c);
2765 			cond_resched();
2766 			dm_bufio_lock(c);
2767 		}
2768 	}
2769 
2770 	dm_bufio_unlock(c);
2771 
2772 	if (count) {
2773 		c->oldest_buffer = oldest_buffer;
2774 		__insert_client(c);
2775 	} else {
2776 		/*
2777 		 * We evicted nothing, so 'oldest_buffer' tells us nothing new
2778 		 * and the client keeps its old, possibly very stale, value.
2779 		 * Requeue it at the back rather than by that value, otherwise
2780 		 * __insert_client() would put it straight back at the front
2781 		 * and every subsequent call would pop this same client again,
2782 		 * never reaching any of the others.
2783 		 *
2784 		 * This leaves the list slightly out of order, which is fine -
2785 		 * it is only ever an approximation.
2786 		 */
2787 		list_add_tail(&c->client_list, &dm_bufio_all_clients);
2788 	}
2789 
2790 	return count;
2791 }
2792 
2793 static void check_watermarks(void)
2794 {
2795 	LIST_HEAD(write_list);
2796 	struct dm_bufio_client *c;
2797 
2798 	mutex_lock(&dm_bufio_clients_lock);
2799 	list_for_each_entry(c, &dm_bufio_all_clients, client_list) {
2800 		dm_bufio_lock(c);
2801 		__check_watermark(c, &write_list);
2802 		dm_bufio_unlock(c);
2803 	}
2804 	mutex_unlock(&dm_bufio_clients_lock);
2805 
2806 	__flush_write_list(&write_list);
2807 }
2808 
2809 static void evict_old(void)
2810 {
2811 	unsigned long cs = dm_budio_get_cache_size();
2812 	unsigned long threshold = cs - cs / DM_BUFIO_LOW_WATERMARK_RATIO;
2813 	int unproductive = 0;
2814 
2815 	mutex_lock(&dm_bufio_clients_lock);
2816 	while (dm_bufio_current_allocated > threshold) {
2817 		if (__evict_a_few(64)) {
2818 			unproductive = 0;
2819 		} else {
2820 			/*
2821 			 * This client had nothing to give.  Try the others
2822 			 * before giving up: one idle client, or one whose
2823 			 * buffers are all held, must not stop us evicting
2824 			 * from everybody else.  Stop once a whole sweep of
2825 			 * the client list has freed nothing.
2826 			 */
2827 			if (++unproductive >= dm_bufio_client_count)
2828 				break;
2829 		}
2830 		cond_resched();
2831 	}
2832 	mutex_unlock(&dm_bufio_clients_lock);
2833 }
2834 
2835 static void do_global_cleanup(struct work_struct *w)
2836 {
2837 	check_watermarks();
2838 	evict_old();
2839 }
2840 
2841 /*
2842  *--------------------------------------------------------------
2843  * Module setup
2844  *--------------------------------------------------------------
2845  */
2846 
2847 /*
2848  * This is called only once for the whole dm_bufio module.
2849  * It initializes memory limit.
2850  */
2851 static int __init dm_bufio_init(void)
2852 {
2853 	__u64 mem;
2854 
2855 	dm_bufio_allocated_kmem_cache = 0;
2856 	dm_bufio_allocated_kmalloc = 0;
2857 	dm_bufio_allocated_get_free_pages = 0;
2858 	dm_bufio_allocated_vmalloc = 0;
2859 	dm_bufio_current_allocated = 0;
2860 
2861 	mem = (__u64)mult_frac(totalram_pages() - totalhigh_pages(),
2862 			       DM_BUFIO_MEMORY_PERCENT, 100) << PAGE_SHIFT;
2863 
2864 	if (mem > ULONG_MAX)
2865 		mem = ULONG_MAX;
2866 
2867 #ifdef CONFIG_MMU
2868 	if (mem > mult_frac(VMALLOC_TOTAL, DM_BUFIO_VMALLOC_PERCENT, 100))
2869 		mem = mult_frac(VMALLOC_TOTAL, DM_BUFIO_VMALLOC_PERCENT, 100);
2870 #endif
2871 
2872 	dm_bufio_default_cache_size = mem;
2873 	if (!dm_bufio_cache_size)
2874 		dm_bufio_cache_size = mem;
2875 
2876 	dm_bufio_wq = alloc_workqueue("dm_bufio_cache",
2877 				      WQ_MEM_RECLAIM | WQ_PERCPU, 0);
2878 	if (!dm_bufio_wq)
2879 		return -ENOMEM;
2880 
2881 	INIT_WORK(&dm_bufio_replacement_work, do_global_cleanup);
2882 
2883 	return 0;
2884 }
2885 
2886 /*
2887  * This is called once when unloading the dm_bufio module.
2888  */
2889 static void __exit dm_bufio_exit(void)
2890 {
2891 	int bug = 0;
2892 
2893 	destroy_workqueue(dm_bufio_wq);
2894 
2895 	if (dm_bufio_client_count) {
2896 		DMCRIT("%s: dm_bufio_client_count leaked: %d",
2897 			__func__, dm_bufio_client_count);
2898 		bug = 1;
2899 	}
2900 
2901 	if (dm_bufio_current_allocated) {
2902 		DMCRIT("%s: dm_bufio_current_allocated leaked: %lu",
2903 			__func__, dm_bufio_current_allocated);
2904 		bug = 1;
2905 	}
2906 
2907 	if (dm_bufio_allocated_get_free_pages) {
2908 		DMCRIT("%s: dm_bufio_allocated_get_free_pages leaked: %lu",
2909 		       __func__, dm_bufio_allocated_get_free_pages);
2910 		bug = 1;
2911 	}
2912 
2913 	if (dm_bufio_allocated_vmalloc) {
2914 		DMCRIT("%s: dm_bufio_vmalloc leaked: %lu",
2915 		       __func__, dm_bufio_allocated_vmalloc);
2916 		bug = 1;
2917 	}
2918 
2919 	WARN_ON(bug); /* leaks are not worth crashing the system */
2920 }
2921 
2922 module_init(dm_bufio_init)
2923 module_exit(dm_bufio_exit)
2924 
2925 module_param_named(max_cache_size_bytes, dm_bufio_cache_size, ulong, 0644);
2926 MODULE_PARM_DESC(max_cache_size_bytes, "Size of metadata cache");
2927 
2928 module_param_named(max_age_seconds, dm_bufio_max_age, uint, 0644);
2929 MODULE_PARM_DESC(max_age_seconds, "No longer does anything");
2930 
2931 module_param_named(retain_bytes, dm_bufio_retain_bytes, ulong, 0644);
2932 MODULE_PARM_DESC(retain_bytes, "Try to keep at least this many bytes cached in memory");
2933 
2934 module_param_named(peak_allocated_bytes, dm_bufio_peak_allocated, ulong, 0644);
2935 MODULE_PARM_DESC(peak_allocated_bytes, "Tracks the maximum allocated memory");
2936 
2937 module_param_named(allocated_kmem_cache_bytes, dm_bufio_allocated_kmem_cache, ulong, 0444);
2938 MODULE_PARM_DESC(allocated_kmem_cache_bytes, "Memory allocated with kmem_cache_alloc");
2939 
2940 module_param_named(allocated_kmalloc_bytes, dm_bufio_allocated_kmalloc, ulong, 0444);
2941 MODULE_PARM_DESC(allocated_kmalloc_bytes, "Memory allocated with kmalloc_alloc");
2942 
2943 module_param_named(allocated_get_free_pages_bytes, dm_bufio_allocated_get_free_pages, ulong, 0444);
2944 MODULE_PARM_DESC(allocated_get_free_pages_bytes, "Memory allocated with get_free_pages");
2945 
2946 module_param_named(allocated_vmalloc_bytes, dm_bufio_allocated_vmalloc, ulong, 0444);
2947 MODULE_PARM_DESC(allocated_vmalloc_bytes, "Memory allocated with vmalloc");
2948 
2949 module_param_named(current_allocated_bytes, dm_bufio_current_allocated, ulong, 0444);
2950 MODULE_PARM_DESC(current_allocated_bytes, "Memory currently used by the cache");
2951 
2952 MODULE_AUTHOR("Mikulas Patocka <dm-devel@lists.linux.dev>");
2953 MODULE_DESCRIPTION(DM_NAME " buffered I/O library");
2954 MODULE_LICENSE("GPL");
2955