2 * Copyright (C) 2009-2011 Red Hat, Inc.
4 * Author: Mikulas Patocka <mpatocka@redhat.com>
6 * This file is released under the GPL.
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/version.h>
16 #include <linux/shrinker.h>
17 #include <linux/module.h>
19 #define DM_MSG_PREFIX "bufio"
22 * Memory management policy:
23 * Limit the number of buffers to DM_BUFIO_MEMORY_PERCENT of main memory
24 * or DM_BUFIO_VMALLOC_PERCENT of vmalloc memory (whichever is lower).
25 * Always allocate at least DM_BUFIO_MIN_BUFFERS buffers.
26 * Start background writeback when there are DM_BUFIO_WRITEBACK_PERCENT
29 #define DM_BUFIO_MIN_BUFFERS 8
31 #define DM_BUFIO_MEMORY_PERCENT 2
32 #define DM_BUFIO_VMALLOC_PERCENT 25
33 #define DM_BUFIO_WRITEBACK_PERCENT 75
36 * Check buffer ages in this interval (seconds)
38 #define DM_BUFIO_WORK_TIMER_SECS 10
41 * Free buffers when they are older than this (seconds)
43 #define DM_BUFIO_DEFAULT_AGE_SECS 60
46 * The number of bvec entries that are embedded directly in the buffer.
47 * If the chunk size is larger, dm-io is used to do the io.
49 #define DM_BUFIO_INLINE_VECS 16
54 #define DM_BUFIO_HASH_BITS 20
55 #define DM_BUFIO_HASH(block) \
56 ((((block) >> DM_BUFIO_HASH_BITS) ^ (block)) & \
57 ((1 << DM_BUFIO_HASH_BITS) - 1))
60 * Don't try to use kmem_cache_alloc for blocks larger than this.
61 * For explanation, see alloc_buffer_data below.
63 #define DM_BUFIO_BLOCK_SIZE_SLAB_LIMIT (PAGE_SIZE >> 1)
64 #define DM_BUFIO_BLOCK_SIZE_GFP_LIMIT (PAGE_SIZE << (MAX_ORDER - 1))
67 * dm_buffer->list_mode
75 * All buffers are linked to cache_hash with their hash_list field.
77 * Clean buffers that are not being written (B_WRITING not set)
78 * are linked to lru[LIST_CLEAN] with their lru_list field.
80 * Dirty and clean buffers that are being written are linked to
81 * lru[LIST_DIRTY] with their lru_list field. When the write
82 * finishes, the buffer cannot be relinked immediately (because we
83 * are in an interrupt context and relinking requires process
84 * context), so some clean-not-writing buffers can be held on
85 * dirty_lru too. They are later added to lru in the process
88 struct dm_bufio_client {
91 struct list_head lru[LIST_SIZE];
92 unsigned long n_buffers[LIST_SIZE];
94 struct block_device *bdev;
96 unsigned char sectors_per_block_bits;
97 unsigned char pages_per_block_bits;
98 unsigned char blocks_per_page_bits;
100 void (*alloc_callback)(struct dm_buffer *);
101 void (*write_callback)(struct dm_buffer *);
103 struct dm_io_client *dm_io;
105 struct list_head reserved_buffers;
106 unsigned need_reserved_buffers;
108 struct hlist_head *cache_hash;
109 wait_queue_head_t free_buffer_wait;
111 int async_write_error;
113 struct list_head client_list;
114 struct shrinker shrinker;
125 * Describes how the block was allocated:
126 * kmem_cache_alloc(), __get_free_pages() or vmalloc().
127 * See the comment at alloc_buffer_data.
131 DATA_MODE_GET_FREE_PAGES = 1,
132 DATA_MODE_VMALLOC = 2,
137 struct hlist_node hash_list;
138 struct list_head lru_list;
141 enum data_mode data_mode;
142 unsigned char list_mode; /* LIST_* */
147 unsigned long last_accessed;
148 struct dm_bufio_client *c;
150 struct bio_vec bio_vec[DM_BUFIO_INLINE_VECS];
153 /*----------------------------------------------------------------*/
155 static struct kmem_cache *dm_bufio_caches[PAGE_SHIFT - SECTOR_SHIFT];
156 static char *dm_bufio_cache_names[PAGE_SHIFT - SECTOR_SHIFT];
158 static inline int dm_bufio_cache_index(struct dm_bufio_client *c)
160 unsigned ret = c->blocks_per_page_bits - 1;
162 BUG_ON(ret >= ARRAY_SIZE(dm_bufio_caches));
167 #define DM_BUFIO_CACHE(c) (dm_bufio_caches[dm_bufio_cache_index(c)])
168 #define DM_BUFIO_CACHE_NAME(c) (dm_bufio_cache_names[dm_bufio_cache_index(c)])
170 #define dm_bufio_in_request() (!!current->bio_list)
172 static void dm_bufio_lock(struct dm_bufio_client *c)
174 mutex_lock_nested(&c->lock, dm_bufio_in_request());
177 static int dm_bufio_trylock(struct dm_bufio_client *c)
179 return mutex_trylock(&c->lock);
182 static void dm_bufio_unlock(struct dm_bufio_client *c)
184 mutex_unlock(&c->lock);
188 * FIXME Move to sched.h?
190 #ifdef CONFIG_PREEMPT_VOLUNTARY
191 # define dm_bufio_cond_resched() \
193 if (unlikely(need_resched())) \
197 # define dm_bufio_cond_resched() do { } while (0)
200 /*----------------------------------------------------------------*/
203 * Default cache size: available memory divided by the ratio.
205 static unsigned long dm_bufio_default_cache_size;
208 * Total cache size set by the user.
210 static unsigned long dm_bufio_cache_size;
213 * A copy of dm_bufio_cache_size because dm_bufio_cache_size can change
214 * at any time. If it disagrees, the user has changed cache size.
216 static unsigned long dm_bufio_cache_size_latch;
218 static DEFINE_SPINLOCK(param_spinlock);
221 * Buffers are freed after this timeout
223 static unsigned dm_bufio_max_age = DM_BUFIO_DEFAULT_AGE_SECS;
225 static unsigned long dm_bufio_peak_allocated;
226 static unsigned long dm_bufio_allocated_kmem_cache;
227 static unsigned long dm_bufio_allocated_get_free_pages;
228 static unsigned long dm_bufio_allocated_vmalloc;
229 static unsigned long dm_bufio_current_allocated;
231 /*----------------------------------------------------------------*/
234 * Per-client cache: dm_bufio_cache_size / dm_bufio_client_count
236 static unsigned long dm_bufio_cache_size_per_client;
239 * The current number of clients.
241 static int dm_bufio_client_count;
244 * The list of all clients.
246 static LIST_HEAD(dm_bufio_all_clients);
249 * This mutex protects dm_bufio_cache_size_latch,
250 * dm_bufio_cache_size_per_client and dm_bufio_client_count
252 static DEFINE_MUTEX(dm_bufio_clients_lock);
254 /*----------------------------------------------------------------*/
256 static void adjust_total_allocated(enum data_mode data_mode, long diff)
258 static unsigned long * const class_ptr[DATA_MODE_LIMIT] = {
259 &dm_bufio_allocated_kmem_cache,
260 &dm_bufio_allocated_get_free_pages,
261 &dm_bufio_allocated_vmalloc,
264 spin_lock(¶m_spinlock);
266 *class_ptr[data_mode] += diff;
268 dm_bufio_current_allocated += diff;
270 if (dm_bufio_current_allocated > dm_bufio_peak_allocated)
271 dm_bufio_peak_allocated = dm_bufio_current_allocated;
273 spin_unlock(¶m_spinlock);
277 * Change the number of clients and recalculate per-client limit.
279 static void __cache_size_refresh(void)
281 BUG_ON(!mutex_is_locked(&dm_bufio_clients_lock));
282 BUG_ON(dm_bufio_client_count < 0);
284 dm_bufio_cache_size_latch = dm_bufio_cache_size;
289 * Use default if set to 0 and report the actual cache size used.
291 if (!dm_bufio_cache_size_latch) {
292 (void)cmpxchg(&dm_bufio_cache_size, 0,
293 dm_bufio_default_cache_size);
294 dm_bufio_cache_size_latch = dm_bufio_default_cache_size;
297 dm_bufio_cache_size_per_client = dm_bufio_cache_size_latch /
298 (dm_bufio_client_count ? : 1);
302 * Allocating buffer data.
304 * Small buffers are allocated with kmem_cache, to use space optimally.
306 * For large buffers, we choose between get_free_pages and vmalloc.
307 * Each has advantages and disadvantages.
309 * __get_free_pages can randomly fail if the memory is fragmented.
310 * __vmalloc won't randomly fail, but vmalloc space is limited (it may be
311 * as low as 128M) so using it for caching is not appropriate.
313 * If the allocation may fail we use __get_free_pages. Memory fragmentation
314 * won't have a fatal effect here, but it just causes flushes of some other
315 * buffers and more I/O will be performed. Don't use __get_free_pages if it
316 * always fails (i.e. order >= MAX_ORDER).
318 * If the allocation shouldn't fail we use __vmalloc. This is only for the
319 * initial reserve allocation, so there's no risk of wasting all vmalloc
322 static void *alloc_buffer_data(struct dm_bufio_client *c, gfp_t gfp_mask,
323 enum data_mode *data_mode)
328 if (c->block_size <= DM_BUFIO_BLOCK_SIZE_SLAB_LIMIT) {
329 *data_mode = DATA_MODE_SLAB;
330 return kmem_cache_alloc(DM_BUFIO_CACHE(c), gfp_mask);
333 if (c->block_size <= DM_BUFIO_BLOCK_SIZE_GFP_LIMIT &&
334 gfp_mask & __GFP_NORETRY) {
335 *data_mode = DATA_MODE_GET_FREE_PAGES;
336 return (void *)__get_free_pages(gfp_mask,
337 c->pages_per_block_bits);
340 *data_mode = DATA_MODE_VMALLOC;
343 * __vmalloc allocates the data pages and auxiliary structures with
344 * gfp_flags that were specified, but pagetables are always allocated
345 * with GFP_KERNEL, no matter what was specified as gfp_mask.
347 * Consequently, we must set per-process flag PF_MEMALLOC_NOIO so that
348 * all allocations done by this process (including pagetables) are done
349 * as if GFP_NOIO was specified.
352 if (gfp_mask & __GFP_NORETRY) {
353 noio_flag = current->flags & PF_MEMALLOC;
354 current->flags |= PF_MEMALLOC;
357 ptr = __vmalloc(c->block_size, gfp_mask, PAGE_KERNEL);
359 if (gfp_mask & __GFP_NORETRY)
360 current->flags = (current->flags & ~PF_MEMALLOC) | noio_flag;
366 * Free buffer's data.
368 static void free_buffer_data(struct dm_bufio_client *c,
369 void *data, enum data_mode data_mode)
373 kmem_cache_free(DM_BUFIO_CACHE(c), data);
376 case DATA_MODE_GET_FREE_PAGES:
377 free_pages((unsigned long)data, c->pages_per_block_bits);
380 case DATA_MODE_VMALLOC:
385 DMCRIT("dm_bufio_free_buffer_data: bad data mode: %d",
392 * Allocate buffer and its data.
394 static struct dm_buffer *alloc_buffer(struct dm_bufio_client *c, gfp_t gfp_mask)
396 struct dm_buffer *b = kmalloc(sizeof(struct dm_buffer) + c->aux_size,
404 b->data = alloc_buffer_data(c, gfp_mask, &b->data_mode);
410 adjust_total_allocated(b->data_mode, (long)c->block_size);
416 * Free buffer and its data.
418 static void free_buffer(struct dm_buffer *b)
420 struct dm_bufio_client *c = b->c;
422 adjust_total_allocated(b->data_mode, -(long)c->block_size);
424 free_buffer_data(c, b->data, b->data_mode);
429 * Link buffer to the hash list and clean or dirty queue.
431 static void __link_buffer(struct dm_buffer *b, sector_t block, int dirty)
433 struct dm_bufio_client *c = b->c;
435 c->n_buffers[dirty]++;
437 b->list_mode = dirty;
438 list_add(&b->lru_list, &c->lru[dirty]);
439 hlist_add_head(&b->hash_list, &c->cache_hash[DM_BUFIO_HASH(block)]);
440 b->last_accessed = jiffies;
444 * Unlink buffer from the hash list and dirty or clean queue.
446 static void __unlink_buffer(struct dm_buffer *b)
448 struct dm_bufio_client *c = b->c;
450 BUG_ON(!c->n_buffers[b->list_mode]);
452 c->n_buffers[b->list_mode]--;
453 hlist_del(&b->hash_list);
454 list_del(&b->lru_list);
458 * Place the buffer to the head of dirty or clean LRU queue.
460 static void __relink_lru(struct dm_buffer *b, int dirty)
462 struct dm_bufio_client *c = b->c;
464 BUG_ON(!c->n_buffers[b->list_mode]);
466 c->n_buffers[b->list_mode]--;
467 c->n_buffers[dirty]++;
468 b->list_mode = dirty;
469 list_del(&b->lru_list);
470 list_add(&b->lru_list, &c->lru[dirty]);
473 /*----------------------------------------------------------------
474 * Submit I/O on the buffer.
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);
480 * the memory must be direct-mapped, not vmalloced;
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.
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.
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
493 *--------------------------------------------------------------*/
496 * dm-io completion routine. It just calls b->bio.bi_end_io, pretending
497 * that the request was handled directly with bio interface.
499 static void dmio_complete(unsigned long error, void *context)
501 struct dm_buffer *b = context;
503 b->bio.bi_end_io(&b->bio, error ? -EIO : 0);
506 static void use_dmio(struct dm_buffer *b, int rw, sector_t block,
507 bio_end_io_t *end_io)
510 struct dm_io_request io_req = {
512 .notify.fn = dmio_complete,
514 .client = b->c->dm_io,
516 struct dm_io_region region = {
518 .sector = block << b->c->sectors_per_block_bits,
519 .count = b->c->block_size >> SECTOR_SHIFT,
522 if (b->data_mode != DATA_MODE_VMALLOC) {
523 io_req.mem.type = DM_IO_KMEM;
524 io_req.mem.ptr.addr = b->data;
526 io_req.mem.type = DM_IO_VMA;
527 io_req.mem.ptr.vma = b->data;
530 b->bio.bi_end_io = end_io;
532 r = dm_io(&io_req, 1, ®ion, NULL);
537 static void use_inline_bio(struct dm_buffer *b, int rw, sector_t block,
538 bio_end_io_t *end_io)
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;
551 * We assume that if len >= PAGE_SIZE ptr is page-aligned.
552 * If len < PAGE_SIZE the buffer doesn't cross page boundary.
555 len = b->c->block_size;
557 if (len >= PAGE_SIZE)
558 BUG_ON((unsigned long)ptr & (PAGE_SIZE - 1));
560 BUG_ON((unsigned long)ptr & (len - 1));
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);
575 submit_bio(rw, &b->bio);
578 static void submit_io(struct dm_buffer *b, int rw, sector_t block,
579 bio_end_io_t *end_io)
581 if (rw == WRITE && b->c->write_callback)
582 b->c->write_callback(b);
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);
588 use_dmio(b, rw, block, end_io);
591 /*----------------------------------------------------------------
592 * Writing dirty buffers
593 *--------------------------------------------------------------*/
596 * The endio routine for write.
598 * Set the error, clear B_WRITING bit and wake anyone who was waiting on
601 static void write_endio(struct bio *bio, int error)
603 struct dm_buffer *b = container_of(bio, struct dm_buffer, bio);
605 b->write_error = error;
607 struct dm_bufio_client *c = b->c;
608 (void)cmpxchg(&c->async_write_error, 0, error);
611 BUG_ON(!test_bit(B_WRITING, &b->state));
613 smp_mb__before_clear_bit();
614 clear_bit(B_WRITING, &b->state);
615 smp_mb__after_clear_bit();
617 wake_up_bit(&b->state, B_WRITING);
621 * This function is called when wait_on_bit is actually waiting.
623 static int do_io_schedule(void *word)
631 * Initiate a write on a dirty buffer, but don't wait for it.
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.
639 static void __write_dirty_buffer(struct dm_buffer *b)
641 if (!test_bit(B_DIRTY, &b->state))
644 clear_bit(B_DIRTY, &b->state);
645 wait_on_bit_lock(&b->state, B_WRITING,
646 do_io_schedule, TASK_UNINTERRUPTIBLE);
648 submit_io(b, WRITE, b->block, write_endio);
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.
656 static void __make_buffer_clean(struct dm_buffer *b)
658 BUG_ON(b->hold_count);
660 if (!b->state) /* fast case */
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);
669 * Find some buffer that is not held by anybody, clean it, unlink it and
672 static struct dm_buffer *__get_unclaimed_buffer(struct dm_bufio_client *c)
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));
680 if (!b->hold_count) {
681 __make_buffer_clean(b);
685 dm_bufio_cond_resched();
688 list_for_each_entry_reverse(b, &c->lru[LIST_DIRTY], lru_list) {
689 BUG_ON(test_bit(B_READING, &b->state));
691 if (!b->hold_count) {
692 __make_buffer_clean(b);
696 dm_bufio_cond_resched();
703 * Wait until some other threads free some buffer or release hold count on
706 * This function is entered with c->lock held, drops it and regains it
709 static void __wait_for_free_buffer(struct dm_bufio_client *c)
711 DECLARE_WAITQUEUE(wait, current);
713 add_wait_queue(&c->free_buffer_wait, &wait);
714 set_task_state(current, TASK_UNINTERRUPTIBLE);
719 set_task_state(current, TASK_RUNNING);
720 remove_wait_queue(&c->free_buffer_wait, &wait);
726 * Allocate a new buffer. If the allocation is not possible, wait until
727 * some other thread frees a buffer.
729 * May drop the lock and regain it.
731 static struct dm_buffer *__alloc_buffer_wait_no_callback(struct dm_bufio_client *c)
736 * dm-bufio is resistant to allocation failures (it just keeps
737 * one buffer reserved in cases all the allocations fail).
738 * So set flags to not try too hard:
739 * GFP_NOIO: don't recurse into the I/O layer
740 * __GFP_NORETRY: don't retry and rather return failure
741 * __GFP_NOMEMALLOC: don't use emergency reserves
742 * __GFP_NOWARN: don't print a warning in case of failure
744 * For debugging, if we set the cache size to 1, no new buffers will
748 if (dm_bufio_cache_size_latch != 1) {
749 b = alloc_buffer(c, GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
754 if (!list_empty(&c->reserved_buffers)) {
755 b = list_entry(c->reserved_buffers.next,
756 struct dm_buffer, lru_list);
757 list_del(&b->lru_list);
758 c->need_reserved_buffers++;
763 b = __get_unclaimed_buffer(c);
767 __wait_for_free_buffer(c);
771 static struct dm_buffer *__alloc_buffer_wait(struct dm_bufio_client *c)
773 struct dm_buffer *b = __alloc_buffer_wait_no_callback(c);
775 if (c->alloc_callback)
776 c->alloc_callback(b);
782 * Free a buffer and wake other threads waiting for free buffers.
784 static void __free_buffer_wake(struct dm_buffer *b)
786 struct dm_bufio_client *c = b->c;
788 if (!c->need_reserved_buffers)
791 list_add(&b->lru_list, &c->reserved_buffers);
792 c->need_reserved_buffers--;
795 wake_up(&c->free_buffer_wait);
798 static void __write_dirty_buffers_async(struct dm_bufio_client *c, int no_wait)
800 struct dm_buffer *b, *tmp;
802 list_for_each_entry_safe_reverse(b, tmp, &c->lru[LIST_DIRTY], lru_list) {
803 BUG_ON(test_bit(B_READING, &b->state));
805 if (!test_bit(B_DIRTY, &b->state) &&
806 !test_bit(B_WRITING, &b->state)) {
807 __relink_lru(b, LIST_CLEAN);
811 if (no_wait && test_bit(B_WRITING, &b->state))
814 __write_dirty_buffer(b);
815 dm_bufio_cond_resched();
820 * Get writeback threshold and buffer limit for a given client.
822 static void __get_memory_limit(struct dm_bufio_client *c,
823 unsigned long *threshold_buffers,
824 unsigned long *limit_buffers)
826 unsigned long buffers;
828 if (dm_bufio_cache_size != dm_bufio_cache_size_latch) {
829 mutex_lock(&dm_bufio_clients_lock);
830 __cache_size_refresh();
831 mutex_unlock(&dm_bufio_clients_lock);
834 buffers = dm_bufio_cache_size_per_client >>
835 (c->sectors_per_block_bits + SECTOR_SHIFT);
837 if (buffers < DM_BUFIO_MIN_BUFFERS)
838 buffers = DM_BUFIO_MIN_BUFFERS;
840 *limit_buffers = buffers;
841 *threshold_buffers = buffers * DM_BUFIO_WRITEBACK_PERCENT / 100;
845 * Check if we're over watermark.
846 * If we are over threshold_buffers, start freeing buffers.
847 * If we're over "limit_buffers", block until we get under the limit.
849 static void __check_watermark(struct dm_bufio_client *c)
851 unsigned long threshold_buffers, limit_buffers;
853 __get_memory_limit(c, &threshold_buffers, &limit_buffers);
855 while (c->n_buffers[LIST_CLEAN] + c->n_buffers[LIST_DIRTY] >
858 struct dm_buffer *b = __get_unclaimed_buffer(c);
863 __free_buffer_wake(b);
864 dm_bufio_cond_resched();
867 if (c->n_buffers[LIST_DIRTY] > threshold_buffers)
868 __write_dirty_buffers_async(c, 1);
872 * Find a buffer in the hash.
874 static struct dm_buffer *__find(struct dm_bufio_client *c, sector_t block)
877 struct hlist_node *hn;
879 hlist_for_each_entry(b, hn, &c->cache_hash[DM_BUFIO_HASH(block)],
881 dm_bufio_cond_resched();
882 if (b->block == block)
889 /*----------------------------------------------------------------
891 *--------------------------------------------------------------*/
899 static struct dm_buffer *__bufio_new(struct dm_bufio_client *c, sector_t block,
900 enum new_flag nf, struct dm_buffer **bp,
903 struct dm_buffer *b, *new_b = NULL;
907 b = __find(c, block);
910 __relink_lru(b, test_bit(B_DIRTY, &b->state) ||
911 test_bit(B_WRITING, &b->state));
918 new_b = __alloc_buffer_wait(c);
921 * We've had a period where the mutex was unlocked, so need to
922 * recheck the hash table.
924 b = __find(c, block);
926 __free_buffer_wake(new_b);
928 __relink_lru(b, test_bit(B_DIRTY, &b->state) ||
929 test_bit(B_WRITING, &b->state));
933 __check_watermark(c);
939 __link_buffer(b, block, LIST_CLEAN);
941 if (nf == NF_FRESH) {
946 b->state = 1 << B_READING;
953 * The endio routine for reading: set the error, clear the bit and wake up
954 * anyone waiting on the buffer.
956 static void read_endio(struct bio *bio, int error)
958 struct dm_buffer *b = container_of(bio, struct dm_buffer, bio);
960 b->read_error = error;
962 BUG_ON(!test_bit(B_READING, &b->state));
964 smp_mb__before_clear_bit();
965 clear_bit(B_READING, &b->state);
966 smp_mb__after_clear_bit();
968 wake_up_bit(&b->state, B_READING);
972 * A common routine for dm_bufio_new and dm_bufio_read. Operation of these
973 * functions is similar except that dm_bufio_new doesn't read the
974 * buffer from the disk (assuming that the caller overwrites all the data
975 * and uses dm_bufio_mark_buffer_dirty to write new data back).
977 static void *new_read(struct dm_bufio_client *c, sector_t block,
978 enum new_flag nf, struct dm_buffer **bp)
984 b = __bufio_new(c, block, nf, bp, &need_submit);
991 submit_io(b, READ, b->block, read_endio);
993 wait_on_bit(&b->state, B_READING, do_io_schedule, TASK_UNINTERRUPTIBLE);
996 int error = b->read_error;
1000 return ERR_PTR(error);
1008 void *dm_bufio_get(struct dm_bufio_client *c, sector_t block,
1009 struct dm_buffer **bp)
1011 return new_read(c, block, NF_GET, bp);
1013 EXPORT_SYMBOL_GPL(dm_bufio_get);
1015 void *dm_bufio_read(struct dm_bufio_client *c, sector_t block,
1016 struct dm_buffer **bp)
1018 BUG_ON(dm_bufio_in_request());
1020 return new_read(c, block, NF_READ, bp);
1022 EXPORT_SYMBOL_GPL(dm_bufio_read);
1024 void *dm_bufio_new(struct dm_bufio_client *c, sector_t block,
1025 struct dm_buffer **bp)
1027 BUG_ON(dm_bufio_in_request());
1029 return new_read(c, block, NF_FRESH, bp);
1031 EXPORT_SYMBOL_GPL(dm_bufio_new);
1033 void dm_bufio_release(struct dm_buffer *b)
1035 struct dm_bufio_client *c = b->c;
1039 BUG_ON(test_bit(B_READING, &b->state));
1040 BUG_ON(!b->hold_count);
1043 if (!b->hold_count) {
1044 wake_up(&c->free_buffer_wait);
1047 * If there were errors on the buffer, and the buffer is not
1048 * to be written, free the buffer. There is no point in caching
1051 if ((b->read_error || b->write_error) &&
1052 !test_bit(B_WRITING, &b->state) &&
1053 !test_bit(B_DIRTY, &b->state)) {
1055 __free_buffer_wake(b);
1061 EXPORT_SYMBOL_GPL(dm_bufio_release);
1063 void dm_bufio_mark_buffer_dirty(struct dm_buffer *b)
1065 struct dm_bufio_client *c = b->c;
1069 if (!test_and_set_bit(B_DIRTY, &b->state))
1070 __relink_lru(b, LIST_DIRTY);
1074 EXPORT_SYMBOL_GPL(dm_bufio_mark_buffer_dirty);
1076 void dm_bufio_write_dirty_buffers_async(struct dm_bufio_client *c)
1078 BUG_ON(dm_bufio_in_request());
1081 __write_dirty_buffers_async(c, 0);
1084 EXPORT_SYMBOL_GPL(dm_bufio_write_dirty_buffers_async);
1087 * For performance, it is essential that the buffers are written asynchronously
1088 * and simultaneously (so that the block layer can merge the writes) and then
1091 * Finally, we flush hardware disk cache.
1093 int dm_bufio_write_dirty_buffers(struct dm_bufio_client *c)
1096 unsigned long buffers_processed = 0;
1097 struct dm_buffer *b, *tmp;
1100 __write_dirty_buffers_async(c, 0);
1103 list_for_each_entry_safe_reverse(b, tmp, &c->lru[LIST_DIRTY], lru_list) {
1104 int dropped_lock = 0;
1106 if (buffers_processed < c->n_buffers[LIST_DIRTY])
1107 buffers_processed++;
1109 BUG_ON(test_bit(B_READING, &b->state));
1111 if (test_bit(B_WRITING, &b->state)) {
1112 if (buffers_processed < c->n_buffers[LIST_DIRTY]) {
1116 wait_on_bit(&b->state, B_WRITING,
1118 TASK_UNINTERRUPTIBLE);
1122 wait_on_bit(&b->state, B_WRITING,
1124 TASK_UNINTERRUPTIBLE);
1127 if (!test_bit(B_DIRTY, &b->state) &&
1128 !test_bit(B_WRITING, &b->state))
1129 __relink_lru(b, LIST_CLEAN);
1131 dm_bufio_cond_resched();
1134 * If we dropped the lock, the list is no longer consistent,
1135 * so we must restart the search.
1137 * In the most common case, the buffer just processed is
1138 * relinked to the clean list, so we won't loop scanning the
1139 * same buffer again and again.
1141 * This may livelock if there is another thread simultaneously
1142 * dirtying buffers, so we count the number of buffers walked
1143 * and if it exceeds the total number of buffers, it means that
1144 * someone is doing some writes simultaneously with us. In
1145 * this case, stop, dropping the lock.
1150 wake_up(&c->free_buffer_wait);
1153 a = xchg(&c->async_write_error, 0);
1154 f = dm_bufio_issue_flush(c);
1160 EXPORT_SYMBOL_GPL(dm_bufio_write_dirty_buffers);
1163 * Use dm-io to send and empty barrier flush the device.
1165 int dm_bufio_issue_flush(struct dm_bufio_client *c)
1167 struct dm_io_request io_req = {
1169 .mem.type = DM_IO_KMEM,
1170 .mem.ptr.addr = NULL,
1173 struct dm_io_region io_reg = {
1179 BUG_ON(dm_bufio_in_request());
1181 return dm_io(&io_req, 1, &io_reg, NULL);
1183 EXPORT_SYMBOL_GPL(dm_bufio_issue_flush);
1186 * We first delete any other buffer that may be at that new location.
1188 * Then, we write the buffer to the original location if it was dirty.
1190 * Then, if we are the only one who is holding the buffer, relink the buffer
1191 * in the hash queue for the new location.
1193 * If there was someone else holding the buffer, we write it to the new
1194 * location but not relink it, because that other user needs to have the buffer
1195 * at the same place.
1197 void dm_bufio_release_move(struct dm_buffer *b, sector_t new_block)
1199 struct dm_bufio_client *c = b->c;
1200 struct dm_buffer *new;
1202 BUG_ON(dm_bufio_in_request());
1207 new = __find(c, new_block);
1209 if (new->hold_count) {
1210 __wait_for_free_buffer(c);
1215 * FIXME: Is there any point waiting for a write that's going
1216 * to be overwritten in a bit?
1218 __make_buffer_clean(new);
1219 __unlink_buffer(new);
1220 __free_buffer_wake(new);
1223 BUG_ON(!b->hold_count);
1224 BUG_ON(test_bit(B_READING, &b->state));
1226 __write_dirty_buffer(b);
1227 if (b->hold_count == 1) {
1228 wait_on_bit(&b->state, B_WRITING,
1229 do_io_schedule, TASK_UNINTERRUPTIBLE);
1230 set_bit(B_DIRTY, &b->state);
1232 __link_buffer(b, new_block, LIST_DIRTY);
1235 wait_on_bit_lock(&b->state, B_WRITING,
1236 do_io_schedule, TASK_UNINTERRUPTIBLE);
1238 * Relink buffer to "new_block" so that write_callback
1239 * sees "new_block" as a block number.
1240 * After the write, link the buffer back to old_block.
1241 * All this must be done in bufio lock, so that block number
1242 * change isn't visible to other threads.
1244 old_block = b->block;
1246 __link_buffer(b, new_block, b->list_mode);
1247 submit_io(b, WRITE, new_block, write_endio);
1248 wait_on_bit(&b->state, B_WRITING,
1249 do_io_schedule, TASK_UNINTERRUPTIBLE);
1251 __link_buffer(b, old_block, b->list_mode);
1255 dm_bufio_release(b);
1257 EXPORT_SYMBOL_GPL(dm_bufio_release_move);
1259 unsigned dm_bufio_get_block_size(struct dm_bufio_client *c)
1261 return c->block_size;
1263 EXPORT_SYMBOL_GPL(dm_bufio_get_block_size);
1265 sector_t dm_bufio_get_device_size(struct dm_bufio_client *c)
1267 return i_size_read(c->bdev->bd_inode) >>
1268 (SECTOR_SHIFT + c->sectors_per_block_bits);
1270 EXPORT_SYMBOL_GPL(dm_bufio_get_device_size);
1272 sector_t dm_bufio_get_block_number(struct dm_buffer *b)
1276 EXPORT_SYMBOL_GPL(dm_bufio_get_block_number);
1278 void *dm_bufio_get_block_data(struct dm_buffer *b)
1282 EXPORT_SYMBOL_GPL(dm_bufio_get_block_data);
1284 void *dm_bufio_get_aux_data(struct dm_buffer *b)
1288 EXPORT_SYMBOL_GPL(dm_bufio_get_aux_data);
1290 struct dm_bufio_client *dm_bufio_get_client(struct dm_buffer *b)
1294 EXPORT_SYMBOL_GPL(dm_bufio_get_client);
1296 static void drop_buffers(struct dm_bufio_client *c)
1298 struct dm_buffer *b;
1301 BUG_ON(dm_bufio_in_request());
1304 * An optimization so that the buffers are not written one-by-one.
1306 dm_bufio_write_dirty_buffers_async(c);
1310 while ((b = __get_unclaimed_buffer(c)))
1311 __free_buffer_wake(b);
1313 for (i = 0; i < LIST_SIZE; i++)
1314 list_for_each_entry(b, &c->lru[i], lru_list)
1315 DMERR("leaked buffer %llx, hold count %u, list %d",
1316 (unsigned long long)b->block, b->hold_count, i);
1318 for (i = 0; i < LIST_SIZE; i++)
1319 BUG_ON(!list_empty(&c->lru[i]));
1325 * Test if the buffer is unused and too old, and commit it.
1326 * At if noio is set, we must not do any I/O because we hold
1327 * dm_bufio_clients_lock and we would risk deadlock if the I/O gets rerouted to
1328 * different bufio client.
1330 static int __cleanup_old_buffer(struct dm_buffer *b, gfp_t gfp,
1331 unsigned long max_jiffies)
1333 if (jiffies - b->last_accessed < max_jiffies)
1336 if (!(gfp & __GFP_IO)) {
1337 if (test_bit(B_READING, &b->state) ||
1338 test_bit(B_WRITING, &b->state) ||
1339 test_bit(B_DIRTY, &b->state))
1346 __make_buffer_clean(b);
1348 __free_buffer_wake(b);
1353 static void __scan(struct dm_bufio_client *c, unsigned long nr_to_scan,
1354 struct shrink_control *sc)
1357 struct dm_buffer *b, *tmp;
1359 for (l = 0; l < LIST_SIZE; l++) {
1360 list_for_each_entry_safe_reverse(b, tmp, &c->lru[l], lru_list)
1361 if (!__cleanup_old_buffer(b, sc->gfp_mask, 0) &&
1364 dm_bufio_cond_resched();
1368 static int shrink(struct shrinker *shrinker, struct shrink_control *sc)
1370 struct dm_bufio_client *c =
1371 container_of(shrinker, struct dm_bufio_client, shrinker);
1373 unsigned long nr_to_scan = sc->nr_to_scan;
1375 if (sc->gfp_mask & __GFP_IO)
1377 else if (!dm_bufio_trylock(c))
1378 return !nr_to_scan ? 0 : -1;
1381 __scan(c, nr_to_scan, sc);
1383 r = c->n_buffers[LIST_CLEAN] + c->n_buffers[LIST_DIRTY];
1393 * Create the buffering interface
1395 struct dm_bufio_client *dm_bufio_client_create(struct block_device *bdev, unsigned block_size,
1396 unsigned reserved_buffers, unsigned aux_size,
1397 void (*alloc_callback)(struct dm_buffer *),
1398 void (*write_callback)(struct dm_buffer *))
1401 struct dm_bufio_client *c;
1404 BUG_ON(block_size < 1 << SECTOR_SHIFT ||
1405 (block_size & (block_size - 1)));
1407 c = kmalloc(sizeof(*c), GFP_KERNEL);
1412 c->cache_hash = vmalloc(sizeof(struct hlist_head) << DM_BUFIO_HASH_BITS);
1413 if (!c->cache_hash) {
1419 c->block_size = block_size;
1420 c->sectors_per_block_bits = ffs(block_size) - 1 - SECTOR_SHIFT;
1421 c->pages_per_block_bits = (ffs(block_size) - 1 >= PAGE_SHIFT) ?
1422 ffs(block_size) - 1 - PAGE_SHIFT : 0;
1423 c->blocks_per_page_bits = (ffs(block_size) - 1 < PAGE_SHIFT ?
1424 PAGE_SHIFT - (ffs(block_size) - 1) : 0);
1426 c->aux_size = aux_size;
1427 c->alloc_callback = alloc_callback;
1428 c->write_callback = write_callback;
1430 for (i = 0; i < LIST_SIZE; i++) {
1431 INIT_LIST_HEAD(&c->lru[i]);
1432 c->n_buffers[i] = 0;
1435 for (i = 0; i < 1 << DM_BUFIO_HASH_BITS; i++)
1436 INIT_HLIST_HEAD(&c->cache_hash[i]);
1438 mutex_init(&c->lock);
1439 INIT_LIST_HEAD(&c->reserved_buffers);
1440 c->need_reserved_buffers = reserved_buffers;
1442 init_waitqueue_head(&c->free_buffer_wait);
1443 c->async_write_error = 0;
1445 c->dm_io = dm_io_client_create();
1446 if (IS_ERR(c->dm_io)) {
1447 r = PTR_ERR(c->dm_io);
1451 mutex_lock(&dm_bufio_clients_lock);
1452 if (c->blocks_per_page_bits) {
1453 if (!DM_BUFIO_CACHE_NAME(c)) {
1454 DM_BUFIO_CACHE_NAME(c) = kasprintf(GFP_KERNEL, "dm_bufio_cache-%u", c->block_size);
1455 if (!DM_BUFIO_CACHE_NAME(c)) {
1457 mutex_unlock(&dm_bufio_clients_lock);
1462 if (!DM_BUFIO_CACHE(c)) {
1463 DM_BUFIO_CACHE(c) = kmem_cache_create(DM_BUFIO_CACHE_NAME(c),
1465 c->block_size, 0, NULL);
1466 if (!DM_BUFIO_CACHE(c)) {
1468 mutex_unlock(&dm_bufio_clients_lock);
1473 mutex_unlock(&dm_bufio_clients_lock);
1475 while (c->need_reserved_buffers) {
1476 struct dm_buffer *b = alloc_buffer(c, GFP_KERNEL);
1482 __free_buffer_wake(b);
1485 mutex_lock(&dm_bufio_clients_lock);
1486 dm_bufio_client_count++;
1487 list_add(&c->client_list, &dm_bufio_all_clients);
1488 __cache_size_refresh();
1489 mutex_unlock(&dm_bufio_clients_lock);
1491 c->shrinker.shrink = shrink;
1492 c->shrinker.seeks = 1;
1493 c->shrinker.batch = 0;
1494 register_shrinker(&c->shrinker);
1500 while (!list_empty(&c->reserved_buffers)) {
1501 struct dm_buffer *b = list_entry(c->reserved_buffers.next,
1502 struct dm_buffer, lru_list);
1503 list_del(&b->lru_list);
1506 dm_io_client_destroy(c->dm_io);
1508 vfree(c->cache_hash);
1514 EXPORT_SYMBOL_GPL(dm_bufio_client_create);
1517 * Free the buffering interface.
1518 * It is required that there are no references on any buffers.
1520 void dm_bufio_client_destroy(struct dm_bufio_client *c)
1526 unregister_shrinker(&c->shrinker);
1528 mutex_lock(&dm_bufio_clients_lock);
1530 list_del(&c->client_list);
1531 dm_bufio_client_count--;
1532 __cache_size_refresh();
1534 mutex_unlock(&dm_bufio_clients_lock);
1536 for (i = 0; i < 1 << DM_BUFIO_HASH_BITS; i++)
1537 BUG_ON(!hlist_empty(&c->cache_hash[i]));
1539 BUG_ON(c->need_reserved_buffers);
1541 while (!list_empty(&c->reserved_buffers)) {
1542 struct dm_buffer *b = list_entry(c->reserved_buffers.next,
1543 struct dm_buffer, lru_list);
1544 list_del(&b->lru_list);
1548 for (i = 0; i < LIST_SIZE; i++)
1549 if (c->n_buffers[i])
1550 DMERR("leaked buffer count %d: %ld", i, c->n_buffers[i]);
1552 for (i = 0; i < LIST_SIZE; i++)
1553 BUG_ON(c->n_buffers[i]);
1555 dm_io_client_destroy(c->dm_io);
1556 vfree(c->cache_hash);
1559 EXPORT_SYMBOL_GPL(dm_bufio_client_destroy);
1561 static void cleanup_old_buffers(void)
1563 unsigned long max_age = dm_bufio_max_age;
1564 struct dm_bufio_client *c;
1568 if (max_age > ULONG_MAX / HZ)
1569 max_age = ULONG_MAX / HZ;
1571 mutex_lock(&dm_bufio_clients_lock);
1572 list_for_each_entry(c, &dm_bufio_all_clients, client_list) {
1573 if (!dm_bufio_trylock(c))
1576 while (!list_empty(&c->lru[LIST_CLEAN])) {
1577 struct dm_buffer *b;
1578 b = list_entry(c->lru[LIST_CLEAN].prev,
1579 struct dm_buffer, lru_list);
1580 if (__cleanup_old_buffer(b, 0, max_age * HZ))
1582 dm_bufio_cond_resched();
1586 dm_bufio_cond_resched();
1588 mutex_unlock(&dm_bufio_clients_lock);
1591 static struct workqueue_struct *dm_bufio_wq;
1592 static struct delayed_work dm_bufio_work;
1594 static void work_fn(struct work_struct *w)
1596 cleanup_old_buffers();
1598 queue_delayed_work(dm_bufio_wq, &dm_bufio_work,
1599 DM_BUFIO_WORK_TIMER_SECS * HZ);
1602 /*----------------------------------------------------------------
1604 *--------------------------------------------------------------*/
1607 * This is called only once for the whole dm_bufio module.
1608 * It initializes memory limit.
1610 static int __init dm_bufio_init(void)
1614 dm_bufio_allocated_kmem_cache = 0;
1615 dm_bufio_allocated_get_free_pages = 0;
1616 dm_bufio_allocated_vmalloc = 0;
1617 dm_bufio_current_allocated = 0;
1619 memset(&dm_bufio_caches, 0, sizeof dm_bufio_caches);
1620 memset(&dm_bufio_cache_names, 0, sizeof dm_bufio_cache_names);
1622 mem = (__u64)((totalram_pages - totalhigh_pages) *
1623 DM_BUFIO_MEMORY_PERCENT / 100) << PAGE_SHIFT;
1625 if (mem > ULONG_MAX)
1630 * Get the size of vmalloc space the same way as VMALLOC_TOTAL
1631 * in fs/proc/internal.h
1633 if (mem > (VMALLOC_END - VMALLOC_START) * DM_BUFIO_VMALLOC_PERCENT / 100)
1634 mem = (VMALLOC_END - VMALLOC_START) * DM_BUFIO_VMALLOC_PERCENT / 100;
1637 dm_bufio_default_cache_size = mem;
1639 mutex_lock(&dm_bufio_clients_lock);
1640 __cache_size_refresh();
1641 mutex_unlock(&dm_bufio_clients_lock);
1643 dm_bufio_wq = create_singlethread_workqueue("dm_bufio_cache");
1647 INIT_DELAYED_WORK(&dm_bufio_work, work_fn);
1648 queue_delayed_work(dm_bufio_wq, &dm_bufio_work,
1649 DM_BUFIO_WORK_TIMER_SECS * HZ);
1655 * This is called once when unloading the dm_bufio module.
1657 static void __exit dm_bufio_exit(void)
1662 cancel_delayed_work_sync(&dm_bufio_work);
1663 destroy_workqueue(dm_bufio_wq);
1665 for (i = 0; i < ARRAY_SIZE(dm_bufio_caches); i++) {
1666 struct kmem_cache *kc = dm_bufio_caches[i];
1669 kmem_cache_destroy(kc);
1672 for (i = 0; i < ARRAY_SIZE(dm_bufio_cache_names); i++)
1673 kfree(dm_bufio_cache_names[i]);
1675 if (dm_bufio_client_count) {
1676 DMCRIT("%s: dm_bufio_client_count leaked: %d",
1677 __func__, dm_bufio_client_count);
1681 if (dm_bufio_current_allocated) {
1682 DMCRIT("%s: dm_bufio_current_allocated leaked: %lu",
1683 __func__, dm_bufio_current_allocated);
1687 if (dm_bufio_allocated_get_free_pages) {
1688 DMCRIT("%s: dm_bufio_allocated_get_free_pages leaked: %lu",
1689 __func__, dm_bufio_allocated_get_free_pages);
1693 if (dm_bufio_allocated_vmalloc) {
1694 DMCRIT("%s: dm_bufio_vmalloc leaked: %lu",
1695 __func__, dm_bufio_allocated_vmalloc);
1703 module_init(dm_bufio_init)
1704 module_exit(dm_bufio_exit)
1706 module_param_named(max_cache_size_bytes, dm_bufio_cache_size, ulong, S_IRUGO | S_IWUSR);
1707 MODULE_PARM_DESC(max_cache_size_bytes, "Size of metadata cache");
1709 module_param_named(max_age_seconds, dm_bufio_max_age, uint, S_IRUGO | S_IWUSR);
1710 MODULE_PARM_DESC(max_age_seconds, "Max age of a buffer in seconds");
1712 module_param_named(peak_allocated_bytes, dm_bufio_peak_allocated, ulong, S_IRUGO | S_IWUSR);
1713 MODULE_PARM_DESC(peak_allocated_bytes, "Tracks the maximum allocated memory");
1715 module_param_named(allocated_kmem_cache_bytes, dm_bufio_allocated_kmem_cache, ulong, S_IRUGO);
1716 MODULE_PARM_DESC(allocated_kmem_cache_bytes, "Memory allocated with kmem_cache_alloc");
1718 module_param_named(allocated_get_free_pages_bytes, dm_bufio_allocated_get_free_pages, ulong, S_IRUGO);
1719 MODULE_PARM_DESC(allocated_get_free_pages_bytes, "Memory allocated with get_free_pages");
1721 module_param_named(allocated_vmalloc_bytes, dm_bufio_allocated_vmalloc, ulong, S_IRUGO);
1722 MODULE_PARM_DESC(allocated_vmalloc_bytes, "Memory allocated with vmalloc");
1724 module_param_named(current_allocated_bytes, dm_bufio_current_allocated, ulong, S_IRUGO);
1725 MODULE_PARM_DESC(current_allocated_bytes, "Memory currently used by the cache");
1727 MODULE_AUTHOR("Mikulas Patocka <dm-devel@redhat.com>");
1728 MODULE_DESCRIPTION(DM_NAME " buffered I/O library");
1729 MODULE_LICENSE("GPL");