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