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