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