fedora core 6 1.2949 + vserver 2.2.0
[linux-2.6.git] / drivers / md / dm.c
1 /*
2  * Copyright (C) 2001, 2002 Sistina Software (UK) Limited.
3  * Copyright (C) 2004-2006 Red Hat, Inc. All rights reserved.
4  *
5  * This file is released under the GPL.
6  */
7
8 #include "dm.h"
9 #include "dm-bio-list.h"
10
11 #include <linux/init.h>
12 #include <linux/module.h>
13 #include <linux/mutex.h>
14 #include <linux/moduleparam.h>
15 #include <linux/blkpg.h>
16 #include <linux/bio.h>
17 #include <linux/buffer_head.h>
18 #include <linux/mempool.h>
19 #include <linux/slab.h>
20 #include <linux/idr.h>
21 #include <linux/hdreg.h>
22 #include <linux/blktrace_api.h>
23 #include <linux/smp_lock.h>
24 #include <linux/vs_base.h>
25
26 #define DM_MSG_PREFIX "core"
27
28 static const char *_name = DM_NAME;
29
30 static unsigned int major = 0;
31 static unsigned int _major = 0;
32
33 static DEFINE_SPINLOCK(_minor_lock);
34 /*
35  * One of these is allocated per bio.
36  */
37 struct dm_io {
38         struct mapped_device *md;
39         int error;
40         struct bio *bio;
41         atomic_t io_count;
42         unsigned long start_time;
43 };
44
45 /*
46  * One of these is allocated per target within a bio.  Hopefully
47  * this will be simplified out one day.
48  */
49 struct target_io {
50         struct dm_io *io;
51         struct dm_target *ti;
52         union map_info info;
53 };
54
55 union map_info *dm_get_mapinfo(struct bio *bio)
56 {
57         if (bio && bio->bi_private)
58                 return &((struct target_io *)bio->bi_private)->info;
59         return NULL;
60 }
61
62 #define MINOR_ALLOCED ((void *)-1)
63
64 /*
65  * Bits for the md->flags field.
66  */
67 #define DMF_BLOCK_IO 0
68 #define DMF_SUSPENDED 1
69 #define DMF_FROZEN 2
70 #define DMF_FREEING 3
71 #define DMF_DELETING 4
72 #define DMF_NOFLUSH_SUSPENDING 5
73
74 struct mapped_device {
75         struct rw_semaphore io_lock;
76         struct semaphore suspend_lock;
77         spinlock_t pushback_lock;
78         rwlock_t map_lock;
79         atomic_t holders;
80         atomic_t open_count;
81         xid_t xid;
82
83         unsigned long flags;
84
85         request_queue_t *queue;
86         struct gendisk *disk;
87         char name[16];
88
89         void *interface_ptr;
90
91         /*
92          * A list of ios that arrived while we were suspended.
93          */
94         atomic_t pending;
95         wait_queue_head_t wait;
96         struct bio_list deferred;
97         struct bio_list pushback;
98
99         /*
100          * The current mapping.
101          */
102         struct dm_table *map;
103
104         /*
105          * io objects are allocated from here.
106          */
107         mempool_t *io_pool;
108         mempool_t *tio_pool;
109
110         struct bio_set *bs;
111
112         /*
113          * Event handling.
114          */
115         atomic_t event_nr;
116         wait_queue_head_t eventq;
117
118         /*
119          * freeze/thaw support require holding onto a super block
120          */
121         struct super_block *frozen_sb;
122         struct block_device *suspended_bdev;
123
124         /* forced geometry settings */
125         struct hd_geometry geometry;
126 };
127
128 #define MIN_IOS 256
129 static struct kmem_cache *_io_cache;
130 static struct kmem_cache *_tio_cache;
131
132 static int __init local_init(void)
133 {
134         int r;
135
136         /* allocate a slab for the dm_ios */
137         _io_cache = kmem_cache_create("dm_io",
138                                       sizeof(struct dm_io), 0, 0, NULL, NULL);
139         if (!_io_cache)
140                 return -ENOMEM;
141
142         /* allocate a slab for the target ios */
143         _tio_cache = kmem_cache_create("dm_tio", sizeof(struct target_io),
144                                        0, 0, NULL, NULL);
145         if (!_tio_cache) {
146                 kmem_cache_destroy(_io_cache);
147                 return -ENOMEM;
148         }
149
150         _major = major;
151         r = register_blkdev(_major, _name);
152         if (r < 0) {
153                 kmem_cache_destroy(_tio_cache);
154                 kmem_cache_destroy(_io_cache);
155                 return r;
156         }
157
158         if (!_major)
159                 _major = r;
160
161         return 0;
162 }
163
164 static void local_exit(void)
165 {
166         kmem_cache_destroy(_tio_cache);
167         kmem_cache_destroy(_io_cache);
168
169         if (unregister_blkdev(_major, _name) < 0)
170                 DMERR("unregister_blkdev failed");
171
172         _major = 0;
173
174         DMINFO("cleaned up");
175 }
176
177 int (*_inits[])(void) __initdata = {
178         local_init,
179         dm_target_init,
180         dm_linear_init,
181         dm_stripe_init,
182         dm_interface_init,
183 };
184
185 void (*_exits[])(void) = {
186         local_exit,
187         dm_target_exit,
188         dm_linear_exit,
189         dm_stripe_exit,
190         dm_interface_exit,
191 };
192
193 static int __init dm_init(void)
194 {
195         const int count = ARRAY_SIZE(_inits);
196
197         int r, i;
198
199         for (i = 0; i < count; i++) {
200                 r = _inits[i]();
201                 if (r)
202                         goto bad;
203         }
204
205         return 0;
206
207       bad:
208         while (i--)
209                 _exits[i]();
210
211         return r;
212 }
213
214 static void __exit dm_exit(void)
215 {
216         int i = ARRAY_SIZE(_exits);
217
218         while (i--)
219                 _exits[i]();
220 }
221
222 /*
223  * Block device functions
224  */
225 static int dm_blk_open(struct inode *inode, struct file *file)
226 {
227         struct mapped_device *md;
228         int ret = -ENXIO;
229
230         spin_lock(&_minor_lock);
231
232         md = inode->i_bdev->bd_disk->private_data;
233         if (!md)
234                 goto out;
235
236         if (test_bit(DMF_FREEING, &md->flags) ||
237             test_bit(DMF_DELETING, &md->flags))
238                 goto out;
239
240         ret = -EACCES;
241         if (!vx_check(md->xid, VS_IDENT|VS_HOSTID))
242                 goto out;
243
244         dm_get(md);
245         atomic_inc(&md->open_count);
246         ret = 0;
247 out:
248         spin_unlock(&_minor_lock);
249         return ret;
250 }
251
252 static int dm_blk_close(struct inode *inode, struct file *file)
253 {
254         struct mapped_device *md;
255
256         md = inode->i_bdev->bd_disk->private_data;
257         atomic_dec(&md->open_count);
258         dm_put(md);
259         return 0;
260 }
261
262 int dm_open_count(struct mapped_device *md)
263 {
264         return atomic_read(&md->open_count);
265 }
266
267 /*
268  * Guarantees nothing is using the device before it's deleted.
269  */
270 int dm_lock_for_deletion(struct mapped_device *md)
271 {
272         int r = 0;
273
274         spin_lock(&_minor_lock);
275
276         if (dm_open_count(md))
277                 r = -EBUSY;
278         else
279                 set_bit(DMF_DELETING, &md->flags);
280
281         spin_unlock(&_minor_lock);
282
283         return r;
284 }
285
286 static int dm_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo)
287 {
288         struct mapped_device *md = bdev->bd_disk->private_data;
289
290         return dm_get_geometry(md, geo);
291 }
292
293 static int dm_blk_ioctl(struct inode *inode, struct file *file,
294                         unsigned int cmd, unsigned long arg)
295 {
296         struct mapped_device *md;
297         struct dm_table *map;
298         struct dm_target *tgt;
299         int r = -ENOTTY;
300
301         /* We don't really need this lock, but we do need 'inode'. */
302         unlock_kernel();
303
304         md = inode->i_bdev->bd_disk->private_data;
305
306         map = dm_get_table(md);
307
308         if (!map || !dm_table_get_size(map))
309                 goto out;
310
311         /* We only support devices that have a single target */
312         if (dm_table_get_num_targets(map) != 1)
313                 goto out;
314
315         tgt = dm_table_get_target(map, 0);
316
317         if (dm_suspended(md)) {
318                 r = -EAGAIN;
319                 goto out;
320         }
321
322         if (tgt->type->ioctl)
323                 r = tgt->type->ioctl(tgt, inode, file, cmd, arg);
324
325 out:
326         dm_table_put(map);
327
328         lock_kernel();
329         return r;
330 }
331
332 static inline struct dm_io *alloc_io(struct mapped_device *md)
333 {
334         return mempool_alloc(md->io_pool, GFP_NOIO);
335 }
336
337 static inline void free_io(struct mapped_device *md, struct dm_io *io)
338 {
339         mempool_free(io, md->io_pool);
340 }
341
342 static inline struct target_io *alloc_tio(struct mapped_device *md)
343 {
344         return mempool_alloc(md->tio_pool, GFP_NOIO);
345 }
346
347 static inline void free_tio(struct mapped_device *md, struct target_io *tio)
348 {
349         mempool_free(tio, md->tio_pool);
350 }
351
352 static void start_io_acct(struct dm_io *io)
353 {
354         struct mapped_device *md = io->md;
355
356         io->start_time = jiffies;
357
358         preempt_disable();
359         disk_round_stats(dm_disk(md));
360         preempt_enable();
361         dm_disk(md)->in_flight = atomic_inc_return(&md->pending);
362 }
363
364 static int end_io_acct(struct dm_io *io)
365 {
366         struct mapped_device *md = io->md;
367         struct bio *bio = io->bio;
368         unsigned long duration = jiffies - io->start_time;
369         int pending;
370         int rw = bio_data_dir(bio);
371
372         preempt_disable();
373         disk_round_stats(dm_disk(md));
374         preempt_enable();
375         dm_disk(md)->in_flight = pending = atomic_dec_return(&md->pending);
376
377         disk_stat_add(dm_disk(md), ticks[rw], duration);
378
379         return !pending;
380 }
381
382 /*
383  * Add the bio to the list of deferred io.
384  */
385 static int queue_io(struct mapped_device *md, struct bio *bio)
386 {
387         down_write(&md->io_lock);
388
389         if (!test_bit(DMF_BLOCK_IO, &md->flags)) {
390                 up_write(&md->io_lock);
391                 return 1;
392         }
393
394         bio_list_add(&md->deferred, bio);
395
396         up_write(&md->io_lock);
397         return 0;               /* deferred successfully */
398 }
399
400 /*
401  * Everyone (including functions in this file), should use this
402  * function to access the md->map field, and make sure they call
403  * dm_table_put() when finished.
404  */
405 struct dm_table *dm_get_table(struct mapped_device *md)
406 {
407         struct dm_table *t;
408
409         read_lock(&md->map_lock);
410         t = md->map;
411         if (t)
412                 dm_table_get(t);
413         read_unlock(&md->map_lock);
414
415         return t;
416 }
417
418 /*
419  * Get the geometry associated with a dm device
420  */
421 int dm_get_geometry(struct mapped_device *md, struct hd_geometry *geo)
422 {
423         *geo = md->geometry;
424
425         return 0;
426 }
427
428 /*
429  * Set the geometry of a device.
430  */
431 int dm_set_geometry(struct mapped_device *md, struct hd_geometry *geo)
432 {
433         sector_t sz = (sector_t)geo->cylinders * geo->heads * geo->sectors;
434
435         if (geo->start > sz) {
436                 DMWARN("Start sector is beyond the geometry limits.");
437                 return -EINVAL;
438         }
439
440         md->geometry = *geo;
441
442         return 0;
443 }
444
445 /*
446  * Get the xid associated with a dm device
447  */
448 xid_t dm_get_xid(struct mapped_device *md)
449 {
450         return md->xid;
451 }
452
453 /*-----------------------------------------------------------------
454  * CRUD START:
455  *   A more elegant soln is in the works that uses the queue
456  *   merge fn, unfortunately there are a couple of changes to
457  *   the block layer that I want to make for this.  So in the
458  *   interests of getting something for people to use I give
459  *   you this clearly demarcated crap.
460  *---------------------------------------------------------------*/
461
462 static int __noflush_suspending(struct mapped_device *md)
463 {
464         return test_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
465 }
466
467 /*
468  * Decrements the number of outstanding ios that a bio has been
469  * cloned into, completing the original io if necc.
470  */
471 static void dec_pending(struct dm_io *io, int error)
472 {
473         unsigned long flags;
474
475         /* Push-back supersedes any I/O errors */
476         if (error && !(io->error > 0 && __noflush_suspending(io->md)))
477                 io->error = error;
478
479         if (atomic_dec_and_test(&io->io_count)) {
480                 if (io->error == DM_ENDIO_REQUEUE) {
481                         /*
482                          * Target requested pushing back the I/O.
483                          * This must be handled before the sleeper on
484                          * suspend queue merges the pushback list.
485                          */
486                         spin_lock_irqsave(&io->md->pushback_lock, flags);
487                         if (__noflush_suspending(io->md))
488                                 bio_list_add(&io->md->pushback, io->bio);
489                         else
490                                 /* noflush suspend was interrupted. */
491                                 io->error = -EIO;
492                         spin_unlock_irqrestore(&io->md->pushback_lock, flags);
493                 }
494
495                 if (end_io_acct(io))
496                         /* nudge anyone waiting on suspend queue */
497                         wake_up(&io->md->wait);
498
499                 if (io->error != DM_ENDIO_REQUEUE) {
500                         blk_add_trace_bio(io->md->queue, io->bio,
501                                           BLK_TA_COMPLETE);
502
503                         bio_endio(io->bio, io->bio->bi_size, io->error);
504                 }
505
506                 free_io(io->md, io);
507         }
508 }
509
510 static int clone_endio(struct bio *bio, unsigned int done, int error)
511 {
512         int r = 0;
513         struct target_io *tio = bio->bi_private;
514         struct mapped_device *md = tio->io->md;
515         dm_endio_fn endio = tio->ti->type->end_io;
516
517         if (bio->bi_size)
518                 return 1;
519
520         if (!bio_flagged(bio, BIO_UPTODATE) && !error)
521                 error = -EIO;
522
523         if (endio) {
524                 r = endio(tio->ti, bio, error, &tio->info);
525                 if (r < 0 || r == DM_ENDIO_REQUEUE)
526                         /*
527                          * error and requeue request are handled
528                          * in dec_pending().
529                          */
530                         error = r;
531                 else if (r == DM_ENDIO_INCOMPLETE)
532                         /* The target will handle the io */
533                         return 1;
534                 else if (r) {
535                         DMWARN("unimplemented target endio return value: %d", r);
536                         BUG();
537                 }
538         }
539
540         dec_pending(tio->io, error);
541
542         /*
543          * Store md for cleanup instead of tio which is about to get freed.
544          */
545         bio->bi_private = md->bs;
546
547         bio_put(bio);
548         free_tio(md, tio);
549         return r;
550 }
551
552 static sector_t max_io_len(struct mapped_device *md,
553                            sector_t sector, struct dm_target *ti)
554 {
555         sector_t offset = sector - ti->begin;
556         sector_t len = ti->len - offset;
557
558         /*
559          * Does the target need to split even further ?
560          */
561         if (ti->split_io) {
562                 sector_t boundary;
563                 boundary = ((offset + ti->split_io) & ~(ti->split_io - 1))
564                            - offset;
565                 if (len > boundary)
566                         len = boundary;
567         }
568
569         return len;
570 }
571
572 static void __map_bio(struct dm_target *ti, struct bio *clone,
573                       struct target_io *tio)
574 {
575         int r;
576         sector_t sector;
577         struct mapped_device *md;
578
579         /*
580          * Sanity checks.
581          */
582         BUG_ON(!clone->bi_size);
583
584         clone->bi_end_io = clone_endio;
585         clone->bi_private = tio;
586
587         /*
588          * Map the clone.  If r == 0 we don't need to do
589          * anything, the target has assumed ownership of
590          * this io.
591          */
592         atomic_inc(&tio->io->io_count);
593         sector = clone->bi_sector;
594         r = ti->type->map(ti, clone, &tio->info);
595         if (r == DM_MAPIO_REMAPPED) {
596                 /* the bio has been remapped so dispatch it */
597
598                 blk_add_trace_remap(bdev_get_queue(clone->bi_bdev), clone,
599                                     tio->io->bio->bi_bdev->bd_dev, sector,
600                                     clone->bi_sector);
601
602                 generic_make_request(clone);
603         } else if (r < 0 || r == DM_MAPIO_REQUEUE) {
604                 /* error the io and bail out, or requeue it if needed */
605                 md = tio->io->md;
606                 dec_pending(tio->io, r);
607                 /*
608                  * Store bio_set for cleanup.
609                  */
610                 clone->bi_private = md->bs;
611                 bio_put(clone);
612                 free_tio(md, tio);
613         } else if (r) {
614                 DMWARN("unimplemented target map return value: %d", r);
615                 BUG();
616         }
617 }
618
619 struct clone_info {
620         struct mapped_device *md;
621         struct dm_table *map;
622         struct bio *bio;
623         struct dm_io *io;
624         sector_t sector;
625         sector_t sector_count;
626         unsigned short idx;
627 };
628
629 static void dm_bio_destructor(struct bio *bio)
630 {
631         struct bio_set *bs = bio->bi_private;
632
633         bio_free(bio, bs);
634 }
635
636 /*
637  * Creates a little bio that is just does part of a bvec.
638  */
639 static struct bio *split_bvec(struct bio *bio, sector_t sector,
640                               unsigned short idx, unsigned int offset,
641                               unsigned int len, struct bio_set *bs)
642 {
643         struct bio *clone;
644         struct bio_vec *bv = bio->bi_io_vec + idx;
645
646         clone = bio_alloc_bioset(GFP_NOIO, 1, bs);
647         clone->bi_destructor = dm_bio_destructor;
648         *clone->bi_io_vec = *bv;
649
650         clone->bi_sector = sector;
651         clone->bi_bdev = bio->bi_bdev;
652         clone->bi_rw = bio->bi_rw;
653         clone->bi_vcnt = 1;
654         clone->bi_size = to_bytes(len);
655         clone->bi_io_vec->bv_offset = offset;
656         clone->bi_io_vec->bv_len = clone->bi_size;
657
658         return clone;
659 }
660
661 /*
662  * Creates a bio that consists of range of complete bvecs.
663  */
664 static struct bio *clone_bio(struct bio *bio, sector_t sector,
665                              unsigned short idx, unsigned short bv_count,
666                              unsigned int len, struct bio_set *bs)
667 {
668         struct bio *clone;
669
670         clone = bio_alloc_bioset(GFP_NOIO, bio->bi_max_vecs, bs);
671         __bio_clone(clone, bio);
672         clone->bi_destructor = dm_bio_destructor;
673         clone->bi_sector = sector;
674         clone->bi_idx = idx;
675         clone->bi_vcnt = idx + bv_count;
676         clone->bi_size = to_bytes(len);
677         clone->bi_flags &= ~(1 << BIO_SEG_VALID);
678
679         return clone;
680 }
681
682 static void __clone_and_map(struct clone_info *ci)
683 {
684         struct bio *clone, *bio = ci->bio;
685         struct dm_target *ti = dm_table_find_target(ci->map, ci->sector);
686         sector_t len = 0, max = max_io_len(ci->md, ci->sector, ti);
687         struct target_io *tio;
688
689         /*
690          * Allocate a target io object.
691          */
692         tio = alloc_tio(ci->md);
693         tio->io = ci->io;
694         tio->ti = ti;
695         memset(&tio->info, 0, sizeof(tio->info));
696
697         if (ci->sector_count <= max) {
698                 /*
699                  * Optimise for the simple case where we can do all of
700                  * the remaining io with a single clone.
701                  */
702                 clone = clone_bio(bio, ci->sector, ci->idx,
703                                   bio->bi_vcnt - ci->idx, ci->sector_count,
704                                   ci->md->bs);
705                 __map_bio(ti, clone, tio);
706                 ci->sector_count = 0;
707
708         } else if (to_sector(bio->bi_io_vec[ci->idx].bv_len) <= max) {
709                 /*
710                  * There are some bvecs that don't span targets.
711                  * Do as many of these as possible.
712                  */
713                 int i;
714                 sector_t remaining = max;
715                 sector_t bv_len;
716
717                 for (i = ci->idx; remaining && (i < bio->bi_vcnt); i++) {
718                         bv_len = to_sector(bio->bi_io_vec[i].bv_len);
719
720                         if (bv_len > remaining)
721                                 break;
722
723                         remaining -= bv_len;
724                         len += bv_len;
725                 }
726
727                 clone = clone_bio(bio, ci->sector, ci->idx, i - ci->idx, len,
728                                   ci->md->bs);
729                 __map_bio(ti, clone, tio);
730
731                 ci->sector += len;
732                 ci->sector_count -= len;
733                 ci->idx = i;
734
735         } else {
736                 /*
737                  * Handle a bvec that must be split between two or more targets.
738                  */
739                 struct bio_vec *bv = bio->bi_io_vec + ci->idx;
740                 sector_t remaining = to_sector(bv->bv_len);
741                 unsigned int offset = 0;
742
743                 do {
744                         if (offset) {
745                                 ti = dm_table_find_target(ci->map, ci->sector);
746                                 max = max_io_len(ci->md, ci->sector, ti);
747
748                                 tio = alloc_tio(ci->md);
749                                 tio->io = ci->io;
750                                 tio->ti = ti;
751                                 memset(&tio->info, 0, sizeof(tio->info));
752                         }
753
754                         len = min(remaining, max);
755
756                         clone = split_bvec(bio, ci->sector, ci->idx,
757                                            bv->bv_offset + offset, len,
758                                            ci->md->bs);
759
760                         __map_bio(ti, clone, tio);
761
762                         ci->sector += len;
763                         ci->sector_count -= len;
764                         offset += to_bytes(len);
765                 } while (remaining -= len);
766
767                 ci->idx++;
768         }
769 }
770
771 /*
772  * Split the bio into several clones.
773  */
774 static void __split_bio(struct mapped_device *md, struct bio *bio)
775 {
776         struct clone_info ci;
777
778         ci.map = dm_get_table(md);
779         if (!ci.map) {
780                 bio_io_error(bio, bio->bi_size);
781                 return;
782         }
783
784         ci.md = md;
785         ci.bio = bio;
786         ci.io = alloc_io(md);
787         ci.io->error = 0;
788         atomic_set(&ci.io->io_count, 1);
789         ci.io->bio = bio;
790         ci.io->md = md;
791         ci.sector = bio->bi_sector;
792         ci.sector_count = bio_sectors(bio);
793         ci.idx = bio->bi_idx;
794
795         start_io_acct(ci.io);
796         while (ci.sector_count)
797                 __clone_and_map(&ci);
798
799         /* drop the extra reference count */
800         dec_pending(ci.io, 0);
801         dm_table_put(ci.map);
802 }
803 /*-----------------------------------------------------------------
804  * CRUD END
805  *---------------------------------------------------------------*/
806
807 /*
808  * The request function that just remaps the bio built up by
809  * dm_merge_bvec.
810  */
811 static int dm_request(request_queue_t *q, struct bio *bio)
812 {
813         int r;
814         int rw = bio_data_dir(bio);
815         struct mapped_device *md = q->queuedata;
816
817         down_read(&md->io_lock);
818
819         disk_stat_inc(dm_disk(md), ios[rw]);
820         disk_stat_add(dm_disk(md), sectors[rw], bio_sectors(bio));
821
822         /*
823          * If we're suspended we have to queue
824          * this io for later.
825          */
826         while (test_bit(DMF_BLOCK_IO, &md->flags)) {
827                 up_read(&md->io_lock);
828
829                 if (bio_rw(bio) == READA) {
830                         bio_io_error(bio, bio->bi_size);
831                         return 0;
832                 }
833
834                 r = queue_io(md, bio);
835                 if (r < 0) {
836                         bio_io_error(bio, bio->bi_size);
837                         return 0;
838
839                 } else if (r == 0)
840                         return 0;       /* deferred successfully */
841
842                 /*
843                  * We're in a while loop, because someone could suspend
844                  * before we get to the following read lock.
845                  */
846                 down_read(&md->io_lock);
847         }
848
849         __split_bio(md, bio);
850         up_read(&md->io_lock);
851         return 0;
852 }
853
854 static int dm_flush_all(request_queue_t *q, struct gendisk *disk,
855                         sector_t *error_sector)
856 {
857         struct mapped_device *md = q->queuedata;
858         struct dm_table *map = dm_get_table(md);
859         int ret = -ENXIO;
860
861         if (map) {
862                 ret = dm_table_flush_all(map);
863                 dm_table_put(map);
864         }
865
866         return ret;
867 }
868
869 static void dm_unplug_all(request_queue_t *q)
870 {
871         struct mapped_device *md = q->queuedata;
872         struct dm_table *map = dm_get_table(md);
873
874         if (map) {
875                 dm_table_unplug_all(map);
876                 dm_table_put(map);
877         }
878 }
879
880 static int dm_any_congested(void *congested_data, int bdi_bits)
881 {
882         int r;
883         struct mapped_device *md = (struct mapped_device *) congested_data;
884         struct dm_table *map = dm_get_table(md);
885
886         if (!map || test_bit(DMF_BLOCK_IO, &md->flags))
887                 r = bdi_bits;
888         else
889                 r = dm_table_any_congested(map, bdi_bits);
890
891         dm_table_put(map);
892         return r;
893 }
894
895 /*-----------------------------------------------------------------
896  * An IDR is used to keep track of allocated minor numbers.
897  *---------------------------------------------------------------*/
898 static DEFINE_IDR(_minor_idr);
899
900 static void free_minor(int minor)
901 {
902         spin_lock(&_minor_lock);
903         idr_remove(&_minor_idr, minor);
904         spin_unlock(&_minor_lock);
905 }
906
907 /*
908  * See if the device with a specific minor # is free.
909  */
910 static int specific_minor(struct mapped_device *md, int minor)
911 {
912         int r, m;
913
914         if (minor >= (1 << MINORBITS))
915                 return -EINVAL;
916
917         r = idr_pre_get(&_minor_idr, GFP_KERNEL);
918         if (!r)
919                 return -ENOMEM;
920
921         spin_lock(&_minor_lock);
922
923         if (idr_find(&_minor_idr, minor)) {
924                 r = -EBUSY;
925                 goto out;
926         }
927
928         r = idr_get_new_above(&_minor_idr, MINOR_ALLOCED, minor, &m);
929         if (r)
930                 goto out;
931
932         if (m != minor) {
933                 idr_remove(&_minor_idr, m);
934                 r = -EBUSY;
935                 goto out;
936         }
937
938 out:
939         spin_unlock(&_minor_lock);
940         return r;
941 }
942
943 static int next_free_minor(struct mapped_device *md, int *minor)
944 {
945         int r, m;
946
947         r = idr_pre_get(&_minor_idr, GFP_KERNEL);
948         if (!r)
949                 return -ENOMEM;
950
951         spin_lock(&_minor_lock);
952
953         r = idr_get_new(&_minor_idr, MINOR_ALLOCED, &m);
954         if (r) {
955                 goto out;
956         }
957
958         if (m >= (1 << MINORBITS)) {
959                 idr_remove(&_minor_idr, m);
960                 r = -ENOSPC;
961                 goto out;
962         }
963
964         *minor = m;
965
966 out:
967         spin_unlock(&_minor_lock);
968         return r;
969 }
970
971 static struct block_device_operations dm_blk_dops;
972
973 /*
974  * Allocate and initialise a blank device with a given minor.
975  */
976 static struct mapped_device *alloc_dev(int minor)
977 {
978         int r;
979         struct mapped_device *md = kmalloc(sizeof(*md), GFP_KERNEL);
980         void *old_md;
981
982         if (!md) {
983                 DMWARN("unable to allocate device, out of memory.");
984                 return NULL;
985         }
986
987         if (!try_module_get(THIS_MODULE))
988                 goto bad0;
989
990         /* get a minor number for the dev */
991         if (minor == DM_ANY_MINOR)
992                 r = next_free_minor(md, &minor);
993         else
994                 r = specific_minor(md, minor);
995         if (r < 0)
996                 goto bad1;
997
998         memset(md, 0, sizeof(*md));
999         init_rwsem(&md->io_lock);
1000         init_MUTEX(&md->suspend_lock);
1001         spin_lock_init(&md->pushback_lock);
1002         rwlock_init(&md->map_lock);
1003         atomic_set(&md->holders, 1);
1004         atomic_set(&md->open_count, 0);
1005         atomic_set(&md->event_nr, 0);
1006         md->xid = vx_current_xid();
1007
1008         md->queue = blk_alloc_queue(GFP_KERNEL);
1009         if (!md->queue)
1010                 goto bad1_free_minor;
1011
1012         md->queue->queuedata = md;
1013         md->queue->backing_dev_info.congested_fn = dm_any_congested;
1014         md->queue->backing_dev_info.congested_data = md;
1015         blk_queue_make_request(md->queue, dm_request);
1016         blk_queue_bounce_limit(md->queue, BLK_BOUNCE_ANY);
1017         md->queue->unplug_fn = dm_unplug_all;
1018         md->queue->issue_flush_fn = dm_flush_all;
1019
1020         md->io_pool = mempool_create_slab_pool(MIN_IOS, _io_cache);
1021         if (!md->io_pool)
1022                 goto bad2;
1023
1024         md->tio_pool = mempool_create_slab_pool(MIN_IOS, _tio_cache);
1025         if (!md->tio_pool)
1026                 goto bad3;
1027
1028         md->bs = bioset_create(16, 16, 4);
1029         if (!md->bs)
1030                 goto bad_no_bioset;
1031
1032         md->disk = alloc_disk(1);
1033         if (!md->disk)
1034                 goto bad4;
1035
1036         atomic_set(&md->pending, 0);
1037         init_waitqueue_head(&md->wait);
1038         init_waitqueue_head(&md->eventq);
1039
1040         md->disk->major = _major;
1041         md->disk->first_minor = minor;
1042         md->disk->fops = &dm_blk_dops;
1043         md->disk->queue = md->queue;
1044         md->disk->private_data = md;
1045         sprintf(md->disk->disk_name, "dm-%d", minor);
1046         add_disk(md->disk);
1047         format_dev_t(md->name, MKDEV(_major, minor));
1048
1049         /* Populate the mapping, nobody knows we exist yet */
1050         spin_lock(&_minor_lock);
1051         old_md = idr_replace(&_minor_idr, md, minor);
1052         spin_unlock(&_minor_lock);
1053
1054         BUG_ON(old_md != MINOR_ALLOCED);
1055
1056         return md;
1057
1058  bad4:
1059         bioset_free(md->bs);
1060  bad_no_bioset:
1061         mempool_destroy(md->tio_pool);
1062  bad3:
1063         mempool_destroy(md->io_pool);
1064  bad2:
1065         blk_cleanup_queue(md->queue);
1066  bad1_free_minor:
1067         free_minor(minor);
1068  bad1:
1069         module_put(THIS_MODULE);
1070  bad0:
1071         kfree(md);
1072         return NULL;
1073 }
1074
1075 static void free_dev(struct mapped_device *md)
1076 {
1077         int minor = md->disk->first_minor;
1078
1079         if (md->suspended_bdev) {
1080                 thaw_bdev(md->suspended_bdev, NULL);
1081                 bdput(md->suspended_bdev);
1082         }
1083         mempool_destroy(md->tio_pool);
1084         mempool_destroy(md->io_pool);
1085         bioset_free(md->bs);
1086         del_gendisk(md->disk);
1087         free_minor(minor);
1088
1089         spin_lock(&_minor_lock);
1090         md->disk->private_data = NULL;
1091         spin_unlock(&_minor_lock);
1092
1093         put_disk(md->disk);
1094         blk_cleanup_queue(md->queue);
1095         module_put(THIS_MODULE);
1096         kfree(md);
1097 }
1098
1099 /*
1100  * Bind a table to the device.
1101  */
1102 static void event_callback(void *context)
1103 {
1104         struct mapped_device *md = (struct mapped_device *) context;
1105
1106         atomic_inc(&md->event_nr);
1107         wake_up(&md->eventq);
1108 }
1109
1110 static void __set_size(struct mapped_device *md, sector_t size)
1111 {
1112         set_capacity(md->disk, size);
1113
1114         mutex_lock(&md->suspended_bdev->bd_inode->i_mutex);
1115         i_size_write(md->suspended_bdev->bd_inode, (loff_t)size << SECTOR_SHIFT);
1116         mutex_unlock(&md->suspended_bdev->bd_inode->i_mutex);
1117 }
1118
1119 static int __bind(struct mapped_device *md, struct dm_table *t)
1120 {
1121         request_queue_t *q = md->queue;
1122         sector_t size;
1123
1124         size = dm_table_get_size(t);
1125
1126         /*
1127          * Wipe any geometry if the size of the table changed.
1128          */
1129         if (size != get_capacity(md->disk))
1130                 memset(&md->geometry, 0, sizeof(md->geometry));
1131
1132         if (md->suspended_bdev)
1133                 __set_size(md, size);
1134         if (size == 0)
1135                 return 0;
1136
1137         dm_table_get(t);
1138         dm_table_event_callback(t, event_callback, md);
1139
1140         write_lock(&md->map_lock);
1141         md->map = t;
1142         dm_table_set_restrictions(t, q);
1143         write_unlock(&md->map_lock);
1144
1145         return 0;
1146 }
1147
1148 static void __unbind(struct mapped_device *md)
1149 {
1150         struct dm_table *map = md->map;
1151
1152         if (!map)
1153                 return;
1154
1155         dm_table_event_callback(map, NULL, NULL);
1156         write_lock(&md->map_lock);
1157         md->map = NULL;
1158         write_unlock(&md->map_lock);
1159         dm_table_put(map);
1160 }
1161
1162 /*
1163  * Constructor for a new device.
1164  */
1165 int dm_create(int minor, struct mapped_device **result)
1166 {
1167         struct mapped_device *md;
1168
1169         md = alloc_dev(minor);
1170         if (!md)
1171                 return -ENXIO;
1172
1173         *result = md;
1174         return 0;
1175 }
1176
1177 static struct mapped_device *dm_find_md(dev_t dev)
1178 {
1179         struct mapped_device *md;
1180         unsigned minor = MINOR(dev);
1181
1182         if (MAJOR(dev) != _major || minor >= (1 << MINORBITS))
1183                 return NULL;
1184
1185         spin_lock(&_minor_lock);
1186
1187         md = idr_find(&_minor_idr, minor);
1188         if (md && (md == MINOR_ALLOCED ||
1189                    (dm_disk(md)->first_minor != minor) ||
1190                    test_bit(DMF_FREEING, &md->flags))) {
1191                 md = NULL;
1192                 goto out;
1193         }
1194
1195 out:
1196         spin_unlock(&_minor_lock);
1197
1198         return md;
1199 }
1200
1201 struct mapped_device *dm_get_md(dev_t dev)
1202 {
1203         struct mapped_device *md = dm_find_md(dev);
1204
1205         if (md)
1206                 dm_get(md);
1207
1208         return md;
1209 }
1210
1211 void *dm_get_mdptr(struct mapped_device *md)
1212 {
1213         return md->interface_ptr;
1214 }
1215
1216 void dm_set_mdptr(struct mapped_device *md, void *ptr)
1217 {
1218         md->interface_ptr = ptr;
1219 }
1220
1221 void dm_get(struct mapped_device *md)
1222 {
1223         atomic_inc(&md->holders);
1224 }
1225
1226 const char *dm_device_name(struct mapped_device *md)
1227 {
1228         return md->name;
1229 }
1230 EXPORT_SYMBOL_GPL(dm_device_name);
1231
1232 void dm_put(struct mapped_device *md)
1233 {
1234         struct dm_table *map;
1235
1236         BUG_ON(test_bit(DMF_FREEING, &md->flags));
1237
1238         if (atomic_dec_and_lock(&md->holders, &_minor_lock)) {
1239                 map = dm_get_table(md);
1240                 idr_replace(&_minor_idr, MINOR_ALLOCED, dm_disk(md)->first_minor);
1241                 set_bit(DMF_FREEING, &md->flags);
1242                 spin_unlock(&_minor_lock);
1243                 if (!dm_suspended(md)) {
1244                         dm_table_presuspend_targets(map);
1245                         dm_table_postsuspend_targets(map);
1246                 }
1247                 __unbind(md);
1248                 dm_table_put(map);
1249                 free_dev(md);
1250         }
1251 }
1252
1253 /*
1254  * Process the deferred bios
1255  */
1256 static void __flush_deferred_io(struct mapped_device *md, struct bio *c)
1257 {
1258         struct bio *n;
1259
1260         while (c) {
1261                 n = c->bi_next;
1262                 c->bi_next = NULL;
1263                 __split_bio(md, c);
1264                 c = n;
1265         }
1266 }
1267
1268 /*
1269  * Swap in a new table (destroying old one).
1270  */
1271 int dm_swap_table(struct mapped_device *md, struct dm_table *table)
1272 {
1273         int r = -EINVAL;
1274
1275         down(&md->suspend_lock);
1276
1277         /* device must be suspended */
1278         if (!dm_suspended(md))
1279                 goto out;
1280
1281         /* without bdev, the device size cannot be changed */
1282         if (!md->suspended_bdev)
1283                 if (get_capacity(md->disk) != dm_table_get_size(table))
1284                         goto out;
1285
1286         __unbind(md);
1287         r = __bind(md, table);
1288
1289 out:
1290         up(&md->suspend_lock);
1291         return r;
1292 }
1293
1294 /*
1295  * Functions to lock and unlock any filesystem running on the
1296  * device.
1297  */
1298 static int lock_fs(struct mapped_device *md)
1299 {
1300         int r;
1301
1302         WARN_ON(md->frozen_sb);
1303
1304         md->frozen_sb = freeze_bdev(md->suspended_bdev);
1305         if (IS_ERR(md->frozen_sb)) {
1306                 r = PTR_ERR(md->frozen_sb);
1307                 md->frozen_sb = NULL;
1308                 return r;
1309         }
1310
1311         set_bit(DMF_FROZEN, &md->flags);
1312
1313         /* don't bdput right now, we don't want the bdev
1314          * to go away while it is locked.
1315          */
1316         return 0;
1317 }
1318
1319 static void unlock_fs(struct mapped_device *md)
1320 {
1321         if (!test_bit(DMF_FROZEN, &md->flags))
1322                 return;
1323
1324         thaw_bdev(md->suspended_bdev, md->frozen_sb);
1325         md->frozen_sb = NULL;
1326         clear_bit(DMF_FROZEN, &md->flags);
1327 }
1328
1329 /*
1330  * We need to be able to change a mapping table under a mounted
1331  * filesystem.  For example we might want to move some data in
1332  * the background.  Before the table can be swapped with
1333  * dm_bind_table, dm_suspend must be called to flush any in
1334  * flight bios and ensure that any further io gets deferred.
1335  */
1336 int dm_suspend(struct mapped_device *md, unsigned suspend_flags)
1337 {
1338         struct dm_table *map = NULL;
1339         unsigned long flags;
1340         DECLARE_WAITQUEUE(wait, current);
1341         struct bio *def;
1342         int r = -EINVAL;
1343         int do_lockfs = suspend_flags & DM_SUSPEND_LOCKFS_FLAG ? 1 : 0;
1344         int noflush = suspend_flags & DM_SUSPEND_NOFLUSH_FLAG ? 1 : 0;
1345
1346         down(&md->suspend_lock);
1347
1348         if (dm_suspended(md))
1349                 goto out_unlock;
1350
1351         map = dm_get_table(md);
1352
1353         /*
1354          * DMF_NOFLUSH_SUSPENDING must be set before presuspend.
1355          * This flag is cleared before dm_suspend returns.
1356          */
1357         if (noflush)
1358                 set_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
1359
1360         /* This does not get reverted if there's an error later. */
1361         dm_table_presuspend_targets(map);
1362
1363         /* bdget() can stall if the pending I/Os are not flushed */
1364         if (!noflush) {
1365                 md->suspended_bdev = bdget_disk(md->disk, 0);
1366                 if (!md->suspended_bdev) {
1367                         DMWARN("bdget failed in dm_suspend");
1368                         r = -ENOMEM;
1369                         goto flush_and_out;
1370                 }
1371         }
1372
1373         /*
1374          * Flush I/O to the device.
1375          * noflush supersedes do_lockfs, because lock_fs() needs to flush I/Os.
1376          */
1377         if (do_lockfs && !noflush) {
1378                 r = lock_fs(md);
1379                 if (r)
1380                         goto out;
1381         }
1382
1383         /*
1384          * First we set the BLOCK_IO flag so no more ios will be mapped.
1385          */
1386         down_write(&md->io_lock);
1387         set_bit(DMF_BLOCK_IO, &md->flags);
1388
1389         add_wait_queue(&md->wait, &wait);
1390         up_write(&md->io_lock);
1391
1392         /* unplug */
1393         if (map)
1394                 dm_table_unplug_all(map);
1395
1396         /*
1397          * Then we wait for the already mapped ios to
1398          * complete.
1399          */
1400         while (1) {
1401                 set_current_state(TASK_INTERRUPTIBLE);
1402
1403                 if (!atomic_read(&md->pending) || signal_pending(current))
1404                         break;
1405
1406                 io_schedule();
1407         }
1408         set_current_state(TASK_RUNNING);
1409
1410         down_write(&md->io_lock);
1411         remove_wait_queue(&md->wait, &wait);
1412
1413         if (noflush) {
1414                 spin_lock_irqsave(&md->pushback_lock, flags);
1415                 clear_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
1416                 bio_list_merge_head(&md->deferred, &md->pushback);
1417                 bio_list_init(&md->pushback);
1418                 spin_unlock_irqrestore(&md->pushback_lock, flags);
1419         }
1420
1421         /* were we interrupted ? */
1422         r = -EINTR;
1423         if (atomic_read(&md->pending)) {
1424                 clear_bit(DMF_BLOCK_IO, &md->flags);
1425                 def = bio_list_get(&md->deferred);
1426                 __flush_deferred_io(md, def);
1427                 up_write(&md->io_lock);
1428                 unlock_fs(md);
1429                 goto out; /* pushback list is already flushed, so skip flush */
1430         }
1431         up_write(&md->io_lock);
1432
1433         dm_table_postsuspend_targets(map);
1434
1435         set_bit(DMF_SUSPENDED, &md->flags);
1436
1437         r = 0;
1438
1439 flush_and_out:
1440         if (r && noflush) {
1441                 /*
1442                  * Because there may be already I/Os in the pushback list,
1443                  * flush them before return.
1444                  */
1445                 down_write(&md->io_lock);
1446
1447                 spin_lock_irqsave(&md->pushback_lock, flags);
1448                 clear_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
1449                 bio_list_merge_head(&md->deferred, &md->pushback);
1450                 bio_list_init(&md->pushback);
1451                 spin_unlock_irqrestore(&md->pushback_lock, flags);
1452
1453                 def = bio_list_get(&md->deferred);
1454                 __flush_deferred_io(md, def);
1455                 up_write(&md->io_lock);
1456         }
1457
1458 out:
1459         if (r && md->suspended_bdev) {
1460                 bdput(md->suspended_bdev);
1461                 md->suspended_bdev = NULL;
1462         }
1463
1464         dm_table_put(map);
1465
1466 out_unlock:
1467         up(&md->suspend_lock);
1468         return r;
1469 }
1470
1471 int dm_resume(struct mapped_device *md)
1472 {
1473         int r = -EINVAL;
1474         struct bio *def;
1475         struct dm_table *map = NULL;
1476
1477         down(&md->suspend_lock);
1478         if (!dm_suspended(md))
1479                 goto out;
1480
1481         map = dm_get_table(md);
1482         if (!map || !dm_table_get_size(map))
1483                 goto out;
1484
1485         r = dm_table_resume_targets(map);
1486         if (r)
1487                 goto out;
1488
1489         down_write(&md->io_lock);
1490         clear_bit(DMF_BLOCK_IO, &md->flags);
1491
1492         def = bio_list_get(&md->deferred);
1493         __flush_deferred_io(md, def);
1494         up_write(&md->io_lock);
1495
1496         unlock_fs(md);
1497
1498         if (md->suspended_bdev) {
1499                 bdput(md->suspended_bdev);
1500                 md->suspended_bdev = NULL;
1501         }
1502
1503         clear_bit(DMF_SUSPENDED, &md->flags);
1504
1505         dm_table_unplug_all(map);
1506
1507         kobject_uevent(&md->disk->kobj, KOBJ_CHANGE);
1508
1509         r = 0;
1510
1511 out:
1512         dm_table_put(map);
1513         up(&md->suspend_lock);
1514
1515         return r;
1516 }
1517
1518 /*-----------------------------------------------------------------
1519  * Event notification.
1520  *---------------------------------------------------------------*/
1521 uint32_t dm_get_event_nr(struct mapped_device *md)
1522 {
1523         return atomic_read(&md->event_nr);
1524 }
1525
1526 int dm_wait_event(struct mapped_device *md, int event_nr)
1527 {
1528         return wait_event_interruptible(md->eventq,
1529                         (event_nr != atomic_read(&md->event_nr)));
1530 }
1531
1532 /*
1533  * The gendisk is only valid as long as you have a reference
1534  * count on 'md'.
1535  */
1536 struct gendisk *dm_disk(struct mapped_device *md)
1537 {
1538         return md->disk;
1539 }
1540
1541 int dm_suspended(struct mapped_device *md)
1542 {
1543         return test_bit(DMF_SUSPENDED, &md->flags);
1544 }
1545
1546 int dm_noflush_suspending(struct dm_target *ti)
1547 {
1548         struct mapped_device *md = dm_table_get_md(ti->table);
1549         int r = __noflush_suspending(md);
1550
1551         dm_put(md);
1552
1553         return r;
1554 }
1555 EXPORT_SYMBOL_GPL(dm_noflush_suspending);
1556
1557 static struct block_device_operations dm_blk_dops = {
1558         .open = dm_blk_open,
1559         .release = dm_blk_close,
1560         .ioctl = dm_blk_ioctl,
1561         .getgeo = dm_blk_getgeo,
1562         .owner = THIS_MODULE
1563 };
1564
1565 EXPORT_SYMBOL(dm_get_mapinfo);
1566
1567 /*
1568  * module hooks
1569  */
1570 module_init(dm_init);
1571 module_exit(dm_exit);
1572
1573 module_param(major, uint, 0);
1574 MODULE_PARM_DESC(major, "The major number of the device mapper");
1575 MODULE_DESCRIPTION(DM_NAME " driver");
1576 MODULE_AUTHOR("Joe Thornber <dm-devel@redhat.com>");
1577 MODULE_LICENSE("GPL");