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