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