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