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