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