Linux 3.2.82
[pandora-kernel.git] / drivers / md / dm-bufio.c
1 /*
2  * Copyright (C) 2009-2011 Red Hat, Inc.
3  *
4  * Author: Mikulas Patocka <mpatocka@redhat.com>
5  *
6  * This file is released under the GPL.
7  */
8
9 #include "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/version.h>
16 #include <linux/shrinker.h>
17 #include <linux/module.h>
18
19 #define DM_MSG_PREFIX "bufio"
20
21 /*
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
27  *      dirty buffers.
28  */
29 #define DM_BUFIO_MIN_BUFFERS            8
30
31 #define DM_BUFIO_MEMORY_PERCENT         2
32 #define DM_BUFIO_VMALLOC_PERCENT        25
33 #define DM_BUFIO_WRITEBACK_PERCENT      75
34
35 /*
36  * Check buffer ages in this interval (seconds)
37  */
38 #define DM_BUFIO_WORK_TIMER_SECS        10
39
40 /*
41  * Free buffers when they are older than this (seconds)
42  */
43 #define DM_BUFIO_DEFAULT_AGE_SECS       60
44
45 /*
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.
48  */
49 #define DM_BUFIO_INLINE_VECS            16
50
51 /*
52  * Buffer hash
53  */
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))
58
59 /*
60  * Don't try to use kmem_cache_alloc for blocks larger than this.
61  * For explanation, see alloc_buffer_data below.
62  */
63 #define DM_BUFIO_BLOCK_SIZE_SLAB_LIMIT  (PAGE_SIZE >> 1)
64 #define DM_BUFIO_BLOCK_SIZE_GFP_LIMIT   (PAGE_SIZE << (MAX_ORDER - 1))
65
66 /*
67  * dm_buffer->list_mode
68  */
69 #define LIST_CLEAN      0
70 #define LIST_DIRTY      1
71 #define LIST_SIZE       2
72
73 /*
74  * Linking of buffers:
75  *      All buffers are linked to cache_hash with their hash_list field.
76  *
77  *      Clean buffers that are not being written (B_WRITING not set)
78  *      are linked to lru[LIST_CLEAN] with their lru_list field.
79  *
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
86  *      context.
87  */
88 struct dm_bufio_client {
89         struct mutex lock;
90
91         struct list_head lru[LIST_SIZE];
92         unsigned long n_buffers[LIST_SIZE];
93
94         struct block_device *bdev;
95         unsigned block_size;
96         unsigned char sectors_per_block_bits;
97         unsigned char pages_per_block_bits;
98         unsigned char blocks_per_page_bits;
99         unsigned aux_size;
100         void (*alloc_callback)(struct dm_buffer *);
101         void (*write_callback)(struct dm_buffer *);
102
103         struct dm_io_client *dm_io;
104
105         struct list_head reserved_buffers;
106         unsigned need_reserved_buffers;
107
108         struct hlist_head *cache_hash;
109         wait_queue_head_t free_buffer_wait;
110
111         int async_write_error;
112
113         struct list_head client_list;
114         struct shrinker shrinker;
115 };
116
117 /*
118  * Buffer state bits.
119  */
120 #define B_READING       0
121 #define B_WRITING       1
122 #define B_DIRTY         2
123
124 /*
125  * Describes how the block was allocated:
126  * kmem_cache_alloc(), __get_free_pages() or vmalloc().
127  * See the comment at alloc_buffer_data.
128  */
129 enum data_mode {
130         DATA_MODE_SLAB = 0,
131         DATA_MODE_GET_FREE_PAGES = 1,
132         DATA_MODE_VMALLOC = 2,
133         DATA_MODE_LIMIT = 3
134 };
135
136 struct dm_buffer {
137         struct hlist_node hash_list;
138         struct list_head lru_list;
139         sector_t block;
140         void *data;
141         enum data_mode data_mode;
142         unsigned char list_mode;                /* LIST_* */
143         unsigned hold_count;
144         int read_error;
145         int write_error;
146         unsigned long state;
147         unsigned long last_accessed;
148         struct dm_bufio_client *c;
149         struct bio bio;
150         struct bio_vec bio_vec[DM_BUFIO_INLINE_VECS];
151 };
152
153 /*----------------------------------------------------------------*/
154
155 static struct kmem_cache *dm_bufio_caches[PAGE_SHIFT - SECTOR_SHIFT];
156 static char *dm_bufio_cache_names[PAGE_SHIFT - SECTOR_SHIFT];
157
158 static inline int dm_bufio_cache_index(struct dm_bufio_client *c)
159 {
160         unsigned ret = c->blocks_per_page_bits - 1;
161
162         BUG_ON(ret >= ARRAY_SIZE(dm_bufio_caches));
163
164         return ret;
165 }
166
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)])
169
170 #define dm_bufio_in_request()   (!!current->bio_list)
171
172 static void dm_bufio_lock(struct dm_bufio_client *c)
173 {
174         mutex_lock_nested(&c->lock, dm_bufio_in_request());
175 }
176
177 static int dm_bufio_trylock(struct dm_bufio_client *c)
178 {
179         return mutex_trylock(&c->lock);
180 }
181
182 static void dm_bufio_unlock(struct dm_bufio_client *c)
183 {
184         mutex_unlock(&c->lock);
185 }
186
187 /*
188  * FIXME Move to sched.h?
189  */
190 #ifdef CONFIG_PREEMPT_VOLUNTARY
191 #  define dm_bufio_cond_resched()               \
192 do {                                            \
193         if (unlikely(need_resched()))           \
194                 _cond_resched();                \
195 } while (0)
196 #else
197 #  define dm_bufio_cond_resched()                do { } while (0)
198 #endif
199
200 /*----------------------------------------------------------------*/
201
202 /*
203  * Default cache size: available memory divided by the ratio.
204  */
205 static unsigned long dm_bufio_default_cache_size;
206
207 /*
208  * Total cache size set by the user.
209  */
210 static unsigned long dm_bufio_cache_size;
211
212 /*
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.
215  */
216 static unsigned long dm_bufio_cache_size_latch;
217
218 static DEFINE_SPINLOCK(param_spinlock);
219
220 /*
221  * Buffers are freed after this timeout
222  */
223 static unsigned dm_bufio_max_age = DM_BUFIO_DEFAULT_AGE_SECS;
224
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;
230
231 /*----------------------------------------------------------------*/
232
233 /*
234  * Per-client cache: dm_bufio_cache_size / dm_bufio_client_count
235  */
236 static unsigned long dm_bufio_cache_size_per_client;
237
238 /*
239  * The current number of clients.
240  */
241 static int dm_bufio_client_count;
242
243 /*
244  * The list of all clients.
245  */
246 static LIST_HEAD(dm_bufio_all_clients);
247
248 /*
249  * This mutex protects dm_bufio_cache_size_latch,
250  * dm_bufio_cache_size_per_client and dm_bufio_client_count
251  */
252 static DEFINE_MUTEX(dm_bufio_clients_lock);
253
254 /*----------------------------------------------------------------*/
255
256 static void adjust_total_allocated(enum data_mode data_mode, long diff)
257 {
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,
262         };
263
264         spin_lock(&param_spinlock);
265
266         *class_ptr[data_mode] += diff;
267
268         dm_bufio_current_allocated += diff;
269
270         if (dm_bufio_current_allocated > dm_bufio_peak_allocated)
271                 dm_bufio_peak_allocated = dm_bufio_current_allocated;
272
273         spin_unlock(&param_spinlock);
274 }
275
276 /*
277  * Change the number of clients and recalculate per-client limit.
278  */
279 static void __cache_size_refresh(void)
280 {
281         BUG_ON(!mutex_is_locked(&dm_bufio_clients_lock));
282         BUG_ON(dm_bufio_client_count < 0);
283
284         dm_bufio_cache_size_latch = dm_bufio_cache_size;
285
286         barrier();
287
288         /*
289          * Use default if set to 0 and report the actual cache size used.
290          */
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;
295         }
296
297         dm_bufio_cache_size_per_client = dm_bufio_cache_size_latch /
298                                          (dm_bufio_client_count ? : 1);
299 }
300
301 /*
302  * Allocating buffer data.
303  *
304  * Small buffers are allocated with kmem_cache, to use space optimally.
305  *
306  * For large buffers, we choose between get_free_pages and vmalloc.
307  * Each has advantages and disadvantages.
308  *
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.
312  *
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).
317  *
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
320  * space.
321  */
322 static void *alloc_buffer_data(struct dm_bufio_client *c, gfp_t gfp_mask,
323                                enum data_mode *data_mode)
324 {
325         unsigned noio_flag;
326         void *ptr;
327
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);
331         }
332
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);
338         }
339
340         *data_mode = DATA_MODE_VMALLOC;
341
342         /*
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.
346          *
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.
350          */
351
352         if (gfp_mask & __GFP_NORETRY) {
353                 noio_flag = current->flags & PF_MEMALLOC;
354                 current->flags |= PF_MEMALLOC;
355         }
356
357         ptr = __vmalloc(c->block_size, gfp_mask, PAGE_KERNEL);
358
359         if (gfp_mask & __GFP_NORETRY)
360                 current->flags = (current->flags & ~PF_MEMALLOC) | noio_flag;
361
362         return ptr;
363 }
364
365 /*
366  * Free buffer's data.
367  */
368 static void free_buffer_data(struct dm_bufio_client *c,
369                              void *data, enum data_mode data_mode)
370 {
371         switch (data_mode) {
372         case DATA_MODE_SLAB:
373                 kmem_cache_free(DM_BUFIO_CACHE(c), data);
374                 break;
375
376         case DATA_MODE_GET_FREE_PAGES:
377                 free_pages((unsigned long)data, c->pages_per_block_bits);
378                 break;
379
380         case DATA_MODE_VMALLOC:
381                 vfree(data);
382                 break;
383
384         default:
385                 DMCRIT("dm_bufio_free_buffer_data: bad data mode: %d",
386                        data_mode);
387                 BUG();
388         }
389 }
390
391 /*
392  * Allocate buffer and its data.
393  */
394 static struct dm_buffer *alloc_buffer(struct dm_bufio_client *c, gfp_t gfp_mask)
395 {
396         struct dm_buffer *b = kmalloc(sizeof(struct dm_buffer) + c->aux_size,
397                                       gfp_mask);
398
399         if (!b)
400                 return NULL;
401
402         b->c = c;
403
404         b->data = alloc_buffer_data(c, gfp_mask, &b->data_mode);
405         if (!b->data) {
406                 kfree(b);
407                 return NULL;
408         }
409
410         adjust_total_allocated(b->data_mode, (long)c->block_size);
411
412         return b;
413 }
414
415 /*
416  * Free buffer and its data.
417  */
418 static void free_buffer(struct dm_buffer *b)
419 {
420         struct dm_bufio_client *c = b->c;
421
422         adjust_total_allocated(b->data_mode, -(long)c->block_size);
423
424         free_buffer_data(c, b->data, b->data_mode);
425         kfree(b);
426 }
427
428 /*
429  * Link buffer to the hash list and clean or dirty queue.
430  */
431 static void __link_buffer(struct dm_buffer *b, sector_t block, int dirty)
432 {
433         struct dm_bufio_client *c = b->c;
434
435         c->n_buffers[dirty]++;
436         b->block = block;
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;
441 }
442
443 /*
444  * Unlink buffer from the hash list and dirty or clean queue.
445  */
446 static void __unlink_buffer(struct dm_buffer *b)
447 {
448         struct dm_bufio_client *c = b->c;
449
450         BUG_ON(!c->n_buffers[b->list_mode]);
451
452         c->n_buffers[b->list_mode]--;
453         hlist_del(&b->hash_list);
454         list_del(&b->lru_list);
455 }
456
457 /*
458  * Place the buffer to the head of dirty or clean LRU queue.
459  */
460 static void __relink_lru(struct dm_buffer *b, int dirty)
461 {
462         struct dm_bufio_client *c = b->c;
463
464         BUG_ON(!c->n_buffers[b->list_mode]);
465
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;
472 }
473
474 /*----------------------------------------------------------------
475  * Submit I/O on the buffer.
476  *
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);
480  *
481  *      the memory must be direct-mapped, not vmalloced;
482  *
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.
486  *
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.
489  *
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
493  * shortcomings.
494  *--------------------------------------------------------------*/
495
496 /*
497  * dm-io completion routine. It just calls b->bio.bi_end_io, pretending
498  * that the request was handled directly with bio interface.
499  */
500 static void dmio_complete(unsigned long error, void *context)
501 {
502         struct dm_buffer *b = context;
503
504         b->bio.bi_end_io(&b->bio, error ? -EIO : 0);
505 }
506
507 static void use_dmio(struct dm_buffer *b, int rw, sector_t block,
508                      bio_end_io_t *end_io)
509 {
510         int r;
511         struct dm_io_request io_req = {
512                 .bi_rw = rw,
513                 .notify.fn = dmio_complete,
514                 .notify.context = b,
515                 .client = b->c->dm_io,
516         };
517         struct dm_io_region region = {
518                 .bdev = b->c->bdev,
519                 .sector = block << b->c->sectors_per_block_bits,
520                 .count = b->c->block_size >> SECTOR_SHIFT,
521         };
522
523         if (b->data_mode != DATA_MODE_VMALLOC) {
524                 io_req.mem.type = DM_IO_KMEM;
525                 io_req.mem.ptr.addr = b->data;
526         } else {
527                 io_req.mem.type = DM_IO_VMA;
528                 io_req.mem.ptr.vma = b->data;
529         }
530
531         b->bio.bi_end_io = end_io;
532
533         r = dm_io(&io_req, 1, &region, NULL);
534         if (r)
535                 end_io(&b->bio, r);
536 }
537
538 static void use_inline_bio(struct dm_buffer *b, int rw, sector_t block,
539                            bio_end_io_t *end_io)
540 {
541         char *ptr;
542         int len;
543
544         bio_init(&b->bio);
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;
550
551         /*
552          * We assume that if len >= PAGE_SIZE ptr is page-aligned.
553          * If len < PAGE_SIZE the buffer doesn't cross page boundary.
554          */
555         ptr = b->data;
556         len = b->c->block_size;
557
558         if (len >= PAGE_SIZE)
559                 BUG_ON((unsigned long)ptr & (PAGE_SIZE - 1));
560         else
561                 BUG_ON((unsigned long)ptr & (len - 1));
562
563         do {
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);
569                         return;
570                 }
571
572                 len -= PAGE_SIZE;
573                 ptr += PAGE_SIZE;
574         } while (len > 0);
575
576         submit_bio(rw, &b->bio);
577 }
578
579 static void submit_io(struct dm_buffer *b, int rw, sector_t block,
580                       bio_end_io_t *end_io)
581 {
582         if (rw == WRITE && b->c->write_callback)
583                 b->c->write_callback(b);
584
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);
588         else
589                 use_dmio(b, rw, block, end_io);
590 }
591
592 /*----------------------------------------------------------------
593  * Writing dirty buffers
594  *--------------------------------------------------------------*/
595
596 /*
597  * The endio routine for write.
598  *
599  * Set the error, clear B_WRITING bit and wake anyone who was waiting on
600  * it.
601  */
602 static void write_endio(struct bio *bio, int error)
603 {
604         struct dm_buffer *b = container_of(bio, struct dm_buffer, bio);
605
606         b->write_error = error;
607         if (error) {
608                 struct dm_bufio_client *c = b->c;
609                 (void)cmpxchg(&c->async_write_error, 0, error);
610         }
611
612         BUG_ON(!test_bit(B_WRITING, &b->state));
613
614         smp_mb__before_clear_bit();
615         clear_bit(B_WRITING, &b->state);
616         smp_mb__after_clear_bit();
617
618         wake_up_bit(&b->state, B_WRITING);
619 }
620
621 /*
622  * This function is called when wait_on_bit is actually waiting.
623  */
624 static int do_io_schedule(void *word)
625 {
626         io_schedule();
627
628         return 0;
629 }
630
631 /*
632  * Initiate a write on a dirty buffer, but don't wait for it.
633  *
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.
639  */
640 static void __write_dirty_buffer(struct dm_buffer *b)
641 {
642         if (!test_bit(B_DIRTY, &b->state))
643                 return;
644
645         clear_bit(B_DIRTY, &b->state);
646         wait_on_bit_lock(&b->state, B_WRITING,
647                          do_io_schedule, TASK_UNINTERRUPTIBLE);
648
649         submit_io(b, WRITE, b->block, write_endio);
650 }
651
652 /*
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.
656  */
657 static void __make_buffer_clean(struct dm_buffer *b)
658 {
659         BUG_ON(b->hold_count);
660
661         if (!b->state)  /* fast case */
662                 return;
663
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);
667 }
668
669 /*
670  * Find some buffer that is not held by anybody, clean it, unlink it and
671  * return it.
672  */
673 static struct dm_buffer *__get_unclaimed_buffer(struct dm_bufio_client *c)
674 {
675         struct dm_buffer *b;
676
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));
680
681                 if (!b->hold_count) {
682                         __make_buffer_clean(b);
683                         __unlink_buffer(b);
684                         return b;
685                 }
686                 dm_bufio_cond_resched();
687         }
688
689         list_for_each_entry_reverse(b, &c->lru[LIST_DIRTY], lru_list) {
690                 BUG_ON(test_bit(B_READING, &b->state));
691
692                 if (!b->hold_count) {
693                         __make_buffer_clean(b);
694                         __unlink_buffer(b);
695                         return b;
696                 }
697                 dm_bufio_cond_resched();
698         }
699
700         return NULL;
701 }
702
703 /*
704  * Wait until some other threads free some buffer or release hold count on
705  * some buffer.
706  *
707  * This function is entered with c->lock held, drops it and regains it
708  * before exiting.
709  */
710 static void __wait_for_free_buffer(struct dm_bufio_client *c)
711 {
712         DECLARE_WAITQUEUE(wait, current);
713
714         add_wait_queue(&c->free_buffer_wait, &wait);
715         set_task_state(current, TASK_UNINTERRUPTIBLE);
716         dm_bufio_unlock(c);
717
718         io_schedule();
719
720         set_task_state(current, TASK_RUNNING);
721         remove_wait_queue(&c->free_buffer_wait, &wait);
722
723         dm_bufio_lock(c);
724 }
725
726 /*
727  * Allocate a new buffer. If the allocation is not possible, wait until
728  * some other thread frees a buffer.
729  *
730  * May drop the lock and regain it.
731  */
732 static struct dm_buffer *__alloc_buffer_wait_no_callback(struct dm_bufio_client *c)
733 {
734         struct dm_buffer *b;
735
736         /*
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
744          *
745          * For debugging, if we set the cache size to 1, no new buffers will
746          * be allocated.
747          */
748         while (1) {
749                 if (dm_bufio_cache_size_latch != 1) {
750                         b = alloc_buffer(c, GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
751                         if (b)
752                                 return b;
753                 }
754
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++;
760
761                         return b;
762                 }
763
764                 b = __get_unclaimed_buffer(c);
765                 if (b)
766                         return b;
767
768                 __wait_for_free_buffer(c);
769         }
770 }
771
772 static struct dm_buffer *__alloc_buffer_wait(struct dm_bufio_client *c)
773 {
774         struct dm_buffer *b = __alloc_buffer_wait_no_callback(c);
775
776         if (c->alloc_callback)
777                 c->alloc_callback(b);
778
779         return b;
780 }
781
782 /*
783  * Free a buffer and wake other threads waiting for free buffers.
784  */
785 static void __free_buffer_wake(struct dm_buffer *b)
786 {
787         struct dm_bufio_client *c = b->c;
788
789         if (!c->need_reserved_buffers)
790                 free_buffer(b);
791         else {
792                 list_add(&b->lru_list, &c->reserved_buffers);
793                 c->need_reserved_buffers--;
794         }
795
796         wake_up(&c->free_buffer_wait);
797 }
798
799 static void __write_dirty_buffers_async(struct dm_bufio_client *c, int no_wait)
800 {
801         struct dm_buffer *b, *tmp;
802
803         list_for_each_entry_safe_reverse(b, tmp, &c->lru[LIST_DIRTY], lru_list) {
804                 BUG_ON(test_bit(B_READING, &b->state));
805
806                 if (!test_bit(B_DIRTY, &b->state) &&
807                     !test_bit(B_WRITING, &b->state)) {
808                         __relink_lru(b, LIST_CLEAN);
809                         continue;
810                 }
811
812                 if (no_wait && test_bit(B_WRITING, &b->state))
813                         return;
814
815                 __write_dirty_buffer(b);
816                 dm_bufio_cond_resched();
817         }
818 }
819
820 /*
821  * Get writeback threshold and buffer limit for a given client.
822  */
823 static void __get_memory_limit(struct dm_bufio_client *c,
824                                unsigned long *threshold_buffers,
825                                unsigned long *limit_buffers)
826 {
827         unsigned long buffers;
828
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);
833         }
834
835         buffers = dm_bufio_cache_size_per_client >>
836                   (c->sectors_per_block_bits + SECTOR_SHIFT);
837
838         if (buffers < DM_BUFIO_MIN_BUFFERS)
839                 buffers = DM_BUFIO_MIN_BUFFERS;
840
841         *limit_buffers = buffers;
842         *threshold_buffers = buffers * DM_BUFIO_WRITEBACK_PERCENT / 100;
843 }
844
845 /*
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.
849  */
850 static void __check_watermark(struct dm_bufio_client *c)
851 {
852         unsigned long threshold_buffers, limit_buffers;
853
854         __get_memory_limit(c, &threshold_buffers, &limit_buffers);
855
856         while (c->n_buffers[LIST_CLEAN] + c->n_buffers[LIST_DIRTY] >
857                limit_buffers) {
858
859                 struct dm_buffer *b = __get_unclaimed_buffer(c);
860
861                 if (!b)
862                         return;
863
864                 __free_buffer_wake(b);
865                 dm_bufio_cond_resched();
866         }
867
868         if (c->n_buffers[LIST_DIRTY] > threshold_buffers)
869                 __write_dirty_buffers_async(c, 1);
870 }
871
872 /*
873  * Find a buffer in the hash.
874  */
875 static struct dm_buffer *__find(struct dm_bufio_client *c, sector_t block)
876 {
877         struct dm_buffer *b;
878         struct hlist_node *hn;
879
880         hlist_for_each_entry(b, hn, &c->cache_hash[DM_BUFIO_HASH(block)],
881                              hash_list) {
882                 dm_bufio_cond_resched();
883                 if (b->block == block)
884                         return b;
885         }
886
887         return NULL;
888 }
889
890 /*----------------------------------------------------------------
891  * Getting a buffer
892  *--------------------------------------------------------------*/
893
894 enum new_flag {
895         NF_FRESH = 0,
896         NF_READ = 1,
897         NF_GET = 2
898 };
899
900 static struct dm_buffer *__bufio_new(struct dm_bufio_client *c, sector_t block,
901                                      enum new_flag nf, struct dm_buffer **bp,
902                                      int *need_submit)
903 {
904         struct dm_buffer *b, *new_b = NULL;
905
906         *need_submit = 0;
907
908         b = __find(c, block);
909         if (b) {
910                 b->hold_count++;
911                 __relink_lru(b, test_bit(B_DIRTY, &b->state) ||
912                              test_bit(B_WRITING, &b->state));
913                 return b;
914         }
915
916         if (nf == NF_GET)
917                 return NULL;
918
919         new_b = __alloc_buffer_wait(c);
920
921         /*
922          * We've had a period where the mutex was unlocked, so need to
923          * recheck the hash table.
924          */
925         b = __find(c, block);
926         if (b) {
927                 __free_buffer_wake(new_b);
928                 b->hold_count++;
929                 __relink_lru(b, test_bit(B_DIRTY, &b->state) ||
930                              test_bit(B_WRITING, &b->state));
931                 return b;
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 }
952
953 /*
954  * The endio routine for reading: set the error, clear the bit and wake up
955  * anyone waiting on the buffer.
956  */
957 static void read_endio(struct bio *bio, int error)
958 {
959         struct dm_buffer *b = container_of(bio, struct dm_buffer, bio);
960
961         b->read_error = error;
962
963         BUG_ON(!test_bit(B_READING, &b->state));
964
965         smp_mb__before_clear_bit();
966         clear_bit(B_READING, &b->state);
967         smp_mb__after_clear_bit();
968
969         wake_up_bit(&b->state, B_READING);
970 }
971
972 /*
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).
977  */
978 static void *new_read(struct dm_bufio_client *c, sector_t block,
979                       enum new_flag nf, struct dm_buffer **bp)
980 {
981         int need_submit;
982         struct dm_buffer *b;
983
984         dm_bufio_lock(c);
985         b = __bufio_new(c, block, nf, bp, &need_submit);
986         dm_bufio_unlock(c);
987
988         if (!b || IS_ERR(b))
989                 return b;
990
991         if (need_submit)
992                 submit_io(b, READ, b->block, read_endio);
993
994         wait_on_bit(&b->state, B_READING, do_io_schedule, TASK_UNINTERRUPTIBLE);
995
996         if (b->read_error) {
997                 int error = b->read_error;
998
999                 dm_bufio_release(b);
1000
1001                 return ERR_PTR(error);
1002         }
1003
1004         *bp = b;
1005
1006         return b->data;
1007 }
1008
1009 void *dm_bufio_get(struct dm_bufio_client *c, sector_t block,
1010                    struct dm_buffer **bp)
1011 {
1012         return new_read(c, block, NF_GET, bp);
1013 }
1014 EXPORT_SYMBOL_GPL(dm_bufio_get);
1015
1016 void *dm_bufio_read(struct dm_bufio_client *c, sector_t block,
1017                     struct dm_buffer **bp)
1018 {
1019         BUG_ON(dm_bufio_in_request());
1020
1021         return new_read(c, block, NF_READ, bp);
1022 }
1023 EXPORT_SYMBOL_GPL(dm_bufio_read);
1024
1025 void *dm_bufio_new(struct dm_bufio_client *c, sector_t block,
1026                    struct dm_buffer **bp)
1027 {
1028         BUG_ON(dm_bufio_in_request());
1029
1030         return new_read(c, block, NF_FRESH, bp);
1031 }
1032 EXPORT_SYMBOL_GPL(dm_bufio_new);
1033
1034 void dm_bufio_release(struct dm_buffer *b)
1035 {
1036         struct dm_bufio_client *c = b->c;
1037
1038         dm_bufio_lock(c);
1039
1040         BUG_ON(test_bit(B_READING, &b->state));
1041         BUG_ON(!b->hold_count);
1042
1043         b->hold_count--;
1044         if (!b->hold_count) {
1045                 wake_up(&c->free_buffer_wait);
1046
1047                 /*
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
1050                  * invalid buffer.
1051                  */
1052                 if ((b->read_error || b->write_error) &&
1053                     !test_bit(B_WRITING, &b->state) &&
1054                     !test_bit(B_DIRTY, &b->state)) {
1055                         __unlink_buffer(b);
1056                         __free_buffer_wake(b);
1057                 }
1058         }
1059
1060         dm_bufio_unlock(c);
1061 }
1062 EXPORT_SYMBOL_GPL(dm_bufio_release);
1063
1064 void dm_bufio_mark_buffer_dirty(struct dm_buffer *b)
1065 {
1066         struct dm_bufio_client *c = b->c;
1067
1068         dm_bufio_lock(c);
1069
1070         if (!test_and_set_bit(B_DIRTY, &b->state))
1071                 __relink_lru(b, LIST_DIRTY);
1072
1073         dm_bufio_unlock(c);
1074 }
1075 EXPORT_SYMBOL_GPL(dm_bufio_mark_buffer_dirty);
1076
1077 void dm_bufio_write_dirty_buffers_async(struct dm_bufio_client *c)
1078 {
1079         BUG_ON(dm_bufio_in_request());
1080
1081         dm_bufio_lock(c);
1082         __write_dirty_buffers_async(c, 0);
1083         dm_bufio_unlock(c);
1084 }
1085 EXPORT_SYMBOL_GPL(dm_bufio_write_dirty_buffers_async);
1086
1087 /*
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
1090  * waited upon.
1091  *
1092  * Finally, we flush hardware disk cache.
1093  */
1094 int dm_bufio_write_dirty_buffers(struct dm_bufio_client *c)
1095 {
1096         int a, f;
1097         unsigned long buffers_processed = 0;
1098         struct dm_buffer *b, *tmp;
1099
1100         dm_bufio_lock(c);
1101         __write_dirty_buffers_async(c, 0);
1102
1103 again:
1104         list_for_each_entry_safe_reverse(b, tmp, &c->lru[LIST_DIRTY], lru_list) {
1105                 int dropped_lock = 0;
1106
1107                 if (buffers_processed < c->n_buffers[LIST_DIRTY])
1108                         buffers_processed++;
1109
1110                 BUG_ON(test_bit(B_READING, &b->state));
1111
1112                 if (test_bit(B_WRITING, &b->state)) {
1113                         if (buffers_processed < c->n_buffers[LIST_DIRTY]) {
1114                                 dropped_lock = 1;
1115                                 b->hold_count++;
1116                                 dm_bufio_unlock(c);
1117                                 wait_on_bit(&b->state, B_WRITING,
1118                                             do_io_schedule,
1119                                             TASK_UNINTERRUPTIBLE);
1120                                 dm_bufio_lock(c);
1121                                 b->hold_count--;
1122                         } else
1123                                 wait_on_bit(&b->state, B_WRITING,
1124                                             do_io_schedule,
1125                                             TASK_UNINTERRUPTIBLE);
1126                 }
1127
1128                 if (!test_bit(B_DIRTY, &b->state) &&
1129                     !test_bit(B_WRITING, &b->state))
1130                         __relink_lru(b, LIST_CLEAN);
1131
1132                 dm_bufio_cond_resched();
1133
1134                 /*
1135                  * If we dropped the lock, the list is no longer consistent,
1136                  * so we must restart the search.
1137                  *
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.
1141                  *
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.
1147                  */
1148                 if (dropped_lock)
1149                         goto again;
1150         }
1151         wake_up(&c->free_buffer_wait);
1152         dm_bufio_unlock(c);
1153
1154         a = xchg(&c->async_write_error, 0);
1155         f = dm_bufio_issue_flush(c);
1156         if (a)
1157                 return a;
1158
1159         return f;
1160 }
1161 EXPORT_SYMBOL_GPL(dm_bufio_write_dirty_buffers);
1162
1163 /*
1164  * Use dm-io to send and empty barrier flush the device.
1165  */
1166 int dm_bufio_issue_flush(struct dm_bufio_client *c)
1167 {
1168         struct dm_io_request io_req = {
1169                 .bi_rw = REQ_FLUSH,
1170                 .mem.type = DM_IO_KMEM,
1171                 .mem.ptr.addr = NULL,
1172                 .client = c->dm_io,
1173         };
1174         struct dm_io_region io_reg = {
1175                 .bdev = c->bdev,
1176                 .sector = 0,
1177                 .count = 0,
1178         };
1179
1180         BUG_ON(dm_bufio_in_request());
1181
1182         return dm_io(&io_req, 1, &io_reg, NULL);
1183 }
1184 EXPORT_SYMBOL_GPL(dm_bufio_issue_flush);
1185
1186 /*
1187  * We first delete any other buffer that may be at that new location.
1188  *
1189  * Then, we write the buffer to the original location if it was dirty.
1190  *
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.
1193  *
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.
1197  */
1198 void dm_bufio_release_move(struct dm_buffer *b, sector_t new_block)
1199 {
1200         struct dm_bufio_client *c = b->c;
1201         struct dm_buffer *new;
1202
1203         BUG_ON(dm_bufio_in_request());
1204
1205         dm_bufio_lock(c);
1206
1207 retry:
1208         new = __find(c, new_block);
1209         if (new) {
1210                 if (new->hold_count) {
1211                         __wait_for_free_buffer(c);
1212                         goto retry;
1213                 }
1214
1215                 /*
1216                  * FIXME: Is there any point waiting for a write that's going
1217                  * to be overwritten in a bit?
1218                  */
1219                 __make_buffer_clean(new);
1220                 __unlink_buffer(new);
1221                 __free_buffer_wake(new);
1222         }
1223
1224         BUG_ON(!b->hold_count);
1225         BUG_ON(test_bit(B_READING, &b->state));
1226
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);
1232                 __unlink_buffer(b);
1233                 __link_buffer(b, new_block, LIST_DIRTY);
1234         } else {
1235                 sector_t old_block;
1236                 wait_on_bit_lock(&b->state, B_WRITING,
1237                                  do_io_schedule, TASK_UNINTERRUPTIBLE);
1238                 /*
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.
1244                  */
1245                 old_block = b->block;
1246                 __unlink_buffer(b);
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);
1251                 __unlink_buffer(b);
1252                 __link_buffer(b, old_block, b->list_mode);
1253         }
1254
1255         dm_bufio_unlock(c);
1256         dm_bufio_release(b);
1257 }
1258 EXPORT_SYMBOL_GPL(dm_bufio_release_move);
1259
1260 unsigned dm_bufio_get_block_size(struct dm_bufio_client *c)
1261 {
1262         return c->block_size;
1263 }
1264 EXPORT_SYMBOL_GPL(dm_bufio_get_block_size);
1265
1266 sector_t dm_bufio_get_device_size(struct dm_bufio_client *c)
1267 {
1268         return i_size_read(c->bdev->bd_inode) >>
1269                            (SECTOR_SHIFT + c->sectors_per_block_bits);
1270 }
1271 EXPORT_SYMBOL_GPL(dm_bufio_get_device_size);
1272
1273 sector_t dm_bufio_get_block_number(struct dm_buffer *b)
1274 {
1275         return b->block;
1276 }
1277 EXPORT_SYMBOL_GPL(dm_bufio_get_block_number);
1278
1279 void *dm_bufio_get_block_data(struct dm_buffer *b)
1280 {
1281         return b->data;
1282 }
1283 EXPORT_SYMBOL_GPL(dm_bufio_get_block_data);
1284
1285 void *dm_bufio_get_aux_data(struct dm_buffer *b)
1286 {
1287         return b + 1;
1288 }
1289 EXPORT_SYMBOL_GPL(dm_bufio_get_aux_data);
1290
1291 struct dm_bufio_client *dm_bufio_get_client(struct dm_buffer *b)
1292 {
1293         return b->c;
1294 }
1295 EXPORT_SYMBOL_GPL(dm_bufio_get_client);
1296
1297 static void drop_buffers(struct dm_bufio_client *c)
1298 {
1299         struct dm_buffer *b;
1300         int i;
1301
1302         BUG_ON(dm_bufio_in_request());
1303
1304         /*
1305          * An optimization so that the buffers are not written one-by-one.
1306          */
1307         dm_bufio_write_dirty_buffers_async(c);
1308
1309         dm_bufio_lock(c);
1310
1311         while ((b = __get_unclaimed_buffer(c)))
1312                 __free_buffer_wake(b);
1313
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);
1318
1319         for (i = 0; i < LIST_SIZE; i++)
1320                 BUG_ON(!list_empty(&c->lru[i]));
1321
1322         dm_bufio_unlock(c);
1323 }
1324
1325 /*
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.
1330  */
1331 static int __cleanup_old_buffer(struct dm_buffer *b, gfp_t gfp,
1332                                 unsigned long max_jiffies)
1333 {
1334         if (jiffies - b->last_accessed < max_jiffies)
1335                 return 1;
1336
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))
1341                         return 1;
1342         }
1343
1344         if (b->hold_count)
1345                 return 1;
1346
1347         __make_buffer_clean(b);
1348         __unlink_buffer(b);
1349         __free_buffer_wake(b);
1350
1351         return 0;
1352 }
1353
1354 static void __scan(struct dm_bufio_client *c, unsigned long nr_to_scan,
1355                    struct shrink_control *sc)
1356 {
1357         int l;
1358         struct dm_buffer *b, *tmp;
1359
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) &&
1363                             !--nr_to_scan)
1364                                 return;
1365                 dm_bufio_cond_resched();
1366         }
1367 }
1368
1369 static int shrink(struct shrinker *shrinker, struct shrink_control *sc)
1370 {
1371         struct dm_bufio_client *c =
1372             container_of(shrinker, struct dm_bufio_client, shrinker);
1373         unsigned long r;
1374         unsigned long nr_to_scan = sc->nr_to_scan;
1375
1376         if (sc->gfp_mask & __GFP_FS)
1377                 dm_bufio_lock(c);
1378         else if (!dm_bufio_trylock(c))
1379                 return !nr_to_scan ? 0 : -1;
1380
1381         if (nr_to_scan)
1382                 __scan(c, nr_to_scan, sc);
1383
1384         r = c->n_buffers[LIST_CLEAN] + c->n_buffers[LIST_DIRTY];
1385         if (r > INT_MAX)
1386                 r = INT_MAX;
1387
1388         dm_bufio_unlock(c);
1389
1390         return r;
1391 }
1392
1393 /*
1394  * Create the buffering interface
1395  */
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 *))
1400 {
1401         int r;
1402         struct dm_bufio_client *c;
1403         unsigned i;
1404
1405         BUG_ON(block_size < 1 << SECTOR_SHIFT ||
1406                (block_size & (block_size - 1)));
1407
1408         c = kmalloc(sizeof(*c), GFP_KERNEL);
1409         if (!c) {
1410                 r = -ENOMEM;
1411                 goto bad_client;
1412         }
1413         c->cache_hash = vmalloc(sizeof(struct hlist_head) << DM_BUFIO_HASH_BITS);
1414         if (!c->cache_hash) {
1415                 r = -ENOMEM;
1416                 goto bad_hash;
1417         }
1418
1419         c->bdev = bdev;
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);
1426
1427         c->aux_size = aux_size;
1428         c->alloc_callback = alloc_callback;
1429         c->write_callback = write_callback;
1430
1431         for (i = 0; i < LIST_SIZE; i++) {
1432                 INIT_LIST_HEAD(&c->lru[i]);
1433                 c->n_buffers[i] = 0;
1434         }
1435
1436         for (i = 0; i < 1 << DM_BUFIO_HASH_BITS; i++)
1437                 INIT_HLIST_HEAD(&c->cache_hash[i]);
1438
1439         mutex_init(&c->lock);
1440         INIT_LIST_HEAD(&c->reserved_buffers);
1441         c->need_reserved_buffers = reserved_buffers;
1442
1443         init_waitqueue_head(&c->free_buffer_wait);
1444         c->async_write_error = 0;
1445
1446         c->dm_io = dm_io_client_create();
1447         if (IS_ERR(c->dm_io)) {
1448                 r = PTR_ERR(c->dm_io);
1449                 goto bad_dm_io;
1450         }
1451
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)) {
1457                                 r = -ENOMEM;
1458                                 mutex_unlock(&dm_bufio_clients_lock);
1459                                 goto bad_cache;
1460                         }
1461                 }
1462
1463                 if (!DM_BUFIO_CACHE(c)) {
1464                         DM_BUFIO_CACHE(c) = kmem_cache_create(DM_BUFIO_CACHE_NAME(c),
1465                                                               c->block_size,
1466                                                               c->block_size, 0, NULL);
1467                         if (!DM_BUFIO_CACHE(c)) {
1468                                 r = -ENOMEM;
1469                                 mutex_unlock(&dm_bufio_clients_lock);
1470                                 goto bad_cache;
1471                         }
1472                 }
1473         }
1474         mutex_unlock(&dm_bufio_clients_lock);
1475
1476         while (c->need_reserved_buffers) {
1477                 struct dm_buffer *b = alloc_buffer(c, GFP_KERNEL);
1478
1479                 if (!b) {
1480                         r = -ENOMEM;
1481                         goto bad_buffer;
1482                 }
1483                 __free_buffer_wake(b);
1484         }
1485
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);
1491
1492         c->shrinker.shrink = shrink;
1493         c->shrinker.seeks = 1;
1494         c->shrinker.batch = 0;
1495         register_shrinker(&c->shrinker);
1496
1497         return c;
1498
1499 bad_buffer:
1500 bad_cache:
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);
1505                 free_buffer(b);
1506         }
1507         dm_io_client_destroy(c->dm_io);
1508 bad_dm_io:
1509         vfree(c->cache_hash);
1510 bad_hash:
1511         kfree(c);
1512 bad_client:
1513         return ERR_PTR(r);
1514 }
1515 EXPORT_SYMBOL_GPL(dm_bufio_client_create);
1516
1517 /*
1518  * Free the buffering interface.
1519  * It is required that there are no references on any buffers.
1520  */
1521 void dm_bufio_client_destroy(struct dm_bufio_client *c)
1522 {
1523         unsigned i;
1524
1525         drop_buffers(c);
1526
1527         unregister_shrinker(&c->shrinker);
1528
1529         mutex_lock(&dm_bufio_clients_lock);
1530
1531         list_del(&c->client_list);
1532         dm_bufio_client_count--;
1533         __cache_size_refresh();
1534
1535         mutex_unlock(&dm_bufio_clients_lock);
1536
1537         for (i = 0; i < 1 << DM_BUFIO_HASH_BITS; i++)
1538                 BUG_ON(!hlist_empty(&c->cache_hash[i]));
1539
1540         BUG_ON(c->need_reserved_buffers);
1541
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);
1546                 free_buffer(b);
1547         }
1548
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]);
1552
1553         for (i = 0; i < LIST_SIZE; i++)
1554                 BUG_ON(c->n_buffers[i]);
1555
1556         dm_io_client_destroy(c->dm_io);
1557         vfree(c->cache_hash);
1558         kfree(c);
1559 }
1560 EXPORT_SYMBOL_GPL(dm_bufio_client_destroy);
1561
1562 static void cleanup_old_buffers(void)
1563 {
1564         unsigned long max_age = dm_bufio_max_age;
1565         struct dm_bufio_client *c;
1566
1567         barrier();
1568
1569         if (max_age > ULONG_MAX / HZ)
1570                 max_age = ULONG_MAX / HZ;
1571
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))
1575                         continue;
1576
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))
1582                                 break;
1583                         dm_bufio_cond_resched();
1584                 }
1585
1586                 dm_bufio_unlock(c);
1587                 dm_bufio_cond_resched();
1588         }
1589         mutex_unlock(&dm_bufio_clients_lock);
1590 }
1591
1592 static struct workqueue_struct *dm_bufio_wq;
1593 static struct delayed_work dm_bufio_work;
1594
1595 static void work_fn(struct work_struct *w)
1596 {
1597         cleanup_old_buffers();
1598
1599         queue_delayed_work(dm_bufio_wq, &dm_bufio_work,
1600                            DM_BUFIO_WORK_TIMER_SECS * HZ);
1601 }
1602
1603 /*----------------------------------------------------------------
1604  * Module setup
1605  *--------------------------------------------------------------*/
1606
1607 /*
1608  * This is called only once for the whole dm_bufio module.
1609  * It initializes memory limit.
1610  */
1611 static int __init dm_bufio_init(void)
1612 {
1613         __u64 mem;
1614
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;
1619
1620         memset(&dm_bufio_caches, 0, sizeof dm_bufio_caches);
1621         memset(&dm_bufio_cache_names, 0, sizeof dm_bufio_cache_names);
1622
1623         mem = (__u64)((totalram_pages - totalhigh_pages) *
1624                       DM_BUFIO_MEMORY_PERCENT / 100) << PAGE_SHIFT;
1625
1626         if (mem > ULONG_MAX)
1627                 mem = ULONG_MAX;
1628
1629 #ifdef CONFIG_MMU
1630         /*
1631          * Get the size of vmalloc space the same way as VMALLOC_TOTAL
1632          * in fs/proc/internal.h
1633          */
1634         if (mem > (VMALLOC_END - VMALLOC_START) * DM_BUFIO_VMALLOC_PERCENT / 100)
1635                 mem = (VMALLOC_END - VMALLOC_START) * DM_BUFIO_VMALLOC_PERCENT / 100;
1636 #endif
1637
1638         dm_bufio_default_cache_size = mem;
1639
1640         mutex_lock(&dm_bufio_clients_lock);
1641         __cache_size_refresh();
1642         mutex_unlock(&dm_bufio_clients_lock);
1643
1644         dm_bufio_wq = create_singlethread_workqueue("dm_bufio_cache");
1645         if (!dm_bufio_wq)
1646                 return -ENOMEM;
1647
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);
1651
1652         return 0;
1653 }
1654
1655 /*
1656  * This is called once when unloading the dm_bufio module.
1657  */
1658 static void __exit dm_bufio_exit(void)
1659 {
1660         int bug = 0;
1661         int i;
1662
1663         cancel_delayed_work_sync(&dm_bufio_work);
1664         destroy_workqueue(dm_bufio_wq);
1665
1666         for (i = 0; i < ARRAY_SIZE(dm_bufio_caches); i++) {
1667                 struct kmem_cache *kc = dm_bufio_caches[i];
1668
1669                 if (kc)
1670                         kmem_cache_destroy(kc);
1671         }
1672
1673         for (i = 0; i < ARRAY_SIZE(dm_bufio_cache_names); i++)
1674                 kfree(dm_bufio_cache_names[i]);
1675
1676         if (dm_bufio_client_count) {
1677                 DMCRIT("%s: dm_bufio_client_count leaked: %d",
1678                         __func__, dm_bufio_client_count);
1679                 bug = 1;
1680         }
1681
1682         if (dm_bufio_current_allocated) {
1683                 DMCRIT("%s: dm_bufio_current_allocated leaked: %lu",
1684                         __func__, dm_bufio_current_allocated);
1685                 bug = 1;
1686         }
1687
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);
1691                 bug = 1;
1692         }
1693
1694         if (dm_bufio_allocated_vmalloc) {
1695                 DMCRIT("%s: dm_bufio_vmalloc leaked: %lu",
1696                        __func__, dm_bufio_allocated_vmalloc);
1697                 bug = 1;
1698         }
1699
1700         if (bug)
1701                 BUG();
1702 }
1703
1704 module_init(dm_bufio_init)
1705 module_exit(dm_bufio_exit)
1706
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");
1709
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");
1712
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");
1715
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");
1718
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");
1721
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");
1724
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");
1727
1728 MODULE_AUTHOR("Mikulas Patocka <dm-devel@redhat.com>");
1729 MODULE_DESCRIPTION(DM_NAME " buffered I/O library");
1730 MODULE_LICENSE("GPL");