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