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