RDMA/ucma: Check that device is connected prior to access it
[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 = mult_frac(buffers,
843                                        DM_BUFIO_WRITEBACK_PERCENT, 100);
844 }
845
846 /*
847  * Check if we're over watermark.
848  * If we are over threshold_buffers, start freeing buffers.
849  * If we're over "limit_buffers", block until we get under the limit.
850  */
851 static void __check_watermark(struct dm_bufio_client *c)
852 {
853         unsigned long threshold_buffers, limit_buffers;
854
855         __get_memory_limit(c, &threshold_buffers, &limit_buffers);
856
857         while (c->n_buffers[LIST_CLEAN] + c->n_buffers[LIST_DIRTY] >
858                limit_buffers) {
859
860                 struct dm_buffer *b = __get_unclaimed_buffer(c);
861
862                 if (!b)
863                         return;
864
865                 __free_buffer_wake(b);
866                 dm_bufio_cond_resched();
867         }
868
869         if (c->n_buffers[LIST_DIRTY] > threshold_buffers)
870                 __write_dirty_buffers_async(c, 1);
871 }
872
873 /*
874  * Find a buffer in the hash.
875  */
876 static struct dm_buffer *__find(struct dm_bufio_client *c, sector_t block)
877 {
878         struct dm_buffer *b;
879         struct hlist_node *hn;
880
881         hlist_for_each_entry(b, hn, &c->cache_hash[DM_BUFIO_HASH(block)],
882                              hash_list) {
883                 dm_bufio_cond_resched();
884                 if (b->block == block)
885                         return b;
886         }
887
888         return NULL;
889 }
890
891 /*----------------------------------------------------------------
892  * Getting a buffer
893  *--------------------------------------------------------------*/
894
895 enum new_flag {
896         NF_FRESH = 0,
897         NF_READ = 1,
898         NF_GET = 2
899 };
900
901 static struct dm_buffer *__bufio_new(struct dm_bufio_client *c, sector_t block,
902                                      enum new_flag nf, struct dm_buffer **bp,
903                                      int *need_submit)
904 {
905         struct dm_buffer *b, *new_b = NULL;
906
907         *need_submit = 0;
908
909         b = __find(c, block);
910         if (b) {
911                 b->hold_count++;
912                 __relink_lru(b, test_bit(B_DIRTY, &b->state) ||
913                              test_bit(B_WRITING, &b->state));
914                 return b;
915         }
916
917         if (nf == NF_GET)
918                 return NULL;
919
920         new_b = __alloc_buffer_wait(c);
921
922         /*
923          * We've had a period where the mutex was unlocked, so need to
924          * recheck the hash table.
925          */
926         b = __find(c, block);
927         if (b) {
928                 __free_buffer_wake(new_b);
929                 b->hold_count++;
930                 __relink_lru(b, test_bit(B_DIRTY, &b->state) ||
931                              test_bit(B_WRITING, &b->state));
932                 return b;
933         }
934
935         __check_watermark(c);
936
937         b = new_b;
938         b->hold_count = 1;
939         b->read_error = 0;
940         b->write_error = 0;
941         __link_buffer(b, block, LIST_CLEAN);
942
943         if (nf == NF_FRESH) {
944                 b->state = 0;
945                 return b;
946         }
947
948         b->state = 1 << B_READING;
949         *need_submit = 1;
950
951         return b;
952 }
953
954 /*
955  * The endio routine for reading: set the error, clear the bit and wake up
956  * anyone waiting on the buffer.
957  */
958 static void read_endio(struct bio *bio, int error)
959 {
960         struct dm_buffer *b = container_of(bio, struct dm_buffer, bio);
961
962         b->read_error = error;
963
964         BUG_ON(!test_bit(B_READING, &b->state));
965
966         smp_mb__before_clear_bit();
967         clear_bit(B_READING, &b->state);
968         smp_mb__after_clear_bit();
969
970         wake_up_bit(&b->state, B_READING);
971 }
972
973 /*
974  * A common routine for dm_bufio_new and dm_bufio_read.  Operation of these
975  * functions is similar except that dm_bufio_new doesn't read the
976  * buffer from the disk (assuming that the caller overwrites all the data
977  * and uses dm_bufio_mark_buffer_dirty to write new data back).
978  */
979 static void *new_read(struct dm_bufio_client *c, sector_t block,
980                       enum new_flag nf, struct dm_buffer **bp)
981 {
982         int need_submit;
983         struct dm_buffer *b;
984
985         dm_bufio_lock(c);
986         b = __bufio_new(c, block, nf, bp, &need_submit);
987         dm_bufio_unlock(c);
988
989         if (!b || IS_ERR(b))
990                 return b;
991
992         if (need_submit)
993                 submit_io(b, READ, b->block, read_endio);
994
995         wait_on_bit(&b->state, B_READING, do_io_schedule, TASK_UNINTERRUPTIBLE);
996
997         if (b->read_error) {
998                 int error = b->read_error;
999
1000                 dm_bufio_release(b);
1001
1002                 return ERR_PTR(error);
1003         }
1004
1005         *bp = b;
1006
1007         return b->data;
1008 }
1009
1010 void *dm_bufio_get(struct dm_bufio_client *c, sector_t block,
1011                    struct dm_buffer **bp)
1012 {
1013         return new_read(c, block, NF_GET, bp);
1014 }
1015 EXPORT_SYMBOL_GPL(dm_bufio_get);
1016
1017 void *dm_bufio_read(struct dm_bufio_client *c, sector_t block,
1018                     struct dm_buffer **bp)
1019 {
1020         BUG_ON(dm_bufio_in_request());
1021
1022         return new_read(c, block, NF_READ, bp);
1023 }
1024 EXPORT_SYMBOL_GPL(dm_bufio_read);
1025
1026 void *dm_bufio_new(struct dm_bufio_client *c, sector_t block,
1027                    struct dm_buffer **bp)
1028 {
1029         BUG_ON(dm_bufio_in_request());
1030
1031         return new_read(c, block, NF_FRESH, bp);
1032 }
1033 EXPORT_SYMBOL_GPL(dm_bufio_new);
1034
1035 void dm_bufio_release(struct dm_buffer *b)
1036 {
1037         struct dm_bufio_client *c = b->c;
1038
1039         dm_bufio_lock(c);
1040
1041         BUG_ON(test_bit(B_READING, &b->state));
1042         BUG_ON(!b->hold_count);
1043
1044         b->hold_count--;
1045         if (!b->hold_count) {
1046                 wake_up(&c->free_buffer_wait);
1047
1048                 /*
1049                  * If there were errors on the buffer, and the buffer is not
1050                  * to be written, free the buffer. There is no point in caching
1051                  * invalid buffer.
1052                  */
1053                 if ((b->read_error || b->write_error) &&
1054                     !test_bit(B_WRITING, &b->state) &&
1055                     !test_bit(B_DIRTY, &b->state)) {
1056                         __unlink_buffer(b);
1057                         __free_buffer_wake(b);
1058                 }
1059         }
1060
1061         dm_bufio_unlock(c);
1062 }
1063 EXPORT_SYMBOL_GPL(dm_bufio_release);
1064
1065 void dm_bufio_mark_buffer_dirty(struct dm_buffer *b)
1066 {
1067         struct dm_bufio_client *c = b->c;
1068
1069         dm_bufio_lock(c);
1070
1071         if (!test_and_set_bit(B_DIRTY, &b->state))
1072                 __relink_lru(b, LIST_DIRTY);
1073
1074         dm_bufio_unlock(c);
1075 }
1076 EXPORT_SYMBOL_GPL(dm_bufio_mark_buffer_dirty);
1077
1078 void dm_bufio_write_dirty_buffers_async(struct dm_bufio_client *c)
1079 {
1080         BUG_ON(dm_bufio_in_request());
1081
1082         dm_bufio_lock(c);
1083         __write_dirty_buffers_async(c, 0);
1084         dm_bufio_unlock(c);
1085 }
1086 EXPORT_SYMBOL_GPL(dm_bufio_write_dirty_buffers_async);
1087
1088 /*
1089  * For performance, it is essential that the buffers are written asynchronously
1090  * and simultaneously (so that the block layer can merge the writes) and then
1091  * waited upon.
1092  *
1093  * Finally, we flush hardware disk cache.
1094  */
1095 int dm_bufio_write_dirty_buffers(struct dm_bufio_client *c)
1096 {
1097         int a, f;
1098         unsigned long buffers_processed = 0;
1099         struct dm_buffer *b, *tmp;
1100
1101         dm_bufio_lock(c);
1102         __write_dirty_buffers_async(c, 0);
1103
1104 again:
1105         list_for_each_entry_safe_reverse(b, tmp, &c->lru[LIST_DIRTY], lru_list) {
1106                 int dropped_lock = 0;
1107
1108                 if (buffers_processed < c->n_buffers[LIST_DIRTY])
1109                         buffers_processed++;
1110
1111                 BUG_ON(test_bit(B_READING, &b->state));
1112
1113                 if (test_bit(B_WRITING, &b->state)) {
1114                         if (buffers_processed < c->n_buffers[LIST_DIRTY]) {
1115                                 dropped_lock = 1;
1116                                 b->hold_count++;
1117                                 dm_bufio_unlock(c);
1118                                 wait_on_bit(&b->state, B_WRITING,
1119                                             do_io_schedule,
1120                                             TASK_UNINTERRUPTIBLE);
1121                                 dm_bufio_lock(c);
1122                                 b->hold_count--;
1123                         } else
1124                                 wait_on_bit(&b->state, B_WRITING,
1125                                             do_io_schedule,
1126                                             TASK_UNINTERRUPTIBLE);
1127                 }
1128
1129                 if (!test_bit(B_DIRTY, &b->state) &&
1130                     !test_bit(B_WRITING, &b->state))
1131                         __relink_lru(b, LIST_CLEAN);
1132
1133                 dm_bufio_cond_resched();
1134
1135                 /*
1136                  * If we dropped the lock, the list is no longer consistent,
1137                  * so we must restart the search.
1138                  *
1139                  * In the most common case, the buffer just processed is
1140                  * relinked to the clean list, so we won't loop scanning the
1141                  * same buffer again and again.
1142                  *
1143                  * This may livelock if there is another thread simultaneously
1144                  * dirtying buffers, so we count the number of buffers walked
1145                  * and if it exceeds the total number of buffers, it means that
1146                  * someone is doing some writes simultaneously with us.  In
1147                  * this case, stop, dropping the lock.
1148                  */
1149                 if (dropped_lock)
1150                         goto again;
1151         }
1152         wake_up(&c->free_buffer_wait);
1153         dm_bufio_unlock(c);
1154
1155         a = xchg(&c->async_write_error, 0);
1156         f = dm_bufio_issue_flush(c);
1157         if (a)
1158                 return a;
1159
1160         return f;
1161 }
1162 EXPORT_SYMBOL_GPL(dm_bufio_write_dirty_buffers);
1163
1164 /*
1165  * Use dm-io to send and empty barrier flush the device.
1166  */
1167 int dm_bufio_issue_flush(struct dm_bufio_client *c)
1168 {
1169         struct dm_io_request io_req = {
1170                 .bi_rw = REQ_FLUSH,
1171                 .mem.type = DM_IO_KMEM,
1172                 .mem.ptr.addr = NULL,
1173                 .client = c->dm_io,
1174         };
1175         struct dm_io_region io_reg = {
1176                 .bdev = c->bdev,
1177                 .sector = 0,
1178                 .count = 0,
1179         };
1180
1181         BUG_ON(dm_bufio_in_request());
1182
1183         return dm_io(&io_req, 1, &io_reg, NULL);
1184 }
1185 EXPORT_SYMBOL_GPL(dm_bufio_issue_flush);
1186
1187 /*
1188  * We first delete any other buffer that may be at that new location.
1189  *
1190  * Then, we write the buffer to the original location if it was dirty.
1191  *
1192  * Then, if we are the only one who is holding the buffer, relink the buffer
1193  * in the hash queue for the new location.
1194  *
1195  * If there was someone else holding the buffer, we write it to the new
1196  * location but not relink it, because that other user needs to have the buffer
1197  * at the same place.
1198  */
1199 void dm_bufio_release_move(struct dm_buffer *b, sector_t new_block)
1200 {
1201         struct dm_bufio_client *c = b->c;
1202         struct dm_buffer *new;
1203
1204         BUG_ON(dm_bufio_in_request());
1205
1206         dm_bufio_lock(c);
1207
1208 retry:
1209         new = __find(c, new_block);
1210         if (new) {
1211                 if (new->hold_count) {
1212                         __wait_for_free_buffer(c);
1213                         goto retry;
1214                 }
1215
1216                 /*
1217                  * FIXME: Is there any point waiting for a write that's going
1218                  * to be overwritten in a bit?
1219                  */
1220                 __make_buffer_clean(new);
1221                 __unlink_buffer(new);
1222                 __free_buffer_wake(new);
1223         }
1224
1225         BUG_ON(!b->hold_count);
1226         BUG_ON(test_bit(B_READING, &b->state));
1227
1228         __write_dirty_buffer(b);
1229         if (b->hold_count == 1) {
1230                 wait_on_bit(&b->state, B_WRITING,
1231                             do_io_schedule, TASK_UNINTERRUPTIBLE);
1232                 set_bit(B_DIRTY, &b->state);
1233                 __unlink_buffer(b);
1234                 __link_buffer(b, new_block, LIST_DIRTY);
1235         } else {
1236                 sector_t old_block;
1237                 wait_on_bit_lock(&b->state, B_WRITING,
1238                                  do_io_schedule, TASK_UNINTERRUPTIBLE);
1239                 /*
1240                  * Relink buffer to "new_block" so that write_callback
1241                  * sees "new_block" as a block number.
1242                  * After the write, link the buffer back to old_block.
1243                  * All this must be done in bufio lock, so that block number
1244                  * change isn't visible to other threads.
1245                  */
1246                 old_block = b->block;
1247                 __unlink_buffer(b);
1248                 __link_buffer(b, new_block, b->list_mode);
1249                 submit_io(b, WRITE, new_block, write_endio);
1250                 wait_on_bit(&b->state, B_WRITING,
1251                             do_io_schedule, TASK_UNINTERRUPTIBLE);
1252                 __unlink_buffer(b);
1253                 __link_buffer(b, old_block, b->list_mode);
1254         }
1255
1256         dm_bufio_unlock(c);
1257         dm_bufio_release(b);
1258 }
1259 EXPORT_SYMBOL_GPL(dm_bufio_release_move);
1260
1261 unsigned dm_bufio_get_block_size(struct dm_bufio_client *c)
1262 {
1263         return c->block_size;
1264 }
1265 EXPORT_SYMBOL_GPL(dm_bufio_get_block_size);
1266
1267 sector_t dm_bufio_get_device_size(struct dm_bufio_client *c)
1268 {
1269         return i_size_read(c->bdev->bd_inode) >>
1270                            (SECTOR_SHIFT + c->sectors_per_block_bits);
1271 }
1272 EXPORT_SYMBOL_GPL(dm_bufio_get_device_size);
1273
1274 sector_t dm_bufio_get_block_number(struct dm_buffer *b)
1275 {
1276         return b->block;
1277 }
1278 EXPORT_SYMBOL_GPL(dm_bufio_get_block_number);
1279
1280 void *dm_bufio_get_block_data(struct dm_buffer *b)
1281 {
1282         return b->data;
1283 }
1284 EXPORT_SYMBOL_GPL(dm_bufio_get_block_data);
1285
1286 void *dm_bufio_get_aux_data(struct dm_buffer *b)
1287 {
1288         return b + 1;
1289 }
1290 EXPORT_SYMBOL_GPL(dm_bufio_get_aux_data);
1291
1292 struct dm_bufio_client *dm_bufio_get_client(struct dm_buffer *b)
1293 {
1294         return b->c;
1295 }
1296 EXPORT_SYMBOL_GPL(dm_bufio_get_client);
1297
1298 static void drop_buffers(struct dm_bufio_client *c)
1299 {
1300         struct dm_buffer *b;
1301         int i;
1302
1303         BUG_ON(dm_bufio_in_request());
1304
1305         /*
1306          * An optimization so that the buffers are not written one-by-one.
1307          */
1308         dm_bufio_write_dirty_buffers_async(c);
1309
1310         dm_bufio_lock(c);
1311
1312         while ((b = __get_unclaimed_buffer(c)))
1313                 __free_buffer_wake(b);
1314
1315         for (i = 0; i < LIST_SIZE; i++)
1316                 list_for_each_entry(b, &c->lru[i], lru_list)
1317                         DMERR("leaked buffer %llx, hold count %u, list %d",
1318                               (unsigned long long)b->block, b->hold_count, i);
1319
1320         for (i = 0; i < LIST_SIZE; i++)
1321                 BUG_ON(!list_empty(&c->lru[i]));
1322
1323         dm_bufio_unlock(c);
1324 }
1325
1326 /*
1327  * Test if the buffer is unused and too old, and commit it.
1328  * And if GFP_NOFS is used, we must not do any I/O because we hold
1329  * dm_bufio_clients_lock and we would risk deadlock if the I/O gets
1330  * rerouted to different bufio client.
1331  */
1332 static int __cleanup_old_buffer(struct dm_buffer *b, gfp_t gfp,
1333                                 unsigned long max_jiffies)
1334 {
1335         if (jiffies - b->last_accessed < max_jiffies)
1336                 return 1;
1337
1338         if (!(gfp & __GFP_FS)) {
1339                 if (test_bit(B_READING, &b->state) ||
1340                     test_bit(B_WRITING, &b->state) ||
1341                     test_bit(B_DIRTY, &b->state))
1342                         return 1;
1343         }
1344
1345         if (b->hold_count)
1346                 return 1;
1347
1348         __make_buffer_clean(b);
1349         __unlink_buffer(b);
1350         __free_buffer_wake(b);
1351
1352         return 0;
1353 }
1354
1355 static void __scan(struct dm_bufio_client *c, unsigned long nr_to_scan,
1356                    struct shrink_control *sc)
1357 {
1358         int l;
1359         struct dm_buffer *b, *tmp;
1360
1361         for (l = 0; l < LIST_SIZE; l++) {
1362                 list_for_each_entry_safe_reverse(b, tmp, &c->lru[l], lru_list)
1363                         if (!__cleanup_old_buffer(b, sc->gfp_mask, 0) &&
1364                             !--nr_to_scan)
1365                                 return;
1366                 dm_bufio_cond_resched();
1367         }
1368 }
1369
1370 static int shrink(struct shrinker *shrinker, struct shrink_control *sc)
1371 {
1372         struct dm_bufio_client *c =
1373             container_of(shrinker, struct dm_bufio_client, shrinker);
1374         unsigned long r;
1375         unsigned long nr_to_scan = sc->nr_to_scan;
1376
1377         if (sc->gfp_mask & __GFP_FS)
1378                 dm_bufio_lock(c);
1379         else if (!dm_bufio_trylock(c))
1380                 return !nr_to_scan ? 0 : -1;
1381
1382         if (nr_to_scan)
1383                 __scan(c, nr_to_scan, sc);
1384
1385         r = c->n_buffers[LIST_CLEAN] + c->n_buffers[LIST_DIRTY];
1386         if (r > INT_MAX)
1387                 r = INT_MAX;
1388
1389         dm_bufio_unlock(c);
1390
1391         return r;
1392 }
1393
1394 /*
1395  * Create the buffering interface
1396  */
1397 struct dm_bufio_client *dm_bufio_client_create(struct block_device *bdev, unsigned block_size,
1398                                                unsigned reserved_buffers, unsigned aux_size,
1399                                                void (*alloc_callback)(struct dm_buffer *),
1400                                                void (*write_callback)(struct dm_buffer *))
1401 {
1402         int r;
1403         struct dm_bufio_client *c;
1404         unsigned i;
1405
1406         BUG_ON(block_size < 1 << SECTOR_SHIFT ||
1407                (block_size & (block_size - 1)));
1408
1409         c = kmalloc(sizeof(*c), GFP_KERNEL);
1410         if (!c) {
1411                 r = -ENOMEM;
1412                 goto bad_client;
1413         }
1414         c->cache_hash = vmalloc(sizeof(struct hlist_head) << DM_BUFIO_HASH_BITS);
1415         if (!c->cache_hash) {
1416                 r = -ENOMEM;
1417                 goto bad_hash;
1418         }
1419
1420         c->bdev = bdev;
1421         c->block_size = block_size;
1422         c->sectors_per_block_bits = ffs(block_size) - 1 - SECTOR_SHIFT;
1423         c->pages_per_block_bits = (ffs(block_size) - 1 >= PAGE_SHIFT) ?
1424                                   ffs(block_size) - 1 - PAGE_SHIFT : 0;
1425         c->blocks_per_page_bits = (ffs(block_size) - 1 < PAGE_SHIFT ?
1426                                   PAGE_SHIFT - (ffs(block_size) - 1) : 0);
1427
1428         c->aux_size = aux_size;
1429         c->alloc_callback = alloc_callback;
1430         c->write_callback = write_callback;
1431
1432         for (i = 0; i < LIST_SIZE; i++) {
1433                 INIT_LIST_HEAD(&c->lru[i]);
1434                 c->n_buffers[i] = 0;
1435         }
1436
1437         for (i = 0; i < 1 << DM_BUFIO_HASH_BITS; i++)
1438                 INIT_HLIST_HEAD(&c->cache_hash[i]);
1439
1440         mutex_init(&c->lock);
1441         INIT_LIST_HEAD(&c->reserved_buffers);
1442         c->need_reserved_buffers = reserved_buffers;
1443
1444         init_waitqueue_head(&c->free_buffer_wait);
1445         c->async_write_error = 0;
1446
1447         c->dm_io = dm_io_client_create();
1448         if (IS_ERR(c->dm_io)) {
1449                 r = PTR_ERR(c->dm_io);
1450                 goto bad_dm_io;
1451         }
1452
1453         mutex_lock(&dm_bufio_clients_lock);
1454         if (c->blocks_per_page_bits) {
1455                 if (!DM_BUFIO_CACHE_NAME(c)) {
1456                         DM_BUFIO_CACHE_NAME(c) = kasprintf(GFP_KERNEL, "dm_bufio_cache-%u", c->block_size);
1457                         if (!DM_BUFIO_CACHE_NAME(c)) {
1458                                 r = -ENOMEM;
1459                                 mutex_unlock(&dm_bufio_clients_lock);
1460                                 goto bad_cache;
1461                         }
1462                 }
1463
1464                 if (!DM_BUFIO_CACHE(c)) {
1465                         DM_BUFIO_CACHE(c) = kmem_cache_create(DM_BUFIO_CACHE_NAME(c),
1466                                                               c->block_size,
1467                                                               c->block_size, 0, NULL);
1468                         if (!DM_BUFIO_CACHE(c)) {
1469                                 r = -ENOMEM;
1470                                 mutex_unlock(&dm_bufio_clients_lock);
1471                                 goto bad_cache;
1472                         }
1473                 }
1474         }
1475         mutex_unlock(&dm_bufio_clients_lock);
1476
1477         while (c->need_reserved_buffers) {
1478                 struct dm_buffer *b = alloc_buffer(c, GFP_KERNEL);
1479
1480                 if (!b) {
1481                         r = -ENOMEM;
1482                         goto bad_buffer;
1483                 }
1484                 __free_buffer_wake(b);
1485         }
1486
1487         mutex_lock(&dm_bufio_clients_lock);
1488         dm_bufio_client_count++;
1489         list_add(&c->client_list, &dm_bufio_all_clients);
1490         __cache_size_refresh();
1491         mutex_unlock(&dm_bufio_clients_lock);
1492
1493         c->shrinker.shrink = shrink;
1494         c->shrinker.seeks = 1;
1495         c->shrinker.batch = 0;
1496         register_shrinker(&c->shrinker);
1497
1498         return c;
1499
1500 bad_buffer:
1501 bad_cache:
1502         while (!list_empty(&c->reserved_buffers)) {
1503                 struct dm_buffer *b = list_entry(c->reserved_buffers.next,
1504                                                  struct dm_buffer, lru_list);
1505                 list_del(&b->lru_list);
1506                 free_buffer(b);
1507         }
1508         dm_io_client_destroy(c->dm_io);
1509 bad_dm_io:
1510         vfree(c->cache_hash);
1511 bad_hash:
1512         kfree(c);
1513 bad_client:
1514         return ERR_PTR(r);
1515 }
1516 EXPORT_SYMBOL_GPL(dm_bufio_client_create);
1517
1518 /*
1519  * Free the buffering interface.
1520  * It is required that there are no references on any buffers.
1521  */
1522 void dm_bufio_client_destroy(struct dm_bufio_client *c)
1523 {
1524         unsigned i;
1525
1526         drop_buffers(c);
1527
1528         unregister_shrinker(&c->shrinker);
1529
1530         mutex_lock(&dm_bufio_clients_lock);
1531
1532         list_del(&c->client_list);
1533         dm_bufio_client_count--;
1534         __cache_size_refresh();
1535
1536         mutex_unlock(&dm_bufio_clients_lock);
1537
1538         for (i = 0; i < 1 << DM_BUFIO_HASH_BITS; i++)
1539                 BUG_ON(!hlist_empty(&c->cache_hash[i]));
1540
1541         BUG_ON(c->need_reserved_buffers);
1542
1543         while (!list_empty(&c->reserved_buffers)) {
1544                 struct dm_buffer *b = list_entry(c->reserved_buffers.next,
1545                                                  struct dm_buffer, lru_list);
1546                 list_del(&b->lru_list);
1547                 free_buffer(b);
1548         }
1549
1550         for (i = 0; i < LIST_SIZE; i++)
1551                 if (c->n_buffers[i])
1552                         DMERR("leaked buffer count %d: %ld", i, c->n_buffers[i]);
1553
1554         for (i = 0; i < LIST_SIZE; i++)
1555                 BUG_ON(c->n_buffers[i]);
1556
1557         dm_io_client_destroy(c->dm_io);
1558         vfree(c->cache_hash);
1559         kfree(c);
1560 }
1561 EXPORT_SYMBOL_GPL(dm_bufio_client_destroy);
1562
1563 static void cleanup_old_buffers(void)
1564 {
1565         unsigned long max_age = dm_bufio_max_age;
1566         struct dm_bufio_client *c;
1567
1568         barrier();
1569
1570         if (max_age > ULONG_MAX / HZ)
1571                 max_age = ULONG_MAX / HZ;
1572
1573         mutex_lock(&dm_bufio_clients_lock);
1574         list_for_each_entry(c, &dm_bufio_all_clients, client_list) {
1575                 if (!dm_bufio_trylock(c))
1576                         continue;
1577
1578                 while (!list_empty(&c->lru[LIST_CLEAN])) {
1579                         struct dm_buffer *b;
1580                         b = list_entry(c->lru[LIST_CLEAN].prev,
1581                                        struct dm_buffer, lru_list);
1582                         if (__cleanup_old_buffer(b, 0, max_age * HZ))
1583                                 break;
1584                         dm_bufio_cond_resched();
1585                 }
1586
1587                 dm_bufio_unlock(c);
1588                 dm_bufio_cond_resched();
1589         }
1590         mutex_unlock(&dm_bufio_clients_lock);
1591 }
1592
1593 static struct workqueue_struct *dm_bufio_wq;
1594 static struct delayed_work dm_bufio_work;
1595
1596 static void work_fn(struct work_struct *w)
1597 {
1598         cleanup_old_buffers();
1599
1600         queue_delayed_work(dm_bufio_wq, &dm_bufio_work,
1601                            DM_BUFIO_WORK_TIMER_SECS * HZ);
1602 }
1603
1604 /*----------------------------------------------------------------
1605  * Module setup
1606  *--------------------------------------------------------------*/
1607
1608 /*
1609  * This is called only once for the whole dm_bufio module.
1610  * It initializes memory limit.
1611  */
1612 static int __init dm_bufio_init(void)
1613 {
1614         __u64 mem;
1615
1616         dm_bufio_allocated_kmem_cache = 0;
1617         dm_bufio_allocated_get_free_pages = 0;
1618         dm_bufio_allocated_vmalloc = 0;
1619         dm_bufio_current_allocated = 0;
1620
1621         memset(&dm_bufio_caches, 0, sizeof dm_bufio_caches);
1622         memset(&dm_bufio_cache_names, 0, sizeof dm_bufio_cache_names);
1623
1624         mem = (__u64)mult_frac(totalram_pages - totalhigh_pages,
1625                                DM_BUFIO_MEMORY_PERCENT, 100) << PAGE_SHIFT;
1626
1627         if (mem > ULONG_MAX)
1628                 mem = ULONG_MAX;
1629
1630 #ifdef CONFIG_MMU
1631         if (mem > mult_frac(VMALLOC_END - VMALLOC_START, DM_BUFIO_VMALLOC_PERCENT, 100))
1632                 mem = mult_frac(VMALLOC_END - VMALLOC_START, DM_BUFIO_VMALLOC_PERCENT, 100);
1633 #endif
1634
1635         dm_bufio_default_cache_size = mem;
1636
1637         mutex_lock(&dm_bufio_clients_lock);
1638         __cache_size_refresh();
1639         mutex_unlock(&dm_bufio_clients_lock);
1640
1641         dm_bufio_wq = create_singlethread_workqueue("dm_bufio_cache");
1642         if (!dm_bufio_wq)
1643                 return -ENOMEM;
1644
1645         INIT_DELAYED_WORK(&dm_bufio_work, work_fn);
1646         queue_delayed_work(dm_bufio_wq, &dm_bufio_work,
1647                            DM_BUFIO_WORK_TIMER_SECS * HZ);
1648
1649         return 0;
1650 }
1651
1652 /*
1653  * This is called once when unloading the dm_bufio module.
1654  */
1655 static void __exit dm_bufio_exit(void)
1656 {
1657         int bug = 0;
1658         int i;
1659
1660         cancel_delayed_work_sync(&dm_bufio_work);
1661         destroy_workqueue(dm_bufio_wq);
1662
1663         for (i = 0; i < ARRAY_SIZE(dm_bufio_caches); i++) {
1664                 struct kmem_cache *kc = dm_bufio_caches[i];
1665
1666                 if (kc)
1667                         kmem_cache_destroy(kc);
1668         }
1669
1670         for (i = 0; i < ARRAY_SIZE(dm_bufio_cache_names); i++)
1671                 kfree(dm_bufio_cache_names[i]);
1672
1673         if (dm_bufio_client_count) {
1674                 DMCRIT("%s: dm_bufio_client_count leaked: %d",
1675                         __func__, dm_bufio_client_count);
1676                 bug = 1;
1677         }
1678
1679         if (dm_bufio_current_allocated) {
1680                 DMCRIT("%s: dm_bufio_current_allocated leaked: %lu",
1681                         __func__, dm_bufio_current_allocated);
1682                 bug = 1;
1683         }
1684
1685         if (dm_bufio_allocated_get_free_pages) {
1686                 DMCRIT("%s: dm_bufio_allocated_get_free_pages leaked: %lu",
1687                        __func__, dm_bufio_allocated_get_free_pages);
1688                 bug = 1;
1689         }
1690
1691         if (dm_bufio_allocated_vmalloc) {
1692                 DMCRIT("%s: dm_bufio_vmalloc leaked: %lu",
1693                        __func__, dm_bufio_allocated_vmalloc);
1694                 bug = 1;
1695         }
1696
1697         if (bug)
1698                 BUG();
1699 }
1700
1701 module_init(dm_bufio_init)
1702 module_exit(dm_bufio_exit)
1703
1704 module_param_named(max_cache_size_bytes, dm_bufio_cache_size, ulong, S_IRUGO | S_IWUSR);
1705 MODULE_PARM_DESC(max_cache_size_bytes, "Size of metadata cache");
1706
1707 module_param_named(max_age_seconds, dm_bufio_max_age, uint, S_IRUGO | S_IWUSR);
1708 MODULE_PARM_DESC(max_age_seconds, "Max age of a buffer in seconds");
1709
1710 module_param_named(peak_allocated_bytes, dm_bufio_peak_allocated, ulong, S_IRUGO | S_IWUSR);
1711 MODULE_PARM_DESC(peak_allocated_bytes, "Tracks the maximum allocated memory");
1712
1713 module_param_named(allocated_kmem_cache_bytes, dm_bufio_allocated_kmem_cache, ulong, S_IRUGO);
1714 MODULE_PARM_DESC(allocated_kmem_cache_bytes, "Memory allocated with kmem_cache_alloc");
1715
1716 module_param_named(allocated_get_free_pages_bytes, dm_bufio_allocated_get_free_pages, ulong, S_IRUGO);
1717 MODULE_PARM_DESC(allocated_get_free_pages_bytes, "Memory allocated with get_free_pages");
1718
1719 module_param_named(allocated_vmalloc_bytes, dm_bufio_allocated_vmalloc, ulong, S_IRUGO);
1720 MODULE_PARM_DESC(allocated_vmalloc_bytes, "Memory allocated with vmalloc");
1721
1722 module_param_named(current_allocated_bytes, dm_bufio_current_allocated, ulong, S_IRUGO);
1723 MODULE_PARM_DESC(current_allocated_bytes, "Memory currently used by the cache");
1724
1725 MODULE_AUTHOR("Mikulas Patocka <dm-devel@redhat.com>");
1726 MODULE_DESCRIPTION(DM_NAME " buffered I/O library");
1727 MODULE_LICENSE("GPL");