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