• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2009-2011 Red Hat, Inc.
3  *
4  * Author: Mikulas Patocka <mpatocka@redhat.com>
5  *
6  * This file is released under the GPL.
7  */
8 
9 #include "dm-bufio.h"
10 
11 #include <linux/device-mapper.h>
12 #include <linux/dm-io.h>
13 #include <linux/slab.h>
14 #include <linux/vmalloc.h>
15 #include <linux/shrinker.h>
16 #include <linux/module.h>
17 #include <linux/rbtree.h>
18 
19 #define DM_MSG_PREFIX "bufio"
20 
21 /*
22  * Memory management policy:
23  *	Limit the number of buffers to DM_BUFIO_MEMORY_PERCENT of main memory
24  *	or DM_BUFIO_VMALLOC_PERCENT of vmalloc memory (whichever is lower).
25  *	Always allocate at least DM_BUFIO_MIN_BUFFERS buffers.
26  *	Start background writeback when there are DM_BUFIO_WRITEBACK_PERCENT
27  *	dirty buffers.
28  */
29 #define DM_BUFIO_MIN_BUFFERS		8
30 
31 #define DM_BUFIO_MEMORY_PERCENT		2
32 #define DM_BUFIO_VMALLOC_PERCENT	25
33 #define DM_BUFIO_WRITEBACK_PERCENT	75
34 
35 /*
36  * Check buffer ages in this interval (seconds)
37  */
38 #define DM_BUFIO_WORK_TIMER_SECS	10
39 
40 /*
41  * Free buffers when they are older than this (seconds)
42  */
43 #define DM_BUFIO_DEFAULT_AGE_SECS	60
44 
45 /*
46  * The number of bvec entries that are embedded directly in the buffer.
47  * If the chunk size is larger, dm-io is used to do the io.
48  */
49 #define DM_BUFIO_INLINE_VECS		16
50 
51 /*
52  * Don't try to use kmem_cache_alloc for blocks larger than this.
53  * For explanation, see alloc_buffer_data below.
54  */
55 #define DM_BUFIO_BLOCK_SIZE_SLAB_LIMIT	(PAGE_SIZE >> 1)
56 #define DM_BUFIO_BLOCK_SIZE_GFP_LIMIT	(PAGE_SIZE << (MAX_ORDER - 1))
57 
58 /*
59  * dm_buffer->list_mode
60  */
61 #define LIST_CLEAN	0
62 #define LIST_DIRTY	1
63 #define LIST_SIZE	2
64 
65 /*
66  * Linking of buffers:
67  *	All buffers are linked to cache_hash with their hash_list field.
68  *
69  *	Clean buffers that are not being written (B_WRITING not set)
70  *	are linked to lru[LIST_CLEAN] with their lru_list field.
71  *
72  *	Dirty and clean buffers that are being written are linked to
73  *	lru[LIST_DIRTY] with their lru_list field. When the write
74  *	finishes, the buffer cannot be relinked immediately (because we
75  *	are in an interrupt context and relinking requires process
76  *	context), so some clean-not-writing buffers can be held on
77  *	dirty_lru too.  They are later added to lru in the process
78  *	context.
79  */
80 struct dm_bufio_client {
81 	struct mutex lock;
82 
83 	struct list_head lru[LIST_SIZE];
84 	unsigned long n_buffers[LIST_SIZE];
85 
86 	struct block_device *bdev;
87 	unsigned block_size;
88 	unsigned char sectors_per_block_bits;
89 	unsigned char pages_per_block_bits;
90 	unsigned char blocks_per_page_bits;
91 	unsigned aux_size;
92 	void (*alloc_callback)(struct dm_buffer *);
93 	void (*write_callback)(struct dm_buffer *);
94 
95 	struct dm_io_client *dm_io;
96 
97 	struct list_head reserved_buffers;
98 	unsigned need_reserved_buffers;
99 
100 	unsigned minimum_buffers;
101 
102 	struct rb_root buffer_tree;
103 	wait_queue_head_t free_buffer_wait;
104 
105 	int async_write_error;
106 
107 	struct list_head client_list;
108 	struct shrinker shrinker;
109 };
110 
111 /*
112  * Buffer state bits.
113  */
114 #define B_READING	0
115 #define B_WRITING	1
116 #define B_DIRTY		2
117 
118 /*
119  * Describes how the block was allocated:
120  * kmem_cache_alloc(), __get_free_pages() or vmalloc().
121  * See the comment at alloc_buffer_data.
122  */
123 enum data_mode {
124 	DATA_MODE_SLAB = 0,
125 	DATA_MODE_GET_FREE_PAGES = 1,
126 	DATA_MODE_VMALLOC = 2,
127 	DATA_MODE_LIMIT = 3
128 };
129 
130 struct dm_buffer {
131 	struct rb_node node;
132 	struct list_head lru_list;
133 	sector_t block;
134 	void *data;
135 	enum data_mode data_mode;
136 	unsigned char list_mode;		/* LIST_* */
137 	unsigned hold_count;
138 	int read_error;
139 	int write_error;
140 	unsigned long state;
141 	unsigned long last_accessed;
142 	struct dm_bufio_client *c;
143 	struct list_head write_list;
144 	struct bio bio;
145 	struct bio_vec bio_vec[DM_BUFIO_INLINE_VECS];
146 };
147 
148 /*----------------------------------------------------------------*/
149 
150 static struct kmem_cache *dm_bufio_caches[PAGE_SHIFT - SECTOR_SHIFT];
151 static char *dm_bufio_cache_names[PAGE_SHIFT - SECTOR_SHIFT];
152 
dm_bufio_cache_index(struct dm_bufio_client * c)153 static inline int dm_bufio_cache_index(struct dm_bufio_client *c)
154 {
155 	unsigned ret = c->blocks_per_page_bits - 1;
156 
157 	BUG_ON(ret >= ARRAY_SIZE(dm_bufio_caches));
158 
159 	return ret;
160 }
161 
162 #define DM_BUFIO_CACHE(c)	(dm_bufio_caches[dm_bufio_cache_index(c)])
163 #define DM_BUFIO_CACHE_NAME(c)	(dm_bufio_cache_names[dm_bufio_cache_index(c)])
164 
165 #define dm_bufio_in_request()	(!!current->bio_list)
166 
dm_bufio_lock(struct dm_bufio_client * c)167 static void dm_bufio_lock(struct dm_bufio_client *c)
168 {
169 	mutex_lock_nested(&c->lock, dm_bufio_in_request());
170 }
171 
dm_bufio_trylock(struct dm_bufio_client * c)172 static int dm_bufio_trylock(struct dm_bufio_client *c)
173 {
174 	return mutex_trylock(&c->lock);
175 }
176 
dm_bufio_unlock(struct dm_bufio_client * c)177 static void dm_bufio_unlock(struct dm_bufio_client *c)
178 {
179 	mutex_unlock(&c->lock);
180 }
181 
182 /*
183  * FIXME Move to sched.h?
184  */
185 #ifdef CONFIG_PREEMPT_VOLUNTARY
186 #  define dm_bufio_cond_resched()		\
187 do {						\
188 	if (unlikely(need_resched()))		\
189 		_cond_resched();		\
190 } while (0)
191 #else
192 #  define dm_bufio_cond_resched()                do { } while (0)
193 #endif
194 
195 /*----------------------------------------------------------------*/
196 
197 /*
198  * Default cache size: available memory divided by the ratio.
199  */
200 static unsigned long dm_bufio_default_cache_size;
201 
202 /*
203  * Total cache size set by the user.
204  */
205 static unsigned long dm_bufio_cache_size;
206 
207 /*
208  * A copy of dm_bufio_cache_size because dm_bufio_cache_size can change
209  * at any time.  If it disagrees, the user has changed cache size.
210  */
211 static unsigned long dm_bufio_cache_size_latch;
212 
213 static DEFINE_SPINLOCK(param_spinlock);
214 
215 /*
216  * Buffers are freed after this timeout
217  */
218 static unsigned dm_bufio_max_age = DM_BUFIO_DEFAULT_AGE_SECS;
219 
220 static unsigned long dm_bufio_peak_allocated;
221 static unsigned long dm_bufio_allocated_kmem_cache;
222 static unsigned long dm_bufio_allocated_get_free_pages;
223 static unsigned long dm_bufio_allocated_vmalloc;
224 static unsigned long dm_bufio_current_allocated;
225 
226 /*----------------------------------------------------------------*/
227 
228 /*
229  * Per-client cache: dm_bufio_cache_size / dm_bufio_client_count
230  */
231 static unsigned long dm_bufio_cache_size_per_client;
232 
233 /*
234  * The current number of clients.
235  */
236 static int dm_bufio_client_count;
237 
238 /*
239  * The list of all clients.
240  */
241 static LIST_HEAD(dm_bufio_all_clients);
242 
243 /*
244  * This mutex protects dm_bufio_cache_size_latch,
245  * dm_bufio_cache_size_per_client and dm_bufio_client_count
246  */
247 static DEFINE_MUTEX(dm_bufio_clients_lock);
248 
249 /*----------------------------------------------------------------
250  * A red/black tree acts as an index for all the buffers.
251  *--------------------------------------------------------------*/
__find(struct dm_bufio_client * c,sector_t block)252 static struct dm_buffer *__find(struct dm_bufio_client *c, sector_t block)
253 {
254 	struct rb_node *n = c->buffer_tree.rb_node;
255 	struct dm_buffer *b;
256 
257 	while (n) {
258 		b = container_of(n, struct dm_buffer, node);
259 
260 		if (b->block == block)
261 			return b;
262 
263 		n = (b->block < block) ? n->rb_left : n->rb_right;
264 	}
265 
266 	return NULL;
267 }
268 
__insert(struct dm_bufio_client * c,struct dm_buffer * b)269 static void __insert(struct dm_bufio_client *c, struct dm_buffer *b)
270 {
271 	struct rb_node **new = &c->buffer_tree.rb_node, *parent = NULL;
272 	struct dm_buffer *found;
273 
274 	while (*new) {
275 		found = container_of(*new, struct dm_buffer, node);
276 
277 		if (found->block == b->block) {
278 			BUG_ON(found != b);
279 			return;
280 		}
281 
282 		parent = *new;
283 		new = (found->block < b->block) ?
284 			&((*new)->rb_left) : &((*new)->rb_right);
285 	}
286 
287 	rb_link_node(&b->node, parent, new);
288 	rb_insert_color(&b->node, &c->buffer_tree);
289 }
290 
__remove(struct dm_bufio_client * c,struct dm_buffer * b)291 static void __remove(struct dm_bufio_client *c, struct dm_buffer *b)
292 {
293 	rb_erase(&b->node, &c->buffer_tree);
294 }
295 
296 /*----------------------------------------------------------------*/
297 
adjust_total_allocated(enum data_mode data_mode,long diff)298 static void adjust_total_allocated(enum data_mode data_mode, long diff)
299 {
300 	static unsigned long * const class_ptr[DATA_MODE_LIMIT] = {
301 		&dm_bufio_allocated_kmem_cache,
302 		&dm_bufio_allocated_get_free_pages,
303 		&dm_bufio_allocated_vmalloc,
304 	};
305 
306 	spin_lock(&param_spinlock);
307 
308 	*class_ptr[data_mode] += diff;
309 
310 	dm_bufio_current_allocated += diff;
311 
312 	if (dm_bufio_current_allocated > dm_bufio_peak_allocated)
313 		dm_bufio_peak_allocated = dm_bufio_current_allocated;
314 
315 	spin_unlock(&param_spinlock);
316 }
317 
318 /*
319  * Change the number of clients and recalculate per-client limit.
320  */
__cache_size_refresh(void)321 static void __cache_size_refresh(void)
322 {
323 	BUG_ON(!mutex_is_locked(&dm_bufio_clients_lock));
324 	BUG_ON(dm_bufio_client_count < 0);
325 
326 	dm_bufio_cache_size_latch = ACCESS_ONCE(dm_bufio_cache_size);
327 
328 	/*
329 	 * Use default if set to 0 and report the actual cache size used.
330 	 */
331 	if (!dm_bufio_cache_size_latch) {
332 		(void)cmpxchg(&dm_bufio_cache_size, 0,
333 			      dm_bufio_default_cache_size);
334 		dm_bufio_cache_size_latch = dm_bufio_default_cache_size;
335 	}
336 
337 	dm_bufio_cache_size_per_client = dm_bufio_cache_size_latch /
338 					 (dm_bufio_client_count ? : 1);
339 }
340 
341 /*
342  * Allocating buffer data.
343  *
344  * Small buffers are allocated with kmem_cache, to use space optimally.
345  *
346  * For large buffers, we choose between get_free_pages and vmalloc.
347  * Each has advantages and disadvantages.
348  *
349  * __get_free_pages can randomly fail if the memory is fragmented.
350  * __vmalloc won't randomly fail, but vmalloc space is limited (it may be
351  * as low as 128M) so using it for caching is not appropriate.
352  *
353  * If the allocation may fail we use __get_free_pages. Memory fragmentation
354  * won't have a fatal effect here, but it just causes flushes of some other
355  * buffers and more I/O will be performed. Don't use __get_free_pages if it
356  * always fails (i.e. order >= MAX_ORDER).
357  *
358  * If the allocation shouldn't fail we use __vmalloc. This is only for the
359  * initial reserve allocation, so there's no risk of wasting all vmalloc
360  * space.
361  */
alloc_buffer_data(struct dm_bufio_client * c,gfp_t gfp_mask,enum data_mode * data_mode)362 static void *alloc_buffer_data(struct dm_bufio_client *c, gfp_t gfp_mask,
363 			       enum data_mode *data_mode)
364 {
365 	unsigned noio_flag;
366 	void *ptr;
367 
368 	if (c->block_size <= DM_BUFIO_BLOCK_SIZE_SLAB_LIMIT) {
369 		*data_mode = DATA_MODE_SLAB;
370 		return kmem_cache_alloc(DM_BUFIO_CACHE(c), gfp_mask);
371 	}
372 
373 	if (c->block_size <= DM_BUFIO_BLOCK_SIZE_GFP_LIMIT &&
374 	    gfp_mask & __GFP_NORETRY) {
375 		*data_mode = DATA_MODE_GET_FREE_PAGES;
376 		return (void *)__get_free_pages(gfp_mask,
377 						c->pages_per_block_bits);
378 	}
379 
380 	*data_mode = DATA_MODE_VMALLOC;
381 
382 	/*
383 	 * __vmalloc allocates the data pages and auxiliary structures with
384 	 * gfp_flags that were specified, but pagetables are always allocated
385 	 * with GFP_KERNEL, no matter what was specified as gfp_mask.
386 	 *
387 	 * Consequently, we must set per-process flag PF_MEMALLOC_NOIO so that
388 	 * all allocations done by this process (including pagetables) are done
389 	 * as if GFP_NOIO was specified.
390 	 */
391 
392 	noio_flag = 0;
393 	if (gfp_mask & __GFP_NORETRY)
394 		noio_flag = memalloc_noio_save();
395 
396 	ptr = __vmalloc(c->block_size, gfp_mask | __GFP_HIGHMEM, PAGE_KERNEL);
397 
398 	if (gfp_mask & __GFP_NORETRY)
399 		memalloc_noio_restore(noio_flag);
400 
401 	return ptr;
402 }
403 
404 /*
405  * Free buffer's data.
406  */
free_buffer_data(struct dm_bufio_client * c,void * data,enum data_mode data_mode)407 static void free_buffer_data(struct dm_bufio_client *c,
408 			     void *data, enum data_mode data_mode)
409 {
410 	switch (data_mode) {
411 	case DATA_MODE_SLAB:
412 		kmem_cache_free(DM_BUFIO_CACHE(c), data);
413 		break;
414 
415 	case DATA_MODE_GET_FREE_PAGES:
416 		free_pages((unsigned long)data, c->pages_per_block_bits);
417 		break;
418 
419 	case DATA_MODE_VMALLOC:
420 		vfree(data);
421 		break;
422 
423 	default:
424 		DMCRIT("dm_bufio_free_buffer_data: bad data mode: %d",
425 		       data_mode);
426 		BUG();
427 	}
428 }
429 
430 /*
431  * Allocate buffer and its data.
432  */
alloc_buffer(struct dm_bufio_client * c,gfp_t gfp_mask)433 static struct dm_buffer *alloc_buffer(struct dm_bufio_client *c, gfp_t gfp_mask)
434 {
435 	struct dm_buffer *b = kmalloc(sizeof(struct dm_buffer) + c->aux_size,
436 				      gfp_mask);
437 
438 	if (!b)
439 		return NULL;
440 
441 	b->c = c;
442 
443 	b->data = alloc_buffer_data(c, gfp_mask, &b->data_mode);
444 	if (!b->data) {
445 		kfree(b);
446 		return NULL;
447 	}
448 
449 	adjust_total_allocated(b->data_mode, (long)c->block_size);
450 
451 	return b;
452 }
453 
454 /*
455  * Free buffer and its data.
456  */
free_buffer(struct dm_buffer * b)457 static void free_buffer(struct dm_buffer *b)
458 {
459 	struct dm_bufio_client *c = b->c;
460 
461 	adjust_total_allocated(b->data_mode, -(long)c->block_size);
462 
463 	free_buffer_data(c, b->data, b->data_mode);
464 	kfree(b);
465 }
466 
467 /*
468  * Link buffer to the hash list and clean or dirty queue.
469  */
__link_buffer(struct dm_buffer * b,sector_t block,int dirty)470 static void __link_buffer(struct dm_buffer *b, sector_t block, int dirty)
471 {
472 	struct dm_bufio_client *c = b->c;
473 
474 	c->n_buffers[dirty]++;
475 	b->block = block;
476 	b->list_mode = dirty;
477 	list_add(&b->lru_list, &c->lru[dirty]);
478 	__insert(b->c, b);
479 	b->last_accessed = jiffies;
480 }
481 
482 /*
483  * Unlink buffer from the hash list and dirty or clean queue.
484  */
__unlink_buffer(struct dm_buffer * b)485 static void __unlink_buffer(struct dm_buffer *b)
486 {
487 	struct dm_bufio_client *c = b->c;
488 
489 	BUG_ON(!c->n_buffers[b->list_mode]);
490 
491 	c->n_buffers[b->list_mode]--;
492 	__remove(b->c, b);
493 	list_del(&b->lru_list);
494 }
495 
496 /*
497  * Place the buffer to the head of dirty or clean LRU queue.
498  */
__relink_lru(struct dm_buffer * b,int dirty)499 static void __relink_lru(struct dm_buffer *b, int dirty)
500 {
501 	struct dm_bufio_client *c = b->c;
502 
503 	BUG_ON(!c->n_buffers[b->list_mode]);
504 
505 	c->n_buffers[b->list_mode]--;
506 	c->n_buffers[dirty]++;
507 	b->list_mode = dirty;
508 	list_move(&b->lru_list, &c->lru[dirty]);
509 	b->last_accessed = jiffies;
510 }
511 
512 /*----------------------------------------------------------------
513  * Submit I/O on the buffer.
514  *
515  * Bio interface is faster but it has some problems:
516  *	the vector list is limited (increasing this limit increases
517  *	memory-consumption per buffer, so it is not viable);
518  *
519  *	the memory must be direct-mapped, not vmalloced;
520  *
521  *	the I/O driver can reject requests spuriously if it thinks that
522  *	the requests are too big for the device or if they cross a
523  *	controller-defined memory boundary.
524  *
525  * If the buffer is small enough (up to DM_BUFIO_INLINE_VECS pages) and
526  * it is not vmalloced, try using the bio interface.
527  *
528  * If the buffer is big, if it is vmalloced or if the underlying device
529  * rejects the bio because it is too large, use dm-io layer to do the I/O.
530  * The dm-io layer splits the I/O into multiple requests, avoiding the above
531  * shortcomings.
532  *--------------------------------------------------------------*/
533 
534 /*
535  * dm-io completion routine. It just calls b->bio.bi_end_io, pretending
536  * that the request was handled directly with bio interface.
537  */
dmio_complete(unsigned long error,void * context)538 static void dmio_complete(unsigned long error, void *context)
539 {
540 	struct dm_buffer *b = context;
541 
542 	b->bio.bi_end_io(&b->bio, error ? -EIO : 0);
543 }
544 
use_dmio(struct dm_buffer * b,int rw,sector_t block,bio_end_io_t * end_io)545 static void use_dmio(struct dm_buffer *b, int rw, sector_t block,
546 		     bio_end_io_t *end_io)
547 {
548 	int r;
549 	struct dm_io_request io_req = {
550 		.bi_rw = rw,
551 		.notify.fn = dmio_complete,
552 		.notify.context = b,
553 		.client = b->c->dm_io,
554 	};
555 	struct dm_io_region region = {
556 		.bdev = b->c->bdev,
557 		.sector = block << b->c->sectors_per_block_bits,
558 		.count = b->c->block_size >> SECTOR_SHIFT,
559 	};
560 
561 	if (b->data_mode != DATA_MODE_VMALLOC) {
562 		io_req.mem.type = DM_IO_KMEM;
563 		io_req.mem.ptr.addr = b->data;
564 	} else {
565 		io_req.mem.type = DM_IO_VMA;
566 		io_req.mem.ptr.vma = b->data;
567 	}
568 
569 	b->bio.bi_end_io = end_io;
570 
571 	r = dm_io(&io_req, 1, &region, NULL);
572 	if (r)
573 		end_io(&b->bio, r);
574 }
575 
inline_endio(struct bio * bio,int error)576 static void inline_endio(struct bio *bio, int error)
577 {
578 	bio_end_io_t *end_fn = bio->bi_private;
579 
580 	/*
581 	 * Reset the bio to free any attached resources
582 	 * (e.g. bio integrity profiles).
583 	 */
584 	bio_reset(bio);
585 
586 	end_fn(bio, error);
587 }
588 
use_inline_bio(struct dm_buffer * b,int rw,sector_t block,bio_end_io_t * end_io)589 static void use_inline_bio(struct dm_buffer *b, int rw, sector_t block,
590 			   bio_end_io_t *end_io)
591 {
592 	char *ptr;
593 	int len;
594 
595 	bio_init(&b->bio);
596 	b->bio.bi_io_vec = b->bio_vec;
597 	b->bio.bi_max_vecs = DM_BUFIO_INLINE_VECS;
598 	b->bio.bi_iter.bi_sector = block << b->c->sectors_per_block_bits;
599 	b->bio.bi_bdev = b->c->bdev;
600 	b->bio.bi_end_io = inline_endio;
601 	/*
602 	 * Use of .bi_private isn't a problem here because
603 	 * the dm_buffer's inline bio is local to bufio.
604 	 */
605 	b->bio.bi_private = end_io;
606 
607 	/*
608 	 * We assume that if len >= PAGE_SIZE ptr is page-aligned.
609 	 * If len < PAGE_SIZE the buffer doesn't cross page boundary.
610 	 */
611 	ptr = b->data;
612 	len = b->c->block_size;
613 
614 	if (len >= PAGE_SIZE)
615 		BUG_ON((unsigned long)ptr & (PAGE_SIZE - 1));
616 	else
617 		BUG_ON((unsigned long)ptr & (len - 1));
618 
619 	do {
620 		if (!bio_add_page(&b->bio, virt_to_page(ptr),
621 				  len < PAGE_SIZE ? len : PAGE_SIZE,
622 				  virt_to_phys(ptr) & (PAGE_SIZE - 1))) {
623 			BUG_ON(b->c->block_size <= PAGE_SIZE);
624 			use_dmio(b, rw, block, end_io);
625 			return;
626 		}
627 
628 		len -= PAGE_SIZE;
629 		ptr += PAGE_SIZE;
630 	} while (len > 0);
631 
632 	submit_bio(rw, &b->bio);
633 }
634 
submit_io(struct dm_buffer * b,int rw,sector_t block,bio_end_io_t * end_io)635 static void submit_io(struct dm_buffer *b, int rw, sector_t block,
636 		      bio_end_io_t *end_io)
637 {
638 	if (rw == WRITE && b->c->write_callback)
639 		b->c->write_callback(b);
640 
641 	if (b->c->block_size <= DM_BUFIO_INLINE_VECS * PAGE_SIZE &&
642 	    b->data_mode != DATA_MODE_VMALLOC)
643 		use_inline_bio(b, rw, block, end_io);
644 	else
645 		use_dmio(b, rw, block, end_io);
646 }
647 
648 /*----------------------------------------------------------------
649  * Writing dirty buffers
650  *--------------------------------------------------------------*/
651 
652 /*
653  * The endio routine for write.
654  *
655  * Set the error, clear B_WRITING bit and wake anyone who was waiting on
656  * it.
657  */
write_endio(struct bio * bio,int error)658 static void write_endio(struct bio *bio, int error)
659 {
660 	struct dm_buffer *b = container_of(bio, struct dm_buffer, bio);
661 
662 	b->write_error = error;
663 	if (unlikely(error)) {
664 		struct dm_bufio_client *c = b->c;
665 		(void)cmpxchg(&c->async_write_error, 0, error);
666 	}
667 
668 	BUG_ON(!test_bit(B_WRITING, &b->state));
669 
670 	smp_mb__before_atomic();
671 	clear_bit(B_WRITING, &b->state);
672 	smp_mb__after_atomic();
673 
674 	wake_up_bit(&b->state, B_WRITING);
675 }
676 
677 /*
678  * Initiate a write on a dirty buffer, but don't wait for it.
679  *
680  * - If the buffer is not dirty, exit.
681  * - If there some previous write going on, wait for it to finish (we can't
682  *   have two writes on the same buffer simultaneously).
683  * - Submit our write and don't wait on it. We set B_WRITING indicating
684  *   that there is a write in progress.
685  */
__write_dirty_buffer(struct dm_buffer * b,struct list_head * write_list)686 static void __write_dirty_buffer(struct dm_buffer *b,
687 				 struct list_head *write_list)
688 {
689 	if (!test_bit(B_DIRTY, &b->state))
690 		return;
691 
692 	clear_bit(B_DIRTY, &b->state);
693 	wait_on_bit_lock_io(&b->state, B_WRITING, TASK_UNINTERRUPTIBLE);
694 
695 	if (!write_list)
696 		submit_io(b, WRITE, b->block, write_endio);
697 	else
698 		list_add_tail(&b->write_list, write_list);
699 }
700 
__flush_write_list(struct list_head * write_list)701 static void __flush_write_list(struct list_head *write_list)
702 {
703 	struct blk_plug plug;
704 	blk_start_plug(&plug);
705 	while (!list_empty(write_list)) {
706 		struct dm_buffer *b =
707 			list_entry(write_list->next, struct dm_buffer, write_list);
708 		list_del(&b->write_list);
709 		submit_io(b, WRITE, b->block, write_endio);
710 		dm_bufio_cond_resched();
711 	}
712 	blk_finish_plug(&plug);
713 }
714 
715 /*
716  * Wait until any activity on the buffer finishes.  Possibly write the
717  * buffer if it is dirty.  When this function finishes, there is no I/O
718  * running on the buffer and the buffer is not dirty.
719  */
__make_buffer_clean(struct dm_buffer * b)720 static void __make_buffer_clean(struct dm_buffer *b)
721 {
722 	BUG_ON(b->hold_count);
723 
724 	if (!b->state)	/* fast case */
725 		return;
726 
727 	wait_on_bit_io(&b->state, B_READING, TASK_UNINTERRUPTIBLE);
728 	__write_dirty_buffer(b, NULL);
729 	wait_on_bit_io(&b->state, B_WRITING, TASK_UNINTERRUPTIBLE);
730 }
731 
732 /*
733  * Find some buffer that is not held by anybody, clean it, unlink it and
734  * return it.
735  */
__get_unclaimed_buffer(struct dm_bufio_client * c)736 static struct dm_buffer *__get_unclaimed_buffer(struct dm_bufio_client *c)
737 {
738 	struct dm_buffer *b;
739 
740 	list_for_each_entry_reverse(b, &c->lru[LIST_CLEAN], lru_list) {
741 		BUG_ON(test_bit(B_WRITING, &b->state));
742 		BUG_ON(test_bit(B_DIRTY, &b->state));
743 
744 		if (!b->hold_count) {
745 			__make_buffer_clean(b);
746 			__unlink_buffer(b);
747 			return b;
748 		}
749 		dm_bufio_cond_resched();
750 	}
751 
752 	list_for_each_entry_reverse(b, &c->lru[LIST_DIRTY], lru_list) {
753 		BUG_ON(test_bit(B_READING, &b->state));
754 
755 		if (!b->hold_count) {
756 			__make_buffer_clean(b);
757 			__unlink_buffer(b);
758 			return b;
759 		}
760 		dm_bufio_cond_resched();
761 	}
762 
763 	return NULL;
764 }
765 
766 /*
767  * Wait until some other threads free some buffer or release hold count on
768  * some buffer.
769  *
770  * This function is entered with c->lock held, drops it and regains it
771  * before exiting.
772  */
__wait_for_free_buffer(struct dm_bufio_client * c)773 static void __wait_for_free_buffer(struct dm_bufio_client *c)
774 {
775 	DECLARE_WAITQUEUE(wait, current);
776 
777 	add_wait_queue(&c->free_buffer_wait, &wait);
778 	set_task_state(current, TASK_UNINTERRUPTIBLE);
779 	dm_bufio_unlock(c);
780 
781 	io_schedule();
782 
783 	remove_wait_queue(&c->free_buffer_wait, &wait);
784 
785 	dm_bufio_lock(c);
786 }
787 
788 enum new_flag {
789 	NF_FRESH = 0,
790 	NF_READ = 1,
791 	NF_GET = 2,
792 	NF_PREFETCH = 3
793 };
794 
795 /*
796  * Allocate a new buffer. If the allocation is not possible, wait until
797  * some other thread frees a buffer.
798  *
799  * May drop the lock and regain it.
800  */
__alloc_buffer_wait_no_callback(struct dm_bufio_client * c,enum new_flag nf)801 static struct dm_buffer *__alloc_buffer_wait_no_callback(struct dm_bufio_client *c, enum new_flag nf)
802 {
803 	struct dm_buffer *b;
804 
805 	/*
806 	 * dm-bufio is resistant to allocation failures (it just keeps
807 	 * one buffer reserved in cases all the allocations fail).
808 	 * So set flags to not try too hard:
809 	 *	GFP_NOIO: don't recurse into the I/O layer
810 	 *	__GFP_NORETRY: don't retry and rather return failure
811 	 *	__GFP_NOMEMALLOC: don't use emergency reserves
812 	 *	__GFP_NOWARN: don't print a warning in case of failure
813 	 *
814 	 * For debugging, if we set the cache size to 1, no new buffers will
815 	 * be allocated.
816 	 */
817 	while (1) {
818 		if (dm_bufio_cache_size_latch != 1) {
819 			b = alloc_buffer(c, GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
820 			if (b)
821 				return b;
822 		}
823 
824 		if (nf == NF_PREFETCH)
825 			return NULL;
826 
827 		if (!list_empty(&c->reserved_buffers)) {
828 			b = list_entry(c->reserved_buffers.next,
829 				       struct dm_buffer, lru_list);
830 			list_del(&b->lru_list);
831 			c->need_reserved_buffers++;
832 
833 			return b;
834 		}
835 
836 		b = __get_unclaimed_buffer(c);
837 		if (b)
838 			return b;
839 
840 		__wait_for_free_buffer(c);
841 	}
842 }
843 
__alloc_buffer_wait(struct dm_bufio_client * c,enum new_flag nf)844 static struct dm_buffer *__alloc_buffer_wait(struct dm_bufio_client *c, enum new_flag nf)
845 {
846 	struct dm_buffer *b = __alloc_buffer_wait_no_callback(c, nf);
847 
848 	if (!b)
849 		return NULL;
850 
851 	if (c->alloc_callback)
852 		c->alloc_callback(b);
853 
854 	return b;
855 }
856 
857 /*
858  * Free a buffer and wake other threads waiting for free buffers.
859  */
__free_buffer_wake(struct dm_buffer * b)860 static void __free_buffer_wake(struct dm_buffer *b)
861 {
862 	struct dm_bufio_client *c = b->c;
863 
864 	if (!c->need_reserved_buffers)
865 		free_buffer(b);
866 	else {
867 		list_add(&b->lru_list, &c->reserved_buffers);
868 		c->need_reserved_buffers--;
869 	}
870 
871 	wake_up(&c->free_buffer_wait);
872 }
873 
__write_dirty_buffers_async(struct dm_bufio_client * c,int no_wait,struct list_head * write_list)874 static void __write_dirty_buffers_async(struct dm_bufio_client *c, int no_wait,
875 					struct list_head *write_list)
876 {
877 	struct dm_buffer *b, *tmp;
878 
879 	list_for_each_entry_safe_reverse(b, tmp, &c->lru[LIST_DIRTY], lru_list) {
880 		BUG_ON(test_bit(B_READING, &b->state));
881 
882 		if (!test_bit(B_DIRTY, &b->state) &&
883 		    !test_bit(B_WRITING, &b->state)) {
884 			__relink_lru(b, LIST_CLEAN);
885 			continue;
886 		}
887 
888 		if (no_wait && test_bit(B_WRITING, &b->state))
889 			return;
890 
891 		__write_dirty_buffer(b, write_list);
892 		dm_bufio_cond_resched();
893 	}
894 }
895 
896 /*
897  * Get writeback threshold and buffer limit for a given client.
898  */
__get_memory_limit(struct dm_bufio_client * c,unsigned long * threshold_buffers,unsigned long * limit_buffers)899 static void __get_memory_limit(struct dm_bufio_client *c,
900 			       unsigned long *threshold_buffers,
901 			       unsigned long *limit_buffers)
902 {
903 	unsigned long buffers;
904 
905 	if (unlikely(ACCESS_ONCE(dm_bufio_cache_size) != dm_bufio_cache_size_latch)) {
906 		if (mutex_trylock(&dm_bufio_clients_lock)) {
907 			__cache_size_refresh();
908 			mutex_unlock(&dm_bufio_clients_lock);
909 		}
910 	}
911 
912 	buffers = dm_bufio_cache_size_per_client >>
913 		  (c->sectors_per_block_bits + SECTOR_SHIFT);
914 
915 	if (buffers < c->minimum_buffers)
916 		buffers = c->minimum_buffers;
917 
918 	*limit_buffers = buffers;
919 	*threshold_buffers = mult_frac(buffers,
920 				       DM_BUFIO_WRITEBACK_PERCENT, 100);
921 }
922 
923 /*
924  * Check if we're over watermark.
925  * If we are over threshold_buffers, start freeing buffers.
926  * If we're over "limit_buffers", block until we get under the limit.
927  */
__check_watermark(struct dm_bufio_client * c,struct list_head * write_list)928 static void __check_watermark(struct dm_bufio_client *c,
929 			      struct list_head *write_list)
930 {
931 	unsigned long threshold_buffers, limit_buffers;
932 
933 	__get_memory_limit(c, &threshold_buffers, &limit_buffers);
934 
935 	while (c->n_buffers[LIST_CLEAN] + c->n_buffers[LIST_DIRTY] >
936 	       limit_buffers) {
937 
938 		struct dm_buffer *b = __get_unclaimed_buffer(c);
939 
940 		if (!b)
941 			return;
942 
943 		__free_buffer_wake(b);
944 		dm_bufio_cond_resched();
945 	}
946 
947 	if (c->n_buffers[LIST_DIRTY] > threshold_buffers)
948 		__write_dirty_buffers_async(c, 1, write_list);
949 }
950 
951 /*----------------------------------------------------------------
952  * Getting a buffer
953  *--------------------------------------------------------------*/
954 
__bufio_new(struct dm_bufio_client * c,sector_t block,enum new_flag nf,int * need_submit,struct list_head * write_list)955 static struct dm_buffer *__bufio_new(struct dm_bufio_client *c, sector_t block,
956 				     enum new_flag nf, int *need_submit,
957 				     struct list_head *write_list)
958 {
959 	struct dm_buffer *b, *new_b = NULL;
960 
961 	*need_submit = 0;
962 
963 	b = __find(c, block);
964 	if (b)
965 		goto found_buffer;
966 
967 	if (nf == NF_GET)
968 		return NULL;
969 
970 	new_b = __alloc_buffer_wait(c, nf);
971 	if (!new_b)
972 		return NULL;
973 
974 	/*
975 	 * We've had a period where the mutex was unlocked, so need to
976 	 * recheck the hash table.
977 	 */
978 	b = __find(c, block);
979 	if (b) {
980 		__free_buffer_wake(new_b);
981 		goto found_buffer;
982 	}
983 
984 	__check_watermark(c, write_list);
985 
986 	b = new_b;
987 	b->hold_count = 1;
988 	b->read_error = 0;
989 	b->write_error = 0;
990 	__link_buffer(b, block, LIST_CLEAN);
991 
992 	if (nf == NF_FRESH) {
993 		b->state = 0;
994 		return b;
995 	}
996 
997 	b->state = 1 << B_READING;
998 	*need_submit = 1;
999 
1000 	return b;
1001 
1002 found_buffer:
1003 	if (nf == NF_PREFETCH)
1004 		return NULL;
1005 	/*
1006 	 * Note: it is essential that we don't wait for the buffer to be
1007 	 * read if dm_bufio_get function is used. Both dm_bufio_get and
1008 	 * dm_bufio_prefetch can be used in the driver request routine.
1009 	 * If the user called both dm_bufio_prefetch and dm_bufio_get on
1010 	 * the same buffer, it would deadlock if we waited.
1011 	 */
1012 	if (nf == NF_GET && unlikely(test_bit(B_READING, &b->state)))
1013 		return NULL;
1014 
1015 	b->hold_count++;
1016 	__relink_lru(b, test_bit(B_DIRTY, &b->state) ||
1017 		     test_bit(B_WRITING, &b->state));
1018 	return b;
1019 }
1020 
1021 /*
1022  * The endio routine for reading: set the error, clear the bit and wake up
1023  * anyone waiting on the buffer.
1024  */
read_endio(struct bio * bio,int error)1025 static void read_endio(struct bio *bio, int error)
1026 {
1027 	struct dm_buffer *b = container_of(bio, struct dm_buffer, bio);
1028 
1029 	b->read_error = error;
1030 
1031 	BUG_ON(!test_bit(B_READING, &b->state));
1032 
1033 	smp_mb__before_atomic();
1034 	clear_bit(B_READING, &b->state);
1035 	smp_mb__after_atomic();
1036 
1037 	wake_up_bit(&b->state, B_READING);
1038 }
1039 
1040 /*
1041  * A common routine for dm_bufio_new and dm_bufio_read.  Operation of these
1042  * functions is similar except that dm_bufio_new doesn't read the
1043  * buffer from the disk (assuming that the caller overwrites all the data
1044  * and uses dm_bufio_mark_buffer_dirty to write new data back).
1045  */
new_read(struct dm_bufio_client * c,sector_t block,enum new_flag nf,struct dm_buffer ** bp)1046 static void *new_read(struct dm_bufio_client *c, sector_t block,
1047 		      enum new_flag nf, struct dm_buffer **bp)
1048 {
1049 	int need_submit;
1050 	struct dm_buffer *b;
1051 
1052 	LIST_HEAD(write_list);
1053 
1054 	dm_bufio_lock(c);
1055 	b = __bufio_new(c, block, nf, &need_submit, &write_list);
1056 	dm_bufio_unlock(c);
1057 
1058 	__flush_write_list(&write_list);
1059 
1060 	if (!b)
1061 		return b;
1062 
1063 	if (need_submit)
1064 		submit_io(b, READ, b->block, read_endio);
1065 
1066 	wait_on_bit_io(&b->state, B_READING, TASK_UNINTERRUPTIBLE);
1067 
1068 	if (b->read_error) {
1069 		int error = b->read_error;
1070 
1071 		dm_bufio_release(b);
1072 
1073 		return ERR_PTR(error);
1074 	}
1075 
1076 	*bp = b;
1077 
1078 	return b->data;
1079 }
1080 
dm_bufio_get(struct dm_bufio_client * c,sector_t block,struct dm_buffer ** bp)1081 void *dm_bufio_get(struct dm_bufio_client *c, sector_t block,
1082 		   struct dm_buffer **bp)
1083 {
1084 	return new_read(c, block, NF_GET, bp);
1085 }
1086 EXPORT_SYMBOL_GPL(dm_bufio_get);
1087 
dm_bufio_read(struct dm_bufio_client * c,sector_t block,struct dm_buffer ** bp)1088 void *dm_bufio_read(struct dm_bufio_client *c, sector_t block,
1089 		    struct dm_buffer **bp)
1090 {
1091 	BUG_ON(dm_bufio_in_request());
1092 
1093 	return new_read(c, block, NF_READ, bp);
1094 }
1095 EXPORT_SYMBOL_GPL(dm_bufio_read);
1096 
dm_bufio_new(struct dm_bufio_client * c,sector_t block,struct dm_buffer ** bp)1097 void *dm_bufio_new(struct dm_bufio_client *c, sector_t block,
1098 		   struct dm_buffer **bp)
1099 {
1100 	BUG_ON(dm_bufio_in_request());
1101 
1102 	return new_read(c, block, NF_FRESH, bp);
1103 }
1104 EXPORT_SYMBOL_GPL(dm_bufio_new);
1105 
dm_bufio_prefetch(struct dm_bufio_client * c,sector_t block,unsigned n_blocks)1106 void dm_bufio_prefetch(struct dm_bufio_client *c,
1107 		       sector_t block, unsigned n_blocks)
1108 {
1109 	struct blk_plug plug;
1110 
1111 	LIST_HEAD(write_list);
1112 
1113 	BUG_ON(dm_bufio_in_request());
1114 
1115 	blk_start_plug(&plug);
1116 	dm_bufio_lock(c);
1117 
1118 	for (; n_blocks--; block++) {
1119 		int need_submit;
1120 		struct dm_buffer *b;
1121 		b = __bufio_new(c, block, NF_PREFETCH, &need_submit,
1122 				&write_list);
1123 		if (unlikely(!list_empty(&write_list))) {
1124 			dm_bufio_unlock(c);
1125 			blk_finish_plug(&plug);
1126 			__flush_write_list(&write_list);
1127 			blk_start_plug(&plug);
1128 			dm_bufio_lock(c);
1129 		}
1130 		if (unlikely(b != NULL)) {
1131 			dm_bufio_unlock(c);
1132 
1133 			if (need_submit)
1134 				submit_io(b, READ, b->block, read_endio);
1135 			dm_bufio_release(b);
1136 
1137 			dm_bufio_cond_resched();
1138 
1139 			if (!n_blocks)
1140 				goto flush_plug;
1141 			dm_bufio_lock(c);
1142 		}
1143 	}
1144 
1145 	dm_bufio_unlock(c);
1146 
1147 flush_plug:
1148 	blk_finish_plug(&plug);
1149 }
1150 EXPORT_SYMBOL_GPL(dm_bufio_prefetch);
1151 
dm_bufio_release(struct dm_buffer * b)1152 void dm_bufio_release(struct dm_buffer *b)
1153 {
1154 	struct dm_bufio_client *c = b->c;
1155 
1156 	dm_bufio_lock(c);
1157 
1158 	BUG_ON(!b->hold_count);
1159 
1160 	b->hold_count--;
1161 	if (!b->hold_count) {
1162 		wake_up(&c->free_buffer_wait);
1163 
1164 		/*
1165 		 * If there were errors on the buffer, and the buffer is not
1166 		 * to be written, free the buffer. There is no point in caching
1167 		 * invalid buffer.
1168 		 */
1169 		if ((b->read_error || b->write_error) &&
1170 		    !test_bit(B_READING, &b->state) &&
1171 		    !test_bit(B_WRITING, &b->state) &&
1172 		    !test_bit(B_DIRTY, &b->state)) {
1173 			__unlink_buffer(b);
1174 			__free_buffer_wake(b);
1175 		}
1176 	}
1177 
1178 	dm_bufio_unlock(c);
1179 }
1180 EXPORT_SYMBOL_GPL(dm_bufio_release);
1181 
dm_bufio_mark_buffer_dirty(struct dm_buffer * b)1182 void dm_bufio_mark_buffer_dirty(struct dm_buffer *b)
1183 {
1184 	struct dm_bufio_client *c = b->c;
1185 
1186 	dm_bufio_lock(c);
1187 
1188 	BUG_ON(test_bit(B_READING, &b->state));
1189 
1190 	if (!test_and_set_bit(B_DIRTY, &b->state))
1191 		__relink_lru(b, LIST_DIRTY);
1192 
1193 	dm_bufio_unlock(c);
1194 }
1195 EXPORT_SYMBOL_GPL(dm_bufio_mark_buffer_dirty);
1196 
dm_bufio_write_dirty_buffers_async(struct dm_bufio_client * c)1197 void dm_bufio_write_dirty_buffers_async(struct dm_bufio_client *c)
1198 {
1199 	LIST_HEAD(write_list);
1200 
1201 	BUG_ON(dm_bufio_in_request());
1202 
1203 	dm_bufio_lock(c);
1204 	__write_dirty_buffers_async(c, 0, &write_list);
1205 	dm_bufio_unlock(c);
1206 	__flush_write_list(&write_list);
1207 }
1208 EXPORT_SYMBOL_GPL(dm_bufio_write_dirty_buffers_async);
1209 
1210 /*
1211  * For performance, it is essential that the buffers are written asynchronously
1212  * and simultaneously (so that the block layer can merge the writes) and then
1213  * waited upon.
1214  *
1215  * Finally, we flush hardware disk cache.
1216  */
dm_bufio_write_dirty_buffers(struct dm_bufio_client * c)1217 int dm_bufio_write_dirty_buffers(struct dm_bufio_client *c)
1218 {
1219 	int a, f;
1220 	unsigned long buffers_processed = 0;
1221 	struct dm_buffer *b, *tmp;
1222 
1223 	LIST_HEAD(write_list);
1224 
1225 	dm_bufio_lock(c);
1226 	__write_dirty_buffers_async(c, 0, &write_list);
1227 	dm_bufio_unlock(c);
1228 	__flush_write_list(&write_list);
1229 	dm_bufio_lock(c);
1230 
1231 again:
1232 	list_for_each_entry_safe_reverse(b, tmp, &c->lru[LIST_DIRTY], lru_list) {
1233 		int dropped_lock = 0;
1234 
1235 		if (buffers_processed < c->n_buffers[LIST_DIRTY])
1236 			buffers_processed++;
1237 
1238 		BUG_ON(test_bit(B_READING, &b->state));
1239 
1240 		if (test_bit(B_WRITING, &b->state)) {
1241 			if (buffers_processed < c->n_buffers[LIST_DIRTY]) {
1242 				dropped_lock = 1;
1243 				b->hold_count++;
1244 				dm_bufio_unlock(c);
1245 				wait_on_bit_io(&b->state, B_WRITING,
1246 					       TASK_UNINTERRUPTIBLE);
1247 				dm_bufio_lock(c);
1248 				b->hold_count--;
1249 			} else
1250 				wait_on_bit_io(&b->state, B_WRITING,
1251 					       TASK_UNINTERRUPTIBLE);
1252 		}
1253 
1254 		if (!test_bit(B_DIRTY, &b->state) &&
1255 		    !test_bit(B_WRITING, &b->state))
1256 			__relink_lru(b, LIST_CLEAN);
1257 
1258 		dm_bufio_cond_resched();
1259 
1260 		/*
1261 		 * If we dropped the lock, the list is no longer consistent,
1262 		 * so we must restart the search.
1263 		 *
1264 		 * In the most common case, the buffer just processed is
1265 		 * relinked to the clean list, so we won't loop scanning the
1266 		 * same buffer again and again.
1267 		 *
1268 		 * This may livelock if there is another thread simultaneously
1269 		 * dirtying buffers, so we count the number of buffers walked
1270 		 * and if it exceeds the total number of buffers, it means that
1271 		 * someone is doing some writes simultaneously with us.  In
1272 		 * this case, stop, dropping the lock.
1273 		 */
1274 		if (dropped_lock)
1275 			goto again;
1276 	}
1277 	wake_up(&c->free_buffer_wait);
1278 	dm_bufio_unlock(c);
1279 
1280 	a = xchg(&c->async_write_error, 0);
1281 	f = dm_bufio_issue_flush(c);
1282 	if (a)
1283 		return a;
1284 
1285 	return f;
1286 }
1287 EXPORT_SYMBOL_GPL(dm_bufio_write_dirty_buffers);
1288 
1289 /*
1290  * Use dm-io to send and empty barrier flush the device.
1291  */
dm_bufio_issue_flush(struct dm_bufio_client * c)1292 int dm_bufio_issue_flush(struct dm_bufio_client *c)
1293 {
1294 	struct dm_io_request io_req = {
1295 		.bi_rw = WRITE_FLUSH,
1296 		.mem.type = DM_IO_KMEM,
1297 		.mem.ptr.addr = NULL,
1298 		.client = c->dm_io,
1299 	};
1300 	struct dm_io_region io_reg = {
1301 		.bdev = c->bdev,
1302 		.sector = 0,
1303 		.count = 0,
1304 	};
1305 
1306 	BUG_ON(dm_bufio_in_request());
1307 
1308 	return dm_io(&io_req, 1, &io_reg, NULL);
1309 }
1310 EXPORT_SYMBOL_GPL(dm_bufio_issue_flush);
1311 
1312 /*
1313  * We first delete any other buffer that may be at that new location.
1314  *
1315  * Then, we write the buffer to the original location if it was dirty.
1316  *
1317  * Then, if we are the only one who is holding the buffer, relink the buffer
1318  * in the hash queue for the new location.
1319  *
1320  * If there was someone else holding the buffer, we write it to the new
1321  * location but not relink it, because that other user needs to have the buffer
1322  * at the same place.
1323  */
dm_bufio_release_move(struct dm_buffer * b,sector_t new_block)1324 void dm_bufio_release_move(struct dm_buffer *b, sector_t new_block)
1325 {
1326 	struct dm_bufio_client *c = b->c;
1327 	struct dm_buffer *new;
1328 
1329 	BUG_ON(dm_bufio_in_request());
1330 
1331 	dm_bufio_lock(c);
1332 
1333 retry:
1334 	new = __find(c, new_block);
1335 	if (new) {
1336 		if (new->hold_count) {
1337 			__wait_for_free_buffer(c);
1338 			goto retry;
1339 		}
1340 
1341 		/*
1342 		 * FIXME: Is there any point waiting for a write that's going
1343 		 * to be overwritten in a bit?
1344 		 */
1345 		__make_buffer_clean(new);
1346 		__unlink_buffer(new);
1347 		__free_buffer_wake(new);
1348 	}
1349 
1350 	BUG_ON(!b->hold_count);
1351 	BUG_ON(test_bit(B_READING, &b->state));
1352 
1353 	__write_dirty_buffer(b, NULL);
1354 	if (b->hold_count == 1) {
1355 		wait_on_bit_io(&b->state, B_WRITING,
1356 			       TASK_UNINTERRUPTIBLE);
1357 		set_bit(B_DIRTY, &b->state);
1358 		__unlink_buffer(b);
1359 		__link_buffer(b, new_block, LIST_DIRTY);
1360 	} else {
1361 		sector_t old_block;
1362 		wait_on_bit_lock_io(&b->state, B_WRITING,
1363 				    TASK_UNINTERRUPTIBLE);
1364 		/*
1365 		 * Relink buffer to "new_block" so that write_callback
1366 		 * sees "new_block" as a block number.
1367 		 * After the write, link the buffer back to old_block.
1368 		 * All this must be done in bufio lock, so that block number
1369 		 * change isn't visible to other threads.
1370 		 */
1371 		old_block = b->block;
1372 		__unlink_buffer(b);
1373 		__link_buffer(b, new_block, b->list_mode);
1374 		submit_io(b, WRITE, new_block, write_endio);
1375 		wait_on_bit_io(&b->state, B_WRITING,
1376 			       TASK_UNINTERRUPTIBLE);
1377 		__unlink_buffer(b);
1378 		__link_buffer(b, old_block, b->list_mode);
1379 	}
1380 
1381 	dm_bufio_unlock(c);
1382 	dm_bufio_release(b);
1383 }
1384 EXPORT_SYMBOL_GPL(dm_bufio_release_move);
1385 
1386 /*
1387  * Free the given buffer.
1388  *
1389  * This is just a hint, if the buffer is in use or dirty, this function
1390  * does nothing.
1391  */
dm_bufio_forget(struct dm_bufio_client * c,sector_t block)1392 void dm_bufio_forget(struct dm_bufio_client *c, sector_t block)
1393 {
1394 	struct dm_buffer *b;
1395 
1396 	dm_bufio_lock(c);
1397 
1398 	b = __find(c, block);
1399 	if (b && likely(!b->hold_count) && likely(!b->state)) {
1400 		__unlink_buffer(b);
1401 		__free_buffer_wake(b);
1402 	}
1403 
1404 	dm_bufio_unlock(c);
1405 }
1406 EXPORT_SYMBOL(dm_bufio_forget);
1407 
dm_bufio_set_minimum_buffers(struct dm_bufio_client * c,unsigned n)1408 void dm_bufio_set_minimum_buffers(struct dm_bufio_client *c, unsigned n)
1409 {
1410 	c->minimum_buffers = n;
1411 }
1412 EXPORT_SYMBOL(dm_bufio_set_minimum_buffers);
1413 
dm_bufio_get_block_size(struct dm_bufio_client * c)1414 unsigned dm_bufio_get_block_size(struct dm_bufio_client *c)
1415 {
1416 	return c->block_size;
1417 }
1418 EXPORT_SYMBOL_GPL(dm_bufio_get_block_size);
1419 
dm_bufio_get_device_size(struct dm_bufio_client * c)1420 sector_t dm_bufio_get_device_size(struct dm_bufio_client *c)
1421 {
1422 	return i_size_read(c->bdev->bd_inode) >>
1423 			   (SECTOR_SHIFT + c->sectors_per_block_bits);
1424 }
1425 EXPORT_SYMBOL_GPL(dm_bufio_get_device_size);
1426 
dm_bufio_get_block_number(struct dm_buffer * b)1427 sector_t dm_bufio_get_block_number(struct dm_buffer *b)
1428 {
1429 	return b->block;
1430 }
1431 EXPORT_SYMBOL_GPL(dm_bufio_get_block_number);
1432 
dm_bufio_get_block_data(struct dm_buffer * b)1433 void *dm_bufio_get_block_data(struct dm_buffer *b)
1434 {
1435 	return b->data;
1436 }
1437 EXPORT_SYMBOL_GPL(dm_bufio_get_block_data);
1438 
dm_bufio_get_aux_data(struct dm_buffer * b)1439 void *dm_bufio_get_aux_data(struct dm_buffer *b)
1440 {
1441 	return b + 1;
1442 }
1443 EXPORT_SYMBOL_GPL(dm_bufio_get_aux_data);
1444 
dm_bufio_get_client(struct dm_buffer * b)1445 struct dm_bufio_client *dm_bufio_get_client(struct dm_buffer *b)
1446 {
1447 	return b->c;
1448 }
1449 EXPORT_SYMBOL_GPL(dm_bufio_get_client);
1450 
drop_buffers(struct dm_bufio_client * c)1451 static void drop_buffers(struct dm_bufio_client *c)
1452 {
1453 	struct dm_buffer *b;
1454 	int i;
1455 
1456 	BUG_ON(dm_bufio_in_request());
1457 
1458 	/*
1459 	 * An optimization so that the buffers are not written one-by-one.
1460 	 */
1461 	dm_bufio_write_dirty_buffers_async(c);
1462 
1463 	dm_bufio_lock(c);
1464 
1465 	while ((b = __get_unclaimed_buffer(c)))
1466 		__free_buffer_wake(b);
1467 
1468 	for (i = 0; i < LIST_SIZE; i++)
1469 		list_for_each_entry(b, &c->lru[i], lru_list)
1470 			DMERR("leaked buffer %llx, hold count %u, list %d",
1471 			      (unsigned long long)b->block, b->hold_count, i);
1472 
1473 	for (i = 0; i < LIST_SIZE; i++)
1474 		BUG_ON(!list_empty(&c->lru[i]));
1475 
1476 	dm_bufio_unlock(c);
1477 }
1478 
1479 /*
1480  * Test if the buffer is unused and too old, and commit it.
1481  * And if GFP_NOFS is used, we must not do any I/O because we hold
1482  * dm_bufio_clients_lock and we would risk deadlock if the I/O gets
1483  * rerouted to different bufio client.
1484  */
__cleanup_old_buffer(struct dm_buffer * b,gfp_t gfp,unsigned long max_jiffies)1485 static int __cleanup_old_buffer(struct dm_buffer *b, gfp_t gfp,
1486 				unsigned long max_jiffies)
1487 {
1488 	if (jiffies - b->last_accessed < max_jiffies)
1489 		return 0;
1490 
1491 	if (!(gfp & __GFP_FS)) {
1492 		if (test_bit(B_READING, &b->state) ||
1493 		    test_bit(B_WRITING, &b->state) ||
1494 		    test_bit(B_DIRTY, &b->state))
1495 			return 0;
1496 	}
1497 
1498 	if (b->hold_count)
1499 		return 0;
1500 
1501 	__make_buffer_clean(b);
1502 	__unlink_buffer(b);
1503 	__free_buffer_wake(b);
1504 
1505 	return 1;
1506 }
1507 
__scan(struct dm_bufio_client * c,unsigned long nr_to_scan,gfp_t gfp_mask)1508 static long __scan(struct dm_bufio_client *c, unsigned long nr_to_scan,
1509 		   gfp_t gfp_mask)
1510 {
1511 	int l;
1512 	struct dm_buffer *b, *tmp;
1513 	long freed = 0;
1514 
1515 	for (l = 0; l < LIST_SIZE; l++) {
1516 		list_for_each_entry_safe_reverse(b, tmp, &c->lru[l], lru_list) {
1517 			freed += __cleanup_old_buffer(b, gfp_mask, 0);
1518 			if (!--nr_to_scan)
1519 				return freed;
1520 			dm_bufio_cond_resched();
1521 		}
1522 	}
1523 	return freed;
1524 }
1525 
1526 static unsigned long
dm_bufio_shrink_scan(struct shrinker * shrink,struct shrink_control * sc)1527 dm_bufio_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
1528 {
1529 	struct dm_bufio_client *c;
1530 	unsigned long freed;
1531 
1532 	c = container_of(shrink, struct dm_bufio_client, shrinker);
1533 	if (sc->gfp_mask & __GFP_FS)
1534 		dm_bufio_lock(c);
1535 	else if (!dm_bufio_trylock(c))
1536 		return SHRINK_STOP;
1537 
1538 	freed  = __scan(c, sc->nr_to_scan, sc->gfp_mask);
1539 	dm_bufio_unlock(c);
1540 	return freed;
1541 }
1542 
1543 static unsigned long
dm_bufio_shrink_count(struct shrinker * shrink,struct shrink_control * sc)1544 dm_bufio_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
1545 {
1546 	struct dm_bufio_client *c;
1547 	unsigned long count;
1548 
1549 	c = container_of(shrink, struct dm_bufio_client, shrinker);
1550 	if (sc->gfp_mask & __GFP_FS)
1551 		dm_bufio_lock(c);
1552 	else if (!dm_bufio_trylock(c))
1553 		return 0;
1554 
1555 	count = c->n_buffers[LIST_CLEAN] + c->n_buffers[LIST_DIRTY];
1556 	dm_bufio_unlock(c);
1557 	return count;
1558 }
1559 
1560 /*
1561  * Create the buffering interface
1562  */
dm_bufio_client_create(struct block_device * bdev,unsigned block_size,unsigned reserved_buffers,unsigned aux_size,void (* alloc_callback)(struct dm_buffer *),void (* write_callback)(struct dm_buffer *))1563 struct dm_bufio_client *dm_bufio_client_create(struct block_device *bdev, unsigned block_size,
1564 					       unsigned reserved_buffers, unsigned aux_size,
1565 					       void (*alloc_callback)(struct dm_buffer *),
1566 					       void (*write_callback)(struct dm_buffer *))
1567 {
1568 	int r;
1569 	struct dm_bufio_client *c;
1570 	unsigned i;
1571 
1572 	BUG_ON(block_size < 1 << SECTOR_SHIFT ||
1573 	       (block_size & (block_size - 1)));
1574 
1575 	c = kzalloc(sizeof(*c), GFP_KERNEL);
1576 	if (!c) {
1577 		r = -ENOMEM;
1578 		goto bad_client;
1579 	}
1580 	c->buffer_tree = RB_ROOT;
1581 
1582 	c->bdev = bdev;
1583 	c->block_size = block_size;
1584 	c->sectors_per_block_bits = ffs(block_size) - 1 - SECTOR_SHIFT;
1585 	c->pages_per_block_bits = (ffs(block_size) - 1 >= PAGE_SHIFT) ?
1586 				  ffs(block_size) - 1 - PAGE_SHIFT : 0;
1587 	c->blocks_per_page_bits = (ffs(block_size) - 1 < PAGE_SHIFT ?
1588 				  PAGE_SHIFT - (ffs(block_size) - 1) : 0);
1589 
1590 	c->aux_size = aux_size;
1591 	c->alloc_callback = alloc_callback;
1592 	c->write_callback = write_callback;
1593 
1594 	for (i = 0; i < LIST_SIZE; i++) {
1595 		INIT_LIST_HEAD(&c->lru[i]);
1596 		c->n_buffers[i] = 0;
1597 	}
1598 
1599 	mutex_init(&c->lock);
1600 	INIT_LIST_HEAD(&c->reserved_buffers);
1601 	c->need_reserved_buffers = reserved_buffers;
1602 
1603 	c->minimum_buffers = DM_BUFIO_MIN_BUFFERS;
1604 
1605 	init_waitqueue_head(&c->free_buffer_wait);
1606 	c->async_write_error = 0;
1607 
1608 	c->dm_io = dm_io_client_create();
1609 	if (IS_ERR(c->dm_io)) {
1610 		r = PTR_ERR(c->dm_io);
1611 		goto bad_dm_io;
1612 	}
1613 
1614 	mutex_lock(&dm_bufio_clients_lock);
1615 	if (c->blocks_per_page_bits) {
1616 		if (!DM_BUFIO_CACHE_NAME(c)) {
1617 			DM_BUFIO_CACHE_NAME(c) = kasprintf(GFP_KERNEL, "dm_bufio_cache-%u", c->block_size);
1618 			if (!DM_BUFIO_CACHE_NAME(c)) {
1619 				r = -ENOMEM;
1620 				mutex_unlock(&dm_bufio_clients_lock);
1621 				goto bad_cache;
1622 			}
1623 		}
1624 
1625 		if (!DM_BUFIO_CACHE(c)) {
1626 			DM_BUFIO_CACHE(c) = kmem_cache_create(DM_BUFIO_CACHE_NAME(c),
1627 							      c->block_size,
1628 							      c->block_size, 0, NULL);
1629 			if (!DM_BUFIO_CACHE(c)) {
1630 				r = -ENOMEM;
1631 				mutex_unlock(&dm_bufio_clients_lock);
1632 				goto bad_cache;
1633 			}
1634 		}
1635 	}
1636 	mutex_unlock(&dm_bufio_clients_lock);
1637 
1638 	while (c->need_reserved_buffers) {
1639 		struct dm_buffer *b = alloc_buffer(c, GFP_KERNEL);
1640 
1641 		if (!b) {
1642 			r = -ENOMEM;
1643 			goto bad_buffer;
1644 		}
1645 		__free_buffer_wake(b);
1646 	}
1647 
1648 	mutex_lock(&dm_bufio_clients_lock);
1649 	dm_bufio_client_count++;
1650 	list_add(&c->client_list, &dm_bufio_all_clients);
1651 	__cache_size_refresh();
1652 	mutex_unlock(&dm_bufio_clients_lock);
1653 
1654 	c->shrinker.count_objects = dm_bufio_shrink_count;
1655 	c->shrinker.scan_objects = dm_bufio_shrink_scan;
1656 	c->shrinker.seeks = 1;
1657 	c->shrinker.batch = 0;
1658 	register_shrinker(&c->shrinker);
1659 
1660 	return c;
1661 
1662 bad_buffer:
1663 bad_cache:
1664 	while (!list_empty(&c->reserved_buffers)) {
1665 		struct dm_buffer *b = list_entry(c->reserved_buffers.next,
1666 						 struct dm_buffer, lru_list);
1667 		list_del(&b->lru_list);
1668 		free_buffer(b);
1669 	}
1670 	dm_io_client_destroy(c->dm_io);
1671 bad_dm_io:
1672 	kfree(c);
1673 bad_client:
1674 	return ERR_PTR(r);
1675 }
1676 EXPORT_SYMBOL_GPL(dm_bufio_client_create);
1677 
1678 /*
1679  * Free the buffering interface.
1680  * It is required that there are no references on any buffers.
1681  */
dm_bufio_client_destroy(struct dm_bufio_client * c)1682 void dm_bufio_client_destroy(struct dm_bufio_client *c)
1683 {
1684 	unsigned i;
1685 
1686 	drop_buffers(c);
1687 
1688 	unregister_shrinker(&c->shrinker);
1689 
1690 	mutex_lock(&dm_bufio_clients_lock);
1691 
1692 	list_del(&c->client_list);
1693 	dm_bufio_client_count--;
1694 	__cache_size_refresh();
1695 
1696 	mutex_unlock(&dm_bufio_clients_lock);
1697 
1698 	BUG_ON(!RB_EMPTY_ROOT(&c->buffer_tree));
1699 	BUG_ON(c->need_reserved_buffers);
1700 
1701 	while (!list_empty(&c->reserved_buffers)) {
1702 		struct dm_buffer *b = list_entry(c->reserved_buffers.next,
1703 						 struct dm_buffer, lru_list);
1704 		list_del(&b->lru_list);
1705 		free_buffer(b);
1706 	}
1707 
1708 	for (i = 0; i < LIST_SIZE; i++)
1709 		if (c->n_buffers[i])
1710 			DMERR("leaked buffer count %d: %ld", i, c->n_buffers[i]);
1711 
1712 	for (i = 0; i < LIST_SIZE; i++)
1713 		BUG_ON(c->n_buffers[i]);
1714 
1715 	dm_io_client_destroy(c->dm_io);
1716 	kfree(c);
1717 }
1718 EXPORT_SYMBOL_GPL(dm_bufio_client_destroy);
1719 
cleanup_old_buffers(void)1720 static void cleanup_old_buffers(void)
1721 {
1722 	unsigned long max_age = ACCESS_ONCE(dm_bufio_max_age);
1723 	struct dm_bufio_client *c;
1724 
1725 	if (max_age > ULONG_MAX / HZ)
1726 		max_age = ULONG_MAX / HZ;
1727 
1728 	mutex_lock(&dm_bufio_clients_lock);
1729 	list_for_each_entry(c, &dm_bufio_all_clients, client_list) {
1730 		if (!dm_bufio_trylock(c))
1731 			continue;
1732 
1733 		while (!list_empty(&c->lru[LIST_CLEAN])) {
1734 			struct dm_buffer *b;
1735 			b = list_entry(c->lru[LIST_CLEAN].prev,
1736 				       struct dm_buffer, lru_list);
1737 			if (!__cleanup_old_buffer(b, 0, max_age * HZ))
1738 				break;
1739 			dm_bufio_cond_resched();
1740 		}
1741 
1742 		dm_bufio_unlock(c);
1743 		dm_bufio_cond_resched();
1744 	}
1745 	mutex_unlock(&dm_bufio_clients_lock);
1746 }
1747 
1748 static struct workqueue_struct *dm_bufio_wq;
1749 static struct delayed_work dm_bufio_work;
1750 
work_fn(struct work_struct * w)1751 static void work_fn(struct work_struct *w)
1752 {
1753 	cleanup_old_buffers();
1754 
1755 	queue_delayed_work(dm_bufio_wq, &dm_bufio_work,
1756 			   DM_BUFIO_WORK_TIMER_SECS * HZ);
1757 }
1758 
1759 /*----------------------------------------------------------------
1760  * Module setup
1761  *--------------------------------------------------------------*/
1762 
1763 /*
1764  * This is called only once for the whole dm_bufio module.
1765  * It initializes memory limit.
1766  */
dm_bufio_init(void)1767 static int __init dm_bufio_init(void)
1768 {
1769 	__u64 mem;
1770 
1771 	dm_bufio_allocated_kmem_cache = 0;
1772 	dm_bufio_allocated_get_free_pages = 0;
1773 	dm_bufio_allocated_vmalloc = 0;
1774 	dm_bufio_current_allocated = 0;
1775 
1776 	memset(&dm_bufio_caches, 0, sizeof dm_bufio_caches);
1777 	memset(&dm_bufio_cache_names, 0, sizeof dm_bufio_cache_names);
1778 
1779 	mem = (__u64)mult_frac(totalram_pages - totalhigh_pages,
1780 			       DM_BUFIO_MEMORY_PERCENT, 100) << PAGE_SHIFT;
1781 
1782 	if (mem > ULONG_MAX)
1783 		mem = ULONG_MAX;
1784 
1785 #ifdef CONFIG_MMU
1786 	if (mem > mult_frac(VMALLOC_TOTAL, DM_BUFIO_VMALLOC_PERCENT, 100))
1787 		mem = mult_frac(VMALLOC_TOTAL, DM_BUFIO_VMALLOC_PERCENT, 100);
1788 #endif
1789 
1790 	dm_bufio_default_cache_size = mem;
1791 
1792 	mutex_lock(&dm_bufio_clients_lock);
1793 	__cache_size_refresh();
1794 	mutex_unlock(&dm_bufio_clients_lock);
1795 
1796 	dm_bufio_wq = create_singlethread_workqueue("dm_bufio_cache");
1797 	if (!dm_bufio_wq)
1798 		return -ENOMEM;
1799 
1800 	INIT_DELAYED_WORK(&dm_bufio_work, work_fn);
1801 	queue_delayed_work(dm_bufio_wq, &dm_bufio_work,
1802 			   DM_BUFIO_WORK_TIMER_SECS * HZ);
1803 
1804 	return 0;
1805 }
1806 
1807 /*
1808  * This is called once when unloading the dm_bufio module.
1809  */
dm_bufio_exit(void)1810 static void __exit dm_bufio_exit(void)
1811 {
1812 	int bug = 0;
1813 	int i;
1814 
1815 	cancel_delayed_work_sync(&dm_bufio_work);
1816 	destroy_workqueue(dm_bufio_wq);
1817 
1818 	for (i = 0; i < ARRAY_SIZE(dm_bufio_caches); i++) {
1819 		struct kmem_cache *kc = dm_bufio_caches[i];
1820 
1821 		if (kc)
1822 			kmem_cache_destroy(kc);
1823 	}
1824 
1825 	for (i = 0; i < ARRAY_SIZE(dm_bufio_cache_names); i++)
1826 		kfree(dm_bufio_cache_names[i]);
1827 
1828 	if (dm_bufio_client_count) {
1829 		DMCRIT("%s: dm_bufio_client_count leaked: %d",
1830 			__func__, dm_bufio_client_count);
1831 		bug = 1;
1832 	}
1833 
1834 	if (dm_bufio_current_allocated) {
1835 		DMCRIT("%s: dm_bufio_current_allocated leaked: %lu",
1836 			__func__, dm_bufio_current_allocated);
1837 		bug = 1;
1838 	}
1839 
1840 	if (dm_bufio_allocated_get_free_pages) {
1841 		DMCRIT("%s: dm_bufio_allocated_get_free_pages leaked: %lu",
1842 		       __func__, dm_bufio_allocated_get_free_pages);
1843 		bug = 1;
1844 	}
1845 
1846 	if (dm_bufio_allocated_vmalloc) {
1847 		DMCRIT("%s: dm_bufio_vmalloc leaked: %lu",
1848 		       __func__, dm_bufio_allocated_vmalloc);
1849 		bug = 1;
1850 	}
1851 
1852 	if (bug)
1853 		BUG();
1854 }
1855 
1856 module_init(dm_bufio_init)
1857 module_exit(dm_bufio_exit)
1858 
1859 module_param_named(max_cache_size_bytes, dm_bufio_cache_size, ulong, S_IRUGO | S_IWUSR);
1860 MODULE_PARM_DESC(max_cache_size_bytes, "Size of metadata cache");
1861 
1862 module_param_named(max_age_seconds, dm_bufio_max_age, uint, S_IRUGO | S_IWUSR);
1863 MODULE_PARM_DESC(max_age_seconds, "Max age of a buffer in seconds");
1864 
1865 module_param_named(peak_allocated_bytes, dm_bufio_peak_allocated, ulong, S_IRUGO | S_IWUSR);
1866 MODULE_PARM_DESC(peak_allocated_bytes, "Tracks the maximum allocated memory");
1867 
1868 module_param_named(allocated_kmem_cache_bytes, dm_bufio_allocated_kmem_cache, ulong, S_IRUGO);
1869 MODULE_PARM_DESC(allocated_kmem_cache_bytes, "Memory allocated with kmem_cache_alloc");
1870 
1871 module_param_named(allocated_get_free_pages_bytes, dm_bufio_allocated_get_free_pages, ulong, S_IRUGO);
1872 MODULE_PARM_DESC(allocated_get_free_pages_bytes, "Memory allocated with get_free_pages");
1873 
1874 module_param_named(allocated_vmalloc_bytes, dm_bufio_allocated_vmalloc, ulong, S_IRUGO);
1875 MODULE_PARM_DESC(allocated_vmalloc_bytes, "Memory allocated with vmalloc");
1876 
1877 module_param_named(current_allocated_bytes, dm_bufio_current_allocated, ulong, S_IRUGO);
1878 MODULE_PARM_DESC(current_allocated_bytes, "Memory currently used by the cache");
1879 
1880 MODULE_AUTHOR("Mikulas Patocka <dm-devel@redhat.com>");
1881 MODULE_DESCRIPTION(DM_NAME " buffered I/O library");
1882 MODULE_LICENSE("GPL");
1883