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