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