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]);
471 b->last_accessed = jiffies;
474 /*----------------------------------------------------------------
475 * Submit I/O on the buffer.
477 * Bio interface is faster but it has some problems:
478 * the vector list is limited (increasing this limit increases
479 * memory-consumption per buffer, so it is not viable);
481 * the memory must be direct-mapped, not vmalloced;
483 * the I/O driver can reject requests spuriously if it thinks that
484 * the requests are too big for the device or if they cross a
485 * controller-defined memory boundary.
487 * If the buffer is small enough (up to DM_BUFIO_INLINE_VECS pages) and
488 * it is not vmalloced, try using the bio interface.
490 * If the buffer is big, if it is vmalloced or if the underlying device
491 * rejects the bio because it is too large, use dm-io layer to do the I/O.
492 * The dm-io layer splits the I/O into multiple requests, avoiding the above
494 *--------------------------------------------------------------*/
497 * dm-io completion routine. It just calls b->bio.bi_end_io, pretending
498 * that the request was handled directly with bio interface.
500 static void dmio_complete(unsigned long error, void *context)
502 struct dm_buffer *b = context;
504 b->bio.bi_end_io(&b->bio, error ? -EIO : 0);
507 static void use_dmio(struct dm_buffer *b, int rw, sector_t block,
508 bio_end_io_t *end_io)
511 struct dm_io_request io_req = {
513 .notify.fn = dmio_complete,
515 .client = b->c->dm_io,
517 struct dm_io_region region = {
519 .sector = block << b->c->sectors_per_block_bits,
520 .count = b->c->block_size >> SECTOR_SHIFT,
523 if (b->data_mode != DATA_MODE_VMALLOC) {
524 io_req.mem.type = DM_IO_KMEM;
525 io_req.mem.ptr.addr = b->data;
527 io_req.mem.type = DM_IO_VMA;
528 io_req.mem.ptr.vma = b->data;
531 b->bio.bi_end_io = end_io;
533 r = dm_io(&io_req, 1, ®ion, NULL);
538 static void use_inline_bio(struct dm_buffer *b, int rw, sector_t block,
539 bio_end_io_t *end_io)
545 b->bio.bi_io_vec = b->bio_vec;
546 b->bio.bi_max_vecs = DM_BUFIO_INLINE_VECS;
547 b->bio.bi_sector = block << b->c->sectors_per_block_bits;
548 b->bio.bi_bdev = b->c->bdev;
549 b->bio.bi_end_io = end_io;
552 * We assume that if len >= PAGE_SIZE ptr is page-aligned.
553 * If len < PAGE_SIZE the buffer doesn't cross page boundary.
556 len = b->c->block_size;
558 if (len >= PAGE_SIZE)
559 BUG_ON((unsigned long)ptr & (PAGE_SIZE - 1));
561 BUG_ON((unsigned long)ptr & (len - 1));
564 if (!bio_add_page(&b->bio, virt_to_page(ptr),
565 len < PAGE_SIZE ? len : PAGE_SIZE,
566 virt_to_phys(ptr) & (PAGE_SIZE - 1))) {
567 BUG_ON(b->c->block_size <= PAGE_SIZE);
568 use_dmio(b, rw, block, end_io);
576 submit_bio(rw, &b->bio);
579 static void submit_io(struct dm_buffer *b, int rw, sector_t block,
580 bio_end_io_t *end_io)
582 if (rw == WRITE && b->c->write_callback)
583 b->c->write_callback(b);
585 if (b->c->block_size <= DM_BUFIO_INLINE_VECS * PAGE_SIZE &&
586 b->data_mode != DATA_MODE_VMALLOC)
587 use_inline_bio(b, rw, block, end_io);
589 use_dmio(b, rw, block, end_io);
592 /*----------------------------------------------------------------
593 * Writing dirty buffers
594 *--------------------------------------------------------------*/
597 * The endio routine for write.
599 * Set the error, clear B_WRITING bit and wake anyone who was waiting on
602 static void write_endio(struct bio *bio, int error)
604 struct dm_buffer *b = container_of(bio, struct dm_buffer, bio);
606 b->write_error = error;
608 struct dm_bufio_client *c = b->c;
609 (void)cmpxchg(&c->async_write_error, 0, error);
612 BUG_ON(!test_bit(B_WRITING, &b->state));
614 smp_mb__before_clear_bit();
615 clear_bit(B_WRITING, &b->state);
616 smp_mb__after_clear_bit();
618 wake_up_bit(&b->state, B_WRITING);
622 * This function is called when wait_on_bit is actually waiting.
624 static int do_io_schedule(void *word)
632 * Initiate a write on a dirty buffer, but don't wait for it.
634 * - If the buffer is not dirty, exit.
635 * - If there some previous write going on, wait for it to finish (we can't
636 * have two writes on the same buffer simultaneously).
637 * - Submit our write and don't wait on it. We set B_WRITING indicating
638 * that there is a write in progress.
640 static void __write_dirty_buffer(struct dm_buffer *b)
642 if (!test_bit(B_DIRTY, &b->state))
645 clear_bit(B_DIRTY, &b->state);
646 wait_on_bit_lock(&b->state, B_WRITING,
647 do_io_schedule, TASK_UNINTERRUPTIBLE);
649 submit_io(b, WRITE, b->block, write_endio);
653 * Wait until any activity on the buffer finishes. Possibly write the
654 * buffer if it is dirty. When this function finishes, there is no I/O
655 * running on the buffer and the buffer is not dirty.
657 static void __make_buffer_clean(struct dm_buffer *b)
659 BUG_ON(b->hold_count);
661 if (!b->state) /* fast case */
664 wait_on_bit(&b->state, B_READING, do_io_schedule, TASK_UNINTERRUPTIBLE);
665 __write_dirty_buffer(b);
666 wait_on_bit(&b->state, B_WRITING, do_io_schedule, TASK_UNINTERRUPTIBLE);
670 * Find some buffer that is not held by anybody, clean it, unlink it and
673 static struct dm_buffer *__get_unclaimed_buffer(struct dm_bufio_client *c)
677 list_for_each_entry_reverse(b, &c->lru[LIST_CLEAN], lru_list) {
678 BUG_ON(test_bit(B_WRITING, &b->state));
679 BUG_ON(test_bit(B_DIRTY, &b->state));
681 if (!b->hold_count) {
682 __make_buffer_clean(b);
686 dm_bufio_cond_resched();
689 list_for_each_entry_reverse(b, &c->lru[LIST_DIRTY], lru_list) {
690 BUG_ON(test_bit(B_READING, &b->state));
692 if (!b->hold_count) {
693 __make_buffer_clean(b);
697 dm_bufio_cond_resched();
704 * Wait until some other threads free some buffer or release hold count on
707 * This function is entered with c->lock held, drops it and regains it
710 static void __wait_for_free_buffer(struct dm_bufio_client *c)
712 DECLARE_WAITQUEUE(wait, current);
714 add_wait_queue(&c->free_buffer_wait, &wait);
715 set_task_state(current, TASK_UNINTERRUPTIBLE);
720 set_task_state(current, TASK_RUNNING);
721 remove_wait_queue(&c->free_buffer_wait, &wait);
727 * Allocate a new buffer. If the allocation is not possible, wait until
728 * some other thread frees a buffer.
730 * May drop the lock and regain it.
732 static struct dm_buffer *__alloc_buffer_wait_no_callback(struct dm_bufio_client *c)
737 * dm-bufio is resistant to allocation failures (it just keeps
738 * one buffer reserved in cases all the allocations fail).
739 * So set flags to not try too hard:
740 * GFP_NOIO: don't recurse into the I/O layer
741 * __GFP_NORETRY: don't retry and rather return failure
742 * __GFP_NOMEMALLOC: don't use emergency reserves
743 * __GFP_NOWARN: don't print a warning in case of failure
745 * For debugging, if we set the cache size to 1, no new buffers will
749 if (dm_bufio_cache_size_latch != 1) {
750 b = alloc_buffer(c, GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
755 if (!list_empty(&c->reserved_buffers)) {
756 b = list_entry(c->reserved_buffers.next,
757 struct dm_buffer, lru_list);
758 list_del(&b->lru_list);
759 c->need_reserved_buffers++;
764 b = __get_unclaimed_buffer(c);
768 __wait_for_free_buffer(c);
772 static struct dm_buffer *__alloc_buffer_wait(struct dm_bufio_client *c)
774 struct dm_buffer *b = __alloc_buffer_wait_no_callback(c);
776 if (c->alloc_callback)
777 c->alloc_callback(b);
783 * Free a buffer and wake other threads waiting for free buffers.
785 static void __free_buffer_wake(struct dm_buffer *b)
787 struct dm_bufio_client *c = b->c;
789 if (!c->need_reserved_buffers)
792 list_add(&b->lru_list, &c->reserved_buffers);
793 c->need_reserved_buffers--;
796 wake_up(&c->free_buffer_wait);
799 static void __write_dirty_buffers_async(struct dm_bufio_client *c, int no_wait)
801 struct dm_buffer *b, *tmp;
803 list_for_each_entry_safe_reverse(b, tmp, &c->lru[LIST_DIRTY], lru_list) {
804 BUG_ON(test_bit(B_READING, &b->state));
806 if (!test_bit(B_DIRTY, &b->state) &&
807 !test_bit(B_WRITING, &b->state)) {
808 __relink_lru(b, LIST_CLEAN);
812 if (no_wait && test_bit(B_WRITING, &b->state))
815 __write_dirty_buffer(b);
816 dm_bufio_cond_resched();
821 * Get writeback threshold and buffer limit for a given client.
823 static void __get_memory_limit(struct dm_bufio_client *c,
824 unsigned long *threshold_buffers,
825 unsigned long *limit_buffers)
827 unsigned long buffers;
829 if (dm_bufio_cache_size != dm_bufio_cache_size_latch) {
830 mutex_lock(&dm_bufio_clients_lock);
831 __cache_size_refresh();
832 mutex_unlock(&dm_bufio_clients_lock);
835 buffers = dm_bufio_cache_size_per_client >>
836 (c->sectors_per_block_bits + SECTOR_SHIFT);
838 if (buffers < DM_BUFIO_MIN_BUFFERS)
839 buffers = DM_BUFIO_MIN_BUFFERS;
841 *limit_buffers = buffers;
842 *threshold_buffers = buffers * DM_BUFIO_WRITEBACK_PERCENT / 100;
846 * Check if we're over watermark.
847 * If we are over threshold_buffers, start freeing buffers.
848 * If we're over "limit_buffers", block until we get under the limit.
850 static void __check_watermark(struct dm_bufio_client *c)
852 unsigned long threshold_buffers, limit_buffers;
854 __get_memory_limit(c, &threshold_buffers, &limit_buffers);
856 while (c->n_buffers[LIST_CLEAN] + c->n_buffers[LIST_DIRTY] >
859 struct dm_buffer *b = __get_unclaimed_buffer(c);
864 __free_buffer_wake(b);
865 dm_bufio_cond_resched();
868 if (c->n_buffers[LIST_DIRTY] > threshold_buffers)
869 __write_dirty_buffers_async(c, 1);
873 * Find a buffer in the hash.
875 static struct dm_buffer *__find(struct dm_bufio_client *c, sector_t block)
878 struct hlist_node *hn;
880 hlist_for_each_entry(b, hn, &c->cache_hash[DM_BUFIO_HASH(block)],
882 dm_bufio_cond_resched();
883 if (b->block == block)
890 /*----------------------------------------------------------------
892 *--------------------------------------------------------------*/
900 static struct dm_buffer *__bufio_new(struct dm_bufio_client *c, sector_t block,
901 enum new_flag nf, struct dm_buffer **bp,
904 struct dm_buffer *b, *new_b = NULL;
908 b = __find(c, block);
911 __relink_lru(b, test_bit(B_DIRTY, &b->state) ||
912 test_bit(B_WRITING, &b->state));
919 new_b = __alloc_buffer_wait(c);
922 * We've had a period where the mutex was unlocked, so need to
923 * recheck the hash table.
925 b = __find(c, block);
927 __free_buffer_wake(new_b);
929 __relink_lru(b, test_bit(B_DIRTY, &b->state) ||
930 test_bit(B_WRITING, &b->state));
934 __check_watermark(c);
940 __link_buffer(b, block, LIST_CLEAN);
942 if (nf == NF_FRESH) {
947 b->state = 1 << B_READING;
954 * The endio routine for reading: set the error, clear the bit and wake up
955 * anyone waiting on the buffer.
957 static void read_endio(struct bio *bio, int error)
959 struct dm_buffer *b = container_of(bio, struct dm_buffer, bio);
961 b->read_error = error;
963 BUG_ON(!test_bit(B_READING, &b->state));
965 smp_mb__before_clear_bit();
966 clear_bit(B_READING, &b->state);
967 smp_mb__after_clear_bit();
969 wake_up_bit(&b->state, B_READING);
973 * A common routine for dm_bufio_new and dm_bufio_read. Operation of these
974 * functions is similar except that dm_bufio_new doesn't read the
975 * buffer from the disk (assuming that the caller overwrites all the data
976 * and uses dm_bufio_mark_buffer_dirty to write new data back).
978 static void *new_read(struct dm_bufio_client *c, sector_t block,
979 enum new_flag nf, struct dm_buffer **bp)
985 b = __bufio_new(c, block, nf, bp, &need_submit);
992 submit_io(b, READ, b->block, read_endio);
994 wait_on_bit(&b->state, B_READING, do_io_schedule, TASK_UNINTERRUPTIBLE);
997 int error = b->read_error;
1001 return ERR_PTR(error);
1009 void *dm_bufio_get(struct dm_bufio_client *c, sector_t block,
1010 struct dm_buffer **bp)
1012 return new_read(c, block, NF_GET, bp);
1014 EXPORT_SYMBOL_GPL(dm_bufio_get);
1016 void *dm_bufio_read(struct dm_bufio_client *c, sector_t block,
1017 struct dm_buffer **bp)
1019 BUG_ON(dm_bufio_in_request());
1021 return new_read(c, block, NF_READ, bp);
1023 EXPORT_SYMBOL_GPL(dm_bufio_read);
1025 void *dm_bufio_new(struct dm_bufio_client *c, sector_t block,
1026 struct dm_buffer **bp)
1028 BUG_ON(dm_bufio_in_request());
1030 return new_read(c, block, NF_FRESH, bp);
1032 EXPORT_SYMBOL_GPL(dm_bufio_new);
1034 void dm_bufio_release(struct dm_buffer *b)
1036 struct dm_bufio_client *c = b->c;
1040 BUG_ON(test_bit(B_READING, &b->state));
1041 BUG_ON(!b->hold_count);
1044 if (!b->hold_count) {
1045 wake_up(&c->free_buffer_wait);
1048 * If there were errors on the buffer, and the buffer is not
1049 * to be written, free the buffer. There is no point in caching
1052 if ((b->read_error || b->write_error) &&
1053 !test_bit(B_WRITING, &b->state) &&
1054 !test_bit(B_DIRTY, &b->state)) {
1056 __free_buffer_wake(b);
1062 EXPORT_SYMBOL_GPL(dm_bufio_release);
1064 void dm_bufio_mark_buffer_dirty(struct dm_buffer *b)
1066 struct dm_bufio_client *c = b->c;
1070 if (!test_and_set_bit(B_DIRTY, &b->state))
1071 __relink_lru(b, LIST_DIRTY);
1075 EXPORT_SYMBOL_GPL(dm_bufio_mark_buffer_dirty);
1077 void dm_bufio_write_dirty_buffers_async(struct dm_bufio_client *c)
1079 BUG_ON(dm_bufio_in_request());
1082 __write_dirty_buffers_async(c, 0);
1085 EXPORT_SYMBOL_GPL(dm_bufio_write_dirty_buffers_async);
1088 * For performance, it is essential that the buffers are written asynchronously
1089 * and simultaneously (so that the block layer can merge the writes) and then
1092 * Finally, we flush hardware disk cache.
1094 int dm_bufio_write_dirty_buffers(struct dm_bufio_client *c)
1097 unsigned long buffers_processed = 0;
1098 struct dm_buffer *b, *tmp;
1101 __write_dirty_buffers_async(c, 0);
1104 list_for_each_entry_safe_reverse(b, tmp, &c->lru[LIST_DIRTY], lru_list) {
1105 int dropped_lock = 0;
1107 if (buffers_processed < c->n_buffers[LIST_DIRTY])
1108 buffers_processed++;
1110 BUG_ON(test_bit(B_READING, &b->state));
1112 if (test_bit(B_WRITING, &b->state)) {
1113 if (buffers_processed < c->n_buffers[LIST_DIRTY]) {
1117 wait_on_bit(&b->state, B_WRITING,
1119 TASK_UNINTERRUPTIBLE);
1123 wait_on_bit(&b->state, B_WRITING,
1125 TASK_UNINTERRUPTIBLE);
1128 if (!test_bit(B_DIRTY, &b->state) &&
1129 !test_bit(B_WRITING, &b->state))
1130 __relink_lru(b, LIST_CLEAN);
1132 dm_bufio_cond_resched();
1135 * If we dropped the lock, the list is no longer consistent,
1136 * so we must restart the search.
1138 * In the most common case, the buffer just processed is
1139 * relinked to the clean list, so we won't loop scanning the
1140 * same buffer again and again.
1142 * This may livelock if there is another thread simultaneously
1143 * dirtying buffers, so we count the number of buffers walked
1144 * and if it exceeds the total number of buffers, it means that
1145 * someone is doing some writes simultaneously with us. In
1146 * this case, stop, dropping the lock.
1151 wake_up(&c->free_buffer_wait);
1154 a = xchg(&c->async_write_error, 0);
1155 f = dm_bufio_issue_flush(c);
1161 EXPORT_SYMBOL_GPL(dm_bufio_write_dirty_buffers);
1164 * Use dm-io to send and empty barrier flush the device.
1166 int dm_bufio_issue_flush(struct dm_bufio_client *c)
1168 struct dm_io_request io_req = {
1170 .mem.type = DM_IO_KMEM,
1171 .mem.ptr.addr = NULL,
1174 struct dm_io_region io_reg = {
1180 BUG_ON(dm_bufio_in_request());
1182 return dm_io(&io_req, 1, &io_reg, NULL);
1184 EXPORT_SYMBOL_GPL(dm_bufio_issue_flush);
1187 * We first delete any other buffer that may be at that new location.
1189 * Then, we write the buffer to the original location if it was dirty.
1191 * Then, if we are the only one who is holding the buffer, relink the buffer
1192 * in the hash queue for the new location.
1194 * If there was someone else holding the buffer, we write it to the new
1195 * location but not relink it, because that other user needs to have the buffer
1196 * at the same place.
1198 void dm_bufio_release_move(struct dm_buffer *b, sector_t new_block)
1200 struct dm_bufio_client *c = b->c;
1201 struct dm_buffer *new;
1203 BUG_ON(dm_bufio_in_request());
1208 new = __find(c, new_block);
1210 if (new->hold_count) {
1211 __wait_for_free_buffer(c);
1216 * FIXME: Is there any point waiting for a write that's going
1217 * to be overwritten in a bit?
1219 __make_buffer_clean(new);
1220 __unlink_buffer(new);
1221 __free_buffer_wake(new);
1224 BUG_ON(!b->hold_count);
1225 BUG_ON(test_bit(B_READING, &b->state));
1227 __write_dirty_buffer(b);
1228 if (b->hold_count == 1) {
1229 wait_on_bit(&b->state, B_WRITING,
1230 do_io_schedule, TASK_UNINTERRUPTIBLE);
1231 set_bit(B_DIRTY, &b->state);
1233 __link_buffer(b, new_block, LIST_DIRTY);
1236 wait_on_bit_lock(&b->state, B_WRITING,
1237 do_io_schedule, TASK_UNINTERRUPTIBLE);
1239 * Relink buffer to "new_block" so that write_callback
1240 * sees "new_block" as a block number.
1241 * After the write, link the buffer back to old_block.
1242 * All this must be done in bufio lock, so that block number
1243 * change isn't visible to other threads.
1245 old_block = b->block;
1247 __link_buffer(b, new_block, b->list_mode);
1248 submit_io(b, WRITE, new_block, write_endio);
1249 wait_on_bit(&b->state, B_WRITING,
1250 do_io_schedule, TASK_UNINTERRUPTIBLE);
1252 __link_buffer(b, old_block, b->list_mode);
1256 dm_bufio_release(b);
1258 EXPORT_SYMBOL_GPL(dm_bufio_release_move);
1260 unsigned dm_bufio_get_block_size(struct dm_bufio_client *c)
1262 return c->block_size;
1264 EXPORT_SYMBOL_GPL(dm_bufio_get_block_size);
1266 sector_t dm_bufio_get_device_size(struct dm_bufio_client *c)
1268 return i_size_read(c->bdev->bd_inode) >>
1269 (SECTOR_SHIFT + c->sectors_per_block_bits);
1271 EXPORT_SYMBOL_GPL(dm_bufio_get_device_size);
1273 sector_t dm_bufio_get_block_number(struct dm_buffer *b)
1277 EXPORT_SYMBOL_GPL(dm_bufio_get_block_number);
1279 void *dm_bufio_get_block_data(struct dm_buffer *b)
1283 EXPORT_SYMBOL_GPL(dm_bufio_get_block_data);
1285 void *dm_bufio_get_aux_data(struct dm_buffer *b)
1289 EXPORT_SYMBOL_GPL(dm_bufio_get_aux_data);
1291 struct dm_bufio_client *dm_bufio_get_client(struct dm_buffer *b)
1295 EXPORT_SYMBOL_GPL(dm_bufio_get_client);
1297 static void drop_buffers(struct dm_bufio_client *c)
1299 struct dm_buffer *b;
1302 BUG_ON(dm_bufio_in_request());
1305 * An optimization so that the buffers are not written one-by-one.
1307 dm_bufio_write_dirty_buffers_async(c);
1311 while ((b = __get_unclaimed_buffer(c)))
1312 __free_buffer_wake(b);
1314 for (i = 0; i < LIST_SIZE; i++)
1315 list_for_each_entry(b, &c->lru[i], lru_list)
1316 DMERR("leaked buffer %llx, hold count %u, list %d",
1317 (unsigned long long)b->block, b->hold_count, i);
1319 for (i = 0; i < LIST_SIZE; i++)
1320 BUG_ON(!list_empty(&c->lru[i]));
1326 * Test if the buffer is unused and too old, and commit it.
1327 * And if GFP_NOFS is used, we must not do any I/O because we hold
1328 * dm_bufio_clients_lock and we would risk deadlock if the I/O gets
1329 * rerouted to different bufio client.
1331 static int __cleanup_old_buffer(struct dm_buffer *b, gfp_t gfp,
1332 unsigned long max_jiffies)
1334 if (jiffies - b->last_accessed < max_jiffies)
1337 if (!(gfp & __GFP_FS)) {
1338 if (test_bit(B_READING, &b->state) ||
1339 test_bit(B_WRITING, &b->state) ||
1340 test_bit(B_DIRTY, &b->state))
1347 __make_buffer_clean(b);
1349 __free_buffer_wake(b);
1354 static void __scan(struct dm_bufio_client *c, unsigned long nr_to_scan,
1355 struct shrink_control *sc)
1358 struct dm_buffer *b, *tmp;
1360 for (l = 0; l < LIST_SIZE; l++) {
1361 list_for_each_entry_safe_reverse(b, tmp, &c->lru[l], lru_list)
1362 if (!__cleanup_old_buffer(b, sc->gfp_mask, 0) &&
1365 dm_bufio_cond_resched();
1369 static int shrink(struct shrinker *shrinker, struct shrink_control *sc)
1371 struct dm_bufio_client *c =
1372 container_of(shrinker, struct dm_bufio_client, shrinker);
1374 unsigned long nr_to_scan = sc->nr_to_scan;
1376 if (sc->gfp_mask & __GFP_FS)
1378 else if (!dm_bufio_trylock(c))
1379 return !nr_to_scan ? 0 : -1;
1382 __scan(c, nr_to_scan, sc);
1384 r = c->n_buffers[LIST_CLEAN] + c->n_buffers[LIST_DIRTY];
1394 * Create the buffering interface
1396 struct dm_bufio_client *dm_bufio_client_create(struct block_device *bdev, unsigned block_size,
1397 unsigned reserved_buffers, unsigned aux_size,
1398 void (*alloc_callback)(struct dm_buffer *),
1399 void (*write_callback)(struct dm_buffer *))
1402 struct dm_bufio_client *c;
1405 BUG_ON(block_size < 1 << SECTOR_SHIFT ||
1406 (block_size & (block_size - 1)));
1408 c = kmalloc(sizeof(*c), GFP_KERNEL);
1413 c->cache_hash = vmalloc(sizeof(struct hlist_head) << DM_BUFIO_HASH_BITS);
1414 if (!c->cache_hash) {
1420 c->block_size = block_size;
1421 c->sectors_per_block_bits = ffs(block_size) - 1 - SECTOR_SHIFT;
1422 c->pages_per_block_bits = (ffs(block_size) - 1 >= PAGE_SHIFT) ?
1423 ffs(block_size) - 1 - PAGE_SHIFT : 0;
1424 c->blocks_per_page_bits = (ffs(block_size) - 1 < PAGE_SHIFT ?
1425 PAGE_SHIFT - (ffs(block_size) - 1) : 0);
1427 c->aux_size = aux_size;
1428 c->alloc_callback = alloc_callback;
1429 c->write_callback = write_callback;
1431 for (i = 0; i < LIST_SIZE; i++) {
1432 INIT_LIST_HEAD(&c->lru[i]);
1433 c->n_buffers[i] = 0;
1436 for (i = 0; i < 1 << DM_BUFIO_HASH_BITS; i++)
1437 INIT_HLIST_HEAD(&c->cache_hash[i]);
1439 mutex_init(&c->lock);
1440 INIT_LIST_HEAD(&c->reserved_buffers);
1441 c->need_reserved_buffers = reserved_buffers;
1443 init_waitqueue_head(&c->free_buffer_wait);
1444 c->async_write_error = 0;
1446 c->dm_io = dm_io_client_create();
1447 if (IS_ERR(c->dm_io)) {
1448 r = PTR_ERR(c->dm_io);
1452 mutex_lock(&dm_bufio_clients_lock);
1453 if (c->blocks_per_page_bits) {
1454 if (!DM_BUFIO_CACHE_NAME(c)) {
1455 DM_BUFIO_CACHE_NAME(c) = kasprintf(GFP_KERNEL, "dm_bufio_cache-%u", c->block_size);
1456 if (!DM_BUFIO_CACHE_NAME(c)) {
1458 mutex_unlock(&dm_bufio_clients_lock);
1463 if (!DM_BUFIO_CACHE(c)) {
1464 DM_BUFIO_CACHE(c) = kmem_cache_create(DM_BUFIO_CACHE_NAME(c),
1466 c->block_size, 0, NULL);
1467 if (!DM_BUFIO_CACHE(c)) {
1469 mutex_unlock(&dm_bufio_clients_lock);
1474 mutex_unlock(&dm_bufio_clients_lock);
1476 while (c->need_reserved_buffers) {
1477 struct dm_buffer *b = alloc_buffer(c, GFP_KERNEL);
1483 __free_buffer_wake(b);
1486 mutex_lock(&dm_bufio_clients_lock);
1487 dm_bufio_client_count++;
1488 list_add(&c->client_list, &dm_bufio_all_clients);
1489 __cache_size_refresh();
1490 mutex_unlock(&dm_bufio_clients_lock);
1492 c->shrinker.shrink = shrink;
1493 c->shrinker.seeks = 1;
1494 c->shrinker.batch = 0;
1495 register_shrinker(&c->shrinker);
1501 while (!list_empty(&c->reserved_buffers)) {
1502 struct dm_buffer *b = list_entry(c->reserved_buffers.next,
1503 struct dm_buffer, lru_list);
1504 list_del(&b->lru_list);
1507 dm_io_client_destroy(c->dm_io);
1509 vfree(c->cache_hash);
1515 EXPORT_SYMBOL_GPL(dm_bufio_client_create);
1518 * Free the buffering interface.
1519 * It is required that there are no references on any buffers.
1521 void dm_bufio_client_destroy(struct dm_bufio_client *c)
1527 unregister_shrinker(&c->shrinker);
1529 mutex_lock(&dm_bufio_clients_lock);
1531 list_del(&c->client_list);
1532 dm_bufio_client_count--;
1533 __cache_size_refresh();
1535 mutex_unlock(&dm_bufio_clients_lock);
1537 for (i = 0; i < 1 << DM_BUFIO_HASH_BITS; i++)
1538 BUG_ON(!hlist_empty(&c->cache_hash[i]));
1540 BUG_ON(c->need_reserved_buffers);
1542 while (!list_empty(&c->reserved_buffers)) {
1543 struct dm_buffer *b = list_entry(c->reserved_buffers.next,
1544 struct dm_buffer, lru_list);
1545 list_del(&b->lru_list);
1549 for (i = 0; i < LIST_SIZE; i++)
1550 if (c->n_buffers[i])
1551 DMERR("leaked buffer count %d: %ld", i, c->n_buffers[i]);
1553 for (i = 0; i < LIST_SIZE; i++)
1554 BUG_ON(c->n_buffers[i]);
1556 dm_io_client_destroy(c->dm_io);
1557 vfree(c->cache_hash);
1560 EXPORT_SYMBOL_GPL(dm_bufio_client_destroy);
1562 static void cleanup_old_buffers(void)
1564 unsigned long max_age = dm_bufio_max_age;
1565 struct dm_bufio_client *c;
1569 if (max_age > ULONG_MAX / HZ)
1570 max_age = ULONG_MAX / HZ;
1572 mutex_lock(&dm_bufio_clients_lock);
1573 list_for_each_entry(c, &dm_bufio_all_clients, client_list) {
1574 if (!dm_bufio_trylock(c))
1577 while (!list_empty(&c->lru[LIST_CLEAN])) {
1578 struct dm_buffer *b;
1579 b = list_entry(c->lru[LIST_CLEAN].prev,
1580 struct dm_buffer, lru_list);
1581 if (__cleanup_old_buffer(b, 0, max_age * HZ))
1583 dm_bufio_cond_resched();
1587 dm_bufio_cond_resched();
1589 mutex_unlock(&dm_bufio_clients_lock);
1592 static struct workqueue_struct *dm_bufio_wq;
1593 static struct delayed_work dm_bufio_work;
1595 static void work_fn(struct work_struct *w)
1597 cleanup_old_buffers();
1599 queue_delayed_work(dm_bufio_wq, &dm_bufio_work,
1600 DM_BUFIO_WORK_TIMER_SECS * HZ);
1603 /*----------------------------------------------------------------
1605 *--------------------------------------------------------------*/
1608 * This is called only once for the whole dm_bufio module.
1609 * It initializes memory limit.
1611 static int __init dm_bufio_init(void)
1615 dm_bufio_allocated_kmem_cache = 0;
1616 dm_bufio_allocated_get_free_pages = 0;
1617 dm_bufio_allocated_vmalloc = 0;
1618 dm_bufio_current_allocated = 0;
1620 memset(&dm_bufio_caches, 0, sizeof dm_bufio_caches);
1621 memset(&dm_bufio_cache_names, 0, sizeof dm_bufio_cache_names);
1623 mem = (__u64)((totalram_pages - totalhigh_pages) *
1624 DM_BUFIO_MEMORY_PERCENT / 100) << PAGE_SHIFT;
1626 if (mem > ULONG_MAX)
1631 * Get the size of vmalloc space the same way as VMALLOC_TOTAL
1632 * in fs/proc/internal.h
1634 if (mem > (VMALLOC_END - VMALLOC_START) * DM_BUFIO_VMALLOC_PERCENT / 100)
1635 mem = (VMALLOC_END - VMALLOC_START) * DM_BUFIO_VMALLOC_PERCENT / 100;
1638 dm_bufio_default_cache_size = mem;
1640 mutex_lock(&dm_bufio_clients_lock);
1641 __cache_size_refresh();
1642 mutex_unlock(&dm_bufio_clients_lock);
1644 dm_bufio_wq = create_singlethread_workqueue("dm_bufio_cache");
1648 INIT_DELAYED_WORK(&dm_bufio_work, work_fn);
1649 queue_delayed_work(dm_bufio_wq, &dm_bufio_work,
1650 DM_BUFIO_WORK_TIMER_SECS * HZ);
1656 * This is called once when unloading the dm_bufio module.
1658 static void __exit dm_bufio_exit(void)
1663 cancel_delayed_work_sync(&dm_bufio_work);
1664 destroy_workqueue(dm_bufio_wq);
1666 for (i = 0; i < ARRAY_SIZE(dm_bufio_caches); i++) {
1667 struct kmem_cache *kc = dm_bufio_caches[i];
1670 kmem_cache_destroy(kc);
1673 for (i = 0; i < ARRAY_SIZE(dm_bufio_cache_names); i++)
1674 kfree(dm_bufio_cache_names[i]);
1676 if (dm_bufio_client_count) {
1677 DMCRIT("%s: dm_bufio_client_count leaked: %d",
1678 __func__, dm_bufio_client_count);
1682 if (dm_bufio_current_allocated) {
1683 DMCRIT("%s: dm_bufio_current_allocated leaked: %lu",
1684 __func__, dm_bufio_current_allocated);
1688 if (dm_bufio_allocated_get_free_pages) {
1689 DMCRIT("%s: dm_bufio_allocated_get_free_pages leaked: %lu",
1690 __func__, dm_bufio_allocated_get_free_pages);
1694 if (dm_bufio_allocated_vmalloc) {
1695 DMCRIT("%s: dm_bufio_vmalloc leaked: %lu",
1696 __func__, dm_bufio_allocated_vmalloc);
1704 module_init(dm_bufio_init)
1705 module_exit(dm_bufio_exit)
1707 module_param_named(max_cache_size_bytes, dm_bufio_cache_size, ulong, S_IRUGO | S_IWUSR);
1708 MODULE_PARM_DESC(max_cache_size_bytes, "Size of metadata cache");
1710 module_param_named(max_age_seconds, dm_bufio_max_age, uint, S_IRUGO | S_IWUSR);
1711 MODULE_PARM_DESC(max_age_seconds, "Max age of a buffer in seconds");
1713 module_param_named(peak_allocated_bytes, dm_bufio_peak_allocated, ulong, S_IRUGO | S_IWUSR);
1714 MODULE_PARM_DESC(peak_allocated_bytes, "Tracks the maximum allocated memory");
1716 module_param_named(allocated_kmem_cache_bytes, dm_bufio_allocated_kmem_cache, ulong, S_IRUGO);
1717 MODULE_PARM_DESC(allocated_kmem_cache_bytes, "Memory allocated with kmem_cache_alloc");
1719 module_param_named(allocated_get_free_pages_bytes, dm_bufio_allocated_get_free_pages, ulong, S_IRUGO);
1720 MODULE_PARM_DESC(allocated_get_free_pages_bytes, "Memory allocated with get_free_pages");
1722 module_param_named(allocated_vmalloc_bytes, dm_bufio_allocated_vmalloc, ulong, S_IRUGO);
1723 MODULE_PARM_DESC(allocated_vmalloc_bytes, "Memory allocated with vmalloc");
1725 module_param_named(current_allocated_bytes, dm_bufio_current_allocated, ulong, S_IRUGO);
1726 MODULE_PARM_DESC(current_allocated_bytes, "Memory currently used by the cache");
1728 MODULE_AUTHOR("Mikulas Patocka <dm-devel@redhat.com>");
1729 MODULE_DESCRIPTION(DM_NAME " buffered I/O library");
1730 MODULE_LICENSE("GPL");