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