4b940745ba9e3a2b8e73f2cbed17508848cad106
[platform/adaptation/renesas_rcar/renesas_kernel.git] / drivers / md / dm-thin.c
1 /*
2  * Copyright (C) 2011-2012 Red Hat UK.
3  *
4  * This file is released under the GPL.
5  */
6
7 #include "dm-thin-metadata.h"
8 #include "dm-bio-prison.h"
9 #include "dm.h"
10
11 #include <linux/device-mapper.h>
12 #include <linux/dm-io.h>
13 #include <linux/dm-kcopyd.h>
14 #include <linux/list.h>
15 #include <linux/init.h>
16 #include <linux/module.h>
17 #include <linux/slab.h>
18
19 #define DM_MSG_PREFIX   "thin"
20
21 /*
22  * Tunable constants
23  */
24 #define ENDIO_HOOK_POOL_SIZE 1024
25 #define MAPPING_POOL_SIZE 1024
26 #define PRISON_CELLS 1024
27 #define COMMIT_PERIOD HZ
28
29 /*
30  * The block size of the device holding pool data must be
31  * between 64KB and 1GB.
32  */
33 #define DATA_DEV_BLOCK_SIZE_MIN_SECTORS (64 * 1024 >> SECTOR_SHIFT)
34 #define DATA_DEV_BLOCK_SIZE_MAX_SECTORS (1024 * 1024 * 1024 >> SECTOR_SHIFT)
35
36 /*
37  * Device id is restricted to 24 bits.
38  */
39 #define MAX_DEV_ID ((1 << 24) - 1)
40
41 /*
42  * How do we handle breaking sharing of data blocks?
43  * =================================================
44  *
45  * We use a standard copy-on-write btree to store the mappings for the
46  * devices (note I'm talking about copy-on-write of the metadata here, not
47  * the data).  When you take an internal snapshot you clone the root node
48  * of the origin btree.  After this there is no concept of an origin or a
49  * snapshot.  They are just two device trees that happen to point to the
50  * same data blocks.
51  *
52  * When we get a write in we decide if it's to a shared data block using
53  * some timestamp magic.  If it is, we have to break sharing.
54  *
55  * Let's say we write to a shared block in what was the origin.  The
56  * steps are:
57  *
58  * i) plug io further to this physical block. (see bio_prison code).
59  *
60  * ii) quiesce any read io to that shared data block.  Obviously
61  * including all devices that share this block.  (see dm_deferred_set code)
62  *
63  * iii) copy the data block to a newly allocate block.  This step can be
64  * missed out if the io covers the block. (schedule_copy).
65  *
66  * iv) insert the new mapping into the origin's btree
67  * (process_prepared_mapping).  This act of inserting breaks some
68  * sharing of btree nodes between the two devices.  Breaking sharing only
69  * effects the btree of that specific device.  Btrees for the other
70  * devices that share the block never change.  The btree for the origin
71  * device as it was after the last commit is untouched, ie. we're using
72  * persistent data structures in the functional programming sense.
73  *
74  * v) unplug io to this physical block, including the io that triggered
75  * the breaking of sharing.
76  *
77  * Steps (ii) and (iii) occur in parallel.
78  *
79  * The metadata _doesn't_ need to be committed before the io continues.  We
80  * get away with this because the io is always written to a _new_ block.
81  * If there's a crash, then:
82  *
83  * - The origin mapping will point to the old origin block (the shared
84  * one).  This will contain the data as it was before the io that triggered
85  * the breaking of sharing came in.
86  *
87  * - The snap mapping still points to the old block.  As it would after
88  * the commit.
89  *
90  * The downside of this scheme is the timestamp magic isn't perfect, and
91  * will continue to think that data block in the snapshot device is shared
92  * even after the write to the origin has broken sharing.  I suspect data
93  * blocks will typically be shared by many different devices, so we're
94  * breaking sharing n + 1 times, rather than n, where n is the number of
95  * devices that reference this data block.  At the moment I think the
96  * benefits far, far outweigh the disadvantages.
97  */
98
99 /*----------------------------------------------------------------*/
100
101 /*
102  * Key building.
103  */
104 static void build_data_key(struct dm_thin_device *td,
105                            dm_block_t b, struct dm_cell_key *key)
106 {
107         key->virtual = 0;
108         key->dev = dm_thin_dev_id(td);
109         key->block = b;
110 }
111
112 static void build_virtual_key(struct dm_thin_device *td, dm_block_t b,
113                               struct dm_cell_key *key)
114 {
115         key->virtual = 1;
116         key->dev = dm_thin_dev_id(td);
117         key->block = b;
118 }
119
120 /*----------------------------------------------------------------*/
121
122 /*
123  * A pool device ties together a metadata device and a data device.  It
124  * also provides the interface for creating and destroying internal
125  * devices.
126  */
127 struct dm_thin_new_mapping;
128
129 /*
130  * The pool runs in 3 modes.  Ordered in degraded order for comparisons.
131  */
132 enum pool_mode {
133         PM_WRITE,               /* metadata may be changed */
134         PM_READ_ONLY,           /* metadata may not be changed */
135         PM_FAIL,                /* all I/O fails */
136 };
137
138 struct pool_features {
139         enum pool_mode mode;
140
141         bool zero_new_blocks:1;
142         bool discard_enabled:1;
143         bool discard_passdown:1;
144 };
145
146 struct thin_c;
147 typedef void (*process_bio_fn)(struct thin_c *tc, struct bio *bio);
148 typedef void (*process_mapping_fn)(struct dm_thin_new_mapping *m);
149
150 struct pool {
151         struct list_head list;
152         struct dm_target *ti;   /* Only set if a pool target is bound */
153
154         struct mapped_device *pool_md;
155         struct block_device *md_dev;
156         struct dm_pool_metadata *pmd;
157
158         dm_block_t low_water_blocks;
159         uint32_t sectors_per_block;
160         int sectors_per_block_shift;
161
162         struct pool_features pf;
163         unsigned low_water_triggered:1; /* A dm event has been sent */
164         unsigned no_free_space:1;       /* A -ENOSPC warning has been issued */
165
166         struct dm_bio_prison *prison;
167         struct dm_kcopyd_client *copier;
168
169         struct workqueue_struct *wq;
170         struct work_struct worker;
171         struct delayed_work waker;
172
173         unsigned long last_commit_jiffies;
174         unsigned ref_count;
175
176         spinlock_t lock;
177         struct bio_list deferred_bios;
178         struct bio_list deferred_flush_bios;
179         struct list_head prepared_mappings;
180         struct list_head prepared_discards;
181
182         struct bio_list retry_on_resume_list;
183
184         struct dm_deferred_set *shared_read_ds;
185         struct dm_deferred_set *all_io_ds;
186
187         struct dm_thin_new_mapping *next_mapping;
188         mempool_t *mapping_pool;
189         mempool_t *endio_hook_pool;
190
191         process_bio_fn process_bio;
192         process_bio_fn process_discard;
193
194         process_mapping_fn process_prepared_mapping;
195         process_mapping_fn process_prepared_discard;
196 };
197
198 static enum pool_mode get_pool_mode(struct pool *pool);
199 static void set_pool_mode(struct pool *pool, enum pool_mode mode);
200
201 /*
202  * Target context for a pool.
203  */
204 struct pool_c {
205         struct dm_target *ti;
206         struct pool *pool;
207         struct dm_dev *data_dev;
208         struct dm_dev *metadata_dev;
209         struct dm_target_callbacks callbacks;
210
211         dm_block_t low_water_blocks;
212         struct pool_features requested_pf; /* Features requested during table load */
213         struct pool_features adjusted_pf;  /* Features used after adjusting for constituent devices */
214 };
215
216 /*
217  * Target context for a thin.
218  */
219 struct thin_c {
220         struct dm_dev *pool_dev;
221         struct dm_dev *origin_dev;
222         dm_thin_id dev_id;
223
224         struct pool *pool;
225         struct dm_thin_device *td;
226 };
227
228 /*----------------------------------------------------------------*/
229
230 /*
231  * A global list of pools that uses a struct mapped_device as a key.
232  */
233 static struct dm_thin_pool_table {
234         struct mutex mutex;
235         struct list_head pools;
236 } dm_thin_pool_table;
237
238 static void pool_table_init(void)
239 {
240         mutex_init(&dm_thin_pool_table.mutex);
241         INIT_LIST_HEAD(&dm_thin_pool_table.pools);
242 }
243
244 static void __pool_table_insert(struct pool *pool)
245 {
246         BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
247         list_add(&pool->list, &dm_thin_pool_table.pools);
248 }
249
250 static void __pool_table_remove(struct pool *pool)
251 {
252         BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
253         list_del(&pool->list);
254 }
255
256 static struct pool *__pool_table_lookup(struct mapped_device *md)
257 {
258         struct pool *pool = NULL, *tmp;
259
260         BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
261
262         list_for_each_entry(tmp, &dm_thin_pool_table.pools, list) {
263                 if (tmp->pool_md == md) {
264                         pool = tmp;
265                         break;
266                 }
267         }
268
269         return pool;
270 }
271
272 static struct pool *__pool_table_lookup_metadata_dev(struct block_device *md_dev)
273 {
274         struct pool *pool = NULL, *tmp;
275
276         BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
277
278         list_for_each_entry(tmp, &dm_thin_pool_table.pools, list) {
279                 if (tmp->md_dev == md_dev) {
280                         pool = tmp;
281                         break;
282                 }
283         }
284
285         return pool;
286 }
287
288 /*----------------------------------------------------------------*/
289
290 struct dm_thin_endio_hook {
291         struct thin_c *tc;
292         struct dm_deferred_entry *shared_read_entry;
293         struct dm_deferred_entry *all_io_entry;
294         struct dm_thin_new_mapping *overwrite_mapping;
295 };
296
297 static void __requeue_bio_list(struct thin_c *tc, struct bio_list *master)
298 {
299         struct bio *bio;
300         struct bio_list bios;
301
302         bio_list_init(&bios);
303         bio_list_merge(&bios, master);
304         bio_list_init(master);
305
306         while ((bio = bio_list_pop(&bios))) {
307                 struct dm_thin_endio_hook *h = dm_get_mapinfo(bio)->ptr;
308
309                 if (h->tc == tc)
310                         bio_endio(bio, DM_ENDIO_REQUEUE);
311                 else
312                         bio_list_add(master, bio);
313         }
314 }
315
316 static void requeue_io(struct thin_c *tc)
317 {
318         struct pool *pool = tc->pool;
319         unsigned long flags;
320
321         spin_lock_irqsave(&pool->lock, flags);
322         __requeue_bio_list(tc, &pool->deferred_bios);
323         __requeue_bio_list(tc, &pool->retry_on_resume_list);
324         spin_unlock_irqrestore(&pool->lock, flags);
325 }
326
327 /*
328  * This section of code contains the logic for processing a thin device's IO.
329  * Much of the code depends on pool object resources (lists, workqueues, etc)
330  * but most is exclusively called from the thin target rather than the thin-pool
331  * target.
332  */
333
334 static dm_block_t get_bio_block(struct thin_c *tc, struct bio *bio)
335 {
336         sector_t block_nr = bio->bi_sector;
337
338         if (tc->pool->sectors_per_block_shift < 0)
339                 (void) sector_div(block_nr, tc->pool->sectors_per_block);
340         else
341                 block_nr >>= tc->pool->sectors_per_block_shift;
342
343         return block_nr;
344 }
345
346 static void remap(struct thin_c *tc, struct bio *bio, dm_block_t block)
347 {
348         struct pool *pool = tc->pool;
349         sector_t bi_sector = bio->bi_sector;
350
351         bio->bi_bdev = tc->pool_dev->bdev;
352         if (tc->pool->sectors_per_block_shift < 0)
353                 bio->bi_sector = (block * pool->sectors_per_block) +
354                                  sector_div(bi_sector, pool->sectors_per_block);
355         else
356                 bio->bi_sector = (block << pool->sectors_per_block_shift) |
357                                 (bi_sector & (pool->sectors_per_block - 1));
358 }
359
360 static void remap_to_origin(struct thin_c *tc, struct bio *bio)
361 {
362         bio->bi_bdev = tc->origin_dev->bdev;
363 }
364
365 static int bio_triggers_commit(struct thin_c *tc, struct bio *bio)
366 {
367         return (bio->bi_rw & (REQ_FLUSH | REQ_FUA)) &&
368                 dm_thin_changed_this_transaction(tc->td);
369 }
370
371 static void inc_all_io_entry(struct pool *pool, struct bio *bio)
372 {
373         struct dm_thin_endio_hook *h;
374
375         if (bio->bi_rw & REQ_DISCARD)
376                 return;
377
378         h = dm_get_mapinfo(bio)->ptr;
379         h->all_io_entry = dm_deferred_entry_inc(pool->all_io_ds);
380 }
381
382 static void issue(struct thin_c *tc, struct bio *bio)
383 {
384         struct pool *pool = tc->pool;
385         unsigned long flags;
386
387         if (!bio_triggers_commit(tc, bio)) {
388                 generic_make_request(bio);
389                 return;
390         }
391
392         /*
393          * Complete bio with an error if earlier I/O caused changes to
394          * the metadata that can't be committed e.g, due to I/O errors
395          * on the metadata device.
396          */
397         if (dm_thin_aborted_changes(tc->td)) {
398                 bio_io_error(bio);
399                 return;
400         }
401
402         /*
403          * Batch together any bios that trigger commits and then issue a
404          * single commit for them in process_deferred_bios().
405          */
406         spin_lock_irqsave(&pool->lock, flags);
407         bio_list_add(&pool->deferred_flush_bios, bio);
408         spin_unlock_irqrestore(&pool->lock, flags);
409 }
410
411 static void remap_to_origin_and_issue(struct thin_c *tc, struct bio *bio)
412 {
413         remap_to_origin(tc, bio);
414         issue(tc, bio);
415 }
416
417 static void remap_and_issue(struct thin_c *tc, struct bio *bio,
418                             dm_block_t block)
419 {
420         remap(tc, bio, block);
421         issue(tc, bio);
422 }
423
424 /*
425  * wake_worker() is used when new work is queued and when pool_resume is
426  * ready to continue deferred IO processing.
427  */
428 static void wake_worker(struct pool *pool)
429 {
430         queue_work(pool->wq, &pool->worker);
431 }
432
433 /*----------------------------------------------------------------*/
434
435 /*
436  * Bio endio functions.
437  */
438 struct dm_thin_new_mapping {
439         struct list_head list;
440
441         unsigned quiesced:1;
442         unsigned prepared:1;
443         unsigned pass_discard:1;
444
445         struct thin_c *tc;
446         dm_block_t virt_block;
447         dm_block_t data_block;
448         struct dm_bio_prison_cell *cell, *cell2;
449         int err;
450
451         /*
452          * If the bio covers the whole area of a block then we can avoid
453          * zeroing or copying.  Instead this bio is hooked.  The bio will
454          * still be in the cell, so care has to be taken to avoid issuing
455          * the bio twice.
456          */
457         struct bio *bio;
458         bio_end_io_t *saved_bi_end_io;
459 };
460
461 static void __maybe_add_mapping(struct dm_thin_new_mapping *m)
462 {
463         struct pool *pool = m->tc->pool;
464
465         if (m->quiesced && m->prepared) {
466                 list_add(&m->list, &pool->prepared_mappings);
467                 wake_worker(pool);
468         }
469 }
470
471 static void copy_complete(int read_err, unsigned long write_err, void *context)
472 {
473         unsigned long flags;
474         struct dm_thin_new_mapping *m = context;
475         struct pool *pool = m->tc->pool;
476
477         m->err = read_err || write_err ? -EIO : 0;
478
479         spin_lock_irqsave(&pool->lock, flags);
480         m->prepared = 1;
481         __maybe_add_mapping(m);
482         spin_unlock_irqrestore(&pool->lock, flags);
483 }
484
485 static void overwrite_endio(struct bio *bio, int err)
486 {
487         unsigned long flags;
488         struct dm_thin_endio_hook *h = dm_get_mapinfo(bio)->ptr;
489         struct dm_thin_new_mapping *m = h->overwrite_mapping;
490         struct pool *pool = m->tc->pool;
491
492         m->err = err;
493
494         spin_lock_irqsave(&pool->lock, flags);
495         m->prepared = 1;
496         __maybe_add_mapping(m);
497         spin_unlock_irqrestore(&pool->lock, flags);
498 }
499
500 /*----------------------------------------------------------------*/
501
502 /*
503  * Workqueue.
504  */
505
506 /*
507  * Prepared mapping jobs.
508  */
509
510 /*
511  * This sends the bios in the cell back to the deferred_bios list.
512  */
513 static void cell_defer(struct thin_c *tc, struct dm_bio_prison_cell *cell)
514 {
515         struct pool *pool = tc->pool;
516         unsigned long flags;
517
518         spin_lock_irqsave(&pool->lock, flags);
519         dm_cell_release(cell, &pool->deferred_bios);
520         spin_unlock_irqrestore(&tc->pool->lock, flags);
521
522         wake_worker(pool);
523 }
524
525 /*
526  * Same as cell_defer except it omits the original holder of the cell.
527  */
528 static void cell_defer_no_holder(struct thin_c *tc, struct dm_bio_prison_cell *cell)
529 {
530         struct pool *pool = tc->pool;
531         unsigned long flags;
532
533         spin_lock_irqsave(&pool->lock, flags);
534         dm_cell_release_no_holder(cell, &pool->deferred_bios);
535         spin_unlock_irqrestore(&pool->lock, flags);
536
537         wake_worker(pool);
538 }
539
540 static void process_prepared_mapping_fail(struct dm_thin_new_mapping *m)
541 {
542         if (m->bio)
543                 m->bio->bi_end_io = m->saved_bi_end_io;
544         dm_cell_error(m->cell);
545         list_del(&m->list);
546         mempool_free(m, m->tc->pool->mapping_pool);
547 }
548 static void process_prepared_mapping(struct dm_thin_new_mapping *m)
549 {
550         struct thin_c *tc = m->tc;
551         struct bio *bio;
552         int r;
553
554         bio = m->bio;
555         if (bio)
556                 bio->bi_end_io = m->saved_bi_end_io;
557
558         if (m->err) {
559                 dm_cell_error(m->cell);
560                 goto out;
561         }
562
563         /*
564          * Commit the prepared block into the mapping btree.
565          * Any I/O for this block arriving after this point will get
566          * remapped to it directly.
567          */
568         r = dm_thin_insert_block(tc->td, m->virt_block, m->data_block);
569         if (r) {
570                 DMERR_LIMIT("dm_thin_insert_block() failed");
571                 dm_cell_error(m->cell);
572                 goto out;
573         }
574
575         /*
576          * Release any bios held while the block was being provisioned.
577          * If we are processing a write bio that completely covers the block,
578          * we already processed it so can ignore it now when processing
579          * the bios in the cell.
580          */
581         if (bio) {
582                 cell_defer_no_holder(tc, m->cell);
583                 bio_endio(bio, 0);
584         } else
585                 cell_defer(tc, m->cell);
586
587 out:
588         list_del(&m->list);
589         mempool_free(m, tc->pool->mapping_pool);
590 }
591
592 static void process_prepared_discard_fail(struct dm_thin_new_mapping *m)
593 {
594         struct thin_c *tc = m->tc;
595
596         bio_io_error(m->bio);
597         cell_defer_no_holder(tc, m->cell);
598         cell_defer_no_holder(tc, m->cell2);
599         mempool_free(m, tc->pool->mapping_pool);
600 }
601
602 static void process_prepared_discard_passdown(struct dm_thin_new_mapping *m)
603 {
604         struct thin_c *tc = m->tc;
605
606         inc_all_io_entry(tc->pool, m->bio);
607         cell_defer_no_holder(tc, m->cell);
608         cell_defer_no_holder(tc, m->cell2);
609
610         if (m->pass_discard)
611                 remap_and_issue(tc, m->bio, m->data_block);
612         else
613                 bio_endio(m->bio, 0);
614
615         mempool_free(m, tc->pool->mapping_pool);
616 }
617
618 static void process_prepared_discard(struct dm_thin_new_mapping *m)
619 {
620         int r;
621         struct thin_c *tc = m->tc;
622
623         r = dm_thin_remove_block(tc->td, m->virt_block);
624         if (r)
625                 DMERR_LIMIT("dm_thin_remove_block() failed");
626
627         process_prepared_discard_passdown(m);
628 }
629
630 static void process_prepared(struct pool *pool, struct list_head *head,
631                              process_mapping_fn *fn)
632 {
633         unsigned long flags;
634         struct list_head maps;
635         struct dm_thin_new_mapping *m, *tmp;
636
637         INIT_LIST_HEAD(&maps);
638         spin_lock_irqsave(&pool->lock, flags);
639         list_splice_init(head, &maps);
640         spin_unlock_irqrestore(&pool->lock, flags);
641
642         list_for_each_entry_safe(m, tmp, &maps, list)
643                 (*fn)(m);
644 }
645
646 /*
647  * Deferred bio jobs.
648  */
649 static int io_overlaps_block(struct pool *pool, struct bio *bio)
650 {
651         return bio->bi_size == (pool->sectors_per_block << SECTOR_SHIFT);
652 }
653
654 static int io_overwrites_block(struct pool *pool, struct bio *bio)
655 {
656         return (bio_data_dir(bio) == WRITE) &&
657                 io_overlaps_block(pool, bio);
658 }
659
660 static void save_and_set_endio(struct bio *bio, bio_end_io_t **save,
661                                bio_end_io_t *fn)
662 {
663         *save = bio->bi_end_io;
664         bio->bi_end_io = fn;
665 }
666
667 static int ensure_next_mapping(struct pool *pool)
668 {
669         if (pool->next_mapping)
670                 return 0;
671
672         pool->next_mapping = mempool_alloc(pool->mapping_pool, GFP_ATOMIC);
673
674         return pool->next_mapping ? 0 : -ENOMEM;
675 }
676
677 static struct dm_thin_new_mapping *get_next_mapping(struct pool *pool)
678 {
679         struct dm_thin_new_mapping *r = pool->next_mapping;
680
681         BUG_ON(!pool->next_mapping);
682
683         pool->next_mapping = NULL;
684
685         return r;
686 }
687
688 static void schedule_copy(struct thin_c *tc, dm_block_t virt_block,
689                           struct dm_dev *origin, dm_block_t data_origin,
690                           dm_block_t data_dest,
691                           struct dm_bio_prison_cell *cell, struct bio *bio)
692 {
693         int r;
694         struct pool *pool = tc->pool;
695         struct dm_thin_new_mapping *m = get_next_mapping(pool);
696
697         INIT_LIST_HEAD(&m->list);
698         m->quiesced = 0;
699         m->prepared = 0;
700         m->tc = tc;
701         m->virt_block = virt_block;
702         m->data_block = data_dest;
703         m->cell = cell;
704         m->err = 0;
705         m->bio = NULL;
706
707         if (!dm_deferred_set_add_work(pool->shared_read_ds, &m->list))
708                 m->quiesced = 1;
709
710         /*
711          * IO to pool_dev remaps to the pool target's data_dev.
712          *
713          * If the whole block of data is being overwritten, we can issue the
714          * bio immediately. Otherwise we use kcopyd to clone the data first.
715          */
716         if (io_overwrites_block(pool, bio)) {
717                 struct dm_thin_endio_hook *h = dm_get_mapinfo(bio)->ptr;
718
719                 h->overwrite_mapping = m;
720                 m->bio = bio;
721                 save_and_set_endio(bio, &m->saved_bi_end_io, overwrite_endio);
722                 inc_all_io_entry(pool, bio);
723                 remap_and_issue(tc, bio, data_dest);
724         } else {
725                 struct dm_io_region from, to;
726
727                 from.bdev = origin->bdev;
728                 from.sector = data_origin * pool->sectors_per_block;
729                 from.count = pool->sectors_per_block;
730
731                 to.bdev = tc->pool_dev->bdev;
732                 to.sector = data_dest * pool->sectors_per_block;
733                 to.count = pool->sectors_per_block;
734
735                 r = dm_kcopyd_copy(pool->copier, &from, 1, &to,
736                                    0, copy_complete, m);
737                 if (r < 0) {
738                         mempool_free(m, pool->mapping_pool);
739                         DMERR_LIMIT("dm_kcopyd_copy() failed");
740                         dm_cell_error(cell);
741                 }
742         }
743 }
744
745 static void schedule_internal_copy(struct thin_c *tc, dm_block_t virt_block,
746                                    dm_block_t data_origin, dm_block_t data_dest,
747                                    struct dm_bio_prison_cell *cell, struct bio *bio)
748 {
749         schedule_copy(tc, virt_block, tc->pool_dev,
750                       data_origin, data_dest, cell, bio);
751 }
752
753 static void schedule_external_copy(struct thin_c *tc, dm_block_t virt_block,
754                                    dm_block_t data_dest,
755                                    struct dm_bio_prison_cell *cell, struct bio *bio)
756 {
757         schedule_copy(tc, virt_block, tc->origin_dev,
758                       virt_block, data_dest, cell, bio);
759 }
760
761 static void schedule_zero(struct thin_c *tc, dm_block_t virt_block,
762                           dm_block_t data_block, struct dm_bio_prison_cell *cell,
763                           struct bio *bio)
764 {
765         struct pool *pool = tc->pool;
766         struct dm_thin_new_mapping *m = get_next_mapping(pool);
767
768         INIT_LIST_HEAD(&m->list);
769         m->quiesced = 1;
770         m->prepared = 0;
771         m->tc = tc;
772         m->virt_block = virt_block;
773         m->data_block = data_block;
774         m->cell = cell;
775         m->err = 0;
776         m->bio = NULL;
777
778         /*
779          * If the whole block of data is being overwritten or we are not
780          * zeroing pre-existing data, we can issue the bio immediately.
781          * Otherwise we use kcopyd to zero the data first.
782          */
783         if (!pool->pf.zero_new_blocks)
784                 process_prepared_mapping(m);
785
786         else if (io_overwrites_block(pool, bio)) {
787                 struct dm_thin_endio_hook *h = dm_get_mapinfo(bio)->ptr;
788
789                 h->overwrite_mapping = m;
790                 m->bio = bio;
791                 save_and_set_endio(bio, &m->saved_bi_end_io, overwrite_endio);
792                 inc_all_io_entry(pool, bio);
793                 remap_and_issue(tc, bio, data_block);
794         } else {
795                 int r;
796                 struct dm_io_region to;
797
798                 to.bdev = tc->pool_dev->bdev;
799                 to.sector = data_block * pool->sectors_per_block;
800                 to.count = pool->sectors_per_block;
801
802                 r = dm_kcopyd_zero(pool->copier, 1, &to, 0, copy_complete, m);
803                 if (r < 0) {
804                         mempool_free(m, pool->mapping_pool);
805                         DMERR_LIMIT("dm_kcopyd_zero() failed");
806                         dm_cell_error(cell);
807                 }
808         }
809 }
810
811 static int commit(struct pool *pool)
812 {
813         int r;
814
815         r = dm_pool_commit_metadata(pool->pmd);
816         if (r)
817                 DMERR_LIMIT("commit failed: error = %d", r);
818
819         return r;
820 }
821
822 /*
823  * A non-zero return indicates read_only or fail_io mode.
824  * Many callers don't care about the return value.
825  */
826 static int commit_or_fallback(struct pool *pool)
827 {
828         int r;
829
830         if (get_pool_mode(pool) != PM_WRITE)
831                 return -EINVAL;
832
833         r = commit(pool);
834         if (r)
835                 set_pool_mode(pool, PM_READ_ONLY);
836
837         return r;
838 }
839
840 static int alloc_data_block(struct thin_c *tc, dm_block_t *result)
841 {
842         int r;
843         dm_block_t free_blocks;
844         unsigned long flags;
845         struct pool *pool = tc->pool;
846
847         r = dm_pool_get_free_block_count(pool->pmd, &free_blocks);
848         if (r)
849                 return r;
850
851         if (free_blocks <= pool->low_water_blocks && !pool->low_water_triggered) {
852                 DMWARN("%s: reached low water mark, sending event.",
853                        dm_device_name(pool->pool_md));
854                 spin_lock_irqsave(&pool->lock, flags);
855                 pool->low_water_triggered = 1;
856                 spin_unlock_irqrestore(&pool->lock, flags);
857                 dm_table_event(pool->ti->table);
858         }
859
860         if (!free_blocks) {
861                 if (pool->no_free_space)
862                         return -ENOSPC;
863                 else {
864                         /*
865                          * Try to commit to see if that will free up some
866                          * more space.
867                          */
868                         (void) commit_or_fallback(pool);
869
870                         r = dm_pool_get_free_block_count(pool->pmd, &free_blocks);
871                         if (r)
872                                 return r;
873
874                         /*
875                          * If we still have no space we set a flag to avoid
876                          * doing all this checking and return -ENOSPC.
877                          */
878                         if (!free_blocks) {
879                                 DMWARN("%s: no free space available.",
880                                        dm_device_name(pool->pool_md));
881                                 spin_lock_irqsave(&pool->lock, flags);
882                                 pool->no_free_space = 1;
883                                 spin_unlock_irqrestore(&pool->lock, flags);
884                                 return -ENOSPC;
885                         }
886                 }
887         }
888
889         r = dm_pool_alloc_data_block(pool->pmd, result);
890         if (r)
891                 return r;
892
893         return 0;
894 }
895
896 /*
897  * If we have run out of space, queue bios until the device is
898  * resumed, presumably after having been reloaded with more space.
899  */
900 static void retry_on_resume(struct bio *bio)
901 {
902         struct dm_thin_endio_hook *h = dm_get_mapinfo(bio)->ptr;
903         struct thin_c *tc = h->tc;
904         struct pool *pool = tc->pool;
905         unsigned long flags;
906
907         spin_lock_irqsave(&pool->lock, flags);
908         bio_list_add(&pool->retry_on_resume_list, bio);
909         spin_unlock_irqrestore(&pool->lock, flags);
910 }
911
912 static void no_space(struct dm_bio_prison_cell *cell)
913 {
914         struct bio *bio;
915         struct bio_list bios;
916
917         bio_list_init(&bios);
918         dm_cell_release(cell, &bios);
919
920         while ((bio = bio_list_pop(&bios)))
921                 retry_on_resume(bio);
922 }
923
924 static void process_discard(struct thin_c *tc, struct bio *bio)
925 {
926         int r;
927         unsigned long flags;
928         struct pool *pool = tc->pool;
929         struct dm_bio_prison_cell *cell, *cell2;
930         struct dm_cell_key key, key2;
931         dm_block_t block = get_bio_block(tc, bio);
932         struct dm_thin_lookup_result lookup_result;
933         struct dm_thin_new_mapping *m;
934
935         build_virtual_key(tc->td, block, &key);
936         if (dm_bio_detain(tc->pool->prison, &key, bio, &cell))
937                 return;
938
939         r = dm_thin_find_block(tc->td, block, 1, &lookup_result);
940         switch (r) {
941         case 0:
942                 /*
943                  * Check nobody is fiddling with this pool block.  This can
944                  * happen if someone's in the process of breaking sharing
945                  * on this block.
946                  */
947                 build_data_key(tc->td, lookup_result.block, &key2);
948                 if (dm_bio_detain(tc->pool->prison, &key2, bio, &cell2)) {
949                         cell_defer_no_holder(tc, cell);
950                         break;
951                 }
952
953                 if (io_overlaps_block(pool, bio)) {
954                         /*
955                          * IO may still be going to the destination block.  We must
956                          * quiesce before we can do the removal.
957                          */
958                         m = get_next_mapping(pool);
959                         m->tc = tc;
960                         m->pass_discard = (!lookup_result.shared) && pool->pf.discard_passdown;
961                         m->virt_block = block;
962                         m->data_block = lookup_result.block;
963                         m->cell = cell;
964                         m->cell2 = cell2;
965                         m->err = 0;
966                         m->bio = bio;
967
968                         if (!dm_deferred_set_add_work(pool->all_io_ds, &m->list)) {
969                                 spin_lock_irqsave(&pool->lock, flags);
970                                 list_add(&m->list, &pool->prepared_discards);
971                                 spin_unlock_irqrestore(&pool->lock, flags);
972                                 wake_worker(pool);
973                         }
974                 } else {
975                         inc_all_io_entry(pool, bio);
976                         cell_defer_no_holder(tc, cell);
977                         cell_defer_no_holder(tc, cell2);
978
979                         /*
980                          * The DM core makes sure that the discard doesn't span
981                          * a block boundary.  So we submit the discard of a
982                          * partial block appropriately.
983                          */
984                         if ((!lookup_result.shared) && pool->pf.discard_passdown)
985                                 remap_and_issue(tc, bio, lookup_result.block);
986                         else
987                                 bio_endio(bio, 0);
988                 }
989                 break;
990
991         case -ENODATA:
992                 /*
993                  * It isn't provisioned, just forget it.
994                  */
995                 cell_defer_no_holder(tc, cell);
996                 bio_endio(bio, 0);
997                 break;
998
999         default:
1000                 DMERR_LIMIT("%s: dm_thin_find_block() failed: error = %d",
1001                             __func__, r);
1002                 cell_defer_no_holder(tc, cell);
1003                 bio_io_error(bio);
1004                 break;
1005         }
1006 }
1007
1008 static void break_sharing(struct thin_c *tc, struct bio *bio, dm_block_t block,
1009                           struct dm_cell_key *key,
1010                           struct dm_thin_lookup_result *lookup_result,
1011                           struct dm_bio_prison_cell *cell)
1012 {
1013         int r;
1014         dm_block_t data_block;
1015
1016         r = alloc_data_block(tc, &data_block);
1017         switch (r) {
1018         case 0:
1019                 schedule_internal_copy(tc, block, lookup_result->block,
1020                                        data_block, cell, bio);
1021                 break;
1022
1023         case -ENOSPC:
1024                 no_space(cell);
1025                 break;
1026
1027         default:
1028                 DMERR_LIMIT("%s: alloc_data_block() failed: error = %d",
1029                             __func__, r);
1030                 dm_cell_error(cell);
1031                 break;
1032         }
1033 }
1034
1035 static void process_shared_bio(struct thin_c *tc, struct bio *bio,
1036                                dm_block_t block,
1037                                struct dm_thin_lookup_result *lookup_result)
1038 {
1039         struct dm_bio_prison_cell *cell;
1040         struct pool *pool = tc->pool;
1041         struct dm_cell_key key;
1042
1043         /*
1044          * If cell is already occupied, then sharing is already in the process
1045          * of being broken so we have nothing further to do here.
1046          */
1047         build_data_key(tc->td, lookup_result->block, &key);
1048         if (dm_bio_detain(pool->prison, &key, bio, &cell))
1049                 return;
1050
1051         if (bio_data_dir(bio) == WRITE && bio->bi_size)
1052                 break_sharing(tc, bio, block, &key, lookup_result, cell);
1053         else {
1054                 struct dm_thin_endio_hook *h = dm_get_mapinfo(bio)->ptr;
1055
1056                 h->shared_read_entry = dm_deferred_entry_inc(pool->shared_read_ds);
1057                 inc_all_io_entry(pool, bio);
1058                 cell_defer_no_holder(tc, cell);
1059
1060                 remap_and_issue(tc, bio, lookup_result->block);
1061         }
1062 }
1063
1064 static void provision_block(struct thin_c *tc, struct bio *bio, dm_block_t block,
1065                             struct dm_bio_prison_cell *cell)
1066 {
1067         int r;
1068         dm_block_t data_block;
1069
1070         /*
1071          * Remap empty bios (flushes) immediately, without provisioning.
1072          */
1073         if (!bio->bi_size) {
1074                 inc_all_io_entry(tc->pool, bio);
1075                 cell_defer_no_holder(tc, cell);
1076
1077                 remap_and_issue(tc, bio, 0);
1078                 return;
1079         }
1080
1081         /*
1082          * Fill read bios with zeroes and complete them immediately.
1083          */
1084         if (bio_data_dir(bio) == READ) {
1085                 zero_fill_bio(bio);
1086                 cell_defer_no_holder(tc, cell);
1087                 bio_endio(bio, 0);
1088                 return;
1089         }
1090
1091         r = alloc_data_block(tc, &data_block);
1092         switch (r) {
1093         case 0:
1094                 if (tc->origin_dev)
1095                         schedule_external_copy(tc, block, data_block, cell, bio);
1096                 else
1097                         schedule_zero(tc, block, data_block, cell, bio);
1098                 break;
1099
1100         case -ENOSPC:
1101                 no_space(cell);
1102                 break;
1103
1104         default:
1105                 DMERR_LIMIT("%s: alloc_data_block() failed: error = %d",
1106                             __func__, r);
1107                 set_pool_mode(tc->pool, PM_READ_ONLY);
1108                 dm_cell_error(cell);
1109                 break;
1110         }
1111 }
1112
1113 static void process_bio(struct thin_c *tc, struct bio *bio)
1114 {
1115         int r;
1116         dm_block_t block = get_bio_block(tc, bio);
1117         struct dm_bio_prison_cell *cell;
1118         struct dm_cell_key key;
1119         struct dm_thin_lookup_result lookup_result;
1120
1121         /*
1122          * If cell is already occupied, then the block is already
1123          * being provisioned so we have nothing further to do here.
1124          */
1125         build_virtual_key(tc->td, block, &key);
1126         if (dm_bio_detain(tc->pool->prison, &key, bio, &cell))
1127                 return;
1128
1129         r = dm_thin_find_block(tc->td, block, 1, &lookup_result);
1130         switch (r) {
1131         case 0:
1132                 if (lookup_result.shared) {
1133                         process_shared_bio(tc, bio, block, &lookup_result);
1134                         cell_defer_no_holder(tc, cell);
1135                 } else {
1136                         inc_all_io_entry(tc->pool, bio);
1137                         cell_defer_no_holder(tc, cell);
1138
1139                         remap_and_issue(tc, bio, lookup_result.block);
1140                 }
1141                 break;
1142
1143         case -ENODATA:
1144                 if (bio_data_dir(bio) == READ && tc->origin_dev) {
1145                         inc_all_io_entry(tc->pool, bio);
1146                         cell_defer_no_holder(tc, cell);
1147
1148                         remap_to_origin_and_issue(tc, bio);
1149                 } else
1150                         provision_block(tc, bio, block, cell);
1151                 break;
1152
1153         default:
1154                 DMERR_LIMIT("%s: dm_thin_find_block() failed: error = %d",
1155                             __func__, r);
1156                 cell_defer_no_holder(tc, cell);
1157                 bio_io_error(bio);
1158                 break;
1159         }
1160 }
1161
1162 static void process_bio_read_only(struct thin_c *tc, struct bio *bio)
1163 {
1164         int r;
1165         int rw = bio_data_dir(bio);
1166         dm_block_t block = get_bio_block(tc, bio);
1167         struct dm_thin_lookup_result lookup_result;
1168
1169         r = dm_thin_find_block(tc->td, block, 1, &lookup_result);
1170         switch (r) {
1171         case 0:
1172                 if (lookup_result.shared && (rw == WRITE) && bio->bi_size)
1173                         bio_io_error(bio);
1174                 else {
1175                         inc_all_io_entry(tc->pool, bio);
1176                         remap_and_issue(tc, bio, lookup_result.block);
1177                 }
1178                 break;
1179
1180         case -ENODATA:
1181                 if (rw != READ) {
1182                         bio_io_error(bio);
1183                         break;
1184                 }
1185
1186                 if (tc->origin_dev) {
1187                         inc_all_io_entry(tc->pool, bio);
1188                         remap_to_origin_and_issue(tc, bio);
1189                         break;
1190                 }
1191
1192                 zero_fill_bio(bio);
1193                 bio_endio(bio, 0);
1194                 break;
1195
1196         default:
1197                 DMERR_LIMIT("%s: dm_thin_find_block() failed: error = %d",
1198                             __func__, r);
1199                 bio_io_error(bio);
1200                 break;
1201         }
1202 }
1203
1204 static void process_bio_fail(struct thin_c *tc, struct bio *bio)
1205 {
1206         bio_io_error(bio);
1207 }
1208
1209 static int need_commit_due_to_time(struct pool *pool)
1210 {
1211         return jiffies < pool->last_commit_jiffies ||
1212                jiffies > pool->last_commit_jiffies + COMMIT_PERIOD;
1213 }
1214
1215 static void process_deferred_bios(struct pool *pool)
1216 {
1217         unsigned long flags;
1218         struct bio *bio;
1219         struct bio_list bios;
1220
1221         bio_list_init(&bios);
1222
1223         spin_lock_irqsave(&pool->lock, flags);
1224         bio_list_merge(&bios, &pool->deferred_bios);
1225         bio_list_init(&pool->deferred_bios);
1226         spin_unlock_irqrestore(&pool->lock, flags);
1227
1228         while ((bio = bio_list_pop(&bios))) {
1229                 struct dm_thin_endio_hook *h = dm_get_mapinfo(bio)->ptr;
1230                 struct thin_c *tc = h->tc;
1231
1232                 /*
1233                  * If we've got no free new_mapping structs, and processing
1234                  * this bio might require one, we pause until there are some
1235                  * prepared mappings to process.
1236                  */
1237                 if (ensure_next_mapping(pool)) {
1238                         spin_lock_irqsave(&pool->lock, flags);
1239                         bio_list_merge(&pool->deferred_bios, &bios);
1240                         spin_unlock_irqrestore(&pool->lock, flags);
1241
1242                         break;
1243                 }
1244
1245                 if (bio->bi_rw & REQ_DISCARD)
1246                         pool->process_discard(tc, bio);
1247                 else
1248                         pool->process_bio(tc, bio);
1249         }
1250
1251         /*
1252          * If there are any deferred flush bios, we must commit
1253          * the metadata before issuing them.
1254          */
1255         bio_list_init(&bios);
1256         spin_lock_irqsave(&pool->lock, flags);
1257         bio_list_merge(&bios, &pool->deferred_flush_bios);
1258         bio_list_init(&pool->deferred_flush_bios);
1259         spin_unlock_irqrestore(&pool->lock, flags);
1260
1261         if (bio_list_empty(&bios) && !need_commit_due_to_time(pool))
1262                 return;
1263
1264         if (commit_or_fallback(pool)) {
1265                 while ((bio = bio_list_pop(&bios)))
1266                         bio_io_error(bio);
1267                 return;
1268         }
1269         pool->last_commit_jiffies = jiffies;
1270
1271         while ((bio = bio_list_pop(&bios)))
1272                 generic_make_request(bio);
1273 }
1274
1275 static void do_worker(struct work_struct *ws)
1276 {
1277         struct pool *pool = container_of(ws, struct pool, worker);
1278
1279         process_prepared(pool, &pool->prepared_mappings, &pool->process_prepared_mapping);
1280         process_prepared(pool, &pool->prepared_discards, &pool->process_prepared_discard);
1281         process_deferred_bios(pool);
1282 }
1283
1284 /*
1285  * We want to commit periodically so that not too much
1286  * unwritten data builds up.
1287  */
1288 static void do_waker(struct work_struct *ws)
1289 {
1290         struct pool *pool = container_of(to_delayed_work(ws), struct pool, waker);
1291         wake_worker(pool);
1292         queue_delayed_work(pool->wq, &pool->waker, COMMIT_PERIOD);
1293 }
1294
1295 /*----------------------------------------------------------------*/
1296
1297 static enum pool_mode get_pool_mode(struct pool *pool)
1298 {
1299         return pool->pf.mode;
1300 }
1301
1302 static void set_pool_mode(struct pool *pool, enum pool_mode mode)
1303 {
1304         int r;
1305
1306         pool->pf.mode = mode;
1307
1308         switch (mode) {
1309         case PM_FAIL:
1310                 DMERR("switching pool to failure mode");
1311                 pool->process_bio = process_bio_fail;
1312                 pool->process_discard = process_bio_fail;
1313                 pool->process_prepared_mapping = process_prepared_mapping_fail;
1314                 pool->process_prepared_discard = process_prepared_discard_fail;
1315                 break;
1316
1317         case PM_READ_ONLY:
1318                 DMERR("switching pool to read-only mode");
1319                 r = dm_pool_abort_metadata(pool->pmd);
1320                 if (r) {
1321                         DMERR("aborting transaction failed");
1322                         set_pool_mode(pool, PM_FAIL);
1323                 } else {
1324                         dm_pool_metadata_read_only(pool->pmd);
1325                         pool->process_bio = process_bio_read_only;
1326                         pool->process_discard = process_discard;
1327                         pool->process_prepared_mapping = process_prepared_mapping_fail;
1328                         pool->process_prepared_discard = process_prepared_discard_passdown;
1329                 }
1330                 break;
1331
1332         case PM_WRITE:
1333                 pool->process_bio = process_bio;
1334                 pool->process_discard = process_discard;
1335                 pool->process_prepared_mapping = process_prepared_mapping;
1336                 pool->process_prepared_discard = process_prepared_discard;
1337                 break;
1338         }
1339 }
1340
1341 /*----------------------------------------------------------------*/
1342
1343 /*
1344  * Mapping functions.
1345  */
1346
1347 /*
1348  * Called only while mapping a thin bio to hand it over to the workqueue.
1349  */
1350 static void thin_defer_bio(struct thin_c *tc, struct bio *bio)
1351 {
1352         unsigned long flags;
1353         struct pool *pool = tc->pool;
1354
1355         spin_lock_irqsave(&pool->lock, flags);
1356         bio_list_add(&pool->deferred_bios, bio);
1357         spin_unlock_irqrestore(&pool->lock, flags);
1358
1359         wake_worker(pool);
1360 }
1361
1362 static struct dm_thin_endio_hook *thin_hook_bio(struct thin_c *tc, struct bio *bio)
1363 {
1364         struct pool *pool = tc->pool;
1365         struct dm_thin_endio_hook *h = mempool_alloc(pool->endio_hook_pool, GFP_NOIO);
1366
1367         h->tc = tc;
1368         h->shared_read_entry = NULL;
1369         h->all_io_entry = NULL;
1370         h->overwrite_mapping = NULL;
1371
1372         return h;
1373 }
1374
1375 /*
1376  * Non-blocking function called from the thin target's map function.
1377  */
1378 static int thin_bio_map(struct dm_target *ti, struct bio *bio,
1379                         union map_info *map_context)
1380 {
1381         int r;
1382         struct thin_c *tc = ti->private;
1383         dm_block_t block = get_bio_block(tc, bio);
1384         struct dm_thin_device *td = tc->td;
1385         struct dm_thin_lookup_result result;
1386         struct dm_bio_prison_cell *cell1, *cell2;
1387         struct dm_cell_key key;
1388
1389         map_context->ptr = thin_hook_bio(tc, bio);
1390
1391         if (get_pool_mode(tc->pool) == PM_FAIL) {
1392                 bio_io_error(bio);
1393                 return DM_MAPIO_SUBMITTED;
1394         }
1395
1396         if (bio->bi_rw & (REQ_DISCARD | REQ_FLUSH | REQ_FUA)) {
1397                 thin_defer_bio(tc, bio);
1398                 return DM_MAPIO_SUBMITTED;
1399         }
1400
1401         r = dm_thin_find_block(td, block, 0, &result);
1402
1403         /*
1404          * Note that we defer readahead too.
1405          */
1406         switch (r) {
1407         case 0:
1408                 if (unlikely(result.shared)) {
1409                         /*
1410                          * We have a race condition here between the
1411                          * result.shared value returned by the lookup and
1412                          * snapshot creation, which may cause new
1413                          * sharing.
1414                          *
1415                          * To avoid this always quiesce the origin before
1416                          * taking the snap.  You want to do this anyway to
1417                          * ensure a consistent application view
1418                          * (i.e. lockfs).
1419                          *
1420                          * More distant ancestors are irrelevant. The
1421                          * shared flag will be set in their case.
1422                          */
1423                         thin_defer_bio(tc, bio);
1424                         return DM_MAPIO_SUBMITTED;
1425                 }
1426
1427                 build_virtual_key(tc->td, block, &key);
1428                 if (dm_bio_detain(tc->pool->prison, &key, bio, &cell1))
1429                         return DM_MAPIO_SUBMITTED;
1430
1431                 build_data_key(tc->td, result.block, &key);
1432                 if (dm_bio_detain(tc->pool->prison, &key, bio, &cell2)) {
1433                         cell_defer_no_holder(tc, cell1);
1434                         return DM_MAPIO_SUBMITTED;
1435                 }
1436
1437                 inc_all_io_entry(tc->pool, bio);
1438                 cell_defer_no_holder(tc, cell2);
1439                 cell_defer_no_holder(tc, cell1);
1440
1441                 remap(tc, bio, result.block);
1442                 return DM_MAPIO_REMAPPED;
1443
1444         case -ENODATA:
1445                 if (get_pool_mode(tc->pool) == PM_READ_ONLY) {
1446                         /*
1447                          * This block isn't provisioned, and we have no way
1448                          * of doing so.  Just error it.
1449                          */
1450                         bio_io_error(bio);
1451                         return DM_MAPIO_SUBMITTED;
1452                 }
1453                 /* fall through */
1454
1455         case -EWOULDBLOCK:
1456                 /*
1457                  * In future, the failed dm_thin_find_block above could
1458                  * provide the hint to load the metadata into cache.
1459                  */
1460                 thin_defer_bio(tc, bio);
1461                 return DM_MAPIO_SUBMITTED;
1462
1463         default:
1464                 /*
1465                  * Must always call bio_io_error on failure.
1466                  * dm_thin_find_block can fail with -EINVAL if the
1467                  * pool is switched to fail-io mode.
1468                  */
1469                 bio_io_error(bio);
1470                 return DM_MAPIO_SUBMITTED;
1471         }
1472 }
1473
1474 static int pool_is_congested(struct dm_target_callbacks *cb, int bdi_bits)
1475 {
1476         int r;
1477         unsigned long flags;
1478         struct pool_c *pt = container_of(cb, struct pool_c, callbacks);
1479
1480         spin_lock_irqsave(&pt->pool->lock, flags);
1481         r = !bio_list_empty(&pt->pool->retry_on_resume_list);
1482         spin_unlock_irqrestore(&pt->pool->lock, flags);
1483
1484         if (!r) {
1485                 struct request_queue *q = bdev_get_queue(pt->data_dev->bdev);
1486                 r = bdi_congested(&q->backing_dev_info, bdi_bits);
1487         }
1488
1489         return r;
1490 }
1491
1492 static void __requeue_bios(struct pool *pool)
1493 {
1494         bio_list_merge(&pool->deferred_bios, &pool->retry_on_resume_list);
1495         bio_list_init(&pool->retry_on_resume_list);
1496 }
1497
1498 /*----------------------------------------------------------------
1499  * Binding of control targets to a pool object
1500  *--------------------------------------------------------------*/
1501 static bool data_dev_supports_discard(struct pool_c *pt)
1502 {
1503         struct request_queue *q = bdev_get_queue(pt->data_dev->bdev);
1504
1505         return q && blk_queue_discard(q);
1506 }
1507
1508 /*
1509  * If discard_passdown was enabled verify that the data device
1510  * supports discards.  Disable discard_passdown if not.
1511  */
1512 static void disable_passdown_if_not_supported(struct pool_c *pt)
1513 {
1514         struct pool *pool = pt->pool;
1515         struct block_device *data_bdev = pt->data_dev->bdev;
1516         struct queue_limits *data_limits = &bdev_get_queue(data_bdev)->limits;
1517         sector_t block_size = pool->sectors_per_block << SECTOR_SHIFT;
1518         const char *reason = NULL;
1519         char buf[BDEVNAME_SIZE];
1520
1521         if (!pt->adjusted_pf.discard_passdown)
1522                 return;
1523
1524         if (!data_dev_supports_discard(pt))
1525                 reason = "discard unsupported";
1526
1527         else if (data_limits->max_discard_sectors < pool->sectors_per_block)
1528                 reason = "max discard sectors smaller than a block";
1529
1530         else if (data_limits->discard_granularity > block_size)
1531                 reason = "discard granularity larger than a block";
1532
1533         else if (block_size & (data_limits->discard_granularity - 1))
1534                 reason = "discard granularity not a factor of block size";
1535
1536         if (reason) {
1537                 DMWARN("Data device (%s) %s: Disabling discard passdown.", bdevname(data_bdev, buf), reason);
1538                 pt->adjusted_pf.discard_passdown = false;
1539         }
1540 }
1541
1542 static int bind_control_target(struct pool *pool, struct dm_target *ti)
1543 {
1544         struct pool_c *pt = ti->private;
1545
1546         /*
1547          * We want to make sure that degraded pools are never upgraded.
1548          */
1549         enum pool_mode old_mode = pool->pf.mode;
1550         enum pool_mode new_mode = pt->adjusted_pf.mode;
1551
1552         if (old_mode > new_mode)
1553                 new_mode = old_mode;
1554
1555         pool->ti = ti;
1556         pool->low_water_blocks = pt->low_water_blocks;
1557         pool->pf = pt->adjusted_pf;
1558
1559         set_pool_mode(pool, new_mode);
1560
1561         return 0;
1562 }
1563
1564 static void unbind_control_target(struct pool *pool, struct dm_target *ti)
1565 {
1566         if (pool->ti == ti)
1567                 pool->ti = NULL;
1568 }
1569
1570 /*----------------------------------------------------------------
1571  * Pool creation
1572  *--------------------------------------------------------------*/
1573 /* Initialize pool features. */
1574 static void pool_features_init(struct pool_features *pf)
1575 {
1576         pf->mode = PM_WRITE;
1577         pf->zero_new_blocks = true;
1578         pf->discard_enabled = true;
1579         pf->discard_passdown = true;
1580 }
1581
1582 static void __pool_destroy(struct pool *pool)
1583 {
1584         __pool_table_remove(pool);
1585
1586         if (dm_pool_metadata_close(pool->pmd) < 0)
1587                 DMWARN("%s: dm_pool_metadata_close() failed.", __func__);
1588
1589         dm_bio_prison_destroy(pool->prison);
1590         dm_kcopyd_client_destroy(pool->copier);
1591
1592         if (pool->wq)
1593                 destroy_workqueue(pool->wq);
1594
1595         if (pool->next_mapping)
1596                 mempool_free(pool->next_mapping, pool->mapping_pool);
1597         mempool_destroy(pool->mapping_pool);
1598         mempool_destroy(pool->endio_hook_pool);
1599         dm_deferred_set_destroy(pool->shared_read_ds);
1600         dm_deferred_set_destroy(pool->all_io_ds);
1601         kfree(pool);
1602 }
1603
1604 static struct kmem_cache *_new_mapping_cache;
1605 static struct kmem_cache *_endio_hook_cache;
1606
1607 static struct pool *pool_create(struct mapped_device *pool_md,
1608                                 struct block_device *metadata_dev,
1609                                 unsigned long block_size,
1610                                 int read_only, char **error)
1611 {
1612         int r;
1613         void *err_p;
1614         struct pool *pool;
1615         struct dm_pool_metadata *pmd;
1616         bool format_device = read_only ? false : true;
1617
1618         pmd = dm_pool_metadata_open(metadata_dev, block_size, format_device);
1619         if (IS_ERR(pmd)) {
1620                 *error = "Error creating metadata object";
1621                 return (struct pool *)pmd;
1622         }
1623
1624         pool = kmalloc(sizeof(*pool), GFP_KERNEL);
1625         if (!pool) {
1626                 *error = "Error allocating memory for pool";
1627                 err_p = ERR_PTR(-ENOMEM);
1628                 goto bad_pool;
1629         }
1630
1631         pool->pmd = pmd;
1632         pool->sectors_per_block = block_size;
1633         if (block_size & (block_size - 1))
1634                 pool->sectors_per_block_shift = -1;
1635         else
1636                 pool->sectors_per_block_shift = __ffs(block_size);
1637         pool->low_water_blocks = 0;
1638         pool_features_init(&pool->pf);
1639         pool->prison = dm_bio_prison_create(PRISON_CELLS);
1640         if (!pool->prison) {
1641                 *error = "Error creating pool's bio prison";
1642                 err_p = ERR_PTR(-ENOMEM);
1643                 goto bad_prison;
1644         }
1645
1646         pool->copier = dm_kcopyd_client_create();
1647         if (IS_ERR(pool->copier)) {
1648                 r = PTR_ERR(pool->copier);
1649                 *error = "Error creating pool's kcopyd client";
1650                 err_p = ERR_PTR(r);
1651                 goto bad_kcopyd_client;
1652         }
1653
1654         /*
1655          * Create singlethreaded workqueue that will service all devices
1656          * that use this metadata.
1657          */
1658         pool->wq = alloc_ordered_workqueue("dm-" DM_MSG_PREFIX, WQ_MEM_RECLAIM);
1659         if (!pool->wq) {
1660                 *error = "Error creating pool's workqueue";
1661                 err_p = ERR_PTR(-ENOMEM);
1662                 goto bad_wq;
1663         }
1664
1665         INIT_WORK(&pool->worker, do_worker);
1666         INIT_DELAYED_WORK(&pool->waker, do_waker);
1667         spin_lock_init(&pool->lock);
1668         bio_list_init(&pool->deferred_bios);
1669         bio_list_init(&pool->deferred_flush_bios);
1670         INIT_LIST_HEAD(&pool->prepared_mappings);
1671         INIT_LIST_HEAD(&pool->prepared_discards);
1672         pool->low_water_triggered = 0;
1673         pool->no_free_space = 0;
1674         bio_list_init(&pool->retry_on_resume_list);
1675
1676         pool->shared_read_ds = dm_deferred_set_create();
1677         if (!pool->shared_read_ds) {
1678                 *error = "Error creating pool's shared read deferred set";
1679                 err_p = ERR_PTR(-ENOMEM);
1680                 goto bad_shared_read_ds;
1681         }
1682
1683         pool->all_io_ds = dm_deferred_set_create();
1684         if (!pool->all_io_ds) {
1685                 *error = "Error creating pool's all io deferred set";
1686                 err_p = ERR_PTR(-ENOMEM);
1687                 goto bad_all_io_ds;
1688         }
1689
1690         pool->next_mapping = NULL;
1691         pool->mapping_pool = mempool_create_slab_pool(MAPPING_POOL_SIZE,
1692                                                       _new_mapping_cache);
1693         if (!pool->mapping_pool) {
1694                 *error = "Error creating pool's mapping mempool";
1695                 err_p = ERR_PTR(-ENOMEM);
1696                 goto bad_mapping_pool;
1697         }
1698
1699         pool->endio_hook_pool = mempool_create_slab_pool(ENDIO_HOOK_POOL_SIZE,
1700                                                          _endio_hook_cache);
1701         if (!pool->endio_hook_pool) {
1702                 *error = "Error creating pool's endio_hook mempool";
1703                 err_p = ERR_PTR(-ENOMEM);
1704                 goto bad_endio_hook_pool;
1705         }
1706         pool->ref_count = 1;
1707         pool->last_commit_jiffies = jiffies;
1708         pool->pool_md = pool_md;
1709         pool->md_dev = metadata_dev;
1710         __pool_table_insert(pool);
1711
1712         return pool;
1713
1714 bad_endio_hook_pool:
1715         mempool_destroy(pool->mapping_pool);
1716 bad_mapping_pool:
1717         dm_deferred_set_destroy(pool->all_io_ds);
1718 bad_all_io_ds:
1719         dm_deferred_set_destroy(pool->shared_read_ds);
1720 bad_shared_read_ds:
1721         destroy_workqueue(pool->wq);
1722 bad_wq:
1723         dm_kcopyd_client_destroy(pool->copier);
1724 bad_kcopyd_client:
1725         dm_bio_prison_destroy(pool->prison);
1726 bad_prison:
1727         kfree(pool);
1728 bad_pool:
1729         if (dm_pool_metadata_close(pmd))
1730                 DMWARN("%s: dm_pool_metadata_close() failed.", __func__);
1731
1732         return err_p;
1733 }
1734
1735 static void __pool_inc(struct pool *pool)
1736 {
1737         BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
1738         pool->ref_count++;
1739 }
1740
1741 static void __pool_dec(struct pool *pool)
1742 {
1743         BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
1744         BUG_ON(!pool->ref_count);
1745         if (!--pool->ref_count)
1746                 __pool_destroy(pool);
1747 }
1748
1749 static struct pool *__pool_find(struct mapped_device *pool_md,
1750                                 struct block_device *metadata_dev,
1751                                 unsigned long block_size, int read_only,
1752                                 char **error, int *created)
1753 {
1754         struct pool *pool = __pool_table_lookup_metadata_dev(metadata_dev);
1755
1756         if (pool) {
1757                 if (pool->pool_md != pool_md) {
1758                         *error = "metadata device already in use by a pool";
1759                         return ERR_PTR(-EBUSY);
1760                 }
1761                 __pool_inc(pool);
1762
1763         } else {
1764                 pool = __pool_table_lookup(pool_md);
1765                 if (pool) {
1766                         if (pool->md_dev != metadata_dev) {
1767                                 *error = "different pool cannot replace a pool";
1768                                 return ERR_PTR(-EINVAL);
1769                         }
1770                         __pool_inc(pool);
1771
1772                 } else {
1773                         pool = pool_create(pool_md, metadata_dev, block_size, read_only, error);
1774                         *created = 1;
1775                 }
1776         }
1777
1778         return pool;
1779 }
1780
1781 /*----------------------------------------------------------------
1782  * Pool target methods
1783  *--------------------------------------------------------------*/
1784 static void pool_dtr(struct dm_target *ti)
1785 {
1786         struct pool_c *pt = ti->private;
1787
1788         mutex_lock(&dm_thin_pool_table.mutex);
1789
1790         unbind_control_target(pt->pool, ti);
1791         __pool_dec(pt->pool);
1792         dm_put_device(ti, pt->metadata_dev);
1793         dm_put_device(ti, pt->data_dev);
1794         kfree(pt);
1795
1796         mutex_unlock(&dm_thin_pool_table.mutex);
1797 }
1798
1799 static int parse_pool_features(struct dm_arg_set *as, struct pool_features *pf,
1800                                struct dm_target *ti)
1801 {
1802         int r;
1803         unsigned argc;
1804         const char *arg_name;
1805
1806         static struct dm_arg _args[] = {
1807                 {0, 3, "Invalid number of pool feature arguments"},
1808         };
1809
1810         /*
1811          * No feature arguments supplied.
1812          */
1813         if (!as->argc)
1814                 return 0;
1815
1816         r = dm_read_arg_group(_args, as, &argc, &ti->error);
1817         if (r)
1818                 return -EINVAL;
1819
1820         while (argc && !r) {
1821                 arg_name = dm_shift_arg(as);
1822                 argc--;
1823
1824                 if (!strcasecmp(arg_name, "skip_block_zeroing"))
1825                         pf->zero_new_blocks = false;
1826
1827                 else if (!strcasecmp(arg_name, "ignore_discard"))
1828                         pf->discard_enabled = false;
1829
1830                 else if (!strcasecmp(arg_name, "no_discard_passdown"))
1831                         pf->discard_passdown = false;
1832
1833                 else if (!strcasecmp(arg_name, "read_only"))
1834                         pf->mode = PM_READ_ONLY;
1835
1836                 else {
1837                         ti->error = "Unrecognised pool feature requested";
1838                         r = -EINVAL;
1839                         break;
1840                 }
1841         }
1842
1843         return r;
1844 }
1845
1846 /*
1847  * thin-pool <metadata dev> <data dev>
1848  *           <data block size (sectors)>
1849  *           <low water mark (blocks)>
1850  *           [<#feature args> [<arg>]*]
1851  *
1852  * Optional feature arguments are:
1853  *           skip_block_zeroing: skips the zeroing of newly-provisioned blocks.
1854  *           ignore_discard: disable discard
1855  *           no_discard_passdown: don't pass discards down to the data device
1856  */
1857 static int pool_ctr(struct dm_target *ti, unsigned argc, char **argv)
1858 {
1859         int r, pool_created = 0;
1860         struct pool_c *pt;
1861         struct pool *pool;
1862         struct pool_features pf;
1863         struct dm_arg_set as;
1864         struct dm_dev *data_dev;
1865         unsigned long block_size;
1866         dm_block_t low_water_blocks;
1867         struct dm_dev *metadata_dev;
1868         sector_t metadata_dev_size;
1869         char b[BDEVNAME_SIZE];
1870
1871         /*
1872          * FIXME Remove validation from scope of lock.
1873          */
1874         mutex_lock(&dm_thin_pool_table.mutex);
1875
1876         if (argc < 4) {
1877                 ti->error = "Invalid argument count";
1878                 r = -EINVAL;
1879                 goto out_unlock;
1880         }
1881         as.argc = argc;
1882         as.argv = argv;
1883
1884         r = dm_get_device(ti, argv[0], FMODE_READ | FMODE_WRITE, &metadata_dev);
1885         if (r) {
1886                 ti->error = "Error opening metadata block device";
1887                 goto out_unlock;
1888         }
1889
1890         metadata_dev_size = i_size_read(metadata_dev->bdev->bd_inode) >> SECTOR_SHIFT;
1891         if (metadata_dev_size > THIN_METADATA_MAX_SECTORS_WARNING)
1892                 DMWARN("Metadata device %s is larger than %u sectors: excess space will not be used.",
1893                        bdevname(metadata_dev->bdev, b), THIN_METADATA_MAX_SECTORS);
1894
1895         r = dm_get_device(ti, argv[1], FMODE_READ | FMODE_WRITE, &data_dev);
1896         if (r) {
1897                 ti->error = "Error getting data device";
1898                 goto out_metadata;
1899         }
1900
1901         if (kstrtoul(argv[2], 10, &block_size) || !block_size ||
1902             block_size < DATA_DEV_BLOCK_SIZE_MIN_SECTORS ||
1903             block_size > DATA_DEV_BLOCK_SIZE_MAX_SECTORS ||
1904             block_size & (DATA_DEV_BLOCK_SIZE_MIN_SECTORS - 1)) {
1905                 ti->error = "Invalid block size";
1906                 r = -EINVAL;
1907                 goto out;
1908         }
1909
1910         if (kstrtoull(argv[3], 10, (unsigned long long *)&low_water_blocks)) {
1911                 ti->error = "Invalid low water mark";
1912                 r = -EINVAL;
1913                 goto out;
1914         }
1915
1916         /*
1917          * Set default pool features.
1918          */
1919         pool_features_init(&pf);
1920
1921         dm_consume_args(&as, 4);
1922         r = parse_pool_features(&as, &pf, ti);
1923         if (r)
1924                 goto out;
1925
1926         pt = kzalloc(sizeof(*pt), GFP_KERNEL);
1927         if (!pt) {
1928                 r = -ENOMEM;
1929                 goto out;
1930         }
1931
1932         pool = __pool_find(dm_table_get_md(ti->table), metadata_dev->bdev,
1933                            block_size, pf.mode == PM_READ_ONLY, &ti->error, &pool_created);
1934         if (IS_ERR(pool)) {
1935                 r = PTR_ERR(pool);
1936                 goto out_free_pt;
1937         }
1938
1939         /*
1940          * 'pool_created' reflects whether this is the first table load.
1941          * Top level discard support is not allowed to be changed after
1942          * initial load.  This would require a pool reload to trigger thin
1943          * device changes.
1944          */
1945         if (!pool_created && pf.discard_enabled != pool->pf.discard_enabled) {
1946                 ti->error = "Discard support cannot be disabled once enabled";
1947                 r = -EINVAL;
1948                 goto out_flags_changed;
1949         }
1950
1951         pt->pool = pool;
1952         pt->ti = ti;
1953         pt->metadata_dev = metadata_dev;
1954         pt->data_dev = data_dev;
1955         pt->low_water_blocks = low_water_blocks;
1956         pt->adjusted_pf = pt->requested_pf = pf;
1957         ti->num_flush_requests = 1;
1958
1959         /*
1960          * Only need to enable discards if the pool should pass
1961          * them down to the data device.  The thin device's discard
1962          * processing will cause mappings to be removed from the btree.
1963          */
1964         if (pf.discard_enabled && pf.discard_passdown) {
1965                 ti->num_discard_requests = 1;
1966
1967                 /*
1968                  * Setting 'discards_supported' circumvents the normal
1969                  * stacking of discard limits (this keeps the pool and
1970                  * thin devices' discard limits consistent).
1971                  */
1972                 ti->discards_supported = true;
1973                 ti->discard_zeroes_data_unsupported = true;
1974         }
1975         ti->private = pt;
1976
1977         pt->callbacks.congested_fn = pool_is_congested;
1978         dm_table_add_target_callbacks(ti->table, &pt->callbacks);
1979
1980         mutex_unlock(&dm_thin_pool_table.mutex);
1981
1982         return 0;
1983
1984 out_flags_changed:
1985         __pool_dec(pool);
1986 out_free_pt:
1987         kfree(pt);
1988 out:
1989         dm_put_device(ti, data_dev);
1990 out_metadata:
1991         dm_put_device(ti, metadata_dev);
1992 out_unlock:
1993         mutex_unlock(&dm_thin_pool_table.mutex);
1994
1995         return r;
1996 }
1997
1998 static int pool_map(struct dm_target *ti, struct bio *bio,
1999                     union map_info *map_context)
2000 {
2001         int r;
2002         struct pool_c *pt = ti->private;
2003         struct pool *pool = pt->pool;
2004         unsigned long flags;
2005
2006         /*
2007          * As this is a singleton target, ti->begin is always zero.
2008          */
2009         spin_lock_irqsave(&pool->lock, flags);
2010         bio->bi_bdev = pt->data_dev->bdev;
2011         r = DM_MAPIO_REMAPPED;
2012         spin_unlock_irqrestore(&pool->lock, flags);
2013
2014         return r;
2015 }
2016
2017 /*
2018  * Retrieves the number of blocks of the data device from
2019  * the superblock and compares it to the actual device size,
2020  * thus resizing the data device in case it has grown.
2021  *
2022  * This both copes with opening preallocated data devices in the ctr
2023  * being followed by a resume
2024  * -and-
2025  * calling the resume method individually after userspace has
2026  * grown the data device in reaction to a table event.
2027  */
2028 static int pool_preresume(struct dm_target *ti)
2029 {
2030         int r;
2031         struct pool_c *pt = ti->private;
2032         struct pool *pool = pt->pool;
2033         sector_t data_size = ti->len;
2034         dm_block_t sb_data_size;
2035
2036         /*
2037          * Take control of the pool object.
2038          */
2039         r = bind_control_target(pool, ti);
2040         if (r)
2041                 return r;
2042
2043         (void) sector_div(data_size, pool->sectors_per_block);
2044
2045         r = dm_pool_get_data_dev_size(pool->pmd, &sb_data_size);
2046         if (r) {
2047                 DMERR("failed to retrieve data device size");
2048                 return r;
2049         }
2050
2051         if (data_size < sb_data_size) {
2052                 DMERR("pool target too small, is %llu blocks (expected %llu)",
2053                       (unsigned long long)data_size, sb_data_size);
2054                 return -EINVAL;
2055
2056         } else if (data_size > sb_data_size) {
2057                 r = dm_pool_resize_data_dev(pool->pmd, data_size);
2058                 if (r) {
2059                         DMERR("failed to resize data device");
2060                         /* FIXME Stricter than necessary: Rollback transaction instead here */
2061                         set_pool_mode(pool, PM_READ_ONLY);
2062                         return r;
2063                 }
2064
2065                 (void) commit_or_fallback(pool);
2066         }
2067
2068         return 0;
2069 }
2070
2071 static void pool_resume(struct dm_target *ti)
2072 {
2073         struct pool_c *pt = ti->private;
2074         struct pool *pool = pt->pool;
2075         unsigned long flags;
2076
2077         spin_lock_irqsave(&pool->lock, flags);
2078         pool->low_water_triggered = 0;
2079         pool->no_free_space = 0;
2080         __requeue_bios(pool);
2081         spin_unlock_irqrestore(&pool->lock, flags);
2082
2083         do_waker(&pool->waker.work);
2084 }
2085
2086 static void pool_postsuspend(struct dm_target *ti)
2087 {
2088         struct pool_c *pt = ti->private;
2089         struct pool *pool = pt->pool;
2090
2091         cancel_delayed_work(&pool->waker);
2092         flush_workqueue(pool->wq);
2093         (void) commit_or_fallback(pool);
2094 }
2095
2096 static int check_arg_count(unsigned argc, unsigned args_required)
2097 {
2098         if (argc != args_required) {
2099                 DMWARN("Message received with %u arguments instead of %u.",
2100                        argc, args_required);
2101                 return -EINVAL;
2102         }
2103
2104         return 0;
2105 }
2106
2107 static int read_dev_id(char *arg, dm_thin_id *dev_id, int warning)
2108 {
2109         if (!kstrtoull(arg, 10, (unsigned long long *)dev_id) &&
2110             *dev_id <= MAX_DEV_ID)
2111                 return 0;
2112
2113         if (warning)
2114                 DMWARN("Message received with invalid device id: %s", arg);
2115
2116         return -EINVAL;
2117 }
2118
2119 static int process_create_thin_mesg(unsigned argc, char **argv, struct pool *pool)
2120 {
2121         dm_thin_id dev_id;
2122         int r;
2123
2124         r = check_arg_count(argc, 2);
2125         if (r)
2126                 return r;
2127
2128         r = read_dev_id(argv[1], &dev_id, 1);
2129         if (r)
2130                 return r;
2131
2132         r = dm_pool_create_thin(pool->pmd, dev_id);
2133         if (r) {
2134                 DMWARN("Creation of new thinly-provisioned device with id %s failed.",
2135                        argv[1]);
2136                 return r;
2137         }
2138
2139         return 0;
2140 }
2141
2142 static int process_create_snap_mesg(unsigned argc, char **argv, struct pool *pool)
2143 {
2144         dm_thin_id dev_id;
2145         dm_thin_id origin_dev_id;
2146         int r;
2147
2148         r = check_arg_count(argc, 3);
2149         if (r)
2150                 return r;
2151
2152         r = read_dev_id(argv[1], &dev_id, 1);
2153         if (r)
2154                 return r;
2155
2156         r = read_dev_id(argv[2], &origin_dev_id, 1);
2157         if (r)
2158                 return r;
2159
2160         r = dm_pool_create_snap(pool->pmd, dev_id, origin_dev_id);
2161         if (r) {
2162                 DMWARN("Creation of new snapshot %s of device %s failed.",
2163                        argv[1], argv[2]);
2164                 return r;
2165         }
2166
2167         return 0;
2168 }
2169
2170 static int process_delete_mesg(unsigned argc, char **argv, struct pool *pool)
2171 {
2172         dm_thin_id dev_id;
2173         int r;
2174
2175         r = check_arg_count(argc, 2);
2176         if (r)
2177                 return r;
2178
2179         r = read_dev_id(argv[1], &dev_id, 1);
2180         if (r)
2181                 return r;
2182
2183         r = dm_pool_delete_thin_device(pool->pmd, dev_id);
2184         if (r)
2185                 DMWARN("Deletion of thin device %s failed.", argv[1]);
2186
2187         return r;
2188 }
2189
2190 static int process_set_transaction_id_mesg(unsigned argc, char **argv, struct pool *pool)
2191 {
2192         dm_thin_id old_id, new_id;
2193         int r;
2194
2195         r = check_arg_count(argc, 3);
2196         if (r)
2197                 return r;
2198
2199         if (kstrtoull(argv[1], 10, (unsigned long long *)&old_id)) {
2200                 DMWARN("set_transaction_id message: Unrecognised id %s.", argv[1]);
2201                 return -EINVAL;
2202         }
2203
2204         if (kstrtoull(argv[2], 10, (unsigned long long *)&new_id)) {
2205                 DMWARN("set_transaction_id message: Unrecognised new id %s.", argv[2]);
2206                 return -EINVAL;
2207         }
2208
2209         r = dm_pool_set_metadata_transaction_id(pool->pmd, old_id, new_id);
2210         if (r) {
2211                 DMWARN("Failed to change transaction id from %s to %s.",
2212                        argv[1], argv[2]);
2213                 return r;
2214         }
2215
2216         return 0;
2217 }
2218
2219 static int process_reserve_metadata_snap_mesg(unsigned argc, char **argv, struct pool *pool)
2220 {
2221         int r;
2222
2223         r = check_arg_count(argc, 1);
2224         if (r)
2225                 return r;
2226
2227         (void) commit_or_fallback(pool);
2228
2229         r = dm_pool_reserve_metadata_snap(pool->pmd);
2230         if (r)
2231                 DMWARN("reserve_metadata_snap message failed.");
2232
2233         return r;
2234 }
2235
2236 static int process_release_metadata_snap_mesg(unsigned argc, char **argv, struct pool *pool)
2237 {
2238         int r;
2239
2240         r = check_arg_count(argc, 1);
2241         if (r)
2242                 return r;
2243
2244         r = dm_pool_release_metadata_snap(pool->pmd);
2245         if (r)
2246                 DMWARN("release_metadata_snap message failed.");
2247
2248         return r;
2249 }
2250
2251 /*
2252  * Messages supported:
2253  *   create_thin        <dev_id>
2254  *   create_snap        <dev_id> <origin_id>
2255  *   delete             <dev_id>
2256  *   trim               <dev_id> <new_size_in_sectors>
2257  *   set_transaction_id <current_trans_id> <new_trans_id>
2258  *   reserve_metadata_snap
2259  *   release_metadata_snap
2260  */
2261 static int pool_message(struct dm_target *ti, unsigned argc, char **argv)
2262 {
2263         int r = -EINVAL;
2264         struct pool_c *pt = ti->private;
2265         struct pool *pool = pt->pool;
2266
2267         if (!strcasecmp(argv[0], "create_thin"))
2268                 r = process_create_thin_mesg(argc, argv, pool);
2269
2270         else if (!strcasecmp(argv[0], "create_snap"))
2271                 r = process_create_snap_mesg(argc, argv, pool);
2272
2273         else if (!strcasecmp(argv[0], "delete"))
2274                 r = process_delete_mesg(argc, argv, pool);
2275
2276         else if (!strcasecmp(argv[0], "set_transaction_id"))
2277                 r = process_set_transaction_id_mesg(argc, argv, pool);
2278
2279         else if (!strcasecmp(argv[0], "reserve_metadata_snap"))
2280                 r = process_reserve_metadata_snap_mesg(argc, argv, pool);
2281
2282         else if (!strcasecmp(argv[0], "release_metadata_snap"))
2283                 r = process_release_metadata_snap_mesg(argc, argv, pool);
2284
2285         else
2286                 DMWARN("Unrecognised thin pool target message received: %s", argv[0]);
2287
2288         if (!r)
2289                 (void) commit_or_fallback(pool);
2290
2291         return r;
2292 }
2293
2294 static void emit_flags(struct pool_features *pf, char *result,
2295                        unsigned sz, unsigned maxlen)
2296 {
2297         unsigned count = !pf->zero_new_blocks + !pf->discard_enabled +
2298                 !pf->discard_passdown + (pf->mode == PM_READ_ONLY);
2299         DMEMIT("%u ", count);
2300
2301         if (!pf->zero_new_blocks)
2302                 DMEMIT("skip_block_zeroing ");
2303
2304         if (!pf->discard_enabled)
2305                 DMEMIT("ignore_discard ");
2306
2307         if (!pf->discard_passdown)
2308                 DMEMIT("no_discard_passdown ");
2309
2310         if (pf->mode == PM_READ_ONLY)
2311                 DMEMIT("read_only ");
2312 }
2313
2314 /*
2315  * Status line is:
2316  *    <transaction id> <used metadata sectors>/<total metadata sectors>
2317  *    <used data sectors>/<total data sectors> <held metadata root>
2318  */
2319 static int pool_status(struct dm_target *ti, status_type_t type,
2320                        unsigned status_flags, char *result, unsigned maxlen)
2321 {
2322         int r;
2323         unsigned sz = 0;
2324         uint64_t transaction_id;
2325         dm_block_t nr_free_blocks_data;
2326         dm_block_t nr_free_blocks_metadata;
2327         dm_block_t nr_blocks_data;
2328         dm_block_t nr_blocks_metadata;
2329         dm_block_t held_root;
2330         char buf[BDEVNAME_SIZE];
2331         char buf2[BDEVNAME_SIZE];
2332         struct pool_c *pt = ti->private;
2333         struct pool *pool = pt->pool;
2334
2335         switch (type) {
2336         case STATUSTYPE_INFO:
2337                 if (get_pool_mode(pool) == PM_FAIL) {
2338                         DMEMIT("Fail");
2339                         break;
2340                 }
2341
2342                 /* Commit to ensure statistics aren't out-of-date */
2343                 if (!(status_flags & DM_STATUS_NOFLUSH_FLAG) && !dm_suspended(ti))
2344                         (void) commit_or_fallback(pool);
2345
2346                 r = dm_pool_get_metadata_transaction_id(pool->pmd,
2347                                                         &transaction_id);
2348                 if (r)
2349                         return r;
2350
2351                 r = dm_pool_get_free_metadata_block_count(pool->pmd,
2352                                                           &nr_free_blocks_metadata);
2353                 if (r)
2354                         return r;
2355
2356                 r = dm_pool_get_metadata_dev_size(pool->pmd, &nr_blocks_metadata);
2357                 if (r)
2358                         return r;
2359
2360                 r = dm_pool_get_free_block_count(pool->pmd,
2361                                                  &nr_free_blocks_data);
2362                 if (r)
2363                         return r;
2364
2365                 r = dm_pool_get_data_dev_size(pool->pmd, &nr_blocks_data);
2366                 if (r)
2367                         return r;
2368
2369                 r = dm_pool_get_metadata_snap(pool->pmd, &held_root);
2370                 if (r)
2371                         return r;
2372
2373                 DMEMIT("%llu %llu/%llu %llu/%llu ",
2374                        (unsigned long long)transaction_id,
2375                        (unsigned long long)(nr_blocks_metadata - nr_free_blocks_metadata),
2376                        (unsigned long long)nr_blocks_metadata,
2377                        (unsigned long long)(nr_blocks_data - nr_free_blocks_data),
2378                        (unsigned long long)nr_blocks_data);
2379
2380                 if (held_root)
2381                         DMEMIT("%llu ", held_root);
2382                 else
2383                         DMEMIT("- ");
2384
2385                 if (pool->pf.mode == PM_READ_ONLY)
2386                         DMEMIT("ro ");
2387                 else
2388                         DMEMIT("rw ");
2389
2390                 if (!pool->pf.discard_enabled)
2391                         DMEMIT("ignore_discard");
2392                 else if (pool->pf.discard_passdown)
2393                         DMEMIT("discard_passdown");
2394                 else
2395                         DMEMIT("no_discard_passdown");
2396
2397                 break;
2398
2399         case STATUSTYPE_TABLE:
2400                 DMEMIT("%s %s %lu %llu ",
2401                        format_dev_t(buf, pt->metadata_dev->bdev->bd_dev),
2402                        format_dev_t(buf2, pt->data_dev->bdev->bd_dev),
2403                        (unsigned long)pool->sectors_per_block,
2404                        (unsigned long long)pt->low_water_blocks);
2405                 emit_flags(&pt->requested_pf, result, sz, maxlen);
2406                 break;
2407         }
2408
2409         return 0;
2410 }
2411
2412 static int pool_iterate_devices(struct dm_target *ti,
2413                                 iterate_devices_callout_fn fn, void *data)
2414 {
2415         struct pool_c *pt = ti->private;
2416
2417         return fn(ti, pt->data_dev, 0, ti->len, data);
2418 }
2419
2420 static int pool_merge(struct dm_target *ti, struct bvec_merge_data *bvm,
2421                       struct bio_vec *biovec, int max_size)
2422 {
2423         struct pool_c *pt = ti->private;
2424         struct request_queue *q = bdev_get_queue(pt->data_dev->bdev);
2425
2426         if (!q->merge_bvec_fn)
2427                 return max_size;
2428
2429         bvm->bi_bdev = pt->data_dev->bdev;
2430
2431         return min(max_size, q->merge_bvec_fn(q, bvm, biovec));
2432 }
2433
2434 static bool block_size_is_power_of_two(struct pool *pool)
2435 {
2436         return pool->sectors_per_block_shift >= 0;
2437 }
2438
2439 static void set_discard_limits(struct pool_c *pt, struct queue_limits *limits)
2440 {
2441         struct pool *pool = pt->pool;
2442         struct queue_limits *data_limits;
2443
2444         limits->max_discard_sectors = pool->sectors_per_block;
2445
2446         /*
2447          * discard_granularity is just a hint, and not enforced.
2448          */
2449         if (pt->adjusted_pf.discard_passdown) {
2450                 data_limits = &bdev_get_queue(pt->data_dev->bdev)->limits;
2451                 limits->discard_granularity = data_limits->discard_granularity;
2452         } else if (block_size_is_power_of_two(pool))
2453                 limits->discard_granularity = pool->sectors_per_block << SECTOR_SHIFT;
2454         else
2455                 /*
2456                  * Use largest power of 2 that is a factor of sectors_per_block
2457                  * but at least DATA_DEV_BLOCK_SIZE_MIN_SECTORS.
2458                  */
2459                 limits->discard_granularity = max(1 << (ffs(pool->sectors_per_block) - 1),
2460                                                   DATA_DEV_BLOCK_SIZE_MIN_SECTORS) << SECTOR_SHIFT;
2461 }
2462
2463 static void pool_io_hints(struct dm_target *ti, struct queue_limits *limits)
2464 {
2465         struct pool_c *pt = ti->private;
2466         struct pool *pool = pt->pool;
2467
2468         blk_limits_io_min(limits, 0);
2469         blk_limits_io_opt(limits, pool->sectors_per_block << SECTOR_SHIFT);
2470
2471         /*
2472          * pt->adjusted_pf is a staging area for the actual features to use.
2473          * They get transferred to the live pool in bind_control_target()
2474          * called from pool_preresume().
2475          */
2476         if (!pt->adjusted_pf.discard_enabled)
2477                 return;
2478
2479         disable_passdown_if_not_supported(pt);
2480
2481         set_discard_limits(pt, limits);
2482 }
2483
2484 static struct target_type pool_target = {
2485         .name = "thin-pool",
2486         .features = DM_TARGET_SINGLETON | DM_TARGET_ALWAYS_WRITEABLE |
2487                     DM_TARGET_IMMUTABLE,
2488         .version = {1, 6, 0},
2489         .module = THIS_MODULE,
2490         .ctr = pool_ctr,
2491         .dtr = pool_dtr,
2492         .map = pool_map,
2493         .postsuspend = pool_postsuspend,
2494         .preresume = pool_preresume,
2495         .resume = pool_resume,
2496         .message = pool_message,
2497         .status = pool_status,
2498         .merge = pool_merge,
2499         .iterate_devices = pool_iterate_devices,
2500         .io_hints = pool_io_hints,
2501 };
2502
2503 /*----------------------------------------------------------------
2504  * Thin target methods
2505  *--------------------------------------------------------------*/
2506 static void thin_dtr(struct dm_target *ti)
2507 {
2508         struct thin_c *tc = ti->private;
2509
2510         mutex_lock(&dm_thin_pool_table.mutex);
2511
2512         __pool_dec(tc->pool);
2513         dm_pool_close_thin_device(tc->td);
2514         dm_put_device(ti, tc->pool_dev);
2515         if (tc->origin_dev)
2516                 dm_put_device(ti, tc->origin_dev);
2517         kfree(tc);
2518
2519         mutex_unlock(&dm_thin_pool_table.mutex);
2520 }
2521
2522 /*
2523  * Thin target parameters:
2524  *
2525  * <pool_dev> <dev_id> [origin_dev]
2526  *
2527  * pool_dev: the path to the pool (eg, /dev/mapper/my_pool)
2528  * dev_id: the internal device identifier
2529  * origin_dev: a device external to the pool that should act as the origin
2530  *
2531  * If the pool device has discards disabled, they get disabled for the thin
2532  * device as well.
2533  */
2534 static int thin_ctr(struct dm_target *ti, unsigned argc, char **argv)
2535 {
2536         int r;
2537         struct thin_c *tc;
2538         struct dm_dev *pool_dev, *origin_dev;
2539         struct mapped_device *pool_md;
2540
2541         mutex_lock(&dm_thin_pool_table.mutex);
2542
2543         if (argc != 2 && argc != 3) {
2544                 ti->error = "Invalid argument count";
2545                 r = -EINVAL;
2546                 goto out_unlock;
2547         }
2548
2549         tc = ti->private = kzalloc(sizeof(*tc), GFP_KERNEL);
2550         if (!tc) {
2551                 ti->error = "Out of memory";
2552                 r = -ENOMEM;
2553                 goto out_unlock;
2554         }
2555
2556         if (argc == 3) {
2557                 r = dm_get_device(ti, argv[2], FMODE_READ, &origin_dev);
2558                 if (r) {
2559                         ti->error = "Error opening origin device";
2560                         goto bad_origin_dev;
2561                 }
2562                 tc->origin_dev = origin_dev;
2563         }
2564
2565         r = dm_get_device(ti, argv[0], dm_table_get_mode(ti->table), &pool_dev);
2566         if (r) {
2567                 ti->error = "Error opening pool device";
2568                 goto bad_pool_dev;
2569         }
2570         tc->pool_dev = pool_dev;
2571
2572         if (read_dev_id(argv[1], (unsigned long long *)&tc->dev_id, 0)) {
2573                 ti->error = "Invalid device id";
2574                 r = -EINVAL;
2575                 goto bad_common;
2576         }
2577
2578         pool_md = dm_get_md(tc->pool_dev->bdev->bd_dev);
2579         if (!pool_md) {
2580                 ti->error = "Couldn't get pool mapped device";
2581                 r = -EINVAL;
2582                 goto bad_common;
2583         }
2584
2585         tc->pool = __pool_table_lookup(pool_md);
2586         if (!tc->pool) {
2587                 ti->error = "Couldn't find pool object";
2588                 r = -EINVAL;
2589                 goto bad_pool_lookup;
2590         }
2591         __pool_inc(tc->pool);
2592
2593         if (get_pool_mode(tc->pool) == PM_FAIL) {
2594                 ti->error = "Couldn't open thin device, Pool is in fail mode";
2595                 goto bad_thin_open;
2596         }
2597
2598         r = dm_pool_open_thin_device(tc->pool->pmd, tc->dev_id, &tc->td);
2599         if (r) {
2600                 ti->error = "Couldn't open thin internal device";
2601                 goto bad_thin_open;
2602         }
2603
2604         r = dm_set_target_max_io_len(ti, tc->pool->sectors_per_block);
2605         if (r)
2606                 goto bad_thin_open;
2607
2608         ti->num_flush_requests = 1;
2609         ti->flush_supported = true;
2610
2611         /* In case the pool supports discards, pass them on. */
2612         if (tc->pool->pf.discard_enabled) {
2613                 ti->discards_supported = true;
2614                 ti->num_discard_requests = 1;
2615                 ti->discard_zeroes_data_unsupported = true;
2616                 /* Discard requests must be split on a block boundary */
2617                 ti->split_discard_requests = true;
2618         }
2619
2620         dm_put(pool_md);
2621
2622         mutex_unlock(&dm_thin_pool_table.mutex);
2623
2624         return 0;
2625
2626 bad_thin_open:
2627         __pool_dec(tc->pool);
2628 bad_pool_lookup:
2629         dm_put(pool_md);
2630 bad_common:
2631         dm_put_device(ti, tc->pool_dev);
2632 bad_pool_dev:
2633         if (tc->origin_dev)
2634                 dm_put_device(ti, tc->origin_dev);
2635 bad_origin_dev:
2636         kfree(tc);
2637 out_unlock:
2638         mutex_unlock(&dm_thin_pool_table.mutex);
2639
2640         return r;
2641 }
2642
2643 static int thin_map(struct dm_target *ti, struct bio *bio,
2644                     union map_info *map_context)
2645 {
2646         bio->bi_sector = dm_target_offset(ti, bio->bi_sector);
2647
2648         return thin_bio_map(ti, bio, map_context);
2649 }
2650
2651 static int thin_endio(struct dm_target *ti,
2652                       struct bio *bio, int err,
2653                       union map_info *map_context)
2654 {
2655         unsigned long flags;
2656         struct dm_thin_endio_hook *h = map_context->ptr;
2657         struct list_head work;
2658         struct dm_thin_new_mapping *m, *tmp;
2659         struct pool *pool = h->tc->pool;
2660
2661         if (h->shared_read_entry) {
2662                 INIT_LIST_HEAD(&work);
2663                 dm_deferred_entry_dec(h->shared_read_entry, &work);
2664
2665                 spin_lock_irqsave(&pool->lock, flags);
2666                 list_for_each_entry_safe(m, tmp, &work, list) {
2667                         list_del(&m->list);
2668                         m->quiesced = 1;
2669                         __maybe_add_mapping(m);
2670                 }
2671                 spin_unlock_irqrestore(&pool->lock, flags);
2672         }
2673
2674         if (h->all_io_entry) {
2675                 INIT_LIST_HEAD(&work);
2676                 dm_deferred_entry_dec(h->all_io_entry, &work);
2677                 if (!list_empty(&work)) {
2678                         spin_lock_irqsave(&pool->lock, flags);
2679                         list_for_each_entry_safe(m, tmp, &work, list)
2680                                 list_add(&m->list, &pool->prepared_discards);
2681                         spin_unlock_irqrestore(&pool->lock, flags);
2682                         wake_worker(pool);
2683                 }
2684         }
2685
2686         mempool_free(h, pool->endio_hook_pool);
2687
2688         return 0;
2689 }
2690
2691 static void thin_postsuspend(struct dm_target *ti)
2692 {
2693         if (dm_noflush_suspending(ti))
2694                 requeue_io((struct thin_c *)ti->private);
2695 }
2696
2697 /*
2698  * <nr mapped sectors> <highest mapped sector>
2699  */
2700 static int thin_status(struct dm_target *ti, status_type_t type,
2701                        unsigned status_flags, char *result, unsigned maxlen)
2702 {
2703         int r;
2704         ssize_t sz = 0;
2705         dm_block_t mapped, highest;
2706         char buf[BDEVNAME_SIZE];
2707         struct thin_c *tc = ti->private;
2708
2709         if (get_pool_mode(tc->pool) == PM_FAIL) {
2710                 DMEMIT("Fail");
2711                 return 0;
2712         }
2713
2714         if (!tc->td)
2715                 DMEMIT("-");
2716         else {
2717                 switch (type) {
2718                 case STATUSTYPE_INFO:
2719                         r = dm_thin_get_mapped_count(tc->td, &mapped);
2720                         if (r)
2721                                 return r;
2722
2723                         r = dm_thin_get_highest_mapped_block(tc->td, &highest);
2724                         if (r < 0)
2725                                 return r;
2726
2727                         DMEMIT("%llu ", mapped * tc->pool->sectors_per_block);
2728                         if (r)
2729                                 DMEMIT("%llu", ((highest + 1) *
2730                                                 tc->pool->sectors_per_block) - 1);
2731                         else
2732                                 DMEMIT("-");
2733                         break;
2734
2735                 case STATUSTYPE_TABLE:
2736                         DMEMIT("%s %lu",
2737                                format_dev_t(buf, tc->pool_dev->bdev->bd_dev),
2738                                (unsigned long) tc->dev_id);
2739                         if (tc->origin_dev)
2740                                 DMEMIT(" %s", format_dev_t(buf, tc->origin_dev->bdev->bd_dev));
2741                         break;
2742                 }
2743         }
2744
2745         return 0;
2746 }
2747
2748 static int thin_iterate_devices(struct dm_target *ti,
2749                                 iterate_devices_callout_fn fn, void *data)
2750 {
2751         sector_t blocks;
2752         struct thin_c *tc = ti->private;
2753         struct pool *pool = tc->pool;
2754
2755         /*
2756          * We can't call dm_pool_get_data_dev_size() since that blocks.  So
2757          * we follow a more convoluted path through to the pool's target.
2758          */
2759         if (!pool->ti)
2760                 return 0;       /* nothing is bound */
2761
2762         blocks = pool->ti->len;
2763         (void) sector_div(blocks, pool->sectors_per_block);
2764         if (blocks)
2765                 return fn(ti, tc->pool_dev, 0, pool->sectors_per_block * blocks, data);
2766
2767         return 0;
2768 }
2769
2770 /*
2771  * A thin device always inherits its queue limits from its pool.
2772  */
2773 static void thin_io_hints(struct dm_target *ti, struct queue_limits *limits)
2774 {
2775         struct thin_c *tc = ti->private;
2776
2777         *limits = bdev_get_queue(tc->pool_dev->bdev)->limits;
2778 }
2779
2780 static struct target_type thin_target = {
2781         .name = "thin",
2782         .version = {1, 6, 0},
2783         .module = THIS_MODULE,
2784         .ctr = thin_ctr,
2785         .dtr = thin_dtr,
2786         .map = thin_map,
2787         .end_io = thin_endio,
2788         .postsuspend = thin_postsuspend,
2789         .status = thin_status,
2790         .iterate_devices = thin_iterate_devices,
2791         .io_hints = thin_io_hints,
2792 };
2793
2794 /*----------------------------------------------------------------*/
2795
2796 static int __init dm_thin_init(void)
2797 {
2798         int r;
2799
2800         pool_table_init();
2801
2802         r = dm_register_target(&thin_target);
2803         if (r)
2804                 return r;
2805
2806         r = dm_register_target(&pool_target);
2807         if (r)
2808                 goto bad_pool_target;
2809
2810         r = -ENOMEM;
2811
2812         _new_mapping_cache = KMEM_CACHE(dm_thin_new_mapping, 0);
2813         if (!_new_mapping_cache)
2814                 goto bad_new_mapping_cache;
2815
2816         _endio_hook_cache = KMEM_CACHE(dm_thin_endio_hook, 0);
2817         if (!_endio_hook_cache)
2818                 goto bad_endio_hook_cache;
2819
2820         return 0;
2821
2822 bad_endio_hook_cache:
2823         kmem_cache_destroy(_new_mapping_cache);
2824 bad_new_mapping_cache:
2825         dm_unregister_target(&pool_target);
2826 bad_pool_target:
2827         dm_unregister_target(&thin_target);
2828
2829         return r;
2830 }
2831
2832 static void dm_thin_exit(void)
2833 {
2834         dm_unregister_target(&thin_target);
2835         dm_unregister_target(&pool_target);
2836
2837         kmem_cache_destroy(_new_mapping_cache);
2838         kmem_cache_destroy(_endio_hook_cache);
2839 }
2840
2841 module_init(dm_thin_init);
2842 module_exit(dm_thin_exit);
2843
2844 MODULE_DESCRIPTION(DM_NAME " thin provisioning target");
2845 MODULE_AUTHOR("Joe Thornber <dm-devel@redhat.com>");
2846 MODULE_LICENSE("GPL");