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