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