GNU Linux-libre 4.4.296-gnu1
[releases.git] / block / genhd.c
1 /*
2  *  gendisk handling
3  */
4
5 #include <linux/module.h>
6 #include <linux/fs.h>
7 #include <linux/genhd.h>
8 #include <linux/kdev_t.h>
9 #include <linux/kernel.h>
10 #include <linux/blkdev.h>
11 #include <linux/backing-dev.h>
12 #include <linux/init.h>
13 #include <linux/spinlock.h>
14 #include <linux/proc_fs.h>
15 #include <linux/seq_file.h>
16 #include <linux/slab.h>
17 #include <linux/kmod.h>
18 #include <linux/kobj_map.h>
19 #include <linux/mutex.h>
20 #include <linux/idr.h>
21 #include <linux/log2.h>
22 #include <linux/pm_runtime.h>
23
24 #include "blk.h"
25
26 static DEFINE_MUTEX(block_class_lock);
27 struct kobject *block_depr;
28
29 /* for extended dynamic devt allocation, currently only one major is used */
30 #define NR_EXT_DEVT             (1 << MINORBITS)
31
32 /* For extended devt allocation.  ext_devt_lock prevents look up
33  * results from going away underneath its user.
34  */
35 static DEFINE_SPINLOCK(ext_devt_lock);
36 static DEFINE_IDR(ext_devt_idr);
37
38 static struct device_type disk_type;
39
40 static void disk_check_events(struct disk_events *ev,
41                               unsigned int *clearing_ptr);
42 static void disk_alloc_events(struct gendisk *disk);
43 static void disk_add_events(struct gendisk *disk);
44 static void disk_del_events(struct gendisk *disk);
45 static void disk_release_events(struct gendisk *disk);
46
47 /**
48  * disk_get_part - get partition
49  * @disk: disk to look partition from
50  * @partno: partition number
51  *
52  * Look for partition @partno from @disk.  If found, increment
53  * reference count and return it.
54  *
55  * CONTEXT:
56  * Don't care.
57  *
58  * RETURNS:
59  * Pointer to the found partition on success, NULL if not found.
60  */
61 struct hd_struct *disk_get_part(struct gendisk *disk, int partno)
62 {
63         struct hd_struct *part = NULL;
64         struct disk_part_tbl *ptbl;
65
66         if (unlikely(partno < 0))
67                 return NULL;
68
69         rcu_read_lock();
70
71         ptbl = rcu_dereference(disk->part_tbl);
72         if (likely(partno < ptbl->len)) {
73                 part = rcu_dereference(ptbl->part[partno]);
74                 if (part)
75                         get_device(part_to_dev(part));
76         }
77
78         rcu_read_unlock();
79
80         return part;
81 }
82 EXPORT_SYMBOL_GPL(disk_get_part);
83
84 /**
85  * disk_part_iter_init - initialize partition iterator
86  * @piter: iterator to initialize
87  * @disk: disk to iterate over
88  * @flags: DISK_PITER_* flags
89  *
90  * Initialize @piter so that it iterates over partitions of @disk.
91  *
92  * CONTEXT:
93  * Don't care.
94  */
95 void disk_part_iter_init(struct disk_part_iter *piter, struct gendisk *disk,
96                           unsigned int flags)
97 {
98         struct disk_part_tbl *ptbl;
99
100         rcu_read_lock();
101         ptbl = rcu_dereference(disk->part_tbl);
102
103         piter->disk = disk;
104         piter->part = NULL;
105
106         if (flags & DISK_PITER_REVERSE)
107                 piter->idx = ptbl->len - 1;
108         else if (flags & (DISK_PITER_INCL_PART0 | DISK_PITER_INCL_EMPTY_PART0))
109                 piter->idx = 0;
110         else
111                 piter->idx = 1;
112
113         piter->flags = flags;
114
115         rcu_read_unlock();
116 }
117 EXPORT_SYMBOL_GPL(disk_part_iter_init);
118
119 /**
120  * disk_part_iter_next - proceed iterator to the next partition and return it
121  * @piter: iterator of interest
122  *
123  * Proceed @piter to the next partition and return it.
124  *
125  * CONTEXT:
126  * Don't care.
127  */
128 struct hd_struct *disk_part_iter_next(struct disk_part_iter *piter)
129 {
130         struct disk_part_tbl *ptbl;
131         int inc, end;
132
133         /* put the last partition */
134         disk_put_part(piter->part);
135         piter->part = NULL;
136
137         /* get part_tbl */
138         rcu_read_lock();
139         ptbl = rcu_dereference(piter->disk->part_tbl);
140
141         /* determine iteration parameters */
142         if (piter->flags & DISK_PITER_REVERSE) {
143                 inc = -1;
144                 if (piter->flags & (DISK_PITER_INCL_PART0 |
145                                     DISK_PITER_INCL_EMPTY_PART0))
146                         end = -1;
147                 else
148                         end = 0;
149         } else {
150                 inc = 1;
151                 end = ptbl->len;
152         }
153
154         /* iterate to the next partition */
155         for (; piter->idx != end; piter->idx += inc) {
156                 struct hd_struct *part;
157
158                 part = rcu_dereference(ptbl->part[piter->idx]);
159                 if (!part)
160                         continue;
161                 get_device(part_to_dev(part));
162                 piter->part = part;
163                 if (!part_nr_sects_read(part) &&
164                     !(piter->flags & DISK_PITER_INCL_EMPTY) &&
165                     !(piter->flags & DISK_PITER_INCL_EMPTY_PART0 &&
166                       piter->idx == 0)) {
167                         put_device(part_to_dev(part));
168                         piter->part = NULL;
169                         continue;
170                 }
171
172                 piter->idx += inc;
173                 break;
174         }
175
176         rcu_read_unlock();
177
178         return piter->part;
179 }
180 EXPORT_SYMBOL_GPL(disk_part_iter_next);
181
182 /**
183  * disk_part_iter_exit - finish up partition iteration
184  * @piter: iter of interest
185  *
186  * Called when iteration is over.  Cleans up @piter.
187  *
188  * CONTEXT:
189  * Don't care.
190  */
191 void disk_part_iter_exit(struct disk_part_iter *piter)
192 {
193         disk_put_part(piter->part);
194         piter->part = NULL;
195 }
196 EXPORT_SYMBOL_GPL(disk_part_iter_exit);
197
198 static inline int sector_in_part(struct hd_struct *part, sector_t sector)
199 {
200         return part->start_sect <= sector &&
201                 sector < part->start_sect + part_nr_sects_read(part);
202 }
203
204 /**
205  * disk_map_sector_rcu - map sector to partition
206  * @disk: gendisk of interest
207  * @sector: sector to map
208  *
209  * Find out which partition @sector maps to on @disk.  This is
210  * primarily used for stats accounting.
211  *
212  * CONTEXT:
213  * RCU read locked.  The returned partition pointer is valid only
214  * while preemption is disabled.
215  *
216  * RETURNS:
217  * Found partition on success, part0 is returned if no partition matches
218  */
219 struct hd_struct *disk_map_sector_rcu(struct gendisk *disk, sector_t sector)
220 {
221         struct disk_part_tbl *ptbl;
222         struct hd_struct *part;
223         int i;
224
225         ptbl = rcu_dereference(disk->part_tbl);
226
227         part = rcu_dereference(ptbl->last_lookup);
228         if (part && sector_in_part(part, sector))
229                 return part;
230
231         for (i = 1; i < ptbl->len; i++) {
232                 part = rcu_dereference(ptbl->part[i]);
233
234                 if (part && sector_in_part(part, sector)) {
235                         rcu_assign_pointer(ptbl->last_lookup, part);
236                         return part;
237                 }
238         }
239         return &disk->part0;
240 }
241 EXPORT_SYMBOL_GPL(disk_map_sector_rcu);
242
243 /*
244  * Can be deleted altogether. Later.
245  *
246  */
247 static struct blk_major_name {
248         struct blk_major_name *next;
249         int major;
250         char name[16];
251 } *major_names[BLKDEV_MAJOR_HASH_SIZE];
252
253 /* index in the above - for now: assume no multimajor ranges */
254 static inline int major_to_index(unsigned major)
255 {
256         return major % BLKDEV_MAJOR_HASH_SIZE;
257 }
258
259 #ifdef CONFIG_PROC_FS
260 void blkdev_show(struct seq_file *seqf, off_t offset)
261 {
262         struct blk_major_name *dp;
263
264         if (offset < BLKDEV_MAJOR_HASH_SIZE) {
265                 mutex_lock(&block_class_lock);
266                 for (dp = major_names[offset]; dp; dp = dp->next)
267                         seq_printf(seqf, "%3d %s\n", dp->major, dp->name);
268                 mutex_unlock(&block_class_lock);
269         }
270 }
271 #endif /* CONFIG_PROC_FS */
272
273 /**
274  * register_blkdev - register a new block device
275  *
276  * @major: the requested major device number [1..255]. If @major=0, try to
277  *         allocate any unused major number.
278  * @name: the name of the new block device as a zero terminated string
279  *
280  * The @name must be unique within the system.
281  *
282  * The return value depends on the @major input parameter.
283  *  - if a major device number was requested in range [1..255] then the
284  *    function returns zero on success, or a negative error code
285  *  - if any unused major number was requested with @major=0 parameter
286  *    then the return value is the allocated major number in range
287  *    [1..255] or a negative error code otherwise
288  */
289 int register_blkdev(unsigned int major, const char *name)
290 {
291         struct blk_major_name **n, *p;
292         int index, ret = 0;
293
294         mutex_lock(&block_class_lock);
295
296         /* temporary */
297         if (major == 0) {
298                 for (index = ARRAY_SIZE(major_names)-1; index > 0; index--) {
299                         if (major_names[index] == NULL)
300                                 break;
301                 }
302
303                 if (index == 0) {
304                         printk("register_blkdev: failed to get major for %s\n",
305                                name);
306                         ret = -EBUSY;
307                         goto out;
308                 }
309                 major = index;
310                 ret = major;
311         }
312
313         p = kmalloc(sizeof(struct blk_major_name), GFP_KERNEL);
314         if (p == NULL) {
315                 ret = -ENOMEM;
316                 goto out;
317         }
318
319         p->major = major;
320         strlcpy(p->name, name, sizeof(p->name));
321         p->next = NULL;
322         index = major_to_index(major);
323
324         for (n = &major_names[index]; *n; n = &(*n)->next) {
325                 if ((*n)->major == major)
326                         break;
327         }
328         if (!*n)
329                 *n = p;
330         else
331                 ret = -EBUSY;
332
333         if (ret < 0) {
334                 printk("register_blkdev: cannot get major %d for %s\n",
335                        major, name);
336                 kfree(p);
337         }
338 out:
339         mutex_unlock(&block_class_lock);
340         return ret;
341 }
342
343 EXPORT_SYMBOL(register_blkdev);
344
345 void unregister_blkdev(unsigned int major, const char *name)
346 {
347         struct blk_major_name **n;
348         struct blk_major_name *p = NULL;
349         int index = major_to_index(major);
350
351         mutex_lock(&block_class_lock);
352         for (n = &major_names[index]; *n; n = &(*n)->next)
353                 if ((*n)->major == major)
354                         break;
355         if (!*n || strcmp((*n)->name, name)) {
356                 WARN_ON(1);
357         } else {
358                 p = *n;
359                 *n = p->next;
360         }
361         mutex_unlock(&block_class_lock);
362         kfree(p);
363 }
364
365 EXPORT_SYMBOL(unregister_blkdev);
366
367 static struct kobj_map *bdev_map;
368
369 /**
370  * blk_mangle_minor - scatter minor numbers apart
371  * @minor: minor number to mangle
372  *
373  * Scatter consecutively allocated @minor number apart if MANGLE_DEVT
374  * is enabled.  Mangling twice gives the original value.
375  *
376  * RETURNS:
377  * Mangled value.
378  *
379  * CONTEXT:
380  * Don't care.
381  */
382 static int blk_mangle_minor(int minor)
383 {
384 #ifdef CONFIG_DEBUG_BLOCK_EXT_DEVT
385         int i;
386
387         for (i = 0; i < MINORBITS / 2; i++) {
388                 int low = minor & (1 << i);
389                 int high = minor & (1 << (MINORBITS - 1 - i));
390                 int distance = MINORBITS - 1 - 2 * i;
391
392                 minor ^= low | high;    /* clear both bits */
393                 low <<= distance;       /* swap the positions */
394                 high >>= distance;
395                 minor |= low | high;    /* and set */
396         }
397 #endif
398         return minor;
399 }
400
401 /**
402  * blk_alloc_devt - allocate a dev_t for a partition
403  * @part: partition to allocate dev_t for
404  * @devt: out parameter for resulting dev_t
405  *
406  * Allocate a dev_t for block device.
407  *
408  * RETURNS:
409  * 0 on success, allocated dev_t is returned in *@devt.  -errno on
410  * failure.
411  *
412  * CONTEXT:
413  * Might sleep.
414  */
415 int blk_alloc_devt(struct hd_struct *part, dev_t *devt)
416 {
417         struct gendisk *disk = part_to_disk(part);
418         int idx;
419
420         /* in consecutive minor range? */
421         if (part->partno < disk->minors) {
422                 *devt = MKDEV(disk->major, disk->first_minor + part->partno);
423                 return 0;
424         }
425
426         /* allocate ext devt */
427         idr_preload(GFP_KERNEL);
428
429         spin_lock_bh(&ext_devt_lock);
430         idx = idr_alloc(&ext_devt_idr, part, 0, NR_EXT_DEVT, GFP_NOWAIT);
431         spin_unlock_bh(&ext_devt_lock);
432
433         idr_preload_end();
434         if (idx < 0)
435                 return idx == -ENOSPC ? -EBUSY : idx;
436
437         *devt = MKDEV(BLOCK_EXT_MAJOR, blk_mangle_minor(idx));
438         return 0;
439 }
440
441 /**
442  * blk_free_devt - free a dev_t
443  * @devt: dev_t to free
444  *
445  * Free @devt which was allocated using blk_alloc_devt().
446  *
447  * CONTEXT:
448  * Might sleep.
449  */
450 void blk_free_devt(dev_t devt)
451 {
452         if (devt == MKDEV(0, 0))
453                 return;
454
455         if (MAJOR(devt) == BLOCK_EXT_MAJOR) {
456                 spin_lock_bh(&ext_devt_lock);
457                 idr_remove(&ext_devt_idr, blk_mangle_minor(MINOR(devt)));
458                 spin_unlock_bh(&ext_devt_lock);
459         }
460 }
461
462 static char *bdevt_str(dev_t devt, char *buf)
463 {
464         if (MAJOR(devt) <= 0xff && MINOR(devt) <= 0xff) {
465                 char tbuf[BDEVT_SIZE];
466                 snprintf(tbuf, BDEVT_SIZE, "%02x%02x", MAJOR(devt), MINOR(devt));
467                 snprintf(buf, BDEVT_SIZE, "%-9s", tbuf);
468         } else
469                 snprintf(buf, BDEVT_SIZE, "%03x:%05x", MAJOR(devt), MINOR(devt));
470
471         return buf;
472 }
473
474 /*
475  * Register device numbers dev..(dev+range-1)
476  * range must be nonzero
477  * The hash chain is sorted on range, so that subranges can override.
478  */
479 void blk_register_region(dev_t devt, unsigned long range, struct module *module,
480                          struct kobject *(*probe)(dev_t, int *, void *),
481                          int (*lock)(dev_t, void *), void *data)
482 {
483         kobj_map(bdev_map, devt, range, module, probe, lock, data);
484 }
485
486 EXPORT_SYMBOL(blk_register_region);
487
488 void blk_unregister_region(dev_t devt, unsigned long range)
489 {
490         kobj_unmap(bdev_map, devt, range);
491 }
492
493 EXPORT_SYMBOL(blk_unregister_region);
494
495 static struct kobject *exact_match(dev_t devt, int *partno, void *data)
496 {
497         struct gendisk *p = data;
498
499         return &disk_to_dev(p)->kobj;
500 }
501
502 static int exact_lock(dev_t devt, void *data)
503 {
504         struct gendisk *p = data;
505
506         if (!get_disk(p))
507                 return -1;
508         return 0;
509 }
510
511 static void register_disk(struct gendisk *disk)
512 {
513         struct device *ddev = disk_to_dev(disk);
514         struct block_device *bdev;
515         struct disk_part_iter piter;
516         struct hd_struct *part;
517         int err;
518
519         ddev->parent = disk->driverfs_dev;
520
521         dev_set_name(ddev, "%s", disk->disk_name);
522
523         /* delay uevents, until we scanned partition table */
524         dev_set_uevent_suppress(ddev, 1);
525
526         if (device_add(ddev))
527                 return;
528         if (!sysfs_deprecated) {
529                 err = sysfs_create_link(block_depr, &ddev->kobj,
530                                         kobject_name(&ddev->kobj));
531                 if (err) {
532                         device_del(ddev);
533                         return;
534                 }
535         }
536
537         /*
538          * avoid probable deadlock caused by allocating memory with
539          * GFP_KERNEL in runtime_resume callback of its all ancestor
540          * devices
541          */
542         pm_runtime_set_memalloc_noio(ddev, true);
543
544         disk->part0.holder_dir = kobject_create_and_add("holders", &ddev->kobj);
545         disk->slave_dir = kobject_create_and_add("slaves", &ddev->kobj);
546
547         /* No minors to use for partitions */
548         if (!disk_part_scan_enabled(disk))
549                 goto exit;
550
551         /* No such device (e.g., media were just removed) */
552         if (!get_capacity(disk))
553                 goto exit;
554
555         bdev = bdget_disk(disk, 0);
556         if (!bdev)
557                 goto exit;
558
559         bdev->bd_invalidated = 1;
560         err = blkdev_get(bdev, FMODE_READ, NULL);
561         if (err < 0)
562                 goto exit;
563         blkdev_put(bdev, FMODE_READ);
564
565 exit:
566         /* announce disk after possible partitions are created */
567         dev_set_uevent_suppress(ddev, 0);
568         kobject_uevent(&ddev->kobj, KOBJ_ADD);
569
570         /* announce possible partitions */
571         disk_part_iter_init(&piter, disk, 0);
572         while ((part = disk_part_iter_next(&piter)))
573                 kobject_uevent(&part_to_dev(part)->kobj, KOBJ_ADD);
574         disk_part_iter_exit(&piter);
575 }
576
577 /**
578  * add_disk - add partitioning information to kernel list
579  * @disk: per-device partitioning information
580  *
581  * This function registers the partitioning information in @disk
582  * with the kernel.
583  *
584  * FIXME: error handling
585  */
586 void add_disk(struct gendisk *disk)
587 {
588         struct backing_dev_info *bdi;
589         dev_t devt;
590         int retval;
591
592         /* minors == 0 indicates to use ext devt from part0 and should
593          * be accompanied with EXT_DEVT flag.  Make sure all
594          * parameters make sense.
595          */
596         WARN_ON(disk->minors && !(disk->major || disk->first_minor));
597         WARN_ON(!disk->minors && !(disk->flags & GENHD_FL_EXT_DEVT));
598
599         disk->flags |= GENHD_FL_UP;
600
601         retval = blk_alloc_devt(&disk->part0, &devt);
602         if (retval) {
603                 WARN_ON(1);
604                 return;
605         }
606         disk_to_dev(disk)->devt = devt;
607
608         /* ->major and ->first_minor aren't supposed to be
609          * dereferenced from here on, but set them just in case.
610          */
611         disk->major = MAJOR(devt);
612         disk->first_minor = MINOR(devt);
613
614         disk_alloc_events(disk);
615
616         /* Register BDI before referencing it from bdev */
617         bdi = &disk->queue->backing_dev_info;
618         bdi_register_owner(bdi, disk_to_dev(disk));
619
620         blk_register_region(disk_devt(disk), disk->minors, NULL,
621                             exact_match, exact_lock, disk);
622         register_disk(disk);
623         blk_register_queue(disk);
624
625         /*
626          * Take an extra ref on queue which will be put on disk_release()
627          * so that it sticks around as long as @disk is there.
628          */
629         WARN_ON_ONCE(!blk_get_queue(disk->queue));
630
631         retval = sysfs_create_link(&disk_to_dev(disk)->kobj, &bdi->dev->kobj,
632                                    "bdi");
633         WARN_ON(retval);
634
635         disk_add_events(disk);
636         blk_integrity_add(disk);
637 }
638 EXPORT_SYMBOL(add_disk);
639
640 void del_gendisk(struct gendisk *disk)
641 {
642         struct disk_part_iter piter;
643         struct hd_struct *part;
644
645         blk_integrity_del(disk);
646         disk_del_events(disk);
647
648         /* invalidate stuff */
649         disk_part_iter_init(&piter, disk,
650                              DISK_PITER_INCL_EMPTY | DISK_PITER_REVERSE);
651         while ((part = disk_part_iter_next(&piter))) {
652                 invalidate_partition(disk, part->partno);
653                 delete_partition(disk, part->partno);
654         }
655         disk_part_iter_exit(&piter);
656
657         invalidate_partition(disk, 0);
658         set_capacity(disk, 0);
659         disk->flags &= ~GENHD_FL_UP;
660
661         sysfs_remove_link(&disk_to_dev(disk)->kobj, "bdi");
662         blk_unregister_queue(disk);
663         blk_unregister_region(disk_devt(disk), disk->minors);
664
665         part_stat_set_all(&disk->part0, 0);
666         disk->part0.stamp = 0;
667
668         kobject_put(disk->part0.holder_dir);
669         kobject_put(disk->slave_dir);
670         if (!sysfs_deprecated)
671                 sysfs_remove_link(block_depr, dev_name(disk_to_dev(disk)));
672         pm_runtime_set_memalloc_noio(disk_to_dev(disk), false);
673         device_del(disk_to_dev(disk));
674 }
675 EXPORT_SYMBOL(del_gendisk);
676
677 /**
678  * get_gendisk - get partitioning information for a given device
679  * @devt: device to get partitioning information for
680  * @partno: returned partition index
681  *
682  * This function gets the structure containing partitioning
683  * information for the given device @devt.
684  */
685 struct gendisk *get_gendisk(dev_t devt, int *partno)
686 {
687         struct gendisk *disk = NULL;
688
689         if (MAJOR(devt) != BLOCK_EXT_MAJOR) {
690                 struct kobject *kobj;
691
692                 kobj = kobj_lookup(bdev_map, devt, partno);
693                 if (kobj)
694                         disk = dev_to_disk(kobj_to_dev(kobj));
695         } else {
696                 struct hd_struct *part;
697
698                 spin_lock_bh(&ext_devt_lock);
699                 part = idr_find(&ext_devt_idr, blk_mangle_minor(MINOR(devt)));
700                 if (part && get_disk(part_to_disk(part))) {
701                         *partno = part->partno;
702                         disk = part_to_disk(part);
703                 }
704                 spin_unlock_bh(&ext_devt_lock);
705         }
706
707         return disk;
708 }
709 EXPORT_SYMBOL(get_gendisk);
710
711 /**
712  * bdget_disk - do bdget() by gendisk and partition number
713  * @disk: gendisk of interest
714  * @partno: partition number
715  *
716  * Find partition @partno from @disk, do bdget() on it.
717  *
718  * CONTEXT:
719  * Don't care.
720  *
721  * RETURNS:
722  * Resulting block_device on success, NULL on failure.
723  */
724 struct block_device *bdget_disk(struct gendisk *disk, int partno)
725 {
726         struct hd_struct *part;
727         struct block_device *bdev = NULL;
728
729         part = disk_get_part(disk, partno);
730         if (part)
731                 bdev = bdget(part_devt(part));
732         disk_put_part(part);
733
734         return bdev;
735 }
736 EXPORT_SYMBOL(bdget_disk);
737
738 /*
739  * print a full list of all partitions - intended for places where the root
740  * filesystem can't be mounted and thus to give the victim some idea of what
741  * went wrong
742  */
743 void __init printk_all_partitions(void)
744 {
745         struct class_dev_iter iter;
746         struct device *dev;
747
748         class_dev_iter_init(&iter, &block_class, NULL, &disk_type);
749         while ((dev = class_dev_iter_next(&iter))) {
750                 struct gendisk *disk = dev_to_disk(dev);
751                 struct disk_part_iter piter;
752                 struct hd_struct *part;
753                 char name_buf[BDEVNAME_SIZE];
754                 char devt_buf[BDEVT_SIZE];
755
756                 /*
757                  * Don't show empty devices or things that have been
758                  * suppressed
759                  */
760                 if (get_capacity(disk) == 0 ||
761                     (disk->flags & GENHD_FL_SUPPRESS_PARTITION_INFO))
762                         continue;
763
764                 /*
765                  * Note, unlike /proc/partitions, I am showing the
766                  * numbers in hex - the same format as the root=
767                  * option takes.
768                  */
769                 disk_part_iter_init(&piter, disk, DISK_PITER_INCL_PART0);
770                 while ((part = disk_part_iter_next(&piter))) {
771                         bool is_part0 = part == &disk->part0;
772
773                         printk("%s%s %10llu %s %s", is_part0 ? "" : "  ",
774                                bdevt_str(part_devt(part), devt_buf),
775                                (unsigned long long)part_nr_sects_read(part) >> 1
776                                , disk_name(disk, part->partno, name_buf),
777                                part->info ? part->info->uuid : "");
778                         if (is_part0) {
779                                 if (disk->driverfs_dev != NULL &&
780                                     disk->driverfs_dev->driver != NULL)
781                                         printk(" driver: %s\n",
782                                               disk->driverfs_dev->driver->name);
783                                 else
784                                         printk(" (driver?)\n");
785                         } else
786                                 printk("\n");
787                 }
788                 disk_part_iter_exit(&piter);
789         }
790         class_dev_iter_exit(&iter);
791 }
792
793 #ifdef CONFIG_PROC_FS
794 /* iterator */
795 static void *disk_seqf_start(struct seq_file *seqf, loff_t *pos)
796 {
797         loff_t skip = *pos;
798         struct class_dev_iter *iter;
799         struct device *dev;
800
801         iter = kmalloc(sizeof(*iter), GFP_KERNEL);
802         if (!iter)
803                 return ERR_PTR(-ENOMEM);
804
805         seqf->private = iter;
806         class_dev_iter_init(iter, &block_class, NULL, &disk_type);
807         do {
808                 dev = class_dev_iter_next(iter);
809                 if (!dev)
810                         return NULL;
811         } while (skip--);
812
813         return dev_to_disk(dev);
814 }
815
816 static void *disk_seqf_next(struct seq_file *seqf, void *v, loff_t *pos)
817 {
818         struct device *dev;
819
820         (*pos)++;
821         dev = class_dev_iter_next(seqf->private);
822         if (dev)
823                 return dev_to_disk(dev);
824
825         return NULL;
826 }
827
828 static void disk_seqf_stop(struct seq_file *seqf, void *v)
829 {
830         struct class_dev_iter *iter = seqf->private;
831
832         /* stop is called even after start failed :-( */
833         if (iter) {
834                 class_dev_iter_exit(iter);
835                 kfree(iter);
836                 seqf->private = NULL;
837         }
838 }
839
840 static void *show_partition_start(struct seq_file *seqf, loff_t *pos)
841 {
842         void *p;
843
844         p = disk_seqf_start(seqf, pos);
845         if (!IS_ERR_OR_NULL(p) && !*pos)
846                 seq_puts(seqf, "major minor  #blocks  name\n\n");
847         return p;
848 }
849
850 static int show_partition(struct seq_file *seqf, void *v)
851 {
852         struct gendisk *sgp = v;
853         struct disk_part_iter piter;
854         struct hd_struct *part;
855         char buf[BDEVNAME_SIZE];
856
857         /* Don't show non-partitionable removeable devices or empty devices */
858         if (!get_capacity(sgp) || (!disk_max_parts(sgp) &&
859                                    (sgp->flags & GENHD_FL_REMOVABLE)))
860                 return 0;
861         if (sgp->flags & GENHD_FL_SUPPRESS_PARTITION_INFO)
862                 return 0;
863
864         /* show the full disk and all non-0 size partitions of it */
865         disk_part_iter_init(&piter, sgp, DISK_PITER_INCL_PART0);
866         while ((part = disk_part_iter_next(&piter)))
867                 seq_printf(seqf, "%4d  %7d %10llu %s\n",
868                            MAJOR(part_devt(part)), MINOR(part_devt(part)),
869                            (unsigned long long)part_nr_sects_read(part) >> 1,
870                            disk_name(sgp, part->partno, buf));
871         disk_part_iter_exit(&piter);
872
873         return 0;
874 }
875
876 static const struct seq_operations partitions_op = {
877         .start  = show_partition_start,
878         .next   = disk_seqf_next,
879         .stop   = disk_seqf_stop,
880         .show   = show_partition
881 };
882
883 static int partitions_open(struct inode *inode, struct file *file)
884 {
885         return seq_open(file, &partitions_op);
886 }
887
888 static const struct file_operations proc_partitions_operations = {
889         .open           = partitions_open,
890         .read           = seq_read,
891         .llseek         = seq_lseek,
892         .release        = seq_release,
893 };
894 #endif
895
896
897 static struct kobject *base_probe(dev_t devt, int *partno, void *data)
898 {
899         if (request_module("block-major-%d-%d", MAJOR(devt), MINOR(devt)) > 0)
900                 /* Make old-style 2.4 aliases work */
901                 request_module("block-major-%d", MAJOR(devt));
902         return NULL;
903 }
904
905 static int __init genhd_device_init(void)
906 {
907         int error;
908
909         block_class.dev_kobj = sysfs_dev_block_kobj;
910         error = class_register(&block_class);
911         if (unlikely(error))
912                 return error;
913         bdev_map = kobj_map_init(base_probe, &block_class_lock);
914         blk_dev_init();
915
916         register_blkdev(BLOCK_EXT_MAJOR, "blkext");
917
918         /* create top-level block dir */
919         if (!sysfs_deprecated)
920                 block_depr = kobject_create_and_add("block", NULL);
921         return 0;
922 }
923
924 subsys_initcall(genhd_device_init);
925
926 static ssize_t disk_range_show(struct device *dev,
927                                struct device_attribute *attr, char *buf)
928 {
929         struct gendisk *disk = dev_to_disk(dev);
930
931         return sprintf(buf, "%d\n", disk->minors);
932 }
933
934 static ssize_t disk_ext_range_show(struct device *dev,
935                                    struct device_attribute *attr, char *buf)
936 {
937         struct gendisk *disk = dev_to_disk(dev);
938
939         return sprintf(buf, "%d\n", disk_max_parts(disk));
940 }
941
942 static ssize_t disk_removable_show(struct device *dev,
943                                    struct device_attribute *attr, char *buf)
944 {
945         struct gendisk *disk = dev_to_disk(dev);
946
947         return sprintf(buf, "%d\n",
948                        (disk->flags & GENHD_FL_REMOVABLE ? 1 : 0));
949 }
950
951 static ssize_t disk_ro_show(struct device *dev,
952                                    struct device_attribute *attr, char *buf)
953 {
954         struct gendisk *disk = dev_to_disk(dev);
955
956         return sprintf(buf, "%d\n", get_disk_ro(disk) ? 1 : 0);
957 }
958
959 static ssize_t disk_capability_show(struct device *dev,
960                                     struct device_attribute *attr, char *buf)
961 {
962         struct gendisk *disk = dev_to_disk(dev);
963
964         return sprintf(buf, "%x\n", disk->flags);
965 }
966
967 static ssize_t disk_alignment_offset_show(struct device *dev,
968                                           struct device_attribute *attr,
969                                           char *buf)
970 {
971         struct gendisk *disk = dev_to_disk(dev);
972
973         return sprintf(buf, "%d\n", queue_alignment_offset(disk->queue));
974 }
975
976 static ssize_t disk_discard_alignment_show(struct device *dev,
977                                            struct device_attribute *attr,
978                                            char *buf)
979 {
980         struct gendisk *disk = dev_to_disk(dev);
981
982         return sprintf(buf, "%d\n", queue_discard_alignment(disk->queue));
983 }
984
985 static DEVICE_ATTR(range, S_IRUGO, disk_range_show, NULL);
986 static DEVICE_ATTR(ext_range, S_IRUGO, disk_ext_range_show, NULL);
987 static DEVICE_ATTR(removable, S_IRUGO, disk_removable_show, NULL);
988 static DEVICE_ATTR(ro, S_IRUGO, disk_ro_show, NULL);
989 static DEVICE_ATTR(size, S_IRUGO, part_size_show, NULL);
990 static DEVICE_ATTR(alignment_offset, S_IRUGO, disk_alignment_offset_show, NULL);
991 static DEVICE_ATTR(discard_alignment, S_IRUGO, disk_discard_alignment_show,
992                    NULL);
993 static DEVICE_ATTR(capability, S_IRUGO, disk_capability_show, NULL);
994 static DEVICE_ATTR(stat, S_IRUGO, part_stat_show, NULL);
995 static DEVICE_ATTR(inflight, S_IRUGO, part_inflight_show, NULL);
996 #ifdef CONFIG_FAIL_MAKE_REQUEST
997 static struct device_attribute dev_attr_fail =
998         __ATTR(make-it-fail, S_IRUGO|S_IWUSR, part_fail_show, part_fail_store);
999 #endif
1000 #ifdef CONFIG_FAIL_IO_TIMEOUT
1001 static struct device_attribute dev_attr_fail_timeout =
1002         __ATTR(io-timeout-fail,  S_IRUGO|S_IWUSR, part_timeout_show,
1003                 part_timeout_store);
1004 #endif
1005
1006 static struct attribute *disk_attrs[] = {
1007         &dev_attr_range.attr,
1008         &dev_attr_ext_range.attr,
1009         &dev_attr_removable.attr,
1010         &dev_attr_ro.attr,
1011         &dev_attr_size.attr,
1012         &dev_attr_alignment_offset.attr,
1013         &dev_attr_discard_alignment.attr,
1014         &dev_attr_capability.attr,
1015         &dev_attr_stat.attr,
1016         &dev_attr_inflight.attr,
1017 #ifdef CONFIG_FAIL_MAKE_REQUEST
1018         &dev_attr_fail.attr,
1019 #endif
1020 #ifdef CONFIG_FAIL_IO_TIMEOUT
1021         &dev_attr_fail_timeout.attr,
1022 #endif
1023         NULL
1024 };
1025
1026 static struct attribute_group disk_attr_group = {
1027         .attrs = disk_attrs,
1028 };
1029
1030 static const struct attribute_group *disk_attr_groups[] = {
1031         &disk_attr_group,
1032         NULL
1033 };
1034
1035 /**
1036  * disk_replace_part_tbl - replace disk->part_tbl in RCU-safe way
1037  * @disk: disk to replace part_tbl for
1038  * @new_ptbl: new part_tbl to install
1039  *
1040  * Replace disk->part_tbl with @new_ptbl in RCU-safe way.  The
1041  * original ptbl is freed using RCU callback.
1042  *
1043  * LOCKING:
1044  * Matching bd_mutx locked.
1045  */
1046 static void disk_replace_part_tbl(struct gendisk *disk,
1047                                   struct disk_part_tbl *new_ptbl)
1048 {
1049         struct disk_part_tbl *old_ptbl = disk->part_tbl;
1050
1051         rcu_assign_pointer(disk->part_tbl, new_ptbl);
1052
1053         if (old_ptbl) {
1054                 rcu_assign_pointer(old_ptbl->last_lookup, NULL);
1055                 kfree_rcu(old_ptbl, rcu_head);
1056         }
1057 }
1058
1059 /**
1060  * disk_expand_part_tbl - expand disk->part_tbl
1061  * @disk: disk to expand part_tbl for
1062  * @partno: expand such that this partno can fit in
1063  *
1064  * Expand disk->part_tbl such that @partno can fit in.  disk->part_tbl
1065  * uses RCU to allow unlocked dereferencing for stats and other stuff.
1066  *
1067  * LOCKING:
1068  * Matching bd_mutex locked, might sleep.
1069  *
1070  * RETURNS:
1071  * 0 on success, -errno on failure.
1072  */
1073 int disk_expand_part_tbl(struct gendisk *disk, int partno)
1074 {
1075         struct disk_part_tbl *old_ptbl = disk->part_tbl;
1076         struct disk_part_tbl *new_ptbl;
1077         int len = old_ptbl ? old_ptbl->len : 0;
1078         int i, target;
1079         size_t size;
1080
1081         /*
1082          * check for int overflow, since we can get here from blkpg_ioctl()
1083          * with a user passed 'partno'.
1084          */
1085         target = partno + 1;
1086         if (target < 0)
1087                 return -EINVAL;
1088
1089         /* disk_max_parts() is zero during initialization, ignore if so */
1090         if (disk_max_parts(disk) && target > disk_max_parts(disk))
1091                 return -EINVAL;
1092
1093         if (target <= len)
1094                 return 0;
1095
1096         size = sizeof(*new_ptbl) + target * sizeof(new_ptbl->part[0]);
1097         new_ptbl = kzalloc_node(size, GFP_KERNEL, disk->node_id);
1098         if (!new_ptbl)
1099                 return -ENOMEM;
1100
1101         new_ptbl->len = target;
1102
1103         for (i = 0; i < len; i++)
1104                 rcu_assign_pointer(new_ptbl->part[i], old_ptbl->part[i]);
1105
1106         disk_replace_part_tbl(disk, new_ptbl);
1107         return 0;
1108 }
1109
1110 static void disk_release(struct device *dev)
1111 {
1112         struct gendisk *disk = dev_to_disk(dev);
1113
1114         blk_free_devt(dev->devt);
1115         disk_release_events(disk);
1116         kfree(disk->random);
1117         disk_replace_part_tbl(disk, NULL);
1118         hd_free_part(&disk->part0);
1119         if (disk->queue)
1120                 blk_put_queue(disk->queue);
1121         kfree(disk);
1122 }
1123 struct class block_class = {
1124         .name           = "block",
1125 };
1126
1127 static char *block_devnode(struct device *dev, umode_t *mode,
1128                            kuid_t *uid, kgid_t *gid)
1129 {
1130         struct gendisk *disk = dev_to_disk(dev);
1131
1132         if (disk->devnode)
1133                 return disk->devnode(disk, mode);
1134         return NULL;
1135 }
1136
1137 static struct device_type disk_type = {
1138         .name           = "disk",
1139         .groups         = disk_attr_groups,
1140         .release        = disk_release,
1141         .devnode        = block_devnode,
1142 };
1143
1144 #ifdef CONFIG_PROC_FS
1145 /*
1146  * aggregate disk stat collector.  Uses the same stats that the sysfs
1147  * entries do, above, but makes them available through one seq_file.
1148  *
1149  * The output looks suspiciously like /proc/partitions with a bunch of
1150  * extra fields.
1151  */
1152 static int diskstats_show(struct seq_file *seqf, void *v)
1153 {
1154         struct gendisk *gp = v;
1155         struct disk_part_iter piter;
1156         struct hd_struct *hd;
1157         char buf[BDEVNAME_SIZE];
1158         int cpu;
1159
1160         /*
1161         if (&disk_to_dev(gp)->kobj.entry == block_class.devices.next)
1162                 seq_puts(seqf,  "major minor name"
1163                                 "     rio rmerge rsect ruse wio wmerge "
1164                                 "wsect wuse running use aveq"
1165                                 "\n\n");
1166         */
1167
1168         disk_part_iter_init(&piter, gp, DISK_PITER_INCL_EMPTY_PART0);
1169         while ((hd = disk_part_iter_next(&piter))) {
1170                 cpu = part_stat_lock();
1171                 part_round_stats(cpu, hd);
1172                 part_stat_unlock();
1173                 seq_printf(seqf, "%4d %7d %s %lu %lu %lu "
1174                            "%u %lu %lu %lu %u %u %u %u\n",
1175                            MAJOR(part_devt(hd)), MINOR(part_devt(hd)),
1176                            disk_name(gp, hd->partno, buf),
1177                            part_stat_read(hd, ios[READ]),
1178                            part_stat_read(hd, merges[READ]),
1179                            part_stat_read(hd, sectors[READ]),
1180                            jiffies_to_msecs(part_stat_read(hd, ticks[READ])),
1181                            part_stat_read(hd, ios[WRITE]),
1182                            part_stat_read(hd, merges[WRITE]),
1183                            part_stat_read(hd, sectors[WRITE]),
1184                            jiffies_to_msecs(part_stat_read(hd, ticks[WRITE])),
1185                            part_in_flight(hd),
1186                            jiffies_to_msecs(part_stat_read(hd, io_ticks)),
1187                            jiffies_to_msecs(part_stat_read(hd, time_in_queue))
1188                         );
1189         }
1190         disk_part_iter_exit(&piter);
1191
1192         return 0;
1193 }
1194
1195 static const struct seq_operations diskstats_op = {
1196         .start  = disk_seqf_start,
1197         .next   = disk_seqf_next,
1198         .stop   = disk_seqf_stop,
1199         .show   = diskstats_show
1200 };
1201
1202 static int diskstats_open(struct inode *inode, struct file *file)
1203 {
1204         return seq_open(file, &diskstats_op);
1205 }
1206
1207 static const struct file_operations proc_diskstats_operations = {
1208         .open           = diskstats_open,
1209         .read           = seq_read,
1210         .llseek         = seq_lseek,
1211         .release        = seq_release,
1212 };
1213
1214 static int __init proc_genhd_init(void)
1215 {
1216         proc_create("diskstats", 0, NULL, &proc_diskstats_operations);
1217         proc_create("partitions", 0, NULL, &proc_partitions_operations);
1218         return 0;
1219 }
1220 module_init(proc_genhd_init);
1221 #endif /* CONFIG_PROC_FS */
1222
1223 dev_t blk_lookup_devt(const char *name, int partno)
1224 {
1225         dev_t devt = MKDEV(0, 0);
1226         struct class_dev_iter iter;
1227         struct device *dev;
1228
1229         class_dev_iter_init(&iter, &block_class, NULL, &disk_type);
1230         while ((dev = class_dev_iter_next(&iter))) {
1231                 struct gendisk *disk = dev_to_disk(dev);
1232                 struct hd_struct *part;
1233
1234                 if (strcmp(dev_name(dev), name))
1235                         continue;
1236
1237                 if (partno < disk->minors) {
1238                         /* We need to return the right devno, even
1239                          * if the partition doesn't exist yet.
1240                          */
1241                         devt = MKDEV(MAJOR(dev->devt),
1242                                      MINOR(dev->devt) + partno);
1243                         break;
1244                 }
1245                 part = disk_get_part(disk, partno);
1246                 if (part) {
1247                         devt = part_devt(part);
1248                         disk_put_part(part);
1249                         break;
1250                 }
1251                 disk_put_part(part);
1252         }
1253         class_dev_iter_exit(&iter);
1254         return devt;
1255 }
1256 EXPORT_SYMBOL(blk_lookup_devt);
1257
1258 struct gendisk *alloc_disk(int minors)
1259 {
1260         return alloc_disk_node(minors, NUMA_NO_NODE);
1261 }
1262 EXPORT_SYMBOL(alloc_disk);
1263
1264 struct gendisk *alloc_disk_node(int minors, int node_id)
1265 {
1266         struct gendisk *disk;
1267
1268         disk = kzalloc_node(sizeof(struct gendisk), GFP_KERNEL, node_id);
1269         if (disk) {
1270                 if (!init_part_stats(&disk->part0)) {
1271                         kfree(disk);
1272                         return NULL;
1273                 }
1274                 disk->node_id = node_id;
1275                 if (disk_expand_part_tbl(disk, 0)) {
1276                         free_part_stats(&disk->part0);
1277                         kfree(disk);
1278                         return NULL;
1279                 }
1280                 disk->part_tbl->part[0] = &disk->part0;
1281
1282                 /*
1283                  * set_capacity() and get_capacity() currently don't use
1284                  * seqcounter to read/update the part0->nr_sects. Still init
1285                  * the counter as we can read the sectors in IO submission
1286                  * patch using seqence counters.
1287                  *
1288                  * TODO: Ideally set_capacity() and get_capacity() should be
1289                  * converted to make use of bd_mutex and sequence counters.
1290                  */
1291                 seqcount_init(&disk->part0.nr_sects_seq);
1292                 if (hd_ref_init(&disk->part0)) {
1293                         hd_free_part(&disk->part0);
1294                         kfree(disk);
1295                         return NULL;
1296                 }
1297
1298                 disk->minors = minors;
1299                 rand_initialize_disk(disk);
1300                 disk_to_dev(disk)->class = &block_class;
1301                 disk_to_dev(disk)->type = &disk_type;
1302                 device_initialize(disk_to_dev(disk));
1303         }
1304         return disk;
1305 }
1306 EXPORT_SYMBOL(alloc_disk_node);
1307
1308 struct kobject *get_disk(struct gendisk *disk)
1309 {
1310         struct module *owner;
1311         struct kobject *kobj;
1312
1313         if (!disk->fops)
1314                 return NULL;
1315         owner = disk->fops->owner;
1316         if (owner && !try_module_get(owner))
1317                 return NULL;
1318         kobj = kobject_get(&disk_to_dev(disk)->kobj);
1319         if (kobj == NULL) {
1320                 module_put(owner);
1321                 return NULL;
1322         }
1323         return kobj;
1324
1325 }
1326
1327 EXPORT_SYMBOL(get_disk);
1328
1329 void put_disk(struct gendisk *disk)
1330 {
1331         if (disk)
1332                 kobject_put(&disk_to_dev(disk)->kobj);
1333 }
1334
1335 EXPORT_SYMBOL(put_disk);
1336
1337 static void set_disk_ro_uevent(struct gendisk *gd, int ro)
1338 {
1339         char event[] = "DISK_RO=1";
1340         char *envp[] = { event, NULL };
1341
1342         if (!ro)
1343                 event[8] = '0';
1344         kobject_uevent_env(&disk_to_dev(gd)->kobj, KOBJ_CHANGE, envp);
1345 }
1346
1347 void set_device_ro(struct block_device *bdev, int flag)
1348 {
1349         bdev->bd_part->policy = flag;
1350 }
1351
1352 EXPORT_SYMBOL(set_device_ro);
1353
1354 void set_disk_ro(struct gendisk *disk, int flag)
1355 {
1356         struct disk_part_iter piter;
1357         struct hd_struct *part;
1358
1359         if (disk->part0.policy != flag) {
1360                 set_disk_ro_uevent(disk, flag);
1361                 disk->part0.policy = flag;
1362         }
1363
1364         disk_part_iter_init(&piter, disk, DISK_PITER_INCL_EMPTY);
1365         while ((part = disk_part_iter_next(&piter)))
1366                 part->policy = flag;
1367         disk_part_iter_exit(&piter);
1368 }
1369
1370 EXPORT_SYMBOL(set_disk_ro);
1371
1372 int bdev_read_only(struct block_device *bdev)
1373 {
1374         if (!bdev)
1375                 return 0;
1376         return bdev->bd_part->policy;
1377 }
1378
1379 EXPORT_SYMBOL(bdev_read_only);
1380
1381 int invalidate_partition(struct gendisk *disk, int partno)
1382 {
1383         int res = 0;
1384         struct block_device *bdev = bdget_disk(disk, partno);
1385         if (bdev) {
1386                 fsync_bdev(bdev);
1387                 res = __invalidate_device(bdev, true);
1388                 bdput(bdev);
1389         }
1390         return res;
1391 }
1392
1393 EXPORT_SYMBOL(invalidate_partition);
1394
1395 /*
1396  * Disk events - monitor disk events like media change and eject request.
1397  */
1398 struct disk_events {
1399         struct list_head        node;           /* all disk_event's */
1400         struct gendisk          *disk;          /* the associated disk */
1401         spinlock_t              lock;
1402
1403         struct mutex            block_mutex;    /* protects blocking */
1404         int                     block;          /* event blocking depth */
1405         unsigned int            pending;        /* events already sent out */
1406         unsigned int            clearing;       /* events being cleared */
1407
1408         long                    poll_msecs;     /* interval, -1 for default */
1409         struct delayed_work     dwork;
1410 };
1411
1412 static const char *disk_events_strs[] = {
1413         [ilog2(DISK_EVENT_MEDIA_CHANGE)]        = "media_change",
1414         [ilog2(DISK_EVENT_EJECT_REQUEST)]       = "eject_request",
1415 };
1416
1417 static char *disk_uevents[] = {
1418         [ilog2(DISK_EVENT_MEDIA_CHANGE)]        = "DISK_MEDIA_CHANGE=1",
1419         [ilog2(DISK_EVENT_EJECT_REQUEST)]       = "DISK_EJECT_REQUEST=1",
1420 };
1421
1422 /* list of all disk_events */
1423 static DEFINE_MUTEX(disk_events_mutex);
1424 static LIST_HEAD(disk_events);
1425
1426 /* disable in-kernel polling by default */
1427 static unsigned long disk_events_dfl_poll_msecs = 0;
1428
1429 static unsigned long disk_events_poll_jiffies(struct gendisk *disk)
1430 {
1431         struct disk_events *ev = disk->ev;
1432         long intv_msecs = 0;
1433
1434         /*
1435          * If device-specific poll interval is set, always use it.  If
1436          * the default is being used, poll iff there are events which
1437          * can't be monitored asynchronously.
1438          */
1439         if (ev->poll_msecs >= 0)
1440                 intv_msecs = ev->poll_msecs;
1441         else if (disk->events & ~disk->async_events)
1442                 intv_msecs = disk_events_dfl_poll_msecs;
1443
1444         return msecs_to_jiffies(intv_msecs);
1445 }
1446
1447 /**
1448  * disk_block_events - block and flush disk event checking
1449  * @disk: disk to block events for
1450  *
1451  * On return from this function, it is guaranteed that event checking
1452  * isn't in progress and won't happen until unblocked by
1453  * disk_unblock_events().  Events blocking is counted and the actual
1454  * unblocking happens after the matching number of unblocks are done.
1455  *
1456  * Note that this intentionally does not block event checking from
1457  * disk_clear_events().
1458  *
1459  * CONTEXT:
1460  * Might sleep.
1461  */
1462 void disk_block_events(struct gendisk *disk)
1463 {
1464         struct disk_events *ev = disk->ev;
1465         unsigned long flags;
1466         bool cancel;
1467
1468         if (!ev)
1469                 return;
1470
1471         /*
1472          * Outer mutex ensures that the first blocker completes canceling
1473          * the event work before further blockers are allowed to finish.
1474          */
1475         mutex_lock(&ev->block_mutex);
1476
1477         spin_lock_irqsave(&ev->lock, flags);
1478         cancel = !ev->block++;
1479         spin_unlock_irqrestore(&ev->lock, flags);
1480
1481         if (cancel)
1482                 cancel_delayed_work_sync(&disk->ev->dwork);
1483
1484         mutex_unlock(&ev->block_mutex);
1485 }
1486
1487 static void __disk_unblock_events(struct gendisk *disk, bool check_now)
1488 {
1489         struct disk_events *ev = disk->ev;
1490         unsigned long intv;
1491         unsigned long flags;
1492
1493         spin_lock_irqsave(&ev->lock, flags);
1494
1495         if (WARN_ON_ONCE(ev->block <= 0))
1496                 goto out_unlock;
1497
1498         if (--ev->block)
1499                 goto out_unlock;
1500
1501         /*
1502          * Not exactly a latency critical operation, set poll timer
1503          * slack to 25% and kick event check.
1504          */
1505         intv = disk_events_poll_jiffies(disk);
1506         set_timer_slack(&ev->dwork.timer, intv / 4);
1507         if (check_now)
1508                 queue_delayed_work(system_freezable_power_efficient_wq,
1509                                 &ev->dwork, 0);
1510         else if (intv)
1511                 queue_delayed_work(system_freezable_power_efficient_wq,
1512                                 &ev->dwork, intv);
1513 out_unlock:
1514         spin_unlock_irqrestore(&ev->lock, flags);
1515 }
1516
1517 /**
1518  * disk_unblock_events - unblock disk event checking
1519  * @disk: disk to unblock events for
1520  *
1521  * Undo disk_block_events().  When the block count reaches zero, it
1522  * starts events polling if configured.
1523  *
1524  * CONTEXT:
1525  * Don't care.  Safe to call from irq context.
1526  */
1527 void disk_unblock_events(struct gendisk *disk)
1528 {
1529         if (disk->ev)
1530                 __disk_unblock_events(disk, false);
1531 }
1532
1533 /**
1534  * disk_flush_events - schedule immediate event checking and flushing
1535  * @disk: disk to check and flush events for
1536  * @mask: events to flush
1537  *
1538  * Schedule immediate event checking on @disk if not blocked.  Events in
1539  * @mask are scheduled to be cleared from the driver.  Note that this
1540  * doesn't clear the events from @disk->ev.
1541  *
1542  * CONTEXT:
1543  * If @mask is non-zero must be called with bdev->bd_mutex held.
1544  */
1545 void disk_flush_events(struct gendisk *disk, unsigned int mask)
1546 {
1547         struct disk_events *ev = disk->ev;
1548
1549         if (!ev)
1550                 return;
1551
1552         spin_lock_irq(&ev->lock);
1553         ev->clearing |= mask;
1554         if (!ev->block)
1555                 mod_delayed_work(system_freezable_power_efficient_wq,
1556                                 &ev->dwork, 0);
1557         spin_unlock_irq(&ev->lock);
1558 }
1559
1560 /**
1561  * disk_clear_events - synchronously check, clear and return pending events
1562  * @disk: disk to fetch and clear events from
1563  * @mask: mask of events to be fetched and cleared
1564  *
1565  * Disk events are synchronously checked and pending events in @mask
1566  * are cleared and returned.  This ignores the block count.
1567  *
1568  * CONTEXT:
1569  * Might sleep.
1570  */
1571 unsigned int disk_clear_events(struct gendisk *disk, unsigned int mask)
1572 {
1573         const struct block_device_operations *bdops = disk->fops;
1574         struct disk_events *ev = disk->ev;
1575         unsigned int pending;
1576         unsigned int clearing = mask;
1577
1578         if (!ev) {
1579                 /* for drivers still using the old ->media_changed method */
1580                 if ((mask & DISK_EVENT_MEDIA_CHANGE) &&
1581                     bdops->media_changed && bdops->media_changed(disk))
1582                         return DISK_EVENT_MEDIA_CHANGE;
1583                 return 0;
1584         }
1585
1586         disk_block_events(disk);
1587
1588         /*
1589          * store the union of mask and ev->clearing on the stack so that the
1590          * race with disk_flush_events does not cause ambiguity (ev->clearing
1591          * can still be modified even if events are blocked).
1592          */
1593         spin_lock_irq(&ev->lock);
1594         clearing |= ev->clearing;
1595         ev->clearing = 0;
1596         spin_unlock_irq(&ev->lock);
1597
1598         disk_check_events(ev, &clearing);
1599         /*
1600          * if ev->clearing is not 0, the disk_flush_events got called in the
1601          * middle of this function, so we want to run the workfn without delay.
1602          */
1603         __disk_unblock_events(disk, ev->clearing ? true : false);
1604
1605         /* then, fetch and clear pending events */
1606         spin_lock_irq(&ev->lock);
1607         pending = ev->pending & mask;
1608         ev->pending &= ~mask;
1609         spin_unlock_irq(&ev->lock);
1610         WARN_ON_ONCE(clearing & mask);
1611
1612         return pending;
1613 }
1614
1615 /*
1616  * Separate this part out so that a different pointer for clearing_ptr can be
1617  * passed in for disk_clear_events.
1618  */
1619 static void disk_events_workfn(struct work_struct *work)
1620 {
1621         struct delayed_work *dwork = to_delayed_work(work);
1622         struct disk_events *ev = container_of(dwork, struct disk_events, dwork);
1623
1624         disk_check_events(ev, &ev->clearing);
1625 }
1626
1627 static void disk_check_events(struct disk_events *ev,
1628                               unsigned int *clearing_ptr)
1629 {
1630         struct gendisk *disk = ev->disk;
1631         char *envp[ARRAY_SIZE(disk_uevents) + 1] = { };
1632         unsigned int clearing = *clearing_ptr;
1633         unsigned int events;
1634         unsigned long intv;
1635         int nr_events = 0, i;
1636
1637         /* check events */
1638         events = disk->fops->check_events(disk, clearing);
1639
1640         /* accumulate pending events and schedule next poll if necessary */
1641         spin_lock_irq(&ev->lock);
1642
1643         events &= ~ev->pending;
1644         ev->pending |= events;
1645         *clearing_ptr &= ~clearing;
1646
1647         intv = disk_events_poll_jiffies(disk);
1648         if (!ev->block && intv)
1649                 queue_delayed_work(system_freezable_power_efficient_wq,
1650                                 &ev->dwork, intv);
1651
1652         spin_unlock_irq(&ev->lock);
1653
1654         /*
1655          * Tell userland about new events.  Only the events listed in
1656          * @disk->events are reported.  Unlisted events are processed the
1657          * same internally but never get reported to userland.
1658          */
1659         for (i = 0; i < ARRAY_SIZE(disk_uevents); i++)
1660                 if (events & disk->events & (1 << i))
1661                         envp[nr_events++] = disk_uevents[i];
1662
1663         if (nr_events)
1664                 kobject_uevent_env(&disk_to_dev(disk)->kobj, KOBJ_CHANGE, envp);
1665 }
1666
1667 /*
1668  * A disk events enabled device has the following sysfs nodes under
1669  * its /sys/block/X/ directory.
1670  *
1671  * events               : list of all supported events
1672  * events_async         : list of events which can be detected w/o polling
1673  * events_poll_msecs    : polling interval, 0: disable, -1: system default
1674  */
1675 static ssize_t __disk_events_show(unsigned int events, char *buf)
1676 {
1677         const char *delim = "";
1678         ssize_t pos = 0;
1679         int i;
1680
1681         for (i = 0; i < ARRAY_SIZE(disk_events_strs); i++)
1682                 if (events & (1 << i)) {
1683                         pos += sprintf(buf + pos, "%s%s",
1684                                        delim, disk_events_strs[i]);
1685                         delim = " ";
1686                 }
1687         if (pos)
1688                 pos += sprintf(buf + pos, "\n");
1689         return pos;
1690 }
1691
1692 static ssize_t disk_events_show(struct device *dev,
1693                                 struct device_attribute *attr, char *buf)
1694 {
1695         struct gendisk *disk = dev_to_disk(dev);
1696
1697         return __disk_events_show(disk->events, buf);
1698 }
1699
1700 static ssize_t disk_events_async_show(struct device *dev,
1701                                       struct device_attribute *attr, char *buf)
1702 {
1703         struct gendisk *disk = dev_to_disk(dev);
1704
1705         return __disk_events_show(disk->async_events, buf);
1706 }
1707
1708 static ssize_t disk_events_poll_msecs_show(struct device *dev,
1709                                            struct device_attribute *attr,
1710                                            char *buf)
1711 {
1712         struct gendisk *disk = dev_to_disk(dev);
1713
1714         return sprintf(buf, "%ld\n", disk->ev->poll_msecs);
1715 }
1716
1717 static ssize_t disk_events_poll_msecs_store(struct device *dev,
1718                                             struct device_attribute *attr,
1719                                             const char *buf, size_t count)
1720 {
1721         struct gendisk *disk = dev_to_disk(dev);
1722         long intv;
1723
1724         if (!count || !sscanf(buf, "%ld", &intv))
1725                 return -EINVAL;
1726
1727         if (intv < 0 && intv != -1)
1728                 return -EINVAL;
1729
1730         disk_block_events(disk);
1731         disk->ev->poll_msecs = intv;
1732         __disk_unblock_events(disk, true);
1733
1734         return count;
1735 }
1736
1737 static const DEVICE_ATTR(events, S_IRUGO, disk_events_show, NULL);
1738 static const DEVICE_ATTR(events_async, S_IRUGO, disk_events_async_show, NULL);
1739 static const DEVICE_ATTR(events_poll_msecs, S_IRUGO|S_IWUSR,
1740                          disk_events_poll_msecs_show,
1741                          disk_events_poll_msecs_store);
1742
1743 static const struct attribute *disk_events_attrs[] = {
1744         &dev_attr_events.attr,
1745         &dev_attr_events_async.attr,
1746         &dev_attr_events_poll_msecs.attr,
1747         NULL,
1748 };
1749
1750 /*
1751  * The default polling interval can be specified by the kernel
1752  * parameter block.events_dfl_poll_msecs which defaults to 0
1753  * (disable).  This can also be modified runtime by writing to
1754  * /sys/module/block/events_dfl_poll_msecs.
1755  */
1756 static int disk_events_set_dfl_poll_msecs(const char *val,
1757                                           const struct kernel_param *kp)
1758 {
1759         struct disk_events *ev;
1760         int ret;
1761
1762         ret = param_set_ulong(val, kp);
1763         if (ret < 0)
1764                 return ret;
1765
1766         mutex_lock(&disk_events_mutex);
1767
1768         list_for_each_entry(ev, &disk_events, node)
1769                 disk_flush_events(ev->disk, 0);
1770
1771         mutex_unlock(&disk_events_mutex);
1772
1773         return 0;
1774 }
1775
1776 static const struct kernel_param_ops disk_events_dfl_poll_msecs_param_ops = {
1777         .set    = disk_events_set_dfl_poll_msecs,
1778         .get    = param_get_ulong,
1779 };
1780
1781 #undef MODULE_PARAM_PREFIX
1782 #define MODULE_PARAM_PREFIX     "block."
1783
1784 module_param_cb(events_dfl_poll_msecs, &disk_events_dfl_poll_msecs_param_ops,
1785                 &disk_events_dfl_poll_msecs, 0644);
1786
1787 /*
1788  * disk_{alloc|add|del|release}_events - initialize and destroy disk_events.
1789  */
1790 static void disk_alloc_events(struct gendisk *disk)
1791 {
1792         struct disk_events *ev;
1793
1794         if (!disk->fops->check_events)
1795                 return;
1796
1797         ev = kzalloc(sizeof(*ev), GFP_KERNEL);
1798         if (!ev) {
1799                 pr_warn("%s: failed to initialize events\n", disk->disk_name);
1800                 return;
1801         }
1802
1803         INIT_LIST_HEAD(&ev->node);
1804         ev->disk = disk;
1805         spin_lock_init(&ev->lock);
1806         mutex_init(&ev->block_mutex);
1807         ev->block = 1;
1808         ev->poll_msecs = -1;
1809         INIT_DELAYED_WORK(&ev->dwork, disk_events_workfn);
1810
1811         disk->ev = ev;
1812 }
1813
1814 static void disk_add_events(struct gendisk *disk)
1815 {
1816         if (!disk->ev)
1817                 return;
1818
1819         /* FIXME: error handling */
1820         if (sysfs_create_files(&disk_to_dev(disk)->kobj, disk_events_attrs) < 0)
1821                 pr_warn("%s: failed to create sysfs files for events\n",
1822                         disk->disk_name);
1823
1824         mutex_lock(&disk_events_mutex);
1825         list_add_tail(&disk->ev->node, &disk_events);
1826         mutex_unlock(&disk_events_mutex);
1827
1828         /*
1829          * Block count is initialized to 1 and the following initial
1830          * unblock kicks it into action.
1831          */
1832         __disk_unblock_events(disk, true);
1833 }
1834
1835 static void disk_del_events(struct gendisk *disk)
1836 {
1837         if (!disk->ev)
1838                 return;
1839
1840         disk_block_events(disk);
1841
1842         mutex_lock(&disk_events_mutex);
1843         list_del_init(&disk->ev->node);
1844         mutex_unlock(&disk_events_mutex);
1845
1846         sysfs_remove_files(&disk_to_dev(disk)->kobj, disk_events_attrs);
1847 }
1848
1849 static void disk_release_events(struct gendisk *disk)
1850 {
1851         /* the block count should be 1 from disk_del_events() */
1852         WARN_ON_ONCE(disk->ev && disk->ev->block != 1);
1853         kfree(disk->ev);
1854 }