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