drm/i915: quirk invert brightness for Acer Aspire 5336
[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 }
472
473 /*----------------------------------------------------------------
474  * Submit I/O on the buffer.
475  *
476  * Bio interface is faster but it has some problems:
477  *      the vector list is limited (increasing this limit increases
478  *      memory-consumption per buffer, so it is not viable);
479  *
480  *      the memory must be direct-mapped, not vmalloced;
481  *
482  *      the I/O driver can reject requests spuriously if it thinks that
483  *      the requests are too big for the device or if they cross a
484  *      controller-defined memory boundary.
485  *
486  * If the buffer is small enough (up to DM_BUFIO_INLINE_VECS pages) and
487  * it is not vmalloced, try using the bio interface.
488  *
489  * If the buffer is big, if it is vmalloced or if the underlying device
490  * rejects the bio because it is too large, use dm-io layer to do the I/O.
491  * The dm-io layer splits the I/O into multiple requests, avoiding the above
492  * shortcomings.
493  *--------------------------------------------------------------*/
494
495 /*
496  * dm-io completion routine. It just calls b->bio.bi_end_io, pretending
497  * that the request was handled directly with bio interface.
498  */
499 static void dmio_complete(unsigned long error, void *context)
500 {
501         struct dm_buffer *b = context;
502
503         b->bio.bi_end_io(&b->bio, error ? -EIO : 0);
504 }
505
506 static void use_dmio(struct dm_buffer *b, int rw, sector_t block,
507                      bio_end_io_t *end_io)
508 {
509         int r;
510         struct dm_io_request io_req = {
511                 .bi_rw = rw,
512                 .notify.fn = dmio_complete,
513                 .notify.context = b,
514                 .client = b->c->dm_io,
515         };
516         struct dm_io_region region = {
517                 .bdev = b->c->bdev,
518                 .sector = block << b->c->sectors_per_block_bits,
519                 .count = b->c->block_size >> SECTOR_SHIFT,
520         };
521
522         if (b->data_mode != DATA_MODE_VMALLOC) {
523                 io_req.mem.type = DM_IO_KMEM;
524                 io_req.mem.ptr.addr = b->data;
525         } else {
526                 io_req.mem.type = DM_IO_VMA;
527                 io_req.mem.ptr.vma = b->data;
528         }
529
530         b->bio.bi_end_io = end_io;
531
532         r = dm_io(&io_req, 1, &region, NULL);
533         if (r)
534                 end_io(&b->bio, r);
535 }
536
537 static void use_inline_bio(struct dm_buffer *b, int rw, sector_t block,
538                            bio_end_io_t *end_io)
539 {
540         char *ptr;
541         int len;
542
543         bio_init(&b->bio);
544         b->bio.bi_io_vec = b->bio_vec;
545         b->bio.bi_max_vecs = DM_BUFIO_INLINE_VECS;
546         b->bio.bi_sector = block << b->c->sectors_per_block_bits;
547         b->bio.bi_bdev = b->c->bdev;
548         b->bio.bi_end_io = end_io;
549
550         /*
551          * We assume that if len >= PAGE_SIZE ptr is page-aligned.
552          * If len < PAGE_SIZE the buffer doesn't cross page boundary.
553          */
554         ptr = b->data;
555         len = b->c->block_size;
556
557         if (len >= PAGE_SIZE)
558                 BUG_ON((unsigned long)ptr & (PAGE_SIZE - 1));
559         else
560                 BUG_ON((unsigned long)ptr & (len - 1));
561
562         do {
563                 if (!bio_add_page(&b->bio, virt_to_page(ptr),
564                                   len < PAGE_SIZE ? len : PAGE_SIZE,
565                                   virt_to_phys(ptr) & (PAGE_SIZE - 1))) {
566                         BUG_ON(b->c->block_size <= PAGE_SIZE);
567                         use_dmio(b, rw, block, end_io);
568                         return;
569                 }
570
571                 len -= PAGE_SIZE;
572                 ptr += PAGE_SIZE;
573         } while (len > 0);
574
575         submit_bio(rw, &b->bio);
576 }
577
578 static void submit_io(struct dm_buffer *b, int rw, sector_t block,
579                       bio_end_io_t *end_io)
580 {
581         if (rw == WRITE && b->c->write_callback)
582                 b->c->write_callback(b);
583
584         if (b->c->block_size <= DM_BUFIO_INLINE_VECS * PAGE_SIZE &&
585             b->data_mode != DATA_MODE_VMALLOC)
586                 use_inline_bio(b, rw, block, end_io);
587         else
588                 use_dmio(b, rw, block, end_io);
589 }
590
591 /*----------------------------------------------------------------
592  * Writing dirty buffers
593  *--------------------------------------------------------------*/
594
595 /*
596  * The endio routine for write.
597  *
598  * Set the error, clear B_WRITING bit and wake anyone who was waiting on
599  * it.
600  */
601 static void write_endio(struct bio *bio, int error)
602 {
603         struct dm_buffer *b = container_of(bio, struct dm_buffer, bio);
604
605         b->write_error = error;
606         if (error) {
607                 struct dm_bufio_client *c = b->c;
608                 (void)cmpxchg(&c->async_write_error, 0, error);
609         }
610
611         BUG_ON(!test_bit(B_WRITING, &b->state));
612
613         smp_mb__before_clear_bit();
614         clear_bit(B_WRITING, &b->state);
615         smp_mb__after_clear_bit();
616
617         wake_up_bit(&b->state, B_WRITING);
618 }
619
620 /*
621  * This function is called when wait_on_bit is actually waiting.
622  */
623 static int do_io_schedule(void *word)
624 {
625         io_schedule();
626
627         return 0;
628 }
629
630 /*
631  * Initiate a write on a dirty buffer, but don't wait for it.
632  *
633  * - If the buffer is not dirty, exit.
634  * - If there some previous write going on, wait for it to finish (we can't
635  *   have two writes on the same buffer simultaneously).
636  * - Submit our write and don't wait on it. We set B_WRITING indicating
637  *   that there is a write in progress.
638  */
639 static void __write_dirty_buffer(struct dm_buffer *b)
640 {
641         if (!test_bit(B_DIRTY, &b->state))
642                 return;
643
644         clear_bit(B_DIRTY, &b->state);
645         wait_on_bit_lock(&b->state, B_WRITING,
646                          do_io_schedule, TASK_UNINTERRUPTIBLE);
647
648         submit_io(b, WRITE, b->block, write_endio);
649 }
650
651 /*
652  * Wait until any activity on the buffer finishes.  Possibly write the
653  * buffer if it is dirty.  When this function finishes, there is no I/O
654  * running on the buffer and the buffer is not dirty.
655  */
656 static void __make_buffer_clean(struct dm_buffer *b)
657 {
658         BUG_ON(b->hold_count);
659
660         if (!b->state)  /* fast case */
661                 return;
662
663         wait_on_bit(&b->state, B_READING, do_io_schedule, TASK_UNINTERRUPTIBLE);
664         __write_dirty_buffer(b);
665         wait_on_bit(&b->state, B_WRITING, do_io_schedule, TASK_UNINTERRUPTIBLE);
666 }
667
668 /*
669  * Find some buffer that is not held by anybody, clean it, unlink it and
670  * return it.
671  */
672 static struct dm_buffer *__get_unclaimed_buffer(struct dm_bufio_client *c)
673 {
674         struct dm_buffer *b;
675
676         list_for_each_entry_reverse(b, &c->lru[LIST_CLEAN], lru_list) {
677                 BUG_ON(test_bit(B_WRITING, &b->state));
678                 BUG_ON(test_bit(B_DIRTY, &b->state));
679
680                 if (!b->hold_count) {
681                         __make_buffer_clean(b);
682                         __unlink_buffer(b);
683                         return b;
684                 }
685                 dm_bufio_cond_resched();
686         }
687
688         list_for_each_entry_reverse(b, &c->lru[LIST_DIRTY], lru_list) {
689                 BUG_ON(test_bit(B_READING, &b->state));
690
691                 if (!b->hold_count) {
692                         __make_buffer_clean(b);
693                         __unlink_buffer(b);
694                         return b;
695                 }
696                 dm_bufio_cond_resched();
697         }
698
699         return NULL;
700 }
701
702 /*
703  * Wait until some other threads free some buffer or release hold count on
704  * some buffer.
705  *
706  * This function is entered with c->lock held, drops it and regains it
707  * before exiting.
708  */
709 static void __wait_for_free_buffer(struct dm_bufio_client *c)
710 {
711         DECLARE_WAITQUEUE(wait, current);
712
713         add_wait_queue(&c->free_buffer_wait, &wait);
714         set_task_state(current, TASK_UNINTERRUPTIBLE);
715         dm_bufio_unlock(c);
716
717         io_schedule();
718
719         set_task_state(current, TASK_RUNNING);
720         remove_wait_queue(&c->free_buffer_wait, &wait);
721
722         dm_bufio_lock(c);
723 }
724
725 /*
726  * Allocate a new buffer. If the allocation is not possible, wait until
727  * some other thread frees a buffer.
728  *
729  * May drop the lock and regain it.
730  */
731 static struct dm_buffer *__alloc_buffer_wait_no_callback(struct dm_bufio_client *c)
732 {
733         struct dm_buffer *b;
734
735         /*
736          * dm-bufio is resistant to allocation failures (it just keeps
737          * one buffer reserved in cases all the allocations fail).
738          * So set flags to not try too hard:
739          *      GFP_NOIO: don't recurse into the I/O layer
740          *      __GFP_NORETRY: don't retry and rather return failure
741          *      __GFP_NOMEMALLOC: don't use emergency reserves
742          *      __GFP_NOWARN: don't print a warning in case of failure
743          *
744          * For debugging, if we set the cache size to 1, no new buffers will
745          * be allocated.
746          */
747         while (1) {
748                 if (dm_bufio_cache_size_latch != 1) {
749                         b = alloc_buffer(c, GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
750                         if (b)
751                                 return b;
752                 }
753
754                 if (!list_empty(&c->reserved_buffers)) {
755                         b = list_entry(c->reserved_buffers.next,
756                                        struct dm_buffer, lru_list);
757                         list_del(&b->lru_list);
758                         c->need_reserved_buffers++;
759
760                         return b;
761                 }
762
763                 b = __get_unclaimed_buffer(c);
764                 if (b)
765                         return b;
766
767                 __wait_for_free_buffer(c);
768         }
769 }
770
771 static struct dm_buffer *__alloc_buffer_wait(struct dm_bufio_client *c)
772 {
773         struct dm_buffer *b = __alloc_buffer_wait_no_callback(c);
774
775         if (c->alloc_callback)
776                 c->alloc_callback(b);
777
778         return b;
779 }
780
781 /*
782  * Free a buffer and wake other threads waiting for free buffers.
783  */
784 static void __free_buffer_wake(struct dm_buffer *b)
785 {
786         struct dm_bufio_client *c = b->c;
787
788         if (!c->need_reserved_buffers)
789                 free_buffer(b);
790         else {
791                 list_add(&b->lru_list, &c->reserved_buffers);
792                 c->need_reserved_buffers--;
793         }
794
795         wake_up(&c->free_buffer_wait);
796 }
797
798 static void __write_dirty_buffers_async(struct dm_bufio_client *c, int no_wait)
799 {
800         struct dm_buffer *b, *tmp;
801
802         list_for_each_entry_safe_reverse(b, tmp, &c->lru[LIST_DIRTY], lru_list) {
803                 BUG_ON(test_bit(B_READING, &b->state));
804
805                 if (!test_bit(B_DIRTY, &b->state) &&
806                     !test_bit(B_WRITING, &b->state)) {
807                         __relink_lru(b, LIST_CLEAN);
808                         continue;
809                 }
810
811                 if (no_wait && test_bit(B_WRITING, &b->state))
812                         return;
813
814                 __write_dirty_buffer(b);
815                 dm_bufio_cond_resched();
816         }
817 }
818
819 /*
820  * Get writeback threshold and buffer limit for a given client.
821  */
822 static void __get_memory_limit(struct dm_bufio_client *c,
823                                unsigned long *threshold_buffers,
824                                unsigned long *limit_buffers)
825 {
826         unsigned long buffers;
827
828         if (dm_bufio_cache_size != dm_bufio_cache_size_latch) {
829                 mutex_lock(&dm_bufio_clients_lock);
830                 __cache_size_refresh();
831                 mutex_unlock(&dm_bufio_clients_lock);
832         }
833
834         buffers = dm_bufio_cache_size_per_client >>
835                   (c->sectors_per_block_bits + SECTOR_SHIFT);
836
837         if (buffers < DM_BUFIO_MIN_BUFFERS)
838                 buffers = DM_BUFIO_MIN_BUFFERS;
839
840         *limit_buffers = buffers;
841         *threshold_buffers = buffers * DM_BUFIO_WRITEBACK_PERCENT / 100;
842 }
843
844 /*
845  * Check if we're over watermark.
846  * If we are over threshold_buffers, start freeing buffers.
847  * If we're over "limit_buffers", block until we get under the limit.
848  */
849 static void __check_watermark(struct dm_bufio_client *c)
850 {
851         unsigned long threshold_buffers, limit_buffers;
852
853         __get_memory_limit(c, &threshold_buffers, &limit_buffers);
854
855         while (c->n_buffers[LIST_CLEAN] + c->n_buffers[LIST_DIRTY] >
856                limit_buffers) {
857
858                 struct dm_buffer *b = __get_unclaimed_buffer(c);
859
860                 if (!b)
861                         return;
862
863                 __free_buffer_wake(b);
864                 dm_bufio_cond_resched();
865         }
866
867         if (c->n_buffers[LIST_DIRTY] > threshold_buffers)
868                 __write_dirty_buffers_async(c, 1);
869 }
870
871 /*
872  * Find a buffer in the hash.
873  */
874 static struct dm_buffer *__find(struct dm_bufio_client *c, sector_t block)
875 {
876         struct dm_buffer *b;
877         struct hlist_node *hn;
878
879         hlist_for_each_entry(b, hn, &c->cache_hash[DM_BUFIO_HASH(block)],
880                              hash_list) {
881                 dm_bufio_cond_resched();
882                 if (b->block == block)
883                         return b;
884         }
885
886         return NULL;
887 }
888
889 /*----------------------------------------------------------------
890  * Getting a buffer
891  *--------------------------------------------------------------*/
892
893 enum new_flag {
894         NF_FRESH = 0,
895         NF_READ = 1,
896         NF_GET = 2
897 };
898
899 static struct dm_buffer *__bufio_new(struct dm_bufio_client *c, sector_t block,
900                                      enum new_flag nf, struct dm_buffer **bp,
901                                      int *need_submit)
902 {
903         struct dm_buffer *b, *new_b = NULL;
904
905         *need_submit = 0;
906
907         b = __find(c, block);
908         if (b) {
909                 b->hold_count++;
910                 __relink_lru(b, test_bit(B_DIRTY, &b->state) ||
911                              test_bit(B_WRITING, &b->state));
912                 return b;
913         }
914
915         if (nf == NF_GET)
916                 return NULL;
917
918         new_b = __alloc_buffer_wait(c);
919
920         /*
921          * We've had a period where the mutex was unlocked, so need to
922          * recheck the hash table.
923          */
924         b = __find(c, block);
925         if (b) {
926                 __free_buffer_wake(new_b);
927                 b->hold_count++;
928                 __relink_lru(b, test_bit(B_DIRTY, &b->state) ||
929                              test_bit(B_WRITING, &b->state));
930                 return b;
931         }
932
933         __check_watermark(c);
934
935         b = new_b;
936         b->hold_count = 1;
937         b->read_error = 0;
938         b->write_error = 0;
939         __link_buffer(b, block, LIST_CLEAN);
940
941         if (nf == NF_FRESH) {
942                 b->state = 0;
943                 return b;
944         }
945
946         b->state = 1 << B_READING;
947         *need_submit = 1;
948
949         return b;
950 }
951
952 /*
953  * The endio routine for reading: set the error, clear the bit and wake up
954  * anyone waiting on the buffer.
955  */
956 static void read_endio(struct bio *bio, int error)
957 {
958         struct dm_buffer *b = container_of(bio, struct dm_buffer, bio);
959
960         b->read_error = error;
961
962         BUG_ON(!test_bit(B_READING, &b->state));
963
964         smp_mb__before_clear_bit();
965         clear_bit(B_READING, &b->state);
966         smp_mb__after_clear_bit();
967
968         wake_up_bit(&b->state, B_READING);
969 }
970
971 /*
972  * A common routine for dm_bufio_new and dm_bufio_read.  Operation of these
973  * functions is similar except that dm_bufio_new doesn't read the
974  * buffer from the disk (assuming that the caller overwrites all the data
975  * and uses dm_bufio_mark_buffer_dirty to write new data back).
976  */
977 static void *new_read(struct dm_bufio_client *c, sector_t block,
978                       enum new_flag nf, struct dm_buffer **bp)
979 {
980         int need_submit;
981         struct dm_buffer *b;
982
983         dm_bufio_lock(c);
984         b = __bufio_new(c, block, nf, bp, &need_submit);
985         dm_bufio_unlock(c);
986
987         if (!b || IS_ERR(b))
988                 return b;
989
990         if (need_submit)
991                 submit_io(b, READ, b->block, read_endio);
992
993         wait_on_bit(&b->state, B_READING, do_io_schedule, TASK_UNINTERRUPTIBLE);
994
995         if (b->read_error) {
996                 int error = b->read_error;
997
998                 dm_bufio_release(b);
999
1000                 return ERR_PTR(error);
1001         }
1002
1003         *bp = b;
1004
1005         return b->data;
1006 }
1007
1008 void *dm_bufio_get(struct dm_bufio_client *c, sector_t block,
1009                    struct dm_buffer **bp)
1010 {
1011         return new_read(c, block, NF_GET, bp);
1012 }
1013 EXPORT_SYMBOL_GPL(dm_bufio_get);
1014
1015 void *dm_bufio_read(struct dm_bufio_client *c, sector_t block,
1016                     struct dm_buffer **bp)
1017 {
1018         BUG_ON(dm_bufio_in_request());
1019
1020         return new_read(c, block, NF_READ, bp);
1021 }
1022 EXPORT_SYMBOL_GPL(dm_bufio_read);
1023
1024 void *dm_bufio_new(struct dm_bufio_client *c, sector_t block,
1025                    struct dm_buffer **bp)
1026 {
1027         BUG_ON(dm_bufio_in_request());
1028
1029         return new_read(c, block, NF_FRESH, bp);
1030 }
1031 EXPORT_SYMBOL_GPL(dm_bufio_new);
1032
1033 void dm_bufio_release(struct dm_buffer *b)
1034 {
1035         struct dm_bufio_client *c = b->c;
1036
1037         dm_bufio_lock(c);
1038
1039         BUG_ON(test_bit(B_READING, &b->state));
1040         BUG_ON(!b->hold_count);
1041
1042         b->hold_count--;
1043         if (!b->hold_count) {
1044                 wake_up(&c->free_buffer_wait);
1045
1046                 /*
1047                  * If there were errors on the buffer, and the buffer is not
1048                  * to be written, free the buffer. There is no point in caching
1049                  * invalid buffer.
1050                  */
1051                 if ((b->read_error || b->write_error) &&
1052                     !test_bit(B_WRITING, &b->state) &&
1053                     !test_bit(B_DIRTY, &b->state)) {
1054                         __unlink_buffer(b);
1055                         __free_buffer_wake(b);
1056                 }
1057         }
1058
1059         dm_bufio_unlock(c);
1060 }
1061 EXPORT_SYMBOL_GPL(dm_bufio_release);
1062
1063 void dm_bufio_mark_buffer_dirty(struct dm_buffer *b)
1064 {
1065         struct dm_bufio_client *c = b->c;
1066
1067         dm_bufio_lock(c);
1068
1069         if (!test_and_set_bit(B_DIRTY, &b->state))
1070                 __relink_lru(b, LIST_DIRTY);
1071
1072         dm_bufio_unlock(c);
1073 }
1074 EXPORT_SYMBOL_GPL(dm_bufio_mark_buffer_dirty);
1075
1076 void dm_bufio_write_dirty_buffers_async(struct dm_bufio_client *c)
1077 {
1078         BUG_ON(dm_bufio_in_request());
1079
1080         dm_bufio_lock(c);
1081         __write_dirty_buffers_async(c, 0);
1082         dm_bufio_unlock(c);
1083 }
1084 EXPORT_SYMBOL_GPL(dm_bufio_write_dirty_buffers_async);
1085
1086 /*
1087  * For performance, it is essential that the buffers are written asynchronously
1088  * and simultaneously (so that the block layer can merge the writes) and then
1089  * waited upon.
1090  *
1091  * Finally, we flush hardware disk cache.
1092  */
1093 int dm_bufio_write_dirty_buffers(struct dm_bufio_client *c)
1094 {
1095         int a, f;
1096         unsigned long buffers_processed = 0;
1097         struct dm_buffer *b, *tmp;
1098
1099         dm_bufio_lock(c);
1100         __write_dirty_buffers_async(c, 0);
1101
1102 again:
1103         list_for_each_entry_safe_reverse(b, tmp, &c->lru[LIST_DIRTY], lru_list) {
1104                 int dropped_lock = 0;
1105
1106                 if (buffers_processed < c->n_buffers[LIST_DIRTY])
1107                         buffers_processed++;
1108
1109                 BUG_ON(test_bit(B_READING, &b->state));
1110
1111                 if (test_bit(B_WRITING, &b->state)) {
1112                         if (buffers_processed < c->n_buffers[LIST_DIRTY]) {
1113                                 dropped_lock = 1;
1114                                 b->hold_count++;
1115                                 dm_bufio_unlock(c);
1116                                 wait_on_bit(&b->state, B_WRITING,
1117                                             do_io_schedule,
1118                                             TASK_UNINTERRUPTIBLE);
1119                                 dm_bufio_lock(c);
1120                                 b->hold_count--;
1121                         } else
1122                                 wait_on_bit(&b->state, B_WRITING,
1123                                             do_io_schedule,
1124                                             TASK_UNINTERRUPTIBLE);
1125                 }
1126
1127                 if (!test_bit(B_DIRTY, &b->state) &&
1128                     !test_bit(B_WRITING, &b->state))
1129                         __relink_lru(b, LIST_CLEAN);
1130
1131                 dm_bufio_cond_resched();
1132
1133                 /*
1134                  * If we dropped the lock, the list is no longer consistent,
1135                  * so we must restart the search.
1136                  *
1137                  * In the most common case, the buffer just processed is
1138                  * relinked to the clean list, so we won't loop scanning the
1139                  * same buffer again and again.
1140                  *
1141                  * This may livelock if there is another thread simultaneously
1142                  * dirtying buffers, so we count the number of buffers walked
1143                  * and if it exceeds the total number of buffers, it means that
1144                  * someone is doing some writes simultaneously with us.  In
1145                  * this case, stop, dropping the lock.
1146                  */
1147                 if (dropped_lock)
1148                         goto again;
1149         }
1150         wake_up(&c->free_buffer_wait);
1151         dm_bufio_unlock(c);
1152
1153         a = xchg(&c->async_write_error, 0);
1154         f = dm_bufio_issue_flush(c);
1155         if (a)
1156                 return a;
1157
1158         return f;
1159 }
1160 EXPORT_SYMBOL_GPL(dm_bufio_write_dirty_buffers);
1161
1162 /*
1163  * Use dm-io to send and empty barrier flush the device.
1164  */
1165 int dm_bufio_issue_flush(struct dm_bufio_client *c)
1166 {
1167         struct dm_io_request io_req = {
1168                 .bi_rw = REQ_FLUSH,
1169                 .mem.type = DM_IO_KMEM,
1170                 .mem.ptr.addr = NULL,
1171                 .client = c->dm_io,
1172         };
1173         struct dm_io_region io_reg = {
1174                 .bdev = c->bdev,
1175                 .sector = 0,
1176                 .count = 0,
1177         };
1178
1179         BUG_ON(dm_bufio_in_request());
1180
1181         return dm_io(&io_req, 1, &io_reg, NULL);
1182 }
1183 EXPORT_SYMBOL_GPL(dm_bufio_issue_flush);
1184
1185 /*
1186  * We first delete any other buffer that may be at that new location.
1187  *
1188  * Then, we write the buffer to the original location if it was dirty.
1189  *
1190  * Then, if we are the only one who is holding the buffer, relink the buffer
1191  * in the hash queue for the new location.
1192  *
1193  * If there was someone else holding the buffer, we write it to the new
1194  * location but not relink it, because that other user needs to have the buffer
1195  * at the same place.
1196  */
1197 void dm_bufio_release_move(struct dm_buffer *b, sector_t new_block)
1198 {
1199         struct dm_bufio_client *c = b->c;
1200         struct dm_buffer *new;
1201
1202         BUG_ON(dm_bufio_in_request());
1203
1204         dm_bufio_lock(c);
1205
1206 retry:
1207         new = __find(c, new_block);
1208         if (new) {
1209                 if (new->hold_count) {
1210                         __wait_for_free_buffer(c);
1211                         goto retry;
1212                 }
1213
1214                 /*
1215                  * FIXME: Is there any point waiting for a write that's going
1216                  * to be overwritten in a bit?
1217                  */
1218                 __make_buffer_clean(new);
1219                 __unlink_buffer(new);
1220                 __free_buffer_wake(new);
1221         }
1222
1223         BUG_ON(!b->hold_count);
1224         BUG_ON(test_bit(B_READING, &b->state));
1225
1226         __write_dirty_buffer(b);
1227         if (b->hold_count == 1) {
1228                 wait_on_bit(&b->state, B_WRITING,
1229                             do_io_schedule, TASK_UNINTERRUPTIBLE);
1230                 set_bit(B_DIRTY, &b->state);
1231                 __unlink_buffer(b);
1232                 __link_buffer(b, new_block, LIST_DIRTY);
1233         } else {
1234                 sector_t old_block;
1235                 wait_on_bit_lock(&b->state, B_WRITING,
1236                                  do_io_schedule, TASK_UNINTERRUPTIBLE);
1237                 /*
1238                  * Relink buffer to "new_block" so that write_callback
1239                  * sees "new_block" as a block number.
1240                  * After the write, link the buffer back to old_block.
1241                  * All this must be done in bufio lock, so that block number
1242                  * change isn't visible to other threads.
1243                  */
1244                 old_block = b->block;
1245                 __unlink_buffer(b);
1246                 __link_buffer(b, new_block, b->list_mode);
1247                 submit_io(b, WRITE, new_block, write_endio);
1248                 wait_on_bit(&b->state, B_WRITING,
1249                             do_io_schedule, TASK_UNINTERRUPTIBLE);
1250                 __unlink_buffer(b);
1251                 __link_buffer(b, old_block, b->list_mode);
1252         }
1253
1254         dm_bufio_unlock(c);
1255         dm_bufio_release(b);
1256 }
1257 EXPORT_SYMBOL_GPL(dm_bufio_release_move);
1258
1259 unsigned dm_bufio_get_block_size(struct dm_bufio_client *c)
1260 {
1261         return c->block_size;
1262 }
1263 EXPORT_SYMBOL_GPL(dm_bufio_get_block_size);
1264
1265 sector_t dm_bufio_get_device_size(struct dm_bufio_client *c)
1266 {
1267         return i_size_read(c->bdev->bd_inode) >>
1268                            (SECTOR_SHIFT + c->sectors_per_block_bits);
1269 }
1270 EXPORT_SYMBOL_GPL(dm_bufio_get_device_size);
1271
1272 sector_t dm_bufio_get_block_number(struct dm_buffer *b)
1273 {
1274         return b->block;
1275 }
1276 EXPORT_SYMBOL_GPL(dm_bufio_get_block_number);
1277
1278 void *dm_bufio_get_block_data(struct dm_buffer *b)
1279 {
1280         return b->data;
1281 }
1282 EXPORT_SYMBOL_GPL(dm_bufio_get_block_data);
1283
1284 void *dm_bufio_get_aux_data(struct dm_buffer *b)
1285 {
1286         return b + 1;
1287 }
1288 EXPORT_SYMBOL_GPL(dm_bufio_get_aux_data);
1289
1290 struct dm_bufio_client *dm_bufio_get_client(struct dm_buffer *b)
1291 {
1292         return b->c;
1293 }
1294 EXPORT_SYMBOL_GPL(dm_bufio_get_client);
1295
1296 static void drop_buffers(struct dm_bufio_client *c)
1297 {
1298         struct dm_buffer *b;
1299         int i;
1300
1301         BUG_ON(dm_bufio_in_request());
1302
1303         /*
1304          * An optimization so that the buffers are not written one-by-one.
1305          */
1306         dm_bufio_write_dirty_buffers_async(c);
1307
1308         dm_bufio_lock(c);
1309
1310         while ((b = __get_unclaimed_buffer(c)))
1311                 __free_buffer_wake(b);
1312
1313         for (i = 0; i < LIST_SIZE; i++)
1314                 list_for_each_entry(b, &c->lru[i], lru_list)
1315                         DMERR("leaked buffer %llx, hold count %u, list %d",
1316                               (unsigned long long)b->block, b->hold_count, i);
1317
1318         for (i = 0; i < LIST_SIZE; i++)
1319                 BUG_ON(!list_empty(&c->lru[i]));
1320
1321         dm_bufio_unlock(c);
1322 }
1323
1324 /*
1325  * Test if the buffer is unused and too old, and commit it.
1326  * At if noio is set, we must not do any I/O because we hold
1327  * dm_bufio_clients_lock and we would risk deadlock if the I/O gets rerouted to
1328  * different bufio client.
1329  */
1330 static int __cleanup_old_buffer(struct dm_buffer *b, gfp_t gfp,
1331                                 unsigned long max_jiffies)
1332 {
1333         if (jiffies - b->last_accessed < max_jiffies)
1334                 return 1;
1335
1336         if (!(gfp & __GFP_IO)) {
1337                 if (test_bit(B_READING, &b->state) ||
1338                     test_bit(B_WRITING, &b->state) ||
1339                     test_bit(B_DIRTY, &b->state))
1340                         return 1;
1341         }
1342
1343         if (b->hold_count)
1344                 return 1;
1345
1346         __make_buffer_clean(b);
1347         __unlink_buffer(b);
1348         __free_buffer_wake(b);
1349
1350         return 0;
1351 }
1352
1353 static void __scan(struct dm_bufio_client *c, unsigned long nr_to_scan,
1354                    struct shrink_control *sc)
1355 {
1356         int l;
1357         struct dm_buffer *b, *tmp;
1358
1359         for (l = 0; l < LIST_SIZE; l++) {
1360                 list_for_each_entry_safe_reverse(b, tmp, &c->lru[l], lru_list)
1361                         if (!__cleanup_old_buffer(b, sc->gfp_mask, 0) &&
1362                             !--nr_to_scan)
1363                                 return;
1364                 dm_bufio_cond_resched();
1365         }
1366 }
1367
1368 static int shrink(struct shrinker *shrinker, struct shrink_control *sc)
1369 {
1370         struct dm_bufio_client *c =
1371             container_of(shrinker, struct dm_bufio_client, shrinker);
1372         unsigned long r;
1373         unsigned long nr_to_scan = sc->nr_to_scan;
1374
1375         if (sc->gfp_mask & __GFP_IO)
1376                 dm_bufio_lock(c);
1377         else if (!dm_bufio_trylock(c))
1378                 return !nr_to_scan ? 0 : -1;
1379
1380         if (nr_to_scan)
1381                 __scan(c, nr_to_scan, sc);
1382
1383         r = c->n_buffers[LIST_CLEAN] + c->n_buffers[LIST_DIRTY];
1384         if (r > INT_MAX)
1385                 r = INT_MAX;
1386
1387         dm_bufio_unlock(c);
1388
1389         return r;
1390 }
1391
1392 /*
1393  * Create the buffering interface
1394  */
1395 struct dm_bufio_client *dm_bufio_client_create(struct block_device *bdev, unsigned block_size,
1396                                                unsigned reserved_buffers, unsigned aux_size,
1397                                                void (*alloc_callback)(struct dm_buffer *),
1398                                                void (*write_callback)(struct dm_buffer *))
1399 {
1400         int r;
1401         struct dm_bufio_client *c;
1402         unsigned i;
1403
1404         BUG_ON(block_size < 1 << SECTOR_SHIFT ||
1405                (block_size & (block_size - 1)));
1406
1407         c = kmalloc(sizeof(*c), GFP_KERNEL);
1408         if (!c) {
1409                 r = -ENOMEM;
1410                 goto bad_client;
1411         }
1412         c->cache_hash = vmalloc(sizeof(struct hlist_head) << DM_BUFIO_HASH_BITS);
1413         if (!c->cache_hash) {
1414                 r = -ENOMEM;
1415                 goto bad_hash;
1416         }
1417
1418         c->bdev = bdev;
1419         c->block_size = block_size;
1420         c->sectors_per_block_bits = ffs(block_size) - 1 - SECTOR_SHIFT;
1421         c->pages_per_block_bits = (ffs(block_size) - 1 >= PAGE_SHIFT) ?
1422                                   ffs(block_size) - 1 - PAGE_SHIFT : 0;
1423         c->blocks_per_page_bits = (ffs(block_size) - 1 < PAGE_SHIFT ?
1424                                   PAGE_SHIFT - (ffs(block_size) - 1) : 0);
1425
1426         c->aux_size = aux_size;
1427         c->alloc_callback = alloc_callback;
1428         c->write_callback = write_callback;
1429
1430         for (i = 0; i < LIST_SIZE; i++) {
1431                 INIT_LIST_HEAD(&c->lru[i]);
1432                 c->n_buffers[i] = 0;
1433         }
1434
1435         for (i = 0; i < 1 << DM_BUFIO_HASH_BITS; i++)
1436                 INIT_HLIST_HEAD(&c->cache_hash[i]);
1437
1438         mutex_init(&c->lock);
1439         INIT_LIST_HEAD(&c->reserved_buffers);
1440         c->need_reserved_buffers = reserved_buffers;
1441
1442         init_waitqueue_head(&c->free_buffer_wait);
1443         c->async_write_error = 0;
1444
1445         c->dm_io = dm_io_client_create();
1446         if (IS_ERR(c->dm_io)) {
1447                 r = PTR_ERR(c->dm_io);
1448                 goto bad_dm_io;
1449         }
1450
1451         mutex_lock(&dm_bufio_clients_lock);
1452         if (c->blocks_per_page_bits) {
1453                 if (!DM_BUFIO_CACHE_NAME(c)) {
1454                         DM_BUFIO_CACHE_NAME(c) = kasprintf(GFP_KERNEL, "dm_bufio_cache-%u", c->block_size);
1455                         if (!DM_BUFIO_CACHE_NAME(c)) {
1456                                 r = -ENOMEM;
1457                                 mutex_unlock(&dm_bufio_clients_lock);
1458                                 goto bad_cache;
1459                         }
1460                 }
1461
1462                 if (!DM_BUFIO_CACHE(c)) {
1463                         DM_BUFIO_CACHE(c) = kmem_cache_create(DM_BUFIO_CACHE_NAME(c),
1464                                                               c->block_size,
1465                                                               c->block_size, 0, NULL);
1466                         if (!DM_BUFIO_CACHE(c)) {
1467                                 r = -ENOMEM;
1468                                 mutex_unlock(&dm_bufio_clients_lock);
1469                                 goto bad_cache;
1470                         }
1471                 }
1472         }
1473         mutex_unlock(&dm_bufio_clients_lock);
1474
1475         while (c->need_reserved_buffers) {
1476                 struct dm_buffer *b = alloc_buffer(c, GFP_KERNEL);
1477
1478                 if (!b) {
1479                         r = -ENOMEM;
1480                         goto bad_buffer;
1481                 }
1482                 __free_buffer_wake(b);
1483         }
1484
1485         mutex_lock(&dm_bufio_clients_lock);
1486         dm_bufio_client_count++;
1487         list_add(&c->client_list, &dm_bufio_all_clients);
1488         __cache_size_refresh();
1489         mutex_unlock(&dm_bufio_clients_lock);
1490
1491         c->shrinker.shrink = shrink;
1492         c->shrinker.seeks = 1;
1493         c->shrinker.batch = 0;
1494         register_shrinker(&c->shrinker);
1495
1496         return c;
1497
1498 bad_buffer:
1499 bad_cache:
1500         while (!list_empty(&c->reserved_buffers)) {
1501                 struct dm_buffer *b = list_entry(c->reserved_buffers.next,
1502                                                  struct dm_buffer, lru_list);
1503                 list_del(&b->lru_list);
1504                 free_buffer(b);
1505         }
1506         dm_io_client_destroy(c->dm_io);
1507 bad_dm_io:
1508         vfree(c->cache_hash);
1509 bad_hash:
1510         kfree(c);
1511 bad_client:
1512         return ERR_PTR(r);
1513 }
1514 EXPORT_SYMBOL_GPL(dm_bufio_client_create);
1515
1516 /*
1517  * Free the buffering interface.
1518  * It is required that there are no references on any buffers.
1519  */
1520 void dm_bufio_client_destroy(struct dm_bufio_client *c)
1521 {
1522         unsigned i;
1523
1524         drop_buffers(c);
1525
1526         unregister_shrinker(&c->shrinker);
1527
1528         mutex_lock(&dm_bufio_clients_lock);
1529
1530         list_del(&c->client_list);
1531         dm_bufio_client_count--;
1532         __cache_size_refresh();
1533
1534         mutex_unlock(&dm_bufio_clients_lock);
1535
1536         for (i = 0; i < 1 << DM_BUFIO_HASH_BITS; i++)
1537                 BUG_ON(!hlist_empty(&c->cache_hash[i]));
1538
1539         BUG_ON(c->need_reserved_buffers);
1540
1541         while (!list_empty(&c->reserved_buffers)) {
1542                 struct dm_buffer *b = list_entry(c->reserved_buffers.next,
1543                                                  struct dm_buffer, lru_list);
1544                 list_del(&b->lru_list);
1545                 free_buffer(b);
1546         }
1547
1548         for (i = 0; i < LIST_SIZE; i++)
1549                 if (c->n_buffers[i])
1550                         DMERR("leaked buffer count %d: %ld", i, c->n_buffers[i]);
1551
1552         for (i = 0; i < LIST_SIZE; i++)
1553                 BUG_ON(c->n_buffers[i]);
1554
1555         dm_io_client_destroy(c->dm_io);
1556         vfree(c->cache_hash);
1557         kfree(c);
1558 }
1559 EXPORT_SYMBOL_GPL(dm_bufio_client_destroy);
1560
1561 static void cleanup_old_buffers(void)
1562 {
1563         unsigned long max_age = dm_bufio_max_age;
1564         struct dm_bufio_client *c;
1565
1566         barrier();
1567
1568         if (max_age > ULONG_MAX / HZ)
1569                 max_age = ULONG_MAX / HZ;
1570
1571         mutex_lock(&dm_bufio_clients_lock);
1572         list_for_each_entry(c, &dm_bufio_all_clients, client_list) {
1573                 if (!dm_bufio_trylock(c))
1574                         continue;
1575
1576                 while (!list_empty(&c->lru[LIST_CLEAN])) {
1577                         struct dm_buffer *b;
1578                         b = list_entry(c->lru[LIST_CLEAN].prev,
1579                                        struct dm_buffer, lru_list);
1580                         if (__cleanup_old_buffer(b, 0, max_age * HZ))
1581                                 break;
1582                         dm_bufio_cond_resched();
1583                 }
1584
1585                 dm_bufio_unlock(c);
1586                 dm_bufio_cond_resched();
1587         }
1588         mutex_unlock(&dm_bufio_clients_lock);
1589 }
1590
1591 static struct workqueue_struct *dm_bufio_wq;
1592 static struct delayed_work dm_bufio_work;
1593
1594 static void work_fn(struct work_struct *w)
1595 {
1596         cleanup_old_buffers();
1597
1598         queue_delayed_work(dm_bufio_wq, &dm_bufio_work,
1599                            DM_BUFIO_WORK_TIMER_SECS * HZ);
1600 }
1601
1602 /*----------------------------------------------------------------
1603  * Module setup
1604  *--------------------------------------------------------------*/
1605
1606 /*
1607  * This is called only once for the whole dm_bufio module.
1608  * It initializes memory limit.
1609  */
1610 static int __init dm_bufio_init(void)
1611 {
1612         __u64 mem;
1613
1614         dm_bufio_allocated_kmem_cache = 0;
1615         dm_bufio_allocated_get_free_pages = 0;
1616         dm_bufio_allocated_vmalloc = 0;
1617         dm_bufio_current_allocated = 0;
1618
1619         memset(&dm_bufio_caches, 0, sizeof dm_bufio_caches);
1620         memset(&dm_bufio_cache_names, 0, sizeof dm_bufio_cache_names);
1621
1622         mem = (__u64)((totalram_pages - totalhigh_pages) *
1623                       DM_BUFIO_MEMORY_PERCENT / 100) << PAGE_SHIFT;
1624
1625         if (mem > ULONG_MAX)
1626                 mem = ULONG_MAX;
1627
1628 #ifdef CONFIG_MMU
1629         /*
1630          * Get the size of vmalloc space the same way as VMALLOC_TOTAL
1631          * in fs/proc/internal.h
1632          */
1633         if (mem > (VMALLOC_END - VMALLOC_START) * DM_BUFIO_VMALLOC_PERCENT / 100)
1634                 mem = (VMALLOC_END - VMALLOC_START) * DM_BUFIO_VMALLOC_PERCENT / 100;
1635 #endif
1636
1637         dm_bufio_default_cache_size = mem;
1638
1639         mutex_lock(&dm_bufio_clients_lock);
1640         __cache_size_refresh();
1641         mutex_unlock(&dm_bufio_clients_lock);
1642
1643         dm_bufio_wq = create_singlethread_workqueue("dm_bufio_cache");
1644         if (!dm_bufio_wq)
1645                 return -ENOMEM;
1646
1647         INIT_DELAYED_WORK(&dm_bufio_work, work_fn);
1648         queue_delayed_work(dm_bufio_wq, &dm_bufio_work,
1649                            DM_BUFIO_WORK_TIMER_SECS * HZ);
1650
1651         return 0;
1652 }
1653
1654 /*
1655  * This is called once when unloading the dm_bufio module.
1656  */
1657 static void __exit dm_bufio_exit(void)
1658 {
1659         int bug = 0;
1660         int i;
1661
1662         cancel_delayed_work_sync(&dm_bufio_work);
1663         destroy_workqueue(dm_bufio_wq);
1664
1665         for (i = 0; i < ARRAY_SIZE(dm_bufio_caches); i++) {
1666                 struct kmem_cache *kc = dm_bufio_caches[i];
1667
1668                 if (kc)
1669                         kmem_cache_destroy(kc);
1670         }
1671
1672         for (i = 0; i < ARRAY_SIZE(dm_bufio_cache_names); i++)
1673                 kfree(dm_bufio_cache_names[i]);
1674
1675         if (dm_bufio_client_count) {
1676                 DMCRIT("%s: dm_bufio_client_count leaked: %d",
1677                         __func__, dm_bufio_client_count);
1678                 bug = 1;
1679         }
1680
1681         if (dm_bufio_current_allocated) {
1682                 DMCRIT("%s: dm_bufio_current_allocated leaked: %lu",
1683                         __func__, dm_bufio_current_allocated);
1684                 bug = 1;
1685         }
1686
1687         if (dm_bufio_allocated_get_free_pages) {
1688                 DMCRIT("%s: dm_bufio_allocated_get_free_pages leaked: %lu",
1689                        __func__, dm_bufio_allocated_get_free_pages);
1690                 bug = 1;
1691         }
1692
1693         if (dm_bufio_allocated_vmalloc) {
1694                 DMCRIT("%s: dm_bufio_vmalloc leaked: %lu",
1695                        __func__, dm_bufio_allocated_vmalloc);
1696                 bug = 1;
1697         }
1698
1699         if (bug)
1700                 BUG();
1701 }
1702
1703 module_init(dm_bufio_init)
1704 module_exit(dm_bufio_exit)
1705
1706 module_param_named(max_cache_size_bytes, dm_bufio_cache_size, ulong, S_IRUGO | S_IWUSR);
1707 MODULE_PARM_DESC(max_cache_size_bytes, "Size of metadata cache");
1708
1709 module_param_named(max_age_seconds, dm_bufio_max_age, uint, S_IRUGO | S_IWUSR);
1710 MODULE_PARM_DESC(max_age_seconds, "Max age of a buffer in seconds");
1711
1712 module_param_named(peak_allocated_bytes, dm_bufio_peak_allocated, ulong, S_IRUGO | S_IWUSR);
1713 MODULE_PARM_DESC(peak_allocated_bytes, "Tracks the maximum allocated memory");
1714
1715 module_param_named(allocated_kmem_cache_bytes, dm_bufio_allocated_kmem_cache, ulong, S_IRUGO);
1716 MODULE_PARM_DESC(allocated_kmem_cache_bytes, "Memory allocated with kmem_cache_alloc");
1717
1718 module_param_named(allocated_get_free_pages_bytes, dm_bufio_allocated_get_free_pages, ulong, S_IRUGO);
1719 MODULE_PARM_DESC(allocated_get_free_pages_bytes, "Memory allocated with get_free_pages");
1720
1721 module_param_named(allocated_vmalloc_bytes, dm_bufio_allocated_vmalloc, ulong, S_IRUGO);
1722 MODULE_PARM_DESC(allocated_vmalloc_bytes, "Memory allocated with vmalloc");
1723
1724 module_param_named(current_allocated_bytes, dm_bufio_current_allocated, ulong, S_IRUGO);
1725 MODULE_PARM_DESC(current_allocated_bytes, "Memory currently used by the cache");
1726
1727 MODULE_AUTHOR("Mikulas Patocka <dm-devel@redhat.com>");
1728 MODULE_DESCRIPTION(DM_NAME " buffered I/O library");
1729 MODULE_LICENSE("GPL");