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