MD: fix sleep in atomic
[muen/linux.git] / drivers / md / md.c
1 /*
2    md.c : Multiple Devices driver for Linux
3      Copyright (C) 1998, 1999, 2000 Ingo Molnar
4
5      completely rewritten, based on the MD driver code from Marc Zyngier
6
7    Changes:
8
9    - RAID-1/RAID-5 extensions by Miguel de Icaza, Gadi Oxman, Ingo Molnar
10    - RAID-6 extensions by H. Peter Anvin <hpa@zytor.com>
11    - boot support for linear and striped mode by Harald Hoyer <HarryH@Royal.Net>
12    - kerneld support by Boris Tobotras <boris@xtalk.msk.su>
13    - kmod support by: Cyrus Durgin
14    - RAID0 bugfixes: Mark Anthony Lisher <markal@iname.com>
15    - Devfs support by Richard Gooch <rgooch@atnf.csiro.au>
16
17    - lots of fixes and improvements to the RAID1/RAID5 and generic
18      RAID code (such as request based resynchronization):
19
20      Neil Brown <neilb@cse.unsw.edu.au>.
21
22    - persistent bitmap code
23      Copyright (C) 2003-2004, Paul Clements, SteelEye Technology, Inc.
24
25    This program is free software; you can redistribute it and/or modify
26    it under the terms of the GNU General Public License as published by
27    the Free Software Foundation; either version 2, or (at your option)
28    any later version.
29
30    You should have received a copy of the GNU General Public License
31    (for example /usr/src/linux/COPYING); if not, write to the Free
32    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
33
34    Errors, Warnings, etc.
35    Please use:
36      pr_crit() for error conditions that risk data loss
37      pr_err() for error conditions that are unexpected, like an IO error
38          or internal inconsistency
39      pr_warn() for error conditions that could have been predicated, like
40          adding a device to an array when it has incompatible metadata
41      pr_info() for every interesting, very rare events, like an array starting
42          or stopping, or resync starting or stopping
43      pr_debug() for everything else.
44
45 */
46
47 #include <linux/sched/signal.h>
48 #include <linux/kthread.h>
49 #include <linux/blkdev.h>
50 #include <linux/badblocks.h>
51 #include <linux/sysctl.h>
52 #include <linux/seq_file.h>
53 #include <linux/fs.h>
54 #include <linux/poll.h>
55 #include <linux/ctype.h>
56 #include <linux/string.h>
57 #include <linux/hdreg.h>
58 #include <linux/proc_fs.h>
59 #include <linux/random.h>
60 #include <linux/module.h>
61 #include <linux/reboot.h>
62 #include <linux/file.h>
63 #include <linux/compat.h>
64 #include <linux/delay.h>
65 #include <linux/raid/md_p.h>
66 #include <linux/raid/md_u.h>
67 #include <linux/slab.h>
68 #include <linux/percpu-refcount.h>
69
70 #include <trace/events/block.h>
71 #include "md.h"
72 #include "bitmap.h"
73 #include "md-cluster.h"
74
75 #ifndef MODULE
76 static void autostart_arrays(int part);
77 #endif
78
79 /* pers_list is a list of registered personalities protected
80  * by pers_lock.
81  * pers_lock does extra service to protect accesses to
82  * mddev->thread when the mutex cannot be held.
83  */
84 static LIST_HEAD(pers_list);
85 static DEFINE_SPINLOCK(pers_lock);
86
87 struct md_cluster_operations *md_cluster_ops;
88 EXPORT_SYMBOL(md_cluster_ops);
89 struct module *md_cluster_mod;
90 EXPORT_SYMBOL(md_cluster_mod);
91
92 static DECLARE_WAIT_QUEUE_HEAD(resync_wait);
93 static struct workqueue_struct *md_wq;
94 static struct workqueue_struct *md_misc_wq;
95
96 static int remove_and_add_spares(struct mddev *mddev,
97                                  struct md_rdev *this);
98 static void mddev_detach(struct mddev *mddev);
99
100 /*
101  * Default number of read corrections we'll attempt on an rdev
102  * before ejecting it from the array. We divide the read error
103  * count by 2 for every hour elapsed between read errors.
104  */
105 #define MD_DEFAULT_MAX_CORRECTED_READ_ERRORS 20
106 /*
107  * Current RAID-1,4,5 parallel reconstruction 'guaranteed speed limit'
108  * is 1000 KB/sec, so the extra system load does not show up that much.
109  * Increase it if you want to have more _guaranteed_ speed. Note that
110  * the RAID driver will use the maximum available bandwidth if the IO
111  * subsystem is idle. There is also an 'absolute maximum' reconstruction
112  * speed limit - in case reconstruction slows down your system despite
113  * idle IO detection.
114  *
115  * you can change it via /proc/sys/dev/raid/speed_limit_min and _max.
116  * or /sys/block/mdX/md/sync_speed_{min,max}
117  */
118
119 static int sysctl_speed_limit_min = 1000;
120 static int sysctl_speed_limit_max = 200000;
121 static inline int speed_min(struct mddev *mddev)
122 {
123         return mddev->sync_speed_min ?
124                 mddev->sync_speed_min : sysctl_speed_limit_min;
125 }
126
127 static inline int speed_max(struct mddev *mddev)
128 {
129         return mddev->sync_speed_max ?
130                 mddev->sync_speed_max : sysctl_speed_limit_max;
131 }
132
133 static struct ctl_table_header *raid_table_header;
134
135 static struct ctl_table raid_table[] = {
136         {
137                 .procname       = "speed_limit_min",
138                 .data           = &sysctl_speed_limit_min,
139                 .maxlen         = sizeof(int),
140                 .mode           = S_IRUGO|S_IWUSR,
141                 .proc_handler   = proc_dointvec,
142         },
143         {
144                 .procname       = "speed_limit_max",
145                 .data           = &sysctl_speed_limit_max,
146                 .maxlen         = sizeof(int),
147                 .mode           = S_IRUGO|S_IWUSR,
148                 .proc_handler   = proc_dointvec,
149         },
150         { }
151 };
152
153 static struct ctl_table raid_dir_table[] = {
154         {
155                 .procname       = "raid",
156                 .maxlen         = 0,
157                 .mode           = S_IRUGO|S_IXUGO,
158                 .child          = raid_table,
159         },
160         { }
161 };
162
163 static struct ctl_table raid_root_table[] = {
164         {
165                 .procname       = "dev",
166                 .maxlen         = 0,
167                 .mode           = 0555,
168                 .child          = raid_dir_table,
169         },
170         {  }
171 };
172
173 static const struct block_device_operations md_fops;
174
175 static int start_readonly;
176
177 /*
178  * The original mechanism for creating an md device is to create
179  * a device node in /dev and to open it.  This causes races with device-close.
180  * The preferred method is to write to the "new_array" module parameter.
181  * This can avoid races.
182  * Setting create_on_open to false disables the original mechanism
183  * so all the races disappear.
184  */
185 static bool create_on_open = true;
186
187 /* bio_clone_mddev
188  * like bio_clone, but with a local bio set
189  */
190
191 struct bio *bio_alloc_mddev(gfp_t gfp_mask, int nr_iovecs,
192                             struct mddev *mddev)
193 {
194         struct bio *b;
195
196         if (!mddev || !mddev->bio_set)
197                 return bio_alloc(gfp_mask, nr_iovecs);
198
199         b = bio_alloc_bioset(gfp_mask, nr_iovecs, mddev->bio_set);
200         if (!b)
201                 return NULL;
202         return b;
203 }
204 EXPORT_SYMBOL_GPL(bio_alloc_mddev);
205
206 static struct bio *md_bio_alloc_sync(struct mddev *mddev)
207 {
208         if (!mddev || !mddev->sync_set)
209                 return bio_alloc(GFP_NOIO, 1);
210
211         return bio_alloc_bioset(GFP_NOIO, 1, mddev->sync_set);
212 }
213
214 /*
215  * We have a system wide 'event count' that is incremented
216  * on any 'interesting' event, and readers of /proc/mdstat
217  * can use 'poll' or 'select' to find out when the event
218  * count increases.
219  *
220  * Events are:
221  *  start array, stop array, error, add device, remove device,
222  *  start build, activate spare
223  */
224 static DECLARE_WAIT_QUEUE_HEAD(md_event_waiters);
225 static atomic_t md_event_count;
226 void md_new_event(struct mddev *mddev)
227 {
228         atomic_inc(&md_event_count);
229         wake_up(&md_event_waiters);
230 }
231 EXPORT_SYMBOL_GPL(md_new_event);
232
233 /*
234  * Enables to iterate over all existing md arrays
235  * all_mddevs_lock protects this list.
236  */
237 static LIST_HEAD(all_mddevs);
238 static DEFINE_SPINLOCK(all_mddevs_lock);
239
240 /*
241  * iterates through all used mddevs in the system.
242  * We take care to grab the all_mddevs_lock whenever navigating
243  * the list, and to always hold a refcount when unlocked.
244  * Any code which breaks out of this loop while own
245  * a reference to the current mddev and must mddev_put it.
246  */
247 #define for_each_mddev(_mddev,_tmp)                                     \
248                                                                         \
249         for (({ spin_lock(&all_mddevs_lock);                            \
250                 _tmp = all_mddevs.next;                                 \
251                 _mddev = NULL;});                                       \
252              ({ if (_tmp != &all_mddevs)                                \
253                         mddev_get(list_entry(_tmp, struct mddev, all_mddevs));\
254                 spin_unlock(&all_mddevs_lock);                          \
255                 if (_mddev) mddev_put(_mddev);                          \
256                 _mddev = list_entry(_tmp, struct mddev, all_mddevs);    \
257                 _tmp != &all_mddevs;});                                 \
258              ({ spin_lock(&all_mddevs_lock);                            \
259                 _tmp = _tmp->next;})                                    \
260                 )
261
262 /* Rather than calling directly into the personality make_request function,
263  * IO requests come here first so that we can check if the device is
264  * being suspended pending a reconfiguration.
265  * We hold a refcount over the call to ->make_request.  By the time that
266  * call has finished, the bio has been linked into some internal structure
267  * and so is visible to ->quiesce(), so we don't need the refcount any more.
268  */
269 static blk_qc_t md_make_request(struct request_queue *q, struct bio *bio)
270 {
271         const int rw = bio_data_dir(bio);
272         struct mddev *mddev = q->queuedata;
273         unsigned int sectors;
274         int cpu;
275
276         blk_queue_split(q, &bio, q->bio_split);
277
278         if (mddev == NULL || mddev->pers == NULL) {
279                 bio_io_error(bio);
280                 return BLK_QC_T_NONE;
281         }
282         if (mddev->ro == 1 && unlikely(rw == WRITE)) {
283                 if (bio_sectors(bio) != 0)
284                         bio->bi_error = -EROFS;
285                 bio_endio(bio);
286                 return BLK_QC_T_NONE;
287         }
288 check_suspended:
289         rcu_read_lock();
290         if (mddev->suspended) {
291                 DEFINE_WAIT(__wait);
292                 for (;;) {
293                         prepare_to_wait(&mddev->sb_wait, &__wait,
294                                         TASK_UNINTERRUPTIBLE);
295                         if (!mddev->suspended)
296                                 break;
297                         rcu_read_unlock();
298                         schedule();
299                         rcu_read_lock();
300                 }
301                 finish_wait(&mddev->sb_wait, &__wait);
302         }
303         atomic_inc(&mddev->active_io);
304         rcu_read_unlock();
305
306         /*
307          * save the sectors now since our bio can
308          * go away inside make_request
309          */
310         sectors = bio_sectors(bio);
311         /* bio could be mergeable after passing to underlayer */
312         bio->bi_opf &= ~REQ_NOMERGE;
313         if (!mddev->pers->make_request(mddev, bio)) {
314                 atomic_dec(&mddev->active_io);
315                 wake_up(&mddev->sb_wait);
316                 goto check_suspended;
317         }
318
319         cpu = part_stat_lock();
320         part_stat_inc(cpu, &mddev->gendisk->part0, ios[rw]);
321         part_stat_add(cpu, &mddev->gendisk->part0, sectors[rw], sectors);
322         part_stat_unlock();
323
324         if (atomic_dec_and_test(&mddev->active_io) && mddev->suspended)
325                 wake_up(&mddev->sb_wait);
326
327         return BLK_QC_T_NONE;
328 }
329
330 /* mddev_suspend makes sure no new requests are submitted
331  * to the device, and that any requests that have been submitted
332  * are completely handled.
333  * Once mddev_detach() is called and completes, the module will be
334  * completely unused.
335  */
336 void mddev_suspend(struct mddev *mddev)
337 {
338         WARN_ON_ONCE(mddev->thread && current == mddev->thread->tsk);
339         if (mddev->suspended++)
340                 return;
341         synchronize_rcu();
342         wake_up(&mddev->sb_wait);
343         wait_event(mddev->sb_wait, atomic_read(&mddev->active_io) == 0);
344         mddev->pers->quiesce(mddev, 1);
345
346         del_timer_sync(&mddev->safemode_timer);
347 }
348 EXPORT_SYMBOL_GPL(mddev_suspend);
349
350 void mddev_resume(struct mddev *mddev)
351 {
352         if (--mddev->suspended)
353                 return;
354         wake_up(&mddev->sb_wait);
355         mddev->pers->quiesce(mddev, 0);
356
357         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
358         md_wakeup_thread(mddev->thread);
359         md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
360 }
361 EXPORT_SYMBOL_GPL(mddev_resume);
362
363 int mddev_congested(struct mddev *mddev, int bits)
364 {
365         struct md_personality *pers = mddev->pers;
366         int ret = 0;
367
368         rcu_read_lock();
369         if (mddev->suspended)
370                 ret = 1;
371         else if (pers && pers->congested)
372                 ret = pers->congested(mddev, bits);
373         rcu_read_unlock();
374         return ret;
375 }
376 EXPORT_SYMBOL_GPL(mddev_congested);
377 static int md_congested(void *data, int bits)
378 {
379         struct mddev *mddev = data;
380         return mddev_congested(mddev, bits);
381 }
382
383 /*
384  * Generic flush handling for md
385  */
386
387 static void md_end_flush(struct bio *bio)
388 {
389         struct md_rdev *rdev = bio->bi_private;
390         struct mddev *mddev = rdev->mddev;
391
392         rdev_dec_pending(rdev, mddev);
393
394         if (atomic_dec_and_test(&mddev->flush_pending)) {
395                 /* The pre-request flush has finished */
396                 queue_work(md_wq, &mddev->flush_work);
397         }
398         bio_put(bio);
399 }
400
401 static void md_submit_flush_data(struct work_struct *ws);
402
403 static void submit_flushes(struct work_struct *ws)
404 {
405         struct mddev *mddev = container_of(ws, struct mddev, flush_work);
406         struct md_rdev *rdev;
407
408         INIT_WORK(&mddev->flush_work, md_submit_flush_data);
409         atomic_set(&mddev->flush_pending, 1);
410         rcu_read_lock();
411         rdev_for_each_rcu(rdev, mddev)
412                 if (rdev->raid_disk >= 0 &&
413                     !test_bit(Faulty, &rdev->flags)) {
414                         /* Take two references, one is dropped
415                          * when request finishes, one after
416                          * we reclaim rcu_read_lock
417                          */
418                         struct bio *bi;
419                         atomic_inc(&rdev->nr_pending);
420                         atomic_inc(&rdev->nr_pending);
421                         rcu_read_unlock();
422                         bi = bio_alloc_mddev(GFP_NOIO, 0, mddev);
423                         bi->bi_end_io = md_end_flush;
424                         bi->bi_private = rdev;
425                         bi->bi_bdev = rdev->bdev;
426                         bi->bi_opf = REQ_OP_WRITE | REQ_PREFLUSH;
427                         atomic_inc(&mddev->flush_pending);
428                         submit_bio(bi);
429                         rcu_read_lock();
430                         rdev_dec_pending(rdev, mddev);
431                 }
432         rcu_read_unlock();
433         if (atomic_dec_and_test(&mddev->flush_pending))
434                 queue_work(md_wq, &mddev->flush_work);
435 }
436
437 static void md_submit_flush_data(struct work_struct *ws)
438 {
439         struct mddev *mddev = container_of(ws, struct mddev, flush_work);
440         struct bio *bio = mddev->flush_bio;
441
442         if (bio->bi_iter.bi_size == 0)
443                 /* an empty barrier - all done */
444                 bio_endio(bio);
445         else {
446                 bio->bi_opf &= ~REQ_PREFLUSH;
447                 mddev->pers->make_request(mddev, bio);
448         }
449
450         mddev->flush_bio = NULL;
451         wake_up(&mddev->sb_wait);
452 }
453
454 void md_flush_request(struct mddev *mddev, struct bio *bio)
455 {
456         spin_lock_irq(&mddev->lock);
457         wait_event_lock_irq(mddev->sb_wait,
458                             !mddev->flush_bio,
459                             mddev->lock);
460         mddev->flush_bio = bio;
461         spin_unlock_irq(&mddev->lock);
462
463         INIT_WORK(&mddev->flush_work, submit_flushes);
464         queue_work(md_wq, &mddev->flush_work);
465 }
466 EXPORT_SYMBOL(md_flush_request);
467
468 static inline struct mddev *mddev_get(struct mddev *mddev)
469 {
470         atomic_inc(&mddev->active);
471         return mddev;
472 }
473
474 static void mddev_delayed_delete(struct work_struct *ws);
475
476 static void mddev_put(struct mddev *mddev)
477 {
478         struct bio_set *bs = NULL, *sync_bs = NULL;
479
480         if (!atomic_dec_and_lock(&mddev->active, &all_mddevs_lock))
481                 return;
482         if (!mddev->raid_disks && list_empty(&mddev->disks) &&
483             mddev->ctime == 0 && !mddev->hold_active) {
484                 /* Array is not configured at all, and not held active,
485                  * so destroy it */
486                 list_del_init(&mddev->all_mddevs);
487                 bs = mddev->bio_set;
488                 sync_bs = mddev->sync_set;
489                 mddev->bio_set = NULL;
490                 mddev->sync_set = NULL;
491                 if (mddev->gendisk) {
492                         /* We did a probe so need to clean up.  Call
493                          * queue_work inside the spinlock so that
494                          * flush_workqueue() after mddev_find will
495                          * succeed in waiting for the work to be done.
496                          */
497                         INIT_WORK(&mddev->del_work, mddev_delayed_delete);
498                         queue_work(md_misc_wq, &mddev->del_work);
499                 } else
500                         kfree(mddev);
501         }
502         spin_unlock(&all_mddevs_lock);
503         if (bs)
504                 bioset_free(bs);
505         if (sync_bs)
506                 bioset_free(sync_bs);
507 }
508
509 static void md_safemode_timeout(unsigned long data);
510
511 void mddev_init(struct mddev *mddev)
512 {
513         mutex_init(&mddev->open_mutex);
514         mutex_init(&mddev->reconfig_mutex);
515         mutex_init(&mddev->bitmap_info.mutex);
516         INIT_LIST_HEAD(&mddev->disks);
517         INIT_LIST_HEAD(&mddev->all_mddevs);
518         setup_timer(&mddev->safemode_timer, md_safemode_timeout,
519                     (unsigned long) mddev);
520         atomic_set(&mddev->active, 1);
521         atomic_set(&mddev->openers, 0);
522         atomic_set(&mddev->active_io, 0);
523         spin_lock_init(&mddev->lock);
524         atomic_set(&mddev->flush_pending, 0);
525         init_waitqueue_head(&mddev->sb_wait);
526         init_waitqueue_head(&mddev->recovery_wait);
527         mddev->reshape_position = MaxSector;
528         mddev->reshape_backwards = 0;
529         mddev->last_sync_action = "none";
530         mddev->resync_min = 0;
531         mddev->resync_max = MaxSector;
532         mddev->level = LEVEL_NONE;
533 }
534 EXPORT_SYMBOL_GPL(mddev_init);
535
536 static struct mddev *mddev_find(dev_t unit)
537 {
538         struct mddev *mddev, *new = NULL;
539
540         if (unit && MAJOR(unit) != MD_MAJOR)
541                 unit &= ~((1<<MdpMinorShift)-1);
542
543  retry:
544         spin_lock(&all_mddevs_lock);
545
546         if (unit) {
547                 list_for_each_entry(mddev, &all_mddevs, all_mddevs)
548                         if (mddev->unit == unit) {
549                                 mddev_get(mddev);
550                                 spin_unlock(&all_mddevs_lock);
551                                 kfree(new);
552                                 return mddev;
553                         }
554
555                 if (new) {
556                         list_add(&new->all_mddevs, &all_mddevs);
557                         spin_unlock(&all_mddevs_lock);
558                         new->hold_active = UNTIL_IOCTL;
559                         return new;
560                 }
561         } else if (new) {
562                 /* find an unused unit number */
563                 static int next_minor = 512;
564                 int start = next_minor;
565                 int is_free = 0;
566                 int dev = 0;
567                 while (!is_free) {
568                         dev = MKDEV(MD_MAJOR, next_minor);
569                         next_minor++;
570                         if (next_minor > MINORMASK)
571                                 next_minor = 0;
572                         if (next_minor == start) {
573                                 /* Oh dear, all in use. */
574                                 spin_unlock(&all_mddevs_lock);
575                                 kfree(new);
576                                 return NULL;
577                         }
578
579                         is_free = 1;
580                         list_for_each_entry(mddev, &all_mddevs, all_mddevs)
581                                 if (mddev->unit == dev) {
582                                         is_free = 0;
583                                         break;
584                                 }
585                 }
586                 new->unit = dev;
587                 new->md_minor = MINOR(dev);
588                 new->hold_active = UNTIL_STOP;
589                 list_add(&new->all_mddevs, &all_mddevs);
590                 spin_unlock(&all_mddevs_lock);
591                 return new;
592         }
593         spin_unlock(&all_mddevs_lock);
594
595         new = kzalloc(sizeof(*new), GFP_KERNEL);
596         if (!new)
597                 return NULL;
598
599         new->unit = unit;
600         if (MAJOR(unit) == MD_MAJOR)
601                 new->md_minor = MINOR(unit);
602         else
603                 new->md_minor = MINOR(unit) >> MdpMinorShift;
604
605         mddev_init(new);
606
607         goto retry;
608 }
609
610 static struct attribute_group md_redundancy_group;
611
612 void mddev_unlock(struct mddev *mddev)
613 {
614         if (mddev->to_remove) {
615                 /* These cannot be removed under reconfig_mutex as
616                  * an access to the files will try to take reconfig_mutex
617                  * while holding the file unremovable, which leads to
618                  * a deadlock.
619                  * So hold set sysfs_active while the remove in happeing,
620                  * and anything else which might set ->to_remove or my
621                  * otherwise change the sysfs namespace will fail with
622                  * -EBUSY if sysfs_active is still set.
623                  * We set sysfs_active under reconfig_mutex and elsewhere
624                  * test it under the same mutex to ensure its correct value
625                  * is seen.
626                  */
627                 struct attribute_group *to_remove = mddev->to_remove;
628                 mddev->to_remove = NULL;
629                 mddev->sysfs_active = 1;
630                 mutex_unlock(&mddev->reconfig_mutex);
631
632                 if (mddev->kobj.sd) {
633                         if (to_remove != &md_redundancy_group)
634                                 sysfs_remove_group(&mddev->kobj, to_remove);
635                         if (mddev->pers == NULL ||
636                             mddev->pers->sync_request == NULL) {
637                                 sysfs_remove_group(&mddev->kobj, &md_redundancy_group);
638                                 if (mddev->sysfs_action)
639                                         sysfs_put(mddev->sysfs_action);
640                                 mddev->sysfs_action = NULL;
641                         }
642                 }
643                 mddev->sysfs_active = 0;
644         } else
645                 mutex_unlock(&mddev->reconfig_mutex);
646
647         /* As we've dropped the mutex we need a spinlock to
648          * make sure the thread doesn't disappear
649          */
650         spin_lock(&pers_lock);
651         md_wakeup_thread(mddev->thread);
652         spin_unlock(&pers_lock);
653 }
654 EXPORT_SYMBOL_GPL(mddev_unlock);
655
656 struct md_rdev *md_find_rdev_nr_rcu(struct mddev *mddev, int nr)
657 {
658         struct md_rdev *rdev;
659
660         rdev_for_each_rcu(rdev, mddev)
661                 if (rdev->desc_nr == nr)
662                         return rdev;
663
664         return NULL;
665 }
666 EXPORT_SYMBOL_GPL(md_find_rdev_nr_rcu);
667
668 static struct md_rdev *find_rdev(struct mddev *mddev, dev_t dev)
669 {
670         struct md_rdev *rdev;
671
672         rdev_for_each(rdev, mddev)
673                 if (rdev->bdev->bd_dev == dev)
674                         return rdev;
675
676         return NULL;
677 }
678
679 static struct md_rdev *find_rdev_rcu(struct mddev *mddev, dev_t dev)
680 {
681         struct md_rdev *rdev;
682
683         rdev_for_each_rcu(rdev, mddev)
684                 if (rdev->bdev->bd_dev == dev)
685                         return rdev;
686
687         return NULL;
688 }
689
690 static struct md_personality *find_pers(int level, char *clevel)
691 {
692         struct md_personality *pers;
693         list_for_each_entry(pers, &pers_list, list) {
694                 if (level != LEVEL_NONE && pers->level == level)
695                         return pers;
696                 if (strcmp(pers->name, clevel)==0)
697                         return pers;
698         }
699         return NULL;
700 }
701
702 /* return the offset of the super block in 512byte sectors */
703 static inline sector_t calc_dev_sboffset(struct md_rdev *rdev)
704 {
705         sector_t num_sectors = i_size_read(rdev->bdev->bd_inode) / 512;
706         return MD_NEW_SIZE_SECTORS(num_sectors);
707 }
708
709 static int alloc_disk_sb(struct md_rdev *rdev)
710 {
711         rdev->sb_page = alloc_page(GFP_KERNEL);
712         if (!rdev->sb_page)
713                 return -ENOMEM;
714         return 0;
715 }
716
717 void md_rdev_clear(struct md_rdev *rdev)
718 {
719         if (rdev->sb_page) {
720                 put_page(rdev->sb_page);
721                 rdev->sb_loaded = 0;
722                 rdev->sb_page = NULL;
723                 rdev->sb_start = 0;
724                 rdev->sectors = 0;
725         }
726         if (rdev->bb_page) {
727                 put_page(rdev->bb_page);
728                 rdev->bb_page = NULL;
729         }
730         badblocks_exit(&rdev->badblocks);
731 }
732 EXPORT_SYMBOL_GPL(md_rdev_clear);
733
734 static void super_written(struct bio *bio)
735 {
736         struct md_rdev *rdev = bio->bi_private;
737         struct mddev *mddev = rdev->mddev;
738
739         if (bio->bi_error) {
740                 pr_err("md: super_written gets error=%d\n", bio->bi_error);
741                 md_error(mddev, rdev);
742                 if (!test_bit(Faulty, &rdev->flags)
743                     && (bio->bi_opf & MD_FAILFAST)) {
744                         set_bit(MD_SB_NEED_REWRITE, &mddev->sb_flags);
745                         set_bit(LastDev, &rdev->flags);
746                 }
747         } else
748                 clear_bit(LastDev, &rdev->flags);
749
750         if (atomic_dec_and_test(&mddev->pending_writes))
751                 wake_up(&mddev->sb_wait);
752         rdev_dec_pending(rdev, mddev);
753         bio_put(bio);
754 }
755
756 void md_super_write(struct mddev *mddev, struct md_rdev *rdev,
757                    sector_t sector, int size, struct page *page)
758 {
759         /* write first size bytes of page to sector of rdev
760          * Increment mddev->pending_writes before returning
761          * and decrement it on completion, waking up sb_wait
762          * if zero is reached.
763          * If an error occurred, call md_error
764          */
765         struct bio *bio;
766         int ff = 0;
767
768         if (test_bit(Faulty, &rdev->flags))
769                 return;
770
771         bio = md_bio_alloc_sync(mddev);
772
773         atomic_inc(&rdev->nr_pending);
774
775         bio->bi_bdev = rdev->meta_bdev ? rdev->meta_bdev : rdev->bdev;
776         bio->bi_iter.bi_sector = sector;
777         bio_add_page(bio, page, size, 0);
778         bio->bi_private = rdev;
779         bio->bi_end_io = super_written;
780
781         if (test_bit(MD_FAILFAST_SUPPORTED, &mddev->flags) &&
782             test_bit(FailFast, &rdev->flags) &&
783             !test_bit(LastDev, &rdev->flags))
784                 ff = MD_FAILFAST;
785         bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH | REQ_FUA | ff;
786
787         atomic_inc(&mddev->pending_writes);
788         submit_bio(bio);
789 }
790
791 int md_super_wait(struct mddev *mddev)
792 {
793         /* wait for all superblock writes that were scheduled to complete */
794         wait_event(mddev->sb_wait, atomic_read(&mddev->pending_writes)==0);
795         if (test_and_clear_bit(MD_SB_NEED_REWRITE, &mddev->sb_flags))
796                 return -EAGAIN;
797         return 0;
798 }
799
800 int sync_page_io(struct md_rdev *rdev, sector_t sector, int size,
801                  struct page *page, int op, int op_flags, bool metadata_op)
802 {
803         struct bio *bio = md_bio_alloc_sync(rdev->mddev);
804         int ret;
805
806         bio->bi_bdev = (metadata_op && rdev->meta_bdev) ?
807                 rdev->meta_bdev : rdev->bdev;
808         bio_set_op_attrs(bio, op, op_flags);
809         if (metadata_op)
810                 bio->bi_iter.bi_sector = sector + rdev->sb_start;
811         else if (rdev->mddev->reshape_position != MaxSector &&
812                  (rdev->mddev->reshape_backwards ==
813                   (sector >= rdev->mddev->reshape_position)))
814                 bio->bi_iter.bi_sector = sector + rdev->new_data_offset;
815         else
816                 bio->bi_iter.bi_sector = sector + rdev->data_offset;
817         bio_add_page(bio, page, size, 0);
818
819         submit_bio_wait(bio);
820
821         ret = !bio->bi_error;
822         bio_put(bio);
823         return ret;
824 }
825 EXPORT_SYMBOL_GPL(sync_page_io);
826
827 static int read_disk_sb(struct md_rdev *rdev, int size)
828 {
829         char b[BDEVNAME_SIZE];
830
831         if (rdev->sb_loaded)
832                 return 0;
833
834         if (!sync_page_io(rdev, 0, size, rdev->sb_page, REQ_OP_READ, 0, true))
835                 goto fail;
836         rdev->sb_loaded = 1;
837         return 0;
838
839 fail:
840         pr_err("md: disabled device %s, could not read superblock.\n",
841                bdevname(rdev->bdev,b));
842         return -EINVAL;
843 }
844
845 static int uuid_equal(mdp_super_t *sb1, mdp_super_t *sb2)
846 {
847         return  sb1->set_uuid0 == sb2->set_uuid0 &&
848                 sb1->set_uuid1 == sb2->set_uuid1 &&
849                 sb1->set_uuid2 == sb2->set_uuid2 &&
850                 sb1->set_uuid3 == sb2->set_uuid3;
851 }
852
853 static int sb_equal(mdp_super_t *sb1, mdp_super_t *sb2)
854 {
855         int ret;
856         mdp_super_t *tmp1, *tmp2;
857
858         tmp1 = kmalloc(sizeof(*tmp1),GFP_KERNEL);
859         tmp2 = kmalloc(sizeof(*tmp2),GFP_KERNEL);
860
861         if (!tmp1 || !tmp2) {
862                 ret = 0;
863                 goto abort;
864         }
865
866         *tmp1 = *sb1;
867         *tmp2 = *sb2;
868
869         /*
870          * nr_disks is not constant
871          */
872         tmp1->nr_disks = 0;
873         tmp2->nr_disks = 0;
874
875         ret = (memcmp(tmp1, tmp2, MD_SB_GENERIC_CONSTANT_WORDS * 4) == 0);
876 abort:
877         kfree(tmp1);
878         kfree(tmp2);
879         return ret;
880 }
881
882 static u32 md_csum_fold(u32 csum)
883 {
884         csum = (csum & 0xffff) + (csum >> 16);
885         return (csum & 0xffff) + (csum >> 16);
886 }
887
888 static unsigned int calc_sb_csum(mdp_super_t *sb)
889 {
890         u64 newcsum = 0;
891         u32 *sb32 = (u32*)sb;
892         int i;
893         unsigned int disk_csum, csum;
894
895         disk_csum = sb->sb_csum;
896         sb->sb_csum = 0;
897
898         for (i = 0; i < MD_SB_BYTES/4 ; i++)
899                 newcsum += sb32[i];
900         csum = (newcsum & 0xffffffff) + (newcsum>>32);
901
902 #ifdef CONFIG_ALPHA
903         /* This used to use csum_partial, which was wrong for several
904          * reasons including that different results are returned on
905          * different architectures.  It isn't critical that we get exactly
906          * the same return value as before (we always csum_fold before
907          * testing, and that removes any differences).  However as we
908          * know that csum_partial always returned a 16bit value on
909          * alphas, do a fold to maximise conformity to previous behaviour.
910          */
911         sb->sb_csum = md_csum_fold(disk_csum);
912 #else
913         sb->sb_csum = disk_csum;
914 #endif
915         return csum;
916 }
917
918 /*
919  * Handle superblock details.
920  * We want to be able to handle multiple superblock formats
921  * so we have a common interface to them all, and an array of
922  * different handlers.
923  * We rely on user-space to write the initial superblock, and support
924  * reading and updating of superblocks.
925  * Interface methods are:
926  *   int load_super(struct md_rdev *dev, struct md_rdev *refdev, int minor_version)
927  *      loads and validates a superblock on dev.
928  *      if refdev != NULL, compare superblocks on both devices
929  *    Return:
930  *      0 - dev has a superblock that is compatible with refdev
931  *      1 - dev has a superblock that is compatible and newer than refdev
932  *          so dev should be used as the refdev in future
933  *     -EINVAL superblock incompatible or invalid
934  *     -othererror e.g. -EIO
935  *
936  *   int validate_super(struct mddev *mddev, struct md_rdev *dev)
937  *      Verify that dev is acceptable into mddev.
938  *       The first time, mddev->raid_disks will be 0, and data from
939  *       dev should be merged in.  Subsequent calls check that dev
940  *       is new enough.  Return 0 or -EINVAL
941  *
942  *   void sync_super(struct mddev *mddev, struct md_rdev *dev)
943  *     Update the superblock for rdev with data in mddev
944  *     This does not write to disc.
945  *
946  */
947
948 struct super_type  {
949         char                *name;
950         struct module       *owner;
951         int                 (*load_super)(struct md_rdev *rdev,
952                                           struct md_rdev *refdev,
953                                           int minor_version);
954         int                 (*validate_super)(struct mddev *mddev,
955                                               struct md_rdev *rdev);
956         void                (*sync_super)(struct mddev *mddev,
957                                           struct md_rdev *rdev);
958         unsigned long long  (*rdev_size_change)(struct md_rdev *rdev,
959                                                 sector_t num_sectors);
960         int                 (*allow_new_offset)(struct md_rdev *rdev,
961                                                 unsigned long long new_offset);
962 };
963
964 /*
965  * Check that the given mddev has no bitmap.
966  *
967  * This function is called from the run method of all personalities that do not
968  * support bitmaps. It prints an error message and returns non-zero if mddev
969  * has a bitmap. Otherwise, it returns 0.
970  *
971  */
972 int md_check_no_bitmap(struct mddev *mddev)
973 {
974         if (!mddev->bitmap_info.file && !mddev->bitmap_info.offset)
975                 return 0;
976         pr_warn("%s: bitmaps are not supported for %s\n",
977                 mdname(mddev), mddev->pers->name);
978         return 1;
979 }
980 EXPORT_SYMBOL(md_check_no_bitmap);
981
982 /*
983  * load_super for 0.90.0
984  */
985 static int super_90_load(struct md_rdev *rdev, struct md_rdev *refdev, int minor_version)
986 {
987         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
988         mdp_super_t *sb;
989         int ret;
990
991         /*
992          * Calculate the position of the superblock (512byte sectors),
993          * it's at the end of the disk.
994          *
995          * It also happens to be a multiple of 4Kb.
996          */
997         rdev->sb_start = calc_dev_sboffset(rdev);
998
999         ret = read_disk_sb(rdev, MD_SB_BYTES);
1000         if (ret)
1001                 return ret;
1002
1003         ret = -EINVAL;
1004
1005         bdevname(rdev->bdev, b);
1006         sb = page_address(rdev->sb_page);
1007
1008         if (sb->md_magic != MD_SB_MAGIC) {
1009                 pr_warn("md: invalid raid superblock magic on %s\n", b);
1010                 goto abort;
1011         }
1012
1013         if (sb->major_version != 0 ||
1014             sb->minor_version < 90 ||
1015             sb->minor_version > 91) {
1016                 pr_warn("Bad version number %d.%d on %s\n",
1017                         sb->major_version, sb->minor_version, b);
1018                 goto abort;
1019         }
1020
1021         if (sb->raid_disks <= 0)
1022                 goto abort;
1023
1024         if (md_csum_fold(calc_sb_csum(sb)) != md_csum_fold(sb->sb_csum)) {
1025                 pr_warn("md: invalid superblock checksum on %s\n", b);
1026                 goto abort;
1027         }
1028
1029         rdev->preferred_minor = sb->md_minor;
1030         rdev->data_offset = 0;
1031         rdev->new_data_offset = 0;
1032         rdev->sb_size = MD_SB_BYTES;
1033         rdev->badblocks.shift = -1;
1034
1035         if (sb->level == LEVEL_MULTIPATH)
1036                 rdev->desc_nr = -1;
1037         else
1038                 rdev->desc_nr = sb->this_disk.number;
1039
1040         if (!refdev) {
1041                 ret = 1;
1042         } else {
1043                 __u64 ev1, ev2;
1044                 mdp_super_t *refsb = page_address(refdev->sb_page);
1045                 if (!uuid_equal(refsb, sb)) {
1046                         pr_warn("md: %s has different UUID to %s\n",
1047                                 b, bdevname(refdev->bdev,b2));
1048                         goto abort;
1049                 }
1050                 if (!sb_equal(refsb, sb)) {
1051                         pr_warn("md: %s has same UUID but different superblock to %s\n",
1052                                 b, bdevname(refdev->bdev, b2));
1053                         goto abort;
1054                 }
1055                 ev1 = md_event(sb);
1056                 ev2 = md_event(refsb);
1057                 if (ev1 > ev2)
1058                         ret = 1;
1059                 else
1060                         ret = 0;
1061         }
1062         rdev->sectors = rdev->sb_start;
1063         /* Limit to 4TB as metadata cannot record more than that.
1064          * (not needed for Linear and RAID0 as metadata doesn't
1065          * record this size)
1066          */
1067         if (IS_ENABLED(CONFIG_LBDAF) && (u64)rdev->sectors >= (2ULL << 32) &&
1068             sb->level >= 1)
1069                 rdev->sectors = (sector_t)(2ULL << 32) - 2;
1070
1071         if (rdev->sectors < ((sector_t)sb->size) * 2 && sb->level >= 1)
1072                 /* "this cannot possibly happen" ... */
1073                 ret = -EINVAL;
1074
1075  abort:
1076         return ret;
1077 }
1078
1079 /*
1080  * validate_super for 0.90.0
1081  */
1082 static int super_90_validate(struct mddev *mddev, struct md_rdev *rdev)
1083 {
1084         mdp_disk_t *desc;
1085         mdp_super_t *sb = page_address(rdev->sb_page);
1086         __u64 ev1 = md_event(sb);
1087
1088         rdev->raid_disk = -1;
1089         clear_bit(Faulty, &rdev->flags);
1090         clear_bit(In_sync, &rdev->flags);
1091         clear_bit(Bitmap_sync, &rdev->flags);
1092         clear_bit(WriteMostly, &rdev->flags);
1093
1094         if (mddev->raid_disks == 0) {
1095                 mddev->major_version = 0;
1096                 mddev->minor_version = sb->minor_version;
1097                 mddev->patch_version = sb->patch_version;
1098                 mddev->external = 0;
1099                 mddev->chunk_sectors = sb->chunk_size >> 9;
1100                 mddev->ctime = sb->ctime;
1101                 mddev->utime = sb->utime;
1102                 mddev->level = sb->level;
1103                 mddev->clevel[0] = 0;
1104                 mddev->layout = sb->layout;
1105                 mddev->raid_disks = sb->raid_disks;
1106                 mddev->dev_sectors = ((sector_t)sb->size) * 2;
1107                 mddev->events = ev1;
1108                 mddev->bitmap_info.offset = 0;
1109                 mddev->bitmap_info.space = 0;
1110                 /* bitmap can use 60 K after the 4K superblocks */
1111                 mddev->bitmap_info.default_offset = MD_SB_BYTES >> 9;
1112                 mddev->bitmap_info.default_space = 64*2 - (MD_SB_BYTES >> 9);
1113                 mddev->reshape_backwards = 0;
1114
1115                 if (mddev->minor_version >= 91) {
1116                         mddev->reshape_position = sb->reshape_position;
1117                         mddev->delta_disks = sb->delta_disks;
1118                         mddev->new_level = sb->new_level;
1119                         mddev->new_layout = sb->new_layout;
1120                         mddev->new_chunk_sectors = sb->new_chunk >> 9;
1121                         if (mddev->delta_disks < 0)
1122                                 mddev->reshape_backwards = 1;
1123                 } else {
1124                         mddev->reshape_position = MaxSector;
1125                         mddev->delta_disks = 0;
1126                         mddev->new_level = mddev->level;
1127                         mddev->new_layout = mddev->layout;
1128                         mddev->new_chunk_sectors = mddev->chunk_sectors;
1129                 }
1130
1131                 if (sb->state & (1<<MD_SB_CLEAN))
1132                         mddev->recovery_cp = MaxSector;
1133                 else {
1134                         if (sb->events_hi == sb->cp_events_hi &&
1135                                 sb->events_lo == sb->cp_events_lo) {
1136                                 mddev->recovery_cp = sb->recovery_cp;
1137                         } else
1138                                 mddev->recovery_cp = 0;
1139                 }
1140
1141                 memcpy(mddev->uuid+0, &sb->set_uuid0, 4);
1142                 memcpy(mddev->uuid+4, &sb->set_uuid1, 4);
1143                 memcpy(mddev->uuid+8, &sb->set_uuid2, 4);
1144                 memcpy(mddev->uuid+12,&sb->set_uuid3, 4);
1145
1146                 mddev->max_disks = MD_SB_DISKS;
1147
1148                 if (sb->state & (1<<MD_SB_BITMAP_PRESENT) &&
1149                     mddev->bitmap_info.file == NULL) {
1150                         mddev->bitmap_info.offset =
1151                                 mddev->bitmap_info.default_offset;
1152                         mddev->bitmap_info.space =
1153                                 mddev->bitmap_info.default_space;
1154                 }
1155
1156         } else if (mddev->pers == NULL) {
1157                 /* Insist on good event counter while assembling, except
1158                  * for spares (which don't need an event count) */
1159                 ++ev1;
1160                 if (sb->disks[rdev->desc_nr].state & (
1161                             (1<<MD_DISK_SYNC) | (1 << MD_DISK_ACTIVE)))
1162                         if (ev1 < mddev->events)
1163                                 return -EINVAL;
1164         } else if (mddev->bitmap) {
1165                 /* if adding to array with a bitmap, then we can accept an
1166                  * older device ... but not too old.
1167                  */
1168                 if (ev1 < mddev->bitmap->events_cleared)
1169                         return 0;
1170                 if (ev1 < mddev->events)
1171                         set_bit(Bitmap_sync, &rdev->flags);
1172         } else {
1173                 if (ev1 < mddev->events)
1174                         /* just a hot-add of a new device, leave raid_disk at -1 */
1175                         return 0;
1176         }
1177
1178         if (mddev->level != LEVEL_MULTIPATH) {
1179                 desc = sb->disks + rdev->desc_nr;
1180
1181                 if (desc->state & (1<<MD_DISK_FAULTY))
1182                         set_bit(Faulty, &rdev->flags);
1183                 else if (desc->state & (1<<MD_DISK_SYNC) /* &&
1184                             desc->raid_disk < mddev->raid_disks */) {
1185                         set_bit(In_sync, &rdev->flags);
1186                         rdev->raid_disk = desc->raid_disk;
1187                         rdev->saved_raid_disk = desc->raid_disk;
1188                 } else if (desc->state & (1<<MD_DISK_ACTIVE)) {
1189                         /* active but not in sync implies recovery up to
1190                          * reshape position.  We don't know exactly where
1191                          * that is, so set to zero for now */
1192                         if (mddev->minor_version >= 91) {
1193                                 rdev->recovery_offset = 0;
1194                                 rdev->raid_disk = desc->raid_disk;
1195                         }
1196                 }
1197                 if (desc->state & (1<<MD_DISK_WRITEMOSTLY))
1198                         set_bit(WriteMostly, &rdev->flags);
1199                 if (desc->state & (1<<MD_DISK_FAILFAST))
1200                         set_bit(FailFast, &rdev->flags);
1201         } else /* MULTIPATH are always insync */
1202                 set_bit(In_sync, &rdev->flags);
1203         return 0;
1204 }
1205
1206 /*
1207  * sync_super for 0.90.0
1208  */
1209 static void super_90_sync(struct mddev *mddev, struct md_rdev *rdev)
1210 {
1211         mdp_super_t *sb;
1212         struct md_rdev *rdev2;
1213         int next_spare = mddev->raid_disks;
1214
1215         /* make rdev->sb match mddev data..
1216          *
1217          * 1/ zero out disks
1218          * 2/ Add info for each disk, keeping track of highest desc_nr (next_spare);
1219          * 3/ any empty disks < next_spare become removed
1220          *
1221          * disks[0] gets initialised to REMOVED because
1222          * we cannot be sure from other fields if it has
1223          * been initialised or not.
1224          */
1225         int i;
1226         int active=0, working=0,failed=0,spare=0,nr_disks=0;
1227
1228         rdev->sb_size = MD_SB_BYTES;
1229
1230         sb = page_address(rdev->sb_page);
1231
1232         memset(sb, 0, sizeof(*sb));
1233
1234         sb->md_magic = MD_SB_MAGIC;
1235         sb->major_version = mddev->major_version;
1236         sb->patch_version = mddev->patch_version;
1237         sb->gvalid_words  = 0; /* ignored */
1238         memcpy(&sb->set_uuid0, mddev->uuid+0, 4);
1239         memcpy(&sb->set_uuid1, mddev->uuid+4, 4);
1240         memcpy(&sb->set_uuid2, mddev->uuid+8, 4);
1241         memcpy(&sb->set_uuid3, mddev->uuid+12,4);
1242
1243         sb->ctime = clamp_t(time64_t, mddev->ctime, 0, U32_MAX);
1244         sb->level = mddev->level;
1245         sb->size = mddev->dev_sectors / 2;
1246         sb->raid_disks = mddev->raid_disks;
1247         sb->md_minor = mddev->md_minor;
1248         sb->not_persistent = 0;
1249         sb->utime = clamp_t(time64_t, mddev->utime, 0, U32_MAX);
1250         sb->state = 0;
1251         sb->events_hi = (mddev->events>>32);
1252         sb->events_lo = (u32)mddev->events;
1253
1254         if (mddev->reshape_position == MaxSector)
1255                 sb->minor_version = 90;
1256         else {
1257                 sb->minor_version = 91;
1258                 sb->reshape_position = mddev->reshape_position;
1259                 sb->new_level = mddev->new_level;
1260                 sb->delta_disks = mddev->delta_disks;
1261                 sb->new_layout = mddev->new_layout;
1262                 sb->new_chunk = mddev->new_chunk_sectors << 9;
1263         }
1264         mddev->minor_version = sb->minor_version;
1265         if (mddev->in_sync)
1266         {
1267                 sb->recovery_cp = mddev->recovery_cp;
1268                 sb->cp_events_hi = (mddev->events>>32);
1269                 sb->cp_events_lo = (u32)mddev->events;
1270                 if (mddev->recovery_cp == MaxSector)
1271                         sb->state = (1<< MD_SB_CLEAN);
1272         } else
1273                 sb->recovery_cp = 0;
1274
1275         sb->layout = mddev->layout;
1276         sb->chunk_size = mddev->chunk_sectors << 9;
1277
1278         if (mddev->bitmap && mddev->bitmap_info.file == NULL)
1279                 sb->state |= (1<<MD_SB_BITMAP_PRESENT);
1280
1281         sb->disks[0].state = (1<<MD_DISK_REMOVED);
1282         rdev_for_each(rdev2, mddev) {
1283                 mdp_disk_t *d;
1284                 int desc_nr;
1285                 int is_active = test_bit(In_sync, &rdev2->flags);
1286
1287                 if (rdev2->raid_disk >= 0 &&
1288                     sb->minor_version >= 91)
1289                         /* we have nowhere to store the recovery_offset,
1290                          * but if it is not below the reshape_position,
1291                          * we can piggy-back on that.
1292                          */
1293                         is_active = 1;
1294                 if (rdev2->raid_disk < 0 ||
1295                     test_bit(Faulty, &rdev2->flags))
1296                         is_active = 0;
1297                 if (is_active)
1298                         desc_nr = rdev2->raid_disk;
1299                 else
1300                         desc_nr = next_spare++;
1301                 rdev2->desc_nr = desc_nr;
1302                 d = &sb->disks[rdev2->desc_nr];
1303                 nr_disks++;
1304                 d->number = rdev2->desc_nr;
1305                 d->major = MAJOR(rdev2->bdev->bd_dev);
1306                 d->minor = MINOR(rdev2->bdev->bd_dev);
1307                 if (is_active)
1308                         d->raid_disk = rdev2->raid_disk;
1309                 else
1310                         d->raid_disk = rdev2->desc_nr; /* compatibility */
1311                 if (test_bit(Faulty, &rdev2->flags))
1312                         d->state = (1<<MD_DISK_FAULTY);
1313                 else if (is_active) {
1314                         d->state = (1<<MD_DISK_ACTIVE);
1315                         if (test_bit(In_sync, &rdev2->flags))
1316                                 d->state |= (1<<MD_DISK_SYNC);
1317                         active++;
1318                         working++;
1319                 } else {
1320                         d->state = 0;
1321                         spare++;
1322                         working++;
1323                 }
1324                 if (test_bit(WriteMostly, &rdev2->flags))
1325                         d->state |= (1<<MD_DISK_WRITEMOSTLY);
1326                 if (test_bit(FailFast, &rdev2->flags))
1327                         d->state |= (1<<MD_DISK_FAILFAST);
1328         }
1329         /* now set the "removed" and "faulty" bits on any missing devices */
1330         for (i=0 ; i < mddev->raid_disks ; i++) {
1331                 mdp_disk_t *d = &sb->disks[i];
1332                 if (d->state == 0 && d->number == 0) {
1333                         d->number = i;
1334                         d->raid_disk = i;
1335                         d->state = (1<<MD_DISK_REMOVED);
1336                         d->state |= (1<<MD_DISK_FAULTY);
1337                         failed++;
1338                 }
1339         }
1340         sb->nr_disks = nr_disks;
1341         sb->active_disks = active;
1342         sb->working_disks = working;
1343         sb->failed_disks = failed;
1344         sb->spare_disks = spare;
1345
1346         sb->this_disk = sb->disks[rdev->desc_nr];
1347         sb->sb_csum = calc_sb_csum(sb);
1348 }
1349
1350 /*
1351  * rdev_size_change for 0.90.0
1352  */
1353 static unsigned long long
1354 super_90_rdev_size_change(struct md_rdev *rdev, sector_t num_sectors)
1355 {
1356         if (num_sectors && num_sectors < rdev->mddev->dev_sectors)
1357                 return 0; /* component must fit device */
1358         if (rdev->mddev->bitmap_info.offset)
1359                 return 0; /* can't move bitmap */
1360         rdev->sb_start = calc_dev_sboffset(rdev);
1361         if (!num_sectors || num_sectors > rdev->sb_start)
1362                 num_sectors = rdev->sb_start;
1363         /* Limit to 4TB as metadata cannot record more than that.
1364          * 4TB == 2^32 KB, or 2*2^32 sectors.
1365          */
1366         if (IS_ENABLED(CONFIG_LBDAF) && (u64)num_sectors >= (2ULL << 32) &&
1367             rdev->mddev->level >= 1)
1368                 num_sectors = (sector_t)(2ULL << 32) - 2;
1369         do {
1370                 md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
1371                        rdev->sb_page);
1372         } while (md_super_wait(rdev->mddev) < 0);
1373         return num_sectors;
1374 }
1375
1376 static int
1377 super_90_allow_new_offset(struct md_rdev *rdev, unsigned long long new_offset)
1378 {
1379         /* non-zero offset changes not possible with v0.90 */
1380         return new_offset == 0;
1381 }
1382
1383 /*
1384  * version 1 superblock
1385  */
1386
1387 static __le32 calc_sb_1_csum(struct mdp_superblock_1 *sb)
1388 {
1389         __le32 disk_csum;
1390         u32 csum;
1391         unsigned long long newcsum;
1392         int size = 256 + le32_to_cpu(sb->max_dev)*2;
1393         __le32 *isuper = (__le32*)sb;
1394
1395         disk_csum = sb->sb_csum;
1396         sb->sb_csum = 0;
1397         newcsum = 0;
1398         for (; size >= 4; size -= 4)
1399                 newcsum += le32_to_cpu(*isuper++);
1400
1401         if (size == 2)
1402                 newcsum += le16_to_cpu(*(__le16*) isuper);
1403
1404         csum = (newcsum & 0xffffffff) + (newcsum >> 32);
1405         sb->sb_csum = disk_csum;
1406         return cpu_to_le32(csum);
1407 }
1408
1409 static int super_1_load(struct md_rdev *rdev, struct md_rdev *refdev, int minor_version)
1410 {
1411         struct mdp_superblock_1 *sb;
1412         int ret;
1413         sector_t sb_start;
1414         sector_t sectors;
1415         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1416         int bmask;
1417
1418         /*
1419          * Calculate the position of the superblock in 512byte sectors.
1420          * It is always aligned to a 4K boundary and
1421          * depeding on minor_version, it can be:
1422          * 0: At least 8K, but less than 12K, from end of device
1423          * 1: At start of device
1424          * 2: 4K from start of device.
1425          */
1426         switch(minor_version) {
1427         case 0:
1428                 sb_start = i_size_read(rdev->bdev->bd_inode) >> 9;
1429                 sb_start -= 8*2;
1430                 sb_start &= ~(sector_t)(4*2-1);
1431                 break;
1432         case 1:
1433                 sb_start = 0;
1434                 break;
1435         case 2:
1436                 sb_start = 8;
1437                 break;
1438         default:
1439                 return -EINVAL;
1440         }
1441         rdev->sb_start = sb_start;
1442
1443         /* superblock is rarely larger than 1K, but it can be larger,
1444          * and it is safe to read 4k, so we do that
1445          */
1446         ret = read_disk_sb(rdev, 4096);
1447         if (ret) return ret;
1448
1449         sb = page_address(rdev->sb_page);
1450
1451         if (sb->magic != cpu_to_le32(MD_SB_MAGIC) ||
1452             sb->major_version != cpu_to_le32(1) ||
1453             le32_to_cpu(sb->max_dev) > (4096-256)/2 ||
1454             le64_to_cpu(sb->super_offset) != rdev->sb_start ||
1455             (le32_to_cpu(sb->feature_map) & ~MD_FEATURE_ALL) != 0)
1456                 return -EINVAL;
1457
1458         if (calc_sb_1_csum(sb) != sb->sb_csum) {
1459                 pr_warn("md: invalid superblock checksum on %s\n",
1460                         bdevname(rdev->bdev,b));
1461                 return -EINVAL;
1462         }
1463         if (le64_to_cpu(sb->data_size) < 10) {
1464                 pr_warn("md: data_size too small on %s\n",
1465                         bdevname(rdev->bdev,b));
1466                 return -EINVAL;
1467         }
1468         if (sb->pad0 ||
1469             sb->pad3[0] ||
1470             memcmp(sb->pad3, sb->pad3+1, sizeof(sb->pad3) - sizeof(sb->pad3[1])))
1471                 /* Some padding is non-zero, might be a new feature */
1472                 return -EINVAL;
1473
1474         rdev->preferred_minor = 0xffff;
1475         rdev->data_offset = le64_to_cpu(sb->data_offset);
1476         rdev->new_data_offset = rdev->data_offset;
1477         if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE) &&
1478             (le32_to_cpu(sb->feature_map) & MD_FEATURE_NEW_OFFSET))
1479                 rdev->new_data_offset += (s32)le32_to_cpu(sb->new_offset);
1480         atomic_set(&rdev->corrected_errors, le32_to_cpu(sb->cnt_corrected_read));
1481
1482         rdev->sb_size = le32_to_cpu(sb->max_dev) * 2 + 256;
1483         bmask = queue_logical_block_size(rdev->bdev->bd_disk->queue)-1;
1484         if (rdev->sb_size & bmask)
1485                 rdev->sb_size = (rdev->sb_size | bmask) + 1;
1486
1487         if (minor_version
1488             && rdev->data_offset < sb_start + (rdev->sb_size/512))
1489                 return -EINVAL;
1490         if (minor_version
1491             && rdev->new_data_offset < sb_start + (rdev->sb_size/512))
1492                 return -EINVAL;
1493
1494         if (sb->level == cpu_to_le32(LEVEL_MULTIPATH))
1495                 rdev->desc_nr = -1;
1496         else
1497                 rdev->desc_nr = le32_to_cpu(sb->dev_number);
1498
1499         if (!rdev->bb_page) {
1500                 rdev->bb_page = alloc_page(GFP_KERNEL);
1501                 if (!rdev->bb_page)
1502                         return -ENOMEM;
1503         }
1504         if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BAD_BLOCKS) &&
1505             rdev->badblocks.count == 0) {
1506                 /* need to load the bad block list.
1507                  * Currently we limit it to one page.
1508                  */
1509                 s32 offset;
1510                 sector_t bb_sector;
1511                 u64 *bbp;
1512                 int i;
1513                 int sectors = le16_to_cpu(sb->bblog_size);
1514                 if (sectors > (PAGE_SIZE / 512))
1515                         return -EINVAL;
1516                 offset = le32_to_cpu(sb->bblog_offset);
1517                 if (offset == 0)
1518                         return -EINVAL;
1519                 bb_sector = (long long)offset;
1520                 if (!sync_page_io(rdev, bb_sector, sectors << 9,
1521                                   rdev->bb_page, REQ_OP_READ, 0, true))
1522                         return -EIO;
1523                 bbp = (u64 *)page_address(rdev->bb_page);
1524                 rdev->badblocks.shift = sb->bblog_shift;
1525                 for (i = 0 ; i < (sectors << (9-3)) ; i++, bbp++) {
1526                         u64 bb = le64_to_cpu(*bbp);
1527                         int count = bb & (0x3ff);
1528                         u64 sector = bb >> 10;
1529                         sector <<= sb->bblog_shift;
1530                         count <<= sb->bblog_shift;
1531                         if (bb + 1 == 0)
1532                                 break;
1533                         if (badblocks_set(&rdev->badblocks, sector, count, 1))
1534                                 return -EINVAL;
1535                 }
1536         } else if (sb->bblog_offset != 0)
1537                 rdev->badblocks.shift = 0;
1538
1539         if (le32_to_cpu(sb->feature_map) & MD_FEATURE_PPL) {
1540                 rdev->ppl.offset = (__s16)le16_to_cpu(sb->ppl.offset);
1541                 rdev->ppl.size = le16_to_cpu(sb->ppl.size);
1542                 rdev->ppl.sector = rdev->sb_start + rdev->ppl.offset;
1543         }
1544
1545         if (!refdev) {
1546                 ret = 1;
1547         } else {
1548                 __u64 ev1, ev2;
1549                 struct mdp_superblock_1 *refsb = page_address(refdev->sb_page);
1550
1551                 if (memcmp(sb->set_uuid, refsb->set_uuid, 16) != 0 ||
1552                     sb->level != refsb->level ||
1553                     sb->layout != refsb->layout ||
1554                     sb->chunksize != refsb->chunksize) {
1555                         pr_warn("md: %s has strangely different superblock to %s\n",
1556                                 bdevname(rdev->bdev,b),
1557                                 bdevname(refdev->bdev,b2));
1558                         return -EINVAL;
1559                 }
1560                 ev1 = le64_to_cpu(sb->events);
1561                 ev2 = le64_to_cpu(refsb->events);
1562
1563                 if (ev1 > ev2)
1564                         ret = 1;
1565                 else
1566                         ret = 0;
1567         }
1568         if (minor_version) {
1569                 sectors = (i_size_read(rdev->bdev->bd_inode) >> 9);
1570                 sectors -= rdev->data_offset;
1571         } else
1572                 sectors = rdev->sb_start;
1573         if (sectors < le64_to_cpu(sb->data_size))
1574                 return -EINVAL;
1575         rdev->sectors = le64_to_cpu(sb->data_size);
1576         return ret;
1577 }
1578
1579 static int super_1_validate(struct mddev *mddev, struct md_rdev *rdev)
1580 {
1581         struct mdp_superblock_1 *sb = page_address(rdev->sb_page);
1582         __u64 ev1 = le64_to_cpu(sb->events);
1583
1584         rdev->raid_disk = -1;
1585         clear_bit(Faulty, &rdev->flags);
1586         clear_bit(In_sync, &rdev->flags);
1587         clear_bit(Bitmap_sync, &rdev->flags);
1588         clear_bit(WriteMostly, &rdev->flags);
1589
1590         if (mddev->raid_disks == 0) {
1591                 mddev->major_version = 1;
1592                 mddev->patch_version = 0;
1593                 mddev->external = 0;
1594                 mddev->chunk_sectors = le32_to_cpu(sb->chunksize);
1595                 mddev->ctime = le64_to_cpu(sb->ctime);
1596                 mddev->utime = le64_to_cpu(sb->utime);
1597                 mddev->level = le32_to_cpu(sb->level);
1598                 mddev->clevel[0] = 0;
1599                 mddev->layout = le32_to_cpu(sb->layout);
1600                 mddev->raid_disks = le32_to_cpu(sb->raid_disks);
1601                 mddev->dev_sectors = le64_to_cpu(sb->size);
1602                 mddev->events = ev1;
1603                 mddev->bitmap_info.offset = 0;
1604                 mddev->bitmap_info.space = 0;
1605                 /* Default location for bitmap is 1K after superblock
1606                  * using 3K - total of 4K
1607                  */
1608                 mddev->bitmap_info.default_offset = 1024 >> 9;
1609                 mddev->bitmap_info.default_space = (4096-1024) >> 9;
1610                 mddev->reshape_backwards = 0;
1611
1612                 mddev->recovery_cp = le64_to_cpu(sb->resync_offset);
1613                 memcpy(mddev->uuid, sb->set_uuid, 16);
1614
1615                 mddev->max_disks =  (4096-256)/2;
1616
1617                 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BITMAP_OFFSET) &&
1618                     mddev->bitmap_info.file == NULL) {
1619                         mddev->bitmap_info.offset =
1620                                 (__s32)le32_to_cpu(sb->bitmap_offset);
1621                         /* Metadata doesn't record how much space is available.
1622                          * For 1.0, we assume we can use up to the superblock
1623                          * if before, else to 4K beyond superblock.
1624                          * For others, assume no change is possible.
1625                          */
1626                         if (mddev->minor_version > 0)
1627                                 mddev->bitmap_info.space = 0;
1628                         else if (mddev->bitmap_info.offset > 0)
1629                                 mddev->bitmap_info.space =
1630                                         8 - mddev->bitmap_info.offset;
1631                         else
1632                                 mddev->bitmap_info.space =
1633                                         -mddev->bitmap_info.offset;
1634                 }
1635
1636                 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE)) {
1637                         mddev->reshape_position = le64_to_cpu(sb->reshape_position);
1638                         mddev->delta_disks = le32_to_cpu(sb->delta_disks);
1639                         mddev->new_level = le32_to_cpu(sb->new_level);
1640                         mddev->new_layout = le32_to_cpu(sb->new_layout);
1641                         mddev->new_chunk_sectors = le32_to_cpu(sb->new_chunk);
1642                         if (mddev->delta_disks < 0 ||
1643                             (mddev->delta_disks == 0 &&
1644                              (le32_to_cpu(sb->feature_map)
1645                               & MD_FEATURE_RESHAPE_BACKWARDS)))
1646                                 mddev->reshape_backwards = 1;
1647                 } else {
1648                         mddev->reshape_position = MaxSector;
1649                         mddev->delta_disks = 0;
1650                         mddev->new_level = mddev->level;
1651                         mddev->new_layout = mddev->layout;
1652                         mddev->new_chunk_sectors = mddev->chunk_sectors;
1653                 }
1654
1655                 if (le32_to_cpu(sb->feature_map) & MD_FEATURE_JOURNAL)
1656                         set_bit(MD_HAS_JOURNAL, &mddev->flags);
1657
1658                 if (le32_to_cpu(sb->feature_map) & MD_FEATURE_PPL) {
1659                         if (le32_to_cpu(sb->feature_map) &
1660                             (MD_FEATURE_BITMAP_OFFSET | MD_FEATURE_JOURNAL))
1661                                 return -EINVAL;
1662                         set_bit(MD_HAS_PPL, &mddev->flags);
1663                 }
1664         } else if (mddev->pers == NULL) {
1665                 /* Insist of good event counter while assembling, except for
1666                  * spares (which don't need an event count) */
1667                 ++ev1;
1668                 if (rdev->desc_nr >= 0 &&
1669                     rdev->desc_nr < le32_to_cpu(sb->max_dev) &&
1670                     (le16_to_cpu(sb->dev_roles[rdev->desc_nr]) < MD_DISK_ROLE_MAX ||
1671                      le16_to_cpu(sb->dev_roles[rdev->desc_nr]) == MD_DISK_ROLE_JOURNAL))
1672                         if (ev1 < mddev->events)
1673                                 return -EINVAL;
1674         } else if (mddev->bitmap) {
1675                 /* If adding to array with a bitmap, then we can accept an
1676                  * older device, but not too old.
1677                  */
1678                 if (ev1 < mddev->bitmap->events_cleared)
1679                         return 0;
1680                 if (ev1 < mddev->events)
1681                         set_bit(Bitmap_sync, &rdev->flags);
1682         } else {
1683                 if (ev1 < mddev->events)
1684                         /* just a hot-add of a new device, leave raid_disk at -1 */
1685                         return 0;
1686         }
1687         if (mddev->level != LEVEL_MULTIPATH) {
1688                 int role;
1689                 if (rdev->desc_nr < 0 ||
1690                     rdev->desc_nr >= le32_to_cpu(sb->max_dev)) {
1691                         role = MD_DISK_ROLE_SPARE;
1692                         rdev->desc_nr = -1;
1693                 } else
1694                         role = le16_to_cpu(sb->dev_roles[rdev->desc_nr]);
1695                 switch(role) {
1696                 case MD_DISK_ROLE_SPARE: /* spare */
1697                         break;
1698                 case MD_DISK_ROLE_FAULTY: /* faulty */
1699                         set_bit(Faulty, &rdev->flags);
1700                         break;
1701                 case MD_DISK_ROLE_JOURNAL: /* journal device */
1702                         if (!(le32_to_cpu(sb->feature_map) & MD_FEATURE_JOURNAL)) {
1703                                 /* journal device without journal feature */
1704                                 pr_warn("md: journal device provided without journal feature, ignoring the device\n");
1705                                 return -EINVAL;
1706                         }
1707                         set_bit(Journal, &rdev->flags);
1708                         rdev->journal_tail = le64_to_cpu(sb->journal_tail);
1709                         rdev->raid_disk = 0;
1710                         break;
1711                 default:
1712                         rdev->saved_raid_disk = role;
1713                         if ((le32_to_cpu(sb->feature_map) &
1714                              MD_FEATURE_RECOVERY_OFFSET)) {
1715                                 rdev->recovery_offset = le64_to_cpu(sb->recovery_offset);
1716                                 if (!(le32_to_cpu(sb->feature_map) &
1717                                       MD_FEATURE_RECOVERY_BITMAP))
1718                                         rdev->saved_raid_disk = -1;
1719                         } else
1720                                 set_bit(In_sync, &rdev->flags);
1721                         rdev->raid_disk = role;
1722                         break;
1723                 }
1724                 if (sb->devflags & WriteMostly1)
1725                         set_bit(WriteMostly, &rdev->flags);
1726                 if (sb->devflags & FailFast1)
1727                         set_bit(FailFast, &rdev->flags);
1728                 if (le32_to_cpu(sb->feature_map) & MD_FEATURE_REPLACEMENT)
1729                         set_bit(Replacement, &rdev->flags);
1730         } else /* MULTIPATH are always insync */
1731                 set_bit(In_sync, &rdev->flags);
1732
1733         return 0;
1734 }
1735
1736 static void super_1_sync(struct mddev *mddev, struct md_rdev *rdev)
1737 {
1738         struct mdp_superblock_1 *sb;
1739         struct md_rdev *rdev2;
1740         int max_dev, i;
1741         /* make rdev->sb match mddev and rdev data. */
1742
1743         sb = page_address(rdev->sb_page);
1744
1745         sb->feature_map = 0;
1746         sb->pad0 = 0;
1747         sb->recovery_offset = cpu_to_le64(0);
1748         memset(sb->pad3, 0, sizeof(sb->pad3));
1749
1750         sb->utime = cpu_to_le64((__u64)mddev->utime);
1751         sb->events = cpu_to_le64(mddev->events);
1752         if (mddev->in_sync)
1753                 sb->resync_offset = cpu_to_le64(mddev->recovery_cp);
1754         else if (test_bit(MD_JOURNAL_CLEAN, &mddev->flags))
1755                 sb->resync_offset = cpu_to_le64(MaxSector);
1756         else
1757                 sb->resync_offset = cpu_to_le64(0);
1758
1759         sb->cnt_corrected_read = cpu_to_le32(atomic_read(&rdev->corrected_errors));
1760
1761         sb->raid_disks = cpu_to_le32(mddev->raid_disks);
1762         sb->size = cpu_to_le64(mddev->dev_sectors);
1763         sb->chunksize = cpu_to_le32(mddev->chunk_sectors);
1764         sb->level = cpu_to_le32(mddev->level);
1765         sb->layout = cpu_to_le32(mddev->layout);
1766         if (test_bit(FailFast, &rdev->flags))
1767                 sb->devflags |= FailFast1;
1768         else
1769                 sb->devflags &= ~FailFast1;
1770
1771         if (test_bit(WriteMostly, &rdev->flags))
1772                 sb->devflags |= WriteMostly1;
1773         else
1774                 sb->devflags &= ~WriteMostly1;
1775         sb->data_offset = cpu_to_le64(rdev->data_offset);
1776         sb->data_size = cpu_to_le64(rdev->sectors);
1777
1778         if (mddev->bitmap && mddev->bitmap_info.file == NULL) {
1779                 sb->bitmap_offset = cpu_to_le32((__u32)mddev->bitmap_info.offset);
1780                 sb->feature_map = cpu_to_le32(MD_FEATURE_BITMAP_OFFSET);
1781         }
1782
1783         if (rdev->raid_disk >= 0 && !test_bit(Journal, &rdev->flags) &&
1784             !test_bit(In_sync, &rdev->flags)) {
1785                 sb->feature_map |=
1786                         cpu_to_le32(MD_FEATURE_RECOVERY_OFFSET);
1787                 sb->recovery_offset =
1788                         cpu_to_le64(rdev->recovery_offset);
1789                 if (rdev->saved_raid_disk >= 0 && mddev->bitmap)
1790                         sb->feature_map |=
1791                                 cpu_to_le32(MD_FEATURE_RECOVERY_BITMAP);
1792         }
1793         /* Note: recovery_offset and journal_tail share space  */
1794         if (test_bit(Journal, &rdev->flags))
1795                 sb->journal_tail = cpu_to_le64(rdev->journal_tail);
1796         if (test_bit(Replacement, &rdev->flags))
1797                 sb->feature_map |=
1798                         cpu_to_le32(MD_FEATURE_REPLACEMENT);
1799
1800         if (mddev->reshape_position != MaxSector) {
1801                 sb->feature_map |= cpu_to_le32(MD_FEATURE_RESHAPE_ACTIVE);
1802                 sb->reshape_position = cpu_to_le64(mddev->reshape_position);
1803                 sb->new_layout = cpu_to_le32(mddev->new_layout);
1804                 sb->delta_disks = cpu_to_le32(mddev->delta_disks);
1805                 sb->new_level = cpu_to_le32(mddev->new_level);
1806                 sb->new_chunk = cpu_to_le32(mddev->new_chunk_sectors);
1807                 if (mddev->delta_disks == 0 &&
1808                     mddev->reshape_backwards)
1809                         sb->feature_map
1810                                 |= cpu_to_le32(MD_FEATURE_RESHAPE_BACKWARDS);
1811                 if (rdev->new_data_offset != rdev->data_offset) {
1812                         sb->feature_map
1813                                 |= cpu_to_le32(MD_FEATURE_NEW_OFFSET);
1814                         sb->new_offset = cpu_to_le32((__u32)(rdev->new_data_offset
1815                                                              - rdev->data_offset));
1816                 }
1817         }
1818
1819         if (mddev_is_clustered(mddev))
1820                 sb->feature_map |= cpu_to_le32(MD_FEATURE_CLUSTERED);
1821
1822         if (rdev->badblocks.count == 0)
1823                 /* Nothing to do for bad blocks*/ ;
1824         else if (sb->bblog_offset == 0)
1825                 /* Cannot record bad blocks on this device */
1826                 md_error(mddev, rdev);
1827         else {
1828                 struct badblocks *bb = &rdev->badblocks;
1829                 u64 *bbp = (u64 *)page_address(rdev->bb_page);
1830                 u64 *p = bb->page;
1831                 sb->feature_map |= cpu_to_le32(MD_FEATURE_BAD_BLOCKS);
1832                 if (bb->changed) {
1833                         unsigned seq;
1834
1835 retry:
1836                         seq = read_seqbegin(&bb->lock);
1837
1838                         memset(bbp, 0xff, PAGE_SIZE);
1839
1840                         for (i = 0 ; i < bb->count ; i++) {
1841                                 u64 internal_bb = p[i];
1842                                 u64 store_bb = ((BB_OFFSET(internal_bb) << 10)
1843                                                 | BB_LEN(internal_bb));
1844                                 bbp[i] = cpu_to_le64(store_bb);
1845                         }
1846                         bb->changed = 0;
1847                         if (read_seqretry(&bb->lock, seq))
1848                                 goto retry;
1849
1850                         bb->sector = (rdev->sb_start +
1851                                       (int)le32_to_cpu(sb->bblog_offset));
1852                         bb->size = le16_to_cpu(sb->bblog_size);
1853                 }
1854         }
1855
1856         max_dev = 0;
1857         rdev_for_each(rdev2, mddev)
1858                 if (rdev2->desc_nr+1 > max_dev)
1859                         max_dev = rdev2->desc_nr+1;
1860
1861         if (max_dev > le32_to_cpu(sb->max_dev)) {
1862                 int bmask;
1863                 sb->max_dev = cpu_to_le32(max_dev);
1864                 rdev->sb_size = max_dev * 2 + 256;
1865                 bmask = queue_logical_block_size(rdev->bdev->bd_disk->queue)-1;
1866                 if (rdev->sb_size & bmask)
1867                         rdev->sb_size = (rdev->sb_size | bmask) + 1;
1868         } else
1869                 max_dev = le32_to_cpu(sb->max_dev);
1870
1871         for (i=0; i<max_dev;i++)
1872                 sb->dev_roles[i] = cpu_to_le16(MD_DISK_ROLE_SPARE);
1873
1874         if (test_bit(MD_HAS_JOURNAL, &mddev->flags))
1875                 sb->feature_map |= cpu_to_le32(MD_FEATURE_JOURNAL);
1876
1877         if (test_bit(MD_HAS_PPL, &mddev->flags)) {
1878                 sb->feature_map |= cpu_to_le32(MD_FEATURE_PPL);
1879                 sb->ppl.offset = cpu_to_le16(rdev->ppl.offset);
1880                 sb->ppl.size = cpu_to_le16(rdev->ppl.size);
1881         }
1882
1883         rdev_for_each(rdev2, mddev) {
1884                 i = rdev2->desc_nr;
1885                 if (test_bit(Faulty, &rdev2->flags))
1886                         sb->dev_roles[i] = cpu_to_le16(MD_DISK_ROLE_FAULTY);
1887                 else if (test_bit(In_sync, &rdev2->flags))
1888                         sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1889                 else if (test_bit(Journal, &rdev2->flags))
1890                         sb->dev_roles[i] = cpu_to_le16(MD_DISK_ROLE_JOURNAL);
1891                 else if (rdev2->raid_disk >= 0)
1892                         sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1893                 else
1894                         sb->dev_roles[i] = cpu_to_le16(MD_DISK_ROLE_SPARE);
1895         }
1896
1897         sb->sb_csum = calc_sb_1_csum(sb);
1898 }
1899
1900 static unsigned long long
1901 super_1_rdev_size_change(struct md_rdev *rdev, sector_t num_sectors)
1902 {
1903         struct mdp_superblock_1 *sb;
1904         sector_t max_sectors;
1905         if (num_sectors && num_sectors < rdev->mddev->dev_sectors)
1906                 return 0; /* component must fit device */
1907         if (rdev->data_offset != rdev->new_data_offset)
1908                 return 0; /* too confusing */
1909         if (rdev->sb_start < rdev->data_offset) {
1910                 /* minor versions 1 and 2; superblock before data */
1911                 max_sectors = i_size_read(rdev->bdev->bd_inode) >> 9;
1912                 max_sectors -= rdev->data_offset;
1913                 if (!num_sectors || num_sectors > max_sectors)
1914                         num_sectors = max_sectors;
1915         } else if (rdev->mddev->bitmap_info.offset) {
1916                 /* minor version 0 with bitmap we can't move */
1917                 return 0;
1918         } else {
1919                 /* minor version 0; superblock after data */
1920                 sector_t sb_start;
1921                 sb_start = (i_size_read(rdev->bdev->bd_inode) >> 9) - 8*2;
1922                 sb_start &= ~(sector_t)(4*2 - 1);
1923                 max_sectors = rdev->sectors + sb_start - rdev->sb_start;
1924                 if (!num_sectors || num_sectors > max_sectors)
1925                         num_sectors = max_sectors;
1926                 rdev->sb_start = sb_start;
1927         }
1928         sb = page_address(rdev->sb_page);
1929         sb->data_size = cpu_to_le64(num_sectors);
1930         sb->super_offset = cpu_to_le64(rdev->sb_start);
1931         sb->sb_csum = calc_sb_1_csum(sb);
1932         do {
1933                 md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
1934                                rdev->sb_page);
1935         } while (md_super_wait(rdev->mddev) < 0);
1936         return num_sectors;
1937
1938 }
1939
1940 static int
1941 super_1_allow_new_offset(struct md_rdev *rdev,
1942                          unsigned long long new_offset)
1943 {
1944         /* All necessary checks on new >= old have been done */
1945         struct bitmap *bitmap;
1946         if (new_offset >= rdev->data_offset)
1947                 return 1;
1948
1949         /* with 1.0 metadata, there is no metadata to tread on
1950          * so we can always move back */
1951         if (rdev->mddev->minor_version == 0)
1952                 return 1;
1953
1954         /* otherwise we must be sure not to step on
1955          * any metadata, so stay:
1956          * 36K beyond start of superblock
1957          * beyond end of badblocks
1958          * beyond write-intent bitmap
1959          */
1960         if (rdev->sb_start + (32+4)*2 > new_offset)
1961                 return 0;
1962         bitmap = rdev->mddev->bitmap;
1963         if (bitmap && !rdev->mddev->bitmap_info.file &&
1964             rdev->sb_start + rdev->mddev->bitmap_info.offset +
1965             bitmap->storage.file_pages * (PAGE_SIZE>>9) > new_offset)
1966                 return 0;
1967         if (rdev->badblocks.sector + rdev->badblocks.size > new_offset)
1968                 return 0;
1969
1970         return 1;
1971 }
1972
1973 static struct super_type super_types[] = {
1974         [0] = {
1975                 .name   = "0.90.0",
1976                 .owner  = THIS_MODULE,
1977                 .load_super         = super_90_load,
1978                 .validate_super     = super_90_validate,
1979                 .sync_super         = super_90_sync,
1980                 .rdev_size_change   = super_90_rdev_size_change,
1981                 .allow_new_offset   = super_90_allow_new_offset,
1982         },
1983         [1] = {
1984                 .name   = "md-1",
1985                 .owner  = THIS_MODULE,
1986                 .load_super         = super_1_load,
1987                 .validate_super     = super_1_validate,
1988                 .sync_super         = super_1_sync,
1989                 .rdev_size_change   = super_1_rdev_size_change,
1990                 .allow_new_offset   = super_1_allow_new_offset,
1991         },
1992 };
1993
1994 static void sync_super(struct mddev *mddev, struct md_rdev *rdev)
1995 {
1996         if (mddev->sync_super) {
1997                 mddev->sync_super(mddev, rdev);
1998                 return;
1999         }
2000
2001         BUG_ON(mddev->major_version >= ARRAY_SIZE(super_types));
2002
2003         super_types[mddev->major_version].sync_super(mddev, rdev);
2004 }
2005
2006 static int match_mddev_units(struct mddev *mddev1, struct mddev *mddev2)
2007 {
2008         struct md_rdev *rdev, *rdev2;
2009
2010         rcu_read_lock();
2011         rdev_for_each_rcu(rdev, mddev1) {
2012                 if (test_bit(Faulty, &rdev->flags) ||
2013                     test_bit(Journal, &rdev->flags) ||
2014                     rdev->raid_disk == -1)
2015                         continue;
2016                 rdev_for_each_rcu(rdev2, mddev2) {
2017                         if (test_bit(Faulty, &rdev2->flags) ||
2018                             test_bit(Journal, &rdev2->flags) ||
2019                             rdev2->raid_disk == -1)
2020                                 continue;
2021                         if (rdev->bdev->bd_contains ==
2022                             rdev2->bdev->bd_contains) {
2023                                 rcu_read_unlock();
2024                                 return 1;
2025                         }
2026                 }
2027         }
2028         rcu_read_unlock();
2029         return 0;
2030 }
2031
2032 static LIST_HEAD(pending_raid_disks);
2033
2034 /*
2035  * Try to register data integrity profile for an mddev
2036  *
2037  * This is called when an array is started and after a disk has been kicked
2038  * from the array. It only succeeds if all working and active component devices
2039  * are integrity capable with matching profiles.
2040  */
2041 int md_integrity_register(struct mddev *mddev)
2042 {
2043         struct md_rdev *rdev, *reference = NULL;
2044
2045         if (list_empty(&mddev->disks))
2046                 return 0; /* nothing to do */
2047         if (!mddev->gendisk || blk_get_integrity(mddev->gendisk))
2048                 return 0; /* shouldn't register, or already is */
2049         rdev_for_each(rdev, mddev) {
2050                 /* skip spares and non-functional disks */
2051                 if (test_bit(Faulty, &rdev->flags))
2052                         continue;
2053                 if (rdev->raid_disk < 0)
2054                         continue;
2055                 if (!reference) {
2056                         /* Use the first rdev as the reference */
2057                         reference = rdev;
2058                         continue;
2059                 }
2060                 /* does this rdev's profile match the reference profile? */
2061                 if (blk_integrity_compare(reference->bdev->bd_disk,
2062                                 rdev->bdev->bd_disk) < 0)
2063                         return -EINVAL;
2064         }
2065         if (!reference || !bdev_get_integrity(reference->bdev))
2066                 return 0;
2067         /*
2068          * All component devices are integrity capable and have matching
2069          * profiles, register the common profile for the md device.
2070          */
2071         blk_integrity_register(mddev->gendisk,
2072                                bdev_get_integrity(reference->bdev));
2073
2074         pr_debug("md: data integrity enabled on %s\n", mdname(mddev));
2075         if (bioset_integrity_create(mddev->bio_set, BIO_POOL_SIZE)) {
2076                 pr_err("md: failed to create integrity pool for %s\n",
2077                        mdname(mddev));
2078                 return -EINVAL;
2079         }
2080         return 0;
2081 }
2082 EXPORT_SYMBOL(md_integrity_register);
2083
2084 /*
2085  * Attempt to add an rdev, but only if it is consistent with the current
2086  * integrity profile
2087  */
2088 int md_integrity_add_rdev(struct md_rdev *rdev, struct mddev *mddev)
2089 {
2090         struct blk_integrity *bi_rdev;
2091         struct blk_integrity *bi_mddev;
2092         char name[BDEVNAME_SIZE];
2093
2094         if (!mddev->gendisk)
2095                 return 0;
2096
2097         bi_rdev = bdev_get_integrity(rdev->bdev);
2098         bi_mddev = blk_get_integrity(mddev->gendisk);
2099
2100         if (!bi_mddev) /* nothing to do */
2101                 return 0;
2102
2103         if (blk_integrity_compare(mddev->gendisk, rdev->bdev->bd_disk) != 0) {
2104                 pr_err("%s: incompatible integrity profile for %s\n",
2105                        mdname(mddev), bdevname(rdev->bdev, name));
2106                 return -ENXIO;
2107         }
2108
2109         return 0;
2110 }
2111 EXPORT_SYMBOL(md_integrity_add_rdev);
2112
2113 static int bind_rdev_to_array(struct md_rdev *rdev, struct mddev *mddev)
2114 {
2115         char b[BDEVNAME_SIZE];
2116         struct kobject *ko;
2117         int err;
2118
2119         /* prevent duplicates */
2120         if (find_rdev(mddev, rdev->bdev->bd_dev))
2121                 return -EEXIST;
2122
2123         if ((bdev_read_only(rdev->bdev) || bdev_read_only(rdev->meta_bdev)) &&
2124             mddev->pers)
2125                 return -EROFS;
2126
2127         /* make sure rdev->sectors exceeds mddev->dev_sectors */
2128         if (!test_bit(Journal, &rdev->flags) &&
2129             rdev->sectors &&
2130             (mddev->dev_sectors == 0 || rdev->sectors < mddev->dev_sectors)) {
2131                 if (mddev->pers) {
2132                         /* Cannot change size, so fail
2133                          * If mddev->level <= 0, then we don't care
2134                          * about aligning sizes (e.g. linear)
2135                          */
2136                         if (mddev->level > 0)
2137                                 return -ENOSPC;
2138                 } else
2139                         mddev->dev_sectors = rdev->sectors;
2140         }
2141
2142         /* Verify rdev->desc_nr is unique.
2143          * If it is -1, assign a free number, else
2144          * check number is not in use
2145          */
2146         rcu_read_lock();
2147         if (rdev->desc_nr < 0) {
2148                 int choice = 0;
2149                 if (mddev->pers)
2150                         choice = mddev->raid_disks;
2151                 while (md_find_rdev_nr_rcu(mddev, choice))
2152                         choice++;
2153                 rdev->desc_nr = choice;
2154         } else {
2155                 if (md_find_rdev_nr_rcu(mddev, rdev->desc_nr)) {
2156                         rcu_read_unlock();
2157                         return -EBUSY;
2158                 }
2159         }
2160         rcu_read_unlock();
2161         if (!test_bit(Journal, &rdev->flags) &&
2162             mddev->max_disks && rdev->desc_nr >= mddev->max_disks) {
2163                 pr_warn("md: %s: array is limited to %d devices\n",
2164                         mdname(mddev), mddev->max_disks);
2165                 return -EBUSY;
2166         }
2167         bdevname(rdev->bdev,b);
2168         strreplace(b, '/', '!');
2169
2170         rdev->mddev = mddev;
2171         pr_debug("md: bind<%s>\n", b);
2172
2173         if ((err = kobject_add(&rdev->kobj, &mddev->kobj, "dev-%s", b)))
2174                 goto fail;
2175
2176         ko = &part_to_dev(rdev->bdev->bd_part)->kobj;
2177         if (sysfs_create_link(&rdev->kobj, ko, "block"))
2178                 /* failure here is OK */;
2179         rdev->sysfs_state = sysfs_get_dirent_safe(rdev->kobj.sd, "state");
2180
2181         list_add_rcu(&rdev->same_set, &mddev->disks);
2182         bd_link_disk_holder(rdev->bdev, mddev->gendisk);
2183
2184         /* May as well allow recovery to be retried once */
2185         mddev->recovery_disabled++;
2186
2187         return 0;
2188
2189  fail:
2190         pr_warn("md: failed to register dev-%s for %s\n",
2191                 b, mdname(mddev));
2192         return err;
2193 }
2194
2195 static void md_delayed_delete(struct work_struct *ws)
2196 {
2197         struct md_rdev *rdev = container_of(ws, struct md_rdev, del_work);
2198         kobject_del(&rdev->kobj);
2199         kobject_put(&rdev->kobj);
2200 }
2201
2202 static void unbind_rdev_from_array(struct md_rdev *rdev)
2203 {
2204         char b[BDEVNAME_SIZE];
2205
2206         bd_unlink_disk_holder(rdev->bdev, rdev->mddev->gendisk);
2207         list_del_rcu(&rdev->same_set);
2208         pr_debug("md: unbind<%s>\n", bdevname(rdev->bdev,b));
2209         rdev->mddev = NULL;
2210         sysfs_remove_link(&rdev->kobj, "block");
2211         sysfs_put(rdev->sysfs_state);
2212         rdev->sysfs_state = NULL;
2213         rdev->badblocks.count = 0;
2214         /* We need to delay this, otherwise we can deadlock when
2215          * writing to 'remove' to "dev/state".  We also need
2216          * to delay it due to rcu usage.
2217          */
2218         synchronize_rcu();
2219         INIT_WORK(&rdev->del_work, md_delayed_delete);
2220         kobject_get(&rdev->kobj);
2221         queue_work(md_misc_wq, &rdev->del_work);
2222 }
2223
2224 /*
2225  * prevent the device from being mounted, repartitioned or
2226  * otherwise reused by a RAID array (or any other kernel
2227  * subsystem), by bd_claiming the device.
2228  */
2229 static int lock_rdev(struct md_rdev *rdev, dev_t dev, int shared)
2230 {
2231         int err = 0;
2232         struct block_device *bdev;
2233         char b[BDEVNAME_SIZE];
2234
2235         bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL,
2236                                  shared ? (struct md_rdev *)lock_rdev : rdev);
2237         if (IS_ERR(bdev)) {
2238                 pr_warn("md: could not open %s.\n", __bdevname(dev, b));
2239                 return PTR_ERR(bdev);
2240         }
2241         rdev->bdev = bdev;
2242         return err;
2243 }
2244
2245 static void unlock_rdev(struct md_rdev *rdev)
2246 {
2247         struct block_device *bdev = rdev->bdev;
2248         rdev->bdev = NULL;
2249         blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2250 }
2251
2252 void md_autodetect_dev(dev_t dev);
2253
2254 static void export_rdev(struct md_rdev *rdev)
2255 {
2256         char b[BDEVNAME_SIZE];
2257
2258         pr_debug("md: export_rdev(%s)\n", bdevname(rdev->bdev,b));
2259         md_rdev_clear(rdev);
2260 #ifndef MODULE
2261         if (test_bit(AutoDetected, &rdev->flags))
2262                 md_autodetect_dev(rdev->bdev->bd_dev);
2263 #endif
2264         unlock_rdev(rdev);
2265         kobject_put(&rdev->kobj);
2266 }
2267
2268 void md_kick_rdev_from_array(struct md_rdev *rdev)
2269 {
2270         unbind_rdev_from_array(rdev);
2271         export_rdev(rdev);
2272 }
2273 EXPORT_SYMBOL_GPL(md_kick_rdev_from_array);
2274
2275 static void export_array(struct mddev *mddev)
2276 {
2277         struct md_rdev *rdev;
2278
2279         while (!list_empty(&mddev->disks)) {
2280                 rdev = list_first_entry(&mddev->disks, struct md_rdev,
2281                                         same_set);
2282                 md_kick_rdev_from_array(rdev);
2283         }
2284         mddev->raid_disks = 0;
2285         mddev->major_version = 0;
2286 }
2287
2288 static bool set_in_sync(struct mddev *mddev)
2289 {
2290         WARN_ON_ONCE(!spin_is_locked(&mddev->lock));
2291         if (!mddev->in_sync) {
2292                 mddev->sync_checkers++;
2293                 spin_unlock(&mddev->lock);
2294                 percpu_ref_switch_to_atomic_sync(&mddev->writes_pending);
2295                 spin_lock(&mddev->lock);
2296                 if (!mddev->in_sync &&
2297                     percpu_ref_is_zero(&mddev->writes_pending)) {
2298                         mddev->in_sync = 1;
2299                         /*
2300                          * Ensure ->in_sync is visible before we clear
2301                          * ->sync_checkers.
2302                          */
2303                         smp_mb();
2304                         set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
2305                         sysfs_notify_dirent_safe(mddev->sysfs_state);
2306                 }
2307                 if (--mddev->sync_checkers == 0)
2308                         percpu_ref_switch_to_percpu(&mddev->writes_pending);
2309         }
2310         if (mddev->safemode == 1)
2311                 mddev->safemode = 0;
2312         return mddev->in_sync;
2313 }
2314
2315 static void sync_sbs(struct mddev *mddev, int nospares)
2316 {
2317         /* Update each superblock (in-memory image), but
2318          * if we are allowed to, skip spares which already
2319          * have the right event counter, or have one earlier
2320          * (which would mean they aren't being marked as dirty
2321          * with the rest of the array)
2322          */
2323         struct md_rdev *rdev;
2324         rdev_for_each(rdev, mddev) {
2325                 if (rdev->sb_events == mddev->events ||
2326                     (nospares &&
2327                      rdev->raid_disk < 0 &&
2328                      rdev->sb_events+1 == mddev->events)) {
2329                         /* Don't update this superblock */
2330                         rdev->sb_loaded = 2;
2331                 } else {
2332                         sync_super(mddev, rdev);
2333                         rdev->sb_loaded = 1;
2334                 }
2335         }
2336 }
2337
2338 static bool does_sb_need_changing(struct mddev *mddev)
2339 {
2340         struct md_rdev *rdev;
2341         struct mdp_superblock_1 *sb;
2342         int role;
2343
2344         /* Find a good rdev */
2345         rdev_for_each(rdev, mddev)
2346                 if ((rdev->raid_disk >= 0) && !test_bit(Faulty, &rdev->flags))
2347                         break;
2348
2349         /* No good device found. */
2350         if (!rdev)
2351                 return false;
2352
2353         sb = page_address(rdev->sb_page);
2354         /* Check if a device has become faulty or a spare become active */
2355         rdev_for_each(rdev, mddev) {
2356                 role = le16_to_cpu(sb->dev_roles[rdev->desc_nr]);
2357                 /* Device activated? */
2358                 if (role == 0xffff && rdev->raid_disk >=0 &&
2359                     !test_bit(Faulty, &rdev->flags))
2360                         return true;
2361                 /* Device turned faulty? */
2362                 if (test_bit(Faulty, &rdev->flags) && (role < 0xfffd))
2363                         return true;
2364         }
2365
2366         /* Check if any mddev parameters have changed */
2367         if ((mddev->dev_sectors != le64_to_cpu(sb->size)) ||
2368             (mddev->reshape_position != le64_to_cpu(sb->reshape_position)) ||
2369             (mddev->layout != le32_to_cpu(sb->layout)) ||
2370             (mddev->raid_disks != le32_to_cpu(sb->raid_disks)) ||
2371             (mddev->chunk_sectors != le32_to_cpu(sb->chunksize)))
2372                 return true;
2373
2374         return false;
2375 }
2376
2377 void md_update_sb(struct mddev *mddev, int force_change)
2378 {
2379         struct md_rdev *rdev;
2380         int sync_req;
2381         int nospares = 0;
2382         int any_badblocks_changed = 0;
2383         int ret = -1;
2384
2385         if (mddev->ro) {
2386                 if (force_change)
2387                         set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
2388                 return;
2389         }
2390
2391 repeat:
2392         if (mddev_is_clustered(mddev)) {
2393                 if (test_and_clear_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags))
2394                         force_change = 1;
2395                 if (test_and_clear_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags))
2396                         nospares = 1;
2397                 ret = md_cluster_ops->metadata_update_start(mddev);
2398                 /* Has someone else has updated the sb */
2399                 if (!does_sb_need_changing(mddev)) {
2400                         if (ret == 0)
2401                                 md_cluster_ops->metadata_update_cancel(mddev);
2402                         bit_clear_unless(&mddev->sb_flags, BIT(MD_SB_CHANGE_PENDING),
2403                                                          BIT(MD_SB_CHANGE_DEVS) |
2404                                                          BIT(MD_SB_CHANGE_CLEAN));
2405                         return;
2406                 }
2407         }
2408
2409         /* First make sure individual recovery_offsets are correct */
2410         rdev_for_each(rdev, mddev) {
2411                 if (rdev->raid_disk >= 0 &&
2412                     mddev->delta_disks >= 0 &&
2413                     !test_bit(Journal, &rdev->flags) &&
2414                     !test_bit(In_sync, &rdev->flags) &&
2415                     mddev->curr_resync_completed > rdev->recovery_offset)
2416                                 rdev->recovery_offset = mddev->curr_resync_completed;
2417
2418         }
2419         if (!mddev->persistent) {
2420                 clear_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
2421                 clear_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
2422                 if (!mddev->external) {
2423                         clear_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
2424                         rdev_for_each(rdev, mddev) {
2425                                 if (rdev->badblocks.changed) {
2426                                         rdev->badblocks.changed = 0;
2427                                         ack_all_badblocks(&rdev->badblocks);
2428                                         md_error(mddev, rdev);
2429                                 }
2430                                 clear_bit(Blocked, &rdev->flags);
2431                                 clear_bit(BlockedBadBlocks, &rdev->flags);
2432                                 wake_up(&rdev->blocked_wait);
2433                         }
2434                 }
2435                 wake_up(&mddev->sb_wait);
2436                 return;
2437         }
2438
2439         spin_lock(&mddev->lock);
2440
2441         mddev->utime = ktime_get_real_seconds();
2442
2443         if (test_and_clear_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags))
2444                 force_change = 1;
2445         if (test_and_clear_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags))
2446                 /* just a clean<-> dirty transition, possibly leave spares alone,
2447                  * though if events isn't the right even/odd, we will have to do
2448                  * spares after all
2449                  */
2450                 nospares = 1;
2451         if (force_change)
2452                 nospares = 0;
2453         if (mddev->degraded)
2454                 /* If the array is degraded, then skipping spares is both
2455                  * dangerous and fairly pointless.
2456                  * Dangerous because a device that was removed from the array
2457                  * might have a event_count that still looks up-to-date,
2458                  * so it can be re-added without a resync.
2459                  * Pointless because if there are any spares to skip,
2460                  * then a recovery will happen and soon that array won't
2461                  * be degraded any more and the spare can go back to sleep then.
2462                  */
2463                 nospares = 0;
2464
2465         sync_req = mddev->in_sync;
2466
2467         /* If this is just a dirty<->clean transition, and the array is clean
2468          * and 'events' is odd, we can roll back to the previous clean state */
2469         if (nospares
2470             && (mddev->in_sync && mddev->recovery_cp == MaxSector)
2471             && mddev->can_decrease_events
2472             && mddev->events != 1) {
2473                 mddev->events--;
2474                 mddev->can_decrease_events = 0;
2475         } else {
2476                 /* otherwise we have to go forward and ... */
2477                 mddev->events ++;
2478                 mddev->can_decrease_events = nospares;
2479         }
2480
2481         /*
2482          * This 64-bit counter should never wrap.
2483          * Either we are in around ~1 trillion A.C., assuming
2484          * 1 reboot per second, or we have a bug...
2485          */
2486         WARN_ON(mddev->events == 0);
2487
2488         rdev_for_each(rdev, mddev) {
2489                 if (rdev->badblocks.changed)
2490                         any_badblocks_changed++;
2491                 if (test_bit(Faulty, &rdev->flags))
2492                         set_bit(FaultRecorded, &rdev->flags);
2493         }
2494
2495         sync_sbs(mddev, nospares);
2496         spin_unlock(&mddev->lock);
2497
2498         pr_debug("md: updating %s RAID superblock on device (in sync %d)\n",
2499                  mdname(mddev), mddev->in_sync);
2500
2501         if (mddev->queue)
2502                 blk_add_trace_msg(mddev->queue, "md md_update_sb");
2503 rewrite:
2504         bitmap_update_sb(mddev->bitmap);
2505         rdev_for_each(rdev, mddev) {
2506                 char b[BDEVNAME_SIZE];
2507
2508                 if (rdev->sb_loaded != 1)
2509                         continue; /* no noise on spare devices */
2510
2511                 if (!test_bit(Faulty, &rdev->flags)) {
2512                         md_super_write(mddev,rdev,
2513                                        rdev->sb_start, rdev->sb_size,
2514                                        rdev->sb_page);
2515                         pr_debug("md: (write) %s's sb offset: %llu\n",
2516                                  bdevname(rdev->bdev, b),
2517                                  (unsigned long long)rdev->sb_start);
2518                         rdev->sb_events = mddev->events;
2519                         if (rdev->badblocks.size) {
2520                                 md_super_write(mddev, rdev,
2521                                                rdev->badblocks.sector,
2522                                                rdev->badblocks.size << 9,
2523                                                rdev->bb_page);
2524                                 rdev->badblocks.size = 0;
2525                         }
2526
2527                 } else
2528                         pr_debug("md: %s (skipping faulty)\n",
2529                                  bdevname(rdev->bdev, b));
2530
2531                 if (mddev->level == LEVEL_MULTIPATH)
2532                         /* only need to write one superblock... */
2533                         break;
2534         }
2535         if (md_super_wait(mddev) < 0)
2536                 goto rewrite;
2537         /* if there was a failure, MD_SB_CHANGE_DEVS was set, and we re-write super */
2538
2539         if (mddev_is_clustered(mddev) && ret == 0)
2540                 md_cluster_ops->metadata_update_finish(mddev);
2541
2542         if (mddev->in_sync != sync_req ||
2543             !bit_clear_unless(&mddev->sb_flags, BIT(MD_SB_CHANGE_PENDING),
2544                                BIT(MD_SB_CHANGE_DEVS) | BIT(MD_SB_CHANGE_CLEAN)))
2545                 /* have to write it out again */
2546                 goto repeat;
2547         wake_up(&mddev->sb_wait);
2548         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
2549                 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
2550
2551         rdev_for_each(rdev, mddev) {
2552                 if (test_and_clear_bit(FaultRecorded, &rdev->flags))
2553                         clear_bit(Blocked, &rdev->flags);
2554
2555                 if (any_badblocks_changed)
2556                         ack_all_badblocks(&rdev->badblocks);
2557                 clear_bit(BlockedBadBlocks, &rdev->flags);
2558                 wake_up(&rdev->blocked_wait);
2559         }
2560 }
2561 EXPORT_SYMBOL(md_update_sb);
2562
2563 static int add_bound_rdev(struct md_rdev *rdev)
2564 {
2565         struct mddev *mddev = rdev->mddev;
2566         int err = 0;
2567         bool add_journal = test_bit(Journal, &rdev->flags);
2568
2569         if (!mddev->pers->hot_remove_disk || add_journal) {
2570                 /* If there is hot_add_disk but no hot_remove_disk
2571                  * then added disks for geometry changes,
2572                  * and should be added immediately.
2573                  */
2574                 super_types[mddev->major_version].
2575                         validate_super(mddev, rdev);
2576                 if (add_journal)
2577                         mddev_suspend(mddev);
2578                 err = mddev->pers->hot_add_disk(mddev, rdev);
2579                 if (add_journal)
2580                         mddev_resume(mddev);
2581                 if (err) {
2582                         md_kick_rdev_from_array(rdev);
2583                         return err;
2584                 }
2585         }
2586         sysfs_notify_dirent_safe(rdev->sysfs_state);
2587
2588         set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
2589         if (mddev->degraded)
2590                 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
2591         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2592         md_new_event(mddev);
2593         md_wakeup_thread(mddev->thread);
2594         return 0;
2595 }
2596
2597 /* words written to sysfs files may, or may not, be \n terminated.
2598  * We want to accept with case. For this we use cmd_match.
2599  */
2600 static int cmd_match(const char *cmd, const char *str)
2601 {
2602         /* See if cmd, written into a sysfs file, matches
2603          * str.  They must either be the same, or cmd can
2604          * have a trailing newline
2605          */
2606         while (*cmd && *str && *cmd == *str) {
2607                 cmd++;
2608                 str++;
2609         }
2610         if (*cmd == '\n')
2611                 cmd++;
2612         if (*str || *cmd)
2613                 return 0;
2614         return 1;
2615 }
2616
2617 struct rdev_sysfs_entry {
2618         struct attribute attr;
2619         ssize_t (*show)(struct md_rdev *, char *);
2620         ssize_t (*store)(struct md_rdev *, const char *, size_t);
2621 };
2622
2623 static ssize_t
2624 state_show(struct md_rdev *rdev, char *page)
2625 {
2626         char *sep = ",";
2627         size_t len = 0;
2628         unsigned long flags = ACCESS_ONCE(rdev->flags);
2629
2630         if (test_bit(Faulty, &flags) ||
2631             (!test_bit(ExternalBbl, &flags) &&
2632             rdev->badblocks.unacked_exist))
2633                 len += sprintf(page+len, "faulty%s", sep);
2634         if (test_bit(In_sync, &flags))
2635                 len += sprintf(page+len, "in_sync%s", sep);
2636         if (test_bit(Journal, &flags))
2637                 len += sprintf(page+len, "journal%s", sep);
2638         if (test_bit(WriteMostly, &flags))
2639                 len += sprintf(page+len, "write_mostly%s", sep);
2640         if (test_bit(Blocked, &flags) ||
2641             (rdev->badblocks.unacked_exist
2642              && !test_bit(Faulty, &flags)))
2643                 len += sprintf(page+len, "blocked%s", sep);
2644         if (!test_bit(Faulty, &flags) &&
2645             !test_bit(Journal, &flags) &&
2646             !test_bit(In_sync, &flags))
2647                 len += sprintf(page+len, "spare%s", sep);
2648         if (test_bit(WriteErrorSeen, &flags))
2649                 len += sprintf(page+len, "write_error%s", sep);
2650         if (test_bit(WantReplacement, &flags))
2651                 len += sprintf(page+len, "want_replacement%s", sep);
2652         if (test_bit(Replacement, &flags))
2653                 len += sprintf(page+len, "replacement%s", sep);
2654         if (test_bit(ExternalBbl, &flags))
2655                 len += sprintf(page+len, "external_bbl%s", sep);
2656         if (test_bit(FailFast, &flags))
2657                 len += sprintf(page+len, "failfast%s", sep);
2658
2659         if (len)
2660                 len -= strlen(sep);
2661
2662         return len+sprintf(page+len, "\n");
2663 }
2664
2665 static ssize_t
2666 state_store(struct md_rdev *rdev, const char *buf, size_t len)
2667 {
2668         /* can write
2669          *  faulty  - simulates an error
2670          *  remove  - disconnects the device
2671          *  writemostly - sets write_mostly
2672          *  -writemostly - clears write_mostly
2673          *  blocked - sets the Blocked flags
2674          *  -blocked - clears the Blocked and possibly simulates an error
2675          *  insync - sets Insync providing device isn't active
2676          *  -insync - clear Insync for a device with a slot assigned,
2677          *            so that it gets rebuilt based on bitmap
2678          *  write_error - sets WriteErrorSeen
2679          *  -write_error - clears WriteErrorSeen
2680          *  {,-}failfast - set/clear FailFast
2681          */
2682         int err = -EINVAL;
2683         if (cmd_match(buf, "faulty") && rdev->mddev->pers) {
2684                 md_error(rdev->mddev, rdev);
2685                 if (test_bit(Faulty, &rdev->flags))
2686                         err = 0;
2687                 else
2688                         err = -EBUSY;
2689         } else if (cmd_match(buf, "remove")) {
2690                 if (rdev->mddev->pers) {
2691                         clear_bit(Blocked, &rdev->flags);
2692                         remove_and_add_spares(rdev->mddev, rdev);
2693                 }
2694                 if (rdev->raid_disk >= 0)
2695                         err = -EBUSY;
2696                 else {
2697                         struct mddev *mddev = rdev->mddev;
2698                         err = 0;
2699                         if (mddev_is_clustered(mddev))
2700                                 err = md_cluster_ops->remove_disk(mddev, rdev);
2701
2702                         if (err == 0) {
2703                                 md_kick_rdev_from_array(rdev);
2704                                 if (mddev->pers) {
2705                                         set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
2706                                         md_wakeup_thread(mddev->thread);
2707                                 }
2708                                 md_new_event(mddev);
2709                         }
2710                 }
2711         } else if (cmd_match(buf, "writemostly")) {
2712                 set_bit(WriteMostly, &rdev->flags);
2713                 err = 0;
2714         } else if (cmd_match(buf, "-writemostly")) {
2715                 clear_bit(WriteMostly, &rdev->flags);
2716                 err = 0;
2717         } else if (cmd_match(buf, "blocked")) {
2718                 set_bit(Blocked, &rdev->flags);
2719                 err = 0;
2720         } else if (cmd_match(buf, "-blocked")) {
2721                 if (!test_bit(Faulty, &rdev->flags) &&
2722                     !test_bit(ExternalBbl, &rdev->flags) &&
2723                     rdev->badblocks.unacked_exist) {
2724                         /* metadata handler doesn't understand badblocks,
2725                          * so we need to fail the device
2726                          */
2727                         md_error(rdev->mddev, rdev);
2728                 }
2729                 clear_bit(Blocked, &rdev->flags);
2730                 clear_bit(BlockedBadBlocks, &rdev->flags);
2731                 wake_up(&rdev->blocked_wait);
2732                 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2733                 md_wakeup_thread(rdev->mddev->thread);
2734
2735                 err = 0;
2736         } else if (cmd_match(buf, "insync") && rdev->raid_disk == -1) {
2737                 set_bit(In_sync, &rdev->flags);
2738                 err = 0;
2739         } else if (cmd_match(buf, "failfast")) {
2740                 set_bit(FailFast, &rdev->flags);
2741                 err = 0;
2742         } else if (cmd_match(buf, "-failfast")) {
2743                 clear_bit(FailFast, &rdev->flags);
2744                 err = 0;
2745         } else if (cmd_match(buf, "-insync") && rdev->raid_disk >= 0 &&
2746                    !test_bit(Journal, &rdev->flags)) {
2747                 if (rdev->mddev->pers == NULL) {
2748                         clear_bit(In_sync, &rdev->flags);
2749                         rdev->saved_raid_disk = rdev->raid_disk;
2750                         rdev->raid_disk = -1;
2751                         err = 0;
2752                 }
2753         } else if (cmd_match(buf, "write_error")) {
2754                 set_bit(WriteErrorSeen, &rdev->flags);
2755                 err = 0;
2756         } else if (cmd_match(buf, "-write_error")) {
2757                 clear_bit(WriteErrorSeen, &rdev->flags);
2758                 err = 0;
2759         } else if (cmd_match(buf, "want_replacement")) {
2760                 /* Any non-spare device that is not a replacement can
2761                  * become want_replacement at any time, but we then need to
2762                  * check if recovery is needed.
2763                  */
2764                 if (rdev->raid_disk >= 0 &&
2765                     !test_bit(Journal, &rdev->flags) &&
2766                     !test_bit(Replacement, &rdev->flags))
2767                         set_bit(WantReplacement, &rdev->flags);
2768                 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2769                 md_wakeup_thread(rdev->mddev->thread);
2770                 err = 0;
2771         } else if (cmd_match(buf, "-want_replacement")) {
2772                 /* Clearing 'want_replacement' is always allowed.
2773                  * Once replacements starts it is too late though.
2774                  */
2775                 err = 0;
2776                 clear_bit(WantReplacement, &rdev->flags);
2777         } else if (cmd_match(buf, "replacement")) {
2778                 /* Can only set a device as a replacement when array has not
2779                  * yet been started.  Once running, replacement is automatic
2780                  * from spares, or by assigning 'slot'.
2781                  */
2782                 if (rdev->mddev->pers)
2783                         err = -EBUSY;
2784                 else {
2785                         set_bit(Replacement, &rdev->flags);
2786                         err = 0;
2787                 }
2788         } else if (cmd_match(buf, "-replacement")) {
2789                 /* Similarly, can only clear Replacement before start */
2790                 if (rdev->mddev->pers)
2791                         err = -EBUSY;
2792                 else {
2793                         clear_bit(Replacement, &rdev->flags);
2794                         err = 0;
2795                 }
2796         } else if (cmd_match(buf, "re-add")) {
2797                 if (test_bit(Faulty, &rdev->flags) && (rdev->raid_disk == -1)) {
2798                         /* clear_bit is performed _after_ all the devices
2799                          * have their local Faulty bit cleared. If any writes
2800                          * happen in the meantime in the local node, they
2801                          * will land in the local bitmap, which will be synced
2802                          * by this node eventually
2803                          */
2804                         if (!mddev_is_clustered(rdev->mddev) ||
2805                             (err = md_cluster_ops->gather_bitmaps(rdev)) == 0) {
2806                                 clear_bit(Faulty, &rdev->flags);
2807                                 err = add_bound_rdev(rdev);
2808                         }
2809                 } else
2810                         err = -EBUSY;
2811         } else if (cmd_match(buf, "external_bbl") && (rdev->mddev->external)) {
2812                 set_bit(ExternalBbl, &rdev->flags);
2813                 rdev->badblocks.shift = 0;
2814                 err = 0;
2815         } else if (cmd_match(buf, "-external_bbl") && (rdev->mddev->external)) {
2816                 clear_bit(ExternalBbl, &rdev->flags);
2817                 err = 0;
2818         }
2819         if (!err)
2820                 sysfs_notify_dirent_safe(rdev->sysfs_state);
2821         return err ? err : len;
2822 }
2823 static struct rdev_sysfs_entry rdev_state =
2824 __ATTR_PREALLOC(state, S_IRUGO|S_IWUSR, state_show, state_store);
2825
2826 static ssize_t
2827 errors_show(struct md_rdev *rdev, char *page)
2828 {
2829         return sprintf(page, "%d\n", atomic_read(&rdev->corrected_errors));
2830 }
2831
2832 static ssize_t
2833 errors_store(struct md_rdev *rdev, const char *buf, size_t len)
2834 {
2835         unsigned int n;
2836         int rv;
2837
2838         rv = kstrtouint(buf, 10, &n);
2839         if (rv < 0)
2840                 return rv;
2841         atomic_set(&rdev->corrected_errors, n);
2842         return len;
2843 }
2844 static struct rdev_sysfs_entry rdev_errors =
2845 __ATTR(errors, S_IRUGO|S_IWUSR, errors_show, errors_store);
2846
2847 static ssize_t
2848 slot_show(struct md_rdev *rdev, char *page)
2849 {
2850         if (test_bit(Journal, &rdev->flags))
2851                 return sprintf(page, "journal\n");
2852         else if (rdev->raid_disk < 0)
2853                 return sprintf(page, "none\n");
2854         else
2855                 return sprintf(page, "%d\n", rdev->raid_disk);
2856 }
2857
2858 static ssize_t
2859 slot_store(struct md_rdev *rdev, const char *buf, size_t len)
2860 {
2861         int slot;
2862         int err;
2863
2864         if (test_bit(Journal, &rdev->flags))
2865                 return -EBUSY;
2866         if (strncmp(buf, "none", 4)==0)
2867                 slot = -1;
2868         else {
2869                 err = kstrtouint(buf, 10, (unsigned int *)&slot);
2870                 if (err < 0)
2871                         return err;
2872         }
2873         if (rdev->mddev->pers && slot == -1) {
2874                 /* Setting 'slot' on an active array requires also
2875                  * updating the 'rd%d' link, and communicating
2876                  * with the personality with ->hot_*_disk.
2877                  * For now we only support removing
2878                  * failed/spare devices.  This normally happens automatically,
2879                  * but not when the metadata is externally managed.
2880                  */
2881                 if (rdev->raid_disk == -1)
2882                         return -EEXIST;
2883                 /* personality does all needed checks */
2884                 if (rdev->mddev->pers->hot_remove_disk == NULL)
2885                         return -EINVAL;
2886                 clear_bit(Blocked, &rdev->flags);
2887                 remove_and_add_spares(rdev->mddev, rdev);
2888                 if (rdev->raid_disk >= 0)
2889                         return -EBUSY;
2890                 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2891                 md_wakeup_thread(rdev->mddev->thread);
2892         } else if (rdev->mddev->pers) {
2893                 /* Activating a spare .. or possibly reactivating
2894                  * if we ever get bitmaps working here.
2895                  */
2896                 int err;
2897
2898                 if (rdev->raid_disk != -1)
2899                         return -EBUSY;
2900
2901                 if (test_bit(MD_RECOVERY_RUNNING, &rdev->mddev->recovery))
2902                         return -EBUSY;
2903
2904                 if (rdev->mddev->pers->hot_add_disk == NULL)
2905                         return -EINVAL;
2906
2907                 if (slot >= rdev->mddev->raid_disks &&
2908                     slot >= rdev->mddev->raid_disks + rdev->mddev->delta_disks)
2909                         return -ENOSPC;
2910
2911                 rdev->raid_disk = slot;
2912                 if (test_bit(In_sync, &rdev->flags))
2913                         rdev->saved_raid_disk = slot;
2914                 else
2915                         rdev->saved_raid_disk = -1;
2916                 clear_bit(In_sync, &rdev->flags);
2917                 clear_bit(Bitmap_sync, &rdev->flags);
2918                 err = rdev->mddev->pers->
2919                         hot_add_disk(rdev->mddev, rdev);
2920                 if (err) {
2921                         rdev->raid_disk = -1;
2922                         return err;
2923                 } else
2924                         sysfs_notify_dirent_safe(rdev->sysfs_state);
2925                 if (sysfs_link_rdev(rdev->mddev, rdev))
2926                         /* failure here is OK */;
2927                 /* don't wakeup anyone, leave that to userspace. */
2928         } else {
2929                 if (slot >= rdev->mddev->raid_disks &&
2930                     slot >= rdev->mddev->raid_disks + rdev->mddev->delta_disks)
2931                         return -ENOSPC;
2932                 rdev->raid_disk = slot;
2933                 /* assume it is working */
2934                 clear_bit(Faulty, &rdev->flags);
2935                 clear_bit(WriteMostly, &rdev->flags);
2936                 set_bit(In_sync, &rdev->flags);
2937                 sysfs_notify_dirent_safe(rdev->sysfs_state);
2938         }
2939         return len;
2940 }
2941
2942 static struct rdev_sysfs_entry rdev_slot =
2943 __ATTR(slot, S_IRUGO|S_IWUSR, slot_show, slot_store);
2944
2945 static ssize_t
2946 offset_show(struct md_rdev *rdev, char *page)
2947 {
2948         return sprintf(page, "%llu\n", (unsigned long long)rdev->data_offset);
2949 }
2950
2951 static ssize_t
2952 offset_store(struct md_rdev *rdev, const char *buf, size_t len)
2953 {
2954         unsigned long long offset;
2955         if (kstrtoull(buf, 10, &offset) < 0)
2956                 return -EINVAL;
2957         if (rdev->mddev->pers && rdev->raid_disk >= 0)
2958                 return -EBUSY;
2959         if (rdev->sectors && rdev->mddev->external)
2960                 /* Must set offset before size, so overlap checks
2961                  * can be sane */
2962                 return -EBUSY;
2963         rdev->data_offset = offset;
2964         rdev->new_data_offset = offset;
2965         return len;
2966 }
2967
2968 static struct rdev_sysfs_entry rdev_offset =
2969 __ATTR(offset, S_IRUGO|S_IWUSR, offset_show, offset_store);
2970
2971 static ssize_t new_offset_show(struct md_rdev *rdev, char *page)
2972 {
2973         return sprintf(page, "%llu\n",
2974                        (unsigned long long)rdev->new_data_offset);
2975 }
2976
2977 static ssize_t new_offset_store(struct md_rdev *rdev,
2978                                 const char *buf, size_t len)
2979 {
2980         unsigned long long new_offset;
2981         struct mddev *mddev = rdev->mddev;
2982
2983         if (kstrtoull(buf, 10, &new_offset) < 0)
2984                 return -EINVAL;
2985
2986         if (mddev->sync_thread ||
2987             test_bit(MD_RECOVERY_RUNNING,&mddev->recovery))
2988                 return -EBUSY;
2989         if (new_offset == rdev->data_offset)
2990                 /* reset is always permitted */
2991                 ;
2992         else if (new_offset > rdev->data_offset) {
2993                 /* must not push array size beyond rdev_sectors */
2994                 if (new_offset - rdev->data_offset
2995                     + mddev->dev_sectors > rdev->sectors)
2996                                 return -E2BIG;
2997         }
2998         /* Metadata worries about other space details. */
2999
3000         /* decreasing the offset is inconsistent with a backwards
3001          * reshape.
3002          */
3003         if (new_offset < rdev->data_offset &&
3004             mddev->reshape_backwards)
3005                 return -EINVAL;
3006         /* Increasing offset is inconsistent with forwards
3007          * reshape.  reshape_direction should be set to
3008          * 'backwards' first.
3009          */
3010         if (new_offset > rdev->data_offset &&
3011             !mddev->reshape_backwards)
3012                 return -EINVAL;
3013
3014         if (mddev->pers && mddev->persistent &&
3015             !super_types[mddev->major_version]
3016             .allow_new_offset(rdev, new_offset))
3017                 return -E2BIG;
3018         rdev->new_data_offset = new_offset;
3019         if (new_offset > rdev->data_offset)
3020                 mddev->reshape_backwards = 1;
3021         else if (new_offset < rdev->data_offset)
3022                 mddev->reshape_backwards = 0;
3023
3024         return len;
3025 }
3026 static struct rdev_sysfs_entry rdev_new_offset =
3027 __ATTR(new_offset, S_IRUGO|S_IWUSR, new_offset_show, new_offset_store);
3028
3029 static ssize_t
3030 rdev_size_show(struct md_rdev *rdev, char *page)
3031 {
3032         return sprintf(page, "%llu\n", (unsigned long long)rdev->sectors / 2);
3033 }
3034
3035 static int overlaps(sector_t s1, sector_t l1, sector_t s2, sector_t l2)
3036 {
3037         /* check if two start/length pairs overlap */
3038         if (s1+l1 <= s2)
3039                 return 0;
3040         if (s2+l2 <= s1)
3041                 return 0;
3042         return 1;
3043 }
3044
3045 static int strict_blocks_to_sectors(const char *buf, sector_t *sectors)
3046 {
3047         unsigned long long blocks;
3048         sector_t new;
3049
3050         if (kstrtoull(buf, 10, &blocks) < 0)
3051                 return -EINVAL;
3052
3053         if (blocks & 1ULL << (8 * sizeof(blocks) - 1))
3054                 return -EINVAL; /* sector conversion overflow */
3055
3056         new = blocks * 2;
3057         if (new != blocks * 2)
3058                 return -EINVAL; /* unsigned long long to sector_t overflow */
3059
3060         *sectors = new;
3061         return 0;
3062 }
3063
3064 static ssize_t
3065 rdev_size_store(struct md_rdev *rdev, const char *buf, size_t len)
3066 {
3067         struct mddev *my_mddev = rdev->mddev;
3068         sector_t oldsectors = rdev->sectors;
3069         sector_t sectors;
3070
3071         if (test_bit(Journal, &rdev->flags))
3072                 return -EBUSY;
3073         if (strict_blocks_to_sectors(buf, &sectors) < 0)
3074                 return -EINVAL;
3075         if (rdev->data_offset != rdev->new_data_offset)
3076                 return -EINVAL; /* too confusing */
3077         if (my_mddev->pers && rdev->raid_disk >= 0) {
3078                 if (my_mddev->persistent) {
3079                         sectors = super_types[my_mddev->major_version].
3080                                 rdev_size_change(rdev, sectors);
3081                         if (!sectors)
3082                                 return -EBUSY;
3083                 } else if (!sectors)
3084                         sectors = (i_size_read(rdev->bdev->bd_inode) >> 9) -
3085                                 rdev->data_offset;
3086                 if (!my_mddev->pers->resize)
3087                         /* Cannot change size for RAID0 or Linear etc */
3088                         return -EINVAL;
3089         }
3090         if (sectors < my_mddev->dev_sectors)
3091                 return -EINVAL; /* component must fit device */
3092
3093         rdev->sectors = sectors;
3094         if (sectors > oldsectors && my_mddev->external) {
3095                 /* Need to check that all other rdevs with the same
3096                  * ->bdev do not overlap.  'rcu' is sufficient to walk
3097                  * the rdev lists safely.
3098                  * This check does not provide a hard guarantee, it
3099                  * just helps avoid dangerous mistakes.
3100                  */
3101                 struct mddev *mddev;
3102                 int overlap = 0;
3103                 struct list_head *tmp;
3104
3105                 rcu_read_lock();
3106                 for_each_mddev(mddev, tmp) {
3107                         struct md_rdev *rdev2;
3108
3109                         rdev_for_each(rdev2, mddev)
3110                                 if (rdev->bdev == rdev2->bdev &&
3111                                     rdev != rdev2 &&
3112                                     overlaps(rdev->data_offset, rdev->sectors,
3113                                              rdev2->data_offset,
3114                                              rdev2->sectors)) {
3115                                         overlap = 1;
3116                                         break;
3117                                 }
3118                         if (overlap) {
3119                                 mddev_put(mddev);
3120                                 break;
3121                         }
3122                 }
3123                 rcu_read_unlock();
3124                 if (overlap) {
3125                         /* Someone else could have slipped in a size
3126                          * change here, but doing so is just silly.
3127                          * We put oldsectors back because we *know* it is
3128                          * safe, and trust userspace not to race with
3129                          * itself
3130                          */
3131                         rdev->sectors = oldsectors;
3132                         return -EBUSY;
3133                 }
3134         }
3135         return len;
3136 }
3137
3138 static struct rdev_sysfs_entry rdev_size =
3139 __ATTR(size, S_IRUGO|S_IWUSR, rdev_size_show, rdev_size_store);
3140
3141 static ssize_t recovery_start_show(struct md_rdev *rdev, char *page)
3142 {
3143         unsigned long long recovery_start = rdev->recovery_offset;
3144
3145         if (test_bit(In_sync, &rdev->flags) ||
3146             recovery_start == MaxSector)
3147                 return sprintf(page, "none\n");
3148
3149         return sprintf(page, "%llu\n", recovery_start);
3150 }
3151
3152 static ssize_t recovery_start_store(struct md_rdev *rdev, const char *buf, size_t len)
3153 {
3154         unsigned long long recovery_start;
3155
3156         if (cmd_match(buf, "none"))
3157                 recovery_start = MaxSector;
3158         else if (kstrtoull(buf, 10, &recovery_start))
3159                 return -EINVAL;
3160
3161         if (rdev->mddev->pers &&
3162             rdev->raid_disk >= 0)
3163                 return -EBUSY;
3164
3165         rdev->recovery_offset = recovery_start;
3166         if (recovery_start == MaxSector)
3167                 set_bit(In_sync, &rdev->flags);
3168         else
3169                 clear_bit(In_sync, &rdev->flags);
3170         return len;
3171 }
3172
3173 static struct rdev_sysfs_entry rdev_recovery_start =
3174 __ATTR(recovery_start, S_IRUGO|S_IWUSR, recovery_start_show, recovery_start_store);
3175
3176 /* sysfs access to bad-blocks list.
3177  * We present two files.
3178  * 'bad-blocks' lists sector numbers and lengths of ranges that
3179  *    are recorded as bad.  The list is truncated to fit within
3180  *    the one-page limit of sysfs.
3181  *    Writing "sector length" to this file adds an acknowledged
3182  *    bad block list.
3183  * 'unacknowledged-bad-blocks' lists bad blocks that have not yet
3184  *    been acknowledged.  Writing to this file adds bad blocks
3185  *    without acknowledging them.  This is largely for testing.
3186  */
3187 static ssize_t bb_show(struct md_rdev *rdev, char *page)
3188 {
3189         return badblocks_show(&rdev->badblocks, page, 0);
3190 }
3191 static ssize_t bb_store(struct md_rdev *rdev, const char *page, size_t len)
3192 {
3193         int rv = badblocks_store(&rdev->badblocks, page, len, 0);
3194         /* Maybe that ack was all we needed */
3195         if (test_and_clear_bit(BlockedBadBlocks, &rdev->flags))
3196                 wake_up(&rdev->blocked_wait);
3197         return rv;
3198 }
3199 static struct rdev_sysfs_entry rdev_bad_blocks =
3200 __ATTR(bad_blocks, S_IRUGO|S_IWUSR, bb_show, bb_store);
3201
3202 static ssize_t ubb_show(struct md_rdev *rdev, char *page)
3203 {
3204         return badblocks_show(&rdev->badblocks, page, 1);
3205 }
3206 static ssize_t ubb_store(struct md_rdev *rdev, const char *page, size_t len)
3207 {
3208         return badblocks_store(&rdev->badblocks, page, len, 1);
3209 }
3210 static struct rdev_sysfs_entry rdev_unack_bad_blocks =
3211 __ATTR(unacknowledged_bad_blocks, S_IRUGO|S_IWUSR, ubb_show, ubb_store);
3212
3213 static ssize_t
3214 ppl_sector_show(struct md_rdev *rdev, char *page)
3215 {
3216         return sprintf(page, "%llu\n", (unsigned long long)rdev->ppl.sector);
3217 }
3218
3219 static ssize_t
3220 ppl_sector_store(struct md_rdev *rdev, const char *buf, size_t len)
3221 {
3222         unsigned long long sector;
3223
3224         if (kstrtoull(buf, 10, &sector) < 0)
3225                 return -EINVAL;
3226         if (sector != (sector_t)sector)
3227                 return -EINVAL;
3228
3229         if (rdev->mddev->pers && test_bit(MD_HAS_PPL, &rdev->mddev->flags) &&
3230             rdev->raid_disk >= 0)
3231                 return -EBUSY;
3232
3233         if (rdev->mddev->persistent) {
3234                 if (rdev->mddev->major_version == 0)
3235                         return -EINVAL;
3236                 if ((sector > rdev->sb_start &&
3237                      sector - rdev->sb_start > S16_MAX) ||
3238                     (sector < rdev->sb_start &&
3239                      rdev->sb_start - sector > -S16_MIN))
3240                         return -EINVAL;
3241                 rdev->ppl.offset = sector - rdev->sb_start;
3242         } else if (!rdev->mddev->external) {
3243                 return -EBUSY;
3244         }
3245         rdev->ppl.sector = sector;
3246         return len;
3247 }
3248
3249 static struct rdev_sysfs_entry rdev_ppl_sector =
3250 __ATTR(ppl_sector, S_IRUGO|S_IWUSR, ppl_sector_show, ppl_sector_store);
3251
3252 static ssize_t
3253 ppl_size_show(struct md_rdev *rdev, char *page)
3254 {
3255         return sprintf(page, "%u\n", rdev->ppl.size);
3256 }
3257
3258 static ssize_t
3259 ppl_size_store(struct md_rdev *rdev, const char *buf, size_t len)
3260 {
3261         unsigned int size;
3262
3263         if (kstrtouint(buf, 10, &size) < 0)
3264                 return -EINVAL;
3265
3266         if (rdev->mddev->pers && test_bit(MD_HAS_PPL, &rdev->mddev->flags) &&
3267             rdev->raid_disk >= 0)
3268                 return -EBUSY;
3269
3270         if (rdev->mddev->persistent) {
3271                 if (rdev->mddev->major_version == 0)
3272                         return -EINVAL;
3273                 if (size > U16_MAX)
3274                         return -EINVAL;
3275         } else if (!rdev->mddev->external) {
3276                 return -EBUSY;
3277         }
3278         rdev->ppl.size = size;
3279         return len;
3280 }
3281
3282 static struct rdev_sysfs_entry rdev_ppl_size =
3283 __ATTR(ppl_size, S_IRUGO|S_IWUSR, ppl_size_show, ppl_size_store);
3284
3285 static struct attribute *rdev_default_attrs[] = {
3286         &rdev_state.attr,
3287         &rdev_errors.attr,
3288         &rdev_slot.attr,
3289         &rdev_offset.attr,
3290         &rdev_new_offset.attr,
3291         &rdev_size.attr,
3292         &rdev_recovery_start.attr,
3293         &rdev_bad_blocks.attr,
3294         &rdev_unack_bad_blocks.attr,
3295         &rdev_ppl_sector.attr,
3296         &rdev_ppl_size.attr,
3297         NULL,
3298 };
3299 static ssize_t
3300 rdev_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
3301 {
3302         struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
3303         struct md_rdev *rdev = container_of(kobj, struct md_rdev, kobj);
3304
3305         if (!entry->show)
3306                 return -EIO;
3307         if (!rdev->mddev)
3308                 return -EBUSY;
3309         return entry->show(rdev, page);
3310 }
3311
3312 static ssize_t
3313 rdev_attr_store(struct kobject *kobj, struct attribute *attr,
3314               const char *page, size_t length)
3315 {
3316         struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
3317         struct md_rdev *rdev = container_of(kobj, struct md_rdev, kobj);
3318         ssize_t rv;
3319         struct mddev *mddev = rdev->mddev;
3320
3321         if (!entry->store)
3322                 return -EIO;
3323         if (!capable(CAP_SYS_ADMIN))
3324                 return -EACCES;
3325         rv = mddev ? mddev_lock(mddev): -EBUSY;
3326         if (!rv) {
3327                 if (rdev->mddev == NULL)
3328                         rv = -EBUSY;
3329                 else
3330                         rv = entry->store(rdev, page, length);
3331                 mddev_unlock(mddev);
3332         }
3333         return rv;
3334 }
3335
3336 static void rdev_free(struct kobject *ko)
3337 {
3338         struct md_rdev *rdev = container_of(ko, struct md_rdev, kobj);
3339         kfree(rdev);
3340 }
3341 static const struct sysfs_ops rdev_sysfs_ops = {
3342         .show           = rdev_attr_show,
3343         .store          = rdev_attr_store,
3344 };
3345 static struct kobj_type rdev_ktype = {
3346         .release        = rdev_free,
3347         .sysfs_ops      = &rdev_sysfs_ops,
3348         .default_attrs  = rdev_default_attrs,
3349 };
3350
3351 int md_rdev_init(struct md_rdev *rdev)
3352 {
3353         rdev->desc_nr = -1;
3354         rdev->saved_raid_disk = -1;
3355         rdev->raid_disk = -1;
3356         rdev->flags = 0;
3357         rdev->data_offset = 0;
3358         rdev->new_data_offset = 0;
3359         rdev->sb_events = 0;
3360         rdev->last_read_error = 0;
3361         rdev->sb_loaded = 0;
3362         rdev->bb_page = NULL;
3363         atomic_set(&rdev->nr_pending, 0);
3364         atomic_set(&rdev->read_errors, 0);
3365         atomic_set(&rdev->corrected_errors, 0);
3366
3367         INIT_LIST_HEAD(&rdev->same_set);
3368         init_waitqueue_head(&rdev->blocked_wait);
3369
3370