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