xref: /linux/block/genhd.c (revision e7602bb4f3a1234df8b75728ac3260bcb8242612)
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/kdev_t.h>
12 #include <linux/kernel.h>
13 #include <linux/blkdev.h>
14 #include <linux/backing-dev.h>
15 #include <linux/init.h>
16 #include <linux/spinlock.h>
17 #include <linux/proc_fs.h>
18 #include <linux/seq_file.h>
19 #include <linux/slab.h>
20 #include <linux/kmod.h>
21 #include <linux/major.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 #include <linux/part_stat.h>
28 #include <linux/blktrace_api.h>
29 
30 #include "blk-throttle.h"
31 #include "blk.h"
32 #include "blk-mq-sched.h"
33 #include "blk-rq-qos.h"
34 #include "blk-cgroup.h"
35 
36 static struct kobject *block_depr;
37 
38 /*
39  * Unique, monotonically increasing sequential number associated with block
40  * devices instances (i.e. incremented each time a device is attached).
41  * Associating uevents with block devices in userspace is difficult and racy:
42  * the uevent netlink socket is lossy, and on slow and overloaded systems has
43  * a very high latency.
44  * Block devices do not have exclusive owners in userspace, any process can set
45  * one up (e.g. loop devices). Moreover, device names can be reused (e.g. loop0
46  * can be reused again and again).
47  * A userspace process setting up a block device and watching for its events
48  * cannot thus reliably tell whether an event relates to the device it just set
49  * up or another earlier instance with the same name.
50  * This sequential number allows userspace processes to solve this problem, and
51  * uniquely associate an uevent to the lifetime to a device.
52  */
53 static atomic64_t diskseq;
54 
55 /* for extended dynamic devt allocation, currently only one major is used */
56 #define NR_EXT_DEVT		(1 << MINORBITS)
57 static DEFINE_IDA(ext_devt_ida);
58 
59 void set_capacity(struct gendisk *disk, sector_t sectors)
60 {
61 	bdev_set_nr_sectors(disk->part0, sectors);
62 }
63 EXPORT_SYMBOL(set_capacity);
64 
65 /*
66  * Set disk capacity and notify if the size is not currently zero and will not
67  * be set to zero.  Returns true if a uevent was sent, otherwise false.
68  */
69 bool set_capacity_and_notify(struct gendisk *disk, sector_t size)
70 {
71 	sector_t capacity = get_capacity(disk);
72 	char *envp[] = { "RESIZE=1", NULL };
73 
74 	set_capacity(disk, size);
75 
76 	/*
77 	 * Only print a message and send a uevent if the gendisk is user visible
78 	 * and alive.  This avoids spamming the log and udev when setting the
79 	 * initial capacity during probing.
80 	 */
81 	if (size == capacity ||
82 	    !disk_live(disk) ||
83 	    (disk->flags & GENHD_FL_HIDDEN))
84 		return false;
85 
86 	pr_info("%s: detected capacity change from %lld to %lld\n",
87 		disk->disk_name, capacity, size);
88 
89 	/*
90 	 * Historically we did not send a uevent for changes to/from an empty
91 	 * device.
92 	 */
93 	if (!capacity || !size)
94 		return false;
95 	kobject_uevent_env(&disk_to_dev(disk)->kobj, KOBJ_CHANGE, envp);
96 	return true;
97 }
98 EXPORT_SYMBOL_GPL(set_capacity_and_notify);
99 
100 static void part_stat_read_all(struct block_device *part,
101 		struct disk_stats *stat)
102 {
103 	int cpu;
104 
105 	memset(stat, 0, sizeof(struct disk_stats));
106 	for_each_possible_cpu(cpu) {
107 		struct disk_stats *ptr = per_cpu_ptr(part->bd_stats, cpu);
108 		int group;
109 
110 		for (group = 0; group < NR_STAT_GROUPS; group++) {
111 			stat->nsecs[group] += ptr->nsecs[group];
112 			stat->sectors[group] += ptr->sectors[group];
113 			stat->ios[group] += ptr->ios[group];
114 			stat->merges[group] += ptr->merges[group];
115 		}
116 
117 		stat->io_ticks += ptr->io_ticks;
118 	}
119 }
120 
121 unsigned int part_in_flight(struct block_device *part)
122 {
123 	unsigned int inflight = 0;
124 	int cpu;
125 
126 	for_each_possible_cpu(cpu) {
127 		inflight += part_stat_local_read_cpu(part, in_flight[0], cpu) +
128 			    part_stat_local_read_cpu(part, in_flight[1], cpu);
129 	}
130 	if ((int)inflight < 0)
131 		inflight = 0;
132 
133 	return inflight;
134 }
135 
136 static void part_in_flight_rw(struct block_device *part,
137 		unsigned int inflight[2])
138 {
139 	int cpu;
140 
141 	inflight[0] = 0;
142 	inflight[1] = 0;
143 	for_each_possible_cpu(cpu) {
144 		inflight[0] += part_stat_local_read_cpu(part, in_flight[0], cpu);
145 		inflight[1] += part_stat_local_read_cpu(part, in_flight[1], cpu);
146 	}
147 	if ((int)inflight[0] < 0)
148 		inflight[0] = 0;
149 	if ((int)inflight[1] < 0)
150 		inflight[1] = 0;
151 }
152 
153 /*
154  * Can be deleted altogether. Later.
155  *
156  */
157 #define BLKDEV_MAJOR_HASH_SIZE 255
158 static struct blk_major_name {
159 	struct blk_major_name *next;
160 	int major;
161 	char name[16];
162 #ifdef CONFIG_BLOCK_LEGACY_AUTOLOAD
163 	void (*probe)(dev_t devt);
164 #endif
165 } *major_names[BLKDEV_MAJOR_HASH_SIZE];
166 static DEFINE_MUTEX(major_names_lock);
167 static DEFINE_SPINLOCK(major_names_spinlock);
168 
169 /* index in the above - for now: assume no multimajor ranges */
170 static inline int major_to_index(unsigned major)
171 {
172 	return major % BLKDEV_MAJOR_HASH_SIZE;
173 }
174 
175 #ifdef CONFIG_PROC_FS
176 void blkdev_show(struct seq_file *seqf, off_t offset)
177 {
178 	struct blk_major_name *dp;
179 
180 	spin_lock(&major_names_spinlock);
181 	for (dp = major_names[major_to_index(offset)]; dp; dp = dp->next)
182 		if (dp->major == offset)
183 			seq_printf(seqf, "%3d %s\n", dp->major, dp->name);
184 	spin_unlock(&major_names_spinlock);
185 }
186 #endif /* CONFIG_PROC_FS */
187 
188 /**
189  * __register_blkdev - register a new block device
190  *
191  * @major: the requested major device number [1..BLKDEV_MAJOR_MAX-1]. If
192  *         @major = 0, try to allocate any unused major number.
193  * @name: the name of the new block device as a zero terminated string
194  * @probe: pre-devtmpfs / pre-udev callback used to create disks when their
195  *	   pre-created device node is accessed. When a probe call uses
196  *	   add_disk() and it fails the driver must cleanup resources. This
197  *	   interface may soon be removed.
198  *
199  * The @name must be unique within the system.
200  *
201  * The return value depends on the @major input parameter:
202  *
203  *  - if a major device number was requested in range [1..BLKDEV_MAJOR_MAX-1]
204  *    then the function returns zero on success, or a negative error code
205  *  - if any unused major number was requested with @major = 0 parameter
206  *    then the return value is the allocated major number in range
207  *    [1..BLKDEV_MAJOR_MAX-1] or a negative error code otherwise
208  *
209  * See Documentation/admin-guide/devices.txt for the list of allocated
210  * major numbers.
211  *
212  * Use register_blkdev instead for any new code.
213  */
214 int __register_blkdev(unsigned int major, const char *name,
215 		void (*probe)(dev_t devt))
216 {
217 	struct blk_major_name **n, *p;
218 	int index, ret = 0;
219 
220 	mutex_lock(&major_names_lock);
221 
222 	/* temporary */
223 	if (major == 0) {
224 		for (index = ARRAY_SIZE(major_names)-1; index > 0; index--) {
225 			if (major_names[index] == NULL)
226 				break;
227 		}
228 
229 		if (index == 0) {
230 			printk("%s: failed to get major for %s\n",
231 			       __func__, name);
232 			ret = -EBUSY;
233 			goto out;
234 		}
235 		major = index;
236 		ret = major;
237 	}
238 
239 	if (major >= BLKDEV_MAJOR_MAX) {
240 		pr_err("%s: major requested (%u) is greater than the maximum (%u) for %s\n",
241 		       __func__, major, BLKDEV_MAJOR_MAX-1, name);
242 
243 		ret = -EINVAL;
244 		goto out;
245 	}
246 
247 	p = kmalloc(sizeof(struct blk_major_name), GFP_KERNEL);
248 	if (p == NULL) {
249 		ret = -ENOMEM;
250 		goto out;
251 	}
252 
253 	p->major = major;
254 #ifdef CONFIG_BLOCK_LEGACY_AUTOLOAD
255 	p->probe = probe;
256 #endif
257 	strscpy(p->name, name, sizeof(p->name));
258 	p->next = NULL;
259 	index = major_to_index(major);
260 
261 	spin_lock(&major_names_spinlock);
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 	spin_unlock(&major_names_spinlock);
271 
272 	if (ret < 0) {
273 		printk("register_blkdev: cannot get major %u for %s\n",
274 		       major, name);
275 		kfree(p);
276 	}
277 out:
278 	mutex_unlock(&major_names_lock);
279 	return ret;
280 }
281 EXPORT_SYMBOL(__register_blkdev);
282 
283 void unregister_blkdev(unsigned int major, const char *name)
284 {
285 	struct blk_major_name **n;
286 	struct blk_major_name *p = NULL;
287 	int index = major_to_index(major);
288 
289 	mutex_lock(&major_names_lock);
290 	spin_lock(&major_names_spinlock);
291 	for (n = &major_names[index]; *n; n = &(*n)->next)
292 		if ((*n)->major == major)
293 			break;
294 	if (!*n || strcmp((*n)->name, name)) {
295 		WARN_ON(1);
296 	} else {
297 		p = *n;
298 		*n = p->next;
299 	}
300 	spin_unlock(&major_names_spinlock);
301 	mutex_unlock(&major_names_lock);
302 	kfree(p);
303 }
304 
305 EXPORT_SYMBOL(unregister_blkdev);
306 
307 int blk_alloc_ext_minor(void)
308 {
309 	int idx;
310 
311 	idx = ida_alloc_range(&ext_devt_ida, 0, NR_EXT_DEVT - 1, GFP_KERNEL);
312 	if (idx == -ENOSPC)
313 		return -EBUSY;
314 	return idx;
315 }
316 
317 void blk_free_ext_minor(unsigned int minor)
318 {
319 	ida_free(&ext_devt_ida, minor);
320 }
321 
322 void disk_uevent(struct gendisk *disk, enum kobject_action action)
323 {
324 	struct block_device *part;
325 	unsigned long idx;
326 
327 	rcu_read_lock();
328 	xa_for_each(&disk->part_tbl, idx, part) {
329 		if (bdev_is_partition(part) && !bdev_nr_sectors(part))
330 			continue;
331 		if (!kobject_get_unless_zero(&part->bd_device.kobj))
332 			continue;
333 
334 		rcu_read_unlock();
335 		kobject_uevent(bdev_kobj(part), action);
336 		put_device(&part->bd_device);
337 		rcu_read_lock();
338 	}
339 	rcu_read_unlock();
340 }
341 EXPORT_SYMBOL_GPL(disk_uevent);
342 
343 int disk_scan_partitions(struct gendisk *disk, blk_mode_t mode)
344 {
345 	struct file *file;
346 	int ret = 0;
347 
348 	if (!disk_has_partscan(disk))
349 		return -EINVAL;
350 	if (disk->open_partitions)
351 		return -EBUSY;
352 
353 	/*
354 	 * If the device is opened exclusively by current thread already, it's
355 	 * safe to scan partitons, otherwise, use bd_prepare_to_claim() to
356 	 * synchronize with other exclusive openers and other partition
357 	 * scanners.
358 	 */
359 	if (!(mode & BLK_OPEN_EXCL)) {
360 		ret = bd_prepare_to_claim(disk->part0, disk_scan_partitions,
361 					  NULL);
362 		if (ret)
363 			return ret;
364 	}
365 
366 	set_bit(GD_NEED_PART_SCAN, &disk->state);
367 	file = bdev_file_open_by_dev(disk_devt(disk), mode & ~BLK_OPEN_EXCL,
368 				     NULL, NULL);
369 	if (IS_ERR(file))
370 		ret = PTR_ERR(file);
371 	else
372 		fput(file);
373 
374 	/*
375 	 * If blkdev_get_by_dev() failed early, GD_NEED_PART_SCAN is still set,
376 	 * and this will cause that re-assemble partitioned raid device will
377 	 * creat partition for underlying disk.
378 	 */
379 	clear_bit(GD_NEED_PART_SCAN, &disk->state);
380 	if (!(mode & BLK_OPEN_EXCL))
381 		bd_abort_claiming(disk->part0, disk_scan_partitions);
382 	return ret;
383 }
384 
385 /**
386  * add_disk_fwnode - add disk information to kernel list with fwnode
387  * @parent: parent device for the disk
388  * @disk: per-device partitioning information
389  * @groups: Additional per-device sysfs groups
390  * @fwnode: attached disk fwnode
391  *
392  * This function registers the partitioning information in @disk
393  * with the kernel. Also attach a fwnode to the disk device.
394  */
395 int __must_check add_disk_fwnode(struct device *parent, struct gendisk *disk,
396 				 const struct attribute_group **groups,
397 				 struct fwnode_handle *fwnode)
398 
399 {
400 	struct device *ddev = disk_to_dev(disk);
401 	int ret;
402 
403 	if (queue_is_mq(disk->queue)) {
404 		/*
405 		 * ->submit_bio and ->poll_bio are bypassed for blk-mq drivers.
406 		 */
407 		if (disk->fops->submit_bio || disk->fops->poll_bio)
408 			return -EINVAL;
409 
410 		/*
411 		 * Initialize the I/O scheduler code and pick a default one if
412 		 * needed.
413 		 */
414 		elevator_init_mq(disk->queue);
415 	} else {
416 		if (!disk->fops->submit_bio)
417 			return -EINVAL;
418 		bdev_set_flag(disk->part0, BD_HAS_SUBMIT_BIO);
419 	}
420 
421 	/*
422 	 * If the driver provides an explicit major number it also must provide
423 	 * the number of minors numbers supported, and those will be used to
424 	 * setup the gendisk.
425 	 * Otherwise just allocate the device numbers for both the whole device
426 	 * and all partitions from the extended dev_t space.
427 	 */
428 	ret = -EINVAL;
429 	if (disk->major) {
430 		if (WARN_ON(!disk->minors))
431 			goto out_exit_elevator;
432 
433 		if (disk->minors > DISK_MAX_PARTS) {
434 			pr_err("block: can't allocate more than %d partitions\n",
435 				DISK_MAX_PARTS);
436 			disk->minors = DISK_MAX_PARTS;
437 		}
438 		if (disk->first_minor > MINORMASK ||
439 		    disk->minors > MINORMASK + 1 ||
440 		    disk->first_minor + disk->minors > MINORMASK + 1)
441 			goto out_exit_elevator;
442 	} else {
443 		if (WARN_ON(disk->minors))
444 			goto out_exit_elevator;
445 
446 		ret = blk_alloc_ext_minor();
447 		if (ret < 0)
448 			goto out_exit_elevator;
449 		disk->major = BLOCK_EXT_MAJOR;
450 		disk->first_minor = ret;
451 	}
452 
453 	/* delay uevents, until we scanned partition table */
454 	dev_set_uevent_suppress(ddev, 1);
455 
456 	ddev->parent = parent;
457 	ddev->groups = groups;
458 	dev_set_name(ddev, "%s", disk->disk_name);
459 	if (fwnode)
460 		device_set_node(ddev, fwnode);
461 	if (!(disk->flags & GENHD_FL_HIDDEN))
462 		ddev->devt = MKDEV(disk->major, disk->first_minor);
463 	ret = device_add(ddev);
464 	if (ret)
465 		goto out_free_ext_minor;
466 
467 	ret = disk_alloc_events(disk);
468 	if (ret)
469 		goto out_device_del;
470 
471 	ret = sysfs_create_link(block_depr, &ddev->kobj,
472 				kobject_name(&ddev->kobj));
473 	if (ret)
474 		goto out_device_del;
475 
476 	/*
477 	 * avoid probable deadlock caused by allocating memory with
478 	 * GFP_KERNEL in runtime_resume callback of its all ancestor
479 	 * devices
480 	 */
481 	pm_runtime_set_memalloc_noio(ddev, true);
482 
483 	disk->part0->bd_holder_dir =
484 		kobject_create_and_add("holders", &ddev->kobj);
485 	if (!disk->part0->bd_holder_dir) {
486 		ret = -ENOMEM;
487 		goto out_del_block_link;
488 	}
489 	disk->slave_dir = kobject_create_and_add("slaves", &ddev->kobj);
490 	if (!disk->slave_dir) {
491 		ret = -ENOMEM;
492 		goto out_put_holder_dir;
493 	}
494 
495 	ret = blk_register_queue(disk);
496 	if (ret)
497 		goto out_put_slave_dir;
498 
499 	if (!(disk->flags & GENHD_FL_HIDDEN)) {
500 		ret = bdi_register(disk->bdi, "%u:%u",
501 				   disk->major, disk->first_minor);
502 		if (ret)
503 			goto out_unregister_queue;
504 		bdi_set_owner(disk->bdi, ddev);
505 		ret = sysfs_create_link(&ddev->kobj,
506 					&disk->bdi->dev->kobj, "bdi");
507 		if (ret)
508 			goto out_unregister_bdi;
509 
510 		/* Make sure the first partition scan will be proceed */
511 		if (get_capacity(disk) && disk_has_partscan(disk))
512 			set_bit(GD_NEED_PART_SCAN, &disk->state);
513 
514 		bdev_add(disk->part0, ddev->devt);
515 		if (get_capacity(disk))
516 			disk_scan_partitions(disk, BLK_OPEN_READ);
517 
518 		/*
519 		 * Announce the disk and partitions after all partitions are
520 		 * created. (for hidden disks uevents remain suppressed forever)
521 		 */
522 		dev_set_uevent_suppress(ddev, 0);
523 		disk_uevent(disk, KOBJ_ADD);
524 	} else {
525 		/*
526 		 * Even if the block_device for a hidden gendisk is not
527 		 * registered, it needs to have a valid bd_dev so that the
528 		 * freeing of the dynamic major works.
529 		 */
530 		disk->part0->bd_dev = MKDEV(disk->major, disk->first_minor);
531 	}
532 
533 	blk_apply_bdi_limits(disk->bdi, &disk->queue->limits);
534 	disk_add_events(disk);
535 	set_bit(GD_ADDED, &disk->state);
536 	return 0;
537 
538 out_unregister_bdi:
539 	if (!(disk->flags & GENHD_FL_HIDDEN))
540 		bdi_unregister(disk->bdi);
541 out_unregister_queue:
542 	blk_unregister_queue(disk);
543 	rq_qos_exit(disk->queue);
544 out_put_slave_dir:
545 	kobject_put(disk->slave_dir);
546 	disk->slave_dir = NULL;
547 out_put_holder_dir:
548 	kobject_put(disk->part0->bd_holder_dir);
549 out_del_block_link:
550 	sysfs_remove_link(block_depr, dev_name(ddev));
551 	pm_runtime_set_memalloc_noio(ddev, false);
552 out_device_del:
553 	device_del(ddev);
554 out_free_ext_minor:
555 	if (disk->major == BLOCK_EXT_MAJOR)
556 		blk_free_ext_minor(disk->first_minor);
557 out_exit_elevator:
558 	if (disk->queue->elevator)
559 		elevator_exit(disk->queue);
560 	return ret;
561 }
562 EXPORT_SYMBOL_GPL(add_disk_fwnode);
563 
564 /**
565  * device_add_disk - add disk information to kernel list
566  * @parent: parent device for the disk
567  * @disk: per-device partitioning information
568  * @groups: Additional per-device sysfs groups
569  *
570  * This function registers the partitioning information in @disk
571  * with the kernel.
572  */
573 int __must_check device_add_disk(struct device *parent, struct gendisk *disk,
574 				 const struct attribute_group **groups)
575 {
576 	return add_disk_fwnode(parent, disk, groups, NULL);
577 }
578 EXPORT_SYMBOL(device_add_disk);
579 
580 static void blk_report_disk_dead(struct gendisk *disk, bool surprise)
581 {
582 	struct block_device *bdev;
583 	unsigned long idx;
584 
585 	/*
586 	 * On surprise disk removal, bdev_mark_dead() may call into file
587 	 * systems below. Make it clear that we're expecting to not hold
588 	 * disk->open_mutex.
589 	 */
590 	lockdep_assert_not_held(&disk->open_mutex);
591 
592 	rcu_read_lock();
593 	xa_for_each(&disk->part_tbl, idx, bdev) {
594 		if (!kobject_get_unless_zero(&bdev->bd_device.kobj))
595 			continue;
596 		rcu_read_unlock();
597 
598 		bdev_mark_dead(bdev, surprise);
599 
600 		put_device(&bdev->bd_device);
601 		rcu_read_lock();
602 	}
603 	rcu_read_unlock();
604 }
605 
606 static bool __blk_mark_disk_dead(struct gendisk *disk)
607 {
608 	/*
609 	 * Fail any new I/O.
610 	 */
611 	if (test_and_set_bit(GD_DEAD, &disk->state))
612 		return false;
613 
614 	if (test_bit(GD_OWNS_QUEUE, &disk->state))
615 		blk_queue_flag_set(QUEUE_FLAG_DYING, disk->queue);
616 
617 	/*
618 	 * Stop buffered writers from dirtying pages that can't be written out.
619 	 */
620 	set_capacity(disk, 0);
621 
622 	/*
623 	 * Prevent new I/O from crossing bio_queue_enter().
624 	 */
625 	return blk_queue_start_drain(disk->queue);
626 }
627 
628 /**
629  * blk_mark_disk_dead - mark a disk as dead
630  * @disk: disk to mark as dead
631  *
632  * Mark as disk as dead (e.g. surprise removed) and don't accept any new I/O
633  * to this disk.
634  */
635 void blk_mark_disk_dead(struct gendisk *disk)
636 {
637 	__blk_mark_disk_dead(disk);
638 	blk_report_disk_dead(disk, true);
639 }
640 EXPORT_SYMBOL_GPL(blk_mark_disk_dead);
641 
642 /**
643  * del_gendisk - remove the gendisk
644  * @disk: the struct gendisk to remove
645  *
646  * Removes the gendisk and all its associated resources. This deletes the
647  * partitions associated with the gendisk, and unregisters the associated
648  * request_queue.
649  *
650  * This is the counter to the respective __device_add_disk() call.
651  *
652  * The final removal of the struct gendisk happens when its refcount reaches 0
653  * with put_disk(), which should be called after del_gendisk(), if
654  * __device_add_disk() was used.
655  *
656  * Drivers exist which depend on the release of the gendisk to be synchronous,
657  * it should not be deferred.
658  *
659  * Context: can sleep
660  */
661 void del_gendisk(struct gendisk *disk)
662 {
663 	struct request_queue *q = disk->queue;
664 	struct block_device *part;
665 	unsigned long idx;
666 	bool start_drain;
667 
668 	might_sleep();
669 
670 	if (WARN_ON_ONCE(!disk_live(disk) && !(disk->flags & GENHD_FL_HIDDEN)))
671 		return;
672 
673 	disk_del_events(disk);
674 
675 	/*
676 	 * Prevent new openers by unlinked the bdev inode.
677 	 */
678 	mutex_lock(&disk->open_mutex);
679 	xa_for_each(&disk->part_tbl, idx, part)
680 		bdev_unhash(part);
681 	mutex_unlock(&disk->open_mutex);
682 
683 	/*
684 	 * Tell the file system to write back all dirty data and shut down if
685 	 * it hasn't been notified earlier.
686 	 */
687 	if (!test_bit(GD_DEAD, &disk->state))
688 		blk_report_disk_dead(disk, false);
689 
690 	/*
691 	 * Drop all partitions now that the disk is marked dead.
692 	 */
693 	mutex_lock(&disk->open_mutex);
694 	start_drain = __blk_mark_disk_dead(disk);
695 	if (start_drain)
696 		blk_freeze_acquire_lock(q);
697 	xa_for_each_start(&disk->part_tbl, idx, part, 1)
698 		drop_partition(part);
699 	mutex_unlock(&disk->open_mutex);
700 
701 	if (!(disk->flags & GENHD_FL_HIDDEN)) {
702 		sysfs_remove_link(&disk_to_dev(disk)->kobj, "bdi");
703 
704 		/*
705 		 * Unregister bdi before releasing device numbers (as they can
706 		 * get reused and we'd get clashes in sysfs).
707 		 */
708 		bdi_unregister(disk->bdi);
709 	}
710 
711 	blk_unregister_queue(disk);
712 
713 	kobject_put(disk->part0->bd_holder_dir);
714 	kobject_put(disk->slave_dir);
715 	disk->slave_dir = NULL;
716 
717 	part_stat_set_all(disk->part0, 0);
718 	disk->part0->bd_stamp = 0;
719 	sysfs_remove_link(block_depr, dev_name(disk_to_dev(disk)));
720 	pm_runtime_set_memalloc_noio(disk_to_dev(disk), false);
721 	device_del(disk_to_dev(disk));
722 
723 	blk_mq_freeze_queue_wait(q);
724 
725 	blk_throtl_cancel_bios(disk);
726 
727 	blk_sync_queue(q);
728 	blk_flush_integrity();
729 
730 	if (queue_is_mq(q))
731 		blk_mq_cancel_work_sync(q);
732 
733 	blk_mq_quiesce_queue(q);
734 	if (q->elevator) {
735 		mutex_lock(&q->sysfs_lock);
736 		elevator_exit(q);
737 		mutex_unlock(&q->sysfs_lock);
738 	}
739 	rq_qos_exit(q);
740 	blk_mq_unquiesce_queue(q);
741 
742 	/*
743 	 * If the disk does not own the queue, allow using passthrough requests
744 	 * again.  Else leave the queue frozen to fail all I/O.
745 	 */
746 	if (!test_bit(GD_OWNS_QUEUE, &disk->state))
747 		__blk_mq_unfreeze_queue(q, true);
748 	else if (queue_is_mq(q))
749 		blk_mq_exit_queue(q);
750 
751 	if (start_drain)
752 		blk_unfreeze_release_lock(q);
753 }
754 EXPORT_SYMBOL(del_gendisk);
755 
756 /**
757  * invalidate_disk - invalidate the disk
758  * @disk: the struct gendisk to invalidate
759  *
760  * A helper to invalidates the disk. It will clean the disk's associated
761  * buffer/page caches and reset its internal states so that the disk
762  * can be reused by the drivers.
763  *
764  * Context: can sleep
765  */
766 void invalidate_disk(struct gendisk *disk)
767 {
768 	struct block_device *bdev = disk->part0;
769 
770 	invalidate_bdev(bdev);
771 	bdev->bd_mapping->wb_err = 0;
772 	set_capacity(disk, 0);
773 }
774 EXPORT_SYMBOL(invalidate_disk);
775 
776 /* sysfs access to bad-blocks list. */
777 static ssize_t disk_badblocks_show(struct device *dev,
778 					struct device_attribute *attr,
779 					char *page)
780 {
781 	struct gendisk *disk = dev_to_disk(dev);
782 
783 	if (!disk->bb)
784 		return sysfs_emit(page, "\n");
785 
786 	return badblocks_show(disk->bb, page, 0);
787 }
788 
789 static ssize_t disk_badblocks_store(struct device *dev,
790 					struct device_attribute *attr,
791 					const char *page, size_t len)
792 {
793 	struct gendisk *disk = dev_to_disk(dev);
794 
795 	if (!disk->bb)
796 		return -ENXIO;
797 
798 	return badblocks_store(disk->bb, page, len, 0);
799 }
800 
801 #ifdef CONFIG_BLOCK_LEGACY_AUTOLOAD
802 static bool blk_probe_dev(dev_t devt)
803 {
804 	unsigned int major = MAJOR(devt);
805 	struct blk_major_name **n;
806 
807 	mutex_lock(&major_names_lock);
808 	for (n = &major_names[major_to_index(major)]; *n; n = &(*n)->next) {
809 		if ((*n)->major == major && (*n)->probe) {
810 			(*n)->probe(devt);
811 			mutex_unlock(&major_names_lock);
812 			return true;
813 		}
814 	}
815 	mutex_unlock(&major_names_lock);
816 	return false;
817 }
818 
819 void blk_request_module(dev_t devt)
820 {
821 	int error;
822 
823 	if (blk_probe_dev(devt))
824 		return;
825 
826 	error = request_module("block-major-%d-%d", MAJOR(devt), MINOR(devt));
827 	/* Make old-style 2.4 aliases work */
828 	if (error > 0)
829 		error = request_module("block-major-%d", MAJOR(devt));
830 	if (!error)
831 		blk_probe_dev(devt);
832 }
833 #endif /* CONFIG_BLOCK_LEGACY_AUTOLOAD */
834 
835 #ifdef CONFIG_PROC_FS
836 /* iterator */
837 static void *disk_seqf_start(struct seq_file *seqf, loff_t *pos)
838 {
839 	loff_t skip = *pos;
840 	struct class_dev_iter *iter;
841 	struct device *dev;
842 
843 	iter = kmalloc(sizeof(*iter), GFP_KERNEL);
844 	if (!iter)
845 		return ERR_PTR(-ENOMEM);
846 
847 	seqf->private = iter;
848 	class_dev_iter_init(iter, &block_class, NULL, &disk_type);
849 	do {
850 		dev = class_dev_iter_next(iter);
851 		if (!dev)
852 			return NULL;
853 	} while (skip--);
854 
855 	return dev_to_disk(dev);
856 }
857 
858 static void *disk_seqf_next(struct seq_file *seqf, void *v, loff_t *pos)
859 {
860 	struct device *dev;
861 
862 	(*pos)++;
863 	dev = class_dev_iter_next(seqf->private);
864 	if (dev)
865 		return dev_to_disk(dev);
866 
867 	return NULL;
868 }
869 
870 static void disk_seqf_stop(struct seq_file *seqf, void *v)
871 {
872 	struct class_dev_iter *iter = seqf->private;
873 
874 	/* stop is called even after start failed :-( */
875 	if (iter) {
876 		class_dev_iter_exit(iter);
877 		kfree(iter);
878 		seqf->private = NULL;
879 	}
880 }
881 
882 static void *show_partition_start(struct seq_file *seqf, loff_t *pos)
883 {
884 	void *p;
885 
886 	p = disk_seqf_start(seqf, pos);
887 	if (!IS_ERR_OR_NULL(p) && !*pos)
888 		seq_puts(seqf, "major minor  #blocks  name\n\n");
889 	return p;
890 }
891 
892 static int show_partition(struct seq_file *seqf, void *v)
893 {
894 	struct gendisk *sgp = v;
895 	struct block_device *part;
896 	unsigned long idx;
897 
898 	if (!get_capacity(sgp) || (sgp->flags & GENHD_FL_HIDDEN))
899 		return 0;
900 
901 	rcu_read_lock();
902 	xa_for_each(&sgp->part_tbl, idx, part) {
903 		if (!bdev_nr_sectors(part))
904 			continue;
905 		seq_printf(seqf, "%4d  %7d %10llu %pg\n",
906 			   MAJOR(part->bd_dev), MINOR(part->bd_dev),
907 			   bdev_nr_sectors(part) >> 1, part);
908 	}
909 	rcu_read_unlock();
910 	return 0;
911 }
912 
913 static const struct seq_operations partitions_op = {
914 	.start	= show_partition_start,
915 	.next	= disk_seqf_next,
916 	.stop	= disk_seqf_stop,
917 	.show	= show_partition
918 };
919 #endif
920 
921 static int __init genhd_device_init(void)
922 {
923 	int error;
924 
925 	error = class_register(&block_class);
926 	if (unlikely(error))
927 		return error;
928 	blk_dev_init();
929 
930 	register_blkdev(BLOCK_EXT_MAJOR, "blkext");
931 
932 	/* create top-level block dir */
933 	block_depr = kobject_create_and_add("block", NULL);
934 	return 0;
935 }
936 
937 subsys_initcall(genhd_device_init);
938 
939 static ssize_t disk_range_show(struct device *dev,
940 			       struct device_attribute *attr, char *buf)
941 {
942 	struct gendisk *disk = dev_to_disk(dev);
943 
944 	return sysfs_emit(buf, "%d\n", disk->minors);
945 }
946 
947 static ssize_t disk_ext_range_show(struct device *dev,
948 				   struct device_attribute *attr, char *buf)
949 {
950 	struct gendisk *disk = dev_to_disk(dev);
951 
952 	return sysfs_emit(buf, "%d\n",
953 		(disk->flags & GENHD_FL_NO_PART) ? 1 : DISK_MAX_PARTS);
954 }
955 
956 static ssize_t disk_removable_show(struct device *dev,
957 				   struct device_attribute *attr, char *buf)
958 {
959 	struct gendisk *disk = dev_to_disk(dev);
960 
961 	return sysfs_emit(buf, "%d\n",
962 		       (disk->flags & GENHD_FL_REMOVABLE ? 1 : 0));
963 }
964 
965 static ssize_t disk_hidden_show(struct device *dev,
966 				   struct device_attribute *attr, char *buf)
967 {
968 	struct gendisk *disk = dev_to_disk(dev);
969 
970 	return sysfs_emit(buf, "%d\n",
971 		       (disk->flags & GENHD_FL_HIDDEN ? 1 : 0));
972 }
973 
974 static ssize_t disk_ro_show(struct device *dev,
975 				   struct device_attribute *attr, char *buf)
976 {
977 	struct gendisk *disk = dev_to_disk(dev);
978 
979 	return sysfs_emit(buf, "%d\n", get_disk_ro(disk) ? 1 : 0);
980 }
981 
982 ssize_t part_size_show(struct device *dev,
983 		       struct device_attribute *attr, char *buf)
984 {
985 	return sysfs_emit(buf, "%llu\n", bdev_nr_sectors(dev_to_bdev(dev)));
986 }
987 
988 ssize_t part_stat_show(struct device *dev,
989 		       struct device_attribute *attr, char *buf)
990 {
991 	struct block_device *bdev = dev_to_bdev(dev);
992 	struct disk_stats stat;
993 	unsigned int inflight;
994 
995 	inflight = part_in_flight(bdev);
996 	if (inflight) {
997 		part_stat_lock();
998 		update_io_ticks(bdev, jiffies, true);
999 		part_stat_unlock();
1000 	}
1001 	part_stat_read_all(bdev, &stat);
1002 	return sysfs_emit(buf,
1003 		"%8lu %8lu %8llu %8u "
1004 		"%8lu %8lu %8llu %8u "
1005 		"%8u %8u %8u "
1006 		"%8lu %8lu %8llu %8u "
1007 		"%8lu %8u"
1008 		"\n",
1009 		stat.ios[STAT_READ],
1010 		stat.merges[STAT_READ],
1011 		(unsigned long long)stat.sectors[STAT_READ],
1012 		(unsigned int)div_u64(stat.nsecs[STAT_READ], NSEC_PER_MSEC),
1013 		stat.ios[STAT_WRITE],
1014 		stat.merges[STAT_WRITE],
1015 		(unsigned long long)stat.sectors[STAT_WRITE],
1016 		(unsigned int)div_u64(stat.nsecs[STAT_WRITE], NSEC_PER_MSEC),
1017 		inflight,
1018 		jiffies_to_msecs(stat.io_ticks),
1019 		(unsigned int)div_u64(stat.nsecs[STAT_READ] +
1020 				      stat.nsecs[STAT_WRITE] +
1021 				      stat.nsecs[STAT_DISCARD] +
1022 				      stat.nsecs[STAT_FLUSH],
1023 						NSEC_PER_MSEC),
1024 		stat.ios[STAT_DISCARD],
1025 		stat.merges[STAT_DISCARD],
1026 		(unsigned long long)stat.sectors[STAT_DISCARD],
1027 		(unsigned int)div_u64(stat.nsecs[STAT_DISCARD], NSEC_PER_MSEC),
1028 		stat.ios[STAT_FLUSH],
1029 		(unsigned int)div_u64(stat.nsecs[STAT_FLUSH], NSEC_PER_MSEC));
1030 }
1031 
1032 ssize_t part_inflight_show(struct device *dev, struct device_attribute *attr,
1033 			   char *buf)
1034 {
1035 	struct block_device *bdev = dev_to_bdev(dev);
1036 	struct request_queue *q = bdev_get_queue(bdev);
1037 	unsigned int inflight[2];
1038 
1039 	if (queue_is_mq(q))
1040 		blk_mq_in_flight_rw(q, bdev, inflight);
1041 	else
1042 		part_in_flight_rw(bdev, inflight);
1043 
1044 	return sysfs_emit(buf, "%8u %8u\n", inflight[0], inflight[1]);
1045 }
1046 
1047 static ssize_t disk_capability_show(struct device *dev,
1048 				    struct device_attribute *attr, char *buf)
1049 {
1050 	dev_warn_once(dev, "the capability attribute has been deprecated.\n");
1051 	return sysfs_emit(buf, "0\n");
1052 }
1053 
1054 static ssize_t disk_alignment_offset_show(struct device *dev,
1055 					  struct device_attribute *attr,
1056 					  char *buf)
1057 {
1058 	struct gendisk *disk = dev_to_disk(dev);
1059 
1060 	return sysfs_emit(buf, "%d\n", bdev_alignment_offset(disk->part0));
1061 }
1062 
1063 static ssize_t disk_discard_alignment_show(struct device *dev,
1064 					   struct device_attribute *attr,
1065 					   char *buf)
1066 {
1067 	struct gendisk *disk = dev_to_disk(dev);
1068 
1069 	return sysfs_emit(buf, "%d\n", bdev_alignment_offset(disk->part0));
1070 }
1071 
1072 static ssize_t diskseq_show(struct device *dev,
1073 			    struct device_attribute *attr, char *buf)
1074 {
1075 	struct gendisk *disk = dev_to_disk(dev);
1076 
1077 	return sysfs_emit(buf, "%llu\n", disk->diskseq);
1078 }
1079 
1080 static ssize_t partscan_show(struct device *dev,
1081 		struct device_attribute *attr, char *buf)
1082 {
1083 	return sysfs_emit(buf, "%u\n", disk_has_partscan(dev_to_disk(dev)));
1084 }
1085 
1086 static DEVICE_ATTR(range, 0444, disk_range_show, NULL);
1087 static DEVICE_ATTR(ext_range, 0444, disk_ext_range_show, NULL);
1088 static DEVICE_ATTR(removable, 0444, disk_removable_show, NULL);
1089 static DEVICE_ATTR(hidden, 0444, disk_hidden_show, NULL);
1090 static DEVICE_ATTR(ro, 0444, disk_ro_show, NULL);
1091 static DEVICE_ATTR(size, 0444, part_size_show, NULL);
1092 static DEVICE_ATTR(alignment_offset, 0444, disk_alignment_offset_show, NULL);
1093 static DEVICE_ATTR(discard_alignment, 0444, disk_discard_alignment_show, NULL);
1094 static DEVICE_ATTR(capability, 0444, disk_capability_show, NULL);
1095 static DEVICE_ATTR(stat, 0444, part_stat_show, NULL);
1096 static DEVICE_ATTR(inflight, 0444, part_inflight_show, NULL);
1097 static DEVICE_ATTR(badblocks, 0644, disk_badblocks_show, disk_badblocks_store);
1098 static DEVICE_ATTR(diskseq, 0444, diskseq_show, NULL);
1099 static DEVICE_ATTR(partscan, 0444, partscan_show, NULL);
1100 
1101 #ifdef CONFIG_FAIL_MAKE_REQUEST
1102 ssize_t part_fail_show(struct device *dev,
1103 		       struct device_attribute *attr, char *buf)
1104 {
1105 	return sysfs_emit(buf, "%d\n",
1106 		       bdev_test_flag(dev_to_bdev(dev), BD_MAKE_IT_FAIL));
1107 }
1108 
1109 ssize_t part_fail_store(struct device *dev,
1110 			struct device_attribute *attr,
1111 			const char *buf, size_t count)
1112 {
1113 	int i;
1114 
1115 	if (count > 0 && sscanf(buf, "%d", &i) > 0) {
1116 		if (i)
1117 			bdev_set_flag(dev_to_bdev(dev), BD_MAKE_IT_FAIL);
1118 		else
1119 			bdev_clear_flag(dev_to_bdev(dev), BD_MAKE_IT_FAIL);
1120 	}
1121 	return count;
1122 }
1123 
1124 static struct device_attribute dev_attr_fail =
1125 	__ATTR(make-it-fail, 0644, part_fail_show, part_fail_store);
1126 #endif /* CONFIG_FAIL_MAKE_REQUEST */
1127 
1128 #ifdef CONFIG_FAIL_IO_TIMEOUT
1129 static struct device_attribute dev_attr_fail_timeout =
1130 	__ATTR(io-timeout-fail, 0644, part_timeout_show, part_timeout_store);
1131 #endif
1132 
1133 static struct attribute *disk_attrs[] = {
1134 	&dev_attr_range.attr,
1135 	&dev_attr_ext_range.attr,
1136 	&dev_attr_removable.attr,
1137 	&dev_attr_hidden.attr,
1138 	&dev_attr_ro.attr,
1139 	&dev_attr_size.attr,
1140 	&dev_attr_alignment_offset.attr,
1141 	&dev_attr_discard_alignment.attr,
1142 	&dev_attr_capability.attr,
1143 	&dev_attr_stat.attr,
1144 	&dev_attr_inflight.attr,
1145 	&dev_attr_badblocks.attr,
1146 	&dev_attr_events.attr,
1147 	&dev_attr_events_async.attr,
1148 	&dev_attr_events_poll_msecs.attr,
1149 	&dev_attr_diskseq.attr,
1150 	&dev_attr_partscan.attr,
1151 #ifdef CONFIG_FAIL_MAKE_REQUEST
1152 	&dev_attr_fail.attr,
1153 #endif
1154 #ifdef CONFIG_FAIL_IO_TIMEOUT
1155 	&dev_attr_fail_timeout.attr,
1156 #endif
1157 	NULL
1158 };
1159 
1160 static umode_t disk_visible(struct kobject *kobj, struct attribute *a, int n)
1161 {
1162 	struct device *dev = container_of(kobj, typeof(*dev), kobj);
1163 	struct gendisk *disk = dev_to_disk(dev);
1164 
1165 	if (a == &dev_attr_badblocks.attr && !disk->bb)
1166 		return 0;
1167 	return a->mode;
1168 }
1169 
1170 static struct attribute_group disk_attr_group = {
1171 	.attrs = disk_attrs,
1172 	.is_visible = disk_visible,
1173 };
1174 
1175 static const struct attribute_group *disk_attr_groups[] = {
1176 	&disk_attr_group,
1177 #ifdef CONFIG_BLK_DEV_IO_TRACE
1178 	&blk_trace_attr_group,
1179 #endif
1180 #ifdef CONFIG_BLK_DEV_INTEGRITY
1181 	&blk_integrity_attr_group,
1182 #endif
1183 	NULL
1184 };
1185 
1186 /**
1187  * disk_release - releases all allocated resources of the gendisk
1188  * @dev: the device representing this disk
1189  *
1190  * This function releases all allocated resources of the gendisk.
1191  *
1192  * Drivers which used __device_add_disk() have a gendisk with a request_queue
1193  * assigned. Since the request_queue sits on top of the gendisk for these
1194  * drivers we also call blk_put_queue() for them, and we expect the
1195  * request_queue refcount to reach 0 at this point, and so the request_queue
1196  * will also be freed prior to the disk.
1197  *
1198  * Context: can sleep
1199  */
1200 static void disk_release(struct device *dev)
1201 {
1202 	struct gendisk *disk = dev_to_disk(dev);
1203 
1204 	might_sleep();
1205 	WARN_ON_ONCE(disk_live(disk));
1206 
1207 	blk_trace_remove(disk->queue);
1208 
1209 	/*
1210 	 * To undo the all initialization from blk_mq_init_allocated_queue in
1211 	 * case of a probe failure where add_disk is never called we have to
1212 	 * call blk_mq_exit_queue here. We can't do this for the more common
1213 	 * teardown case (yet) as the tagset can be gone by the time the disk
1214 	 * is released once it was added.
1215 	 */
1216 	if (queue_is_mq(disk->queue) &&
1217 	    test_bit(GD_OWNS_QUEUE, &disk->state) &&
1218 	    !test_bit(GD_ADDED, &disk->state))
1219 		blk_mq_exit_queue(disk->queue);
1220 
1221 	blkcg_exit_disk(disk);
1222 
1223 	bioset_exit(&disk->bio_split);
1224 
1225 	disk_release_events(disk);
1226 	kfree(disk->random);
1227 	disk_free_zone_resources(disk);
1228 	xa_destroy(&disk->part_tbl);
1229 
1230 	disk->queue->disk = NULL;
1231 	blk_put_queue(disk->queue);
1232 
1233 	if (test_bit(GD_ADDED, &disk->state) && disk->fops->free_disk)
1234 		disk->fops->free_disk(disk);
1235 
1236 	bdev_drop(disk->part0);	/* frees the disk */
1237 }
1238 
1239 static int block_uevent(const struct device *dev, struct kobj_uevent_env *env)
1240 {
1241 	const struct gendisk *disk = dev_to_disk(dev);
1242 
1243 	return add_uevent_var(env, "DISKSEQ=%llu", disk->diskseq);
1244 }
1245 
1246 const struct class block_class = {
1247 	.name		= "block",
1248 	.dev_uevent	= block_uevent,
1249 };
1250 
1251 static char *block_devnode(const struct device *dev, umode_t *mode,
1252 			   kuid_t *uid, kgid_t *gid)
1253 {
1254 	struct gendisk *disk = dev_to_disk(dev);
1255 
1256 	if (disk->fops->devnode)
1257 		return disk->fops->devnode(disk, mode);
1258 	return NULL;
1259 }
1260 
1261 const struct device_type disk_type = {
1262 	.name		= "disk",
1263 	.groups		= disk_attr_groups,
1264 	.release	= disk_release,
1265 	.devnode	= block_devnode,
1266 };
1267 
1268 #ifdef CONFIG_PROC_FS
1269 /*
1270  * aggregate disk stat collector.  Uses the same stats that the sysfs
1271  * entries do, above, but makes them available through one seq_file.
1272  *
1273  * The output looks suspiciously like /proc/partitions with a bunch of
1274  * extra fields.
1275  */
1276 static int diskstats_show(struct seq_file *seqf, void *v)
1277 {
1278 	struct gendisk *gp = v;
1279 	struct block_device *hd;
1280 	unsigned int inflight;
1281 	struct disk_stats stat;
1282 	unsigned long idx;
1283 
1284 	/*
1285 	if (&disk_to_dev(gp)->kobj.entry == block_class.devices.next)
1286 		seq_puts(seqf,	"major minor name"
1287 				"     rio rmerge rsect ruse wio wmerge "
1288 				"wsect wuse running use aveq"
1289 				"\n\n");
1290 	*/
1291 
1292 	rcu_read_lock();
1293 	xa_for_each(&gp->part_tbl, idx, hd) {
1294 		if (bdev_is_partition(hd) && !bdev_nr_sectors(hd))
1295 			continue;
1296 
1297 		inflight = part_in_flight(hd);
1298 		if (inflight) {
1299 			part_stat_lock();
1300 			update_io_ticks(hd, jiffies, true);
1301 			part_stat_unlock();
1302 		}
1303 		part_stat_read_all(hd, &stat);
1304 		seq_put_decimal_ull_width(seqf, "",  MAJOR(hd->bd_dev), 4);
1305 		seq_put_decimal_ull_width(seqf, " ", MINOR(hd->bd_dev), 7);
1306 		seq_printf(seqf, " %pg", hd);
1307 		seq_put_decimal_ull(seqf, " ", stat.ios[STAT_READ]);
1308 		seq_put_decimal_ull(seqf, " ", stat.merges[STAT_READ]);
1309 		seq_put_decimal_ull(seqf, " ", stat.sectors[STAT_READ]);
1310 		seq_put_decimal_ull(seqf, " ", (unsigned int)div_u64(stat.nsecs[STAT_READ],
1311 								     NSEC_PER_MSEC));
1312 		seq_put_decimal_ull(seqf, " ", stat.ios[STAT_WRITE]);
1313 		seq_put_decimal_ull(seqf, " ", stat.merges[STAT_WRITE]);
1314 		seq_put_decimal_ull(seqf, " ", stat.sectors[STAT_WRITE]);
1315 		seq_put_decimal_ull(seqf, " ", (unsigned int)div_u64(stat.nsecs[STAT_WRITE],
1316 								     NSEC_PER_MSEC));
1317 		seq_put_decimal_ull(seqf, " ", inflight);
1318 		seq_put_decimal_ull(seqf, " ", jiffies_to_msecs(stat.io_ticks));
1319 		seq_put_decimal_ull(seqf, " ", (unsigned int)div_u64(stat.nsecs[STAT_READ] +
1320 								     stat.nsecs[STAT_WRITE] +
1321 								     stat.nsecs[STAT_DISCARD] +
1322 								     stat.nsecs[STAT_FLUSH],
1323 								     NSEC_PER_MSEC));
1324 		seq_put_decimal_ull(seqf, " ", stat.ios[STAT_DISCARD]);
1325 		seq_put_decimal_ull(seqf, " ", stat.merges[STAT_DISCARD]);
1326 		seq_put_decimal_ull(seqf, " ", stat.sectors[STAT_DISCARD]);
1327 		seq_put_decimal_ull(seqf, " ", (unsigned int)div_u64(stat.nsecs[STAT_DISCARD],
1328 								     NSEC_PER_MSEC));
1329 		seq_put_decimal_ull(seqf, " ", stat.ios[STAT_FLUSH]);
1330 		seq_put_decimal_ull(seqf, " ", (unsigned int)div_u64(stat.nsecs[STAT_FLUSH],
1331 								     NSEC_PER_MSEC));
1332 		seq_putc(seqf, '\n');
1333 	}
1334 	rcu_read_unlock();
1335 
1336 	return 0;
1337 }
1338 
1339 static const struct seq_operations diskstats_op = {
1340 	.start	= disk_seqf_start,
1341 	.next	= disk_seqf_next,
1342 	.stop	= disk_seqf_stop,
1343 	.show	= diskstats_show
1344 };
1345 
1346 static int __init proc_genhd_init(void)
1347 {
1348 	proc_create_seq("diskstats", 0, NULL, &diskstats_op);
1349 	proc_create_seq("partitions", 0, NULL, &partitions_op);
1350 	return 0;
1351 }
1352 module_init(proc_genhd_init);
1353 #endif /* CONFIG_PROC_FS */
1354 
1355 dev_t part_devt(struct gendisk *disk, u8 partno)
1356 {
1357 	struct block_device *part;
1358 	dev_t devt = 0;
1359 
1360 	rcu_read_lock();
1361 	part = xa_load(&disk->part_tbl, partno);
1362 	if (part)
1363 		devt = part->bd_dev;
1364 	rcu_read_unlock();
1365 
1366 	return devt;
1367 }
1368 
1369 struct gendisk *__alloc_disk_node(struct request_queue *q, int node_id,
1370 		struct lock_class_key *lkclass)
1371 {
1372 	struct gendisk *disk;
1373 
1374 	disk = kzalloc_node(sizeof(struct gendisk), GFP_KERNEL, node_id);
1375 	if (!disk)
1376 		return NULL;
1377 
1378 	if (bioset_init(&disk->bio_split, BIO_POOL_SIZE, 0, 0))
1379 		goto out_free_disk;
1380 
1381 	disk->bdi = bdi_alloc(node_id);
1382 	if (!disk->bdi)
1383 		goto out_free_bioset;
1384 
1385 	/* bdev_alloc() might need the queue, set before the first call */
1386 	disk->queue = q;
1387 
1388 	disk->part0 = bdev_alloc(disk, 0);
1389 	if (!disk->part0)
1390 		goto out_free_bdi;
1391 
1392 	disk->node_id = node_id;
1393 	mutex_init(&disk->open_mutex);
1394 	xa_init(&disk->part_tbl);
1395 	if (xa_insert(&disk->part_tbl, 0, disk->part0, GFP_KERNEL))
1396 		goto out_destroy_part_tbl;
1397 
1398 	if (blkcg_init_disk(disk))
1399 		goto out_erase_part0;
1400 
1401 	disk_init_zone_resources(disk);
1402 	rand_initialize_disk(disk);
1403 	disk_to_dev(disk)->class = &block_class;
1404 	disk_to_dev(disk)->type = &disk_type;
1405 	device_initialize(disk_to_dev(disk));
1406 	inc_diskseq(disk);
1407 	q->disk = disk;
1408 	lockdep_init_map(&disk->lockdep_map, "(bio completion)", lkclass, 0);
1409 #ifdef CONFIG_BLOCK_HOLDER_DEPRECATED
1410 	INIT_LIST_HEAD(&disk->slave_bdevs);
1411 #endif
1412 	return disk;
1413 
1414 out_erase_part0:
1415 	xa_erase(&disk->part_tbl, 0);
1416 out_destroy_part_tbl:
1417 	xa_destroy(&disk->part_tbl);
1418 	disk->part0->bd_disk = NULL;
1419 	bdev_drop(disk->part0);
1420 out_free_bdi:
1421 	bdi_put(disk->bdi);
1422 out_free_bioset:
1423 	bioset_exit(&disk->bio_split);
1424 out_free_disk:
1425 	kfree(disk);
1426 	return NULL;
1427 }
1428 
1429 struct gendisk *__blk_alloc_disk(struct queue_limits *lim, int node,
1430 		struct lock_class_key *lkclass)
1431 {
1432 	struct queue_limits default_lim = { };
1433 	struct request_queue *q;
1434 	struct gendisk *disk;
1435 
1436 	q = blk_alloc_queue(lim ? lim : &default_lim, node);
1437 	if (IS_ERR(q))
1438 		return ERR_CAST(q);
1439 
1440 	disk = __alloc_disk_node(q, node, lkclass);
1441 	if (!disk) {
1442 		blk_put_queue(q);
1443 		return ERR_PTR(-ENOMEM);
1444 	}
1445 	set_bit(GD_OWNS_QUEUE, &disk->state);
1446 	return disk;
1447 }
1448 EXPORT_SYMBOL(__blk_alloc_disk);
1449 
1450 /**
1451  * put_disk - decrements the gendisk refcount
1452  * @disk: the struct gendisk to decrement the refcount for
1453  *
1454  * This decrements the refcount for the struct gendisk. When this reaches 0
1455  * we'll have disk_release() called.
1456  *
1457  * Note: for blk-mq disk put_disk must be called before freeing the tag_set
1458  * when handling probe errors (that is before add_disk() is called).
1459  *
1460  * Context: Any context, but the last reference must not be dropped from
1461  *          atomic context.
1462  */
1463 void put_disk(struct gendisk *disk)
1464 {
1465 	if (disk)
1466 		put_device(disk_to_dev(disk));
1467 }
1468 EXPORT_SYMBOL(put_disk);
1469 
1470 static void set_disk_ro_uevent(struct gendisk *gd, int ro)
1471 {
1472 	char event[] = "DISK_RO=1";
1473 	char *envp[] = { event, NULL };
1474 
1475 	if (!ro)
1476 		event[8] = '0';
1477 	kobject_uevent_env(&disk_to_dev(gd)->kobj, KOBJ_CHANGE, envp);
1478 }
1479 
1480 /**
1481  * set_disk_ro - set a gendisk read-only
1482  * @disk:	gendisk to operate on
1483  * @read_only:	%true to set the disk read-only, %false set the disk read/write
1484  *
1485  * This function is used to indicate whether a given disk device should have its
1486  * read-only flag set. set_disk_ro() is typically used by device drivers to
1487  * indicate whether the underlying physical device is write-protected.
1488  */
1489 void set_disk_ro(struct gendisk *disk, bool read_only)
1490 {
1491 	if (read_only) {
1492 		if (test_and_set_bit(GD_READ_ONLY, &disk->state))
1493 			return;
1494 	} else {
1495 		if (!test_and_clear_bit(GD_READ_ONLY, &disk->state))
1496 			return;
1497 	}
1498 	set_disk_ro_uevent(disk, read_only);
1499 }
1500 EXPORT_SYMBOL(set_disk_ro);
1501 
1502 void inc_diskseq(struct gendisk *disk)
1503 {
1504 	disk->diskseq = atomic64_inc_return(&diskseq);
1505 }
1506