1 // SPDX-License-Identifier: GPL-2.0
6 #include <linux/module.h>
7 #include <linux/ctype.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/kobj_map.h>
21 #include <linux/mutex.h>
22 #include <linux/idr.h>
23 #include <linux/log2.h>
24 #include <linux/pm_runtime.h>
25 #include <linux/badblocks.h>
29 static DEFINE_MUTEX(block_class_lock);
30 static struct kobject *block_depr;
32 /* for extended dynamic devt allocation, currently only one major is used */
33 #define NR_EXT_DEVT (1 << MINORBITS)
35 /* For extended devt allocation. ext_devt_lock prevents look up
36 * results from going away underneath its user.
38 static DEFINE_SPINLOCK(ext_devt_lock);
39 static DEFINE_IDR(ext_devt_idr);
41 static const struct device_type disk_type;
43 static void disk_check_events(struct disk_events *ev,
44 unsigned int *clearing_ptr);
45 static void disk_alloc_events(struct gendisk *disk);
46 static void disk_add_events(struct gendisk *disk);
47 static void disk_del_events(struct gendisk *disk);
48 static void disk_release_events(struct gendisk *disk);
51 * Set disk capacity and notify if the size is not currently
52 * zero and will not be set to zero
54 void set_capacity_revalidate_and_notify(struct gendisk *disk, sector_t size,
57 sector_t capacity = get_capacity(disk);
59 set_capacity(disk, size);
62 revalidate_disk(disk);
64 if (capacity != size && capacity != 0 && size != 0) {
65 char *envp[] = { "RESIZE=1", NULL };
67 kobject_uevent_env(&disk_to_dev(disk)->kobj, KOBJ_CHANGE, envp);
71 EXPORT_SYMBOL_GPL(set_capacity_revalidate_and_notify);
74 * Format the device name of the indicated disk into the supplied buffer and
75 * return a pointer to that same buffer for convenience.
77 char *disk_name(struct gendisk *hd, int partno, char *buf)
80 snprintf(buf, BDEVNAME_SIZE, "%s", hd->disk_name);
81 else if (isdigit(hd->disk_name[strlen(hd->disk_name)-1]))
82 snprintf(buf, BDEVNAME_SIZE, "%sp%d", hd->disk_name, partno);
84 snprintf(buf, BDEVNAME_SIZE, "%s%d", hd->disk_name, partno);
89 const char *bdevname(struct block_device *bdev, char *buf)
91 return disk_name(bdev->bd_disk, bdev->bd_part->partno, buf);
93 EXPORT_SYMBOL(bdevname);
96 static void part_stat_read_all(struct hd_struct *part, struct disk_stats *stat)
100 memset(stat, 0, sizeof(struct disk_stats));
101 for_each_possible_cpu(cpu) {
102 struct disk_stats *ptr = per_cpu_ptr(part->dkstats, cpu);
105 for (group = 0; group < NR_STAT_GROUPS; group++) {
106 stat->nsecs[group] += ptr->nsecs[group];
107 stat->sectors[group] += ptr->sectors[group];
108 stat->ios[group] += ptr->ios[group];
109 stat->merges[group] += ptr->merges[group];
112 stat->io_ticks += ptr->io_ticks;
115 #else /* CONFIG_SMP */
116 static void part_stat_read_all(struct hd_struct *part, struct disk_stats *stat)
118 memcpy(stat, &part->dkstats, sizeof(struct disk_stats));
120 #endif /* CONFIG_SMP */
122 void part_inc_in_flight(struct request_queue *q, struct hd_struct *part, int rw)
127 part_stat_local_inc(part, in_flight[rw]);
129 part_stat_local_inc(&part_to_disk(part)->part0, in_flight[rw]);
132 void part_dec_in_flight(struct request_queue *q, struct hd_struct *part, int rw)
137 part_stat_local_dec(part, in_flight[rw]);
139 part_stat_local_dec(&part_to_disk(part)->part0, in_flight[rw]);
142 static unsigned int part_in_flight(struct request_queue *q,
143 struct hd_struct *part)
146 unsigned int inflight;
148 if (queue_is_mq(q)) {
149 return blk_mq_in_flight(q, part);
153 for_each_possible_cpu(cpu) {
154 inflight += part_stat_local_read_cpu(part, in_flight[0], cpu) +
155 part_stat_local_read_cpu(part, in_flight[1], cpu);
157 if ((int)inflight < 0)
163 static void part_in_flight_rw(struct request_queue *q, struct hd_struct *part,
164 unsigned int inflight[2])
168 if (queue_is_mq(q)) {
169 blk_mq_in_flight_rw(q, part, inflight);
175 for_each_possible_cpu(cpu) {
176 inflight[0] += part_stat_local_read_cpu(part, in_flight[0], cpu);
177 inflight[1] += part_stat_local_read_cpu(part, in_flight[1], cpu);
179 if ((int)inflight[0] < 0)
181 if ((int)inflight[1] < 0)
185 struct hd_struct *__disk_get_part(struct gendisk *disk, int partno)
187 struct disk_part_tbl *ptbl = rcu_dereference(disk->part_tbl);
189 if (unlikely(partno < 0 || partno >= ptbl->len))
191 return rcu_dereference(ptbl->part[partno]);
195 * disk_get_part - get partition
196 * @disk: disk to look partition from
197 * @partno: partition number
199 * Look for partition @partno from @disk. If found, increment
200 * reference count and return it.
206 * Pointer to the found partition on success, NULL if not found.
208 struct hd_struct *disk_get_part(struct gendisk *disk, int partno)
210 struct hd_struct *part;
213 part = __disk_get_part(disk, partno);
215 get_device(part_to_dev(part));
222 * disk_part_iter_init - initialize partition iterator
223 * @piter: iterator to initialize
224 * @disk: disk to iterate over
225 * @flags: DISK_PITER_* flags
227 * Initialize @piter so that it iterates over partitions of @disk.
232 void disk_part_iter_init(struct disk_part_iter *piter, struct gendisk *disk,
235 struct disk_part_tbl *ptbl;
238 ptbl = rcu_dereference(disk->part_tbl);
243 if (flags & DISK_PITER_REVERSE)
244 piter->idx = ptbl->len - 1;
245 else if (flags & (DISK_PITER_INCL_PART0 | DISK_PITER_INCL_EMPTY_PART0))
250 piter->flags = flags;
254 EXPORT_SYMBOL_GPL(disk_part_iter_init);
257 * disk_part_iter_next - proceed iterator to the next partition and return it
258 * @piter: iterator of interest
260 * Proceed @piter to the next partition and return it.
265 struct hd_struct *disk_part_iter_next(struct disk_part_iter *piter)
267 struct disk_part_tbl *ptbl;
270 /* put the last partition */
271 disk_put_part(piter->part);
276 ptbl = rcu_dereference(piter->disk->part_tbl);
278 /* determine iteration parameters */
279 if (piter->flags & DISK_PITER_REVERSE) {
281 if (piter->flags & (DISK_PITER_INCL_PART0 |
282 DISK_PITER_INCL_EMPTY_PART0))
291 /* iterate to the next partition */
292 for (; piter->idx != end; piter->idx += inc) {
293 struct hd_struct *part;
295 part = rcu_dereference(ptbl->part[piter->idx]);
298 if (!part_nr_sects_read(part) &&
299 !(piter->flags & DISK_PITER_INCL_EMPTY) &&
300 !(piter->flags & DISK_PITER_INCL_EMPTY_PART0 &&
304 get_device(part_to_dev(part));
314 EXPORT_SYMBOL_GPL(disk_part_iter_next);
317 * disk_part_iter_exit - finish up partition iteration
318 * @piter: iter of interest
320 * Called when iteration is over. Cleans up @piter.
325 void disk_part_iter_exit(struct disk_part_iter *piter)
327 disk_put_part(piter->part);
330 EXPORT_SYMBOL_GPL(disk_part_iter_exit);
332 static inline int sector_in_part(struct hd_struct *part, sector_t sector)
334 return part->start_sect <= sector &&
335 sector < part->start_sect + part_nr_sects_read(part);
339 * disk_map_sector_rcu - map sector to partition
340 * @disk: gendisk of interest
341 * @sector: sector to map
343 * Find out which partition @sector maps to on @disk. This is
344 * primarily used for stats accounting.
347 * RCU read locked. The returned partition pointer is valid only
348 * while preemption is disabled.
351 * Found partition on success, part0 is returned if no partition matches
353 struct hd_struct *disk_map_sector_rcu(struct gendisk *disk, sector_t sector)
355 struct disk_part_tbl *ptbl;
356 struct hd_struct *part;
359 ptbl = rcu_dereference(disk->part_tbl);
361 part = rcu_dereference(ptbl->last_lookup);
362 if (part && sector_in_part(part, sector))
365 for (i = 1; i < ptbl->len; i++) {
366 part = rcu_dereference(ptbl->part[i]);
368 if (part && sector_in_part(part, sector)) {
369 rcu_assign_pointer(ptbl->last_lookup, part);
377 * Can be deleted altogether. Later.
380 #define BLKDEV_MAJOR_HASH_SIZE 255
381 static struct blk_major_name {
382 struct blk_major_name *next;
385 } *major_names[BLKDEV_MAJOR_HASH_SIZE];
387 /* index in the above - for now: assume no multimajor ranges */
388 static inline int major_to_index(unsigned major)
390 return major % BLKDEV_MAJOR_HASH_SIZE;
393 #ifdef CONFIG_PROC_FS
394 void blkdev_show(struct seq_file *seqf, off_t offset)
396 struct blk_major_name *dp;
398 mutex_lock(&block_class_lock);
399 for (dp = major_names[major_to_index(offset)]; dp; dp = dp->next)
400 if (dp->major == offset)
401 seq_printf(seqf, "%3d %s\n", dp->major, dp->name);
402 mutex_unlock(&block_class_lock);
404 #endif /* CONFIG_PROC_FS */
407 * register_blkdev - register a new block device
409 * @major: the requested major device number [1..BLKDEV_MAJOR_MAX-1]. If
410 * @major = 0, try to allocate any unused major number.
411 * @name: the name of the new block device as a zero terminated string
413 * The @name must be unique within the system.
415 * The return value depends on the @major input parameter:
417 * - if a major device number was requested in range [1..BLKDEV_MAJOR_MAX-1]
418 * then the function returns zero on success, or a negative error code
419 * - if any unused major number was requested with @major = 0 parameter
420 * then the return value is the allocated major number in range
421 * [1..BLKDEV_MAJOR_MAX-1] or a negative error code otherwise
423 * See Documentation/admin-guide/devices.txt for the list of allocated
426 int register_blkdev(unsigned int major, const char *name)
428 struct blk_major_name **n, *p;
431 mutex_lock(&block_class_lock);
435 for (index = ARRAY_SIZE(major_names)-1; index > 0; index--) {
436 if (major_names[index] == NULL)
441 printk("%s: failed to get major for %s\n",
450 if (major >= BLKDEV_MAJOR_MAX) {
451 pr_err("%s: major requested (%u) is greater than the maximum (%u) for %s\n",
452 __func__, major, BLKDEV_MAJOR_MAX-1, name);
458 p = kmalloc(sizeof(struct blk_major_name), GFP_KERNEL);
465 strlcpy(p->name, name, sizeof(p->name));
467 index = major_to_index(major);
469 for (n = &major_names[index]; *n; n = &(*n)->next) {
470 if ((*n)->major == major)
479 printk("register_blkdev: cannot get major %u for %s\n",
484 mutex_unlock(&block_class_lock);
488 EXPORT_SYMBOL(register_blkdev);
490 void unregister_blkdev(unsigned int major, const char *name)
492 struct blk_major_name **n;
493 struct blk_major_name *p = NULL;
494 int index = major_to_index(major);
496 mutex_lock(&block_class_lock);
497 for (n = &major_names[index]; *n; n = &(*n)->next)
498 if ((*n)->major == major)
500 if (!*n || strcmp((*n)->name, name)) {
506 mutex_unlock(&block_class_lock);
510 EXPORT_SYMBOL(unregister_blkdev);
512 static struct kobj_map *bdev_map;
515 * blk_mangle_minor - scatter minor numbers apart
516 * @minor: minor number to mangle
518 * Scatter consecutively allocated @minor number apart if MANGLE_DEVT
519 * is enabled. Mangling twice gives the original value.
527 static int blk_mangle_minor(int minor)
529 #ifdef CONFIG_DEBUG_BLOCK_EXT_DEVT
532 for (i = 0; i < MINORBITS / 2; i++) {
533 int low = minor & (1 << i);
534 int high = minor & (1 << (MINORBITS - 1 - i));
535 int distance = MINORBITS - 1 - 2 * i;
537 minor ^= low | high; /* clear both bits */
538 low <<= distance; /* swap the positions */
540 minor |= low | high; /* and set */
547 * blk_alloc_devt - allocate a dev_t for a partition
548 * @part: partition to allocate dev_t for
549 * @devt: out parameter for resulting dev_t
551 * Allocate a dev_t for block device.
554 * 0 on success, allocated dev_t is returned in *@devt. -errno on
560 int blk_alloc_devt(struct hd_struct *part, dev_t *devt)
562 struct gendisk *disk = part_to_disk(part);
565 /* in consecutive minor range? */
566 if (part->partno < disk->minors) {
567 *devt = MKDEV(disk->major, disk->first_minor + part->partno);
571 /* allocate ext devt */
572 idr_preload(GFP_KERNEL);
574 spin_lock_bh(&ext_devt_lock);
575 idx = idr_alloc(&ext_devt_idr, part, 0, NR_EXT_DEVT, GFP_NOWAIT);
576 spin_unlock_bh(&ext_devt_lock);
580 return idx == -ENOSPC ? -EBUSY : idx;
582 *devt = MKDEV(BLOCK_EXT_MAJOR, blk_mangle_minor(idx));
587 * blk_free_devt - free a dev_t
588 * @devt: dev_t to free
590 * Free @devt which was allocated using blk_alloc_devt().
595 void blk_free_devt(dev_t devt)
597 if (devt == MKDEV(0, 0))
600 if (MAJOR(devt) == BLOCK_EXT_MAJOR) {
601 spin_lock_bh(&ext_devt_lock);
602 idr_remove(&ext_devt_idr, blk_mangle_minor(MINOR(devt)));
603 spin_unlock_bh(&ext_devt_lock);
608 * We invalidate devt by assigning NULL pointer for devt in idr.
610 void blk_invalidate_devt(dev_t devt)
612 if (MAJOR(devt) == BLOCK_EXT_MAJOR) {
613 spin_lock_bh(&ext_devt_lock);
614 idr_replace(&ext_devt_idr, NULL, blk_mangle_minor(MINOR(devt)));
615 spin_unlock_bh(&ext_devt_lock);
619 static char *bdevt_str(dev_t devt, char *buf)
621 if (MAJOR(devt) <= 0xff && MINOR(devt) <= 0xff) {
622 char tbuf[BDEVT_SIZE];
623 snprintf(tbuf, BDEVT_SIZE, "%02x%02x", MAJOR(devt), MINOR(devt));
624 snprintf(buf, BDEVT_SIZE, "%-9s", tbuf);
626 snprintf(buf, BDEVT_SIZE, "%03x:%05x", MAJOR(devt), MINOR(devt));
632 * Register device numbers dev..(dev+range-1)
633 * range must be nonzero
634 * The hash chain is sorted on range, so that subranges can override.
636 void blk_register_region(dev_t devt, unsigned long range, struct module *module,
637 struct kobject *(*probe)(dev_t, int *, void *),
638 int (*lock)(dev_t, void *), void *data)
640 kobj_map(bdev_map, devt, range, module, probe, lock, data);
643 EXPORT_SYMBOL(blk_register_region);
645 void blk_unregister_region(dev_t devt, unsigned long range)
647 kobj_unmap(bdev_map, devt, range);
650 EXPORT_SYMBOL(blk_unregister_region);
652 static struct kobject *exact_match(dev_t devt, int *partno, void *data)
654 struct gendisk *p = data;
656 return &disk_to_dev(p)->kobj;
659 static int exact_lock(dev_t devt, void *data)
661 struct gendisk *p = data;
663 if (!get_disk_and_module(p))
668 static void register_disk(struct device *parent, struct gendisk *disk,
669 const struct attribute_group **groups)
671 struct device *ddev = disk_to_dev(disk);
672 struct block_device *bdev;
673 struct disk_part_iter piter;
674 struct hd_struct *part;
677 ddev->parent = parent;
679 dev_set_name(ddev, "%s", disk->disk_name);
681 /* delay uevents, until we scanned partition table */
682 dev_set_uevent_suppress(ddev, 1);
685 WARN_ON(ddev->groups);
686 ddev->groups = groups;
688 if (device_add(ddev))
690 if (!sysfs_deprecated) {
691 err = sysfs_create_link(block_depr, &ddev->kobj,
692 kobject_name(&ddev->kobj));
700 * avoid probable deadlock caused by allocating memory with
701 * GFP_KERNEL in runtime_resume callback of its all ancestor
704 pm_runtime_set_memalloc_noio(ddev, true);
706 disk->part0.holder_dir = kobject_create_and_add("holders", &ddev->kobj);
707 disk->slave_dir = kobject_create_and_add("slaves", &ddev->kobj);
709 if (disk->flags & GENHD_FL_HIDDEN) {
710 dev_set_uevent_suppress(ddev, 0);
714 /* No minors to use for partitions */
715 if (!disk_part_scan_enabled(disk))
718 /* No such device (e.g., media were just removed) */
719 if (!get_capacity(disk))
722 bdev = bdget_disk(disk, 0);
726 bdev->bd_invalidated = 1;
727 err = blkdev_get(bdev, FMODE_READ, NULL);
730 blkdev_put(bdev, FMODE_READ);
733 /* announce disk after possible partitions are created */
734 dev_set_uevent_suppress(ddev, 0);
735 kobject_uevent(&ddev->kobj, KOBJ_ADD);
737 /* announce possible partitions */
738 disk_part_iter_init(&piter, disk, 0);
739 while ((part = disk_part_iter_next(&piter)))
740 kobject_uevent(&part_to_dev(part)->kobj, KOBJ_ADD);
741 disk_part_iter_exit(&piter);
743 if (disk->queue->backing_dev_info->dev) {
744 err = sysfs_create_link(&ddev->kobj,
745 &disk->queue->backing_dev_info->dev->kobj,
752 * __device_add_disk - add disk information to kernel list
753 * @parent: parent device for the disk
754 * @disk: per-device partitioning information
755 * @groups: Additional per-device sysfs groups
756 * @register_queue: register the queue if set to true
758 * This function registers the partitioning information in @disk
761 * FIXME: error handling
763 static void __device_add_disk(struct device *parent, struct gendisk *disk,
764 const struct attribute_group **groups,
771 * The disk queue should now be all set with enough information about
772 * the device for the elevator code to pick an adequate default
773 * elevator if one is needed, that is, for devices requesting queue
777 elevator_init_mq(disk->queue);
779 /* minors == 0 indicates to use ext devt from part0 and should
780 * be accompanied with EXT_DEVT flag. Make sure all
781 * parameters make sense.
783 WARN_ON(disk->minors && !(disk->major || disk->first_minor));
784 WARN_ON(!disk->minors &&
785 !(disk->flags & (GENHD_FL_EXT_DEVT | GENHD_FL_HIDDEN)));
787 disk->flags |= GENHD_FL_UP;
789 retval = blk_alloc_devt(&disk->part0, &devt);
794 disk->major = MAJOR(devt);
795 disk->first_minor = MINOR(devt);
797 disk_alloc_events(disk);
799 if (disk->flags & GENHD_FL_HIDDEN) {
801 * Don't let hidden disks show up in /proc/partitions,
802 * and don't bother scanning for partitions either.
804 disk->flags |= GENHD_FL_SUPPRESS_PARTITION_INFO;
805 disk->flags |= GENHD_FL_NO_PART_SCAN;
809 /* Register BDI before referencing it from bdev */
810 disk_to_dev(disk)->devt = devt;
811 ret = bdi_register_owner(disk->queue->backing_dev_info,
814 blk_register_region(disk_devt(disk), disk->minors, NULL,
815 exact_match, exact_lock, disk);
817 register_disk(parent, disk, groups);
819 blk_register_queue(disk);
822 * Take an extra ref on queue which will be put on disk_release()
823 * so that it sticks around as long as @disk is there.
825 WARN_ON_ONCE(!blk_get_queue(disk->queue));
827 disk_add_events(disk);
828 blk_integrity_add(disk);
831 void device_add_disk(struct device *parent, struct gendisk *disk,
832 const struct attribute_group **groups)
835 __device_add_disk(parent, disk, groups, true);
837 EXPORT_SYMBOL(device_add_disk);
839 void device_add_disk_no_queue_reg(struct device *parent, struct gendisk *disk)
841 __device_add_disk(parent, disk, NULL, false);
843 EXPORT_SYMBOL(device_add_disk_no_queue_reg);
845 void del_gendisk(struct gendisk *disk)
847 struct disk_part_iter piter;
848 struct hd_struct *part;
850 blk_integrity_del(disk);
851 disk_del_events(disk);
854 * Block lookups of the disk until all bdevs are unhashed and the
855 * disk is marked as dead (GENHD_FL_UP cleared).
857 down_write(&disk->lookup_sem);
858 /* invalidate stuff */
859 disk_part_iter_init(&piter, disk,
860 DISK_PITER_INCL_EMPTY | DISK_PITER_REVERSE);
861 while ((part = disk_part_iter_next(&piter))) {
862 invalidate_partition(disk, part->partno);
863 bdev_unhash_inode(part_devt(part));
864 delete_partition(disk, part->partno);
866 disk_part_iter_exit(&piter);
868 invalidate_partition(disk, 0);
869 bdev_unhash_inode(disk_devt(disk));
870 set_capacity(disk, 0);
871 disk->flags &= ~GENHD_FL_UP;
872 up_write(&disk->lookup_sem);
874 if (!(disk->flags & GENHD_FL_HIDDEN))
875 sysfs_remove_link(&disk_to_dev(disk)->kobj, "bdi");
878 * Unregister bdi before releasing device numbers (as they can
879 * get reused and we'd get clashes in sysfs).
881 if (!(disk->flags & GENHD_FL_HIDDEN))
882 bdi_unregister(disk->queue->backing_dev_info);
883 blk_unregister_queue(disk);
888 if (!(disk->flags & GENHD_FL_HIDDEN))
889 blk_unregister_region(disk_devt(disk), disk->minors);
891 * Remove gendisk pointer from idr so that it cannot be looked up
892 * while RCU period before freeing gendisk is running to prevent
893 * use-after-free issues. Note that the device number stays
894 * "in-use" until we really free the gendisk.
896 blk_invalidate_devt(disk_devt(disk));
898 kobject_put(disk->part0.holder_dir);
899 kobject_put(disk->slave_dir);
901 part_stat_set_all(&disk->part0, 0);
902 disk->part0.stamp = 0;
903 if (!sysfs_deprecated)
904 sysfs_remove_link(block_depr, dev_name(disk_to_dev(disk)));
905 pm_runtime_set_memalloc_noio(disk_to_dev(disk), false);
906 device_del(disk_to_dev(disk));
908 EXPORT_SYMBOL(del_gendisk);
910 /* sysfs access to bad-blocks list. */
911 static ssize_t disk_badblocks_show(struct device *dev,
912 struct device_attribute *attr,
915 struct gendisk *disk = dev_to_disk(dev);
918 return sprintf(page, "\n");
920 return badblocks_show(disk->bb, page, 0);
923 static ssize_t disk_badblocks_store(struct device *dev,
924 struct device_attribute *attr,
925 const char *page, size_t len)
927 struct gendisk *disk = dev_to_disk(dev);
932 return badblocks_store(disk->bb, page, len, 0);
936 * get_gendisk - get partitioning information for a given device
937 * @devt: device to get partitioning information for
938 * @partno: returned partition index
940 * This function gets the structure containing partitioning
941 * information for the given device @devt.
943 struct gendisk *get_gendisk(dev_t devt, int *partno)
945 struct gendisk *disk = NULL;
947 if (MAJOR(devt) != BLOCK_EXT_MAJOR) {
948 struct kobject *kobj;
950 kobj = kobj_lookup(bdev_map, devt, partno);
952 disk = dev_to_disk(kobj_to_dev(kobj));
954 struct hd_struct *part;
956 spin_lock_bh(&ext_devt_lock);
957 part = idr_find(&ext_devt_idr, blk_mangle_minor(MINOR(devt)));
958 if (part && get_disk_and_module(part_to_disk(part))) {
959 *partno = part->partno;
960 disk = part_to_disk(part);
962 spin_unlock_bh(&ext_devt_lock);
969 * Synchronize with del_gendisk() to not return disk that is being
972 down_read(&disk->lookup_sem);
973 if (unlikely((disk->flags & GENHD_FL_HIDDEN) ||
974 !(disk->flags & GENHD_FL_UP))) {
975 up_read(&disk->lookup_sem);
976 put_disk_and_module(disk);
979 up_read(&disk->lookup_sem);
985 * bdget_disk - do bdget() by gendisk and partition number
986 * @disk: gendisk of interest
987 * @partno: partition number
989 * Find partition @partno from @disk, do bdget() on it.
995 * Resulting block_device on success, NULL on failure.
997 struct block_device *bdget_disk(struct gendisk *disk, int partno)
999 struct hd_struct *part;
1000 struct block_device *bdev = NULL;
1002 part = disk_get_part(disk, partno);
1004 bdev = bdget(part_devt(part));
1005 disk_put_part(part);
1009 EXPORT_SYMBOL(bdget_disk);
1012 * print a full list of all partitions - intended for places where the root
1013 * filesystem can't be mounted and thus to give the victim some idea of what
1016 void __init printk_all_partitions(void)
1018 struct class_dev_iter iter;
1021 class_dev_iter_init(&iter, &block_class, NULL, &disk_type);
1022 while ((dev = class_dev_iter_next(&iter))) {
1023 struct gendisk *disk = dev_to_disk(dev);
1024 struct disk_part_iter piter;
1025 struct hd_struct *part;
1026 char name_buf[BDEVNAME_SIZE];
1027 char devt_buf[BDEVT_SIZE];
1030 * Don't show empty devices or things that have been
1033 if (get_capacity(disk) == 0 ||
1034 (disk->flags & GENHD_FL_SUPPRESS_PARTITION_INFO))
1038 * Note, unlike /proc/partitions, I am showing the
1039 * numbers in hex - the same format as the root=
1042 disk_part_iter_init(&piter, disk, DISK_PITER_INCL_PART0);
1043 while ((part = disk_part_iter_next(&piter))) {
1044 bool is_part0 = part == &disk->part0;
1046 printk("%s%s %10llu %s %s", is_part0 ? "" : " ",
1047 bdevt_str(part_devt(part), devt_buf),
1048 (unsigned long long)part_nr_sects_read(part) >> 1
1049 , disk_name(disk, part->partno, name_buf),
1050 part->info ? part->info->uuid : "");
1052 if (dev->parent && dev->parent->driver)
1053 printk(" driver: %s\n",
1054 dev->parent->driver->name);
1056 printk(" (driver?)\n");
1060 disk_part_iter_exit(&piter);
1062 class_dev_iter_exit(&iter);
1065 #ifdef CONFIG_PROC_FS
1067 static void *disk_seqf_start(struct seq_file *seqf, loff_t *pos)
1070 struct class_dev_iter *iter;
1073 iter = kmalloc(sizeof(*iter), GFP_KERNEL);
1075 return ERR_PTR(-ENOMEM);
1077 seqf->private = iter;
1078 class_dev_iter_init(iter, &block_class, NULL, &disk_type);
1080 dev = class_dev_iter_next(iter);
1085 return dev_to_disk(dev);
1088 static void *disk_seqf_next(struct seq_file *seqf, void *v, loff_t *pos)
1093 dev = class_dev_iter_next(seqf->private);
1095 return dev_to_disk(dev);
1100 static void disk_seqf_stop(struct seq_file *seqf, void *v)
1102 struct class_dev_iter *iter = seqf->private;
1104 /* stop is called even after start failed :-( */
1106 class_dev_iter_exit(iter);
1108 seqf->private = NULL;
1112 static void *show_partition_start(struct seq_file *seqf, loff_t *pos)
1116 p = disk_seqf_start(seqf, pos);
1117 if (!IS_ERR_OR_NULL(p) && !*pos)
1118 seq_puts(seqf, "major minor #blocks name\n\n");
1122 static int show_partition(struct seq_file *seqf, void *v)
1124 struct gendisk *sgp = v;
1125 struct disk_part_iter piter;
1126 struct hd_struct *part;
1127 char buf[BDEVNAME_SIZE];
1129 /* Don't show non-partitionable removeable devices or empty devices */
1130 if (!get_capacity(sgp) || (!disk_max_parts(sgp) &&
1131 (sgp->flags & GENHD_FL_REMOVABLE)))
1133 if (sgp->flags & GENHD_FL_SUPPRESS_PARTITION_INFO)
1136 /* show the full disk and all non-0 size partitions of it */
1137 disk_part_iter_init(&piter, sgp, DISK_PITER_INCL_PART0);
1138 while ((part = disk_part_iter_next(&piter)))
1139 seq_printf(seqf, "%4d %7d %10llu %s\n",
1140 MAJOR(part_devt(part)), MINOR(part_devt(part)),
1141 (unsigned long long)part_nr_sects_read(part) >> 1,
1142 disk_name(sgp, part->partno, buf));
1143 disk_part_iter_exit(&piter);
1148 static const struct seq_operations partitions_op = {
1149 .start = show_partition_start,
1150 .next = disk_seqf_next,
1151 .stop = disk_seqf_stop,
1152 .show = show_partition
1157 static struct kobject *base_probe(dev_t devt, int *partno, void *data)
1159 if (request_module("block-major-%d-%d", MAJOR(devt), MINOR(devt)) > 0)
1160 /* Make old-style 2.4 aliases work */
1161 request_module("block-major-%d", MAJOR(devt));
1165 static int __init genhd_device_init(void)
1169 block_class.dev_kobj = sysfs_dev_block_kobj;
1170 error = class_register(&block_class);
1171 if (unlikely(error))
1173 bdev_map = kobj_map_init(base_probe, &block_class_lock);
1176 register_blkdev(BLOCK_EXT_MAJOR, "blkext");
1178 /* create top-level block dir */
1179 if (!sysfs_deprecated)
1180 block_depr = kobject_create_and_add("block", NULL);
1184 subsys_initcall(genhd_device_init);
1186 static ssize_t disk_range_show(struct device *dev,
1187 struct device_attribute *attr, char *buf)
1189 struct gendisk *disk = dev_to_disk(dev);
1191 return sprintf(buf, "%d\n", disk->minors);
1194 static ssize_t disk_ext_range_show(struct device *dev,
1195 struct device_attribute *attr, char *buf)
1197 struct gendisk *disk = dev_to_disk(dev);
1199 return sprintf(buf, "%d\n", disk_max_parts(disk));
1202 static ssize_t disk_removable_show(struct device *dev,
1203 struct device_attribute *attr, char *buf)
1205 struct gendisk *disk = dev_to_disk(dev);
1207 return sprintf(buf, "%d\n",
1208 (disk->flags & GENHD_FL_REMOVABLE ? 1 : 0));
1211 static ssize_t disk_hidden_show(struct device *dev,
1212 struct device_attribute *attr, char *buf)
1214 struct gendisk *disk = dev_to_disk(dev);
1216 return sprintf(buf, "%d\n",
1217 (disk->flags & GENHD_FL_HIDDEN ? 1 : 0));
1220 static ssize_t disk_ro_show(struct device *dev,
1221 struct device_attribute *attr, char *buf)
1223 struct gendisk *disk = dev_to_disk(dev);
1225 return sprintf(buf, "%d\n", get_disk_ro(disk) ? 1 : 0);
1228 ssize_t part_size_show(struct device *dev,
1229 struct device_attribute *attr, char *buf)
1231 struct hd_struct *p = dev_to_part(dev);
1233 return sprintf(buf, "%llu\n",
1234 (unsigned long long)part_nr_sects_read(p));
1237 ssize_t part_stat_show(struct device *dev,
1238 struct device_attribute *attr, char *buf)
1240 struct hd_struct *p = dev_to_part(dev);
1241 struct request_queue *q = part_to_disk(p)->queue;
1242 struct disk_stats stat;
1243 unsigned int inflight;
1245 part_stat_read_all(p, &stat);
1246 inflight = part_in_flight(q, p);
1249 "%8lu %8lu %8llu %8u "
1250 "%8lu %8lu %8llu %8u "
1252 "%8lu %8lu %8llu %8u "
1255 stat.ios[STAT_READ],
1256 stat.merges[STAT_READ],
1257 (unsigned long long)stat.sectors[STAT_READ],
1258 (unsigned int)div_u64(stat.nsecs[STAT_READ], NSEC_PER_MSEC),
1259 stat.ios[STAT_WRITE],
1260 stat.merges[STAT_WRITE],
1261 (unsigned long long)stat.sectors[STAT_WRITE],
1262 (unsigned int)div_u64(stat.nsecs[STAT_WRITE], NSEC_PER_MSEC),
1264 jiffies_to_msecs(stat.io_ticks),
1265 (unsigned int)div_u64(stat.nsecs[STAT_READ] +
1266 stat.nsecs[STAT_WRITE] +
1267 stat.nsecs[STAT_DISCARD] +
1268 stat.nsecs[STAT_FLUSH],
1270 stat.ios[STAT_DISCARD],
1271 stat.merges[STAT_DISCARD],
1272 (unsigned long long)stat.sectors[STAT_DISCARD],
1273 (unsigned int)div_u64(stat.nsecs[STAT_DISCARD], NSEC_PER_MSEC),
1274 stat.ios[STAT_FLUSH],
1275 (unsigned int)div_u64(stat.nsecs[STAT_FLUSH], NSEC_PER_MSEC));
1278 ssize_t part_inflight_show(struct device *dev, struct device_attribute *attr,
1281 struct hd_struct *p = dev_to_part(dev);
1282 struct request_queue *q = part_to_disk(p)->queue;
1283 unsigned int inflight[2];
1285 part_in_flight_rw(q, p, inflight);
1286 return sprintf(buf, "%8u %8u\n", inflight[0], inflight[1]);
1289 static ssize_t disk_capability_show(struct device *dev,
1290 struct device_attribute *attr, char *buf)
1292 struct gendisk *disk = dev_to_disk(dev);
1294 return sprintf(buf, "%x\n", disk->flags);
1297 static ssize_t disk_alignment_offset_show(struct device *dev,
1298 struct device_attribute *attr,
1301 struct gendisk *disk = dev_to_disk(dev);
1303 return sprintf(buf, "%d\n", queue_alignment_offset(disk->queue));
1306 static ssize_t disk_discard_alignment_show(struct device *dev,
1307 struct device_attribute *attr,
1310 struct gendisk *disk = dev_to_disk(dev);
1312 return sprintf(buf, "%d\n", queue_discard_alignment(disk->queue));
1315 static DEVICE_ATTR(range, 0444, disk_range_show, NULL);
1316 static DEVICE_ATTR(ext_range, 0444, disk_ext_range_show, NULL);
1317 static DEVICE_ATTR(removable, 0444, disk_removable_show, NULL);
1318 static DEVICE_ATTR(hidden, 0444, disk_hidden_show, NULL);
1319 static DEVICE_ATTR(ro, 0444, disk_ro_show, NULL);
1320 static DEVICE_ATTR(size, 0444, part_size_show, NULL);
1321 static DEVICE_ATTR(alignment_offset, 0444, disk_alignment_offset_show, NULL);
1322 static DEVICE_ATTR(discard_alignment, 0444, disk_discard_alignment_show, NULL);
1323 static DEVICE_ATTR(capability, 0444, disk_capability_show, NULL);
1324 static DEVICE_ATTR(stat, 0444, part_stat_show, NULL);
1325 static DEVICE_ATTR(inflight, 0444, part_inflight_show, NULL);
1326 static DEVICE_ATTR(badblocks, 0644, disk_badblocks_show, disk_badblocks_store);
1328 #ifdef CONFIG_FAIL_MAKE_REQUEST
1329 ssize_t part_fail_show(struct device *dev,
1330 struct device_attribute *attr, char *buf)
1332 struct hd_struct *p = dev_to_part(dev);
1334 return sprintf(buf, "%d\n", p->make_it_fail);
1337 ssize_t part_fail_store(struct device *dev,
1338 struct device_attribute *attr,
1339 const char *buf, size_t count)
1341 struct hd_struct *p = dev_to_part(dev);
1344 if (count > 0 && sscanf(buf, "%d", &i) > 0)
1345 p->make_it_fail = (i == 0) ? 0 : 1;
1350 static struct device_attribute dev_attr_fail =
1351 __ATTR(make-it-fail, 0644, part_fail_show, part_fail_store);
1352 #endif /* CONFIG_FAIL_MAKE_REQUEST */
1354 #ifdef CONFIG_FAIL_IO_TIMEOUT
1355 static struct device_attribute dev_attr_fail_timeout =
1356 __ATTR(io-timeout-fail, 0644, part_timeout_show, part_timeout_store);
1359 static struct attribute *disk_attrs[] = {
1360 &dev_attr_range.attr,
1361 &dev_attr_ext_range.attr,
1362 &dev_attr_removable.attr,
1363 &dev_attr_hidden.attr,
1365 &dev_attr_size.attr,
1366 &dev_attr_alignment_offset.attr,
1367 &dev_attr_discard_alignment.attr,
1368 &dev_attr_capability.attr,
1369 &dev_attr_stat.attr,
1370 &dev_attr_inflight.attr,
1371 &dev_attr_badblocks.attr,
1372 #ifdef CONFIG_FAIL_MAKE_REQUEST
1373 &dev_attr_fail.attr,
1375 #ifdef CONFIG_FAIL_IO_TIMEOUT
1376 &dev_attr_fail_timeout.attr,
1381 static umode_t disk_visible(struct kobject *kobj, struct attribute *a, int n)
1383 struct device *dev = container_of(kobj, typeof(*dev), kobj);
1384 struct gendisk *disk = dev_to_disk(dev);
1386 if (a == &dev_attr_badblocks.attr && !disk->bb)
1391 static struct attribute_group disk_attr_group = {
1392 .attrs = disk_attrs,
1393 .is_visible = disk_visible,
1396 static const struct attribute_group *disk_attr_groups[] = {
1402 * disk_replace_part_tbl - replace disk->part_tbl in RCU-safe way
1403 * @disk: disk to replace part_tbl for
1404 * @new_ptbl: new part_tbl to install
1406 * Replace disk->part_tbl with @new_ptbl in RCU-safe way. The
1407 * original ptbl is freed using RCU callback.
1410 * Matching bd_mutex locked or the caller is the only user of @disk.
1412 static void disk_replace_part_tbl(struct gendisk *disk,
1413 struct disk_part_tbl *new_ptbl)
1415 struct disk_part_tbl *old_ptbl =
1416 rcu_dereference_protected(disk->part_tbl, 1);
1418 rcu_assign_pointer(disk->part_tbl, new_ptbl);
1421 rcu_assign_pointer(old_ptbl->last_lookup, NULL);
1422 kfree_rcu(old_ptbl, rcu_head);
1427 * disk_expand_part_tbl - expand disk->part_tbl
1428 * @disk: disk to expand part_tbl for
1429 * @partno: expand such that this partno can fit in
1431 * Expand disk->part_tbl such that @partno can fit in. disk->part_tbl
1432 * uses RCU to allow unlocked dereferencing for stats and other stuff.
1435 * Matching bd_mutex locked or the caller is the only user of @disk.
1439 * 0 on success, -errno on failure.
1441 int disk_expand_part_tbl(struct gendisk *disk, int partno)
1443 struct disk_part_tbl *old_ptbl =
1444 rcu_dereference_protected(disk->part_tbl, 1);
1445 struct disk_part_tbl *new_ptbl;
1446 int len = old_ptbl ? old_ptbl->len : 0;
1450 * check for int overflow, since we can get here from blkpg_ioctl()
1451 * with a user passed 'partno'.
1453 target = partno + 1;
1457 /* disk_max_parts() is zero during initialization, ignore if so */
1458 if (disk_max_parts(disk) && target > disk_max_parts(disk))
1464 new_ptbl = kzalloc_node(struct_size(new_ptbl, part, target), GFP_KERNEL,
1469 new_ptbl->len = target;
1471 for (i = 0; i < len; i++)
1472 rcu_assign_pointer(new_ptbl->part[i], old_ptbl->part[i]);
1474 disk_replace_part_tbl(disk, new_ptbl);
1478 static void disk_release(struct device *dev)
1480 struct gendisk *disk = dev_to_disk(dev);
1482 blk_free_devt(dev->devt);
1483 disk_release_events(disk);
1484 kfree(disk->random);
1485 disk_replace_part_tbl(disk, NULL);
1486 hd_free_part(&disk->part0);
1488 blk_put_queue(disk->queue);
1491 struct class block_class = {
1495 static char *block_devnode(struct device *dev, umode_t *mode,
1496 kuid_t *uid, kgid_t *gid)
1498 struct gendisk *disk = dev_to_disk(dev);
1500 if (disk->fops->devnode)
1501 return disk->fops->devnode(disk, mode);
1505 static const struct device_type disk_type = {
1507 .groups = disk_attr_groups,
1508 .release = disk_release,
1509 .devnode = block_devnode,
1512 #ifdef CONFIG_PROC_FS
1514 * aggregate disk stat collector. Uses the same stats that the sysfs
1515 * entries do, above, but makes them available through one seq_file.
1517 * The output looks suspiciously like /proc/partitions with a bunch of
1520 static int diskstats_show(struct seq_file *seqf, void *v)
1522 struct gendisk *gp = v;
1523 struct disk_part_iter piter;
1524 struct hd_struct *hd;
1525 char buf[BDEVNAME_SIZE];
1526 unsigned int inflight;
1527 struct disk_stats stat;
1530 if (&disk_to_dev(gp)->kobj.entry == block_class.devices.next)
1531 seq_puts(seqf, "major minor name"
1532 " rio rmerge rsect ruse wio wmerge "
1533 "wsect wuse running use aveq"
1537 disk_part_iter_init(&piter, gp, DISK_PITER_INCL_EMPTY_PART0);
1538 while ((hd = disk_part_iter_next(&piter))) {
1539 part_stat_read_all(hd, &stat);
1540 inflight = part_in_flight(gp->queue, hd);
1542 seq_printf(seqf, "%4d %7d %s "
1549 MAJOR(part_devt(hd)), MINOR(part_devt(hd)),
1550 disk_name(gp, hd->partno, buf),
1551 stat.ios[STAT_READ],
1552 stat.merges[STAT_READ],
1553 stat.sectors[STAT_READ],
1554 (unsigned int)div_u64(stat.nsecs[STAT_READ],
1556 stat.ios[STAT_WRITE],
1557 stat.merges[STAT_WRITE],
1558 stat.sectors[STAT_WRITE],
1559 (unsigned int)div_u64(stat.nsecs[STAT_WRITE],
1562 jiffies_to_msecs(stat.io_ticks),
1563 (unsigned int)div_u64(stat.nsecs[STAT_READ] +
1564 stat.nsecs[STAT_WRITE] +
1565 stat.nsecs[STAT_DISCARD] +
1566 stat.nsecs[STAT_FLUSH],
1568 stat.ios[STAT_DISCARD],
1569 stat.merges[STAT_DISCARD],
1570 stat.sectors[STAT_DISCARD],
1571 (unsigned int)div_u64(stat.nsecs[STAT_DISCARD],
1573 stat.ios[STAT_FLUSH],
1574 (unsigned int)div_u64(stat.nsecs[STAT_FLUSH],
1578 disk_part_iter_exit(&piter);
1583 static const struct seq_operations diskstats_op = {
1584 .start = disk_seqf_start,
1585 .next = disk_seqf_next,
1586 .stop = disk_seqf_stop,
1587 .show = diskstats_show
1590 static int __init proc_genhd_init(void)
1592 proc_create_seq("diskstats", 0, NULL, &diskstats_op);
1593 proc_create_seq("partitions", 0, NULL, &partitions_op);
1596 module_init(proc_genhd_init);
1597 #endif /* CONFIG_PROC_FS */
1599 dev_t blk_lookup_devt(const char *name, int partno)
1601 dev_t devt = MKDEV(0, 0);
1602 struct class_dev_iter iter;
1605 class_dev_iter_init(&iter, &block_class, NULL, &disk_type);
1606 while ((dev = class_dev_iter_next(&iter))) {
1607 struct gendisk *disk = dev_to_disk(dev);
1608 struct hd_struct *part;
1610 if (strcmp(dev_name(dev), name))
1613 if (partno < disk->minors) {
1614 /* We need to return the right devno, even
1615 * if the partition doesn't exist yet.
1617 devt = MKDEV(MAJOR(dev->devt),
1618 MINOR(dev->devt) + partno);
1621 part = disk_get_part(disk, partno);
1623 devt = part_devt(part);
1624 disk_put_part(part);
1627 disk_put_part(part);
1629 class_dev_iter_exit(&iter);
1633 struct gendisk *__alloc_disk_node(int minors, int node_id)
1635 struct gendisk *disk;
1636 struct disk_part_tbl *ptbl;
1638 if (minors > DISK_MAX_PARTS) {
1640 "block: can't allocate more than %d partitions\n",
1642 minors = DISK_MAX_PARTS;
1645 disk = kzalloc_node(sizeof(struct gendisk), GFP_KERNEL, node_id);
1647 if (!init_part_stats(&disk->part0)) {
1651 init_rwsem(&disk->lookup_sem);
1652 disk->node_id = node_id;
1653 if (disk_expand_part_tbl(disk, 0)) {
1654 free_part_stats(&disk->part0);
1658 ptbl = rcu_dereference_protected(disk->part_tbl, 1);
1659 rcu_assign_pointer(ptbl->part[0], &disk->part0);
1662 * set_capacity() and get_capacity() currently don't use
1663 * seqcounter to read/update the part0->nr_sects. Still init
1664 * the counter as we can read the sectors in IO submission
1665 * patch using seqence counters.
1667 * TODO: Ideally set_capacity() and get_capacity() should be
1668 * converted to make use of bd_mutex and sequence counters.
1670 seqcount_init(&disk->part0.nr_sects_seq);
1671 if (hd_ref_init(&disk->part0)) {
1672 hd_free_part(&disk->part0);
1677 disk->minors = minors;
1678 rand_initialize_disk(disk);
1679 disk_to_dev(disk)->class = &block_class;
1680 disk_to_dev(disk)->type = &disk_type;
1681 device_initialize(disk_to_dev(disk));
1685 EXPORT_SYMBOL(__alloc_disk_node);
1687 struct kobject *get_disk_and_module(struct gendisk *disk)
1689 struct module *owner;
1690 struct kobject *kobj;
1694 owner = disk->fops->owner;
1695 if (owner && !try_module_get(owner))
1697 kobj = kobject_get_unless_zero(&disk_to_dev(disk)->kobj);
1705 EXPORT_SYMBOL(get_disk_and_module);
1707 void put_disk(struct gendisk *disk)
1710 kobject_put(&disk_to_dev(disk)->kobj);
1712 EXPORT_SYMBOL(put_disk);
1715 * This is a counterpart of get_disk_and_module() and thus also of
1718 void put_disk_and_module(struct gendisk *disk)
1721 struct module *owner = disk->fops->owner;
1727 EXPORT_SYMBOL(put_disk_and_module);
1729 static void set_disk_ro_uevent(struct gendisk *gd, int ro)
1731 char event[] = "DISK_RO=1";
1732 char *envp[] = { event, NULL };
1736 kobject_uevent_env(&disk_to_dev(gd)->kobj, KOBJ_CHANGE, envp);
1739 void set_device_ro(struct block_device *bdev, int flag)
1741 bdev->bd_part->policy = flag;
1744 EXPORT_SYMBOL(set_device_ro);
1746 void set_disk_ro(struct gendisk *disk, int flag)
1748 struct disk_part_iter piter;
1749 struct hd_struct *part;
1751 if (disk->part0.policy != flag) {
1752 set_disk_ro_uevent(disk, flag);
1753 disk->part0.policy = flag;
1756 disk_part_iter_init(&piter, disk, DISK_PITER_INCL_EMPTY);
1757 while ((part = disk_part_iter_next(&piter)))
1758 part->policy = flag;
1759 disk_part_iter_exit(&piter);
1762 EXPORT_SYMBOL(set_disk_ro);
1764 int bdev_read_only(struct block_device *bdev)
1768 return bdev->bd_part->policy;
1771 EXPORT_SYMBOL(bdev_read_only);
1773 int invalidate_partition(struct gendisk *disk, int partno)
1776 struct block_device *bdev = bdget_disk(disk, partno);
1779 res = __invalidate_device(bdev, true);
1785 EXPORT_SYMBOL(invalidate_partition);
1788 * Disk events - monitor disk events like media change and eject request.
1790 struct disk_events {
1791 struct list_head node; /* all disk_event's */
1792 struct gendisk *disk; /* the associated disk */
1795 struct mutex block_mutex; /* protects blocking */
1796 int block; /* event blocking depth */
1797 unsigned int pending; /* events already sent out */
1798 unsigned int clearing; /* events being cleared */
1800 long poll_msecs; /* interval, -1 for default */
1801 struct delayed_work dwork;
1804 static const char *disk_events_strs[] = {
1805 [ilog2(DISK_EVENT_MEDIA_CHANGE)] = "media_change",
1806 [ilog2(DISK_EVENT_EJECT_REQUEST)] = "eject_request",
1809 static char *disk_uevents[] = {
1810 [ilog2(DISK_EVENT_MEDIA_CHANGE)] = "DISK_MEDIA_CHANGE=1",
1811 [ilog2(DISK_EVENT_EJECT_REQUEST)] = "DISK_EJECT_REQUEST=1",
1814 /* list of all disk_events */
1815 static DEFINE_MUTEX(disk_events_mutex);
1816 static LIST_HEAD(disk_events);
1818 /* disable in-kernel polling by default */
1819 static unsigned long disk_events_dfl_poll_msecs;
1821 static unsigned long disk_events_poll_jiffies(struct gendisk *disk)
1823 struct disk_events *ev = disk->ev;
1824 long intv_msecs = 0;
1827 * If device-specific poll interval is set, always use it. If
1828 * the default is being used, poll if the POLL flag is set.
1830 if (ev->poll_msecs >= 0)
1831 intv_msecs = ev->poll_msecs;
1832 else if (disk->event_flags & DISK_EVENT_FLAG_POLL)
1833 intv_msecs = disk_events_dfl_poll_msecs;
1835 return msecs_to_jiffies(intv_msecs);
1839 * disk_block_events - block and flush disk event checking
1840 * @disk: disk to block events for
1842 * On return from this function, it is guaranteed that event checking
1843 * isn't in progress and won't happen until unblocked by
1844 * disk_unblock_events(). Events blocking is counted and the actual
1845 * unblocking happens after the matching number of unblocks are done.
1847 * Note that this intentionally does not block event checking from
1848 * disk_clear_events().
1853 void disk_block_events(struct gendisk *disk)
1855 struct disk_events *ev = disk->ev;
1856 unsigned long flags;
1863 * Outer mutex ensures that the first blocker completes canceling
1864 * the event work before further blockers are allowed to finish.
1866 mutex_lock(&ev->block_mutex);
1868 spin_lock_irqsave(&ev->lock, flags);
1869 cancel = !ev->block++;
1870 spin_unlock_irqrestore(&ev->lock, flags);
1873 cancel_delayed_work_sync(&disk->ev->dwork);
1875 mutex_unlock(&ev->block_mutex);
1878 static void __disk_unblock_events(struct gendisk *disk, bool check_now)
1880 struct disk_events *ev = disk->ev;
1882 unsigned long flags;
1884 spin_lock_irqsave(&ev->lock, flags);
1886 if (WARN_ON_ONCE(ev->block <= 0))
1892 intv = disk_events_poll_jiffies(disk);
1894 queue_delayed_work(system_freezable_power_efficient_wq,
1897 queue_delayed_work(system_freezable_power_efficient_wq,
1900 spin_unlock_irqrestore(&ev->lock, flags);
1904 * disk_unblock_events - unblock disk event checking
1905 * @disk: disk to unblock events for
1907 * Undo disk_block_events(). When the block count reaches zero, it
1908 * starts events polling if configured.
1911 * Don't care. Safe to call from irq context.
1913 void disk_unblock_events(struct gendisk *disk)
1916 __disk_unblock_events(disk, false);
1920 * disk_flush_events - schedule immediate event checking and flushing
1921 * @disk: disk to check and flush events for
1922 * @mask: events to flush
1924 * Schedule immediate event checking on @disk if not blocked. Events in
1925 * @mask are scheduled to be cleared from the driver. Note that this
1926 * doesn't clear the events from @disk->ev.
1929 * If @mask is non-zero must be called with bdev->bd_mutex held.
1931 void disk_flush_events(struct gendisk *disk, unsigned int mask)
1933 struct disk_events *ev = disk->ev;
1938 spin_lock_irq(&ev->lock);
1939 ev->clearing |= mask;
1941 mod_delayed_work(system_freezable_power_efficient_wq,
1943 spin_unlock_irq(&ev->lock);
1947 * disk_clear_events - synchronously check, clear and return pending events
1948 * @disk: disk to fetch and clear events from
1949 * @mask: mask of events to be fetched and cleared
1951 * Disk events are synchronously checked and pending events in @mask
1952 * are cleared and returned. This ignores the block count.
1957 unsigned int disk_clear_events(struct gendisk *disk, unsigned int mask)
1959 const struct block_device_operations *bdops = disk->fops;
1960 struct disk_events *ev = disk->ev;
1961 unsigned int pending;
1962 unsigned int clearing = mask;
1965 /* for drivers still using the old ->media_changed method */
1966 if ((mask & DISK_EVENT_MEDIA_CHANGE) &&
1967 bdops->media_changed && bdops->media_changed(disk))
1968 return DISK_EVENT_MEDIA_CHANGE;
1972 disk_block_events(disk);
1975 * store the union of mask and ev->clearing on the stack so that the
1976 * race with disk_flush_events does not cause ambiguity (ev->clearing
1977 * can still be modified even if events are blocked).
1979 spin_lock_irq(&ev->lock);
1980 clearing |= ev->clearing;
1982 spin_unlock_irq(&ev->lock);
1984 disk_check_events(ev, &clearing);
1986 * if ev->clearing is not 0, the disk_flush_events got called in the
1987 * middle of this function, so we want to run the workfn without delay.
1989 __disk_unblock_events(disk, ev->clearing ? true : false);
1991 /* then, fetch and clear pending events */
1992 spin_lock_irq(&ev->lock);
1993 pending = ev->pending & mask;
1994 ev->pending &= ~mask;
1995 spin_unlock_irq(&ev->lock);
1996 WARN_ON_ONCE(clearing & mask);
2002 * Separate this part out so that a different pointer for clearing_ptr can be
2003 * passed in for disk_clear_events.
2005 static void disk_events_workfn(struct work_struct *work)
2007 struct delayed_work *dwork = to_delayed_work(work);
2008 struct disk_events *ev = container_of(dwork, struct disk_events, dwork);
2010 disk_check_events(ev, &ev->clearing);
2013 static void disk_check_events(struct disk_events *ev,
2014 unsigned int *clearing_ptr)
2016 struct gendisk *disk = ev->disk;
2017 char *envp[ARRAY_SIZE(disk_uevents) + 1] = { };
2018 unsigned int clearing = *clearing_ptr;
2019 unsigned int events;
2021 int nr_events = 0, i;
2024 events = disk->fops->check_events(disk, clearing);
2026 /* accumulate pending events and schedule next poll if necessary */
2027 spin_lock_irq(&ev->lock);
2029 events &= ~ev->pending;
2030 ev->pending |= events;
2031 *clearing_ptr &= ~clearing;
2033 intv = disk_events_poll_jiffies(disk);
2034 if (!ev->block && intv)
2035 queue_delayed_work(system_freezable_power_efficient_wq,
2038 spin_unlock_irq(&ev->lock);
2041 * Tell userland about new events. Only the events listed in
2042 * @disk->events are reported, and only if DISK_EVENT_FLAG_UEVENT
2043 * is set. Otherwise, events are processed internally but never
2044 * get reported to userland.
2046 for (i = 0; i < ARRAY_SIZE(disk_uevents); i++)
2047 if ((events & disk->events & (1 << i)) &&
2048 (disk->event_flags & DISK_EVENT_FLAG_UEVENT))
2049 envp[nr_events++] = disk_uevents[i];
2052 kobject_uevent_env(&disk_to_dev(disk)->kobj, KOBJ_CHANGE, envp);
2056 * A disk events enabled device has the following sysfs nodes under
2057 * its /sys/block/X/ directory.
2059 * events : list of all supported events
2060 * events_async : list of events which can be detected w/o polling
2061 * (always empty, only for backwards compatibility)
2062 * events_poll_msecs : polling interval, 0: disable, -1: system default
2064 static ssize_t __disk_events_show(unsigned int events, char *buf)
2066 const char *delim = "";
2070 for (i = 0; i < ARRAY_SIZE(disk_events_strs); i++)
2071 if (events & (1 << i)) {
2072 pos += sprintf(buf + pos, "%s%s",
2073 delim, disk_events_strs[i]);
2077 pos += sprintf(buf + pos, "\n");
2081 static ssize_t disk_events_show(struct device *dev,
2082 struct device_attribute *attr, char *buf)
2084 struct gendisk *disk = dev_to_disk(dev);
2086 if (!(disk->event_flags & DISK_EVENT_FLAG_UEVENT))
2089 return __disk_events_show(disk->events, buf);
2092 static ssize_t disk_events_async_show(struct device *dev,
2093 struct device_attribute *attr, char *buf)
2098 static ssize_t disk_events_poll_msecs_show(struct device *dev,
2099 struct device_attribute *attr,
2102 struct gendisk *disk = dev_to_disk(dev);
2105 return sprintf(buf, "-1\n");
2107 return sprintf(buf, "%ld\n", disk->ev->poll_msecs);
2110 static ssize_t disk_events_poll_msecs_store(struct device *dev,
2111 struct device_attribute *attr,
2112 const char *buf, size_t count)
2114 struct gendisk *disk = dev_to_disk(dev);
2117 if (!count || !sscanf(buf, "%ld", &intv))
2120 if (intv < 0 && intv != -1)
2126 disk_block_events(disk);
2127 disk->ev->poll_msecs = intv;
2128 __disk_unblock_events(disk, true);
2133 static const DEVICE_ATTR(events, 0444, disk_events_show, NULL);
2134 static const DEVICE_ATTR(events_async, 0444, disk_events_async_show, NULL);
2135 static const DEVICE_ATTR(events_poll_msecs, 0644,
2136 disk_events_poll_msecs_show,
2137 disk_events_poll_msecs_store);
2139 static const struct attribute *disk_events_attrs[] = {
2140 &dev_attr_events.attr,
2141 &dev_attr_events_async.attr,
2142 &dev_attr_events_poll_msecs.attr,
2147 * The default polling interval can be specified by the kernel
2148 * parameter block.events_dfl_poll_msecs which defaults to 0
2149 * (disable). This can also be modified runtime by writing to
2150 * /sys/module/block/parameters/events_dfl_poll_msecs.
2152 static int disk_events_set_dfl_poll_msecs(const char *val,
2153 const struct kernel_param *kp)
2155 struct disk_events *ev;
2158 ret = param_set_ulong(val, kp);
2162 mutex_lock(&disk_events_mutex);
2164 list_for_each_entry(ev, &disk_events, node)
2165 disk_flush_events(ev->disk, 0);
2167 mutex_unlock(&disk_events_mutex);
2172 static const struct kernel_param_ops disk_events_dfl_poll_msecs_param_ops = {
2173 .set = disk_events_set_dfl_poll_msecs,
2174 .get = param_get_ulong,
2177 #undef MODULE_PARAM_PREFIX
2178 #define MODULE_PARAM_PREFIX "block."
2180 module_param_cb(events_dfl_poll_msecs, &disk_events_dfl_poll_msecs_param_ops,
2181 &disk_events_dfl_poll_msecs, 0644);
2184 * disk_{alloc|add|del|release}_events - initialize and destroy disk_events.
2186 static void disk_alloc_events(struct gendisk *disk)
2188 struct disk_events *ev;
2190 if (!disk->fops->check_events || !disk->events)
2193 ev = kzalloc(sizeof(*ev), GFP_KERNEL);
2195 pr_warn("%s: failed to initialize events\n", disk->disk_name);
2199 INIT_LIST_HEAD(&ev->node);
2201 spin_lock_init(&ev->lock);
2202 mutex_init(&ev->block_mutex);
2204 ev->poll_msecs = -1;
2205 INIT_DELAYED_WORK(&ev->dwork, disk_events_workfn);
2210 static void disk_add_events(struct gendisk *disk)
2212 /* FIXME: error handling */
2213 if (sysfs_create_files(&disk_to_dev(disk)->kobj, disk_events_attrs) < 0)
2214 pr_warn("%s: failed to create sysfs files for events\n",
2220 mutex_lock(&disk_events_mutex);
2221 list_add_tail(&disk->ev->node, &disk_events);
2222 mutex_unlock(&disk_events_mutex);
2225 * Block count is initialized to 1 and the following initial
2226 * unblock kicks it into action.
2228 __disk_unblock_events(disk, true);
2231 static void disk_del_events(struct gendisk *disk)
2234 disk_block_events(disk);
2236 mutex_lock(&disk_events_mutex);
2237 list_del_init(&disk->ev->node);
2238 mutex_unlock(&disk_events_mutex);
2241 sysfs_remove_files(&disk_to_dev(disk)->kobj, disk_events_attrs);
2244 static void disk_release_events(struct gendisk *disk)
2246 /* the block count should be 1 from disk_del_events() */
2247 WARN_ON_ONCE(disk->ev && disk->ev->block != 1);