bcache: fix static checker warning in bcache_device_free()
[platform/kernel/linux-rpi.git] / drivers / md / md.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3    md.c : Multiple Devices driver for Linux
4      Copyright (C) 1998, 1999, 2000 Ingo Molnar
5
6      completely rewritten, based on the MD driver code from Marc Zyngier
7
8    Changes:
9
10    - RAID-1/RAID-5 extensions by Miguel de Icaza, Gadi Oxman, Ingo Molnar
11    - RAID-6 extensions by H. Peter Anvin <hpa@zytor.com>
12    - boot support for linear and striped mode by Harald Hoyer <HarryH@Royal.Net>
13    - kerneld support by Boris Tobotras <boris@xtalk.msk.su>
14    - kmod support by: Cyrus Durgin
15    - RAID0 bugfixes: Mark Anthony Lisher <markal@iname.com>
16    - Devfs support by Richard Gooch <rgooch@atnf.csiro.au>
17
18    - lots of fixes and improvements to the RAID1/RAID5 and generic
19      RAID code (such as request based resynchronization):
20
21      Neil Brown <neilb@cse.unsw.edu.au>.
22
23    - persistent bitmap code
24      Copyright (C) 2003-2004, Paul Clements, SteelEye Technology, Inc.
25
26
27    Errors, Warnings, etc.
28    Please use:
29      pr_crit() for error conditions that risk data loss
30      pr_err() for error conditions that are unexpected, like an IO error
31          or internal inconsistency
32      pr_warn() for error conditions that could have been predicated, like
33          adding a device to an array when it has incompatible metadata
34      pr_info() for every interesting, very rare events, like an array starting
35          or stopping, or resync starting or stopping
36      pr_debug() for everything else.
37
38 */
39
40 #include <linux/sched/mm.h>
41 #include <linux/sched/signal.h>
42 #include <linux/kthread.h>
43 #include <linux/blkdev.h>
44 #include <linux/badblocks.h>
45 #include <linux/sysctl.h>
46 #include <linux/seq_file.h>
47 #include <linux/fs.h>
48 #include <linux/poll.h>
49 #include <linux/ctype.h>
50 #include <linux/string.h>
51 #include <linux/hdreg.h>
52 #include <linux/proc_fs.h>
53 #include <linux/random.h>
54 #include <linux/module.h>
55 #include <linux/reboot.h>
56 #include <linux/file.h>
57 #include <linux/compat.h>
58 #include <linux/delay.h>
59 #include <linux/raid/md_p.h>
60 #include <linux/raid/md_u.h>
61 #include <linux/slab.h>
62 #include <linux/percpu-refcount.h>
63
64 #include <trace/events/block.h>
65 #include "md.h"
66 #include "md-bitmap.h"
67 #include "md-cluster.h"
68
69 #ifndef MODULE
70 static void autostart_arrays(int part);
71 #endif
72
73 /* pers_list is a list of registered personalities protected
74  * by pers_lock.
75  * pers_lock does extra service to protect accesses to
76  * mddev->thread when the mutex cannot be held.
77  */
78 static LIST_HEAD(pers_list);
79 static DEFINE_SPINLOCK(pers_lock);
80
81 static struct kobj_type md_ktype;
82
83 struct md_cluster_operations *md_cluster_ops;
84 EXPORT_SYMBOL(md_cluster_ops);
85 static struct module *md_cluster_mod;
86
87 static DECLARE_WAIT_QUEUE_HEAD(resync_wait);
88 static struct workqueue_struct *md_wq;
89 static struct workqueue_struct *md_misc_wq;
90
91 static int remove_and_add_spares(struct mddev *mddev,
92                                  struct md_rdev *this);
93 static void mddev_detach(struct mddev *mddev);
94
95 /*
96  * Default number of read corrections we'll attempt on an rdev
97  * before ejecting it from the array. We divide the read error
98  * count by 2 for every hour elapsed between read errors.
99  */
100 #define MD_DEFAULT_MAX_CORRECTED_READ_ERRORS 20
101 /*
102  * Current RAID-1,4,5 parallel reconstruction 'guaranteed speed limit'
103  * is 1000 KB/sec, so the extra system load does not show up that much.
104  * Increase it if you want to have more _guaranteed_ speed. Note that
105  * the RAID driver will use the maximum available bandwidth if the IO
106  * subsystem is idle. There is also an 'absolute maximum' reconstruction
107  * speed limit - in case reconstruction slows down your system despite
108  * idle IO detection.
109  *
110  * you can change it via /proc/sys/dev/raid/speed_limit_min and _max.
111  * or /sys/block/mdX/md/sync_speed_{min,max}
112  */
113
114 static int sysctl_speed_limit_min = 1000;
115 static int sysctl_speed_limit_max = 200000;
116 static inline int speed_min(struct mddev *mddev)
117 {
118         return mddev->sync_speed_min ?
119                 mddev->sync_speed_min : sysctl_speed_limit_min;
120 }
121
122 static inline int speed_max(struct mddev *mddev)
123 {
124         return mddev->sync_speed_max ?
125                 mddev->sync_speed_max : sysctl_speed_limit_max;
126 }
127
128 static int rdev_init_wb(struct md_rdev *rdev)
129 {
130         if (rdev->bdev->bd_queue->nr_hw_queues == 1)
131                 return 0;
132
133         spin_lock_init(&rdev->wb_list_lock);
134         INIT_LIST_HEAD(&rdev->wb_list);
135         init_waitqueue_head(&rdev->wb_io_wait);
136         set_bit(WBCollisionCheck, &rdev->flags);
137
138         return 1;
139 }
140
141 /*
142  * Create wb_info_pool if rdev is the first multi-queue device flaged
143  * with writemostly, also write-behind mode is enabled.
144  */
145 void mddev_create_wb_pool(struct mddev *mddev, struct md_rdev *rdev,
146                           bool is_suspend)
147 {
148         if (mddev->bitmap_info.max_write_behind == 0)
149                 return;
150
151         if (!test_bit(WriteMostly, &rdev->flags) || !rdev_init_wb(rdev))
152                 return;
153
154         if (mddev->wb_info_pool == NULL) {
155                 unsigned int noio_flag;
156
157                 if (!is_suspend)
158                         mddev_suspend(mddev);
159                 noio_flag = memalloc_noio_save();
160                 mddev->wb_info_pool = mempool_create_kmalloc_pool(NR_WB_INFOS,
161                                                         sizeof(struct wb_info));
162                 memalloc_noio_restore(noio_flag);
163                 if (!mddev->wb_info_pool)
164                         pr_err("can't alloc memory pool for writemostly\n");
165                 if (!is_suspend)
166                         mddev_resume(mddev);
167         }
168 }
169 EXPORT_SYMBOL_GPL(mddev_create_wb_pool);
170
171 /*
172  * destroy wb_info_pool if rdev is the last device flaged with WBCollisionCheck.
173  */
174 static void mddev_destroy_wb_pool(struct mddev *mddev, struct md_rdev *rdev)
175 {
176         if (!test_and_clear_bit(WBCollisionCheck, &rdev->flags))
177                 return;
178
179         if (mddev->wb_info_pool) {
180                 struct md_rdev *temp;
181                 int num = 0;
182
183                 /*
184                  * Check if other rdevs need wb_info_pool.
185                  */
186                 rdev_for_each(temp, mddev)
187                         if (temp != rdev &&
188                             test_bit(WBCollisionCheck, &temp->flags))
189                                 num++;
190                 if (!num) {
191                         mddev_suspend(rdev->mddev);
192                         mempool_destroy(mddev->wb_info_pool);
193                         mddev->wb_info_pool = NULL;
194                         mddev_resume(rdev->mddev);
195                 }
196         }
197 }
198
199 static struct ctl_table_header *raid_table_header;
200
201 static struct ctl_table raid_table[] = {
202         {
203                 .procname       = "speed_limit_min",
204                 .data           = &sysctl_speed_limit_min,
205                 .maxlen         = sizeof(int),
206                 .mode           = S_IRUGO|S_IWUSR,
207                 .proc_handler   = proc_dointvec,
208         },
209         {
210                 .procname       = "speed_limit_max",
211                 .data           = &sysctl_speed_limit_max,
212                 .maxlen         = sizeof(int),
213                 .mode           = S_IRUGO|S_IWUSR,
214                 .proc_handler   = proc_dointvec,
215         },
216         { }
217 };
218
219 static struct ctl_table raid_dir_table[] = {
220         {
221                 .procname       = "raid",
222                 .maxlen         = 0,
223                 .mode           = S_IRUGO|S_IXUGO,
224                 .child          = raid_table,
225         },
226         { }
227 };
228
229 static struct ctl_table raid_root_table[] = {
230         {
231                 .procname       = "dev",
232                 .maxlen         = 0,
233                 .mode           = 0555,
234                 .child          = raid_dir_table,
235         },
236         {  }
237 };
238
239 static const struct block_device_operations md_fops;
240
241 static int start_readonly;
242
243 /*
244  * The original mechanism for creating an md device is to create
245  * a device node in /dev and to open it.  This causes races with device-close.
246  * The preferred method is to write to the "new_array" module parameter.
247  * This can avoid races.
248  * Setting create_on_open to false disables the original mechanism
249  * so all the races disappear.
250  */
251 static bool create_on_open = true;
252
253 struct bio *bio_alloc_mddev(gfp_t gfp_mask, int nr_iovecs,
254                             struct mddev *mddev)
255 {
256         if (!mddev || !bioset_initialized(&mddev->bio_set))
257                 return bio_alloc(gfp_mask, nr_iovecs);
258
259         return bio_alloc_bioset(gfp_mask, nr_iovecs, &mddev->bio_set);
260 }
261 EXPORT_SYMBOL_GPL(bio_alloc_mddev);
262
263 static struct bio *md_bio_alloc_sync(struct mddev *mddev)
264 {
265         if (!mddev || !bioset_initialized(&mddev->sync_set))
266                 return bio_alloc(GFP_NOIO, 1);
267
268         return bio_alloc_bioset(GFP_NOIO, 1, &mddev->sync_set);
269 }
270
271 /*
272  * We have a system wide 'event count' that is incremented
273  * on any 'interesting' event, and readers of /proc/mdstat
274  * can use 'poll' or 'select' to find out when the event
275  * count increases.
276  *
277  * Events are:
278  *  start array, stop array, error, add device, remove device,
279  *  start build, activate spare
280  */
281 static DECLARE_WAIT_QUEUE_HEAD(md_event_waiters);
282 static atomic_t md_event_count;
283 void md_new_event(struct mddev *mddev)
284 {
285         atomic_inc(&md_event_count);
286         wake_up(&md_event_waiters);
287 }
288 EXPORT_SYMBOL_GPL(md_new_event);
289
290 /*
291  * Enables to iterate over all existing md arrays
292  * all_mddevs_lock protects this list.
293  */
294 static LIST_HEAD(all_mddevs);
295 static DEFINE_SPINLOCK(all_mddevs_lock);
296
297 /*
298  * iterates through all used mddevs in the system.
299  * We take care to grab the all_mddevs_lock whenever navigating
300  * the list, and to always hold a refcount when unlocked.
301  * Any code which breaks out of this loop while own
302  * a reference to the current mddev and must mddev_put it.
303  */
304 #define for_each_mddev(_mddev,_tmp)                                     \
305                                                                         \
306         for (({ spin_lock(&all_mddevs_lock);                            \
307                 _tmp = all_mddevs.next;                                 \
308                 _mddev = NULL;});                                       \
309              ({ if (_tmp != &all_mddevs)                                \
310                         mddev_get(list_entry(_tmp, struct mddev, all_mddevs));\
311                 spin_unlock(&all_mddevs_lock);                          \
312                 if (_mddev) mddev_put(_mddev);                          \
313                 _mddev = list_entry(_tmp, struct mddev, all_mddevs);    \
314                 _tmp != &all_mddevs;});                                 \
315              ({ spin_lock(&all_mddevs_lock);                            \
316                 _tmp = _tmp->next;})                                    \
317                 )
318
319 /* Rather than calling directly into the personality make_request function,
320  * IO requests come here first so that we can check if the device is
321  * being suspended pending a reconfiguration.
322  * We hold a refcount over the call to ->make_request.  By the time that
323  * call has finished, the bio has been linked into some internal structure
324  * and so is visible to ->quiesce(), so we don't need the refcount any more.
325  */
326 static bool is_suspended(struct mddev *mddev, struct bio *bio)
327 {
328         if (mddev->suspended)
329                 return true;
330         if (bio_data_dir(bio) != WRITE)
331                 return false;
332         if (mddev->suspend_lo >= mddev->suspend_hi)
333                 return false;
334         if (bio->bi_iter.bi_sector >= mddev->suspend_hi)
335                 return false;
336         if (bio_end_sector(bio) < mddev->suspend_lo)
337                 return false;
338         return true;
339 }
340
341 void md_handle_request(struct mddev *mddev, struct bio *bio)
342 {
343 check_suspended:
344         rcu_read_lock();
345         if (is_suspended(mddev, bio)) {
346                 DEFINE_WAIT(__wait);
347                 for (;;) {
348                         prepare_to_wait(&mddev->sb_wait, &__wait,
349                                         TASK_UNINTERRUPTIBLE);
350                         if (!is_suspended(mddev, bio))
351                                 break;
352                         rcu_read_unlock();
353                         schedule();
354                         rcu_read_lock();
355                 }
356                 finish_wait(&mddev->sb_wait, &__wait);
357         }
358         atomic_inc(&mddev->active_io);
359         rcu_read_unlock();
360
361         if (!mddev->pers->make_request(mddev, bio)) {
362                 atomic_dec(&mddev->active_io);
363                 wake_up(&mddev->sb_wait);
364                 goto check_suspended;
365         }
366
367         if (atomic_dec_and_test(&mddev->active_io) && mddev->suspended)
368                 wake_up(&mddev->sb_wait);
369 }
370 EXPORT_SYMBOL(md_handle_request);
371
372 static blk_qc_t md_make_request(struct request_queue *q, struct bio *bio)
373 {
374         const int rw = bio_data_dir(bio);
375         const int sgrp = op_stat_group(bio_op(bio));
376         struct mddev *mddev = q->queuedata;
377         unsigned int sectors;
378
379         if (unlikely(test_bit(MD_BROKEN, &mddev->flags)) && (rw == WRITE)) {
380                 bio_io_error(bio);
381                 return BLK_QC_T_NONE;
382         }
383
384         blk_queue_split(q, &bio);
385
386         if (mddev == NULL || mddev->pers == NULL) {
387                 bio_io_error(bio);
388                 return BLK_QC_T_NONE;
389         }
390         if (mddev->ro == 1 && unlikely(rw == WRITE)) {
391                 if (bio_sectors(bio) != 0)
392                         bio->bi_status = BLK_STS_IOERR;
393                 bio_endio(bio);
394                 return BLK_QC_T_NONE;
395         }
396
397         /*
398          * save the sectors now since our bio can
399          * go away inside make_request
400          */
401         sectors = bio_sectors(bio);
402         /* bio could be mergeable after passing to underlayer */
403         bio->bi_opf &= ~REQ_NOMERGE;
404
405         md_handle_request(mddev, bio);
406
407         part_stat_lock();
408         part_stat_inc(&mddev->gendisk->part0, ios[sgrp]);
409         part_stat_add(&mddev->gendisk->part0, sectors[sgrp], sectors);
410         part_stat_unlock();
411
412         return BLK_QC_T_NONE;
413 }
414
415 /* mddev_suspend makes sure no new requests are submitted
416  * to the device, and that any requests that have been submitted
417  * are completely handled.
418  * Once mddev_detach() is called and completes, the module will be
419  * completely unused.
420  */
421 void mddev_suspend(struct mddev *mddev)
422 {
423         WARN_ON_ONCE(mddev->thread && current == mddev->thread->tsk);
424         lockdep_assert_held(&mddev->reconfig_mutex);
425         if (mddev->suspended++)
426                 return;
427         synchronize_rcu();
428         wake_up(&mddev->sb_wait);
429         set_bit(MD_ALLOW_SB_UPDATE, &mddev->flags);
430         smp_mb__after_atomic();
431         wait_event(mddev->sb_wait, atomic_read(&mddev->active_io) == 0);
432         mddev->pers->quiesce(mddev, 1);
433         clear_bit_unlock(MD_ALLOW_SB_UPDATE, &mddev->flags);
434         wait_event(mddev->sb_wait, !test_bit(MD_UPDATING_SB, &mddev->flags));
435
436         del_timer_sync(&mddev->safemode_timer);
437 }
438 EXPORT_SYMBOL_GPL(mddev_suspend);
439
440 void mddev_resume(struct mddev *mddev)
441 {
442         lockdep_assert_held(&mddev->reconfig_mutex);
443         if (--mddev->suspended)
444                 return;
445         wake_up(&mddev->sb_wait);
446         mddev->pers->quiesce(mddev, 0);
447
448         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
449         md_wakeup_thread(mddev->thread);
450         md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
451 }
452 EXPORT_SYMBOL_GPL(mddev_resume);
453
454 int mddev_congested(struct mddev *mddev, int bits)
455 {
456         struct md_personality *pers = mddev->pers;
457         int ret = 0;
458
459         rcu_read_lock();
460         if (mddev->suspended)
461                 ret = 1;
462         else if (pers && pers->congested)
463                 ret = pers->congested(mddev, bits);
464         rcu_read_unlock();
465         return ret;
466 }
467 EXPORT_SYMBOL_GPL(mddev_congested);
468 static int md_congested(void *data, int bits)
469 {
470         struct mddev *mddev = data;
471         return mddev_congested(mddev, bits);
472 }
473
474 /*
475  * Generic flush handling for md
476  */
477
478 static void md_end_flush(struct bio *bio)
479 {
480         struct md_rdev *rdev = bio->bi_private;
481         struct mddev *mddev = rdev->mddev;
482
483         rdev_dec_pending(rdev, mddev);
484
485         if (atomic_dec_and_test(&mddev->flush_pending)) {
486                 /* The pre-request flush has finished */
487                 queue_work(md_wq, &mddev->flush_work);
488         }
489         bio_put(bio);
490 }
491
492 static void md_submit_flush_data(struct work_struct *ws);
493
494 static void submit_flushes(struct work_struct *ws)
495 {
496         struct mddev *mddev = container_of(ws, struct mddev, flush_work);
497         struct md_rdev *rdev;
498
499         mddev->start_flush = ktime_get_boottime();
500         INIT_WORK(&mddev->flush_work, md_submit_flush_data);
501         atomic_set(&mddev->flush_pending, 1);
502         rcu_read_lock();
503         rdev_for_each_rcu(rdev, mddev)
504                 if (rdev->raid_disk >= 0 &&
505                     !test_bit(Faulty, &rdev->flags)) {
506                         /* Take two references, one is dropped
507                          * when request finishes, one after
508                          * we reclaim rcu_read_lock
509                          */
510                         struct bio *bi;
511                         atomic_inc(&rdev->nr_pending);
512                         atomic_inc(&rdev->nr_pending);
513                         rcu_read_unlock();
514                         bi = bio_alloc_mddev(GFP_NOIO, 0, mddev);
515                         bi->bi_end_io = md_end_flush;
516                         bi->bi_private = rdev;
517                         bio_set_dev(bi, rdev->bdev);
518                         bi->bi_opf = REQ_OP_WRITE | REQ_PREFLUSH;
519                         atomic_inc(&mddev->flush_pending);
520                         submit_bio(bi);
521                         rcu_read_lock();
522                         rdev_dec_pending(rdev, mddev);
523                 }
524         rcu_read_unlock();
525         if (atomic_dec_and_test(&mddev->flush_pending))
526                 queue_work(md_wq, &mddev->flush_work);
527 }
528
529 static void md_submit_flush_data(struct work_struct *ws)
530 {
531         struct mddev *mddev = container_of(ws, struct mddev, flush_work);
532         struct bio *bio = mddev->flush_bio;
533
534         /*
535          * must reset flush_bio before calling into md_handle_request to avoid a
536          * deadlock, because other bios passed md_handle_request suspend check
537          * could wait for this and below md_handle_request could wait for those
538          * bios because of suspend check
539          */
540         mddev->last_flush = mddev->start_flush;
541         mddev->flush_bio = NULL;
542         wake_up(&mddev->sb_wait);
543
544         if (bio->bi_iter.bi_size == 0) {
545                 /* an empty barrier - all done */
546                 bio_endio(bio);
547         } else {
548                 bio->bi_opf &= ~REQ_PREFLUSH;
549                 md_handle_request(mddev, bio);
550         }
551 }
552
553 /*
554  * Manages consolidation of flushes and submitting any flushes needed for
555  * a bio with REQ_PREFLUSH.  Returns true if the bio is finished or is
556  * being finished in another context.  Returns false if the flushing is
557  * complete but still needs the I/O portion of the bio to be processed.
558  */
559 bool md_flush_request(struct mddev *mddev, struct bio *bio)
560 {
561         ktime_t start = ktime_get_boottime();
562         spin_lock_irq(&mddev->lock);
563         wait_event_lock_irq(mddev->sb_wait,
564                             !mddev->flush_bio ||
565                             ktime_after(mddev->last_flush, start),
566                             mddev->lock);
567         if (!ktime_after(mddev->last_flush, start)) {
568                 WARN_ON(mddev->flush_bio);
569                 mddev->flush_bio = bio;
570                 bio = NULL;
571         }
572         spin_unlock_irq(&mddev->lock);
573
574         if (!bio) {
575                 INIT_WORK(&mddev->flush_work, submit_flushes);
576                 queue_work(md_wq, &mddev->flush_work);
577         } else {
578                 /* flush was performed for some other bio while we waited. */
579                 if (bio->bi_iter.bi_size == 0)
580                         /* an empty barrier - all done */
581                         bio_endio(bio);
582                 else {
583                         bio->bi_opf &= ~REQ_PREFLUSH;
584                         return false;
585                 }
586         }
587         return true;
588 }
589 EXPORT_SYMBOL(md_flush_request);
590
591 static inline struct mddev *mddev_get(struct mddev *mddev)
592 {
593         atomic_inc(&mddev->active);
594         return mddev;
595 }
596
597 static void mddev_delayed_delete(struct work_struct *ws);
598
599 static void mddev_put(struct mddev *mddev)
600 {
601         if (!atomic_dec_and_lock(&mddev->active, &all_mddevs_lock))
602                 return;
603         if (!mddev->raid_disks && list_empty(&mddev->disks) &&
604             mddev->ctime == 0 && !mddev->hold_active) {
605                 /* Array is not configured at all, and not held active,
606                  * so destroy it */
607                 list_del_init(&mddev->all_mddevs);
608
609                 /*
610                  * Call queue_work inside the spinlock so that
611                  * flush_workqueue() after mddev_find will succeed in waiting
612                  * for the work to be done.
613                  */
614                 INIT_WORK(&mddev->del_work, mddev_delayed_delete);
615                 queue_work(md_misc_wq, &mddev->del_work);
616         }
617         spin_unlock(&all_mddevs_lock);
618 }
619
620 static void md_safemode_timeout(struct timer_list *t);
621
622 void mddev_init(struct mddev *mddev)
623 {
624         kobject_init(&mddev->kobj, &md_ktype);
625         mutex_init(&mddev->open_mutex);
626         mutex_init(&mddev->reconfig_mutex);
627         mutex_init(&mddev->bitmap_info.mutex);
628         INIT_LIST_HEAD(&mddev->disks);
629         INIT_LIST_HEAD(&mddev->all_mddevs);
630         timer_setup(&mddev->safemode_timer, md_safemode_timeout, 0);
631         atomic_set(&mddev->active, 1);
632         atomic_set(&mddev->openers, 0);
633         atomic_set(&mddev->active_io, 0);
634         spin_lock_init(&mddev->lock);
635         atomic_set(&mddev->flush_pending, 0);
636         init_waitqueue_head(&mddev->sb_wait);
637         init_waitqueue_head(&mddev->recovery_wait);
638         mddev->reshape_position = MaxSector;
639         mddev->reshape_backwards = 0;
640         mddev->last_sync_action = "none";
641         mddev->resync_min = 0;
642         mddev->resync_max = MaxSector;
643         mddev->level = LEVEL_NONE;
644 }
645 EXPORT_SYMBOL_GPL(mddev_init);
646
647 static struct mddev *mddev_find(dev_t unit)
648 {
649         struct mddev *mddev, *new = NULL;
650
651         if (unit && MAJOR(unit) != MD_MAJOR)
652                 unit &= ~((1<<MdpMinorShift)-1);
653
654  retry:
655         spin_lock(&all_mddevs_lock);
656
657         if (unit) {
658                 list_for_each_entry(mddev, &all_mddevs, all_mddevs)
659                         if (mddev->unit == unit) {
660                                 mddev_get(mddev);
661                                 spin_unlock(&all_mddevs_lock);
662                                 kfree(new);
663                                 return mddev;
664                         }
665
666                 if (new) {
667                         list_add(&new->all_mddevs, &all_mddevs);
668                         spin_unlock(&all_mddevs_lock);
669                         new->hold_active = UNTIL_IOCTL;
670                         return new;
671                 }
672         } else if (new) {
673                 /* find an unused unit number */
674                 static int next_minor = 512;
675                 int start = next_minor;
676                 int is_free = 0;
677                 int dev = 0;
678                 while (!is_free) {
679                         dev = MKDEV(MD_MAJOR, next_minor);
680                         next_minor++;
681                         if (next_minor > MINORMASK)
682                                 next_minor = 0;
683                         if (next_minor == start) {
684                                 /* Oh dear, all in use. */
685                                 spin_unlock(&all_mddevs_lock);
686                                 kfree(new);
687                                 return NULL;
688                         }
689
690                         is_free = 1;
691                         list_for_each_entry(mddev, &all_mddevs, all_mddevs)
692                                 if (mddev->unit == dev) {
693                                         is_free = 0;
694                                         break;
695                                 }
696                 }
697                 new->unit = dev;
698                 new->md_minor = MINOR(dev);
699                 new->hold_active = UNTIL_STOP;
700                 list_add(&new->all_mddevs, &all_mddevs);
701                 spin_unlock(&all_mddevs_lock);
702                 return new;
703         }
704         spin_unlock(&all_mddevs_lock);
705
706         new = kzalloc(sizeof(*new), GFP_KERNEL);
707         if (!new)
708                 return NULL;
709
710         new->unit = unit;
711         if (MAJOR(unit) == MD_MAJOR)
712                 new->md_minor = MINOR(unit);
713         else
714                 new->md_minor = MINOR(unit) >> MdpMinorShift;
715
716         mddev_init(new);
717
718         goto retry;
719 }
720
721 static struct attribute_group md_redundancy_group;
722
723 void mddev_unlock(struct mddev *mddev)
724 {
725         if (mddev->to_remove) {
726                 /* These cannot be removed under reconfig_mutex as
727                  * an access to the files will try to take reconfig_mutex
728                  * while holding the file unremovable, which leads to
729                  * a deadlock.
730                  * So hold set sysfs_active while the remove in happeing,
731                  * and anything else which might set ->to_remove or my
732                  * otherwise change the sysfs namespace will fail with
733                  * -EBUSY if sysfs_active is still set.
734                  * We set sysfs_active under reconfig_mutex and elsewhere
735                  * test it under the same mutex to ensure its correct value
736                  * is seen.
737                  */
738                 struct attribute_group *to_remove = mddev->to_remove;
739                 mddev->to_remove = NULL;
740                 mddev->sysfs_active = 1;
741                 mutex_unlock(&mddev->reconfig_mutex);
742
743                 if (mddev->kobj.sd) {
744                         if (to_remove != &md_redundancy_group)
745                                 sysfs_remove_group(&mddev->kobj, to_remove);
746                         if (mddev->pers == NULL ||
747                             mddev->pers->sync_request == NULL) {
748                                 sysfs_remove_group(&mddev->kobj, &md_redundancy_group);
749                                 if (mddev->sysfs_action)
750                                         sysfs_put(mddev->sysfs_action);
751                                 mddev->sysfs_action = NULL;
752                         }
753                 }
754                 mddev->sysfs_active = 0;
755         } else
756                 mutex_unlock(&mddev->reconfig_mutex);
757
758         /* As we've dropped the mutex we need a spinlock to
759          * make sure the thread doesn't disappear
760          */
761         spin_lock(&pers_lock);
762         md_wakeup_thread(mddev->thread);
763         wake_up(&mddev->sb_wait);
764         spin_unlock(&pers_lock);
765 }
766 EXPORT_SYMBOL_GPL(mddev_unlock);
767
768 struct md_rdev *md_find_rdev_nr_rcu(struct mddev *mddev, int nr)
769 {
770         struct md_rdev *rdev;
771
772         rdev_for_each_rcu(rdev, mddev)
773                 if (rdev->desc_nr == nr)
774                         return rdev;
775
776         return NULL;
777 }
778 EXPORT_SYMBOL_GPL(md_find_rdev_nr_rcu);
779
780 static struct md_rdev *find_rdev(struct mddev *mddev, dev_t dev)
781 {
782         struct md_rdev *rdev;
783
784         rdev_for_each(rdev, mddev)
785                 if (rdev->bdev->bd_dev == dev)
786                         return rdev;
787
788         return NULL;
789 }
790
791 struct md_rdev *md_find_rdev_rcu(struct mddev *mddev, dev_t dev)
792 {
793         struct md_rdev *rdev;
794
795         rdev_for_each_rcu(rdev, mddev)
796                 if (rdev->bdev->bd_dev == dev)
797                         return rdev;
798
799         return NULL;
800 }
801 EXPORT_SYMBOL_GPL(md_find_rdev_rcu);
802
803 static struct md_personality *find_pers(int level, char *clevel)
804 {
805         struct md_personality *pers;
806         list_for_each_entry(pers, &pers_list, list) {
807                 if (level != LEVEL_NONE && pers->level == level)
808                         return pers;
809                 if (strcmp(pers->name, clevel)==0)
810                         return pers;
811         }
812         return NULL;
813 }
814
815 /* return the offset of the super block in 512byte sectors */
816 static inline sector_t calc_dev_sboffset(struct md_rdev *rdev)
817 {
818         sector_t num_sectors = i_size_read(rdev->bdev->bd_inode) / 512;
819         return MD_NEW_SIZE_SECTORS(num_sectors);
820 }
821
822 static int alloc_disk_sb(struct md_rdev *rdev)
823 {
824         rdev->sb_page = alloc_page(GFP_KERNEL);
825         if (!rdev->sb_page)
826                 return -ENOMEM;
827         return 0;
828 }
829
830 void md_rdev_clear(struct md_rdev *rdev)
831 {
832         if (rdev->sb_page) {
833                 put_page(rdev->sb_page);
834                 rdev->sb_loaded = 0;
835                 rdev->sb_page = NULL;
836                 rdev->sb_start = 0;
837                 rdev->sectors = 0;
838         }
839         if (rdev->bb_page) {
840                 put_page(rdev->bb_page);
841                 rdev->bb_page = NULL;
842         }
843         badblocks_exit(&rdev->badblocks);
844 }
845 EXPORT_SYMBOL_GPL(md_rdev_clear);
846
847 static void super_written(struct bio *bio)
848 {
849         struct md_rdev *rdev = bio->bi_private;
850         struct mddev *mddev = rdev->mddev;
851
852         if (bio->bi_status) {
853                 pr_err("md: super_written gets error=%d\n", bio->bi_status);
854                 md_error(mddev, rdev);
855                 if (!test_bit(Faulty, &rdev->flags)
856                     && (bio->bi_opf & MD_FAILFAST)) {
857                         set_bit(MD_SB_NEED_REWRITE, &mddev->sb_flags);
858                         set_bit(LastDev, &rdev->flags);
859                 }
860         } else
861                 clear_bit(LastDev, &rdev->flags);
862
863         if (atomic_dec_and_test(&mddev->pending_writes))
864                 wake_up(&mddev->sb_wait);
865         rdev_dec_pending(rdev, mddev);
866         bio_put(bio);
867 }
868
869 void md_super_write(struct mddev *mddev, struct md_rdev *rdev,
870                    sector_t sector, int size, struct page *page)
871 {
872         /* write first size bytes of page to sector of rdev
873          * Increment mddev->pending_writes before returning
874          * and decrement it on completion, waking up sb_wait
875          * if zero is reached.
876          * If an error occurred, call md_error
877          */
878         struct bio *bio;
879         int ff = 0;
880
881         if (!page)
882                 return;
883
884         if (test_bit(Faulty, &rdev->flags))
885                 return;
886
887         bio = md_bio_alloc_sync(mddev);
888
889         atomic_inc(&rdev->nr_pending);
890
891         bio_set_dev(bio, rdev->meta_bdev ? rdev->meta_bdev : rdev->bdev);
892         bio->bi_iter.bi_sector = sector;
893         bio_add_page(bio, page, size, 0);
894         bio->bi_private = rdev;
895         bio->bi_end_io = super_written;
896
897         if (test_bit(MD_FAILFAST_SUPPORTED, &mddev->flags) &&
898             test_bit(FailFast, &rdev->flags) &&
899             !test_bit(LastDev, &rdev->flags))
900                 ff = MD_FAILFAST;
901         bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH | REQ_FUA | ff;
902
903         atomic_inc(&mddev->pending_writes);
904         submit_bio(bio);
905 }
906
907 int md_super_wait(struct mddev *mddev)
908 {
909         /* wait for all superblock writes that were scheduled to complete */
910         wait_event(mddev->sb_wait, atomic_read(&mddev->pending_writes)==0);
911         if (test_and_clear_bit(MD_SB_NEED_REWRITE, &mddev->sb_flags))
912                 return -EAGAIN;
913         return 0;
914 }
915
916 int sync_page_io(struct md_rdev *rdev, sector_t sector, int size,
917                  struct page *page, int op, int op_flags, bool metadata_op)
918 {
919         struct bio *bio = md_bio_alloc_sync(rdev->mddev);
920         int ret;
921
922         if (metadata_op && rdev->meta_bdev)
923                 bio_set_dev(bio, rdev->meta_bdev);
924         else
925                 bio_set_dev(bio, rdev->bdev);
926         bio_set_op_attrs(bio, op, op_flags);
927         if (metadata_op)
928                 bio->bi_iter.bi_sector = sector + rdev->sb_start;
929         else if (rdev->mddev->reshape_position != MaxSector &&
930                  (rdev->mddev->reshape_backwards ==
931                   (sector >= rdev->mddev->reshape_position)))
932                 bio->bi_iter.bi_sector = sector + rdev->new_data_offset;
933         else
934                 bio->bi_iter.bi_sector = sector + rdev->data_offset;
935         bio_add_page(bio, page, size, 0);
936
937         submit_bio_wait(bio);
938
939         ret = !bio->bi_status;
940         bio_put(bio);
941         return ret;
942 }
943 EXPORT_SYMBOL_GPL(sync_page_io);
944
945 static int read_disk_sb(struct md_rdev *rdev, int size)
946 {
947         char b[BDEVNAME_SIZE];
948
949         if (rdev->sb_loaded)
950                 return 0;
951
952         if (!sync_page_io(rdev, 0, size, rdev->sb_page, REQ_OP_READ, 0, true))
953                 goto fail;
954         rdev->sb_loaded = 1;
955         return 0;
956
957 fail:
958         pr_err("md: disabled device %s, could not read superblock.\n",
959                bdevname(rdev->bdev,b));
960         return -EINVAL;
961 }
962
963 static int md_uuid_equal(mdp_super_t *sb1, mdp_super_t *sb2)
964 {
965         return  sb1->set_uuid0 == sb2->set_uuid0 &&
966                 sb1->set_uuid1 == sb2->set_uuid1 &&
967                 sb1->set_uuid2 == sb2->set_uuid2 &&
968                 sb1->set_uuid3 == sb2->set_uuid3;
969 }
970
971 static int md_sb_equal(mdp_super_t *sb1, mdp_super_t *sb2)
972 {
973         int ret;
974         mdp_super_t *tmp1, *tmp2;
975
976         tmp1 = kmalloc(sizeof(*tmp1),GFP_KERNEL);
977         tmp2 = kmalloc(sizeof(*tmp2),GFP_KERNEL);
978
979         if (!tmp1 || !tmp2) {
980                 ret = 0;
981                 goto abort;
982         }
983
984         *tmp1 = *sb1;
985         *tmp2 = *sb2;
986
987         /*
988          * nr_disks is not constant
989          */
990         tmp1->nr_disks = 0;
991         tmp2->nr_disks = 0;
992
993         ret = (memcmp(tmp1, tmp2, MD_SB_GENERIC_CONSTANT_WORDS * 4) == 0);
994 abort:
995         kfree(tmp1);
996         kfree(tmp2);
997         return ret;
998 }
999
1000 static u32 md_csum_fold(u32 csum)
1001 {
1002         csum = (csum & 0xffff) + (csum >> 16);
1003         return (csum & 0xffff) + (csum >> 16);
1004 }
1005
1006 static unsigned int calc_sb_csum(mdp_super_t *sb)
1007 {
1008         u64 newcsum = 0;
1009         u32 *sb32 = (u32*)sb;
1010         int i;
1011         unsigned int disk_csum, csum;
1012
1013         disk_csum = sb->sb_csum;
1014         sb->sb_csum = 0;
1015
1016         for (i = 0; i < MD_SB_BYTES/4 ; i++)
1017                 newcsum += sb32[i];
1018         csum = (newcsum & 0xffffffff) + (newcsum>>32);
1019
1020 #ifdef CONFIG_ALPHA
1021         /* This used to use csum_partial, which was wrong for several
1022          * reasons including that different results are returned on
1023          * different architectures.  It isn't critical that we get exactly
1024          * the same return value as before (we always csum_fold before
1025          * testing, and that removes any differences).  However as we
1026          * know that csum_partial always returned a 16bit value on
1027          * alphas, do a fold to maximise conformity to previous behaviour.
1028          */
1029         sb->sb_csum = md_csum_fold(disk_csum);
1030 #else
1031         sb->sb_csum = disk_csum;
1032 #endif
1033         return csum;
1034 }
1035
1036 /*
1037  * Handle superblock details.
1038  * We want to be able to handle multiple superblock formats
1039  * so we have a common interface to them all, and an array of
1040  * different handlers.
1041  * We rely on user-space to write the initial superblock, and support
1042  * reading and updating of superblocks.
1043  * Interface methods are:
1044  *   int load_super(struct md_rdev *dev, struct md_rdev *refdev, int minor_version)
1045  *      loads and validates a superblock on dev.
1046  *      if refdev != NULL, compare superblocks on both devices
1047  *    Return:
1048  *      0 - dev has a superblock that is compatible with refdev
1049  *      1 - dev has a superblock that is compatible and newer than refdev
1050  *          so dev should be used as the refdev in future
1051  *     -EINVAL superblock incompatible or invalid
1052  *     -othererror e.g. -EIO
1053  *
1054  *   int validate_super(struct mddev *mddev, struct md_rdev *dev)
1055  *      Verify that dev is acceptable into mddev.
1056  *       The first time, mddev->raid_disks will be 0, and data from
1057  *       dev should be merged in.  Subsequent calls check that dev
1058  *       is new enough.  Return 0 or -EINVAL
1059  *
1060  *   void sync_super(struct mddev *mddev, struct md_rdev *dev)
1061  *     Update the superblock for rdev with data in mddev
1062  *     This does not write to disc.
1063  *
1064  */
1065
1066 struct super_type  {
1067         char                *name;
1068         struct module       *owner;
1069         int                 (*load_super)(struct md_rdev *rdev,
1070                                           struct md_rdev *refdev,
1071                                           int minor_version);
1072         int                 (*validate_super)(struct mddev *mddev,
1073                                               struct md_rdev *rdev);
1074         void                (*sync_super)(struct mddev *mddev,
1075                                           struct md_rdev *rdev);
1076         unsigned long long  (*rdev_size_change)(struct md_rdev *rdev,
1077                                                 sector_t num_sectors);
1078         int                 (*allow_new_offset)(struct md_rdev *rdev,
1079                                                 unsigned long long new_offset);
1080 };
1081
1082 /*
1083  * Check that the given mddev has no bitmap.
1084  *
1085  * This function is called from the run method of all personalities that do not
1086  * support bitmaps. It prints an error message and returns non-zero if mddev
1087  * has a bitmap. Otherwise, it returns 0.
1088  *
1089  */
1090 int md_check_no_bitmap(struct mddev *mddev)
1091 {
1092         if (!mddev->bitmap_info.file && !mddev->bitmap_info.offset)
1093                 return 0;
1094         pr_warn("%s: bitmaps are not supported for %s\n",
1095                 mdname(mddev), mddev->pers->name);
1096         return 1;
1097 }
1098 EXPORT_SYMBOL(md_check_no_bitmap);
1099
1100 /*
1101  * load_super for 0.90.0
1102  */
1103 static int super_90_load(struct md_rdev *rdev, struct md_rdev *refdev, int minor_version)
1104 {
1105         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1106         mdp_super_t *sb;
1107         int ret;
1108
1109         /*
1110          * Calculate the position of the superblock (512byte sectors),
1111          * it's at the end of the disk.
1112          *
1113          * It also happens to be a multiple of 4Kb.
1114          */
1115         rdev->sb_start = calc_dev_sboffset(rdev);
1116
1117         ret = read_disk_sb(rdev, MD_SB_BYTES);
1118         if (ret)
1119                 return ret;
1120
1121         ret = -EINVAL;
1122
1123         bdevname(rdev->bdev, b);
1124         sb = page_address(rdev->sb_page);
1125
1126         if (sb->md_magic != MD_SB_MAGIC) {
1127                 pr_warn("md: invalid raid superblock magic on %s\n", b);
1128                 goto abort;
1129         }
1130
1131         if (sb->major_version != 0 ||
1132             sb->minor_version < 90 ||
1133             sb->minor_version > 91) {
1134                 pr_warn("Bad version number %d.%d on %s\n",
1135                         sb->major_version, sb->minor_version, b);
1136                 goto abort;
1137         }
1138
1139         if (sb->raid_disks <= 0)
1140                 goto abort;
1141
1142         if (md_csum_fold(calc_sb_csum(sb)) != md_csum_fold(sb->sb_csum)) {
1143                 pr_warn("md: invalid superblock checksum on %s\n", b);
1144                 goto abort;
1145         }
1146
1147         rdev->preferred_minor = sb->md_minor;
1148         rdev->data_offset = 0;
1149         rdev->new_data_offset = 0;
1150         rdev->sb_size = MD_SB_BYTES;
1151         rdev->badblocks.shift = -1;
1152
1153         if (sb->level == LEVEL_MULTIPATH)
1154                 rdev->desc_nr = -1;
1155         else
1156                 rdev->desc_nr = sb->this_disk.number;
1157
1158         if (!refdev) {
1159                 /*
1160                  * Insist on good event counter while assembling, except
1161                  * for spares (which don't need an event count)
1162                  */
1163                 if (sb->disks[rdev->desc_nr].state & (
1164                         (1<<MD_DISK_SYNC) | (1 << MD_DISK_ACTIVE)))
1165                         ret = 1;
1166                 else
1167                         ret = 0;
1168         } else {
1169                 __u64 ev1, ev2;
1170                 mdp_super_t *refsb = page_address(refdev->sb_page);
1171                 if (!md_uuid_equal(refsb, sb)) {
1172                         pr_warn("md: %s has different UUID to %s\n",
1173                                 b, bdevname(refdev->bdev,b2));
1174                         goto abort;
1175                 }
1176                 if (!md_sb_equal(refsb, sb)) {
1177                         pr_warn("md: %s has same UUID but different superblock to %s\n",
1178                                 b, bdevname(refdev->bdev, b2));
1179                         goto abort;
1180                 }
1181                 ev1 = md_event(sb);
1182                 ev2 = md_event(refsb);
1183
1184                 /*
1185                  * Insist on good event counter while assembling, except
1186                  * for spares (which don't need an event count)
1187                  */
1188                 if (sb->disks[rdev->desc_nr].state & (
1189                         (1<<MD_DISK_SYNC) | (1 << MD_DISK_ACTIVE)) &&
1190                         (ev1 > ev2))
1191                         ret = 1;
1192                 else
1193                         ret = 0;
1194         }
1195         rdev->sectors = rdev->sb_start;
1196         /* Limit to 4TB as metadata cannot record more than that.
1197          * (not needed for Linear and RAID0 as metadata doesn't
1198          * record this size)
1199          */
1200         if ((u64)rdev->sectors >= (2ULL << 32) && sb->level >= 1)
1201                 rdev->sectors = (sector_t)(2ULL << 32) - 2;
1202
1203         if (rdev->sectors < ((sector_t)sb->size) * 2 && sb->level >= 1)
1204                 /* "this cannot possibly happen" ... */
1205                 ret = -EINVAL;
1206
1207  abort:
1208         return ret;
1209 }
1210
1211 /*
1212  * validate_super for 0.90.0
1213  */
1214 static int super_90_validate(struct mddev *mddev, struct md_rdev *rdev)
1215 {
1216         mdp_disk_t *desc;
1217         mdp_super_t *sb = page_address(rdev->sb_page);
1218         __u64 ev1 = md_event(sb);
1219
1220         rdev->raid_disk = -1;
1221         clear_bit(Faulty, &rdev->flags);
1222         clear_bit(In_sync, &rdev->flags);
1223         clear_bit(Bitmap_sync, &rdev->flags);
1224         clear_bit(WriteMostly, &rdev->flags);
1225
1226         if (mddev->raid_disks == 0) {
1227                 mddev->major_version = 0;
1228                 mddev->minor_version = sb->minor_version;
1229                 mddev->patch_version = sb->patch_version;
1230                 mddev->external = 0;
1231                 mddev->chunk_sectors = sb->chunk_size >> 9;
1232                 mddev->ctime = sb->ctime;
1233                 mddev->utime = sb->utime;
1234                 mddev->level = sb->level;
1235                 mddev->clevel[0] = 0;
1236                 mddev->layout = sb->layout;
1237                 mddev->raid_disks = sb->raid_disks;
1238                 mddev->dev_sectors = ((sector_t)sb->size) * 2;
1239                 mddev->events = ev1;
1240                 mddev->bitmap_info.offset = 0;
1241                 mddev->bitmap_info.space = 0;
1242                 /* bitmap can use 60 K after the 4K superblocks */
1243                 mddev->bitmap_info.default_offset = MD_SB_BYTES >> 9;
1244                 mddev->bitmap_info.default_space = 64*2 - (MD_SB_BYTES >> 9);
1245                 mddev->reshape_backwards = 0;
1246
1247                 if (mddev->minor_version >= 91) {
1248                         mddev->reshape_position = sb->reshape_position;
1249                         mddev->delta_disks = sb->delta_disks;
1250                         mddev->new_level = sb->new_level;
1251                         mddev->new_layout = sb->new_layout;
1252                         mddev->new_chunk_sectors = sb->new_chunk >> 9;
1253                         if (mddev->delta_disks < 0)
1254                                 mddev->reshape_backwards = 1;
1255                 } else {
1256                         mddev->reshape_position = MaxSector;
1257                         mddev->delta_disks = 0;
1258                         mddev->new_level = mddev->level;
1259                         mddev->new_layout = mddev->layout;
1260                         mddev->new_chunk_sectors = mddev->chunk_sectors;
1261                 }
1262                 if (mddev->level == 0)
1263                         mddev->layout = -1;
1264
1265                 if (sb->state & (1<<MD_SB_CLEAN))
1266                         mddev->recovery_cp = MaxSector;
1267                 else {
1268                         if (sb->events_hi == sb->cp_events_hi &&
1269                                 sb->events_lo == sb->cp_events_lo) {
1270                                 mddev->recovery_cp = sb->recovery_cp;
1271                         } else
1272                                 mddev->recovery_cp = 0;
1273                 }
1274
1275                 memcpy(mddev->uuid+0, &sb->set_uuid0, 4);
1276                 memcpy(mddev->uuid+4, &sb->set_uuid1, 4);
1277                 memcpy(mddev->uuid+8, &sb->set_uuid2, 4);
1278                 memcpy(mddev->uuid+12,&sb->set_uuid3, 4);
1279
1280                 mddev->max_disks = MD_SB_DISKS;
1281
1282                 if (sb->state & (1<<MD_SB_BITMAP_PRESENT) &&
1283                     mddev->bitmap_info.file == NULL) {
1284                         mddev->bitmap_info.offset =
1285                                 mddev->bitmap_info.default_offset;
1286                         mddev->bitmap_info.space =
1287                                 mddev->bitmap_info.default_space;
1288                 }
1289
1290         } else if (mddev->pers == NULL) {
1291                 /* Insist on good event counter while assembling, except
1292                  * for spares (which don't need an event count) */
1293                 ++ev1;
1294                 if (sb->disks[rdev->desc_nr].state & (
1295                             (1<<MD_DISK_SYNC) | (1 << MD_DISK_ACTIVE)))
1296                         if (ev1 < mddev->events)
1297                                 return -EINVAL;
1298         } else if (mddev->bitmap) {
1299                 /* if adding to array with a bitmap, then we can accept an
1300                  * older device ... but not too old.
1301                  */
1302                 if (ev1 < mddev->bitmap->events_cleared)
1303                         return 0;
1304                 if (ev1 < mddev->events)
1305                         set_bit(Bitmap_sync, &rdev->flags);
1306         } else {
1307                 if (ev1 < mddev->events)
1308                         /* just a hot-add of a new device, leave raid_disk at -1 */
1309                         return 0;
1310         }
1311
1312         if (mddev->level != LEVEL_MULTIPATH) {
1313                 desc = sb->disks + rdev->desc_nr;
1314
1315                 if (desc->state & (1<<MD_DISK_FAULTY))
1316                         set_bit(Faulty, &rdev->flags);
1317                 else if (desc->state & (1<<MD_DISK_SYNC) /* &&
1318                             desc->raid_disk < mddev->raid_disks */) {
1319                         set_bit(In_sync, &rdev->flags);
1320                         rdev->raid_disk = desc->raid_disk;
1321                         rdev->saved_raid_disk = desc->raid_disk;
1322                 } else if (desc->state & (1<<MD_DISK_ACTIVE)) {
1323                         /* active but not in sync implies recovery up to
1324                          * reshape position.  We don't know exactly where
1325                          * that is, so set to zero for now */
1326                         if (mddev->minor_version >= 91) {
1327                                 rdev->recovery_offset = 0;
1328                                 rdev->raid_disk = desc->raid_disk;
1329                         }
1330                 }
1331                 if (desc->state & (1<<MD_DISK_WRITEMOSTLY))
1332                         set_bit(WriteMostly, &rdev->flags);
1333                 if (desc->state & (1<<MD_DISK_FAILFAST))
1334                         set_bit(FailFast, &rdev->flags);
1335         } else /* MULTIPATH are always insync */
1336                 set_bit(In_sync, &rdev->flags);
1337         return 0;
1338 }
1339
1340 /*
1341  * sync_super for 0.90.0
1342  */
1343 static void super_90_sync(struct mddev *mddev, struct md_rdev *rdev)
1344 {
1345         mdp_super_t *sb;
1346         struct md_rdev *rdev2;
1347         int next_spare = mddev->raid_disks;
1348
1349         /* make rdev->sb match mddev data..
1350          *
1351          * 1/ zero out disks
1352          * 2/ Add info for each disk, keeping track of highest desc_nr (next_spare);
1353          * 3/ any empty disks < next_spare become removed
1354          *
1355          * disks[0] gets initialised to REMOVED because
1356          * we cannot be sure from other fields if it has
1357          * been initialised or not.
1358          */
1359         int i;
1360         int active=0, working=0,failed=0,spare=0,nr_disks=0;
1361
1362         rdev->sb_size = MD_SB_BYTES;
1363
1364         sb = page_address(rdev->sb_page);
1365
1366         memset(sb, 0, sizeof(*sb));
1367
1368         sb->md_magic = MD_SB_MAGIC;
1369         sb->major_version = mddev->major_version;
1370         sb->patch_version = mddev->patch_version;
1371         sb->gvalid_words  = 0; /* ignored */
1372         memcpy(&sb->set_uuid0, mddev->uuid+0, 4);
1373         memcpy(&sb->set_uuid1, mddev->uuid+4, 4);
1374         memcpy(&sb->set_uuid2, mddev->uuid+8, 4);
1375         memcpy(&sb->set_uuid3, mddev->uuid+12,4);
1376
1377         sb->ctime = clamp_t(time64_t, mddev->ctime, 0, U32_MAX);
1378         sb->level = mddev->level;
1379         sb->size = mddev->dev_sectors / 2;
1380         sb->raid_disks = mddev->raid_disks;
1381         sb->md_minor = mddev->md_minor;
1382         sb->not_persistent = 0;
1383         sb->utime = clamp_t(time64_t, mddev->utime, 0, U32_MAX);
1384         sb->state = 0;
1385         sb->events_hi = (mddev->events>>32);
1386         sb->events_lo = (u32)mddev->events;
1387
1388         if (mddev->reshape_position == MaxSector)
1389                 sb->minor_version = 90;
1390         else {
1391                 sb->minor_version = 91;
1392                 sb->reshape_position = mddev->reshape_position;
1393                 sb->new_level = mddev->new_level;
1394                 sb->delta_disks = mddev->delta_disks;
1395                 sb->new_layout = mddev->new_layout;
1396                 sb->new_chunk = mddev->new_chunk_sectors << 9;
1397         }
1398         mddev->minor_version = sb->minor_version;
1399         if (mddev->in_sync)
1400         {
1401                 sb->recovery_cp = mddev->recovery_cp;
1402                 sb->cp_events_hi = (mddev->events>>32);
1403                 sb->cp_events_lo = (u32)mddev->events;
1404                 if (mddev->recovery_cp == MaxSector)
1405                         sb->state = (1<< MD_SB_CLEAN);
1406         } else
1407                 sb->recovery_cp = 0;
1408
1409         sb->layout = mddev->layout;
1410         sb->chunk_size = mddev->chunk_sectors << 9;
1411
1412         if (mddev->bitmap && mddev->bitmap_info.file == NULL)
1413                 sb->state |= (1<<MD_SB_BITMAP_PRESENT);
1414
1415         sb->disks[0].state = (1<<MD_DISK_REMOVED);
1416         rdev_for_each(rdev2, mddev) {
1417                 mdp_disk_t *d;
1418                 int desc_nr;
1419                 int is_active = test_bit(In_sync, &rdev2->flags);
1420
1421                 if (rdev2->raid_disk >= 0 &&
1422                     sb->minor_version >= 91)
1423                         /* we have nowhere to store the recovery_offset,
1424                          * but if it is not below the reshape_position,
1425                          * we can piggy-back on that.
1426                          */
1427                         is_active = 1;
1428                 if (rdev2->raid_disk < 0 ||
1429                     test_bit(Faulty, &rdev2->flags))
1430                         is_active = 0;
1431                 if (is_active)
1432                         desc_nr = rdev2->raid_disk;
1433                 else
1434                         desc_nr = next_spare++;
1435                 rdev2->desc_nr = desc_nr;
1436                 d = &sb->disks[rdev2->desc_nr];
1437                 nr_disks++;
1438                 d->number = rdev2->desc_nr;
1439                 d->major = MAJOR(rdev2->bdev->bd_dev);
1440                 d->minor = MINOR(rdev2->bdev->bd_dev);
1441                 if (is_active)
1442                         d->raid_disk = rdev2->raid_disk;
1443                 else
1444                         d->raid_disk = rdev2->desc_nr; /* compatibility */
1445                 if (test_bit(Faulty, &rdev2->flags))
1446                         d->state = (1<<MD_DISK_FAULTY);
1447                 else if (is_active) {
1448                         d->state = (1<<MD_DISK_ACTIVE);
1449                         if (test_bit(In_sync, &rdev2->flags))
1450                                 d->state |= (1<<MD_DISK_SYNC);
1451                         active++;
1452                         working++;
1453                 } else {
1454                         d->state = 0;
1455                         spare++;
1456                         working++;
1457                 }
1458                 if (test_bit(WriteMostly, &rdev2->flags))
1459                         d->state |= (1<<MD_DISK_WRITEMOSTLY);
1460                 if (test_bit(FailFast, &rdev2->flags))
1461                         d->state |= (1<<MD_DISK_FAILFAST);
1462         }
1463         /* now set the "removed" and "faulty" bits on any missing devices */
1464         for (i=0 ; i < mddev->raid_disks ; i++) {
1465                 mdp_disk_t *d = &sb->disks[i];
1466                 if (d->state == 0 && d->number == 0) {
1467                         d->number = i;
1468                         d->raid_disk = i;
1469                         d->state = (1<<MD_DISK_REMOVED);
1470                         d->state |= (1<<MD_DISK_FAULTY);
1471                         failed++;
1472                 }
1473         }
1474         sb->nr_disks = nr_disks;
1475         sb->active_disks = active;
1476         sb->working_disks = working;
1477         sb->failed_disks = failed;
1478         sb->spare_disks = spare;
1479
1480         sb->this_disk = sb->disks[rdev->desc_nr];
1481         sb->sb_csum = calc_sb_csum(sb);
1482 }
1483
1484 /*
1485  * rdev_size_change for 0.90.0
1486  */
1487 static unsigned long long
1488 super_90_rdev_size_change(struct md_rdev *rdev, sector_t num_sectors)
1489 {
1490         if (num_sectors && num_sectors < rdev->mddev->dev_sectors)
1491                 return 0; /* component must fit device */
1492         if (rdev->mddev->bitmap_info.offset)
1493                 return 0; /* can't move bitmap */
1494         rdev->sb_start = calc_dev_sboffset(rdev);
1495         if (!num_sectors || num_sectors > rdev->sb_start)
1496                 num_sectors = rdev->sb_start;
1497         /* Limit to 4TB as metadata cannot record more than that.
1498          * 4TB == 2^32 KB, or 2*2^32 sectors.
1499          */
1500         if ((u64)num_sectors >= (2ULL << 32) && rdev->mddev->level >= 1)
1501                 num_sectors = (sector_t)(2ULL << 32) - 2;
1502         do {
1503                 md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
1504                        rdev->sb_page);
1505         } while (md_super_wait(rdev->mddev) < 0);
1506         return num_sectors;
1507 }
1508
1509 static int
1510 super_90_allow_new_offset(struct md_rdev *rdev, unsigned long long new_offset)
1511 {
1512         /* non-zero offset changes not possible with v0.90 */
1513         return new_offset == 0;
1514 }
1515
1516 /*
1517  * version 1 superblock
1518  */
1519
1520 static __le32 calc_sb_1_csum(struct mdp_superblock_1 *sb)
1521 {
1522         __le32 disk_csum;
1523         u32 csum;
1524         unsigned long long newcsum;
1525         int size = 256 + le32_to_cpu(sb->max_dev)*2;
1526         __le32 *isuper = (__le32*)sb;
1527
1528         disk_csum = sb->sb_csum;
1529         sb->sb_csum = 0;
1530         newcsum = 0;
1531         for (; size >= 4; size -= 4)
1532                 newcsum += le32_to_cpu(*isuper++);
1533
1534         if (size == 2)
1535                 newcsum += le16_to_cpu(*(__le16*) isuper);
1536
1537         csum = (newcsum & 0xffffffff) + (newcsum >> 32);
1538         sb->sb_csum = disk_csum;
1539         return cpu_to_le32(csum);
1540 }
1541
1542 static int super_1_load(struct md_rdev *rdev, struct md_rdev *refdev, int minor_version)
1543 {
1544         struct mdp_superblock_1 *sb;
1545         int ret;
1546         sector_t sb_start;
1547         sector_t sectors;
1548         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1549         int bmask;
1550         __u64 role;
1551
1552         /*
1553          * Calculate the position of the superblock in 512byte sectors.
1554          * It is always aligned to a 4K boundary and
1555          * depeding on minor_version, it can be:
1556          * 0: At least 8K, but less than 12K, from end of device
1557          * 1: At start of device
1558          * 2: 4K from start of device.
1559          */
1560         switch(minor_version) {
1561         case 0:
1562                 sb_start = i_size_read(rdev->bdev->bd_inode) >> 9;
1563                 sb_start -= 8*2;
1564                 sb_start &= ~(sector_t)(4*2-1);
1565                 break;
1566         case 1:
1567                 sb_start = 0;
1568                 break;
1569         case 2:
1570                 sb_start = 8;
1571                 break;
1572         default:
1573                 return -EINVAL;
1574         }
1575         rdev->sb_start = sb_start;
1576
1577         /* superblock is rarely larger than 1K, but it can be larger,
1578          * and it is safe to read 4k, so we do that
1579          */
1580         ret = read_disk_sb(rdev, 4096);
1581         if (ret) return ret;
1582
1583         sb = page_address(rdev->sb_page);
1584
1585         if (sb->magic != cpu_to_le32(MD_SB_MAGIC) ||
1586             sb->major_version != cpu_to_le32(1) ||
1587             le32_to_cpu(sb->max_dev) > (4096-256)/2 ||
1588             le64_to_cpu(sb->super_offset) != rdev->sb_start ||
1589             (le32_to_cpu(sb->feature_map) & ~MD_FEATURE_ALL) != 0)
1590                 return -EINVAL;
1591
1592         if (calc_sb_1_csum(sb) != sb->sb_csum) {
1593                 pr_warn("md: invalid superblock checksum on %s\n",
1594                         bdevname(rdev->bdev,b));
1595                 return -EINVAL;
1596         }
1597         if (le64_to_cpu(sb->data_size) < 10) {
1598                 pr_warn("md: data_size too small on %s\n",
1599                         bdevname(rdev->bdev,b));
1600                 return -EINVAL;
1601         }
1602         if (sb->pad0 ||
1603             sb->pad3[0] ||
1604             memcmp(sb->pad3, sb->pad3+1, sizeof(sb->pad3) - sizeof(sb->pad3[1])))
1605                 /* Some padding is non-zero, might be a new feature */
1606                 return -EINVAL;
1607
1608         rdev->preferred_minor = 0xffff;
1609         rdev->data_offset = le64_to_cpu(sb->data_offset);
1610         rdev->new_data_offset = rdev->data_offset;
1611         if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE) &&
1612             (le32_to_cpu(sb->feature_map) & MD_FEATURE_NEW_OFFSET))
1613                 rdev->new_data_offset += (s32)le32_to_cpu(sb->new_offset);
1614         atomic_set(&rdev->corrected_errors, le32_to_cpu(sb->cnt_corrected_read));
1615
1616         rdev->sb_size = le32_to_cpu(sb->max_dev) * 2 + 256;
1617         bmask = queue_logical_block_size(rdev->bdev->bd_disk->queue)-1;
1618         if (rdev->sb_size & bmask)
1619                 rdev->sb_size = (rdev->sb_size | bmask) + 1;
1620
1621         if (minor_version
1622             && rdev->data_offset < sb_start + (rdev->sb_size/512))
1623                 return -EINVAL;
1624         if (minor_version
1625             && rdev->new_data_offset < sb_start + (rdev->sb_size/512))
1626                 return -EINVAL;
1627
1628         if (sb->level == cpu_to_le32(LEVEL_MULTIPATH))
1629                 rdev->desc_nr = -1;
1630         else
1631                 rdev->desc_nr = le32_to_cpu(sb->dev_number);
1632
1633         if (!rdev->bb_page) {
1634                 rdev->bb_page = alloc_page(GFP_KERNEL);
1635                 if (!rdev->bb_page)
1636                         return -ENOMEM;
1637         }
1638         if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BAD_BLOCKS) &&
1639             rdev->badblocks.count == 0) {
1640                 /* need to load the bad block list.
1641                  * Currently we limit it to one page.
1642                  */
1643                 s32 offset;
1644                 sector_t bb_sector;
1645                 __le64 *bbp;
1646                 int i;
1647                 int sectors = le16_to_cpu(sb->bblog_size);
1648                 if (sectors > (PAGE_SIZE / 512))
1649                         return -EINVAL;
1650                 offset = le32_to_cpu(sb->bblog_offset);
1651                 if (offset == 0)
1652                         return -EINVAL;
1653                 bb_sector = (long long)offset;
1654                 if (!sync_page_io(rdev, bb_sector, sectors << 9,
1655                                   rdev->bb_page, REQ_OP_READ, 0, true))
1656                         return -EIO;
1657                 bbp = (__le64 *)page_address(rdev->bb_page);
1658                 rdev->badblocks.shift = sb->bblog_shift;
1659                 for (i = 0 ; i < (sectors << (9-3)) ; i++, bbp++) {
1660                         u64 bb = le64_to_cpu(*bbp);
1661                         int count = bb & (0x3ff);
1662                         u64 sector = bb >> 10;
1663                         sector <<= sb->bblog_shift;
1664                         count <<= sb->bblog_shift;
1665                         if (bb + 1 == 0)
1666                                 break;
1667                         if (badblocks_set(&rdev->badblocks, sector, count, 1))
1668                                 return -EINVAL;
1669                 }
1670         } else if (sb->bblog_offset != 0)
1671                 rdev->badblocks.shift = 0;
1672
1673         if ((le32_to_cpu(sb->feature_map) &
1674             (MD_FEATURE_PPL | MD_FEATURE_MULTIPLE_PPLS))) {
1675                 rdev->ppl.offset = (__s16)le16_to_cpu(sb->ppl.offset);
1676                 rdev->ppl.size = le16_to_cpu(sb->ppl.size);
1677                 rdev->ppl.sector = rdev->sb_start + rdev->ppl.offset;
1678         }
1679
1680         if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RAID0_LAYOUT) &&
1681             sb->level != 0)
1682                 return -EINVAL;
1683
1684         role = le16_to_cpu(sb->dev_roles[rdev->desc_nr]);
1685
1686         if (!refdev) {
1687                 /*
1688                  * Insist of good event counter while assembling, except for
1689                  * spares (which don't need an event count)
1690                  */
1691                 if (rdev->desc_nr >= 0 &&
1692                     rdev->desc_nr < le32_to_cpu(sb->max_dev) &&
1693                         (role < MD_DISK_ROLE_MAX ||
1694                          role == MD_DISK_ROLE_JOURNAL))
1695                         ret = 1;
1696                 else
1697                         ret = 0;
1698         } else {
1699                 __u64 ev1, ev2;
1700                 struct mdp_superblock_1 *refsb = page_address(refdev->sb_page);
1701
1702                 if (memcmp(sb->set_uuid, refsb->set_uuid, 16) != 0 ||
1703                     sb->level != refsb->level ||
1704                     sb->layout != refsb->layout ||
1705                     sb->chunksize != refsb->chunksize) {
1706                         pr_warn("md: %s has strangely different superblock to %s\n",
1707                                 bdevname(rdev->bdev,b),
1708                                 bdevname(refdev->bdev,b2));
1709                         return -EINVAL;
1710                 }
1711                 ev1 = le64_to_cpu(sb->events);
1712                 ev2 = le64_to_cpu(refsb->events);
1713
1714                 /*
1715                  * Insist of good event counter while assembling, except for
1716                  * spares (which don't need an event count)
1717                  */
1718                 if (rdev->desc_nr >= 0 &&
1719                     rdev->desc_nr < le32_to_cpu(sb->max_dev) &&
1720                         (role < MD_DISK_ROLE_MAX ||
1721                          role == MD_DISK_ROLE_JOURNAL) && ev1 > ev2)
1722                         ret = 1;
1723                 else
1724                         ret = 0;
1725         }
1726         if (minor_version) {
1727                 sectors = (i_size_read(rdev->bdev->bd_inode) >> 9);
1728                 sectors -= rdev->data_offset;
1729         } else
1730                 sectors = rdev->sb_start;
1731         if (sectors < le64_to_cpu(sb->data_size))
1732                 return -EINVAL;
1733         rdev->sectors = le64_to_cpu(sb->data_size);
1734         return ret;
1735 }
1736
1737 static int super_1_validate(struct mddev *mddev, struct md_rdev *rdev)
1738 {
1739         struct mdp_superblock_1 *sb = page_address(rdev->sb_page);
1740         __u64 ev1 = le64_to_cpu(sb->events);
1741
1742         rdev->raid_disk = -1;
1743         clear_bit(Faulty, &rdev->flags);
1744         clear_bit(In_sync, &rdev->flags);
1745         clear_bit(Bitmap_sync, &rdev->flags);
1746         clear_bit(WriteMostly, &rdev->flags);
1747
1748         if (mddev->raid_disks == 0) {
1749                 mddev->major_version = 1;
1750                 mddev->patch_version = 0;
1751                 mddev->external = 0;
1752                 mddev->chunk_sectors = le32_to_cpu(sb->chunksize);
1753                 mddev->ctime = le64_to_cpu(sb->ctime);
1754                 mddev->utime = le64_to_cpu(sb->utime);
1755                 mddev->level = le32_to_cpu(sb->level);
1756                 mddev->clevel[0] = 0;
1757                 mddev->layout = le32_to_cpu(sb->layout);
1758                 mddev->raid_disks = le32_to_cpu(sb->raid_disks);
1759                 mddev->dev_sectors = le64_to_cpu(sb->size);
1760                 mddev->events = ev1;
1761                 mddev->bitmap_info.offset = 0;
1762                 mddev->bitmap_info.space = 0;
1763                 /* Default location for bitmap is 1K after superblock
1764                  * using 3K - total of 4K
1765                  */
1766                 mddev->bitmap_info.default_offset = 1024 >> 9;
1767                 mddev->bitmap_info.default_space = (4096-1024) >> 9;
1768                 mddev->reshape_backwards = 0;
1769
1770                 mddev->recovery_cp = le64_to_cpu(sb->resync_offset);
1771                 memcpy(mddev->uuid, sb->set_uuid, 16);
1772
1773                 mddev->max_disks =  (4096-256)/2;
1774
1775                 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BITMAP_OFFSET) &&
1776                     mddev->bitmap_info.file == NULL) {
1777                         mddev->bitmap_info.offset =
1778                                 (__s32)le32_to_cpu(sb->bitmap_offset);
1779                         /* Metadata doesn't record how much space is available.
1780                          * For 1.0, we assume we can use up to the superblock
1781                          * if before, else to 4K beyond superblock.
1782                          * For others, assume no change is possible.
1783                          */
1784                         if (mddev->minor_version > 0)
1785                                 mddev->bitmap_info.space = 0;
1786                         else if (mddev->bitmap_info.offset > 0)
1787                                 mddev->bitmap_info.space =
1788                                         8 - mddev->bitmap_info.offset;
1789                         else
1790                                 mddev->bitmap_info.space =
1791                                         -mddev->bitmap_info.offset;
1792                 }
1793
1794                 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE)) {
1795                         mddev->reshape_position = le64_to_cpu(sb->reshape_position);
1796                         mddev->delta_disks = le32_to_cpu(sb->delta_disks);
1797                         mddev->new_level = le32_to_cpu(sb->new_level);
1798                         mddev->new_layout = le32_to_cpu(sb->new_layout);
1799                         mddev->new_chunk_sectors = le32_to_cpu(sb->new_chunk);
1800                         if (mddev->delta_disks < 0 ||
1801                             (mddev->delta_disks == 0 &&
1802                              (le32_to_cpu(sb->feature_map)
1803                               & MD_FEATURE_RESHAPE_BACKWARDS)))
1804                                 mddev->reshape_backwards = 1;
1805                 } else {
1806                         mddev->reshape_position = MaxSector;
1807                         mddev->delta_disks = 0;
1808                         mddev->new_level = mddev->level;
1809                         mddev->new_layout = mddev->layout;
1810                         mddev->new_chunk_sectors = mddev->chunk_sectors;
1811                 }
1812
1813                 if (mddev->level == 0 &&
1814                     !(le32_to_cpu(sb->feature_map) & MD_FEATURE_RAID0_LAYOUT))
1815                         mddev->layout = -1;
1816
1817                 if (le32_to_cpu(sb->feature_map) & MD_FEATURE_JOURNAL)
1818                         set_bit(MD_HAS_JOURNAL, &mddev->flags);
1819
1820                 if (le32_to_cpu(sb->feature_map) &
1821                     (MD_FEATURE_PPL | MD_FEATURE_MULTIPLE_PPLS)) {
1822                         if (le32_to_cpu(sb->feature_map) &
1823                             (MD_FEATURE_BITMAP_OFFSET | MD_FEATURE_JOURNAL))
1824                                 return -EINVAL;
1825                         if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_PPL) &&
1826                             (le32_to_cpu(sb->feature_map) &
1827                                             MD_FEATURE_MULTIPLE_PPLS))
1828                                 return -EINVAL;
1829                         set_bit(MD_HAS_PPL, &mddev->flags);
1830                 }
1831         } else if (mddev->pers == NULL) {
1832                 /* Insist of good event counter while assembling, except for
1833                  * spares (which don't need an event count) */
1834                 ++ev1;
1835                 if (rdev->desc_nr >= 0 &&
1836                     rdev->desc_nr < le32_to_cpu(sb->max_dev) &&
1837                     (le16_to_cpu(sb->dev_roles[rdev->desc_nr]) < MD_DISK_ROLE_MAX ||
1838                      le16_to_cpu(sb->dev_roles[rdev->desc_nr]) == MD_DISK_ROLE_JOURNAL))
1839                         if (ev1 < mddev->events)
1840                                 return -EINVAL;
1841         } else if (mddev->bitmap) {
1842                 /* If adding to array with a bitmap, then we can accept an
1843                  * older device, but not too old.
1844                  */
1845                 if (ev1 < mddev->bitmap->events_cleared)
1846                         return 0;
1847                 if (ev1 < mddev->events)
1848                         set_bit(Bitmap_sync, &rdev->flags);
1849         } else {
1850                 if (ev1 < mddev->events)
1851                         /* just a hot-add of a new device, leave raid_disk at -1 */
1852                         return 0;
1853         }
1854         if (mddev->level != LEVEL_MULTIPATH) {
1855                 int role;
1856                 if (rdev->desc_nr < 0 ||
1857                     rdev->desc_nr >= le32_to_cpu(sb->max_dev)) {
1858                         role = MD_DISK_ROLE_SPARE;
1859                         rdev->desc_nr = -1;
1860                 } else
1861                         role = le16_to_cpu(sb->dev_roles[rdev->desc_nr]);
1862                 switch(role) {
1863                 case MD_DISK_ROLE_SPARE: /* spare */
1864                         break;
1865                 case MD_DISK_ROLE_FAULTY: /* faulty */
1866                         set_bit(Faulty, &rdev->flags);
1867                         break;
1868                 case MD_DISK_ROLE_JOURNAL: /* journal device */
1869                         if (!(le32_to_cpu(sb->feature_map) & MD_FEATURE_JOURNAL)) {
1870                                 /* journal device without journal feature */
1871                                 pr_warn("md: journal device provided without journal feature, ignoring the device\n");
1872                                 return -EINVAL;
1873                         }
1874                         set_bit(Journal, &rdev->flags);
1875                         rdev->journal_tail = le64_to_cpu(sb->journal_tail);
1876                         rdev->raid_disk = 0;
1877                         break;
1878                 default:
1879                         rdev->saved_raid_disk = role;
1880                         if ((le32_to_cpu(sb->feature_map) &
1881                              MD_FEATURE_RECOVERY_OFFSET)) {
1882                                 rdev->recovery_offset = le64_to_cpu(sb->recovery_offset);
1883                                 if (!(le32_to_cpu(sb->feature_map) &
1884                                       MD_FEATURE_RECOVERY_BITMAP))
1885                                         rdev->saved_raid_disk = -1;
1886                         } else {
1887                                 /*
1888                                  * If the array is FROZEN, then the device can't
1889                                  * be in_sync with rest of array.
1890                                  */
1891                                 if (!test_bit(MD_RECOVERY_FROZEN,
1892                                               &mddev->recovery))
1893                                         set_bit(In_sync, &rdev->flags);
1894                         }
1895                         rdev->raid_disk = role;
1896                         break;
1897                 }
1898                 if (sb->devflags & WriteMostly1)
1899                         set_bit(WriteMostly, &rdev->flags);
1900                 if (sb->devflags & FailFast1)
1901                         set_bit(FailFast, &rdev->flags);
1902                 if (le32_to_cpu(sb->feature_map) & MD_FEATURE_REPLACEMENT)
1903                         set_bit(Replacement, &rdev->flags);
1904         } else /* MULTIPATH are always insync */
1905                 set_bit(In_sync, &rdev->flags);
1906
1907         return 0;
1908 }
1909
1910 static void super_1_sync(struct mddev *mddev, struct md_rdev *rdev)
1911 {
1912         struct mdp_superblock_1 *sb;
1913         struct md_rdev *rdev2;
1914         int max_dev, i;
1915         /* make rdev->sb match mddev and rdev data. */
1916
1917         sb = page_address(rdev->sb_page);
1918
1919         sb->feature_map = 0;
1920         sb->pad0 = 0;
1921         sb->recovery_offset = cpu_to_le64(0);
1922         memset(sb->pad3, 0, sizeof(sb->pad3));
1923
1924         sb->utime = cpu_to_le64((__u64)mddev->utime);
1925         sb->events = cpu_to_le64(mddev->events);
1926         if (mddev->in_sync)
1927                 sb->resync_offset = cpu_to_le64(mddev->recovery_cp);
1928         else if (test_bit(MD_JOURNAL_CLEAN, &mddev->flags))
1929                 sb->resync_offset = cpu_to_le64(MaxSector);
1930         else
1931                 sb->resync_offset = cpu_to_le64(0);
1932
1933         sb->cnt_corrected_read = cpu_to_le32(atomic_read(&rdev->corrected_errors));
1934
1935         sb->raid_disks = cpu_to_le32(mddev->raid_disks);
1936         sb->size = cpu_to_le64(mddev->dev_sectors);
1937         sb->chunksize = cpu_to_le32(mddev->chunk_sectors);
1938         sb->level = cpu_to_le32(mddev->level);
1939         sb->layout = cpu_to_le32(mddev->layout);
1940         if (test_bit(FailFast, &rdev->flags))
1941                 sb->devflags |= FailFast1;
1942         else
1943                 sb->devflags &= ~FailFast1;
1944
1945         if (test_bit(WriteMostly, &rdev->flags))
1946                 sb->devflags |= WriteMostly1;
1947         else
1948                 sb->devflags &= ~WriteMostly1;
1949         sb->data_offset = cpu_to_le64(rdev->data_offset);
1950         sb->data_size = cpu_to_le64(rdev->sectors);
1951
1952         if (mddev->bitmap && mddev->bitmap_info.file == NULL) {
1953                 sb->bitmap_offset = cpu_to_le32((__u32)mddev->bitmap_info.offset);
1954                 sb->feature_map = cpu_to_le32(MD_FEATURE_BITMAP_OFFSET);
1955         }
1956
1957         if (rdev->raid_disk >= 0 && !test_bit(Journal, &rdev->flags) &&
1958             !test_bit(In_sync, &rdev->flags)) {
1959                 sb->feature_map |=
1960                         cpu_to_le32(MD_FEATURE_RECOVERY_OFFSET);
1961                 sb->recovery_offset =
1962                         cpu_to_le64(rdev->recovery_offset);
1963                 if (rdev->saved_raid_disk >= 0 && mddev->bitmap)
1964                         sb->feature_map |=
1965                                 cpu_to_le32(MD_FEATURE_RECOVERY_BITMAP);
1966         }
1967         /* Note: recovery_offset and journal_tail share space  */
1968         if (test_bit(Journal, &rdev->flags))
1969                 sb->journal_tail = cpu_to_le64(rdev->journal_tail);
1970         if (test_bit(Replacement, &rdev->flags))
1971                 sb->feature_map |=
1972                         cpu_to_le32(MD_FEATURE_REPLACEMENT);
1973
1974         if (mddev->reshape_position != MaxSector) {
1975                 sb->feature_map |= cpu_to_le32(MD_FEATURE_RESHAPE_ACTIVE);
1976                 sb->reshape_position = cpu_to_le64(mddev->reshape_position);
1977                 sb->new_layout = cpu_to_le32(mddev->new_layout);
1978                 sb->delta_disks = cpu_to_le32(mddev->delta_disks);
1979                 sb->new_level = cpu_to_le32(mddev->new_level);
1980                 sb->new_chunk = cpu_to_le32(mddev->new_chunk_sectors);
1981                 if (mddev->delta_disks == 0 &&
1982                     mddev->reshape_backwards)
1983                         sb->feature_map
1984                                 |= cpu_to_le32(MD_FEATURE_RESHAPE_BACKWARDS);
1985                 if (rdev->new_data_offset != rdev->data_offset) {
1986                         sb->feature_map
1987                                 |= cpu_to_le32(MD_FEATURE_NEW_OFFSET);
1988                         sb->new_offset = cpu_to_le32((__u32)(rdev->new_data_offset
1989                                                              - rdev->data_offset));
1990                 }
1991         }
1992
1993         if (mddev_is_clustered(mddev))
1994                 sb->feature_map |= cpu_to_le32(MD_FEATURE_CLUSTERED);
1995
1996         if (rdev->badblocks.count == 0)
1997                 /* Nothing to do for bad blocks*/ ;
1998         else if (sb->bblog_offset == 0)
1999                 /* Cannot record bad blocks on this device */
2000                 md_error(mddev, rdev);
2001         else {
2002                 struct badblocks *bb = &rdev->badblocks;
2003                 __le64 *bbp = (__le64 *)page_address(rdev->bb_page);
2004                 u64 *p = bb->page;
2005                 sb->feature_map |= cpu_to_le32(MD_FEATURE_BAD_BLOCKS);
2006                 if (bb->changed) {
2007                         unsigned seq;
2008
2009 retry:
2010                         seq = read_seqbegin(&bb->lock);
2011
2012                         memset(bbp, 0xff, PAGE_SIZE);
2013
2014                         for (i = 0 ; i < bb->count ; i++) {
2015                                 u64 internal_bb = p[i];
2016                                 u64 store_bb = ((BB_OFFSET(internal_bb) << 10)
2017                                                 | BB_LEN(internal_bb));
2018                                 bbp[i] = cpu_to_le64(store_bb);
2019                         }
2020                         bb->changed = 0;
2021                         if (read_seqretry(&bb->lock, seq))
2022                                 goto retry;
2023
2024                         bb->sector = (rdev->sb_start +
2025                                       (int)le32_to_cpu(sb->bblog_offset));
2026                         bb->size = le16_to_cpu(sb->bblog_size);
2027                 }
2028         }
2029
2030         max_dev = 0;
2031         rdev_for_each(rdev2, mddev)
2032                 if (rdev2->desc_nr+1 > max_dev)
2033                         max_dev = rdev2->desc_nr+1;
2034
2035         if (max_dev > le32_to_cpu(sb->max_dev)) {
2036                 int bmask;
2037                 sb->max_dev = cpu_to_le32(max_dev);
2038                 rdev->sb_size = max_dev * 2 + 256;
2039                 bmask = queue_logical_block_size(rdev->bdev->bd_disk->queue)-1;
2040                 if (rdev->sb_size & bmask)
2041                         rdev->sb_size = (rdev->sb_size | bmask) + 1;
2042         } else
2043                 max_dev = le32_to_cpu(sb->max_dev);
2044
2045         for (i=0; i<max_dev;i++)
2046                 sb->dev_roles[i] = cpu_to_le16(MD_DISK_ROLE_SPARE);
2047
2048         if (test_bit(MD_HAS_JOURNAL, &mddev->flags))
2049                 sb->feature_map |= cpu_to_le32(MD_FEATURE_JOURNAL);
2050
2051         if (test_bit(MD_HAS_PPL, &mddev->flags)) {
2052                 if (test_bit(MD_HAS_MULTIPLE_PPLS, &mddev->flags))
2053                         sb->feature_map |=
2054                             cpu_to_le32(MD_FEATURE_MULTIPLE_PPLS);
2055                 else
2056                         sb->feature_map |= cpu_to_le32(MD_FEATURE_PPL);
2057                 sb->ppl.offset = cpu_to_le16(rdev->ppl.offset);
2058                 sb->ppl.size = cpu_to_le16(rdev->ppl.size);
2059         }
2060
2061         rdev_for_each(rdev2, mddev) {
2062                 i = rdev2->desc_nr;
2063                 if (test_bit(Faulty, &rdev2->flags))
2064                         sb->dev_roles[i] = cpu_to_le16(MD_DISK_ROLE_FAULTY);
2065                 else if (test_bit(In_sync, &rdev2->flags))
2066                         sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
2067                 else if (test_bit(Journal, &rdev2->flags))
2068                         sb->dev_roles[i] = cpu_to_le16(MD_DISK_ROLE_JOURNAL);
2069                 else if (rdev2->raid_disk >= 0)
2070                         sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
2071                 else
2072                         sb->dev_roles[i] = cpu_to_le16(MD_DISK_ROLE_SPARE);
2073         }
2074
2075         sb->sb_csum = calc_sb_1_csum(sb);
2076 }
2077
2078 static unsigned long long
2079 super_1_rdev_size_change(struct md_rdev *rdev, sector_t num_sectors)
2080 {
2081         struct mdp_superblock_1 *sb;
2082         sector_t max_sectors;
2083         if (num_sectors && num_sectors < rdev->mddev->dev_sectors)
2084                 return 0; /* component must fit device */
2085         if (rdev->data_offset != rdev->new_data_offset)
2086                 return 0; /* too confusing */
2087         if (rdev->sb_start < rdev->data_offset) {
2088                 /* minor versions 1 and 2; superblock before data */
2089                 max_sectors = i_size_read(rdev->bdev->bd_inode) >> 9;
2090                 max_sectors -= rdev->data_offset;
2091                 if (!num_sectors || num_sectors > max_sectors)
2092                         num_sectors = max_sectors;
2093         } else if (rdev->mddev->bitmap_info.offset) {
2094                 /* minor version 0 with bitmap we can't move */
2095                 return 0;
2096         } else {
2097                 /* minor version 0; superblock after data */
2098                 sector_t sb_start;
2099                 sb_start = (i_size_read(rdev->bdev->bd_inode) >> 9) - 8*2;
2100                 sb_start &= ~(sector_t)(4*2 - 1);
2101                 max_sectors = rdev->sectors + sb_start - rdev->sb_start;
2102                 if (!num_sectors || num_sectors > max_sectors)
2103                         num_sectors = max_sectors;
2104                 rdev->sb_start = sb_start;
2105         }
2106         sb = page_address(rdev->sb_page);
2107         sb->data_size = cpu_to_le64(num_sectors);
2108         sb->super_offset = cpu_to_le64(rdev->sb_start);
2109         sb->sb_csum = calc_sb_1_csum(sb);
2110         do {
2111                 md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
2112                                rdev->sb_page);
2113         } while (md_super_wait(rdev->mddev) < 0);
2114         return num_sectors;
2115
2116 }
2117
2118 static int
2119 super_1_allow_new_offset(struct md_rdev *rdev,
2120                          unsigned long long new_offset)
2121 {
2122         /* All necessary checks on new >= old have been done */
2123         struct bitmap *bitmap;
2124         if (new_offset >= rdev->data_offset)
2125                 return 1;
2126
2127         /* with 1.0 metadata, there is no metadata to tread on
2128          * so we can always move back */
2129         if (rdev->mddev->minor_version == 0)
2130                 return 1;
2131
2132         /* otherwise we must be sure not to step on
2133          * any metadata, so stay:
2134          * 36K beyond start of superblock
2135          * beyond end of badblocks
2136          * beyond write-intent bitmap
2137          */
2138         if (rdev->sb_start + (32+4)*2 > new_offset)
2139                 return 0;
2140         bitmap = rdev->mddev->bitmap;
2141         if (bitmap && !rdev->mddev->bitmap_info.file &&
2142             rdev->sb_start + rdev->mddev->bitmap_info.offset +
2143             bitmap->storage.file_pages * (PAGE_SIZE>>9) > new_offset)
2144                 return 0;
2145         if (rdev->badblocks.sector + rdev->badblocks.size > new_offset)
2146                 return 0;
2147
2148         return 1;
2149 }
2150
2151 static struct super_type super_types[] = {
2152         [0] = {
2153                 .name   = "0.90.0",
2154                 .owner  = THIS_MODULE,
2155                 .load_super         = super_90_load,
2156                 .validate_super     = super_90_validate,
2157                 .sync_super         = super_90_sync,
2158                 .rdev_size_change   = super_90_rdev_size_change,
2159                 .allow_new_offset   = super_90_allow_new_offset,
2160         },
2161         [1] = {
2162                 .name   = "md-1",
2163                 .owner  = THIS_MODULE,
2164                 .load_super         = super_1_load,
2165                 .validate_super     = super_1_validate,
2166                 .sync_super         = super_1_sync,
2167                 .rdev_size_change   = super_1_rdev_size_change,
2168                 .allow_new_offset   = super_1_allow_new_offset,
2169         },
2170 };
2171
2172 static void sync_super(struct mddev *mddev, struct md_rdev *rdev)
2173 {
2174         if (mddev->sync_super) {
2175                 mddev->sync_super(mddev, rdev);
2176                 return;
2177         }
2178
2179         BUG_ON(mddev->major_version >= ARRAY_SIZE(super_types));
2180
2181         super_types[mddev->major_version].sync_super(mddev, rdev);
2182 }
2183
2184 static int match_mddev_units(struct mddev *mddev1, struct mddev *mddev2)
2185 {
2186         struct md_rdev *rdev, *rdev2;
2187
2188         rcu_read_lock();
2189         rdev_for_each_rcu(rdev, mddev1) {
2190                 if (test_bit(Faulty, &rdev->flags) ||
2191                     test_bit(Journal, &rdev->flags) ||
2192                     rdev->raid_disk == -1)
2193                         continue;
2194                 rdev_for_each_rcu(rdev2, mddev2) {
2195                         if (test_bit(Faulty, &rdev2->flags) ||
2196                             test_bit(Journal, &rdev2->flags) ||
2197                             rdev2->raid_disk == -1)
2198                                 continue;
2199                         if (rdev->bdev->bd_contains ==
2200                             rdev2->bdev->bd_contains) {
2201                                 rcu_read_unlock();
2202                                 return 1;
2203                         }
2204                 }
2205         }
2206         rcu_read_unlock();
2207         return 0;
2208 }
2209
2210 static LIST_HEAD(pending_raid_disks);
2211
2212 /*
2213  * Try to register data integrity profile for an mddev
2214  *
2215  * This is called when an array is started and after a disk has been kicked
2216  * from the array. It only succeeds if all working and active component devices
2217  * are integrity capable with matching profiles.
2218  */
2219 int md_integrity_register(struct mddev *mddev)
2220 {
2221         struct md_rdev *rdev, *reference = NULL;
2222
2223         if (list_empty(&mddev->disks))
2224                 return 0; /* nothing to do */
2225         if (!mddev->gendisk || blk_get_integrity(mddev->gendisk))
2226                 return 0; /* shouldn't register, or already is */
2227         rdev_for_each(rdev, mddev) {
2228                 /* skip spares and non-functional disks */
2229                 if (test_bit(Faulty, &rdev->flags))
2230                         continue;
2231                 if (rdev->raid_disk < 0)
2232                         continue;
2233                 if (!reference) {
2234                         /* Use the first rdev as the reference */
2235                         reference = rdev;
2236                         continue;
2237                 }
2238                 /* does this rdev's profile match the reference profile? */
2239                 if (blk_integrity_compare(reference->bdev->bd_disk,
2240                                 rdev->bdev->bd_disk) < 0)
2241                         return -EINVAL;
2242         }
2243         if (!reference || !bdev_get_integrity(reference->bdev))
2244                 return 0;
2245         /*
2246          * All component devices are integrity capable and have matching
2247          * profiles, register the common profile for the md device.
2248          */
2249         blk_integrity_register(mddev->gendisk,
2250                                bdev_get_integrity(reference->bdev));
2251
2252         pr_debug("md: data integrity enabled on %s\n", mdname(mddev));
2253         if (bioset_integrity_create(&mddev->bio_set, BIO_POOL_SIZE)) {
2254                 pr_err("md: failed to create integrity pool for %s\n",
2255                        mdname(mddev));
2256                 return -EINVAL;
2257         }
2258         return 0;
2259 }
2260 EXPORT_SYMBOL(md_integrity_register);
2261
2262 /*
2263  * Attempt to add an rdev, but only if it is consistent with the current
2264  * integrity profile
2265  */
2266 int md_integrity_add_rdev(struct md_rdev *rdev, struct mddev *mddev)
2267 {
2268         struct blk_integrity *bi_mddev;
2269         char name[BDEVNAME_SIZE];
2270
2271         if (!mddev->gendisk)
2272                 return 0;
2273
2274         bi_mddev = blk_get_integrity(mddev->gendisk);
2275
2276         if (!bi_mddev) /* nothing to do */
2277                 return 0;
2278
2279         if (blk_integrity_compare(mddev->gendisk, rdev->bdev->bd_disk) != 0) {
2280                 pr_err("%s: incompatible integrity profile for %s\n",
2281                        mdname(mddev), bdevname(rdev->bdev, name));
2282                 return -ENXIO;
2283         }
2284
2285         return 0;
2286 }
2287 EXPORT_SYMBOL(md_integrity_add_rdev);
2288
2289 static int bind_rdev_to_array(struct md_rdev *rdev, struct mddev *mddev)
2290 {
2291         char b[BDEVNAME_SIZE];
2292         struct kobject *ko;
2293         int err;
2294
2295         /* prevent duplicates */
2296         if (find_rdev(mddev, rdev->bdev->bd_dev))
2297                 return -EEXIST;
2298
2299         if ((bdev_read_only(rdev->bdev) || bdev_read_only(rdev->meta_bdev)) &&
2300             mddev->pers)
2301                 return -EROFS;
2302
2303         /* make sure rdev->sectors exceeds mddev->dev_sectors */
2304         if (!test_bit(Journal, &rdev->flags) &&
2305             rdev->sectors &&
2306             (mddev->dev_sectors == 0 || rdev->sectors < mddev->dev_sectors)) {
2307                 if (mddev->pers) {
2308                         /* Cannot change size, so fail
2309                          * If mddev->level <= 0, then we don't care
2310                          * about aligning sizes (e.g. linear)
2311                          */
2312                         if (mddev->level > 0)
2313                                 return -ENOSPC;
2314                 } else
2315                         mddev->dev_sectors = rdev->sectors;
2316         }
2317
2318         /* Verify rdev->desc_nr is unique.
2319          * If it is -1, assign a free number, else
2320          * check number is not in use
2321          */
2322         rcu_read_lock();
2323         if (rdev->desc_nr < 0) {
2324                 int choice = 0;
2325                 if (mddev->pers)
2326                         choice = mddev->raid_disks;
2327                 while (md_find_rdev_nr_rcu(mddev, choice))
2328                         choice++;
2329                 rdev->desc_nr = choice;
2330         } else {
2331                 if (md_find_rdev_nr_rcu(mddev, rdev->desc_nr)) {
2332                         rcu_read_unlock();
2333                         return -EBUSY;
2334                 }
2335         }
2336         rcu_read_unlock();
2337         if (!test_bit(Journal, &rdev->flags) &&
2338             mddev->max_disks && rdev->desc_nr >= mddev->max_disks) {
2339                 pr_warn("md: %s: array is limited to %d devices\n",
2340                         mdname(mddev), mddev->max_disks);
2341                 return -EBUSY;
2342         }
2343         bdevname(rdev->bdev,b);
2344         strreplace(b, '/', '!');
2345
2346         rdev->mddev = mddev;
2347         pr_debug("md: bind<%s>\n", b);
2348
2349         if (mddev->raid_disks)
2350                 mddev_create_wb_pool(mddev, rdev, false);
2351
2352         if ((err = kobject_add(&rdev->kobj, &mddev->kobj, "dev-%s", b)))
2353                 goto fail;
2354
2355         ko = &part_to_dev(rdev->bdev->bd_part)->kobj;
2356         if (sysfs_create_link(&rdev->kobj, ko, "block"))
2357                 /* failure here is OK */;
2358         rdev->sysfs_state = sysfs_get_dirent_safe(rdev->kobj.sd, "state");
2359
2360         list_add_rcu(&rdev->same_set, &mddev->disks);
2361         bd_link_disk_holder(rdev->bdev, mddev->gendisk);
2362
2363         /* May as well allow recovery to be retried once */
2364         mddev->recovery_disabled++;
2365
2366         return 0;
2367
2368  fail:
2369         pr_warn("md: failed to register dev-%s for %s\n",
2370                 b, mdname(mddev));
2371         return err;
2372 }
2373
2374 static void md_delayed_delete(struct work_struct *ws)
2375 {
2376         struct md_rdev *rdev = container_of(ws, struct md_rdev, del_work);
2377         kobject_del(&rdev->kobj);
2378         kobject_put(&rdev->kobj);
2379 }
2380
2381 static void unbind_rdev_from_array(struct md_rdev *rdev)
2382 {
2383         char b[BDEVNAME_SIZE];
2384
2385         bd_unlink_disk_holder(rdev->bdev, rdev->mddev->gendisk);
2386         list_del_rcu(&rdev->same_set);
2387         pr_debug("md: unbind<%s>\n", bdevname(rdev->bdev,b));
2388         mddev_destroy_wb_pool(rdev->mddev, rdev);
2389         rdev->mddev = NULL;
2390         sysfs_remove_link(&rdev->kobj, "block");
2391         sysfs_put(rdev->sysfs_state);
2392         rdev->sysfs_state = NULL;
2393         rdev->badblocks.count = 0;
2394         /* We need to delay this, otherwise we can deadlock when
2395          * writing to 'remove' to "dev/state".  We also need
2396          * to delay it due to rcu usage.
2397          */
2398         synchronize_rcu();
2399         INIT_WORK(&rdev->del_work, md_delayed_delete);
2400         kobject_get(&rdev->kobj);
2401         queue_work(md_misc_wq, &rdev->del_work);
2402 }
2403
2404 /*
2405  * prevent the device from being mounted, repartitioned or
2406  * otherwise reused by a RAID array (or any other kernel
2407  * subsystem), by bd_claiming the device.
2408  */
2409 static int lock_rdev(struct md_rdev *rdev, dev_t dev, int shared)
2410 {
2411         int err = 0;
2412         struct block_device *bdev;
2413         char b[BDEVNAME_SIZE];
2414
2415         bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL,
2416                                  shared ? (struct md_rdev *)lock_rdev : rdev);
2417         if (IS_ERR(bdev)) {
2418                 pr_warn("md: could not open %s.\n", __bdevname(dev, b));
2419                 return PTR_ERR(bdev);
2420         }
2421         rdev->bdev = bdev;
2422         return err;
2423 }
2424
2425 static void unlock_rdev(struct md_rdev *rdev)
2426 {
2427         struct block_device *bdev = rdev->bdev;
2428         rdev->bdev = NULL;
2429         blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2430 }
2431
2432 void md_autodetect_dev(dev_t dev);
2433
2434 static void export_rdev(struct md_rdev *rdev)
2435 {
2436         char b[BDEVNAME_SIZE];
2437
2438         pr_debug("md: export_rdev(%s)\n", bdevname(rdev->bdev,b));
2439         md_rdev_clear(rdev);
2440 #ifndef MODULE
2441         if (test_bit(AutoDetected, &rdev->flags))
2442                 md_autodetect_dev(rdev->bdev->bd_dev);
2443 #endif
2444         unlock_rdev(rdev);
2445         kobject_put(&rdev->kobj);
2446 }
2447
2448 void md_kick_rdev_from_array(struct md_rdev *rdev)
2449 {
2450         unbind_rdev_from_array(rdev);
2451         export_rdev(rdev);
2452 }
2453 EXPORT_SYMBOL_GPL(md_kick_rdev_from_array);
2454
2455 static void export_array(struct mddev *mddev)
2456 {
2457         struct md_rdev *rdev;
2458
2459         while (!list_empty(&mddev->disks)) {
2460                 rdev = list_first_entry(&mddev->disks, struct md_rdev,
2461                                         same_set);
2462                 md_kick_rdev_from_array(rdev);
2463         }
2464         mddev->raid_disks = 0;
2465         mddev->major_version = 0;
2466 }
2467
2468 static bool set_in_sync(struct mddev *mddev)
2469 {
2470         lockdep_assert_held(&mddev->lock);
2471         if (!mddev->in_sync) {
2472                 mddev->sync_checkers++;
2473                 spin_unlock(&mddev->lock);
2474                 percpu_ref_switch_to_atomic_sync(&mddev->writes_pending);
2475                 spin_lock(&mddev->lock);
2476                 if (!mddev->in_sync &&
2477                     percpu_ref_is_zero(&mddev->writes_pending)) {
2478                         mddev->in_sync = 1;
2479                         /*
2480                          * Ensure ->in_sync is visible before we clear
2481                          * ->sync_checkers.
2482                          */
2483                         smp_mb();
2484                         set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
2485                         sysfs_notify_dirent_safe(mddev->sysfs_state);
2486                 }
2487                 if (--mddev->sync_checkers == 0)
2488                         percpu_ref_switch_to_percpu(&mddev->writes_pending);
2489         }
2490         if (mddev->safemode == 1)
2491                 mddev->safemode = 0;
2492         return mddev->in_sync;
2493 }
2494
2495 static void sync_sbs(struct mddev *mddev, int nospares)
2496 {
2497         /* Update each superblock (in-memory image), but
2498          * if we are allowed to, skip spares which already
2499          * have the right event counter, or have one earlier
2500          * (which would mean they aren't being marked as dirty
2501          * with the rest of the array)
2502          */
2503         struct md_rdev *rdev;
2504         rdev_for_each(rdev, mddev) {
2505                 if (rdev->sb_events == mddev->events ||
2506                     (nospares &&
2507                      rdev->raid_disk < 0 &&
2508                      rdev->sb_events+1 == mddev->events)) {
2509                         /* Don't update this superblock */
2510                         rdev->sb_loaded = 2;
2511                 } else {
2512                         sync_super(mddev, rdev);
2513                         rdev->sb_loaded = 1;
2514                 }
2515         }
2516 }
2517
2518 static bool does_sb_need_changing(struct mddev *mddev)
2519 {
2520         struct md_rdev *rdev;
2521         struct mdp_superblock_1 *sb;
2522         int role;
2523
2524         /* Find a good rdev */
2525         rdev_for_each(rdev, mddev)
2526                 if ((rdev->raid_disk >= 0) && !test_bit(Faulty, &rdev->flags))
2527                         break;
2528
2529         /* No good device found. */
2530         if (!rdev)
2531                 return false;
2532
2533         sb = page_address(rdev->sb_page);
2534         /* Check if a device has become faulty or a spare become active */
2535         rdev_for_each(rdev, mddev) {
2536                 role = le16_to_cpu(sb->dev_roles[rdev->desc_nr]);
2537                 /* Device activated? */
2538                 if (role == 0xffff && rdev->raid_disk >=0 &&
2539                     !test_bit(Faulty, &rdev->flags))
2540                         return true;
2541                 /* Device turned faulty? */
2542                 if (test_bit(Faulty, &rdev->flags) && (role < 0xfffd))
2543                         return true;
2544         }
2545
2546         /* Check if any mddev parameters have changed */
2547         if ((mddev->dev_sectors != le64_to_cpu(sb->size)) ||
2548             (mddev->reshape_position != le64_to_cpu(sb->reshape_position)) ||
2549             (mddev->layout != le32_to_cpu(sb->layout)) ||
2550             (mddev->raid_disks != le32_to_cpu(sb->raid_disks)) ||
2551             (mddev->chunk_sectors != le32_to_cpu(sb->chunksize)))
2552                 return true;
2553
2554         return false;
2555 }
2556
2557 void md_update_sb(struct mddev *mddev, int force_change)
2558 {
2559         struct md_rdev *rdev;
2560         int sync_req;
2561         int nospares = 0;
2562         int any_badblocks_changed = 0;
2563         int ret = -1;
2564
2565         if (mddev->ro) {
2566                 if (force_change)
2567                         set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
2568                 return;
2569         }
2570
2571 repeat:
2572         if (mddev_is_clustered(mddev)) {
2573                 if (test_and_clear_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags))
2574                         force_change = 1;
2575                 if (test_and_clear_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags))
2576                         nospares = 1;
2577                 ret = md_cluster_ops->metadata_update_start(mddev);
2578                 /* Has someone else has updated the sb */
2579                 if (!does_sb_need_changing(mddev)) {
2580                         if (ret == 0)
2581                                 md_cluster_ops->metadata_update_cancel(mddev);
2582                         bit_clear_unless(&mddev->sb_flags, BIT(MD_SB_CHANGE_PENDING),
2583                                                          BIT(MD_SB_CHANGE_DEVS) |
2584                                                          BIT(MD_SB_CHANGE_CLEAN));
2585                         return;
2586                 }
2587         }
2588
2589         /*
2590          * First make sure individual recovery_offsets are correct
2591          * curr_resync_completed can only be used during recovery.
2592          * During reshape/resync it might use array-addresses rather
2593          * that device addresses.
2594          */
2595         rdev_for_each(rdev, mddev) {
2596                 if (rdev->raid_disk >= 0 &&
2597                     mddev->delta_disks >= 0 &&
2598                     test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) &&
2599                     test_bit(MD_RECOVERY_RECOVER, &mddev->recovery) &&
2600                     !test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
2601                     !test_bit(Journal, &rdev->flags) &&
2602                     !test_bit(In_sync, &rdev->flags) &&
2603                     mddev->curr_resync_completed > rdev->recovery_offset)
2604                                 rdev->recovery_offset = mddev->curr_resync_completed;
2605
2606         }
2607         if (!mddev->persistent) {
2608                 clear_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
2609                 clear_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
2610                 if (!mddev->external) {
2611                         clear_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
2612                         rdev_for_each(rdev, mddev) {
2613                                 if (rdev->badblocks.changed) {
2614                                         rdev->badblocks.changed = 0;
2615                                         ack_all_badblocks(&rdev->badblocks);
2616                                         md_error(mddev, rdev);
2617                                 }
2618                                 clear_bit(Blocked, &rdev->flags);
2619                                 clear_bit(BlockedBadBlocks, &rdev->flags);
2620                                 wake_up(&rdev->blocked_wait);
2621                         }
2622                 }
2623                 wake_up(&mddev->sb_wait);
2624                 return;
2625         }
2626
2627         spin_lock(&mddev->lock);
2628
2629         mddev->utime = ktime_get_real_seconds();
2630
2631         if (test_and_clear_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags))
2632                 force_change = 1;
2633         if (test_and_clear_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags))
2634                 /* just a clean<-> dirty transition, possibly leave spares alone,
2635                  * though if events isn't the right even/odd, we will have to do
2636                  * spares after all
2637                  */
2638                 nospares = 1;
2639         if (force_change)
2640                 nospares = 0;
2641         if (mddev->degraded)
2642                 /* If the array is degraded, then skipping spares is both
2643                  * dangerous and fairly pointless.
2644                  * Dangerous because a device that was removed from the array
2645                  * might have a event_count that still looks up-to-date,
2646                  * so it can be re-added without a resync.
2647                  * Pointless because if there are any spares to skip,
2648                  * then a recovery will happen and soon that array won't
2649                  * be degraded any more and the spare can go back to sleep then.
2650                  */
2651                 nospares = 0;
2652
2653         sync_req = mddev->in_sync;
2654
2655         /* If this is just a dirty<->clean transition, and the array is clean
2656          * and 'events' is odd, we can roll back to the previous clean state */
2657         if (nospares
2658             && (mddev->in_sync && mddev->recovery_cp == MaxSector)
2659             && mddev->can_decrease_events
2660             && mddev->events != 1) {
2661                 mddev->events--;
2662                 mddev->can_decrease_events = 0;
2663         } else {
2664                 /* otherwise we have to go forward and ... */
2665                 mddev->events ++;
2666                 mddev->can_decrease_events = nospares;
2667         }
2668
2669         /*
2670          * This 64-bit counter should never wrap.
2671          * Either we are in around ~1 trillion A.C., assuming
2672          * 1 reboot per second, or we have a bug...
2673          */
2674         WARN_ON(mddev->events == 0);
2675
2676         rdev_for_each(rdev, mddev) {
2677                 if (rdev->badblocks.changed)
2678                         any_badblocks_changed++;
2679                 if (test_bit(Faulty, &rdev->flags))
2680                         set_bit(FaultRecorded, &rdev->flags);
2681         }
2682
2683         sync_sbs(mddev, nospares);
2684         spin_unlock(&mddev->lock);
2685
2686         pr_debug("md: updating %s RAID superblock on device (in sync %d)\n",
2687                  mdname(mddev), mddev->in_sync);
2688
2689         if (mddev->queue)
2690                 blk_add_trace_msg(mddev->queue, "md md_update_sb");
2691 rewrite:
2692         md_bitmap_update_sb(mddev->bitmap);
2693         rdev_for_each(rdev, mddev) {
2694                 char b[BDEVNAME_SIZE];
2695
2696                 if (rdev->sb_loaded != 1)
2697                         continue; /* no noise on spare devices */
2698
2699                 if (!test_bit(Faulty, &rdev->flags)) {
2700                         md_super_write(mddev,rdev,
2701                                        rdev->sb_start, rdev->sb_size,
2702                                        rdev->sb_page);
2703                         pr_debug("md: (write) %s's sb offset: %llu\n",
2704                                  bdevname(rdev->bdev, b),
2705                                  (unsigned long long)rdev->sb_start);
2706                         rdev->sb_events = mddev->events;
2707                         if (rdev->badblocks.size) {
2708                                 md_super_write(mddev, rdev,
2709                                                rdev->badblocks.sector,
2710                                                rdev->badblocks.size << 9,
2711                                                rdev->bb_page);
2712                                 rdev->badblocks.size = 0;
2713                         }
2714
2715                 } else
2716                         pr_debug("md: %s (skipping faulty)\n",
2717                                  bdevname(rdev->bdev, b));
2718
2719                 if (mddev->level == LEVEL_MULTIPATH)
2720                         /* only need to write one superblock... */
2721                         break;
2722         }
2723         if (md_super_wait(mddev) < 0)
2724                 goto rewrite;
2725         /* if there was a failure, MD_SB_CHANGE_DEVS was set, and we re-write super */
2726
2727         if (mddev_is_clustered(mddev) && ret == 0)
2728                 md_cluster_ops->metadata_update_finish(mddev);
2729
2730         if (mddev->in_sync != sync_req ||
2731             !bit_clear_unless(&mddev->sb_flags, BIT(MD_SB_CHANGE_PENDING),
2732                                BIT(MD_SB_CHANGE_DEVS) | BIT(MD_SB_CHANGE_CLEAN)))
2733                 /* have to write it out again */
2734                 goto repeat;
2735         wake_up(&mddev->sb_wait);
2736         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
2737                 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
2738
2739         rdev_for_each(rdev, mddev) {
2740                 if (test_and_clear_bit(FaultRecorded, &rdev->flags))
2741                         clear_bit(Blocked, &rdev->flags);
2742
2743                 if (any_badblocks_changed)
2744                         ack_all_badblocks(&rdev->badblocks);
2745                 clear_bit(BlockedBadBlocks, &rdev->flags);
2746                 wake_up(&rdev->blocked_wait);
2747         }
2748 }
2749 EXPORT_SYMBOL(md_update_sb);
2750
2751 static int add_bound_rdev(struct md_rdev *rdev)
2752 {
2753         struct mddev *mddev = rdev->mddev;
2754         int err = 0;
2755         bool add_journal = test_bit(Journal, &rdev->flags);
2756
2757         if (!mddev->pers->hot_remove_disk || add_journal) {
2758                 /* If there is hot_add_disk but no hot_remove_disk
2759                  * then added disks for geometry changes,
2760                  * and should be added immediately.
2761                  */
2762                 super_types[mddev->major_version].
2763                         validate_super(mddev, rdev);
2764                 if (add_journal)
2765                         mddev_suspend(mddev);
2766                 err = mddev->pers->hot_add_disk(mddev, rdev);
2767                 if (add_journal)
2768                         mddev_resume(mddev);
2769                 if (err) {
2770                         md_kick_rdev_from_array(rdev);
2771                         return err;
2772                 }
2773         }
2774         sysfs_notify_dirent_safe(rdev->sysfs_state);
2775
2776         set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
2777         if (mddev->degraded)
2778                 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
2779         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2780         md_new_event(mddev);
2781         md_wakeup_thread(mddev->thread);
2782         return 0;
2783 }
2784
2785 /* words written to sysfs files may, or may not, be \n terminated.
2786  * We want to accept with case. For this we use cmd_match.
2787  */
2788 static int cmd_match(const char *cmd, const char *str)
2789 {
2790         /* See if cmd, written into a sysfs file, matches
2791          * str.  They must either be the same, or cmd can
2792          * have a trailing newline
2793          */
2794         while (*cmd && *str && *cmd == *str) {
2795                 cmd++;
2796                 str++;
2797         }
2798         if (*cmd == '\n')
2799                 cmd++;
2800         if (*str || *cmd)
2801                 return 0;
2802         return 1;
2803 }
2804
2805 struct rdev_sysfs_entry {
2806         struct attribute attr;
2807         ssize_t (*show)(struct md_rdev *, char *);
2808         ssize_t (*store)(struct md_rdev *, const char *, size_t);
2809 };
2810
2811 static ssize_t
2812 state_show(struct md_rdev *rdev, char *page)
2813 {
2814         char *sep = ",";
2815         size_t len = 0;
2816         unsigned long flags = READ_ONCE(rdev->flags);
2817
2818         if (test_bit(Faulty, &flags) ||
2819             (!test_bit(ExternalBbl, &flags) &&
2820             rdev->badblocks.unacked_exist))
2821                 len += sprintf(page+len, "faulty%s", sep);
2822         if (test_bit(In_sync, &flags))
2823                 len += sprintf(page+len, "in_sync%s", sep);
2824         if (test_bit(Journal, &flags))
2825                 len += sprintf(page+len, "journal%s", sep);
2826         if (test_bit(WriteMostly, &flags))
2827                 len += sprintf(page+len, "write_mostly%s", sep);
2828         if (test_bit(Blocked, &flags) ||
2829             (rdev->badblocks.unacked_exist
2830              && !test_bit(Faulty, &flags)))
2831                 len += sprintf(page+len, "blocked%s", sep);
2832         if (!test_bit(Faulty, &flags) &&
2833             !test_bit(Journal, &flags) &&
2834             !test_bit(In_sync, &flags))
2835                 len += sprintf(page+len, "spare%s", sep);
2836         if (test_bit(WriteErrorSeen, &flags))
2837                 len += sprintf(page+len, "write_error%s", sep);
2838         if (test_bit(WantReplacement, &flags))
2839                 len += sprintf(page+len, "want_replacement%s", sep);
2840         if (test_bit(Replacement, &flags))
2841                 len += sprintf(page+len, "replacement%s", sep);
2842         if (test_bit(ExternalBbl, &flags))
2843                 len += sprintf(page+len, "external_bbl%s", sep);
2844         if (test_bit(FailFast, &flags))
2845                 len += sprintf(page+len, "failfast%s", sep);
2846
2847         if (len)
2848                 len -= strlen(sep);
2849
2850         return len+sprintf(page+len, "\n");
2851 }
2852
2853 static ssize_t
2854 state_store(struct md_rdev *rdev, const char *buf, size_t len)
2855 {
2856         /* can write
2857          *  faulty  - simulates an error
2858          *  remove  - disconnects the device
2859          *  writemostly - sets write_mostly
2860          *  -writemostly - clears write_mostly
2861          *  blocked - sets the Blocked flags
2862          *  -blocked - clears the Blocked and possibly simulates an error
2863          *  insync - sets Insync providing device isn't active
2864          *  -insync - clear Insync for a device with a slot assigned,
2865          *            so that it gets rebuilt based on bitmap
2866          *  write_error - sets WriteErrorSeen
2867          *  -write_error - clears WriteErrorSeen
2868          *  {,-}failfast - set/clear FailFast
2869          */
2870         int err = -EINVAL;
2871         if (cmd_match(buf, "faulty") && rdev->mddev->pers) {
2872                 md_error(rdev->mddev, rdev);
2873                 if (test_bit(Faulty, &rdev->flags))
2874                         err = 0;
2875                 else
2876                         err = -EBUSY;
2877         } else if (cmd_match(buf, "remove")) {
2878                 if (rdev->mddev->pers) {
2879                         clear_bit(Blocked, &rdev->flags);
2880                         remove_and_add_spares(rdev->mddev, rdev);
2881                 }
2882                 if (rdev->raid_disk >= 0)
2883                         err = -EBUSY;
2884                 else {
2885                         struct mddev *mddev = rdev->mddev;
2886                         err = 0;
2887                         if (mddev_is_clustered(mddev))
2888                                 err = md_cluster_ops->remove_disk(mddev, rdev);
2889
2890                         if (err == 0) {
2891                                 md_kick_rdev_from_array(rdev);
2892                                 if (mddev->pers) {
2893                                         set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
2894                                         md_wakeup_thread(mddev->thread);
2895                                 }
2896                                 md_new_event(mddev);
2897                         }
2898                 }
2899         } else if (cmd_match(buf, "writemostly")) {
2900                 set_bit(WriteMostly, &rdev->flags);
2901                 mddev_create_wb_pool(rdev->mddev, rdev, false);
2902                 err = 0;
2903         } else if (cmd_match(buf, "-writemostly")) {
2904                 mddev_destroy_wb_pool(rdev->mddev, rdev);
2905                 clear_bit(WriteMostly, &rdev->flags);
2906                 err = 0;
2907         } else if (cmd_match(buf, "blocked")) {
2908                 set_bit(Blocked, &rdev->flags);
2909                 err = 0;
2910         } else if (cmd_match(buf, "-blocked")) {
2911                 if (!test_bit(Faulty, &rdev->flags) &&
2912                     !test_bit(ExternalBbl, &rdev->flags) &&
2913                     rdev->badblocks.unacked_exist) {
2914                         /* metadata handler doesn't understand badblocks,
2915                          * so we need to fail the device
2916                          */
2917                         md_error(rdev->mddev, rdev);
2918                 }
2919                 clear_bit(Blocked, &rdev->flags);
2920                 clear_bit(BlockedBadBlocks, &rdev->flags);
2921                 wake_up(&rdev->blocked_wait);
2922                 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2923                 md_wakeup_thread(rdev->mddev->thread);
2924
2925                 err = 0;
2926         } else if (cmd_match(buf, "insync") && rdev->raid_disk == -1) {
2927                 set_bit(In_sync, &rdev->flags);
2928                 err = 0;
2929         } else if (cmd_match(buf, "failfast")) {
2930                 set_bit(FailFast, &rdev->flags);
2931                 err = 0;
2932         } else if (cmd_match(buf, "-failfast")) {
2933                 clear_bit(FailFast, &rdev->flags);
2934                 err = 0;
2935         } else if (cmd_match(buf, "-insync") && rdev->raid_disk >= 0 &&
2936                    !test_bit(Journal, &rdev->flags)) {
2937                 if (rdev->mddev->pers == NULL) {
2938                         clear_bit(In_sync, &rdev->flags);
2939                         rdev->saved_raid_disk = rdev->raid_disk;
2940                         rdev->raid_disk = -1;
2941                         err = 0;
2942                 }
2943         } else if (cmd_match(buf, "write_error")) {
2944                 set_bit(WriteErrorSeen, &rdev->flags);
2945                 err = 0;
2946         } else if (cmd_match(buf, "-write_error")) {
2947                 clear_bit(WriteErrorSeen, &rdev->flags);
2948                 err = 0;
2949         } else if (cmd_match(buf, "want_replacement")) {
2950                 /* Any non-spare device that is not a replacement can
2951                  * become want_replacement at any time, but we then need to
2952                  * check if recovery is needed.
2953                  */
2954                 if (rdev->raid_disk >= 0 &&
2955                     !test_bit(Journal, &rdev->flags) &&
2956                     !test_bit(Replacement, &rdev->flags))
2957                         set_bit(WantReplacement, &rdev->flags);
2958                 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2959                 md_wakeup_thread(rdev->mddev->thread);
2960                 err = 0;
2961         } else if (cmd_match(buf, "-want_replacement")) {
2962                 /* Clearing 'want_replacement' is always allowed.
2963                  * Once replacements starts it is too late though.
2964                  */
2965                 err = 0;
2966                 clear_bit(WantReplacement, &rdev->flags);
2967         } else if (cmd_match(buf, "replacement")) {
2968                 /* Can only set a device as a replacement when array has not
2969                  * yet been started.  Once running, replacement is automatic
2970                  * from spares, or by assigning 'slot'.
2971                  */
2972                 if (rdev->mddev->pers)
2973                         err = -EBUSY;
2974                 else {
2975                         set_bit(Replacement, &rdev->flags);
2976                         err = 0;
2977                 }
2978         } else if (cmd_match(buf, "-replacement")) {
2979                 /* Similarly, can only clear Replacement before start */
2980                 if (rdev->mddev->pers)
2981                         err = -EBUSY;
2982                 else {
2983                         clear_bit(Replacement, &rdev->flags);
2984                         err = 0;
2985                 }
2986         } else if (cmd_match(buf, "re-add")) {
2987                 if (!rdev->mddev->pers)
2988                         err = -EINVAL;
2989                 else if (test_bit(Faulty, &rdev->flags) && (rdev->raid_disk == -1) &&
2990                                 rdev->saved_raid_disk >= 0) {
2991                         /* clear_bit is performed _after_ all the devices
2992                          * have their local Faulty bit cleared. If any writes
2993                          * happen in the meantime in the local node, they
2994                          * will land in the local bitmap, which will be synced
2995                          * by this node eventually
2996                          */
2997                         if (!mddev_is_clustered(rdev->mddev) ||
2998                             (err = md_cluster_ops->gather_bitmaps(rdev)) == 0) {
2999                                 clear_bit(Faulty, &rdev->flags);
3000                                 err = add_bound_rdev(rdev);
3001                         }
3002                 } else
3003                         err = -EBUSY;
3004         } else if (cmd_match(buf, "external_bbl") && (rdev->mddev->external)) {
3005                 set_bit(ExternalBbl, &rdev->flags);
3006                 rdev->badblocks.shift = 0;
3007                 err = 0;
3008         } else if (cmd_match(buf, "-external_bbl") && (rdev->mddev->external)) {
3009                 clear_bit(ExternalBbl, &rdev->flags);
3010                 err = 0;
3011         }
3012         if (!err)
3013                 sysfs_notify_dirent_safe(rdev->sysfs_state);
3014         return err ? err : len;
3015 }
3016 static struct rdev_sysfs_entry rdev_state =
3017 __ATTR_PREALLOC(state, S_IRUGO|S_IWUSR, state_show, state_store);
3018
3019 static ssize_t
3020 errors_show(struct md_rdev *rdev, char *page)
3021 {
3022         return sprintf(page, "%d\n", atomic_read(&rdev->corrected_errors));
3023 }
3024
3025 static ssize_t
3026 errors_store(struct md_rdev *rdev, const char *buf, size_t len)
3027 {
3028         unsigned int n;
3029         int rv;
3030
3031         rv = kstrtouint(buf, 10, &n);
3032         if (rv < 0)
3033                 return rv;
3034         atomic_set(&rdev->corrected_errors, n);
3035         return len;
3036 }
3037 static struct rdev_sysfs_entry rdev_errors =
3038 __ATTR(errors, S_IRUGO|S_IWUSR, errors_show, errors_store);
3039
3040 static ssize_t
3041 slot_show(struct md_rdev *rdev, char *page)
3042 {
3043         if (test_bit(Journal, &rdev->flags))
3044                 return sprintf(page, "journal\n");
3045         else if (rdev->raid_disk < 0)
3046                 return sprintf(page, "none\n");
3047         else
3048                 return sprintf(page, "%d\n", rdev->raid_disk);
3049 }
3050
3051 static ssize_t
3052 slot_store(struct md_rdev *rdev, const char *buf, size_t len)
3053 {
3054         int slot;
3055         int err;
3056
3057         if (test_bit(Journal, &rdev->flags))
3058                 return -EBUSY;
3059         if (strncmp(buf, "none", 4)==0)
3060                 slot = -1;
3061         else {
3062                 err = kstrtouint(buf, 10, (unsigned int *)&slot);
3063                 if (err < 0)
3064                         return err;
3065         }
3066         if (rdev->mddev->pers && slot == -1) {
3067                 /* Setting 'slot' on an active array requires also
3068                  * updating the 'rd%d' link, and communicating
3069                  * with the personality with ->hot_*_disk.
3070                  * For now we only support removing
3071                  * failed/spare devices.  This normally happens automatically,
3072                  * but not when the metadata is externally managed.
3073                  */
3074                 if (rdev->raid_disk == -1)
3075                         return -EEXIST;
3076                 /* personality does all needed checks */
3077                 if (rdev->mddev->pers->hot_remove_disk == NULL)
3078                         return -EINVAL;
3079                 clear_bit(Blocked, &rdev->flags);
3080                 remove_and_add_spares(rdev->mddev, rdev);
3081                 if (rdev->raid_disk >= 0)
3082                         return -EBUSY;
3083                 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
3084                 md_wakeup_thread(rdev->mddev->thread);
3085         } else if (rdev->mddev->pers) {
3086                 /* Activating a spare .. or possibly reactivating
3087                  * if we ever get bitmaps working here.
3088                  */
3089                 int err;
3090
3091                 if (rdev->raid_disk != -1)
3092                         return -EBUSY;
3093
3094                 if (test_bit(MD_RECOVERY_RUNNING, &rdev->mddev->recovery))
3095                         return -EBUSY;
3096
3097                 if (rdev->mddev->pers->hot_add_disk == NULL)
3098                         return -EINVAL;
3099
3100                 if (slot >= rdev->mddev->raid_disks &&
3101                     slot >= rdev->mddev->raid_disks + rdev->mddev->delta_disks)
3102                         return -ENOSPC;
3103
3104                 rdev->raid_disk = slot;
3105                 if (test_bit(In_sync, &rdev->flags))
3106                         rdev->saved_raid_disk = slot;
3107                 else
3108                         rdev->saved_raid_disk = -1;
3109                 clear_bit(In_sync, &rdev->flags);
3110                 clear_bit(Bitmap_sync, &rdev->flags);
3111                 err = rdev->mddev->pers->
3112                         hot_add_disk(rdev->mddev, rdev);
3113                 if (err) {
3114                         rdev->raid_disk = -1;
3115                         return err;
3116                 } else
3117                         sysfs_notify_dirent_safe(rdev->sysfs_state);
3118                 if (sysfs_link_rdev(rdev->mddev, rdev))
3119                         /* failure here is OK */;
3120                 /* don't wakeup anyone, leave that to userspace. */
3121         } else {
3122                 if (slot >= rdev->mddev->raid_disks &&
3123                     slot >= rdev->mddev->raid_disks + rdev->mddev->delta_disks)
3124                         return -ENOSPC;
3125                 rdev->raid_disk = slot;
3126                 /* assume it is working */
3127                 clear_bit(Faulty, &rdev->flags);
3128                 clear_bit(WriteMostly, &rdev->flags);
3129                 set_bit(In_sync, &rdev->flags);
3130                 sysfs_notify_dirent_safe(rdev->sysfs_state);
3131         }
3132         return len;
3133 }
3134
3135 static struct rdev_sysfs_entry rdev_slot =
3136 __ATTR(slot, S_IRUGO|S_IWUSR, slot_show, slot_store);
3137
3138 static ssize_t
3139 offset_show(struct md_rdev *rdev, char *page)
3140 {
3141         return sprintf(page, "%llu\n", (unsigned long long)rdev->data_offset);
3142 }
3143
3144 static ssize_t
3145 offset_store(struct md_rdev *rdev, const char *buf, size_t len)
3146 {
3147         unsigned long long offset;
3148         if (kstrtoull(buf, 10, &offset) < 0)
3149                 return -EINVAL;
3150         if (rdev->mddev->pers && rdev->raid_disk >= 0)
3151                 return -EBUSY;
3152         if (rdev->sectors && rdev->mddev->external)
3153                 /* Must set offset before size, so overlap checks
3154                  * can be sane */
3155                 return -EBUSY;
3156         rdev->data_offset = offset;
3157         rdev->new_data_offset = offset;
3158         return len;
3159 }
3160
3161 static struct rdev_sysfs_entry rdev_offset =
3162 __ATTR(offset, S_IRUGO|S_IWUSR, offset_show, offset_store);
3163
3164 static ssize_t new_offset_show(struct md_rdev *rdev, char *page)
3165 {
3166         return sprintf(page, "%llu\n",
3167                        (unsigned long long)rdev->new_data_offset);
3168 }
3169
3170 static ssize_t new_offset_store(struct md_rdev *rdev,
3171                                 const char *buf, size_t len)
3172 {
3173         unsigned long long new_offset;
3174         struct mddev *mddev = rdev->mddev;
3175
3176         if (kstrtoull(buf, 10, &new_offset) < 0)
3177                 return -EINVAL;
3178
3179         if (mddev->sync_thread ||
3180             test_bit(MD_RECOVERY_RUNNING,&mddev->recovery))
3181                 return -EBUSY;
3182         if (new_offset == rdev->data_offset)
3183                 /* reset is always permitted */
3184                 ;
3185         else if (new_offset > rdev->data_offset) {
3186                 /* must not push array size beyond rdev_sectors */
3187                 if (new_offset - rdev->data_offset
3188                     + mddev->dev_sectors > rdev->sectors)
3189                                 return -E2BIG;
3190         }
3191         /* Metadata worries about other space details. */
3192
3193         /* decreasing the offset is inconsistent with a backwards
3194          * reshape.
3195          */
3196         if (new_offset < rdev->data_offset &&
3197             mddev->reshape_backwards)
3198                 return -EINVAL;
3199         /* Increasing offset is inconsistent with forwards
3200          * reshape.  reshape_direction should be set to
3201          * 'backwards' first.
3202          */
3203         if (new_offset > rdev->data_offset &&
3204             !mddev->reshape_backwards)
3205                 return -EINVAL;
3206
3207         if (mddev->pers && mddev->persistent &&
3208             !super_types[mddev->major_version]
3209             .allow_new_offset(rdev, new_offset))
3210                 return -E2BIG;
3211         rdev->new_data_offset = new_offset;
3212         if (new_offset > rdev->data_offset)
3213                 mddev->reshape_backwards = 1;
3214         else if (new_offset < rdev->data_offset)
3215                 mddev->reshape_backwards = 0;
3216
3217         return len;
3218 }
3219 static struct rdev_sysfs_entry rdev_new_offset =
3220 __ATTR(new_offset, S_IRUGO|S_IWUSR, new_offset_show, new_offset_store);
3221
3222 static ssize_t
3223 rdev_size_show(struct md_rdev *rdev, char *page)
3224 {
3225         return sprintf(page, "%llu\n", (unsigned long long)rdev->sectors / 2);
3226 }
3227
3228 static int overlaps(sector_t s1, sector_t l1, sector_t s2, sector_t l2)
3229 {
3230         /* check if two start/length pairs overlap */
3231         if (s1+l1 <= s2)
3232                 return 0;
3233         if (s2+l2 <= s1)
3234                 return 0;
3235         return 1;
3236 }
3237
3238 static int strict_blocks_to_sectors(const char *buf, sector_t *sectors)
3239 {
3240         unsigned long long blocks;
3241         sector_t new;
3242
3243         if (kstrtoull(buf, 10, &blocks) < 0)
3244                 return -EINVAL;
3245
3246         if (blocks & 1ULL << (8 * sizeof(blocks) - 1))
3247                 return -EINVAL; /* sector conversion overflow */
3248
3249         new = blocks * 2;
3250         if (new != blocks * 2)
3251                 return -EINVAL; /* unsigned long long to sector_t overflow */
3252
3253         *sectors = new;
3254         return 0;
3255 }
3256
3257 static ssize_t
3258 rdev_size_store(struct md_rdev *rdev, const char *buf, size_t len)
3259 {
3260         struct mddev *my_mddev = rdev->mddev;
3261         sector_t oldsectors = rdev->sectors;
3262         sector_t sectors;
3263
3264         if (test_bit(Journal, &rdev->flags))
3265                 return -EBUSY;
3266         if (strict_blocks_to_sectors(buf, &sectors) < 0)
3267                 return -EINVAL;
3268         if (rdev->data_offset != rdev->new_data_offset)
3269                 return -EINVAL; /* too confusing */
3270         if (my_mddev->pers && rdev->raid_disk >= 0) {
3271                 if (my_mddev->persistent) {
3272                         sectors = super_types[my_mddev->major_version].
3273                                 rdev_size_change(rdev, sectors);
3274                         if (!sectors)
3275                                 return -EBUSY;
3276                 } else if (!sectors)
3277                         sectors = (i_size_read(rdev->bdev->bd_inode) >> 9) -
3278                                 rdev->data_offset;
3279                 if (!my_mddev->pers->resize)
3280                         /* Cannot change size for RAID0 or Linear etc */
3281                         return -EINVAL;
3282         }
3283         if (sectors < my_mddev->dev_sectors)
3284                 return -EINVAL; /* component must fit device */
3285
3286         rdev->sectors = sectors;
3287         if (sectors > oldsectors && my_mddev->external) {
3288                 /* Need to check that all other rdevs with the same
3289                  * ->bdev do not overlap.  'rcu' is sufficient to walk
3290                  * the rdev lists safely.
3291                  * This check does not provide a hard guarantee, it
3292                  * just helps avoid dangerous mistakes.
3293                  */
3294                 struct mddev *mddev;
3295                 int overlap = 0;
3296                 struct list_head *tmp;
3297
3298                 rcu_read_lock();
3299                 for_each_mddev(mddev, tmp) {
3300                         struct md_rdev *rdev2;
3301
3302                         rdev_for_each(rdev2, mddev)
3303                                 if (rdev->bdev == rdev2->bdev &&
3304                                     rdev != rdev2 &&
3305                                     overlaps(rdev->data_offset, rdev->sectors,
3306                                              rdev2->data_offset,
3307                                              rdev2->sectors)) {
3308                                         overlap = 1;
3309                                         break;
3310                                 }
3311                         if (overlap) {
3312                                 mddev_put(mddev);
3313                                 break;
3314                         }
3315                 }
3316                 rcu_read_unlock();
3317                 if (overlap) {
3318                         /* Someone else could have slipped in a size
3319                          * change here, but doing so is just silly.
3320                          * We put oldsectors back because we *know* it is
3321                          * safe, and trust userspace not to race with
3322                          * itself
3323                          */
3324                         rdev->sectors = oldsectors;
3325                         return -EBUSY;
3326                 }
3327         }
3328         return len;
3329 }
3330
3331 static struct rdev_sysfs_entry rdev_size =
3332 __ATTR(size, S_IRUGO|S_IWUSR, rdev_size_show, rdev_size_store);
3333
3334 static ssize_t recovery_start_show(struct md_rdev *rdev, char *page)
3335 {
3336         unsigned long long recovery_start = rdev->recovery_offset;
3337
3338         if (test_bit(In_sync, &rdev->flags) ||
3339             recovery_start == MaxSector)
3340                 return sprintf(page, "none\n");
3341
3342         return sprintf(page, "%llu\n", recovery_start);
3343 }
3344
3345 static ssize_t recovery_start_store(struct md_rdev *rdev, const char *buf, size_t len)
3346 {
3347         unsigned long long recovery_start;
3348
3349         if (cmd_match(buf, "none"))
3350                 recovery_start = MaxSector;
3351         else if (kstrtoull(buf, 10, &recovery_start))
3352                 return -EINVAL;
3353
3354         if (rdev->mddev->pers &&
3355             rdev->raid_disk >= 0)
3356                 return -EBUSY;
3357
3358         rdev->recovery_offset = recovery_start;
3359         if (recovery_start == MaxSector)
3360                 set_bit(In_sync, &rdev->flags);
3361         else
3362                 clear_bit(In_sync, &rdev->flags);
3363         return len;
3364 }
3365
3366 static struct rdev_sysfs_entry rdev_recovery_start =
3367 __ATTR(recovery_start, S_IRUGO|S_IWUSR, recovery_start_show, recovery_start_store);
3368
3369 /* sysfs access to bad-blocks list.
3370  * We present two files.
3371  * 'bad-blocks' lists sector numbers and lengths of ranges that
3372  *    are recorded as bad.  The list is truncated to fit within
3373  *    the one-page limit of sysfs.
3374  *    Writing "sector length" to this file adds an acknowledged
3375  *    bad block list.
3376  * 'unacknowledged-bad-blocks' lists bad blocks that have not yet
3377  *    been acknowledged.  Writing to this file adds bad blocks
3378  *    without acknowledging them.  This is largely for testing.
3379  */
3380 static ssize_t bb_show(struct md_rdev *rdev, char *page)
3381 {
3382         return badblocks_show(&rdev->badblocks, page, 0);
3383 }
3384 static ssize_t bb_store(struct md_rdev *rdev, const char *page, size_t len)
3385 {
3386         int rv = badblocks_store(&rdev->badblocks, page, len, 0);
3387         /* Maybe that ack was all we needed */
3388         if (test_and_clear_bit(BlockedBadBlocks, &rdev->flags))
3389                 wake_up(&rdev->blocked_wait);
3390         return rv;
3391 }
3392 static struct rdev_sysfs_entry rdev_bad_blocks =
3393 __ATTR(bad_blocks, S_IRUGO|S_IWUSR, bb_show, bb_store);
3394
3395 static ssize_t ubb_show(struct md_rdev *rdev, char *page)
3396 {
3397         return badblocks_show(&rdev->badblocks, page, 1);
3398 }
3399 static ssize_t ubb_store(struct md_rdev *rdev, const char *page, size_t len)
3400 {
3401         return badblocks_store(&rdev->badblocks, page, len, 1);
3402 }
3403 static struct rdev_sysfs_entry rdev_unack_bad_blocks =
3404 __ATTR(unacknowledged_bad_blocks, S_IRUGO|S_IWUSR, ubb_show, ubb_store);
3405
3406 static ssize_t
3407 ppl_sector_show(struct md_rdev *rdev, char *page)
3408 {
3409         return sprintf(page, "%llu\n", (unsigned long long)rdev->ppl.sector);
3410 }
3411
3412 static ssize_t
3413 ppl_sector_store(struct md_rdev *rdev, const char *buf, size_t len)
3414 {
3415         unsigned long long sector;
3416
3417         if (kstrtoull(buf, 10, &sector) < 0)
3418                 return -EINVAL;
3419         if (sector != (sector_t)sector)
3420                 return -EINVAL;
3421
3422         if (rdev->mddev->pers && test_bit(MD_HAS_PPL, &rdev->mddev->flags) &&
3423             rdev->raid_disk >= 0)
3424                 return -EBUSY;
3425
3426         if (rdev->mddev->persistent) {
3427                 if (rdev->mddev->major_version == 0)
3428                         return -EINVAL;
3429                 if ((sector > rdev->sb_start &&
3430                      sector - rdev->sb_start > S16_MAX) ||
3431                     (sector < rdev->sb_start &&
3432                      rdev->sb_start - sector > -S16_MIN))
3433                         return -EINVAL;
3434                 rdev->ppl.offset = sector - rdev->sb_start;
3435         } else if (!rdev->mddev->external) {
3436                 return -EBUSY;
3437         }
3438         rdev->ppl.sector = sector;
3439         return len;
3440 }
3441
3442 static struct rdev_sysfs_entry rdev_ppl_sector =
3443 __ATTR(ppl_sector, S_IRUGO|S_IWUSR, ppl_sector_show, ppl_sector_store);
3444
3445 static ssize_t
3446 ppl_size_show(struct md_rdev *rdev, char *page)
3447 {
3448         return sprintf(page, "%u\n", rdev->ppl.size);
3449 }
3450
3451 static ssize_t
3452 ppl_size_store(struct md_rdev *rdev, const char *buf, size_t len)
3453 {
3454         unsigned int size;
3455
3456         if (kstrtouint(buf, 10, &size) < 0)
3457                 return -EINVAL;
3458
3459         if (rdev->mddev->pers && test_bit(MD_HAS_PPL, &rdev->mddev->flags) &&
3460             rdev->raid_disk >= 0)
3461                 return -EBUSY;
3462
3463         if (rdev->mddev->persistent) {
3464                 if (rdev->mddev->major_version == 0)
3465                         return -EINVAL;
3466                 if (size > U16_MAX)
3467                         return -EINVAL;
3468         } else if (!rdev->mddev->external) {
3469                 return -EBUSY;
3470         }
3471         rdev->ppl.size = size;
3472         return len;
3473 }
3474
3475 static struct rdev_sysfs_entry rdev_ppl_size =
3476 __ATTR(ppl_size, S_IRUGO|S_IWUSR, ppl_size_show, ppl_size_store);
3477
3478 static struct attribute *rdev_default_attrs[] = {
3479         &rdev_state.attr,
3480         &rdev_errors.attr,
3481         &rdev_slot.attr,
3482         &rdev_offset.attr,
3483         &rdev_new_offset.attr,
3484         &rdev_size.attr,
3485         &rdev_recovery_start.attr,
3486         &rdev_bad_blocks.attr,
3487         &rdev_unack_bad_blocks.attr,
3488         &rdev_ppl_sector.attr,
3489         &rdev_ppl_size.attr,
3490         NULL,
3491 };
3492 static ssize_t
3493 rdev_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
3494 {
3495         struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
3496         struct md_rdev *rdev = container_of(kobj, struct md_rdev, kobj);
3497
3498         if (!entry->show)
3499                 return -EIO;
3500         if (!rdev->mddev)
3501                 return -ENODEV;
3502         return entry->show(rdev, page);
3503 }
3504
3505 static ssize_t
3506 rdev_attr_store(struct kobject *kobj, struct attribute *attr,
3507               const char *page, size_t length)
3508 {
3509         struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
3510         struct md_rdev *rdev = container_of(kobj, struct md_rdev, kobj);
3511         ssize_t rv;
3512         struct mddev *mddev = rdev->mddev;
3513
3514         if (!entry->store)
3515                 return -EIO;
3516         if (!capable(CAP_SYS_ADMIN))
3517                 return -EACCES;
3518         rv = mddev ? mddev_lock(mddev) : -ENODEV;
3519         if (!rv) {
3520                 if (rdev->mddev == NULL)
3521                         rv = -ENODEV;
3522                 else
3523                         rv = entry->store(rdev, page, length);
3524                 mddev_unlock(mddev);
3525         }
3526         return rv;
3527 }
3528
3529 static void rdev_free(struct kobject *ko)
3530 {
3531         struct md_rdev *rdev = container_of(ko, struct md_rdev, kobj);
3532         kfree(rdev);
3533 }
3534 static const struct sysfs_ops rdev_sysfs_ops = {
3535         .show           = rdev_attr_show,
3536         .store          = rdev_attr_store,
3537 };
3538 static struct kobj_type rdev_ktype = {
3539         .release        = rdev_free,
3540         .sysfs_ops      = &rdev_sysfs_ops,
3541         .default_attrs  = rdev_default_attrs,
3542 };
3543
3544 int md_rdev_init(struct md_rdev *rdev)
3545 {
3546         rdev->desc_nr = -1;
3547         rdev->saved_raid_disk = -1;
3548         rdev->raid_disk = -1;
3549         rdev->flags = 0;
3550         rdev->data_offset = 0;
3551         rdev->new_data_offset = 0;
3552         rdev->sb_events = 0;
3553         rdev->last_read_error = 0;
3554         rdev->sb_loaded = 0;
3555         rdev->bb_page = NULL;
3556         atomic_set(&rdev->nr_pending, 0);
3557         atomic_set(&rdev->read_errors, 0);
3558         atomic_set(&rdev->corrected_errors, 0);
3559
3560         INIT_LIST_HEAD(&rdev->same_set);
3561         init_waitqueue_head(&rdev->blocked_wait);
3562
3563         /* Add space to store bad block list.
3564          * This reserves the space even on arrays where it cannot
3565          * be used - I wonder if that matters
3566          */
3567         return badblocks_init(&rdev->badblocks, 0);
3568 }
3569 EXPORT_SYMBOL_GPL(md_rdev_init);
3570 /*
3571  * Import a device. If 'super_format' >= 0, then sanity check the superblock
3572  *
3573  * mark the device faulty if:
3574  *
3575  *   - the device is nonexistent (zero size)
3576  *   - the device has no valid superblock
3577  *
3578  * a faulty rdev _never_ has rdev->sb set.
3579  */
3580 static struct md_rdev *md_import_device(dev_t newdev, int super_format, int super_minor)
3581 {
3582         char b[BDEVNAME_SIZE];
3583         int err;
3584         struct md_rdev *rdev;
3585         sector_t size;
3586
3587         rdev = kzalloc(sizeof(*rdev), GFP_KERNEL);
3588         if (!rdev)
3589                 return ERR_PTR(-ENOMEM);
3590
3591         err = md_rdev_init(rdev);
3592         if (err)
3593                 goto abort_free;
3594         err = alloc_disk_sb(rdev);
3595         if (err)
3596                 goto abort_free;
3597
3598         err = lock_rdev(rdev, newdev, super_format == -2);
3599         if (err)
3600                 goto abort_free;
3601
3602         kobject_init(&rdev->kobj, &rdev_ktype);
3603
3604         size = i_size_read(rdev->bdev->bd_inode) >> BLOCK_SIZE_BITS;
3605         if (!size) {
3606                 pr_warn("md: %s has zero or unknown size, marking faulty!\n",
3607                         bdevname(rdev->bdev,b));
3608                 err = -EINVAL;
3609                 goto abort_free;
3610         }
3611
3612         if (super_format >= 0) {
3613                 err = super_types[super_format].
3614                         load_super(rdev, NULL, super_minor);
3615                 if (err == -EINVAL) {
3616                         pr_warn("md: %s does not have a valid v%d.%d superblock, not importing!\n",
3617                                 bdevname(rdev->bdev,b),
3618                                 super_format, super_minor);
3619                         goto abort_free;
3620                 }
3621                 if (err < 0) {
3622                         pr_warn("md: could not read %s's sb, not importing!\n",
3623                                 bdevname(rdev->bdev,b));
3624                         goto abort_free;
3625                 }
3626         }
3627
3628         return rdev;
3629
3630 abort_free:
3631         if (rdev->bdev)
3632                 unlock_rdev(rdev);
3633         md_rdev_clear(rdev);
3634         kfree(rdev);
3635         return ERR_PTR(err);
3636 }
3637
3638 /*
3639  * Check a full RAID array for plausibility
3640  */
3641
3642 static int analyze_sbs(struct mddev *mddev)
3643 {
3644         int i;
3645         struct md_rdev *rdev, *freshest, *tmp;
3646         char b[BDEVNAME_SIZE];
3647
3648         freshest = NULL;
3649         rdev_for_each_safe(rdev, tmp, mddev)
3650                 switch (super_types[mddev->major_version].
3651                         load_super(rdev, freshest, mddev->minor_version)) {
3652                 case 1:
3653                         freshest = rdev;
3654                         break;
3655                 case 0:
3656                         break;
3657                 default:
3658                         pr_warn("md: fatal superblock inconsistency in %s -- removing from array\n",
3659                                 bdevname(rdev->bdev,b));
3660                         md_kick_rdev_from_array(rdev);
3661                 }
3662
3663         /* Cannot find a valid fresh disk */
3664         if (!freshest) {
3665                 pr_warn("md: cannot find a valid disk\n");
3666                 return -EINVAL;
3667         }
3668
3669         super_types[mddev->major_version].
3670                 validate_super(mddev, freshest);
3671
3672         i = 0;
3673         rdev_for_each_safe(rdev, tmp, mddev) {
3674                 if (mddev->max_disks &&
3675                     (rdev->desc_nr >= mddev->max_disks ||
3676                      i > mddev->max_disks)) {
3677                         pr_warn("md: %s: %s: only %d devices permitted\n",
3678                                 mdname(mddev), bdevname(rdev->bdev, b),
3679                                 mddev->max_disks);
3680                         md_kick_rdev_from_array(rdev);
3681                         continue;
3682                 }
3683                 if (rdev != freshest) {
3684                         if (super_types[mddev->major_version].
3685                             validate_super(mddev, rdev)) {
3686                                 pr_warn("md: kicking non-fresh %s from array!\n",
3687                                         bdevname(rdev->bdev,b));
3688                                 md_kick_rdev_from_array(rdev);
3689                                 continue;
3690                         }
3691                 }
3692                 if (mddev->level == LEVEL_MULTIPATH) {
3693                         rdev->desc_nr = i++;
3694                         rdev->raid_disk = rdev->desc_nr;
3695                         set_bit(In_sync, &rdev->flags);
3696                 } else if (rdev->raid_disk >=
3697                             (mddev->raid_disks - min(0, mddev->delta_disks)) &&
3698                            !test_bit(Journal, &rdev->flags)) {
3699                         rdev->raid_disk = -1;
3700                         clear_bit(In_sync, &rdev->flags);
3701                 }
3702         }
3703
3704         return 0;
3705 }
3706
3707 /* Read a fixed-point number.
3708  * Numbers in sysfs attributes should be in "standard" units where
3709  * possible, so time should be in seconds.
3710  * However we internally use a a much smaller unit such as
3711  * milliseconds or jiffies.
3712  * This function takes a decimal number with a possible fractional
3713  * component, and produces an integer which is the result of
3714  * multiplying that number by 10^'scale'.
3715  * all without any floating-point arithmetic.
3716  */
3717 int strict_strtoul_scaled(const char *cp, unsigned long *res, int scale)
3718 {
3719         unsigned long result = 0;
3720         long decimals = -1;
3721         while (isdigit(*cp) || (*cp == '.' && decimals < 0)) {
3722                 if (*cp == '.')
3723                         decimals = 0;
3724                 else if (decimals < scale) {
3725                         unsigned int value;
3726                         value = *cp - '0';
3727                         result = result * 10 + value;
3728                         if (decimals >= 0)
3729                                 decimals++;
3730                 }
3731                 cp++;
3732         }
3733         if (*cp == '\n')
3734                 cp++;
3735         if (*cp)
3736                 return -EINVAL;
3737         if (decimals < 0)
3738                 decimals = 0;
3739         *res = result * int_pow(10, scale - decimals);
3740         return 0;
3741 }
3742
3743 static ssize_t
3744 safe_delay_show(struct mddev *mddev, char *page)
3745 {
3746         int msec = (mddev->safemode_delay*1000)/HZ;
3747         return sprintf(page, "%d.%03d\n", msec/1000, msec%1000);
3748 }
3749 static ssize_t
3750 safe_delay_store(struct mddev *mddev, const char *cbuf, size_t len)
3751 {
3752         unsigned long msec;
3753
3754         if (mddev_is_clustered(mddev)) {
3755                 pr_warn("md: Safemode is disabled for clustered mode\n");
3756                 return -EINVAL;
3757         }
3758
3759         if (strict_strtoul_scaled(cbuf, &msec, 3) < 0)
3760                 return -EINVAL;
3761         if (msec == 0)
3762                 mddev->safemode_delay = 0;
3763         else {
3764                 unsigned long old_delay = mddev->safemode_delay;
3765                 unsigned long new_delay = (msec*HZ)/1000;
3766
3767                 if (new_delay == 0)
3768                         new_delay = 1;
3769                 mddev->safemode_delay = new_delay;
3770                 if (new_delay < old_delay || old_delay == 0)
3771                         mod_timer(&mddev->safemode_timer, jiffies+1);
3772         }
3773         return len;
3774 }
3775 static struct md_sysfs_entry md_safe_delay =
3776 __ATTR(safe_mode_delay, S_IRUGO|S_IWUSR,safe_delay_show, safe_delay_store);
3777
3778 static ssize_t
3779 level_show(struct mddev *mddev, char *page)
3780 {
3781         struct md_personality *p;
3782         int ret;
3783         spin_lock(&mddev->lock);
3784         p = mddev->pers;
3785         if (p)
3786                 ret = sprintf(page, "%s\n", p->name);
3787         else if (mddev->clevel[0])
3788                 ret = sprintf(page, "%s\n", mddev->clevel);
3789         else if (mddev->level != LEVEL_NONE)
3790                 ret = sprintf(page, "%d\n", mddev->level);
3791         else
3792                 ret = 0;
3793         spin_unlock(&mddev->lock);
3794         return ret;
3795 }
3796
3797 static ssize_t
3798 level_store(struct mddev *mddev, const char *buf, size_t len)
3799 {
3800         char clevel[16];
3801         ssize_t rv;
3802         size_t slen = len;
3803         struct md_personality *pers, *oldpers;
3804         long level;
3805         void *priv, *oldpriv;
3806         struct md_rdev *rdev;
3807
3808         if (slen == 0 || slen >= sizeof(clevel))
3809                 return -EINVAL;
3810
3811         rv = mddev_lock(mddev);
3812         if (rv)
3813                 return rv;
3814
3815         if (mddev->pers == NULL) {
3816                 strncpy(mddev->clevel, buf, slen);
3817                 if (mddev->clevel[slen-1] == '\n')
3818                         slen--;
3819                 mddev->clevel[slen] = 0;
3820                 mddev->level = LEVEL_NONE;
3821                 rv = len;
3822                 goto out_unlock;
3823         }
3824         rv = -EROFS;
3825         if (mddev->ro)
3826                 goto out_unlock;
3827
3828         /* request to change the personality.  Need to ensure:
3829          *  - array is not engaged in resync/recovery/reshape
3830          *  - old personality can be suspended
3831          *  - new personality will access other array.
3832          */
3833
3834         rv = -EBUSY;
3835         if (mddev->sync_thread ||
3836             test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
3837             mddev->reshape_position != MaxSector ||
3838             mddev->sysfs_active)
3839                 goto out_unlock;
3840
3841         rv = -EINVAL;
3842         if (!mddev->pers->quiesce) {
3843                 pr_warn("md: %s: %s does not support online personality change\n",
3844                         mdname(mddev), mddev->pers->name);
3845                 goto out_unlock;
3846         }
3847
3848         /* Now find the new personality */
3849         strncpy(clevel, buf, slen);
3850         if (clevel[slen-1] == '\n')
3851                 slen--;
3852         clevel[slen] = 0;
3853         if (kstrtol(clevel, 10, &level))
3854                 level = LEVEL_NONE;
3855
3856         if (request_module("md-%s", clevel) != 0)
3857                 request_module("md-level-%s", clevel);
3858         spin_lock(&pers_lock);
3859         pers = find_pers(level, clevel);
3860         if (!pers || !try_module_get(pers->owner)) {
3861                 spin_unlock(&pers_lock);
3862                 pr_warn("md: personality %s not loaded\n", clevel);
3863                 rv = -EINVAL;
3864                 goto out_unlock;
3865         }
3866         spin_unlock(&pers_lock);
3867
3868         if (pers == mddev->pers) {
3869                 /* Nothing to do! */
3870                 module_put(pers->owner);
3871                 rv = len;
3872                 goto out_unlock;
3873         }
3874         if (!pers->takeover) {
3875                 module_put(pers->owner);
3876                 pr_warn("md: %s: %s does not support personality takeover\n",
3877                         mdname(mddev), clevel);
3878                 rv = -EINVAL;
3879                 goto out_unlock;
3880         }
3881
3882         rdev_for_each(rdev, mddev)
3883                 rdev->new_raid_disk = rdev->raid_disk;
3884
3885         /* ->takeover must set new_* and/or delta_disks
3886          * if it succeeds, and may set them when it fails.
3887          */
3888         priv = pers->takeover(mddev);
3889         if (IS_ERR(priv)) {
3890                 mddev->new_level = mddev->level;
3891                 mddev->new_layout = mddev->layout;
3892                 mddev->new_chunk_sectors = mddev->chunk_sectors;
3893                 mddev->raid_disks -= mddev->delta_disks;
3894                 mddev->delta_disks = 0;
3895                 mddev->reshape_backwards = 0;
3896                 module_put(pers->owner);
3897                 pr_warn("md: %s: %s would not accept array\n",
3898                         mdname(mddev), clevel);
3899                 rv = PTR_ERR(priv);
3900                 goto out_unlock;
3901         }
3902
3903         /* Looks like we have a winner */
3904         mddev_suspend(mddev);
3905         mddev_detach(mddev);
3906
3907         spin_lock(&mddev->lock);
3908         oldpers = mddev->pers;
3909         oldpriv = mddev->private;
3910         mddev->pers = pers;
3911         mddev->private = priv;
3912         strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
3913         mddev->level = mddev->new_level;
3914         mddev->layout = mddev->new_layout;
3915         mddev->chunk_sectors = mddev->new_chunk_sectors;
3916         mddev->delta_disks = 0;
3917         mddev->reshape_backwards = 0;
3918         mddev->degraded = 0;
3919         spin_unlock(&mddev->lock);
3920
3921         if (oldpers->sync_request == NULL &&
3922             mddev->external) {
3923                 /* We are converting from a no-redundancy array
3924                  * to a redundancy array and metadata is managed
3925                  * externally so we need to be sure that writes
3926                  * won't block due to a need to transition
3927                  *      clean->dirty
3928                  * until external management is started.
3929                  */
3930                 mddev->in_sync = 0;
3931                 mddev->safemode_delay = 0;
3932                 mddev->safemode = 0;
3933         }
3934
3935         oldpers->free(mddev, oldpriv);
3936
3937         if (oldpers->sync_request == NULL &&
3938             pers->sync_request != NULL) {
3939                 /* need to add the md_redundancy_group */
3940                 if (sysfs_create_group(&mddev->kobj, &md_redundancy_group))
3941                         pr_warn("md: cannot register extra attributes for %s\n",
3942                                 mdname(mddev));
3943                 mddev->sysfs_action = sysfs_get_dirent(mddev->kobj.sd, "sync_action");
3944         }
3945         if (oldpers->sync_request != NULL &&
3946             pers->sync_request == NULL) {
3947                 /* need to remove the md_redundancy_group */
3948                 if (mddev->to_remove == NULL)
3949                         mddev->to_remove = &md_redundancy_group;
3950         }
3951
3952         module_put(oldpers->owner);
3953
3954         rdev_for_each(rdev, mddev) {
3955                 if (rdev->raid_disk < 0)
3956                         continue;
3957                 if (rdev->new_raid_disk >= mddev->raid_disks)
3958                         rdev->new_raid_disk = -1;
3959                 if (rdev->new_raid_disk == rdev->raid_disk)
3960                         continue;
3961                 sysfs_unlink_rdev(mddev, rdev);
3962         }
3963         rdev_for_each(rdev, mddev) {
3964                 if (rdev->raid_disk < 0)
3965                         continue;
3966                 if (rdev->new_raid_disk == rdev->raid_disk)
3967                         continue;
3968                 rdev->raid_disk = rdev->new_raid_disk;
3969                 if (rdev->raid_disk < 0)
3970                         clear_bit(In_sync, &rdev->flags);
3971                 else {
3972                         if (sysfs_link_rdev(mddev, rdev))
3973                                 pr_warn("md: cannot register rd%d for %s after level change\n",
3974                                         rdev->raid_disk, mdname(mddev));
3975                 }
3976         }
3977
3978         if (pers->sync_request == NULL) {
3979                 /* this is now an array without redundancy, so
3980                  * it must always be in_sync
3981                  */
3982                 mddev->in_sync = 1;
3983                 del_timer_sync(&mddev->safemode_timer);
3984         }
3985         blk_set_stacking_limits(&mddev->queue->limits);
3986         pers->run(mddev);
3987         set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
3988         mddev_resume(mddev);
3989         if (!mddev->thread)
3990                 md_update_sb(mddev, 1);
3991         sysfs_notify(&mddev->kobj, NULL, "level");
3992         md_new_event(mddev);
3993         rv = len;
3994 out_unlock:
3995         mddev_unlock(mddev);
3996         return rv;
3997 }
3998
3999 static struct md_sysfs_entry md_level =
4000 __ATTR(level, S_IRUGO|S_IWUSR, level_show, level_store);
4001
4002 static ssize_t
4003 layout_show(struct mddev *mddev, char *page)
4004 {
4005         /* just a number, not meaningful for all levels */
4006         if (mddev->reshape_position != MaxSector &&
4007             mddev->layout != mddev->new_layout)
4008                 return sprintf(page, "%d (%d)\n",
4009                                mddev->new_layout, mddev->layout);
4010         return sprintf(page, "%d\n", mddev->layout);
4011 }
4012
4013 static ssize_t
4014 layout_store(struct mddev *mddev, const char *buf, size_t len)
4015 {
4016         unsigned int n;
4017         int err;
4018
4019         err = kstrtouint(buf, 10, &n);
4020         if (err < 0)
4021                 return err;
4022         err = mddev_lock(mddev);
4023         if (err)
4024                 return err;
4025
4026         if (mddev->pers) {
4027                 if (mddev->pers->check_reshape == NULL)
4028                         err = -EBUSY;
4029                 else if (mddev->ro)
4030                         err = -EROFS;
4031                 else {
4032                         mddev->new_layout = n;
4033                         err = mddev->pers->check_reshape(mddev);
4034                         if (err)
4035                                 mddev->new_layout = mddev->layout;
4036                 }
4037         } else {
4038                 mddev->new_layout = n;
4039                 if (mddev->reshape_position == MaxSector)
4040                         mddev->layout = n;
4041         }
4042         mddev_unlock(mddev);
4043         return err ?: len;
4044 }
4045 static struct md_sysfs_entry md_layout =
4046 __ATTR(layout, S_IRUGO|S_IWUSR, layout_show, layout_store);
4047
4048 static ssize_t
4049 raid_disks_show(struct mddev *mddev, char *page)
4050 {
4051         if (mddev->raid_disks == 0)
4052                 return 0;
4053         if (mddev->reshape_position != MaxSector &&
4054             mddev->delta_disks != 0)
4055                 return sprintf(page, "%d (%d)\n", mddev->raid_disks,
4056                                mddev->raid_disks - mddev->delta_disks);
4057         return sprintf(page, "%d\n", mddev->raid_disks);
4058 }
4059
4060 static int update_raid_disks(struct mddev *mddev, int raid_disks);
4061
4062 static ssize_t
4063 raid_disks_store(struct mddev *mddev, const char *buf, size_t len)
4064 {
4065         unsigned int n;
4066         int err;
4067
4068         err = kstrtouint(buf, 10, &n);
4069         if (err < 0)
4070                 return err;
4071
4072         err = mddev_lock(mddev);
4073         if (err)
4074                 return err;
4075         if (mddev->pers)
4076                 err = update_raid_disks(mddev, n);
4077         else if (mddev->reshape_position != MaxSector) {
4078                 struct md_rdev *rdev;
4079                 int olddisks = mddev->raid_disks - mddev->delta_disks;
4080
4081                 err = -EINVAL;
4082                 rdev_for_each(rdev, mddev) {
4083                         if (olddisks < n &&
4084                             rdev->data_offset < rdev->new_data_offset)
4085                                 goto out_unlock;
4086                         if (olddisks > n &&
4087                             rdev->data_offset > rdev->new_data_offset)
4088                                 goto out_unlock;
4089                 }
4090                 err = 0;
4091                 mddev->delta_disks = n - olddisks;
4092                 mddev->raid_disks = n;
4093                 mddev->reshape_backwards = (mddev->delta_disks < 0);
4094         } else
4095                 mddev->raid_disks = n;
4096 out_unlock:
4097         mddev_unlock(mddev);
4098         return err ? err : len;
4099 }
4100 static struct md_sysfs_entry md_raid_disks =
4101 __ATTR(raid_disks, S_IRUGO|S_IWUSR, raid_disks_show, raid_disks_store);
4102
4103 static ssize_t
4104 chunk_size_show(struct mddev *mddev, char *page)
4105 {
4106         if (mddev->reshape_position != MaxSector &&
4107             mddev->chunk_sectors != mddev->new_chunk_sectors)
4108                 return sprintf(page, "%d (%d)\n",
4109                                mddev->new_chunk_sectors << 9,
4110                                mddev->chunk_sectors << 9);
4111         return sprintf(page, "%d\n", mddev->chunk_sectors << 9);
4112 }
4113
4114 static ssize_t
4115 chunk_size_store(struct mddev *mddev, const char *buf, size_t len)
4116 {
4117         unsigned long n;
4118         int err;
4119
4120         err = kstrtoul(buf, 10, &n);
4121         if (err < 0)
4122                 return err;
4123
4124         err = mddev_lock(mddev);
4125         if (err)
4126                 return err;
4127         if (mddev->pers) {
4128                 if (mddev->pers->check_reshape == NULL)
4129                         err = -EBUSY;
4130                 else if (mddev->ro)
4131                         err = -EROFS;
4132                 else {
4133                         mddev->new_chunk_sectors = n >> 9;
4134                         err = mddev->pers->check_reshape(mddev);
4135                         if (err)
4136                                 mddev->new_chunk_sectors = mddev->chunk_sectors;
4137                 }
4138         } else {
4139                 mddev->new_chunk_sectors = n >> 9;
4140                 if (mddev->reshape_position == MaxSector)
4141                         mddev->chunk_sectors = n >> 9;
4142         }
4143         mddev_unlock(mddev);
4144         return err ?: len;
4145 }
4146 static struct md_sysfs_entry md_chunk_size =
4147 __ATTR(chunk_size, S_IRUGO|S_IWUSR, chunk_size_show, chunk_size_store);
4148
4149 static ssize_t
4150 resync_start_show(struct mddev *mddev, char *page)
4151 {
4152         if (mddev->recovery_cp == MaxSector)
4153                 return sprintf(page, "none\n");
4154         return sprintf(page, "%llu\n", (unsigned long long)mddev->recovery_cp);
4155 }
4156
4157 static ssize_t
4158 resync_start_store(struct mddev *mddev, const char *buf, size_t len)
4159 {
4160         unsigned long long n;
4161         int err;
4162
4163         if (cmd_match(buf, "none"))
4164                 n = MaxSector;
4165         else {
4166                 err = kstrtoull(buf, 10, &n);
4167                 if (err < 0)
4168                         return err;
4169                 if (n != (sector_t)n)
4170                         return -EINVAL;
4171         }
4172
4173         err = mddev_lock(mddev);
4174         if (err)
4175                 return err;
4176         if (mddev->pers && !test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
4177                 err = -EBUSY;
4178
4179         if (!err) {
4180                 mddev->recovery_cp = n;
4181                 if (mddev->pers)
4182                         set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
4183         }
4184         mddev_unlock(mddev);
4185         return err ?: len;
4186 }
4187 static struct md_sysfs_entry md_resync_start =
4188 __ATTR_PREALLOC(resync_start, S_IRUGO|S_IWUSR,
4189                 resync_start_show, resync_start_store);
4190
4191 /*
4192  * The array state can be:
4193  *
4194  * clear
4195  *     No devices, no size, no level
4196  *     Equivalent to STOP_ARRAY ioctl
4197  * inactive
4198  *     May have some settings, but array is not active
4199  *        all IO results in error
4200  *     When written, doesn't tear down array, but just stops it
4201  * suspended (not supported yet)
4202  *     All IO requests will block. The array can be reconfigured.
4203  *     Writing this, if accepted, will block until array is quiescent
4204  * readonly
4205  *     no resync can happen.  no superblocks get written.
4206  *     write requests fail
4207  * read-auto
4208  *     like readonly, but behaves like 'clean' on a write request.
4209  *
4210  * clean - no pending writes, but otherwise active.
4211  *     When written to inactive array, starts without resync
4212  *     If a write request arrives then
4213  *       if metadata is known, mark 'dirty' and switch to 'active'.
4214  *       if not known, block and switch to write-pending
4215  *     If written to an active array that has pending writes, then fails.
4216  * active
4217  *     fully active: IO and resync can be happening.
4218  *     When written to inactive array, starts with resync
4219  *
4220  * write-pending
4221  *     clean, but writes are blocked waiting for 'active' to be written.
4222  *
4223  * active-idle
4224  *     like active, but no writes have been seen for a while (100msec).
4225  *
4226  * broken
4227  *     RAID0/LINEAR-only: same as clean, but array is missing a member.
4228  *     It's useful because RAID0/LINEAR mounted-arrays aren't stopped
4229  *     when a member is gone, so this state will at least alert the
4230  *     user that something is wrong.
4231  */
4232 enum array_state { clear, inactive, suspended, readonly, read_auto, clean, active,
4233                    write_pending, active_idle, broken, bad_word};
4234 static char *array_states[] = {
4235         "clear", "inactive", "suspended", "readonly", "read-auto", "clean", "active",
4236         "write-pending", "active-idle", "broken", NULL };
4237
4238 static int match_word(const char *word, char **list)
4239 {
4240         int n;
4241         for (n=0; list[n]; n++)
4242                 if (cmd_match(word, list[n]))
4243                         break;
4244         return n;
4245 }
4246
4247 static ssize_t
4248 array_state_show(struct mddev *mddev, char *page)
4249 {
4250         enum array_state st = inactive;
4251
4252         if (mddev->pers && !test_bit(MD_NOT_READY, &mddev->flags)) {
4253                 switch(mddev->ro) {
4254                 case 1:
4255                         st = readonly;
4256                         break;
4257                 case 2:
4258                         st = read_auto;
4259                         break;
4260                 case 0:
4261                         spin_lock(&mddev->lock);
4262                         if (test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags))
4263                                 st = write_pending;
4264                         else if (mddev->in_sync)
4265                                 st = clean;
4266                         else if (mddev->safemode)
4267                                 st = active_idle;
4268                         else
4269                                 st = active;
4270                         spin_unlock(&mddev->lock);
4271                 }
4272
4273                 if (test_bit(MD_BROKEN, &mddev->flags) && st == clean)
4274                         st = broken;
4275         } else {
4276                 if (list_empty(&mddev->disks) &&
4277                     mddev->raid_disks == 0 &&
4278                     mddev->dev_sectors == 0)
4279                         st = clear;
4280                 else
4281                         st = inactive;
4282         }
4283         return sprintf(page, "%s\n", array_states[st]);
4284 }
4285
4286 static int do_md_stop(struct mddev *mddev, int ro, struct block_device *bdev);
4287 static int md_set_readonly(struct mddev *mddev, struct block_device *bdev);
4288 static int do_md_run(struct mddev *mddev);
4289 static int restart_array(struct mddev *mddev);
4290
4291 static ssize_t
4292 array_state_store(struct mddev *mddev, const char *buf, size_t len)
4293 {
4294         int err = 0;
4295         enum array_state st = match_word(buf, array_states);
4296
4297         if (mddev->pers && (st == active || st == clean) && mddev->ro != 1) {
4298                 /* don't take reconfig_mutex when toggling between
4299                  * clean and active
4300                  */
4301                 spin_lock(&mddev->lock);
4302                 if (st == active) {
4303                         restart_array(mddev);
4304                         clear_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
4305                         md_wakeup_thread(mddev->thread);
4306                         wake_up(&mddev->sb_wait);
4307                 } else /* st == clean */ {
4308                         restart_array(mddev);
4309                         if (!set_in_sync(mddev))
4310                                 err = -EBUSY;
4311                 }
4312                 if (!err)
4313                         sysfs_notify_dirent_safe(mddev->sysfs_state);
4314                 spin_unlock(&mddev->lock);
4315                 return err ?: len;
4316         }
4317         err = mddev_lock(mddev);
4318         if (err)
4319                 return err;
4320         err = -EINVAL;
4321         switch(st) {
4322         case bad_word:
4323                 break;
4324         case clear:
4325                 /* stopping an active array */
4326                 err = do_md_stop(mddev, 0, NULL);
4327                 break;
4328         case inactive:
4329                 /* stopping an active array */
4330                 if (mddev->pers)
4331                         err = do_md_stop(mddev, 2, NULL);
4332                 else
4333                         err = 0; /* already inactive */
4334                 break;
4335         case suspended:
4336                 break; /* not supported yet */
4337         case readonly:
4338                 if (mddev->pers)
4339                         err = md_set_readonly(mddev, NULL);
4340                 else {
4341                         mddev->ro = 1;
4342                         set_disk_ro(mddev->gendisk, 1);
4343                         err = do_md_run(mddev);
4344                 }
4345                 break;
4346         case read_auto:
4347                 if (mddev->pers) {
4348                         if (mddev->ro == 0)
4349                                 err = md_set_readonly(mddev, NULL);
4350                         else if (mddev->ro == 1)
4351                                 err = restart_array(mddev);
4352                         if (err == 0) {
4353                                 mddev->ro = 2;
4354                                 set_disk_ro(mddev->gendisk, 0);
4355                         }
4356                 } else {
4357                         mddev->ro = 2;
4358                         err = do_md_run(mddev);
4359                 }
4360                 break;
4361         case clean:
4362                 if (mddev->pers) {
4363                         err = restart_array(mddev);
4364                         if (err)
4365                                 break;
4366                         spin_lock(&mddev->lock);
4367                         if (!set_in_sync(mddev))
4368                                 err = -EBUSY;
4369                         spin_unlock(&mddev->lock);
4370                 } else
4371                         err = -EINVAL;
4372                 break;
4373         case active:
4374                 if (mddev->pers) {
4375                         err = restart_array(mddev);
4376                         if (err)
4377                                 break;
4378                         clear_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
4379                         wake_up(&mddev->sb_wait);
4380                         err = 0;
4381                 } else {
4382                         mddev->ro = 0;
4383                         set_disk_ro(mddev->gendisk, 0);
4384                         err = do_md_run(mddev);
4385                 }
4386                 break;
4387         case write_pending:
4388         case active_idle:
4389         case broken:
4390                 /* these cannot be set */
4391                 break;
4392         }
4393
4394         if (!err) {
4395                 if (mddev->hold_active == UNTIL_IOCTL)
4396                         mddev->hold_active = 0;
4397                 sysfs_notify_dirent_safe(mddev->sysfs_state);
4398         }
4399         mddev_unlock(mddev);
4400         return err ?: len;
4401 }
4402 static struct md_sysfs_entry md_array_state =
4403 __ATTR_PREALLOC(array_state, S_IRUGO|S_IWUSR, array_state_show, array_state_store);
4404
4405 static ssize_t
4406 max_corrected_read_errors_show(struct mddev *mddev, char *page) {
4407         return sprintf(page, "%d\n",
4408                        atomic_read(&mddev->max_corr_read_errors));
4409 }
4410
4411 static ssize_t
4412 max_corrected_read_errors_store(struct mddev *mddev, const char *buf, size_t len)
4413 {
4414         unsigned int n;
4415         int rv;
4416
4417         rv = kstrtouint(buf, 10, &n);
4418         if (rv < 0)
4419                 return rv;
4420         atomic_set(&mddev->max_corr_read_errors, n);
4421         return len;
4422 }
4423
4424 static struct md_sysfs_entry max_corr_read_errors =
4425 __ATTR(max_read_errors, S_IRUGO|S_IWUSR, max_corrected_read_errors_show,
4426         max_corrected_read_errors_store);
4427
4428 static ssize_t
4429 null_show(struct mddev *mddev, char *page)
4430 {
4431         return -EINVAL;
4432 }
4433
4434 static ssize_t
4435 new_dev_store(struct mddev *mddev, const char *buf, size_t len)
4436 {
4437         /* buf must be %d:%d\n? giving major and minor numbers */
4438         /* The new device is added to the array.
4439          * If the array has a persistent superblock, we read the
4440          * superblock to initialise info and check validity.
4441          * Otherwise, only checking done is that in bind_rdev_to_array,
4442          * which mainly checks size.
4443          */
4444         char *e;
4445         int major = simple_strtoul(buf, &e, 10);
4446         int minor;
4447         dev_t dev;
4448         struct md_rdev *rdev;
4449         int err;
4450
4451         if (!*buf || *e != ':' || !e[1] || e[1] == '\n')
4452                 return -EINVAL;
4453         minor = simple_strtoul(e+1, &e, 10);
4454         if (*e && *e != '\n')
4455                 return -EINVAL;
4456         dev = MKDEV(major, minor);
4457         if (major != MAJOR(dev) ||
4458             minor != MINOR(dev))
4459                 return -EOVERFLOW;
4460
4461         flush_workqueue(md_misc_wq);
4462
4463         err = mddev_lock(mddev);
4464         if (err)
4465                 return err;
4466         if (mddev->persistent) {
4467                 rdev = md_import_device(dev, mddev->major_version,
4468                                         mddev->minor_version);
4469                 if (!IS_ERR(rdev) && !list_empty(&mddev->disks)) {
4470                         struct md_rdev *rdev0
4471                                 = list_entry(mddev->disks.next,
4472                                              struct md_rdev, same_set);
4473                         err = super_types[mddev->major_version]
4474                                 .load_super(rdev, rdev0, mddev->minor_version);
4475                         if (err < 0)
4476                                 goto out;
4477                 }
4478         } else if (mddev->external)
4479                 rdev = md_import_device(dev, -2, -1);
4480         else
4481                 rdev = md_import_device(dev, -1, -1);
4482
4483         if (IS_ERR(rdev)) {
4484                 mddev_unlock(mddev);
4485                 return PTR_ERR(rdev);
4486         }
4487         err = bind_rdev_to_array(rdev, mddev);
4488  out:
4489         if (err)
4490                 export_rdev(rdev);
4491         mddev_unlock(mddev);
4492         if (!err)
4493                 md_new_event(mddev);
4494         return err ? err : len;
4495 }
4496
4497 static struct md_sysfs_entry md_new_device =
4498 __ATTR(new_dev, S_IWUSR, null_show, new_dev_store);
4499
4500 static ssize_t
4501 bitmap_store(struct mddev *mddev, const char *buf, size_t len)
4502 {
4503         char *end;
4504         unsigned long chunk, end_chunk;
4505         int err;
4506
4507         err = mddev_lock(mddev);
4508         if (err)
4509                 return err;
4510         if (!mddev->bitmap)
4511                 goto out;
4512         /* buf should be <chunk> <chunk> ... or <chunk>-<chunk> ... (range) */
4513         while (*buf) {
4514                 chunk = end_chunk = simple_strtoul(buf, &end, 0);
4515                 if (buf == end) break;
4516                 if (*end == '-') { /* range */
4517                         buf = end + 1;
4518                         end_chunk = simple_strtoul(buf, &end, 0);
4519                         if (buf == end) break;
4520                 }
4521                 if (*end && !isspace(*end)) break;
4522                 md_bitmap_dirty_bits(mddev->bitmap, chunk, end_chunk);
4523                 buf = skip_spaces(end);
4524         }
4525         md_bitmap_unplug(mddev->bitmap); /* flush the bits to disk */
4526 out:
4527         mddev_unlock(mddev);
4528         return len;
4529 }
4530
4531 static struct md_sysfs_entry md_bitmap =
4532 __ATTR(bitmap_set_bits, S_IWUSR, null_show, bitmap_store);
4533
4534 static ssize_t
4535 size_show(struct mddev *mddev, char *page)
4536 {
4537         return sprintf(page, "%llu\n",
4538                 (unsigned long long)mddev->dev_sectors / 2);
4539 }
4540
4541 static int update_size(struct mddev *mddev, sector_t num_sectors);
4542
4543 static ssize_t
4544 size_store(struct mddev *mddev, const char *buf, size_t len)
4545 {
4546         /* If array is inactive, we can reduce the component size, but
4547          * not increase it (except from 0).
4548          * If array is active, we can try an on-line resize
4549          */
4550         sector_t sectors;
4551         int err = strict_blocks_to_sectors(buf, &sectors);
4552
4553         if (err < 0)
4554                 return err;
4555         err = mddev_lock(mddev);
4556         if (err)
4557                 return err;
4558         if (mddev->pers) {
4559                 err = update_size(mddev, sectors);
4560                 if (err == 0)
4561                         md_update_sb(mddev, 1);
4562         } else {
4563                 if (mddev->dev_sectors == 0 ||
4564                     mddev->dev_sectors > sectors)
4565                         mddev->dev_sectors = sectors;
4566                 else
4567                         err = -ENOSPC;
4568         }
4569         mddev_unlock(mddev);
4570         return err ? err : len;
4571 }
4572
4573 static struct md_sysfs_entry md_size =
4574 __ATTR(component_size, S_IRUGO|S_IWUSR, size_show, size_store);
4575
4576 /* Metadata version.
4577  * This is one of
4578  *   'none' for arrays with no metadata (good luck...)
4579  *   'external' for arrays with externally managed metadata,
4580  * or N.M for internally known formats
4581  */
4582 static ssize_t
4583 metadata_show(struct mddev *mddev, char *page)
4584 {
4585         if (mddev->persistent)
4586                 return sprintf(page, "%d.%d\n",
4587                                mddev->major_version, mddev->minor_version);
4588         else if (mddev->external)
4589                 return sprintf(page, "external:%s\n", mddev->metadata_type);
4590         else
4591                 return sprintf(page, "none\n");
4592 }
4593
4594 static ssize_t
4595 metadata_store(struct mddev *mddev, const char *buf, size_t len)
4596 {
4597         int major, minor;
4598         char *e;
4599         int err;
4600         /* Changing the details of 'external' metadata is
4601          * always permitted.  Otherwise there must be
4602          * no devices attached to the array.
4603          */
4604
4605         err = mddev_lock(mddev);
4606         if (err)
4607                 return err;
4608         err = -EBUSY;
4609         if (mddev->external && strncmp(buf, "external:", 9) == 0)
4610                 ;
4611         else if (!list_empty(&mddev->disks))
4612                 goto out_unlock;
4613
4614         err = 0;
4615         if (cmd_match(buf, "none")) {
4616                 mddev->persistent = 0;
4617                 mddev->external = 0;
4618                 mddev->major_version = 0;
4619                 mddev->minor_version = 90;
4620                 goto out_unlock;
4621         }
4622         if (strncmp(buf, "external:", 9) == 0) {
4623                 size_t namelen = len-9;
4624                 if (namelen >= sizeof(mddev->metadata_type))
4625                         namelen = sizeof(mddev->metadata_type)-1;
4626                 strncpy(mddev->metadata_type, buf+9, namelen);
4627                 mddev->metadata_type[namelen] = 0;
4628                 if (namelen && mddev->metadata_type[namelen-1] == '\n')
4629                         mddev->metadata_type[--namelen] = 0;
4630                 mddev->persistent = 0;
4631                 mddev->external = 1;
4632                 mddev->major_version = 0;
4633                 mddev->minor_version = 90;
4634                 goto out_unlock;
4635         }
4636         major = simple_strtoul(buf, &e, 10);
4637         err = -EINVAL;
4638         if (e==buf || *e != '.')
4639                 goto out_unlock;
4640         buf = e+1;
4641         minor = simple_strtoul(buf, &e, 10);
4642         if (e==buf || (*e && *e != '\n') )
4643                 goto out_unlock;
4644         err = -ENOENT;
4645         if (major >= ARRAY_SIZE(super_types) || super_types[major].name == NULL)
4646                 goto out_unlock;
4647         mddev->major_version = major;
4648         mddev->minor_version = minor;
4649         mddev->persistent = 1;
4650         mddev->external = 0;
4651         err = 0;
4652 out_unlock:
4653         mddev_unlock(mddev);
4654         return err ?: len;
4655 }
4656
4657 static struct md_sysfs_entry md_metadata =
4658 __ATTR_PREALLOC(metadata_version, S_IRUGO|S_IWUSR, metadata_show, metadata_store);
4659
4660 static ssize_t
4661 action_show(struct mddev *mddev, char *page)
4662 {
4663         char *type = "idle";
4664         unsigned long recovery = mddev->recovery;
4665         if (test_bit(MD_RECOVERY_FROZEN, &recovery))
4666                 type = "frozen";
4667         else if (test_bit(MD_RECOVERY_RUNNING, &recovery) ||
4668             (!mddev->ro && test_bit(MD_RECOVERY_NEEDED, &recovery))) {
4669                 if (test_bit(MD_RECOVERY_RESHAPE, &recovery))
4670                         type = "reshape";
4671                 else if (test_bit(MD_RECOVERY_SYNC, &recovery)) {
4672                         if (!test_bit(MD_RECOVERY_REQUESTED, &recovery))
4673                                 type = "resync";
4674                         else if (test_bit(MD_RECOVERY_CHECK, &recovery))
4675                                 type = "check";
4676                         else
4677                                 type = "repair";
4678                 } else if (test_bit(MD_RECOVERY_RECOVER, &recovery))
4679                         type = "recover";
4680                 else if (mddev->reshape_position != MaxSector)
4681                         type = "reshape";
4682         }
4683         return sprintf(page, "%s\n", type);
4684 }
4685
4686 static ssize_t
4687 action_store(struct mddev *mddev, const char *page, size_t len)
4688 {
4689         if (!mddev->pers || !mddev->pers->sync_request)
4690                 return -EINVAL;
4691
4692
4693         if (cmd_match(page, "idle") || cmd_match(page, "frozen")) {
4694                 if (cmd_match(page, "frozen"))
4695                         set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4696                 else
4697                         clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4698                 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) &&
4699                     mddev_lock(mddev) == 0) {
4700                         flush_workqueue(md_misc_wq);
4701                         if (mddev->sync_thread) {
4702                                 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
4703                                 md_reap_sync_thread(mddev);
4704                         }
4705                         mddev_unlock(mddev);
4706                 }
4707         } else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4708                 return -EBUSY;
4709         else if (cmd_match(page, "resync"))
4710                 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4711         else if (cmd_match(page, "recover")) {
4712                 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4713                 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
4714         } else if (cmd_match(page, "reshape")) {
4715                 int err;
4716                 if (mddev->pers->start_reshape == NULL)
4717                         return -EINVAL;
4718                 err = mddev_lock(mddev);
4719                 if (!err) {
4720                         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4721                                 err =  -EBUSY;
4722                         else {
4723                                 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4724                                 err = mddev->pers->start_reshape(mddev);
4725                         }
4726                         mddev_unlock(mddev);
4727                 }
4728                 if (err)
4729                         return err;
4730                 sysfs_notify(&mddev->kobj, NULL, "degraded");
4731         } else {
4732                 if (cmd_match(page, "check"))
4733                         set_bit(MD_RECOVERY_CHECK, &mddev->recovery);
4734                 else if (!cmd_match(page, "repair"))
4735                         return -EINVAL;
4736                 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4737                 set_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
4738                 set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
4739         }
4740         if (mddev->ro == 2) {
4741                 /* A write to sync_action is enough to justify
4742                  * canceling read-auto mode
4743                  */
4744                 mddev->ro = 0;
4745                 md_wakeup_thread(mddev->sync_thread);
4746         }
4747         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4748         md_wakeup_thread(mddev->thread);
4749         sysfs_notify_dirent_safe(mddev->sysfs_action);
4750         return len;
4751 }
4752
4753 static struct md_sysfs_entry md_scan_mode =
4754 __ATTR_PREALLOC(sync_action, S_IRUGO|S_IWUSR, action_show, action_store);
4755
4756 static ssize_t
4757 last_sync_action_show(struct mddev *mddev, char *page)
4758 {
4759         return sprintf(page, "%s\n", mddev->last_sync_action);
4760 }
4761
4762 static struct md_sysfs_entry md_last_scan_mode = __ATTR_RO(last_sync_action);
4763
4764 static ssize_t
4765 mismatch_cnt_show(struct mddev *mddev, char *page)
4766 {
4767         return sprintf(page, "%llu\n",
4768                        (unsigned long long)
4769                        atomic64_read(&mddev->resync_mismatches));
4770 }
4771
4772 static struct md_sysfs_entry md_mismatches = __ATTR_RO(mismatch_cnt);
4773
4774 static ssize_t
4775 sync_min_show(struct mddev *mddev, char *page)
4776 {
4777         return sprintf(page, "%d (%s)\n", speed_min(mddev),
4778                        mddev->sync_speed_min ? "local": "system");
4779 }
4780
4781 static ssize_t
4782 sync_min_store(struct mddev *mddev, const char *buf, size_t len)
4783 {
4784         unsigned int min;
4785         int rv;
4786
4787         if (strncmp(buf, "system", 6)==0) {
4788                 min = 0;
4789         } else {
4790                 rv = kstrtouint(buf, 10, &min);
4791                 if (rv < 0)
4792                         return rv;
4793                 if (min == 0)
4794                         return -EINVAL;
4795         }
4796         mddev->sync_speed_min = min;
4797         return len;
4798 }
4799
4800 static struct md_sysfs_entry md_sync_min =
4801 __ATTR(sync_speed_min, S_IRUGO|S_IWUSR, sync_min_show, sync_min_store);
4802
4803 static ssize_t
4804 sync_max_show(struct mddev *mddev, char *page)
4805 {
4806         return sprintf(page, "%d (%s)\n", speed_max(mddev),
4807                        mddev->sync_speed_max ? "local": "system");
4808 }
4809
4810 static ssize_t
4811 sync_max_store(struct mddev *mddev, const char *buf, size_t len)
4812 {
4813         unsigned int max;
4814         int rv;
4815
4816         if (strncmp(buf, "system", 6)==0) {
4817                 max = 0;
4818         } else {
4819                 rv = kstrtouint(buf, 10, &max);
4820                 if (rv < 0)
4821                         return rv;
4822                 if (max == 0)
4823                         return -EINVAL;
4824         }
4825         mddev->sync_speed_max = max;
4826         return len;
4827 }
4828
4829 static struct md_sysfs_entry md_sync_max =
4830 __ATTR(sync_speed_max, S_IRUGO|S_IWUSR, sync_max_show, sync_max_store);
4831
4832 static ssize_t
4833 degraded_show(struct mddev *mddev, char *page)
4834 {
4835         return sprintf(page, "%d\n", mddev->degraded);
4836 }
4837 static struct md_sysfs_entry md_degraded = __ATTR_RO(degraded);
4838
4839 static ssize_t
4840 sync_force_parallel_show(struct mddev *mddev, char *page)
4841 {
4842         return sprintf(page, "%d\n", mddev->parallel_resync);
4843 }
4844
4845 static ssize_t
4846 sync_force_parallel_store(struct mddev *mddev, const char *buf, size_t len)
4847 {
4848         long n;
4849
4850         if (kstrtol(buf, 10, &n))
4851                 return -EINVAL;
4852
4853         if (n != 0 && n != 1)
4854                 return -EINVAL;
4855
4856         mddev->parallel_resync = n;
4857
4858         if (mddev->sync_thread)
4859                 wake_up(&resync_wait);
4860
4861         return len;
4862 }
4863
4864 /* force parallel resync, even with shared block devices */
4865 static struct md_sysfs_entry md_sync_force_parallel =
4866 __ATTR(sync_force_parallel, S_IRUGO|S_IWUSR,
4867        sync_force_parallel_show, sync_force_parallel_store);
4868
4869 static ssize_t
4870 sync_speed_show(struct mddev *mddev, char *page)
4871 {
4872         unsigned long resync, dt, db;
4873         if (mddev->curr_resync == 0)
4874                 return sprintf(page, "none\n");
4875         resync = mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active);
4876         dt = (jiffies - mddev->resync_mark) / HZ;
4877         if (!dt) dt++;
4878         db = resync - mddev->resync_mark_cnt;
4879         return sprintf(page, "%lu\n", db/dt/2); /* K/sec */
4880 }
4881
4882 static struct md_sysfs_entry md_sync_speed = __ATTR_RO(sync_speed);
4883
4884 static ssize_t
4885 sync_completed_show(struct mddev *mddev, char *page)
4886 {
4887         unsigned long long max_sectors, resync;
4888
4889         if (!test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4890                 return sprintf(page, "none\n");
4891
4892         if (mddev->curr_resync == 1 ||
4893             mddev->curr_resync == 2)
4894                 return sprintf(page, "delayed\n");
4895
4896         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ||
4897             test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
4898                 max_sectors = mddev->resync_max_sectors;
4899         else
4900                 max_sectors = mddev->dev_sectors;
4901
4902         resync = mddev->curr_resync_completed;
4903         return sprintf(page, "%llu / %llu\n", resync, max_sectors);
4904 }
4905
4906 static struct md_sysfs_entry md_sync_completed =
4907         __ATTR_PREALLOC(sync_completed, S_IRUGO, sync_completed_show, NULL);
4908
4909 static ssize_t
4910 min_sync_show(struct mddev *mddev, char *page)
4911 {
4912         return sprintf(page, "%llu\n",
4913                        (unsigned long long)mddev->resync_min);
4914 }
4915 static ssize_t
4916 min_sync_store(struct mddev *mddev, const char *buf, size_t len)
4917 {
4918         unsigned long long min;
4919         int err;
4920
4921         if (kstrtoull(buf, 10, &min))
4922                 return -EINVAL;
4923
4924         spin_lock(&mddev->lock);
4925         err = -EINVAL;
4926         if (min > mddev->resync_max)
4927                 goto out_unlock;
4928
4929         err = -EBUSY;
4930         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4931                 goto out_unlock;
4932
4933         /* Round down to multiple of 4K for safety */
4934         mddev->resync_min = round_down(min, 8);
4935         err = 0;
4936
4937 out_unlock:
4938         spin_unlock(&mddev->lock);
4939         return err ?: len;
4940 }
4941
4942 static struct md_sysfs_entry md_min_sync =
4943 __ATTR(sync_min, S_IRUGO|S_IWUSR, min_sync_show, min_sync_store);
4944
4945 static ssize_t
4946 max_sync_show(struct mddev *mddev, char *page)
4947 {
4948         if (mddev->resync_max == MaxSector)
4949                 return sprintf(page, "max\n");
4950         else
4951                 return sprintf(page, "%llu\n",
4952                                (unsigned long long)mddev->resync_max);
4953 }
4954 static ssize_t
4955 max_sync_store(struct mddev *mddev, const char *buf, size_t len)
4956 {
4957         int err;
4958         spin_lock(&mddev->lock);
4959         if (strncmp(buf, "max", 3) == 0)
4960                 mddev->resync_max = MaxSector;
4961         else {
4962                 unsigned long long max;
4963                 int chunk;
4964
4965                 err = -EINVAL;
4966                 if (kstrtoull(buf, 10, &max))
4967                         goto out_unlock;
4968                 if (max < mddev->resync_min)
4969                         goto out_unlock;
4970
4971                 err = -EBUSY;
4972                 if (max < mddev->resync_max &&
4973                     mddev->ro == 0 &&
4974                     test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4975                         goto out_unlock;
4976
4977                 /* Must be a multiple of chunk_size */
4978                 chunk = mddev->chunk_sectors;
4979                 if (chunk) {
4980                         sector_t temp = max;
4981
4982                         err = -EINVAL;
4983                         if (sector_div(temp, chunk))
4984                                 goto out_unlock;
4985                 }
4986                 mddev->resync_max = max;
4987         }
4988         wake_up(&mddev->recovery_wait);
4989         err = 0;
4990 out_unlock:
4991         spin_unlock(&mddev->lock);
4992         return err ?: len;
4993 }
4994
4995 static struct md_sysfs_entry md_max_sync =
4996 __ATTR(sync_max, S_IRUGO|S_IWUSR, max_sync_show, max_sync_store);
4997
4998 static ssize_t
4999 suspend_lo_show(struct mddev *mddev, char *page)
5000 {
5001         return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_lo);
5002 }
5003
5004 static ssize_t
5005 suspend_lo_store(struct mddev *mddev, const char *buf, size_t len)
5006 {
5007         unsigned long long new;
5008         int err;
5009
5010         err = kstrtoull(buf, 10, &new);
5011         if (err < 0)
5012                 return err;
5013         if (new != (sector_t)new)
5014                 return -EINVAL;
5015
5016         err = mddev_lock(mddev);
5017         if (err)
5018                 return err;
5019         err = -EINVAL;
5020         if (mddev->pers == NULL ||
5021             mddev->pers->quiesce == NULL)
5022                 goto unlock;
5023         mddev_suspend(mddev);
5024         mddev->suspend_lo = new;
5025         mddev_resume(mddev);
5026
5027         err = 0;
5028 unlock:
5029         mddev_unlock(mddev);
5030         return err ?: len;
5031 }
5032 static struct md_sysfs_entry md_suspend_lo =
5033 __ATTR(suspend_lo, S_IRUGO|S_IWUSR, suspend_lo_show, suspend_lo_store);
5034
5035 static ssize_t
5036 suspend_hi_show(struct mddev *mddev, char *page)
5037 {
5038         return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_hi);
5039 }
5040
5041 static ssize_t
5042 suspend_hi_store(struct mddev *mddev, const char *buf, size_t len)
5043 {
5044         unsigned long long new;
5045         int err;
5046
5047         err = kstrtoull(buf, 10, &new);
5048         if (err < 0)
5049                 return err;
5050         if (new != (sector_t)new)
5051                 return -EINVAL;
5052
5053         err = mddev_lock(mddev);
5054         if (err)
5055                 return err;
5056         err = -EINVAL;
5057         if (mddev->pers == NULL)
5058                 goto unlock;
5059
5060         mddev_suspend(mddev);
5061         mddev->suspend_hi = new;
5062         mddev_resume(mddev);
5063
5064         err = 0;
5065 unlock:
5066         mddev_unlock(mddev);
5067         return err ?: len;
5068 }
5069 static struct md_sysfs_entry md_suspend_hi =
5070 __ATTR(suspend_hi, S_IRUGO|S_IWUSR, suspend_hi_show, suspend_hi_store);
5071
5072 static ssize_t
5073 reshape_position_show(struct mddev *mddev, char *page)
5074 {
5075         if (mddev->reshape_position != MaxSector)
5076                 return sprintf(page, "%llu\n",
5077                                (unsigned long long)mddev->reshape_position);
5078         strcpy(page, "none\n");
5079         return 5;
5080 }
5081
5082 static ssize_t
5083 reshape_position_store(struct mddev *mddev, const char *buf, size_t len)
5084 {
5085         struct md_rdev *rdev;
5086         unsigned long long new;
5087         int err;
5088
5089         err = kstrtoull(buf, 10, &new);
5090         if (err < 0)
5091                 return err;
5092         if (new != (sector_t)new)
5093                 return -EINVAL;
5094         err = mddev_lock(mddev);
5095         if (err)
5096                 return err;
5097         err = -EBUSY;
5098         if (mddev->pers)
5099                 goto unlock;
5100         mddev->reshape_position = new;
5101         mddev->delta_disks = 0;
5102         mddev->reshape_backwards = 0;
5103         mddev->new_level = mddev->level;
5104         mddev->new_layout = mddev->layout;
5105         mddev->new_chunk_sectors = mddev->chunk_sectors;
5106         rdev_for_each(rdev, mddev)
5107                 rdev->new_data_offset = rdev->data_offset;
5108         err = 0;
5109 unlock:
5110         mddev_unlock(mddev);
5111         return err ?: len;
5112 }
5113
5114 static struct md_sysfs_entry md_reshape_position =
5115 __ATTR(reshape_position, S_IRUGO|S_IWUSR, reshape_position_show,
5116        reshape_position_store);
5117
5118 static ssize_t
5119 reshape_direction_show(struct mddev *mddev, char *page)
5120 {
5121         return sprintf(page, "%s\n",
5122                        mddev->reshape_backwards ? "backwards" : "forwards");
5123 }
5124
5125 static ssize_t
5126 reshape_direction_store(struct mddev *mddev, const char *buf, size_t len)
5127 {
5128         int backwards = 0;
5129         int err;
5130
5131         if (cmd_match(buf, "forwards"))
5132                 backwards = 0;
5133         else if (cmd_match(buf, "backwards"))
5134                 backwards = 1;
5135         else
5136                 return -EINVAL;
5137         if (mddev->reshape_backwards == backwards)
5138                 return len;
5139
5140         err = mddev_lock(mddev);
5141         if (err)
5142                 return err;
5143         /* check if we are allowed to change */
5144         if (mddev->delta_disks)
5145                 err = -EBUSY;
5146         else if (mddev->persistent &&
5147             mddev->major_version == 0)
5148                 err =  -EINVAL;
5149         else
5150                 mddev->reshape_backwards = backwards;
5151         mddev_unlock(mddev);
5152         return err ?: len;
5153 }
5154
5155 static struct md_sysfs_entry md_reshape_direction =
5156 __ATTR(reshape_direction, S_IRUGO|S_IWUSR, reshape_direction_show,
5157        reshape_direction_store);
5158
5159 static ssize_t
5160 array_size_show(struct mddev *mddev, char *page)
5161 {
5162         if (mddev->external_size)
5163                 return sprintf(page, "%llu\n",
5164                                (unsigned long long)mddev->array_sectors/2);
5165         else
5166                 return sprintf(page, "default\n");
5167 }
5168
5169 static ssize_t
5170 array_size_store(struct mddev *mddev, const char *buf, size_t len)
5171 {
5172         sector_t sectors;
5173         int err;
5174
5175         err = mddev_lock(mddev);
5176         if (err)
5177                 return err;
5178
5179         /* cluster raid doesn't support change array_sectors */
5180         if (mddev_is_clustered(mddev)) {
5181                 mddev_unlock(mddev);
5182                 return -EINVAL;
5183         }
5184
5185         if (strncmp(buf, "default", 7) == 0) {
5186                 if (mddev->pers)
5187                         sectors = mddev->pers->size(mddev, 0, 0);
5188                 else
5189                         sectors = mddev->array_sectors;
5190
5191                 mddev->external_size = 0;
5192         } else {
5193                 if (strict_blocks_to_sectors(buf, &sectors) < 0)
5194                         err = -EINVAL;
5195                 else if (mddev->pers && mddev->pers->size(mddev, 0, 0) < sectors)
5196                         err = -E2BIG;
5197                 else
5198                         mddev->external_size = 1;
5199         }
5200
5201         if (!err) {
5202                 mddev->array_sectors = sectors;
5203                 if (mddev->pers) {
5204                         set_capacity(mddev->gendisk, mddev->array_sectors);
5205                         revalidate_disk(mddev->gendisk);
5206                 }
5207         }
5208         mddev_unlock(mddev);
5209         return err ?: len;
5210 }
5211
5212 static struct md_sysfs_entry md_array_size =
5213 __ATTR(array_size, S_IRUGO|S_IWUSR, array_size_show,
5214        array_size_store);
5215
5216 static ssize_t
5217 consistency_policy_show(struct mddev *mddev, char *page)
5218 {
5219         int ret;
5220
5221         if (test_bit(MD_HAS_JOURNAL, &mddev->flags)) {
5222                 ret = sprintf(page, "journal\n");
5223         } else if (test_bit(MD_HAS_PPL, &mddev->flags)) {
5224                 ret = sprintf(page, "ppl\n");
5225         } else if (mddev->bitmap) {
5226                 ret = sprintf(page, "bitmap\n");
5227         } else if (mddev->pers) {
5228                 if (mddev->pers->sync_request)
5229                         ret = sprintf(page, "resync\n");
5230                 else
5231                         ret = sprintf(page, "none\n");
5232         } else {
5233                 ret = sprintf(page, "unknown\n");
5234         }
5235
5236         return ret;
5237 }
5238
5239 static ssize_t
5240 consistency_policy_store(struct mddev *mddev, const char *buf, size_t len)
5241 {
5242         int err = 0;
5243
5244         if (mddev->pers) {
5245                 if (mddev->pers->change_consistency_policy)
5246                         err = mddev->pers->change_consistency_policy(mddev, buf);
5247                 else
5248                         err = -EBUSY;
5249         } else if (mddev->external && strncmp(buf, "ppl", 3) == 0) {
5250                 set_bit(MD_HAS_PPL, &mddev->flags);
5251         } else {
5252                 err = -EINVAL;
5253         }
5254
5255         return err ? err : len;
5256 }
5257
5258 static struct md_sysfs_entry md_consistency_policy =
5259 __ATTR(consistency_policy, S_IRUGO | S_IWUSR, consistency_policy_show,
5260        consistency_policy_store);
5261
5262 static ssize_t fail_last_dev_show(struct mddev *mddev, char *page)
5263 {
5264         return sprintf(page, "%d\n", mddev->fail_last_dev);
5265 }
5266
5267 /*
5268  * Setting fail_last_dev to true to allow last device to be forcibly removed
5269  * from RAID1/RAID10.
5270  */
5271 static ssize_t
5272 fail_last_dev_store(struct mddev *mddev, const char *buf, size_t len)
5273 {
5274         int ret;
5275         bool value;
5276
5277         ret = kstrtobool(buf, &value);
5278         if (ret)
5279                 return ret;
5280
5281         if (value != mddev->fail_last_dev)
5282                 mddev->fail_last_dev = value;
5283
5284         return len;
5285 }
5286 static struct md_sysfs_entry md_fail_last_dev =
5287 __ATTR(fail_last_dev, S_IRUGO | S_IWUSR, fail_last_dev_show,
5288        fail_last_dev_store);
5289
5290 static struct attribute *md_default_attrs[] = {
5291         &md_level.attr,
5292         &md_layout.attr,
5293         &md_raid_disks.attr,
5294         &md_chunk_size.attr,
5295         &md_size.attr,
5296         &md_resync_start.attr,
5297         &md_metadata.attr,
5298         &md_new_device.attr,
5299         &md_safe_delay.attr,
5300         &md_array_state.attr,
5301         &md_reshape_position.attr,
5302         &md_reshape_direction.attr,
5303         &md_array_size.attr,
5304         &max_corr_read_errors.attr,
5305         &md_consistency_policy.attr,
5306         &md_fail_last_dev.attr,
5307         NULL,
5308 };
5309
5310 static struct attribute *md_redundancy_attrs[] = {
5311         &md_scan_mode.attr,
5312         &md_last_scan_mode.attr,
5313         &md_mismatches.attr,
5314         &md_sync_min.attr,
5315         &md_sync_max.attr,
5316         &md_sync_speed.attr,
5317         &md_sync_force_parallel.attr,
5318         &md_sync_completed.attr,
5319         &md_min_sync.attr,
5320         &md_max_sync.attr,
5321         &md_suspend_lo.attr,
5322         &md_suspend_hi.attr,
5323         &md_bitmap.attr,
5324         &md_degraded.attr,
5325         NULL,
5326 };
5327 static struct attribute_group md_redundancy_group = {
5328         .name = NULL,
5329         .attrs = md_redundancy_attrs,
5330 };
5331
5332 static ssize_t
5333 md_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
5334 {
5335         struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
5336         struct mddev *mddev = container_of(kobj, struct mddev, kobj);
5337         ssize_t rv;
5338
5339         if (!entry->show)
5340                 return -EIO;
5341         spin_lock(&all_mddevs_lock);
5342         if (list_empty(&mddev->all_mddevs)) {
5343                 spin_unlock(&all_mddevs_lock);
5344                 return -EBUSY;
5345         }
5346         mddev_get(mddev);
5347         spin_unlock(&all_mddevs_lock);
5348
5349         rv = entry->show(mddev, page);
5350         mddev_put(mddev);
5351         return rv;
5352 }
5353
5354 static ssize_t
5355 md_attr_store(struct kobject *kobj, struct attribute *attr,
5356               const char *page, size_t length)
5357 {
5358         struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
5359         struct mddev *mddev = container_of(kobj, struct mddev, kobj);
5360         ssize_t rv;
5361
5362         if (!entry->store)
5363                 return -EIO;
5364         if (!capable(CAP_SYS_ADMIN))
5365                 return -EACCES;
5366         spin_lock(&all_mddevs_lock);
5367         if (list_empty(&mddev->all_mddevs)) {
5368                 spin_unlock(&all_mddevs_lock);
5369                 return -EBUSY;
5370         }
5371         mddev_get(mddev);
5372         spin_unlock(&all_mddevs_lock);
5373         rv = entry->store(mddev, page, length);
5374         mddev_put(mddev);
5375         return rv;
5376 }
5377
5378 static void md_free(struct kobject *ko)
5379 {
5380         struct mddev *mddev = container_of(ko, struct mddev, kobj);
5381
5382         if (mddev->sysfs_state)
5383                 sysfs_put(mddev->sysfs_state);
5384
5385         if (mddev->gendisk)
5386                 del_gendisk(mddev->gendisk);
5387         if (mddev->queue)
5388                 blk_cleanup_queue(mddev->queue);
5389         if (mddev->gendisk)
5390                 put_disk(mddev->gendisk);
5391         percpu_ref_exit(&mddev->writes_pending);
5392
5393         bioset_exit(&mddev->bio_set);
5394         bioset_exit(&mddev->sync_set);
5395         kfree(mddev);
5396 }
5397
5398 static const struct sysfs_ops md_sysfs_ops = {
5399         .show   = md_attr_show,
5400         .store  = md_attr_store,
5401 };
5402 static struct kobj_type md_ktype = {
5403         .release        = md_free,
5404         .sysfs_ops      = &md_sysfs_ops,
5405         .default_attrs  = md_default_attrs,
5406 };
5407
5408 int mdp_major = 0;
5409
5410 static void mddev_delayed_delete(struct work_struct *ws)
5411 {
5412         struct mddev *mddev = container_of(ws, struct mddev, del_work);
5413
5414         sysfs_remove_group(&mddev->kobj, &md_bitmap_group);
5415         kobject_del(&mddev->kobj);
5416         kobject_put(&mddev->kobj);
5417 }
5418
5419 static void no_op(struct percpu_ref *r) {}
5420
5421 int mddev_init_writes_pending(struct mddev *mddev)
5422 {
5423         if (mddev->writes_pending.percpu_count_ptr)
5424                 return 0;
5425         if (percpu_ref_init(&mddev->writes_pending, no_op,
5426                             PERCPU_REF_ALLOW_REINIT, GFP_KERNEL) < 0)
5427                 return -ENOMEM;
5428         /* We want to start with the refcount at zero */
5429         percpu_ref_put(&mddev->writes_pending);
5430         return 0;
5431 }
5432 EXPORT_SYMBOL_GPL(mddev_init_writes_pending);
5433
5434 static int md_alloc(dev_t dev, char *name)
5435 {
5436         /*
5437          * If dev is zero, name is the name of a device to allocate with
5438          * an arbitrary minor number.  It will be "md_???"
5439          * If dev is non-zero it must be a device number with a MAJOR of
5440          * MD_MAJOR or mdp_major.  In this case, if "name" is NULL, then
5441          * the device is being created by opening a node in /dev.
5442          * If "name" is not NULL, the device is being created by
5443          * writing to /sys/module/md_mod/parameters/new_array.
5444          */
5445         static DEFINE_MUTEX(disks_mutex);
5446         struct mddev *mddev = mddev_find(dev);
5447         struct gendisk *disk;
5448         int partitioned;
5449         int shift;
5450         int unit;
5451         int error;
5452
5453         if (!mddev)
5454                 return -ENODEV;
5455
5456         partitioned = (MAJOR(mddev->unit) != MD_MAJOR);
5457         shift = partitioned ? MdpMinorShift : 0;
5458         unit = MINOR(mddev->unit) >> shift;
5459
5460         /* wait for any previous instance of this device to be
5461          * completely removed (mddev_delayed_delete).
5462          */
5463         flush_workqueue(md_misc_wq);
5464
5465         mutex_lock(&disks_mutex);
5466         error = -EEXIST;
5467         if (mddev->gendisk)
5468                 goto abort;
5469
5470         if (name && !dev) {
5471                 /* Need to ensure that 'name' is not a duplicate.
5472                  */
5473                 struct mddev *mddev2;
5474                 spin_lock(&all_mddevs_lock);
5475
5476                 list_for_each_entry(mddev2, &all_mddevs, all_mddevs)
5477                         if (mddev2->gendisk &&
5478                             strcmp(mddev2->gendisk->disk_name, name) == 0) {
5479                                 spin_unlock(&all_mddevs_lock);
5480                                 goto abort;
5481                         }
5482                 spin_unlock(&all_mddevs_lock);
5483         }
5484         if (name && dev)
5485                 /*
5486                  * Creating /dev/mdNNN via "newarray", so adjust hold_active.
5487                  */
5488                 mddev->hold_active = UNTIL_STOP;
5489
5490         error = -ENOMEM;
5491         mddev->queue = blk_alloc_queue(GFP_KERNEL);
5492         if (!mddev->queue)
5493                 goto abort;
5494         mddev->queue->queuedata = mddev;
5495
5496         blk_queue_make_request(mddev->queue, md_make_request);
5497         blk_set_stacking_limits(&mddev->queue->limits);
5498
5499         disk = alloc_disk(1 << shift);
5500         if (!disk) {
5501                 blk_cleanup_queue(mddev->queue);
5502                 mddev->queue = NULL;
5503                 goto abort;
5504         }
5505         disk->major = MAJOR(mddev->unit);
5506         disk->first_minor = unit << shift;
5507         if (name)
5508                 strcpy(disk->disk_name, name);
5509         else if (partitioned)
5510                 sprintf(disk->disk_name, "md_d%d", unit);
5511         else
5512                 sprintf(disk->disk_name, "md%d", unit);
5513         disk->fops = &md_fops;
5514         disk->private_data = mddev;
5515         disk->queue = mddev->queue;
5516         blk_queue_write_cache(mddev->queue, true, true);
5517         /* Allow extended partitions.  This makes the
5518          * 'mdp' device redundant, but we can't really
5519          * remove it now.
5520          */
5521         disk->flags |= GENHD_FL_EXT_DEVT;
5522         mddev->gendisk = disk;
5523         /* As soon as we call add_disk(), another thread could get
5524          * through to md_open, so make sure it doesn't get too far
5525          */
5526         mutex_lock(&mddev->open_mutex);
5527         add_disk(disk);
5528
5529         error = kobject_add(&mddev->kobj, &disk_to_dev(disk)->kobj, "%s", "md");
5530         if (error) {
5531                 /* This isn't possible, but as kobject_init_and_add is marked
5532                  * __must_check, we must do something with the result
5533                  */
5534                 pr_debug("md: cannot register %s/md - name in use\n",
5535                          disk->disk_name);
5536                 error = 0;
5537         }
5538         if (mddev->kobj.sd &&
5539             sysfs_create_group(&mddev->kobj, &md_bitmap_group))
5540                 pr_debug("pointless warning\n");
5541         mutex_unlock(&mddev->open_mutex);
5542  abort:
5543         mutex_unlock(&disks_mutex);
5544         if (!error && mddev->kobj.sd) {
5545                 kobject_uevent(&mddev->kobj, KOBJ_ADD);
5546                 mddev->sysfs_state = sysfs_get_dirent_safe(mddev->kobj.sd, "array_state");
5547         }
5548         mddev_put(mddev);
5549         return error;
5550 }
5551
5552 static struct kobject *md_probe(dev_t dev, int *part, void *data)
5553 {
5554         if (create_on_open)
5555                 md_alloc(dev, NULL);
5556         return NULL;
5557 }
5558
5559 static int add_named_array(const char *val, const struct kernel_param *kp)
5560 {
5561         /*
5562          * val must be "md_*" or "mdNNN".
5563          * For "md_*" we allocate an array with a large free minor number, and
5564          * set the name to val.  val must not already be an active name.
5565          * For "mdNNN" we allocate an array with the minor number NNN
5566          * which must not already be in use.
5567          */
5568         int len = strlen(val);
5569         char buf[DISK_NAME_LEN];
5570         unsigned long devnum;
5571
5572         while (len && val[len-1] == '\n')
5573                 len--;
5574         if (len >= DISK_NAME_LEN)
5575                 return -E2BIG;
5576         strlcpy(buf, val, len+1);
5577         if (strncmp(buf, "md_", 3) == 0)
5578                 return md_alloc(0, buf);
5579         if (strncmp(buf, "md", 2) == 0 &&
5580             isdigit(buf[2]) &&
5581             kstrtoul(buf+2, 10, &devnum) == 0 &&
5582             devnum <= MINORMASK)
5583                 return md_alloc(MKDEV(MD_MAJOR, devnum), NULL);
5584
5585         return -EINVAL;
5586 }
5587
5588 static void md_safemode_timeout(struct timer_list *t)
5589 {
5590         struct mddev *mddev = from_timer(mddev, t, safemode_timer);
5591
5592         mddev->safemode = 1;
5593         if (mddev->external)
5594                 sysfs_notify_dirent_safe(mddev->sysfs_state);
5595
5596         md_wakeup_thread(mddev->thread);
5597 }
5598
5599 static int start_dirty_degraded;
5600
5601 int md_run(struct mddev *mddev)
5602 {
5603         int err;
5604         struct md_rdev *rdev;
5605         struct md_personality *pers;
5606
5607         if (list_empty(&mddev->disks))
5608                 /* cannot run an array with no devices.. */
5609                 return -EINVAL;
5610
5611         if (mddev->pers)
5612                 return -EBUSY;
5613         /* Cannot run until previous stop completes properly */
5614         if (mddev->sysfs_active)
5615                 return -EBUSY;
5616
5617         /*
5618          * Analyze all RAID superblock(s)
5619          */
5620         if (!mddev->raid_disks) {
5621                 if (!mddev->persistent)
5622                         return -EINVAL;
5623                 err = analyze_sbs(mddev);
5624                 if (err)
5625                         return -EINVAL;
5626         }
5627
5628         if (mddev->level != LEVEL_NONE)
5629                 request_module("md-level-%d", mddev->level);
5630         else if (mddev->clevel[0])
5631                 request_module("md-%s", mddev->clevel);
5632
5633         /*
5634          * Drop all container device buffers, from now on
5635          * the only valid external interface is through the md
5636          * device.
5637          */
5638         mddev->has_superblocks = false;
5639         rdev_for_each(rdev, mddev) {
5640                 if (test_bit(Faulty, &rdev->flags))
5641                         continue;
5642                 sync_blockdev(rdev->bdev);
5643                 invalidate_bdev(rdev->bdev);
5644                 if (mddev->ro != 1 &&
5645                     (bdev_read_only(rdev->bdev) ||
5646                      bdev_read_only(rdev->meta_bdev))) {
5647                         mddev->ro = 1;
5648                         if (mddev->gendisk)
5649                                 set_disk_ro(mddev->gendisk, 1);
5650                 }
5651
5652                 if (rdev->sb_page)
5653                         mddev->has_superblocks = true;
5654
5655                 /* perform some consistency tests on the device.
5656                  * We don't want the data to overlap the metadata,
5657                  * Internal Bitmap issues have been handled elsewhere.
5658                  */
5659                 if (rdev->meta_bdev) {
5660                         /* Nothing to check */;
5661                 } else if (rdev->data_offset < rdev->sb_start) {
5662                         if (mddev->dev_sectors &&
5663                             rdev->data_offset + mddev->dev_sectors
5664                             > rdev->sb_start) {
5665                                 pr_warn("md: %s: data overlaps metadata\n",
5666                                         mdname(mddev));
5667                                 return -EINVAL;
5668                         }
5669                 } else {
5670                         if (rdev->sb_start + rdev->sb_size/512
5671                             > rdev->data_offset) {
5672                                 pr_warn("md: %s: metadata overlaps data\n",
5673                                         mdname(mddev));
5674                                 return -EINVAL;
5675                         }
5676                 }
5677                 sysfs_notify_dirent_safe(rdev->sysfs_state);
5678         }
5679
5680         if (!bioset_initialized(&mddev->bio_set)) {
5681                 err = bioset_init(&mddev->bio_set, BIO_POOL_SIZE, 0, BIOSET_NEED_BVECS);
5682                 if (err)
5683                         return err;
5684         }
5685         if (!bioset_initialized(&mddev->sync_set)) {
5686                 err = bioset_init(&mddev->sync_set, BIO_POOL_SIZE, 0, BIOSET_NEED_BVECS);
5687                 if (err)
5688                         return err;
5689         }
5690
5691         spin_lock(&pers_lock);
5692         pers = find_pers(mddev->level, mddev->clevel);
5693         if (!pers || !try_module_get(pers->owner)) {
5694                 spin_unlock(&pers_lock);
5695                 if (mddev->level != LEVEL_NONE)
5696                         pr_warn("md: personality for level %d is not loaded!\n",
5697                                 mddev->level);
5698                 else
5699                         pr_warn("md: personality for level %s is not loaded!\n",
5700                                 mddev->clevel);
5701                 err = -EINVAL;
5702                 goto abort;
5703         }
5704         spin_unlock(&pers_lock);
5705         if (mddev->level != pers->level) {
5706                 mddev->level = pers->level;
5707                 mddev->new_level = pers->level;
5708         }
5709         strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
5710
5711         if (mddev->reshape_position != MaxSector &&
5712             pers->start_reshape == NULL) {
5713                 /* This personality cannot handle reshaping... */
5714                 module_put(pers->owner);
5715                 err = -EINVAL;
5716                 goto abort;
5717         }
5718
5719         if (pers->sync_request) {
5720                 /* Warn if this is a potentially silly
5721                  * configuration.
5722                  */
5723                 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
5724                 struct md_rdev *rdev2;
5725                 int warned = 0;
5726
5727                 rdev_for_each(rdev, mddev)
5728                         rdev_for_each(rdev2, mddev) {
5729                                 if (rdev < rdev2 &&
5730                                     rdev->bdev->bd_contains ==
5731                                     rdev2->bdev->bd_contains) {
5732                                         pr_warn("%s: WARNING: %s appears to be on the same physical disk as %s.\n",
5733                                                 mdname(mddev),
5734                                                 bdevname(rdev->bdev,b),
5735                                                 bdevname(rdev2->bdev,b2));
5736                                         warned = 1;
5737                                 }
5738                         }
5739
5740                 if (warned)
5741                         pr_warn("True protection against single-disk failure might be compromised.\n");
5742         }
5743
5744         mddev->recovery = 0;
5745         /* may be over-ridden by personality */
5746         mddev->resync_max_sectors = mddev->dev_sectors;
5747
5748         mddev->ok_start_degraded = start_dirty_degraded;
5749
5750         if (start_readonly && mddev->ro == 0)
5751                 mddev->ro = 2; /* read-only, but switch on first write */
5752
5753         err = pers->run(mddev);
5754         if (err)
5755                 pr_warn("md: pers->run() failed ...\n");
5756         else if (pers->size(mddev, 0, 0) < mddev->array_sectors) {
5757                 WARN_ONCE(!mddev->external_size,
5758                           "%s: default size too small, but 'external_size' not in effect?\n",
5759                           __func__);
5760                 pr_warn("md: invalid array_size %llu > default size %llu\n",
5761                         (unsigned long long)mddev->array_sectors / 2,
5762                         (unsigned long long)pers->size(mddev, 0, 0) / 2);
5763                 err = -EINVAL;
5764         }
5765         if (err == 0 && pers->sync_request &&
5766             (mddev->bitmap_info.file || mddev->bitmap_info.offset)) {
5767                 struct bitmap *bitmap;
5768
5769                 bitmap = md_bitmap_create(mddev, -1);
5770                 if (IS_ERR(bitmap)) {
5771                         err = PTR_ERR(bitmap);
5772                         pr_warn("%s: failed to create bitmap (%d)\n",
5773                                 mdname(mddev), err);
5774                 } else
5775                         mddev->bitmap = bitmap;
5776
5777         }
5778         if (err)
5779                 goto bitmap_abort;
5780
5781         if (mddev->bitmap_info.max_write_behind > 0) {
5782                 bool creat_pool = false;
5783
5784                 rdev_for_each(rdev, mddev) {
5785                         if (test_bit(WriteMostly, &rdev->flags) &&
5786                             rdev_init_wb(rdev))
5787                                 creat_pool = true;
5788                 }
5789                 if (creat_pool && mddev->wb_info_pool == NULL) {
5790                         mddev->wb_info_pool =
5791                                 mempool_create_kmalloc_pool(NR_WB_INFOS,
5792                                                     sizeof(struct wb_info));
5793                         if (!mddev->wb_info_pool) {
5794                                 err = -ENOMEM;
5795                                 goto bitmap_abort;
5796                         }
5797                 }
5798         }
5799
5800         if (mddev->queue) {
5801                 bool nonrot = true;
5802
5803                 rdev_for_each(rdev, mddev) {
5804                         if (rdev->raid_disk >= 0 &&
5805                             !blk_queue_nonrot(bdev_get_queue(rdev->bdev))) {
5806                                 nonrot = false;
5807                                 break;
5808                         }
5809                 }
5810                 if (mddev->degraded)
5811                         nonrot = false;
5812                 if (nonrot)
5813                         blk_queue_flag_set(QUEUE_FLAG_NONROT, mddev->queue);
5814                 else
5815                         blk_queue_flag_clear(QUEUE_FLAG_NONROT, mddev->queue);
5816                 mddev->queue->backing_dev_info->congested_data = mddev;
5817                 mddev->queue->backing_dev_info->congested_fn = md_congested;
5818         }
5819         if (pers->sync_request) {
5820                 if (mddev->kobj.sd &&
5821                     sysfs_create_group(&mddev->kobj, &md_redundancy_group))
5822                         pr_warn("md: cannot register extra attributes for %s\n",
5823                                 mdname(mddev));
5824                 mddev->sysfs_action = sysfs_get_dirent_safe(mddev->kobj.sd, "sync_action");
5825         } else if (mddev->ro == 2) /* auto-readonly not meaningful */
5826                 mddev->ro = 0;
5827
5828         atomic_set(&mddev->max_corr_read_errors,
5829                    MD_DEFAULT_MAX_CORRECTED_READ_ERRORS);
5830         mddev->safemode = 0;
5831         if (mddev_is_clustered(mddev))
5832                 mddev->safemode_delay = 0;
5833         else
5834                 mddev->safemode_delay = (200 * HZ)/1000 +1; /* 200 msec delay */
5835         mddev->in_sync = 1;
5836         smp_wmb();
5837         spin_lock(&mddev->lock);
5838         mddev->pers = pers;
5839         spin_unlock(&mddev->lock);
5840         rdev_for_each(rdev, mddev)
5841                 if (rdev->raid_disk >= 0)
5842                         sysfs_link_rdev(mddev, rdev); /* failure here is OK */
5843
5844         if (mddev->degraded && !mddev->ro)
5845                 /* This ensures that recovering status is reported immediately
5846                  * via sysfs - until a lack of spares is confirmed.
5847                  */
5848                 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
5849         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5850
5851         if (mddev->sb_flags)
5852                 md_update_sb(mddev, 0);
5853
5854         md_new_event(mddev);
5855         return 0;
5856
5857 bitmap_abort:
5858         mddev_detach(mddev);
5859         if (mddev->private)
5860                 pers->free(mddev, mddev->private);
5861         mddev->private = NULL;
5862         module_put(pers->owner);
5863         md_bitmap_destroy(mddev);
5864 abort:
5865         bioset_exit(&mddev->bio_set);
5866         bioset_exit(&mddev->sync_set);
5867         return err;
5868 }
5869 EXPORT_SYMBOL_GPL(md_run);
5870
5871 static int do_md_run(struct mddev *mddev)
5872 {
5873         int err;
5874
5875         set_bit(MD_NOT_READY, &mddev->flags);
5876         err = md_run(mddev);
5877         if (err)
5878                 goto out;
5879         err = md_bitmap_load(mddev);
5880         if (err) {
5881                 md_bitmap_destroy(mddev);
5882                 goto out;
5883         }
5884
5885         if (mddev_is_clustered(mddev))
5886                 md_allow_write(mddev);
5887
5888         /* run start up tasks that require md_thread */
5889         md_start(mddev);
5890
5891         md_wakeup_thread(mddev->thread);
5892         md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
5893
5894         set_capacity(mddev->gendisk, mddev->array_sectors);
5895         revalidate_disk(mddev->gendisk);
5896         clear_bit(MD_NOT_READY, &mddev->flags);
5897         mddev->changed = 1;
5898         kobject_uevent(&disk_to_dev(mddev->gendisk)->kobj, KOBJ_CHANGE);
5899         sysfs_notify_dirent_safe(mddev->sysfs_state);
5900         sysfs_notify_dirent_safe(mddev->sysfs_action);
5901         sysfs_notify(&mddev->kobj, NULL, "degraded");
5902 out:
5903         clear_bit(MD_NOT_READY, &mddev->flags);
5904         return err;
5905 }
5906
5907 int md_start(struct mddev *mddev)
5908 {
5909         int ret = 0;
5910
5911         if (mddev->pers->start) {
5912                 set_bit(MD_RECOVERY_WAIT, &mddev->recovery);
5913                 md_wakeup_thread(mddev->thread);
5914                 ret = mddev->pers->start(mddev);
5915                 clear_bit(MD_RECOVERY_WAIT, &mddev->recovery);
5916                 md_wakeup_thread(mddev->sync_thread);
5917         }
5918         return ret;
5919 }
5920 EXPORT_SYMBOL_GPL(md_start);
5921
5922 static int restart_array(struct mddev *mddev)
5923 {
5924         struct gendisk *disk = mddev->gendisk;
5925         struct md_rdev *rdev;
5926         bool has_journal = false;
5927         bool has_readonly = false;
5928
5929         /* Complain if it has no devices */
5930         if (list_empty(&mddev->disks))
5931                 return -ENXIO;
5932         if (!mddev->pers)
5933                 return -EINVAL;
5934         if (!mddev->ro)
5935                 return -EBUSY;
5936
5937         rcu_read_lock();
5938         rdev_for_each_rcu(rdev, mddev) {
5939                 if (test_bit(Journal, &rdev->flags) &&
5940                     !test_bit(Faulty, &rdev->flags))
5941                         has_journal = true;
5942                 if (bdev_read_only(rdev->bdev))
5943                         has_readonly = true;
5944         }
5945         rcu_read_unlock();
5946         if (test_bit(MD_HAS_JOURNAL, &mddev->flags) && !has_journal)
5947                 /* Don't restart rw with journal missing/faulty */
5948                         return -EINVAL;
5949         if (has_readonly)
5950                 return -EROFS;
5951
5952         mddev->safemode = 0;
5953         mddev->ro = 0;
5954         set_disk_ro(disk, 0);
5955         pr_debug("md: %s switched to read-write mode.\n", mdname(mddev));
5956         /* Kick recovery or resync if necessary */
5957         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5958         md_wakeup_thread(mddev->thread);
5959         md_wakeup_thread(mddev->sync_thread);
5960         sysfs_notify_dirent_safe(mddev->sysfs_state);
5961         return 0;
5962 }
5963
5964 static void md_clean(struct mddev *mddev)
5965 {
5966         mddev->array_sectors = 0;
5967         mddev->external_size = 0;
5968         mddev->dev_sectors = 0;
5969         mddev->raid_disks = 0;
5970         mddev->recovery_cp = 0;
5971         mddev->resync_min = 0;
5972         mddev->resync_max = MaxSector;
5973         mddev->reshape_position = MaxSector;
5974         mddev->external = 0;
5975         mddev->persistent = 0;
5976         mddev->level = LEVEL_NONE;
5977         mddev->clevel[0] = 0;
5978         mddev->flags = 0;
5979         mddev->sb_flags = 0;
5980         mddev->ro = 0;
5981         mddev->metadata_type[0] = 0;
5982         mddev->chunk_sectors = 0;
5983         mddev->ctime = mddev->utime = 0;
5984         mddev->layout = 0;
5985         mddev->max_disks = 0;
5986         mddev->events = 0;
5987         mddev->can_decrease_events = 0;
5988         mddev->delta_disks = 0;
5989         mddev->reshape_backwards = 0;
5990         mddev->new_level = LEVEL_NONE;
5991         mddev->new_layout = 0;
5992         mddev->new_chunk_sectors = 0;
5993         mddev->curr_resync = 0;
5994         atomic64_set(&mddev->resync_mismatches, 0);
5995         mddev->suspend_lo = mddev->suspend_hi = 0;
5996         mddev->sync_speed_min = mddev->sync_speed_max = 0;
5997         mddev->recovery = 0;
5998         mddev->in_sync = 0;
5999         mddev->changed = 0;
6000         mddev->degraded = 0;
6001         mddev->safemode = 0;
6002         mddev->private = NULL;
6003         mddev->cluster_info = NULL;
6004         mddev->bitmap_info.offset = 0;
6005         mddev->bitmap_info.default_offset = 0;
6006         mddev->bitmap_info.default_space = 0;
6007         mddev->bitmap_info.chunksize = 0;
6008         mddev->bitmap_info.daemon_sleep = 0;
6009         mddev->bitmap_info.max_write_behind = 0;
6010         mddev->bitmap_info.nodes = 0;
6011 }
6012
6013 static void __md_stop_writes(struct mddev *mddev)
6014 {
6015         set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
6016         flush_workqueue(md_misc_wq);
6017         if (mddev->sync_thread) {
6018                 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
6019                 md_reap_sync_thread(mddev);
6020         }
6021
6022         del_timer_sync(&mddev->safemode_timer);
6023
6024         if (mddev->pers && mddev->pers->quiesce) {
6025                 mddev->pers->quiesce(mddev, 1);
6026                 mddev->pers->quiesce(mddev, 0);
6027         }
6028         md_bitmap_flush(mddev);
6029
6030         if (mddev->ro == 0 &&
6031             ((!mddev->in_sync && !mddev_is_clustered(mddev)) ||
6032              mddev->sb_flags)) {
6033                 /* mark array as shutdown cleanly */
6034                 if (!mddev_is_clustered(mddev))
6035                         mddev->in_sync = 1;
6036                 md_update_sb(mddev, 1);
6037         }
6038         mempool_destroy(mddev->wb_info_pool);
6039         mddev->wb_info_pool = NULL;
6040 }
6041
6042 void md_stop_writes(struct mddev *mddev)
6043 {
6044         mddev_lock_nointr(mddev);
6045         __md_stop_writes(mddev);
6046         mddev_unlock(mddev);
6047 }
6048 EXPORT_SYMBOL_GPL(md_stop_writes);
6049
6050 static void mddev_detach(struct mddev *mddev)
6051 {
6052         md_bitmap_wait_behind_writes(mddev);
6053         if (mddev->pers && mddev->pers->quiesce) {
6054                 mddev->pers->quiesce(mddev, 1);
6055                 mddev->pers->quiesce(mddev, 0);
6056         }
6057         md_unregister_thread(&mddev->thread);
6058         if (mddev->queue)
6059                 blk_sync_queue(mddev->queue); /* the unplug fn references 'conf'*/
6060 }
6061
6062 static void __md_stop(struct mddev *mddev)
6063 {
6064         struct md_personality *pers = mddev->pers;
6065         md_bitmap_destroy(mddev);
6066         mddev_detach(mddev);
6067         /* Ensure ->event_work is done */
6068         flush_workqueue(md_misc_wq);
6069         spin_lock(&mddev->lock);
6070         mddev->pers = NULL;
6071         spin_unlock(&mddev->lock);
6072         pers->free(mddev, mddev->private);
6073         mddev->private = NULL;
6074         if (pers->sync_request && mddev->to_remove == NULL)
6075                 mddev->to_remove = &md_redundancy_group;
6076         module_put(pers->owner);
6077         clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
6078 }
6079
6080 void md_stop(struct mddev *mddev)
6081 {
6082         /* stop the array and free an attached data structures.
6083          * This is called from dm-raid
6084          */
6085         __md_stop(mddev);
6086         bioset_exit(&mddev->bio_set);
6087         bioset_exit(&mddev->sync_set);
6088 }
6089
6090 EXPORT_SYMBOL_GPL(md_stop);
6091
6092 static int md_set_readonly(struct mddev *mddev, struct block_device *bdev)
6093 {
6094         int err = 0;
6095         int did_freeze = 0;
6096
6097         if (!test_bit(MD_RECOVERY_FROZEN, &mddev->recovery)) {
6098                 did_freeze = 1;
6099                 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
6100                 md_wakeup_thread(mddev->thread);
6101         }
6102         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
6103                 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
6104         if (mddev->sync_thread)
6105                 /* Thread might be blocked waiting for metadata update
6106                  * which will now never happen */
6107                 wake_up_process(mddev->sync_thread->tsk);
6108
6109         if (mddev->external && test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags))
6110                 return -EBUSY;
6111         mddev_unlock(mddev);
6112         wait_event(resync_wait, !test_bit(MD_RECOVERY_RUNNING,
6113                                           &mddev->recovery));
6114         wait_event(mddev->sb_wait,
6115                    !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags));
6116         mddev_lock_nointr(mddev);
6117
6118         mutex_lock(&mddev->open_mutex);
6119         if ((mddev->pers && atomic_read(&mddev->openers) > !!bdev) ||
6120             mddev->sync_thread ||
6121             test_bit(MD_RECOVERY_RUNNING, &mddev->recovery)) {
6122                 pr_warn("md: %s still in use.\n",mdname(mddev));
6123                 if (did_freeze) {
6124                         clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
6125                         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6126                         md_wakeup_thread(mddev->thread);
6127                 }
6128                 err = -EBUSY;
6129                 goto out;
6130         }
6131         if (mddev->pers) {
6132                 __md_stop_writes(mddev);
6133
6134                 err  = -ENXIO;
6135                 if (mddev->ro==1)
6136                         goto out;
6137                 mddev->ro = 1;
6138                 set_disk_ro(mddev->gendisk, 1);
6139                 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
6140                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6141                 md_wakeup_thread(mddev->thread);
6142                 sysfs_notify_dirent_safe(mddev->sysfs_state);
6143                 err = 0;
6144         }
6145 out:
6146         mutex_unlock(&mddev->open_mutex);
6147         return err;
6148 }
6149
6150 /* mode:
6151  *   0 - completely stop and dis-assemble array
6152  *   2 - stop but do not disassemble array
6153  */
6154 static int do_md_stop(struct mddev *mddev, int mode,
6155                       struct block_device *bdev)
6156 {
6157         struct gendisk *disk = mddev->gendisk;
6158         struct md_rdev *rdev;
6159         int did_freeze = 0;
6160
6161         if (!test_bit(MD_RECOVERY_FROZEN, &mddev->recovery)) {
6162                 did_freeze = 1;
6163                 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
6164                 md_wakeup_thread(mddev->thread);
6165         }
6166         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
6167                 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
6168         if (mddev->sync_thread)
6169                 /* Thread might be blocked waiting for metadata update
6170                  * which will now never happen */
6171                 wake_up_process(mddev->sync_thread->tsk);
6172
6173         mddev_unlock(mddev);
6174         wait_event(resync_wait, (mddev->sync_thread == NULL &&
6175                                  !test_bit(MD_RECOVERY_RUNNING,
6176                                            &mddev->recovery)));
6177         mddev_lock_nointr(mddev);
6178
6179         mutex_lock(&mddev->open_mutex);
6180         if ((mddev->pers && atomic_read(&mddev->openers) > !!bdev) ||
6181             mddev->sysfs_active ||
6182             mddev->sync_thread ||
6183             test_bit(MD_RECOVERY_RUNNING, &mddev->recovery)) {
6184                 pr_warn("md: %s still in use.\n",mdname(mddev));
6185                 mutex_unlock(&mddev->open_mutex);
6186                 if (did_freeze) {
6187                         clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
6188                         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6189                         md_wakeup_thread(mddev->thread);
6190                 }
6191                 return -EBUSY;
6192         }
6193         if (mddev->pers) {
6194                 if (mddev->ro)
6195                         set_disk_ro(disk, 0);
6196
6197                 __md_stop_writes(mddev);
6198                 __md_stop(mddev);
6199                 mddev->queue->backing_dev_info->congested_fn = NULL;
6200
6201                 /* tell userspace to handle 'inactive' */
6202                 sysfs_notify_dirent_safe(mddev->sysfs_state);
6203
6204                 rdev_for_each(rdev, mddev)
6205                         if (rdev->raid_disk >= 0)
6206                                 sysfs_unlink_rdev(mddev, rdev);
6207
6208                 set_capacity(disk, 0);
6209                 mutex_unlock(&mddev->open_mutex);
6210                 mddev->changed = 1;
6211                 revalidate_disk(disk);
6212
6213                 if (mddev->ro)
6214                         mddev->ro = 0;
6215         } else
6216                 mutex_unlock(&mddev->open_mutex);
6217         /*
6218          * Free resources if final stop
6219          */
6220         if (mode == 0) {
6221                 pr_info("md: %s stopped.\n", mdname(mddev));
6222
6223                 if (mddev->bitmap_info.file) {
6224                         struct file *f = mddev->bitmap_info.file;
6225                         spin_lock(&mddev->lock);
6226                         mddev->bitmap_info.file = NULL;
6227                         spin_unlock(&mddev->lock);
6228                         fput(f);
6229                 }
6230                 mddev->bitmap_info.offset = 0;
6231
6232                 export_array(mddev);
6233
6234                 md_clean(mddev);
6235                 if (mddev->hold_active == UNTIL_STOP)
6236                         mddev->hold_active = 0;
6237         }
6238         md_new_event(mddev);
6239         sysfs_notify_dirent_safe(mddev->sysfs_state);
6240         return 0;
6241 }
6242
6243 #ifndef MODULE
6244 static void autorun_array(struct mddev *mddev)
6245 {
6246         struct md_rdev *rdev;
6247         int err;
6248
6249         if (list_empty(&mddev->disks))
6250                 return;
6251
6252         pr_info("md: running: ");
6253
6254         rdev_for_each(rdev, mddev) {
6255                 char b[BDEVNAME_SIZE];
6256                 pr_cont("<%s>", bdevname(rdev->bdev,b));
6257         }
6258         pr_cont("\n");
6259
6260         err = do_md_run(mddev);
6261         if (err) {
6262                 pr_warn("md: do_md_run() returned %d\n", err);
6263                 do_md_stop(mddev, 0, NULL);
6264         }
6265 }
6266
6267 /*
6268  * lets try to run arrays based on all disks that have arrived
6269  * until now. (those are in pending_raid_disks)
6270  *
6271  * the method: pick the first pending disk, collect all disks with
6272  * the same UUID, remove all from the pending list and put them into
6273  * the 'same_array' list. Then order this list based on superblock
6274  * update time (freshest comes first), kick out 'old' disks and
6275  * compare superblocks. If everything's fine then run it.
6276  *
6277  * If "unit" is allocated, then bump its reference count
6278  */
6279 static void autorun_devices(int part)
6280 {
6281         struct md_rdev *rdev0, *rdev, *tmp;
6282         struct mddev *mddev;
6283         char b[BDEVNAME_SIZE];
6284
6285         pr_info("md: autorun ...\n");
6286         while (!list_empty(&pending_raid_disks)) {
6287                 int unit;
6288                 dev_t dev;
6289                 LIST_HEAD(candidates);
6290                 rdev0 = list_entry(pending_raid_disks.next,
6291                                          struct md_rdev, same_set);
6292
6293                 pr_debug("md: considering %s ...\n", bdevname(rdev0->bdev,b));
6294                 INIT_LIST_HEAD(&candidates);
6295                 rdev_for_each_list(rdev, tmp, &pending_raid_disks)
6296                         if (super_90_load(rdev, rdev0, 0) >= 0) {
6297                                 pr_debug("md:  adding %s ...\n",
6298                                          bdevname(rdev->bdev,b));
6299                                 list_move(&rdev->same_set, &candidates);
6300                         }
6301                 /*
6302                  * now we have a set of devices, with all of them having
6303                  * mostly sane superblocks. It's time to allocate the
6304                  * mddev.
6305                  */
6306                 if (part) {
6307                         dev = MKDEV(mdp_major,
6308                                     rdev0->preferred_minor << MdpMinorShift);
6309                         unit = MINOR(dev) >> MdpMinorShift;
6310                 } else {
6311                         dev = MKDEV(MD_MAJOR, rdev0->preferred_minor);
6312                         unit = MINOR(dev);
6313                 }
6314                 if (rdev0->preferred_minor != unit) {
6315                         pr_warn("md: unit number in %s is bad: %d\n",
6316                                 bdevname(rdev0->bdev, b), rdev0->preferred_minor);
6317                         break;
6318                 }
6319
6320                 md_probe(dev, NULL, NULL);
6321                 mddev = mddev_find(dev);
6322                 if (!mddev || !mddev->gendisk) {
6323                         if (mddev)
6324                                 mddev_put(mddev);
6325                         break;
6326                 }
6327                 if (mddev_lock(mddev))
6328                         pr_warn("md: %s locked, cannot run\n", mdname(mddev));
6329                 else if (mddev->raid_disks || mddev->major_version
6330                          || !list_empty(&mddev->disks)) {
6331                         pr_warn("md: %s already running, cannot run %s\n",
6332                                 mdname(mddev), bdevname(rdev0->bdev,b));
6333                         mddev_unlock(mddev);
6334                 } else {
6335                         pr_debug("md: created %s\n", mdname(mddev));
6336                         mddev->persistent = 1;
6337                         rdev_for_each_list(rdev, tmp, &candidates) {
6338                                 list_del_init(&rdev->same_set);
6339                                 if (bind_rdev_to_array(rdev, mddev))
6340                                         export_rdev(rdev);
6341                         }
6342                         autorun_array(mddev);
6343                         mddev_unlock(mddev);
6344                 }
6345                 /* on success, candidates will be empty, on error
6346                  * it won't...
6347                  */
6348                 rdev_for_each_list(rdev, tmp, &candidates) {
6349                         list_del_init(&rdev->same_set);
6350                         export_rdev(rdev);
6351                 }
6352                 mddev_put(mddev);
6353         }
6354         pr_info("md: ... autorun DONE.\n");
6355 }
6356 #endif /* !MODULE */
6357
6358 static int get_version(void __user *arg)
6359 {
6360         mdu_version_t ver;
6361
6362         ver.major = MD_MAJOR_VERSION;
6363         ver.minor = MD_MINOR_VERSION;
6364         ver.patchlevel = MD_PATCHLEVEL_VERSION;
6365
6366         if (copy_to_user(arg, &ver, sizeof(ver)))
6367                 return -EFAULT;
6368
6369         return 0;
6370 }
6371
6372 static int get_array_info(struct mddev *mddev, void __user *arg)
6373 {
6374         mdu_array_info_t info;
6375         int nr,working,insync,failed,spare;
6376         struct md_rdev *rdev;
6377
6378         nr = working = insync = failed = spare = 0;
6379         rcu_read_lock();
6380         rdev_for_each_rcu(rdev, mddev) {
6381                 nr++;
6382                 if (test_bit(Faulty, &rdev->flags))
6383                         failed++;
6384                 else {
6385                         working++;
6386                         if (test_bit(In_sync, &rdev->flags))
6387                                 insync++;
6388                         else if (test_bit(Journal, &rdev->flags))
6389                                 /* TODO: add journal count to md_u.h */
6390                                 ;
6391                         else
6392                                 spare++;
6393                 }
6394         }
6395         rcu_read_unlock();
6396
6397         info.major_version = mddev->major_version;
6398         info.minor_version = mddev->minor_version;
6399         info.patch_version = MD_PATCHLEVEL_VERSION;
6400         info.ctime         = clamp_t(time64_t, mddev->ctime, 0, U32_MAX);
6401         info.level         = mddev->level;
6402         info.size          = mddev->dev_sectors / 2;
6403         if (info.size != mddev->dev_sectors / 2) /* overflow */
6404                 info.size = -1;
6405         info.nr_disks      = nr;
6406         info.raid_disks    = mddev->raid_disks;
6407         info.md_minor      = mddev->md_minor;
6408         info.not_persistent= !mddev->persistent;
6409
6410         info.utime         = clamp_t(time64_t, mddev->utime, 0, U32_MAX);
6411         info.state         = 0;
6412         if (mddev->in_sync)
6413                 info.state = (1<<MD_SB_CLEAN);
6414         if (mddev->bitmap && mddev->bitmap_info.offset)
6415                 info.state |= (1<<MD_SB_BITMAP_PRESENT);
6416         if (mddev_is_clustered(mddev))
6417                 info.state |= (1<<MD_SB_CLUSTERED);
6418         info.active_disks  = insync;
6419         info.working_disks = working;
6420         info.failed_disks  = failed;
6421         info.spare_disks   = spare;
6422
6423         info.layout        = mddev->layout;
6424         info.chunk_size    = mddev->chunk_sectors << 9;
6425
6426         if (copy_to_user(arg, &info, sizeof(info)))
6427                 return -EFAULT;
6428
6429         return 0;
6430 }
6431
6432 static int get_bitmap_file(struct mddev *mddev, void __user * arg)
6433 {
6434         mdu_bitmap_file_t *file = NULL; /* too big for stack allocation */
6435         char *ptr;
6436         int err;
6437
6438         file = kzalloc(sizeof(*file), GFP_NOIO);
6439         if (!file)
6440                 return -ENOMEM;
6441
6442         err = 0;
6443         spin_lock(&mddev->lock);
6444         /* bitmap enabled */
6445         if (mddev->bitmap_info.file) {
6446                 ptr = file_path(mddev->bitmap_info.file, file->pathname,
6447                                 sizeof(file->pathname));
6448                 if (IS_ERR(ptr))
6449                         err = PTR_ERR(ptr);
6450                 else
6451                         memmove(file->pathname, ptr,
6452                                 sizeof(file->pathname)-(ptr-file->pathname));
6453         }
6454         spin_unlock(&mddev->lock);
6455
6456         if (err == 0 &&
6457             copy_to_user(arg, file, sizeof(*file)))
6458                 err = -EFAULT;
6459
6460         kfree(file);
6461         return err;
6462 }
6463
6464 static int get_disk_info(struct mddev *mddev, void __user * arg)
6465 {
6466         mdu_disk_info_t info;
6467         struct md_rdev *rdev;
6468
6469         if (copy_from_user(&info, arg, sizeof(info)))
6470                 return -EFAULT;
6471
6472         rcu_read_lock();
6473         rdev = md_find_rdev_nr_rcu(mddev, info.number);
6474         if (rdev) {
6475                 info.major = MAJOR(rdev->bdev->bd_dev);
6476                 info.minor = MINOR(rdev->bdev->bd_dev);
6477                 info.raid_disk = rdev->raid_disk;
6478                 info.state = 0;
6479                 if (test_bit(Faulty, &rdev->flags))
6480                         info.state |= (1<<MD_DISK_FAULTY);
6481                 else if (test_bit(In_sync, &rdev->flags)) {
6482                         info.state |= (1<<MD_DISK_ACTIVE);
6483                         info.state |= (1<<MD_DISK_SYNC);
6484                 }
6485                 if (test_bit(Journal, &rdev->flags))
6486                         info.state |= (1<<MD_DISK_JOURNAL);
6487                 if (test_bit(WriteMostly, &rdev->flags))
6488                         info.state |= (1<<MD_DISK_WRITEMOSTLY);
6489                 if (test_bit(FailFast, &rdev->flags))
6490                         info.state |= (1<<MD_DISK_FAILFAST);
6491         } else {
6492                 info.major = info.minor = 0;
6493                 info.raid_disk = -1;
6494                 info.state = (1<<MD_DISK_REMOVED);
6495         }
6496         rcu_read_unlock();
6497
6498         if (copy_to_user(arg, &info, sizeof(info)))
6499                 return -EFAULT;
6500
6501         return 0;
6502 }
6503
6504 static int add_new_disk(struct mddev *mddev, mdu_disk_info_t *info)
6505 {
6506         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
6507         struct md_rdev *rdev;
6508         dev_t dev = MKDEV(info->major,info->minor);
6509
6510         if (mddev_is_clustered(mddev) &&
6511                 !(info->state & ((1 << MD_DISK_CLUSTER_ADD) | (1 << MD_DISK_CANDIDATE)))) {
6512                 pr_warn("%s: Cannot add to clustered mddev.\n",
6513                         mdname(mddev));
6514                 return -EINVAL;
6515         }
6516
6517         if (info->major != MAJOR(dev) || info->minor != MINOR(dev))
6518                 return -EOVERFLOW;
6519
6520         if (!mddev->raid_disks) {
6521                 int err;
6522                 /* expecting a device which has a superblock */
6523                 rdev = md_import_device(dev, mddev->major_version, mddev->minor_version);
6524                 if (IS_ERR(rdev)) {
6525                         pr_warn("md: md_import_device returned %ld\n",
6526                                 PTR_ERR(rdev));
6527                         return PTR_ERR(rdev);
6528                 }
6529                 if (!list_empty(&mddev->disks)) {
6530                         struct md_rdev *rdev0
6531                                 = list_entry(mddev->disks.next,
6532                                              struct md_rdev, same_set);
6533                         err = super_types[mddev->major_version]
6534                                 .load_super(rdev, rdev0, mddev->minor_version);
6535                         if (err < 0) {
6536                                 pr_warn("md: %s has different UUID to %s\n",
6537                                         bdevname(rdev->bdev,b),
6538                                         bdevname(rdev0->bdev,b2));
6539                                 export_rdev(rdev);
6540                                 return -EINVAL;
6541                         }
6542                 }
6543                 err = bind_rdev_to_array(rdev, mddev);
6544                 if (err)
6545                         export_rdev(rdev);
6546                 return err;
6547         }
6548
6549         /*
6550          * add_new_disk can be used once the array is assembled
6551          * to add "hot spares".  They must already have a superblock
6552          * written
6553          */
6554         if (mddev->pers) {
6555                 int err;
6556                 if (!mddev->pers->hot_add_disk) {
6557                         pr_warn("%s: personality does not support diskops!\n",
6558                                 mdname(mddev));
6559                         return -EINVAL;
6560                 }
6561                 if (mddev->persistent)
6562                         rdev = md_import_device(dev, mddev->major_version,
6563                                                 mddev->minor_version);
6564                 else
6565                         rdev = md_import_device(dev, -1, -1);
6566                 if (IS_ERR(rdev)) {
6567                         pr_warn("md: md_import_device returned %ld\n",
6568                                 PTR_ERR(rdev));
6569                         return PTR_ERR(rdev);
6570                 }
6571                 /* set saved_raid_disk if appropriate */
6572                 if (!mddev->persistent) {
6573                         if (info->state & (1<<MD_DISK_SYNC)  &&
6574                             info->raid_disk < mddev->raid_disks) {
6575                                 rdev->raid_disk = info->raid_disk;
6576                                 set_bit(In_sync, &rdev->flags);
6577                                 clear_bit(Bitmap_sync, &rdev->flags);
6578                         } else
6579                                 rdev->raid_disk = -1;
6580                         rdev->saved_raid_disk = rdev->raid_disk;
6581                 } else
6582                         super_types[mddev->major_version].
6583                                 validate_super(mddev, rdev);
6584                 if ((info->state & (1<<MD_DISK_SYNC)) &&
6585                      rdev->raid_disk != info->raid_disk) {
6586                         /* This was a hot-add request, but events doesn't
6587                          * match, so reject it.
6588                          */
6589                         export_rdev(rdev);
6590                         return -EINVAL;
6591                 }
6592
6593                 clear_bit(In_sync, &rdev->flags); /* just to be sure */
6594                 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
6595                         set_bit(WriteMostly, &rdev->flags);
6596                 else
6597                         clear_bit(WriteMostly, &rdev->flags);
6598                 if (info->state & (1<<MD_DISK_FAILFAST))
6599                         set_bit(FailFast, &rdev->flags);
6600                 else
6601                         clear_bit(FailFast, &rdev->flags);
6602
6603                 if (info->state & (1<<MD_DISK_JOURNAL)) {
6604                         struct md_rdev *rdev2;
6605                         bool has_journal = false;
6606
6607                         /* make sure no existing journal disk */
6608                         rdev_for_each(rdev2, mddev) {
6609                                 if (test_bit(Journal, &rdev2->flags)) {
6610                                         has_journal = true;
6611                                         break;
6612                                 }
6613                         }
6614                         if (has_journal || mddev->bitmap) {
6615                                 export_rdev(rdev);
6616                                 return -EBUSY;
6617                         }
6618                         set_bit(Journal, &rdev->flags);
6619                 }
6620                 /*
6621                  * check whether the device shows up in other nodes
6622                  */
6623                 if (mddev_is_clustered(mddev)) {
6624                         if (info->state & (1 << MD_DISK_CANDIDATE))
6625                                 set_bit(Candidate, &rdev->flags);
6626                         else if (info->state & (1 << MD_DISK_CLUSTER_ADD)) {
6627                                 /* --add initiated by this node */
6628                                 err = md_cluster_ops->add_new_disk(mddev, rdev);
6629                                 if (err) {
6630                                         export_rdev(rdev);
6631                                         return err;
6632                                 }
6633                         }
6634                 }
6635
6636                 rdev->raid_disk = -1;
6637                 err = bind_rdev_to_array(rdev, mddev);
6638
6639                 if (err)
6640                         export_rdev(rdev);
6641
6642                 if (mddev_is_clustered(mddev)) {
6643                         if (info->state & (1 << MD_DISK_CANDIDATE)) {
6644                                 if (!err) {
6645                                         err = md_cluster_ops->new_disk_ack(mddev,
6646                                                 err == 0);
6647                                         if (err)
6648                                                 md_kick_rdev_from_array(rdev);
6649                                 }
6650                         } else {
6651                                 if (err)
6652                                         md_cluster_ops->add_new_disk_cancel(mddev);
6653                                 else
6654                                         err = add_bound_rdev(rdev);
6655                         }
6656
6657                 } else if (!err)
6658                         err = add_bound_rdev(rdev);
6659
6660                 return err;
6661         }
6662
6663         /* otherwise, add_new_disk is only allowed
6664          * for major_version==0 superblocks
6665          */
6666         if (mddev->major_version != 0) {
6667                 pr_warn("%s: ADD_NEW_DISK not supported\n", mdname(mddev));
6668                 return -EINVAL;
6669         }
6670
6671         if (!(info->state & (1<<MD_DISK_FAULTY))) {
6672                 int err;
6673                 rdev = md_import_device(dev, -1, 0);
6674                 if (IS_ERR(rdev)) {
6675                         pr_warn("md: error, md_import_device() returned %ld\n",
6676                                 PTR_ERR(rdev));
6677                         return PTR_ERR(rdev);
6678                 }
6679                 rdev->desc_nr = info->number;
6680                 if (info->raid_disk < mddev->raid_disks)
6681                         rdev->raid_disk = info->raid_disk;
6682                 else
6683                         rdev->raid_disk = -1;
6684
6685                 if (rdev->raid_disk < mddev->raid_disks)
6686                         if (info->state & (1<<MD_DISK_SYNC))
6687                                 set_bit(In_sync, &rdev->flags);
6688
6689                 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
6690                         set_bit(WriteMostly, &rdev->flags);
6691                 if (info->state & (1<<MD_DISK_FAILFAST))
6692                         set_bit(FailFast, &rdev->flags);
6693
6694                 if (!mddev->persistent) {
6695                         pr_debug("md: nonpersistent superblock ...\n");
6696                         rdev->sb_start = i_size_read(rdev->bdev->bd_inode) / 512;
6697                 } else
6698                         rdev->sb_start = calc_dev_sboffset(rdev);
6699                 rdev->sectors = rdev->sb_start;
6700
6701                 err = bind_rdev_to_array(rdev, mddev);
6702                 if (err) {
6703                         export_rdev(rdev);
6704                         return err;
6705                 }
6706         }
6707
6708         return 0;
6709 }
6710
6711 static int hot_remove_disk(struct mddev *mddev, dev_t dev)
6712 {
6713         char b[BDEVNAME_SIZE];
6714         struct md_rdev *rdev;
6715
6716         if (!mddev->pers)
6717                 return -ENODEV;
6718
6719         rdev = find_rdev(mddev, dev);
6720         if (!rdev)
6721                 return -ENXIO;
6722
6723         if (rdev->raid_disk < 0)
6724                 goto kick_rdev;
6725
6726         clear_bit(Blocked, &rdev->flags);
6727         remove_and_add_spares(mddev, rdev);
6728
6729         if (rdev->raid_disk >= 0)
6730                 goto busy;
6731
6732 kick_rdev:
6733         if (mddev_is_clustered(mddev))
6734                 md_cluster_ops->remove_disk(mddev, rdev);
6735
6736         md_kick_rdev_from_array(rdev);
6737         set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6738         if (mddev->thread)
6739                 md_wakeup_thread(mddev->thread);
6740         else
6741                 md_update_sb(mddev, 1);
6742         md_new_event(mddev);
6743
6744         return 0;
6745 busy:
6746         pr_debug("md: cannot remove active disk %s from %s ...\n",
6747                  bdevname(rdev->bdev,b), mdname(mddev));
6748         return -EBUSY;
6749 }
6750
6751 static int hot_add_disk(struct mddev *mddev, dev_t dev)
6752 {
6753         char b[BDEVNAME_SIZE];
6754         int err;
6755         struct md_rdev *rdev;
6756
6757         if (!mddev->pers)
6758                 return -ENODEV;
6759
6760         if (mddev->major_version != 0) {
6761                 pr_warn("%s: HOT_ADD may only be used with version-0 superblocks.\n",
6762                         mdname(mddev));
6763                 return -EINVAL;
6764         }
6765         if (!mddev->pers->hot_add_disk) {
6766                 pr_warn("%s: personality does not support diskops!\n",
6767                         mdname(mddev));
6768                 return -EINVAL;
6769         }
6770
6771         rdev = md_import_device(dev, -1, 0);
6772         if (IS_ERR(rdev)) {
6773                 pr_warn("md: error, md_import_device() returned %ld\n",
6774                         PTR_ERR(rdev));
6775                 return -EINVAL;
6776         }
6777
6778         if (mddev->persistent)
6779                 rdev->sb_start = calc_dev_sboffset(rdev);
6780         else
6781                 rdev->sb_start = i_size_read(rdev->bdev->bd_inode) / 512;
6782
6783         rdev->sectors = rdev->sb_start;
6784
6785         if (test_bit(Faulty, &rdev->flags)) {
6786                 pr_warn("md: can not hot-add faulty %s disk to %s!\n",
6787                         bdevname(rdev->bdev,b), mdname(mddev));
6788                 err = -EINVAL;
6789                 goto abort_export;
6790         }
6791
6792         clear_bit(In_sync, &rdev->flags);
6793         rdev->desc_nr = -1;
6794         rdev->saved_raid_disk = -1;
6795         err = bind_rdev_to_array(rdev, mddev);
6796         if (err)
6797                 goto abort_export;
6798
6799         /*
6800          * The rest should better be atomic, we can have disk failures
6801          * noticed in interrupt contexts ...
6802          */
6803
6804         rdev->raid_disk = -1;
6805
6806         set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6807         if (!mddev->thread)
6808                 md_update_sb(mddev, 1);
6809         /*
6810          * Kick recovery, maybe this spare has to be added to the
6811          * array immediately.
6812          */
6813         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6814         md_wakeup_thread(mddev->thread);
6815         md_new_event(mddev);
6816         return 0;
6817
6818 abort_export:
6819         export_rdev(rdev);
6820         return err;
6821 }
6822
6823 static int set_bitmap_file(struct mddev *mddev, int fd)
6824 {
6825         int err = 0;
6826
6827         if (mddev->pers) {
6828                 if (!mddev->pers->quiesce || !mddev->thread)
6829                         return -EBUSY;
6830                 if (mddev->recovery || mddev->sync_thread)
6831                         return -EBUSY;
6832                 /* we should be able to change the bitmap.. */
6833         }
6834
6835         if (fd >= 0) {
6836                 struct inode *inode;
6837                 struct file *f;
6838
6839                 if (mddev->bitmap || mddev->bitmap_info.file)
6840                         return -EEXIST; /* cannot add when bitmap is present */
6841                 f = fget(fd);
6842
6843                 if (f == NULL) {
6844                         pr_warn("%s: error: failed to get bitmap file\n",
6845                                 mdname(mddev));
6846                         return -EBADF;
6847                 }
6848
6849                 inode = f->f_mapping->host;
6850                 if (!S_ISREG(inode->i_mode)) {
6851                         pr_warn("%s: error: bitmap file must be a regular file\n",
6852                                 mdname(mddev));
6853                         err = -EBADF;
6854                 } else if (!(f->f_mode & FMODE_WRITE)) {
6855                         pr_warn("%s: error: bitmap file must open for write\n",
6856                                 mdname(mddev));
6857                         err = -EBADF;
6858                 } else if (atomic_read(&inode->i_writecount) != 1) {
6859                         pr_warn("%s: error: bitmap file is already in use\n",
6860                                 mdname(mddev));
6861                         err = -EBUSY;
6862                 }
6863                 if (err) {
6864                         fput(f);
6865                         return err;
6866                 }
6867                 mddev->bitmap_info.file = f;
6868                 mddev->bitmap_info.offset = 0; /* file overrides offset */
6869         } else if (mddev->bitmap == NULL)
6870                 return -ENOENT; /* cannot remove what isn't there */
6871         err = 0;
6872         if (mddev->pers) {
6873                 if (fd >= 0) {
6874                         struct bitmap *bitmap;
6875
6876                         bitmap = md_bitmap_create(mddev, -1);
6877                         mddev_suspend(mddev);
6878                         if (!IS_ERR(bitmap)) {
6879                                 mddev->bitmap = bitmap;
6880                                 err = md_bitmap_load(mddev);
6881                         } else
6882                                 err = PTR_ERR(bitmap);
6883                         if (err) {
6884                                 md_bitmap_destroy(mddev);
6885                                 fd = -1;
6886                         }
6887                         mddev_resume(mddev);
6888                 } else if (fd < 0) {
6889                         mddev_suspend(mddev);
6890                         md_bitmap_destroy(mddev);
6891                         mddev_resume(mddev);
6892                 }
6893         }
6894         if (fd < 0) {
6895                 struct file *f = mddev->bitmap_info.file;
6896                 if (f) {
6897                         spin_lock(&mddev->lock);
6898                         mddev->bitmap_info.file = NULL;
6899                         spin_unlock(&mddev->lock);
6900                         fput(f);
6901                 }
6902         }
6903
6904         return err;
6905 }
6906
6907 /*
6908  * set_array_info is used two different ways
6909  * The original usage is when creating a new array.
6910  * In this usage, raid_disks is > 0 and it together with
6911  *  level, size, not_persistent,layout,chunksize determine the
6912  *  shape of the array.
6913  *  This will always create an array with a type-0.90.0 superblock.
6914  * The newer usage is when assembling an array.
6915  *  In this case raid_disks will be 0, and the major_version field is
6916  *  use to determine which style super-blocks are to be found on the devices.
6917  *  The minor and patch _version numbers are also kept incase the
6918  *  super_block handler wishes to interpret them.
6919  */
6920 static int set_array_info(struct mddev *mddev, mdu_array_info_t *info)
6921 {
6922
6923         if (info->raid_disks == 0) {
6924                 /* just setting version number for superblock loading */
6925                 if (info->major_version < 0 ||
6926                     info->major_version >= ARRAY_SIZE(super_types) ||
6927                     super_types[info->major_version].name == NULL) {
6928                         /* maybe try to auto-load a module? */
6929                         pr_warn("md: superblock version %d not known\n",
6930                                 info->major_version);
6931                         return -EINVAL;
6932                 }
6933                 mddev->major_version = info->major_version;
6934                 mddev->minor_version = info->minor_version;
6935                 mddev->patch_version = info->patch_version;
6936                 mddev->persistent = !info->not_persistent;
6937                 /* ensure mddev_put doesn't delete this now that there
6938                  * is some minimal configuration.
6939                  */
6940                 mddev->ctime         = ktime_get_real_seconds();
6941                 return 0;
6942         }
6943         mddev->major_version = MD_MAJOR_VERSION;
6944         mddev->minor_version = MD_MINOR_VERSION;
6945         mddev->patch_version = MD_PATCHLEVEL_VERSION;
6946         mddev->ctime         = ktime_get_real_seconds();
6947
6948         mddev->level         = info->level;
6949         mddev->clevel[0]     = 0;
6950         mddev->dev_sectors   = 2 * (sector_t)info->size;
6951         mddev->raid_disks    = info->raid_disks;
6952         /* don't set md_minor, it is determined by which /dev/md* was
6953          * openned
6954          */
6955         if (info->state & (1<<MD_SB_CLEAN))
6956                 mddev->recovery_cp = MaxSector;
6957         else
6958                 mddev->recovery_cp = 0;
6959         mddev->persistent    = ! info->not_persistent;
6960         mddev->external      = 0;
6961
6962         mddev->layout        = info->layout;
6963         if (mddev->level == 0)
6964                 /* Cannot trust RAID0 layout info here */
6965                 mddev->layout = -1;
6966         mddev->chunk_sectors = info->chunk_size >> 9;
6967
6968         if (mddev->persistent) {
6969                 mddev->max_disks = MD_SB_DISKS;
6970                 mddev->flags = 0;
6971                 mddev->sb_flags = 0;
6972         }
6973         set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6974
6975         mddev->bitmap_info.default_offset = MD_SB_BYTES >> 9;
6976         mddev->bitmap_info.default_space = 64*2 - (MD_SB_BYTES >> 9);
6977         mddev->bitmap_info.offset = 0;
6978
6979         mddev->reshape_position = MaxSector;
6980
6981         /*
6982          * Generate a 128 bit UUID
6983          */
6984         get_random_bytes(mddev->uuid, 16);
6985
6986         mddev->new_level = mddev->level;
6987         mddev->new_chunk_sectors = mddev->chunk_sectors;
6988         mddev->new_layout = mddev->layout;
6989         mddev->delta_disks = 0;
6990         mddev->reshape_backwards = 0;
6991
6992         return 0;
6993 }
6994
6995 void md_set_array_sectors(struct mddev *mddev, sector_t array_sectors)
6996 {
6997         lockdep_assert_held(&mddev->reconfig_mutex);
6998
6999         if (mddev->external_size)
7000                 return;
7001
7002         mddev->array_sectors = array_sectors;
7003 }
7004 EXPORT_SYMBOL(md_set_array_sectors);
7005
7006 static int update_size(struct mddev *mddev, sector_t num_sectors)
7007 {
7008         struct md_rdev *rdev;
7009         int rv;
7010         int fit = (num_sectors == 0);
7011         sector_t old_dev_sectors = mddev->dev_sectors;
7012
7013         if (mddev->pers->resize == NULL)
7014                 return -EINVAL;
7015         /* The "num_sectors" is the number of sectors of each device that
7016          * is used.  This can only make sense for arrays with redundancy.
7017          * linear and raid0 always use whatever space is available. We can only
7018          * consider changing this number if no resync or reconstruction is
7019          * happening, and if the new size is acceptable. It must fit before the
7020          * sb_start or, if that is <data_offset, it must fit before the size
7021          * of each device.  If num_sectors is zero, we find the largest size
7022          * that fits.
7023          */
7024         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
7025             mddev->sync_thread)
7026                 return -EBUSY;
7027         if (mddev->ro)
7028                 return -EROFS;
7029
7030         rdev_for_each(rdev, mddev) {
7031                 sector_t avail = rdev->sectors;
7032
7033                 if (fit && (num_sectors == 0 || num_sectors > avail))
7034                         num_sectors = avail;
7035                 if (avail < num_sectors)
7036                         return -ENOSPC;
7037         }
7038         rv = mddev->pers->resize(mddev, num_sectors);
7039         if (!rv) {
7040                 if (mddev_is_clustered(mddev))
7041                         md_cluster_ops->update_size(mddev, old_dev_sectors);
7042                 else if (mddev->queue) {
7043                         set_capacity(mddev->gendisk, mddev->array_sectors);
7044                         revalidate_disk(mddev->gendisk);
7045                 }
7046         }
7047         return rv;
7048 }
7049
7050 static int update_raid_disks(struct mddev *mddev, int raid_disks)
7051 {
7052         int rv;
7053         struct md_rdev *rdev;
7054         /* change the number of raid disks */
7055         if (mddev->pers->check_reshape == NULL)
7056                 return -EINVAL;
7057         if (mddev->ro)
7058                 return -EROFS;
7059         if (raid_disks <= 0 ||
7060             (mddev->max_disks && raid_disks >= mddev->max_disks))
7061                 return -EINVAL;
7062         if (mddev->sync_thread ||
7063             test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
7064             mddev->reshape_position != MaxSector)
7065                 return -EBUSY;
7066
7067         rdev_for_each(rdev, mddev) {
7068                 if (mddev->raid_disks < raid_disks &&
7069                     rdev->data_offset < rdev->new_data_offset)
7070                         return -EINVAL;
7071                 if (mddev->raid_disks > raid_disks &&
7072                     rdev->data_offset > rdev->new_data_offset)
7073                         return -EINVAL;
7074         }
7075
7076         mddev->delta_disks = raid_disks - mddev->raid_disks;
7077         if (mddev->delta_disks < 0)
7078                 mddev->reshape_backwards = 1;
7079         else if (mddev->delta_disks > 0)
7080                 mddev->reshape_backwards = 0;
7081
7082         rv = mddev->pers->check_reshape(mddev);
7083         if (rv < 0) {
7084                 mddev->delta_disks = 0;
7085                 mddev->reshape_backwards = 0;
7086         }
7087         return rv;
7088 }
7089
7090 /*
7091  * update_array_info is used to change the configuration of an
7092  * on-line array.
7093  * The version, ctime,level,size,raid_disks,not_persistent, layout,chunk_size
7094  * fields in the info are checked against the array.
7095  * Any differences that cannot be handled will cause an error.
7096  * Normally, only one change can be managed at a time.
7097  */
7098 static int update_array_info(struct mddev *mddev, mdu_array_info_t *info)
7099 {
7100         int rv = 0;
7101         int cnt = 0;
7102         int state = 0;
7103
7104         /* calculate expected state,ignoring low bits */
7105         if (mddev->bitmap && mddev->bitmap_info.offset)
7106                 state |= (1 << MD_SB_BITMAP_PRESENT);
7107
7108         if (mddev->major_version != info->major_version ||
7109             mddev->minor_version != info->minor_version ||
7110 /*          mddev->patch_version != info->patch_version || */
7111             mddev->ctime         != info->ctime         ||
7112             mddev->level         != info->level         ||
7113 /*          mddev->layout        != info->layout        || */
7114             mddev->persistent    != !info->not_persistent ||
7115             mddev->chunk_sectors != info->chunk_size >> 9 ||
7116             /* ignore bottom 8 bits of state, and allow SB_BITMAP_PRESENT to change */
7117             ((state^info->state) & 0xfffffe00)
7118                 )
7119                 return -EINVAL;
7120         /* Check there is only one change */
7121         if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
7122                 cnt++;
7123         if (mddev->raid_disks != info->raid_disks)
7124                 cnt++;
7125         if (mddev->layout != info->layout)
7126                 cnt++;
7127         if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT))
7128                 cnt++;
7129         if (cnt == 0)
7130                 return 0;
7131         if (cnt > 1)
7132                 return -EINVAL;
7133
7134         if (mddev->layout != info->layout) {
7135                 /* Change layout
7136                  * we don't need to do anything at the md level, the
7137                  * personality will take care of it all.
7138                  */
7139                 if (mddev->pers->check_reshape == NULL)
7140                         return -EINVAL;
7141                 else {
7142                         mddev->new_layout = info->layout;
7143                         rv = mddev->pers->check_reshape(mddev);
7144                         if (rv)
7145                                 mddev->new_layout = mddev->layout;
7146                         return rv;
7147                 }
7148         }
7149         if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
7150                 rv = update_size(mddev, (sector_t)info->size * 2);
7151
7152         if (mddev->raid_disks    != info->raid_disks)
7153                 rv = update_raid_disks(mddev, info->raid_disks);
7154
7155         if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT)) {
7156                 if (mddev->pers->quiesce == NULL || mddev->thread == NULL) {
7157                         rv = -EINVAL;
7158                         goto err;
7159                 }
7160                 if (mddev->recovery || mddev->sync_thread) {
7161                         rv = -EBUSY;
7162                         goto err;
7163                 }
7164                 if (info->state & (1<<MD_SB_BITMAP_PRESENT)) {
7165                         struct bitmap *bitmap;
7166                         /* add the bitmap */
7167                         if (mddev->bitmap) {
7168                                 rv = -EEXIST;
7169                                 goto err;
7170                         }
7171                         if (mddev->bitmap_info.default_offset == 0) {
7172                                 rv = -EINVAL;
7173                                 goto err;
7174                         }
7175                         mddev->bitmap_info.offset =
7176                                 mddev->bitmap_info.default_offset;
7177                         mddev->bitmap_info.space =
7178                                 mddev->bitmap_info.default_space;
7179                         bitmap = md_bitmap_create(mddev, -1);
7180                         mddev_suspend(mddev);
7181                         if (!IS_ERR(bitmap)) {
7182                                 mddev->bitmap = bitmap;
7183                                 rv = md_bitmap_load(mddev);
7184                         } else
7185                                 rv = PTR_ERR(bitmap);
7186                         if (rv)
7187                                 md_bitmap_destroy(mddev);
7188                         mddev_resume(mddev);
7189                 } else {
7190                         /* remove the bitmap */
7191                         if (!mddev->bitmap) {
7192                                 rv = -ENOENT;
7193                                 goto err;
7194                         }
7195                         if (mddev->bitmap->storage.file) {
7196                                 rv = -EINVAL;
7197                                 goto err;
7198                         }
7199                         if (mddev->bitmap_info.nodes) {
7200                                 /* hold PW on all the bitmap lock */
7201                                 if (md_cluster_ops->lock_all_bitmaps(mddev) <= 0) {
7202                                         pr_warn("md: can't change bitmap to none since the array is in use by more than one node\n");
7203                                         rv = -EPERM;
7204                                         md_cluster_ops->unlock_all_bitmaps(mddev);
7205                                         goto err;
7206                                 }
7207
7208                                 mddev->bitmap_info.nodes = 0;
7209                                 md_cluster_ops->leave(mddev);
7210                         }
7211                         mddev_suspend(mddev);
7212                         md_bitmap_destroy(mddev);
7213                         mddev_resume(mddev);
7214                         mddev->bitmap_info.offset = 0;
7215                 }
7216         }
7217         md_update_sb(mddev, 1);
7218         return rv;
7219 err:
7220         return rv;
7221 }
7222
7223 static int set_disk_faulty(struct mddev *mddev, dev_t dev)
7224 {
7225         struct md_rdev *rdev;
7226         int err = 0;
7227
7228         if (mddev->pers == NULL)
7229                 return -ENODEV;
7230
7231         rcu_read_lock();
7232         rdev = md_find_rdev_rcu(mddev, dev);
7233         if (!rdev)
7234                 err =  -ENODEV;
7235         else {
7236                 md_error(mddev, rdev);
7237                 if (!test_bit(Faulty, &rdev->flags))
7238                         err = -EBUSY;
7239         }
7240         rcu_read_unlock();
7241         return err;
7242 }
7243
7244 /*
7245  * We have a problem here : there is no easy way to give a CHS
7246  * virtual geometry. We currently pretend that we have a 2 heads
7247  * 4 sectors (with a BIG number of cylinders...). This drives
7248  * dosfs just mad... ;-)
7249  */
7250 static int md_getgeo(struct block_device *bdev, struct hd_geometry *geo)
7251 {
7252         struct mddev *mddev = bdev->bd_disk->private_data;
7253
7254         geo->heads = 2;
7255         geo->sectors = 4;
7256         geo->cylinders = mddev->array_sectors / 8;
7257         return 0;
7258 }
7259
7260 static inline bool md_ioctl_valid(unsigned int cmd)
7261 {
7262         switch (cmd) {
7263         case ADD_NEW_DISK:
7264         case BLKROSET:
7265         case GET_ARRAY_INFO:
7266         case GET_BITMAP_FILE:
7267         case GET_DISK_INFO:
7268         case HOT_ADD_DISK:
7269         case HOT_REMOVE_DISK:
7270         case RAID_AUTORUN:
7271         case RAID_VERSION:
7272         case RESTART_ARRAY_RW:
7273         case RUN_ARRAY:
7274         case SET_ARRAY_INFO:
7275         case SET_BITMAP_FILE:
7276         case SET_DISK_FAULTY:
7277         case STOP_ARRAY:
7278         case STOP_ARRAY_RO:
7279         case CLUSTERED_DISK_NACK:
7280                 return true;
7281         default:
7282                 return false;
7283         }
7284 }
7285
7286 static int md_ioctl(struct block_device *bdev, fmode_t mode,
7287                         unsigned int cmd, unsigned long arg)
7288 {
7289         int err = 0;
7290         void __user *argp = (void __user *)arg;
7291         struct mddev *mddev = NULL;
7292         int ro;
7293         bool did_set_md_closing = false;
7294
7295         if (!md_ioctl_valid(cmd))
7296                 return -ENOTTY;
7297
7298         switch (cmd) {
7299         case RAID_VERSION:
7300         case GET_ARRAY_INFO:
7301         case GET_DISK_INFO:
7302                 break;
7303         default:
7304                 if (!capable(CAP_SYS_ADMIN))
7305                         return -EACCES;
7306         }
7307
7308         /*
7309          * Commands dealing with the RAID driver but not any
7310          * particular array:
7311          */
7312         switch (cmd) {
7313         case RAID_VERSION:
7314                 err = get_version(argp);
7315                 goto out;
7316
7317 #ifndef MODULE
7318         case RAID_AUTORUN:
7319                 err = 0;
7320                 autostart_arrays(arg);
7321                 goto out;
7322 #endif
7323         default:;
7324         }
7325
7326         /*
7327          * Commands creating/starting a new array:
7328          */
7329
7330         mddev = bdev->bd_disk->private_data;
7331
7332         if (!mddev) {
7333                 BUG();
7334                 goto out;
7335         }
7336
7337         /* Some actions do not requires the mutex */
7338         switch (cmd) {
7339         case GET_ARRAY_INFO:
7340                 if (!mddev->raid_disks && !mddev->external)
7341                         err = -ENODEV;
7342                 else
7343                         err = get_array_info(mddev, argp);
7344                 goto out;
7345
7346         case GET_DISK_INFO:
7347                 if (!mddev->raid_disks && !mddev->external)
7348                         err = -ENODEV;
7349                 else
7350                         err = get_disk_info(mddev, argp);
7351                 goto out;
7352
7353         case SET_DISK_FAULTY:
7354                 err = set_disk_faulty(mddev, new_decode_dev(arg));
7355                 goto out;
7356
7357         case GET_BITMAP_FILE:
7358                 err = get_bitmap_file(mddev, argp);
7359                 goto out;
7360
7361         }
7362
7363         if (cmd == ADD_NEW_DISK)
7364                 /* need to ensure md_delayed_delete() has completed */
7365                 flush_workqueue(md_misc_wq);
7366
7367         if (cmd == HOT_REMOVE_DISK)
7368                 /* need to ensure recovery thread has run */
7369                 wait_event_interruptible_timeout(mddev->sb_wait,
7370                                                  !test_bit(MD_RECOVERY_NEEDED,
7371                                                            &mddev->recovery),
7372                                                  msecs_to_jiffies(5000));
7373         if (cmd == STOP_ARRAY || cmd == STOP_ARRAY_RO) {
7374                 /* Need to flush page cache, and ensure no-one else opens
7375                  * and writes
7376                  */
7377                 mutex_lock(&mddev->open_mutex);
7378                 if (mddev->pers && atomic_read(&mddev->openers) > 1) {
7379                         mutex_unlock(&mddev->open_mutex);
7380                         err = -EBUSY;
7381                         goto out;
7382                 }
7383                 WARN_ON_ONCE(test_bit(MD_CLOSING, &mddev->flags));
7384                 set_bit(MD_CLOSING, &mddev->flags);
7385                 did_set_md_closing = true;
7386                 mutex_unlock(&mddev->open_mutex);
7387                 sync_blockdev(bdev);
7388         }
7389         err = mddev_lock(mddev);
7390         if (err) {
7391                 pr_debug("md: ioctl lock interrupted, reason %d, cmd %d\n",
7392                          err, cmd);
7393                 goto out;
7394         }
7395
7396         if (cmd == SET_ARRAY_INFO) {
7397                 mdu_array_info_t info;
7398                 if (!arg)
7399                         memset(&info, 0, sizeof(info));
7400                 else if (copy_from_user(&info, argp, sizeof(info))) {
7401                         err = -EFAULT;
7402                         goto unlock;
7403                 }
7404                 if (mddev->pers) {
7405                         err = update_array_info(mddev, &info);
7406                         if (err) {
7407                                 pr_warn("md: couldn't update array info. %d\n", err);
7408                                 goto unlock;
7409                         }
7410                         goto unlock;
7411                 }
7412                 if (!list_empty(&mddev->disks)) {
7413                         pr_warn("md: array %s already has disks!\n", mdname(mddev));
7414                         err = -EBUSY;
7415                         goto unlock;
7416                 }
7417                 if (mddev->raid_disks) {
7418                         pr_warn("md: array %s already initialised!\n", mdname(mddev));
7419                         err = -EBUSY;
7420                         goto unlock;
7421                 }
7422                 err = set_array_info(mddev, &info);
7423                 if (err) {
7424                         pr_warn("md: couldn't set array info. %d\n", err);
7425                         goto unlock;
7426                 }
7427                 goto unlock;
7428         }
7429
7430         /*
7431          * Commands querying/configuring an existing array:
7432          */
7433         /* if we are not initialised yet, only ADD_NEW_DISK, STOP_ARRAY,
7434          * RUN_ARRAY, and GET_ and SET_BITMAP_FILE are allowed */
7435         if ((!mddev->raid_disks && !mddev->external)
7436             && cmd != ADD_NEW_DISK && cmd != STOP_ARRAY
7437             && cmd != RUN_ARRAY && cmd != SET_BITMAP_FILE
7438             && cmd != GET_BITMAP_FILE) {
7439                 err = -ENODEV;
7440                 goto unlock;
7441         }
7442
7443         /*
7444          * Commands even a read-only array can execute:
7445          */
7446         switch (cmd) {
7447         case RESTART_ARRAY_RW:
7448                 err = restart_array(mddev);
7449                 goto unlock;
7450
7451         case STOP_ARRAY:
7452                 err = do_md_stop(mddev, 0, bdev);
7453                 goto unlock;
7454
7455         case STOP_ARRAY_RO:
7456                 err = md_set_readonly(mddev, bdev);
7457                 goto unlock;
7458
7459         case HOT_REMOVE_DISK:
7460                 err = hot_remove_disk(mddev, new_decode_dev(arg));
7461                 goto unlock;
7462
7463         case ADD_NEW_DISK:
7464                 /* We can support ADD_NEW_DISK on read-only arrays
7465                  * only if we are re-adding a preexisting device.
7466                  * So require mddev->pers and MD_DISK_SYNC.
7467                  */
7468                 if (mddev->pers) {
7469                         mdu_disk_info_t info;
7470                         if (copy_from_user(&info, argp, sizeof(info)))
7471                                 err = -EFAULT;
7472                         else if (!(info.state & (1<<MD_DISK_SYNC)))
7473                                 /* Need to clear read-only for this */
7474                                 break;
7475                         else
7476                                 err = add_new_disk(mddev, &info);
7477                         goto unlock;
7478                 }
7479                 break;
7480
7481         case BLKROSET:
7482                 if (get_user(ro, (int __user *)(arg))) {
7483                         err = -EFAULT;
7484                         goto unlock;
7485                 }
7486                 err = -EINVAL;
7487
7488                 /* if the bdev is going readonly the value of mddev->ro
7489                  * does not matter, no writes are coming
7490                  */
7491                 if (ro)
7492                         goto unlock;
7493
7494                 /* are we are already prepared for writes? */
7495                 if (mddev->ro != 1)
7496                         goto unlock;
7497
7498                 /* transitioning to readauto need only happen for
7499                  * arrays that call md_write_start
7500                  */
7501                 if (mddev->pers) {
7502                         err = restart_array(mddev);
7503                         if (err == 0) {
7504                                 mddev->ro = 2;
7505                                 set_disk_ro(mddev->gendisk, 0);
7506                         }
7507                 }
7508                 goto unlock;
7509         }
7510
7511         /*
7512          * The remaining ioctls are changing the state of the
7513          * superblock, so we do not allow them on read-only arrays.
7514          */
7515         if (mddev->ro && mddev->pers) {
7516                 if (mddev->ro == 2) {
7517                         mddev->ro = 0;
7518                         sysfs_notify_dirent_safe(mddev->sysfs_state);
7519                         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7520                         /* mddev_unlock will wake thread */
7521                         /* If a device failed while we were read-only, we
7522                          * need to make sure the metadata is updated now.
7523                          */
7524                         if (test_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags)) {
7525                                 mddev_unlock(mddev);
7526                                 wait_event(mddev->sb_wait,
7527                                            !test_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags) &&
7528                                            !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags));
7529                                 mddev_lock_nointr(mddev);
7530                         }
7531                 } else {
7532                         err = -EROFS;
7533                         goto unlock;
7534                 }
7535         }
7536
7537         switch (cmd) {
7538         case ADD_NEW_DISK:
7539         {
7540                 mdu_disk_info_t info;
7541                 if (copy_from_user(&info, argp, sizeof(info)))
7542                         err = -EFAULT;
7543                 else
7544                         err = add_new_disk(mddev, &info);
7545                 goto unlock;
7546         }
7547
7548         case CLUSTERED_DISK_NACK:
7549                 if (mddev_is_clustered(mddev))
7550                         md_cluster_ops->new_disk_ack(mddev, false);
7551                 else
7552                         err = -EINVAL;
7553                 goto unlock;
7554
7555         case HOT_ADD_DISK:
7556                 err = hot_add_disk(mddev, new_decode_dev(arg));
7557                 goto unlock;
7558
7559         case RUN_ARRAY:
7560                 err = do_md_run(mddev);
7561                 goto unlock;
7562
7563         case SET_BITMAP_FILE:
7564                 err = set_bitmap_file(mddev, (int)arg);
7565                 goto unlock;
7566
7567         default:
7568                 err = -EINVAL;
7569                 goto unlock;
7570         }
7571
7572 unlock:
7573         if (mddev->hold_active == UNTIL_IOCTL &&
7574             err != -EINVAL)
7575                 mddev->hold_active = 0;
7576         mddev_unlock(mddev);
7577 out:
7578         if(did_set_md_closing)
7579                 clear_bit(MD_CLOSING, &mddev->flags);
7580         return err;
7581 }
7582 #ifdef CONFIG_COMPAT
7583 static int md_compat_ioctl(struct block_device *bdev, fmode_t mode,
7584                     unsigned int cmd, unsigned long arg)
7585 {
7586         switch (cmd) {
7587         case HOT_REMOVE_DISK:
7588         case HOT_ADD_DISK:
7589         case SET_DISK_FAULTY:
7590         case SET_BITMAP_FILE:
7591                 /* These take in integer arg, do not convert */
7592                 break;
7593         default:
7594                 arg = (unsigned long)compat_ptr(arg);
7595                 break;
7596         }
7597
7598         return md_ioctl(bdev, mode, cmd, arg);
7599 }
7600 #endif /* CONFIG_COMPAT */
7601
7602 static int md_open(struct block_device *bdev, fmode_t mode)
7603 {
7604         /*
7605          * Succeed if we can lock the mddev, which confirms that
7606          * it isn't being stopped right now.
7607          */
7608         struct mddev *mddev = mddev_find(bdev->bd_dev);
7609         int err;
7610
7611         if (!mddev)
7612                 return -ENODEV;
7613
7614         if (mddev->gendisk != bdev->bd_disk) {
7615                 /* we are racing with mddev_put which is discarding this
7616                  * bd_disk.
7617                  */
7618                 mddev_put(mddev);
7619                 /* Wait until bdev->bd_disk is definitely gone */
7620                 flush_workqueue(md_misc_wq);
7621                 /* Then retry the open from the top */
7622                 return -ERESTARTSYS;
7623         }
7624         BUG_ON(mddev != bdev->bd_disk->private_data);
7625
7626         if ((err = mutex_lock_interruptible(&mddev->open_mutex)))
7627                 goto out;
7628
7629         if (test_bit(MD_CLOSING, &mddev->flags)) {
7630                 mutex_unlock(&mddev->open_mutex);
7631                 err = -ENODEV;
7632                 goto out;
7633         }
7634
7635         err = 0;
7636         atomic_inc(&mddev->openers);
7637         mutex_unlock(&mddev->open_mutex);
7638
7639         check_disk_change(bdev);
7640  out:
7641         if (err)
7642                 mddev_put(mddev);
7643         return err;
7644 }
7645
7646 static void md_release(struct gendisk *disk, fmode_t mode)
7647 {
7648         struct mddev *mddev = disk->private_data;
7649
7650         BUG_ON(!mddev);
7651         atomic_dec(&mddev->openers);
7652         mddev_put(mddev);
7653 }
7654
7655 static int md_media_changed(struct gendisk *disk)
7656 {
7657         struct mddev *mddev = disk->private_data;
7658
7659         return mddev->changed;
7660 }
7661
7662 static int md_revalidate(struct gendisk *disk)
7663 {
7664         struct mddev *mddev = disk->private_data;
7665
7666         mddev->changed = 0;
7667         return 0;
7668 }
7669 static const struct block_device_operations md_fops =
7670 {
7671         .owner          = THIS_MODULE,
7672         .open           = md_open,
7673         .release        = md_release,
7674         .ioctl          = md_ioctl,
7675 #ifdef CONFIG_COMPAT
7676         .compat_ioctl   = md_compat_ioctl,
7677 #endif
7678         .getgeo         = md_getgeo,
7679         .media_changed  = md_media_changed,
7680         .revalidate_disk= md_revalidate,
7681 };
7682
7683 static int md_thread(void *arg)
7684 {
7685         struct md_thread *thread = arg;
7686
7687         /*
7688          * md_thread is a 'system-thread', it's priority should be very
7689          * high. We avoid resource deadlocks individually in each
7690          * raid personality. (RAID5 does preallocation) We also use RR and
7691          * the very same RT priority as kswapd, thus we will never get
7692          * into a priority inversion deadlock.
7693          *
7694          * we definitely have to have equal or higher priority than
7695          * bdflush, otherwise bdflush will deadlock if there are too
7696          * many dirty RAID5 blocks.
7697          */
7698
7699         allow_signal(SIGKILL);
7700         while (!kthread_should_stop()) {
7701
7702                 /* We need to wait INTERRUPTIBLE so that
7703                  * we don't add to the load-average.
7704                  * That means we need to be sure no signals are
7705                  * pending
7706                  */
7707                 if (signal_pending(current))
7708                         flush_signals(current);
7709
7710                 wait_event_interruptible_timeout
7711                         (thread->wqueue,
7712                          test_bit(THREAD_WAKEUP, &thread->flags)
7713                          || kthread_should_stop() || kthread_should_park(),
7714                          thread->timeout);
7715
7716                 clear_bit(THREAD_WAKEUP, &thread->flags);
7717                 if (kthread_should_park())
7718                         kthread_parkme();
7719                 if (!kthread_should_stop())
7720                         thread->run(thread);
7721         }
7722
7723         return 0;
7724 }
7725
7726 void md_wakeup_thread(struct md_thread *thread)
7727 {
7728         if (thread) {
7729                 pr_debug("md: waking up MD thread %s.\n", thread->tsk->comm);
7730                 set_bit(THREAD_WAKEUP, &thread->flags);
7731                 wake_up(&thread->wqueue);
7732         }
7733 }
7734 EXPORT_SYMBOL(md_wakeup_thread);
7735
7736 struct md_thread *md_register_thread(void (*run) (struct md_thread *),
7737                 struct mddev *mddev, const char *name)
7738 {
7739         struct md_thread *thread;
7740
7741         thread = kzalloc(sizeof(struct md_thread), GFP_KERNEL);
7742         if (!thread)
7743                 return NULL;
7744
7745         init_waitqueue_head(&thread->wqueue);
7746
7747         thread->run = run;
7748         thread->mddev = mddev;
7749         thread->timeout = MAX_SCHEDULE_TIMEOUT;
7750         thread->tsk = kthread_run(md_thread, thread,
7751                                   "%s_%s",
7752                                   mdname(thread->mddev),
7753                                   name);
7754         if (IS_ERR(thread->tsk)) {
7755                 kfree(thread);
7756                 return NULL;
7757         }
7758         return thread;
7759 }
7760 EXPORT_SYMBOL(md_register_thread);
7761
7762 void md_unregister_thread(struct md_thread **threadp)
7763 {
7764         struct md_thread *thread = *threadp;
7765         if (!thread)
7766                 return;
7767         pr_debug("interrupting MD-thread pid %d\n", task_pid_nr(thread->tsk));
7768         /* Locking ensures that mddev_unlock does not wake_up a
7769          * non-existent thread
7770          */
7771         spin_lock(&pers_lock);
7772         *threadp = NULL;
7773         spin_unlock(&pers_lock);
7774
7775         kthread_stop(thread->tsk);
7776         kfree(thread);
7777 }
7778 EXPORT_SYMBOL(md_unregister_thread);
7779
7780 void md_error(struct mddev *mddev, struct md_rdev *rdev)
7781 {
7782         if (!rdev || test_bit(Faulty, &rdev->flags))
7783                 return;
7784
7785         if (!mddev->pers || !mddev->pers->error_handler)
7786                 return;
7787         mddev->pers->error_handler(mddev,rdev);
7788         if (mddev->degraded)
7789                 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
7790         sysfs_notify_dirent_safe(rdev->sysfs_state);
7791         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
7792         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7793         md_wakeup_thread(mddev->thread);
7794         if (mddev->event_work.func)
7795                 queue_work(md_misc_wq, &mddev->event_work);
7796         md_new_event(mddev);
7797 }
7798 EXPORT_SYMBOL(md_error);
7799
7800 /* seq_file implementation /proc/mdstat */
7801
7802 static void status_unused(struct seq_file *seq)
7803 {
7804         int i = 0;
7805         struct md_rdev *rdev;
7806
7807         seq_printf(seq, "unused devices: ");
7808
7809         list_for_each_entry(rdev, &pending_raid_disks, same_set) {
7810                 char b[BDEVNAME_SIZE];
7811                 i++;
7812                 seq_printf(seq, "%s ",
7813                               bdevname(rdev->bdev,b));
7814         }
7815         if (!i)
7816                 seq_printf(seq, "<none>");
7817
7818         seq_printf(seq, "\n");
7819 }
7820
7821 static int status_resync(struct seq_file *seq, struct mddev *mddev)
7822 {
7823         sector_t max_sectors, resync, res;
7824         unsigned long dt, db = 0;
7825         sector_t rt, curr_mark_cnt, resync_mark_cnt;
7826         int scale, recovery_active;
7827         unsigned int per_milli;
7828
7829         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ||
7830             test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
7831                 max_sectors = mddev->resync_max_sectors;
7832         else
7833                 max_sectors = mddev->dev_sectors;
7834
7835         resync = mddev->curr_resync;
7836         if (resync <= 3) {
7837                 if (test_bit(MD_RECOVERY_DONE, &mddev->recovery))
7838                         /* Still cleaning up */
7839                         resync = max_sectors;
7840         } else if (resync > max_sectors)
7841                 resync = max_sectors;
7842         else
7843                 resync -= atomic_read(&mddev->recovery_active);
7844
7845         if (resync == 0) {
7846                 if (test_bit(MD_RESYNCING_REMOTE, &mddev->recovery)) {
7847                         struct md_rdev *rdev;
7848
7849                         rdev_for_each(rdev, mddev)
7850                                 if (rdev->raid_disk >= 0 &&
7851                                     !test_bit(Faulty, &rdev->flags) &&
7852                                     rdev->recovery_offset != MaxSector &&
7853                                     rdev->recovery_offset) {
7854                                         seq_printf(seq, "\trecover=REMOTE");
7855                                         return 1;
7856                                 }
7857                         if (mddev->reshape_position != MaxSector)
7858                                 seq_printf(seq, "\treshape=REMOTE");
7859                         else
7860                                 seq_printf(seq, "\tresync=REMOTE");
7861                         return 1;
7862                 }
7863                 if (mddev->recovery_cp < MaxSector) {
7864                         seq_printf(seq, "\tresync=PENDING");
7865                         return 1;
7866                 }
7867                 return 0;
7868         }
7869         if (resync < 3) {
7870                 seq_printf(seq, "\tresync=DELAYED");
7871                 return 1;
7872         }
7873
7874         WARN_ON(max_sectors == 0);
7875         /* Pick 'scale' such that (resync>>scale)*1000 will fit
7876          * in a sector_t, and (max_sectors>>scale) will fit in a
7877          * u32, as those are the requirements for sector_div.
7878          * Thus 'scale' must be at least 10
7879          */
7880         scale = 10;
7881         if (sizeof(sector_t) > sizeof(unsigned long)) {
7882                 while ( max_sectors/2 > (1ULL<<(scale+32)))
7883                         scale++;
7884         }
7885         res = (resync>>scale)*1000;
7886         sector_div(res, (u32)((max_sectors>>scale)+1));
7887
7888         per_milli = res;
7889         {
7890                 int i, x = per_milli/50, y = 20-x;
7891                 seq_printf(seq, "[");
7892                 for (i = 0; i < x; i++)
7893                         seq_printf(seq, "=");
7894                 seq_printf(seq, ">");
7895                 for (i = 0; i < y; i++)
7896                         seq_printf(seq, ".");
7897                 seq_printf(seq, "] ");
7898         }
7899         seq_printf(seq, " %s =%3u.%u%% (%llu/%llu)",
7900                    (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)?
7901                     "reshape" :
7902                     (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)?
7903                      "check" :
7904                      (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ?
7905                       "resync" : "recovery"))),
7906                    per_milli/10, per_milli % 10,
7907                    (unsigned long long) resync/2,
7908                    (unsigned long long) max_sectors/2);
7909
7910         /*
7911          * dt: time from mark until now
7912          * db: blocks written from mark until now
7913          * rt: remaining time
7914          *
7915          * rt is a sector_t, which is always 64bit now. We are keeping
7916          * the original algorithm, but it is not really necessary.
7917          *
7918          * Original algorithm:
7919          *   So we divide before multiply in case it is 32bit and close
7920          *   to the limit.
7921          *   We scale the divisor (db) by 32 to avoid losing precision
7922          *   near the end of resync when the number of remaining sectors
7923          *   is close to 'db'.
7924          *   We then divide rt by 32 after multiplying by db to compensate.
7925          *   The '+1' avoids division by zero if db is very small.
7926          */
7927         dt = ((jiffies - mddev->resync_mark) / HZ);
7928         if (!dt) dt++;
7929
7930         curr_mark_cnt = mddev->curr_mark_cnt;
7931         recovery_active = atomic_read(&mddev->recovery_active);
7932         resync_mark_cnt = mddev->resync_mark_cnt;
7933
7934         if (curr_mark_cnt >= (recovery_active + resync_mark_cnt))
7935                 db = curr_mark_cnt - (recovery_active + resync_mark_cnt);
7936
7937         rt = max_sectors - resync;    /* number of remaining sectors */
7938         rt = div64_u64(rt, db/32+1);
7939         rt *= dt;
7940         rt >>= 5;
7941
7942         seq_printf(seq, " finish=%lu.%lumin", (unsigned long)rt / 60,
7943                    ((unsigned long)rt % 60)/6);
7944
7945         seq_printf(seq, " speed=%ldK/sec", db/2/dt);
7946         return 1;
7947 }
7948
7949 static void *md_seq_start(struct seq_file *seq, loff_t *pos)
7950 {
7951         struct list_head *tmp;
7952         loff_t l = *pos;
7953         struct mddev *mddev;
7954
7955         if (l >= 0x10000)
7956                 return NULL;
7957         if (!l--)
7958                 /* header */
7959                 return (void*)1;
7960
7961         spin_lock(&all_mddevs_lock);
7962         list_for_each(tmp,&all_mddevs)
7963                 if (!l--) {
7964                         mddev = list_entry(tmp, struct mddev, all_mddevs);
7965                         mddev_get(mddev);
7966                         spin_unlock(&all_mddevs_lock);
7967                         return mddev;
7968                 }
7969         spin_unlock(&all_mddevs_lock);
7970         if (!l--)
7971                 return (void*)2;/* tail */
7972         return NULL;
7973 }
7974
7975 static void *md_seq_next(struct seq_file *seq, void *v, loff_t *pos)
7976 {
7977         struct list_head *tmp;
7978         struct mddev *next_mddev, *mddev = v;
7979
7980         ++*pos;
7981         if (v == (void*)2)
7982                 return NULL;
7983
7984         spin_lock(&all_mddevs_lock);
7985         if (v == (void*)1)
7986                 tmp = all_mddevs.next;
7987         else
7988                 tmp = mddev->all_mddevs.next;
7989         if (tmp != &all_mddevs)
7990                 next_mddev = mddev_get(list_entry(tmp,struct mddev,all_mddevs));
7991         else {
7992                 next_mddev = (void*)2;
7993                 *pos = 0x10000;
7994         }
7995         spin_unlock(&all_mddevs_lock);
7996
7997         if (v != (void*)1)
7998                 mddev_put(mddev);
7999         return next_mddev;
8000
8001 }
8002
8003 static void md_seq_stop(struct seq_file *seq, void *v)
8004 {
8005         struct mddev *mddev = v;
8006
8007         if (mddev && v != (void*)1 && v != (void*)2)
8008                 mddev_put(mddev);
8009 }
8010
8011 static int md_seq_show(struct seq_file *seq, void *v)
8012 {
8013         struct mddev *mddev = v;
8014         sector_t sectors;
8015         struct md_rdev *rdev;
8016
8017         if (v == (void*)1) {
8018                 struct md_personality *pers;
8019                 seq_printf(seq, "Personalities : ");
8020                 spin_lock(&pers_lock);
8021                 list_for_each_entry(pers, &pers_list, list)
8022                         seq_printf(seq, "[%s] ", pers->name);
8023
8024                 spin_unlock(&pers_lock);
8025                 seq_printf(seq, "\n");
8026                 seq->poll_event = atomic_read(&md_event_count);
8027                 return 0;
8028         }
8029         if (v == (void*)2) {
8030                 status_unused(seq);
8031                 return 0;
8032         }
8033
8034         spin_lock(&mddev->lock);
8035         if (mddev->pers || mddev->raid_disks || !list_empty(&mddev->disks)) {
8036                 seq_printf(seq, "%s : %sactive", mdname(mddev),
8037                                                 mddev->pers ? "" : "in");
8038                 if (mddev->pers) {
8039                         if (mddev->ro==1)
8040                                 seq_printf(seq, " (read-only)");
8041                         if (mddev->ro==2)
8042                                 seq_printf(seq, " (auto-read-only)");
8043                         seq_printf(seq, " %s", mddev->pers->name);
8044                 }
8045
8046                 sectors = 0;
8047                 rcu_read_lock();
8048                 rdev_for_each_rcu(rdev, mddev) {
8049                         char b[BDEVNAME_SIZE];
8050                         seq_printf(seq, " %s[%d]",
8051                                 bdevname(rdev->bdev,b), rdev->desc_nr);
8052                         if (test_bit(WriteMostly, &rdev->flags))
8053                                 seq_printf(seq, "(W)");
8054                         if (test_bit(Journal, &rdev->flags))
8055                                 seq_printf(seq, "(J)");
8056                         if (test_bit(Faulty, &rdev->flags)) {
8057                                 seq_printf(seq, "(F)");
8058                                 continue;
8059                         }
8060                         if (rdev->raid_disk < 0)
8061                                 seq_printf(seq, "(S)"); /* spare */
8062                         if (test_bit(Replacement, &rdev->flags))
8063                                 seq_printf(seq, "(R)");
8064                         sectors += rdev->sectors;
8065                 }
8066                 rcu_read_unlock();
8067
8068                 if (!list_empty(&mddev->disks)) {
8069                         if (mddev->pers)
8070                                 seq_printf(seq, "\n      %llu blocks",
8071                                            (unsigned long long)
8072                                            mddev->array_sectors / 2);
8073                         else
8074                                 seq_printf(seq, "\n      %llu blocks",
8075                                            (unsigned long long)sectors / 2);
8076                 }
8077                 if (mddev->persistent) {
8078                         if (mddev->major_version != 0 ||
8079                             mddev->minor_version != 90) {
8080                                 seq_printf(seq," super %d.%d",
8081                                            mddev->major_version,
8082                                            mddev->minor_version);
8083                         }
8084                 } else if (mddev->external)
8085                         seq_printf(seq, " super external:%s",
8086                                    mddev->metadata_type);
8087                 else
8088                         seq_printf(seq, " super non-persistent");
8089
8090                 if (mddev->pers) {
8091                         mddev->pers->status(seq, mddev);
8092                         seq_printf(seq, "\n      ");
8093                         if (mddev->pers->sync_request) {
8094                                 if (status_resync(seq, mddev))
8095                                         seq_printf(seq, "\n      ");
8096                         }
8097                 } else
8098                         seq_printf(seq, "\n       ");
8099
8100                 md_bitmap_status(seq, mddev->bitmap);
8101
8102                 seq_printf(seq, "\n");
8103         }
8104         spin_unlock(&mddev->lock);
8105
8106         return 0;
8107 }
8108
8109 static const struct seq_operations md_seq_ops = {
8110         .start  = md_seq_start,
8111         .next   = md_seq_next,
8112         .stop   = md_seq_stop,
8113         .show   = md_seq_show,
8114 };
8115
8116 static int md_seq_open(struct inode *inode, struct file *file)
8117 {
8118         struct seq_file *seq;
8119         int error;
8120
8121         error = seq_open(file, &md_seq_ops);
8122         if (error)
8123                 return error;
8124
8125         seq = file->private_data;
8126         seq->poll_event = atomic_read(&md_event_count);
8127         return error;
8128 }
8129
8130 static int md_unloading;
8131 static __poll_t mdstat_poll(struct file *filp, poll_table *wait)
8132 {
8133         struct seq_file *seq = filp->private_data;
8134         __poll_t mask;
8135
8136         if (md_unloading)
8137                 return EPOLLIN|EPOLLRDNORM|EPOLLERR|EPOLLPRI;
8138         poll_wait(filp, &md_event_waiters, wait);
8139
8140         /* always allow read */
8141         mask = EPOLLIN | EPOLLRDNORM;
8142
8143         if (seq->poll_event != atomic_read(&md_event_count))
8144                 mask |= EPOLLERR | EPOLLPRI;
8145         return mask;
8146 }
8147
8148 static const struct file_operations md_seq_fops = {
8149         .owner          = THIS_MODULE,
8150         .open           = md_seq_open,
8151         .read           = seq_read,
8152         .llseek         = seq_lseek,
8153         .release        = seq_release,
8154         .poll           = mdstat_poll,
8155 };
8156
8157 int register_md_personality(struct md_personality *p)
8158 {
8159         pr_debug("md: %s personality registered for level %d\n",
8160                  p->name, p->level);
8161         spin_lock(&pers_lock);
8162         list_add_tail(&p->list, &pers_list);
8163         spin_unlock(&pers_lock);
8164         return 0;
8165 }
8166 EXPORT_SYMBOL(register_md_personality);
8167
8168 int unregister_md_personality(struct md_personality *p)
8169 {
8170         pr_debug("md: %s personality unregistered\n", p->name);
8171         spin_lock(&pers_lock);
8172         list_del_init(&p->list);
8173         spin_unlock(&pers_lock);
8174         return 0;
8175 }
8176 EXPORT_SYMBOL(unregister_md_personality);
8177
8178 int register_md_cluster_operations(struct md_cluster_operations *ops,
8179                                    struct module *module)
8180 {
8181         int ret = 0;
8182         spin_lock(&pers_lock);
8183         if (md_cluster_ops != NULL)
8184                 ret = -EALREADY;
8185         else {
8186                 md_cluster_ops = ops;
8187                 md_cluster_mod = module;
8188         }
8189         spin_unlock(&pers_lock);
8190         return ret;
8191 }
8192 EXPORT_SYMBOL(register_md_cluster_operations);
8193
8194 int unregister_md_cluster_operations(void)
8195 {
8196         spin_lock(&pers_lock);
8197         md_cluster_ops = NULL;
8198         spin_unlock(&pers_lock);
8199         return 0;
8200 }
8201 EXPORT_SYMBOL(unregister_md_cluster_operations);
8202
8203 int md_setup_cluster(struct mddev *mddev, int nodes)
8204 {
8205         if (!md_cluster_ops)
8206                 request_module("md-cluster");
8207         spin_lock(&pers_lock);
8208         /* ensure module won't be unloaded */
8209         if (!md_cluster_ops || !try_module_get(md_cluster_mod)) {
8210                 pr_warn("can't find md-cluster module or get it's reference.\n");
8211                 spin_unlock(&pers_lock);
8212                 return -ENOENT;
8213         }
8214         spin_unlock(&pers_lock);
8215
8216         return md_cluster_ops->join(mddev, nodes);
8217 }
8218
8219 void md_cluster_stop(struct mddev *mddev)
8220 {
8221         if (!md_cluster_ops)
8222                 return;
8223         md_cluster_ops->leave(mddev);
8224         module_put(md_cluster_mod);
8225 }
8226
8227 static int is_mddev_idle(struct mddev *mddev, int init)
8228 {
8229         struct md_rdev *rdev;
8230         int idle;
8231         int curr_events;
8232
8233         idle = 1;
8234         rcu_read_lock();
8235         rdev_for_each_rcu(rdev, mddev) {
8236                 struct gendisk *disk = rdev->bdev->bd_contains->bd_disk;
8237                 curr_events = (int)part_stat_read_accum(&disk->part0, sectors) -
8238                               atomic_read(&disk->sync_io);
8239                 /* sync IO will cause sync_io to increase before the disk_stats
8240                  * as sync_io is counted when a request starts, and
8241                  * disk_stats is counted when it completes.
8242                  * So resync activity will cause curr_events to be smaller than
8243                  * when there was no such activity.
8244                  * non-sync IO will cause disk_stat to increase without
8245                  * increasing sync_io so curr_events will (eventually)
8246                  * be larger than it was before.  Once it becomes
8247                  * substantially larger, the test below will cause
8248                  * the array to appear non-idle, and resync will slow
8249                  * down.
8250                  * If there is a lot of outstanding resync activity when
8251                  * we set last_event to curr_events, then all that activity
8252                  * completing might cause the array to appear non-idle
8253                  * and resync will be slowed down even though there might
8254                  * not have been non-resync activity.  This will only
8255                  * happen once though.  'last_events' will soon reflect
8256                  * the state where there is little or no outstanding
8257                  * resync requests, and further resync activity will
8258                  * always make curr_events less than last_events.
8259                  *
8260                  */
8261                 if (init || curr_events - rdev->last_events > 64) {
8262                         rdev->last_events = curr_events;
8263                         idle = 0;
8264                 }
8265         }
8266         rcu_read_unlock();
8267         return idle;
8268 }
8269
8270 void md_done_sync(struct mddev *mddev, int blocks, int ok)
8271 {
8272         /* another "blocks" (512byte) blocks have been synced */
8273         atomic_sub(blocks, &mddev->recovery_active);
8274         wake_up(&mddev->recovery_wait);
8275         if (!ok) {
8276                 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
8277                 set_bit(MD_RECOVERY_ERROR, &mddev->recovery);
8278                 md_wakeup_thread(mddev->thread);
8279                 // stop recovery, signal do_sync ....
8280         }
8281 }
8282 EXPORT_SYMBOL(md_done_sync);
8283
8284 /* md_write_start(mddev, bi)
8285  * If we need to update some array metadata (e.g. 'active' flag
8286  * in superblock) before writing, schedule a superblock update
8287  * and wait for it to complete.
8288  * A return value of 'false' means that the write wasn't recorded
8289  * and cannot proceed as the array is being suspend.
8290  */
8291 bool md_write_start(struct mddev *mddev, struct bio *bi)
8292 {
8293         int did_change = 0;
8294
8295         if (bio_data_dir(bi) != WRITE)
8296                 return true;
8297
8298         BUG_ON(mddev->ro == 1);
8299         if (mddev->ro == 2) {
8300                 /* need to switch to read/write */
8301                 mddev->ro = 0;
8302                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
8303                 md_wakeup_thread(mddev->thread);
8304                 md_wakeup_thread(mddev->sync_thread);
8305                 did_change = 1;
8306         }
8307         rcu_read_lock();
8308         percpu_ref_get(&mddev->writes_pending);
8309         smp_mb(); /* Match smp_mb in set_in_sync() */
8310         if (mddev->safemode == 1)
8311                 mddev->safemode = 0;
8312         /* sync_checkers is always 0 when writes_pending is in per-cpu mode */
8313         if (mddev->in_sync || mddev->sync_checkers) {
8314                 spin_lock(&mddev->lock);
8315                 if (mddev->in_sync) {
8316                         mddev->in_sync = 0;
8317                         set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
8318                         set_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
8319                         md_wakeup_thread(mddev->thread);
8320                         did_change = 1;
8321                 }
8322                 spin_unlock(&mddev->lock);
8323         }
8324         rcu_read_unlock();
8325         if (did_change)
8326                 sysfs_notify_dirent_safe(mddev->sysfs_state);
8327         if (!mddev->has_superblocks)
8328                 return true;
8329         wait_event(mddev->sb_wait,
8330                    !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags) ||
8331                    mddev->suspended);
8332         if (test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags)) {
8333                 percpu_ref_put(&mddev->writes_pending);
8334                 return false;
8335         }
8336         return true;
8337 }
8338 EXPORT_SYMBOL(md_write_start);
8339
8340 /* md_write_inc can only be called when md_write_start() has
8341  * already been called at least once of the current request.
8342  * It increments the counter and is useful when a single request
8343  * is split into several parts.  Each part causes an increment and
8344  * so needs a matching md_write_end().
8345  * Unlike md_write_start(), it is safe to call md_write_inc() inside
8346  * a spinlocked region.
8347  */
8348 void md_write_inc(struct mddev *mddev, struct bio *bi)
8349 {
8350         if (bio_data_dir(bi) != WRITE)
8351                 return;
8352         WARN_ON_ONCE(mddev->in_sync || mddev->ro);
8353         percpu_ref_get(&mddev->writes_pending);
8354 }
8355 EXPORT_SYMBOL(md_write_inc);
8356
8357 void md_write_end(struct mddev *mddev)
8358 {
8359         percpu_ref_put(&mddev->writes_pending);
8360
8361         if (mddev->safemode == 2)
8362                 md_wakeup_thread(mddev->thread);
8363         else if (mddev->safemode_delay)
8364                 /* The roundup() ensures this only performs locking once
8365                  * every ->safemode_delay jiffies
8366                  */
8367                 mod_timer(&mddev->safemode_timer,
8368                           roundup(jiffies, mddev->safemode_delay) +
8369                           mddev->safemode_delay);
8370 }
8371
8372 EXPORT_SYMBOL(md_write_end);
8373
8374 /* md_allow_write(mddev)
8375  * Calling this ensures that the array is marked 'active' so that writes
8376  * may proceed without blocking.  It is important to call this before
8377  * attempting a GFP_KERNEL allocation while holding the mddev lock.
8378  * Must be called with mddev_lock held.
8379  */
8380 void md_allow_write(struct mddev *mddev)
8381 {
8382         if (!mddev->pers)
8383                 return;
8384         if (mddev->ro)
8385                 return;
8386         if (!mddev->pers->sync_request)
8387                 return;
8388
8389         spin_lock(&mddev->lock);
8390         if (mddev->in_sync) {
8391                 mddev->in_sync = 0;
8392                 set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
8393                 set_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
8394                 if (mddev->safemode_delay &&
8395                     mddev->safemode == 0)
8396                         mddev->safemode = 1;
8397                 spin_unlock(&mddev->lock);
8398                 md_update_sb(mddev, 0);
8399                 sysfs_notify_dirent_safe(mddev->sysfs_state);
8400                 /* wait for the dirty state to be recorded in the metadata */
8401                 wait_event(mddev->sb_wait,
8402                            !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags));
8403         } else
8404                 spin_unlock(&mddev->lock);
8405 }
8406 EXPORT_SYMBOL_GPL(md_allow_write);
8407
8408 #define SYNC_MARKS      10
8409 #define SYNC_MARK_STEP  (3*HZ)
8410 #define UPDATE_FREQUENCY (5*60*HZ)
8411 void md_do_sync(struct md_thread *thread)
8412 {
8413         struct mddev *mddev = thread->mddev;
8414         struct mddev *mddev2;
8415         unsigned int currspeed = 0, window;
8416         sector_t max_sectors,j, io_sectors, recovery_done;
8417         unsigned long mark[SYNC_MARKS];
8418         unsigned long update_time;
8419         sector_t mark_cnt[SYNC_MARKS];
8420         int last_mark,m;
8421         struct list_head *tmp;
8422         sector_t last_check;
8423         int skipped = 0;
8424         struct md_rdev *rdev;
8425         char *desc, *action = NULL;
8426         struct blk_plug plug;
8427         int ret;
8428
8429         /* just incase thread restarts... */
8430         if (test_bit(MD_RECOVERY_DONE, &mddev->recovery) ||
8431             test_bit(MD_RECOVERY_WAIT, &mddev->recovery))
8432                 return;
8433         if (mddev->ro) {/* never try to sync a read-only array */
8434                 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
8435                 return;
8436         }
8437
8438         if (mddev_is_clustered(mddev)) {
8439                 ret = md_cluster_ops->resync_start(mddev);
8440                 if (ret)
8441                         goto skip;
8442
8443                 set_bit(MD_CLUSTER_RESYNC_LOCKED, &mddev->flags);
8444                 if (!(test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ||
8445                         test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) ||
8446                         test_bit(MD_RECOVERY_RECOVER, &mddev->recovery))
8447                      && ((unsigned long long)mddev->curr_resync_completed
8448                          < (unsigned long long)mddev->resync_max_sectors))
8449                         goto skip;
8450         }
8451
8452         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
8453                 if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)) {
8454                         desc = "data-check";
8455                         action = "check";
8456                 } else if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
8457                         desc = "requested-resync";
8458                         action = "repair";
8459                 } else
8460                         desc = "resync";
8461         } else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
8462                 desc = "reshape";
8463         else
8464                 desc = "recovery";
8465
8466         mddev->last_sync_action = action ?: desc;
8467
8468         /* we overload curr_resync somewhat here.
8469          * 0 == not engaged in resync at all
8470          * 2 == checking that there is no conflict with another sync
8471          * 1 == like 2, but have yielded to allow conflicting resync to
8472          *              commence
8473          * other == active in resync - this many blocks
8474          *
8475          * Before starting a resync we must have set curr_resync to
8476          * 2, and then checked that every "conflicting" array has curr_resync
8477          * less than ours.  When we find one that is the same or higher
8478          * we wait on resync_wait.  To avoid deadlock, we reduce curr_resync
8479          * to 1 if we choose to yield (based arbitrarily on address of mddev structure).
8480          * This will mean we have to start checking from the beginning again.
8481          *
8482          */
8483
8484         do {
8485                 int mddev2_minor = -1;
8486                 mddev->curr_resync = 2;
8487
8488         try_again:
8489                 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8490                         goto skip;
8491                 for_each_mddev(mddev2, tmp) {
8492                         if (mddev2 == mddev)
8493                                 continue;
8494                         if (!mddev->parallel_resync
8495                         &&  mddev2->curr_resync
8496                         &&  match_mddev_units(mddev, mddev2)) {
8497                                 DEFINE_WAIT(wq);
8498                                 if (mddev < mddev2 && mddev->curr_resync == 2) {
8499                                         /* arbitrarily yield */
8500                                         mddev->curr_resync = 1;
8501                                         wake_up(&resync_wait);
8502                                 }
8503                                 if (mddev > mddev2 && mddev->curr_resync == 1)
8504                                         /* no need to wait here, we can wait the next
8505                                          * time 'round when curr_resync == 2
8506                                          */
8507                                         continue;
8508                                 /* We need to wait 'interruptible' so as not to
8509                                  * contribute to the load average, and not to
8510                                  * be caught by 'softlockup'
8511                                  */
8512                                 prepare_to_wait(&resync_wait, &wq, TASK_INTERRUPTIBLE);
8513                                 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
8514                                     mddev2->curr_resync >= mddev->curr_resync) {
8515                                         if (mddev2_minor != mddev2->md_minor) {
8516                                                 mddev2_minor = mddev2->md_minor;
8517                                                 pr_info("md: delaying %s of %s until %s has finished (they share one or more physical units)\n",
8518                                                         desc, mdname(mddev),
8519                                                         mdname(mddev2));
8520                                         }
8521                                         mddev_put(mddev2);
8522                                         if (signal_pending(current))
8523                                                 flush_signals(current);
8524                                         schedule();
8525                                         finish_wait(&resync_wait, &wq);
8526                                         goto try_again;
8527                                 }
8528                                 finish_wait(&resync_wait, &wq);
8529                         }
8530                 }
8531         } while (mddev->curr_resync < 2);
8532
8533         j = 0;
8534         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
8535                 /* resync follows the size requested by the personality,
8536                  * which defaults to physical size, but can be virtual size
8537                  */
8538                 max_sectors = mddev->resync_max_sectors;
8539                 atomic64_set(&mddev->resync_mismatches, 0);
8540                 /* we don't use the checkpoint if there's a bitmap */
8541                 if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
8542                         j = mddev->resync_min;
8543                 else if (!mddev->bitmap)
8544                         j = mddev->recovery_cp;
8545
8546         } else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
8547                 max_sectors = mddev->resync_max_sectors;
8548                 /*
8549                  * If the original node aborts reshaping then we continue the
8550                  * reshaping, so set j again to avoid restart reshape from the
8551                  * first beginning
8552                  */
8553                 if (mddev_is_clustered(mddev) &&
8554                     mddev->reshape_position != MaxSector)
8555                         j = mddev->reshape_position;
8556         } else {
8557                 /* recovery follows the physical size of devices */
8558                 max_sectors = mddev->dev_sectors;
8559                 j = MaxSector;
8560                 rcu_read_lock();
8561                 rdev_for_each_rcu(rdev, mddev)
8562                         if (rdev->raid_disk >= 0 &&
8563                             !test_bit(Journal, &rdev->flags) &&
8564                             !test_bit(Faulty, &rdev->flags) &&
8565                             !test_bit(In_sync, &rdev->flags) &&
8566                             rdev->recovery_offset < j)
8567                                 j = rdev->recovery_offset;
8568                 rcu_read_unlock();
8569
8570                 /* If there is a bitmap, we need to make sure all
8571                  * writes that started before we added a spare
8572                  * complete before we start doing a recovery.
8573                  * Otherwise the write might complete and (via
8574                  * bitmap_endwrite) set a bit in the bitmap after the
8575                  * recovery has checked that bit and skipped that
8576                  * region.
8577                  */
8578                 if (mddev->bitmap) {
8579                         mddev->pers->quiesce(mddev, 1);
8580                         mddev->pers->quiesce(mddev, 0);
8581                 }
8582         }
8583
8584         pr_info("md: %s of RAID array %s\n", desc, mdname(mddev));
8585         pr_debug("md: minimum _guaranteed_  speed: %d KB/sec/disk.\n", speed_min(mddev));
8586         pr_debug("md: using maximum available idle IO bandwidth (but not more than %d KB/sec) for %s.\n",
8587                  speed_max(mddev), desc);
8588
8589         is_mddev_idle(mddev, 1); /* this initializes IO event counters */
8590
8591         io_sectors = 0;
8592         for (m = 0; m < SYNC_MARKS; m++) {
8593                 mark[m] = jiffies;
8594                 mark_cnt[m] = io_sectors;
8595         }
8596         last_mark = 0;
8597         mddev->resync_mark = mark[last_mark];
8598         mddev->resync_mark_cnt = mark_cnt[last_mark];
8599
8600         /*
8601          * Tune reconstruction:
8602          */
8603         window = 32 * (PAGE_SIZE / 512);
8604         pr_debug("md: using %dk window, over a total of %lluk.\n",
8605                  window/2, (unsigned long long)max_sectors/2);
8606
8607         atomic_set(&mddev->recovery_active, 0);
8608         last_check = 0;
8609
8610         if (j>2) {
8611                 pr_debug("md: resuming %s of %s from checkpoint.\n",
8612                          desc, mdname(mddev));
8613                 mddev->curr_resync = j;
8614         } else
8615                 mddev->curr_resync = 3; /* no longer delayed */
8616         mddev->curr_resync_completed = j;
8617         sysfs_notify(&mddev->kobj, NULL, "sync_completed");
8618         md_new_event(mddev);
8619         update_time = jiffies;
8620
8621         blk_start_plug(&plug);
8622         while (j < max_sectors) {
8623                 sector_t sectors;
8624
8625                 skipped = 0;
8626
8627                 if (!test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
8628                     ((mddev->curr_resync > mddev->curr_resync_completed &&
8629                       (mddev->curr_resync - mddev->curr_resync_completed)
8630                       > (max_sectors >> 4)) ||
8631                      time_after_eq(jiffies, update_time + UPDATE_FREQUENCY) ||
8632                      (j - mddev->curr_resync_completed)*2
8633                      >= mddev->resync_max - mddev->curr_resync_completed ||
8634                      mddev->curr_resync_completed > mddev->resync_max
8635                             )) {
8636                         /* time to update curr_resync_completed */
8637                         wait_event(mddev->recovery_wait,
8638                                    atomic_read(&mddev->recovery_active) == 0);
8639                         mddev->curr_resync_completed = j;
8640                         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) &&
8641                             j > mddev->recovery_cp)
8642                                 mddev->recovery_cp = j;
8643                         update_time = jiffies;
8644                         set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
8645                         sysfs_notify(&mddev->kobj, NULL, "sync_completed");
8646                 }
8647
8648                 while (j >= mddev->resync_max &&
8649                        !test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
8650                         /* As this condition is controlled by user-space,
8651                          * we can block indefinitely, so use '_interruptible'
8652                          * to avoid triggering warnings.
8653                          */
8654                         flush_signals(current); /* just in case */
8655                         wait_event_interruptible(mddev->recovery_wait,
8656                                                  mddev->resync_max > j
8657                                                  || test_bit(MD_RECOVERY_INTR,
8658                                                              &mddev->recovery));
8659                 }
8660
8661                 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8662                         break;
8663
8664                 sectors = mddev->pers->sync_request(mddev, j, &skipped);
8665                 if (sectors == 0) {
8666                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
8667                         break;
8668                 }
8669
8670                 if (!skipped) { /* actual IO requested */
8671                         io_sectors += sectors;
8672                         atomic_add(sectors, &mddev->recovery_active);
8673                 }
8674
8675                 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8676                         break;
8677
8678                 j += sectors;
8679                 if (j > max_sectors)
8680                         /* when skipping, extra large numbers can be returned. */
8681                         j = max_sectors;
8682                 if (j > 2)
8683                         mddev->curr_resync = j;
8684                 mddev->curr_mark_cnt = io_sectors;
8685                 if (last_check == 0)
8686                         /* this is the earliest that rebuild will be
8687                          * visible in /proc/mdstat
8688                          */
8689                         md_new_event(mddev);
8690
8691                 if (last_check + window > io_sectors || j == max_sectors)
8692                         continue;
8693
8694                 last_check = io_sectors;
8695         repeat:
8696                 if (time_after_eq(jiffies, mark[last_mark] + SYNC_MARK_STEP )) {
8697                         /* step marks */
8698                         int next = (last_mark+1) % SYNC_MARKS;
8699
8700                         mddev->resync_mark = mark[next];
8701                         mddev->resync_mark_cnt = mark_cnt[next];
8702                         mark[next] = jiffies;
8703                         mark_cnt[next] = io_sectors - atomic_read(&mddev->recovery_active);
8704                         last_mark = next;
8705                 }
8706
8707                 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8708                         break;
8709
8710                 /*
8711                  * this loop exits only if either when we are slower than
8712                  * the 'hard' speed limit, or the system was IO-idle for
8713                  * a jiffy.
8714                  * the system might be non-idle CPU-wise, but we only care
8715                  * about not overloading the IO subsystem. (things like an
8716                  * e2fsck being done on the RAID array should execute fast)
8717                  */
8718                 cond_resched();
8719
8720                 recovery_done = io_sectors - atomic_read(&mddev->recovery_active);
8721                 currspeed = ((unsigned long)(recovery_done - mddev->resync_mark_cnt))/2
8722                         /((jiffies-mddev->resync_mark)/HZ +1) +1;
8723
8724                 if (currspeed > speed_min(mddev)) {
8725                         if (currspeed > speed_max(mddev)) {
8726                                 msleep(500);
8727                                 goto repeat;
8728                         }
8729                         if (!is_mddev_idle(mddev, 0)) {
8730                                 /*
8731                                  * Give other IO more of a chance.
8732                                  * The faster the devices, the less we wait.
8733                                  */
8734                                 wait_event(mddev->recovery_wait,
8735                                            !atomic_read(&mddev->recovery_active));
8736                         }
8737                 }
8738         }
8739         pr_info("md: %s: %s %s.\n",mdname(mddev), desc,
8740                 test_bit(MD_RECOVERY_INTR, &mddev->recovery)
8741                 ? "interrupted" : "done");
8742         /*
8743          * this also signals 'finished resyncing' to md_stop
8744          */
8745         blk_finish_plug(&plug);
8746         wait_event(mddev->recovery_wait, !atomic_read(&mddev->recovery_active));
8747
8748         if (!test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
8749             !test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
8750             mddev->curr_resync > 3) {
8751                 mddev->curr_resync_completed = mddev->curr_resync;
8752                 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
8753         }
8754         mddev->pers->sync_request(mddev, max_sectors, &skipped);
8755
8756         if (!test_bit(MD_RECOVERY_CHECK, &mddev->recovery) &&
8757             mddev->curr_resync > 3) {
8758                 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
8759                         if (test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
8760                                 if (mddev->curr_resync >= mddev->recovery_cp) {
8761                                         pr_debug("md: checkpointing %s of %s.\n",
8762                                                  desc, mdname(mddev));
8763                                         if (test_bit(MD_RECOVERY_ERROR,
8764                                                 &mddev->recovery))
8765                                                 mddev->recovery_cp =
8766                                                         mddev->curr_resync_completed;
8767                                         else
8768                                                 mddev->recovery_cp =
8769                                                         mddev->curr_resync;
8770                                 }
8771                         } else
8772                                 mddev->recovery_cp = MaxSector;
8773                 } else {
8774                         if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8775                                 mddev->curr_resync = MaxSector;
8776                         if (!test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
8777                             test_bit(MD_RECOVERY_RECOVER, &mddev->recovery)) {
8778                                 rcu_read_lock();
8779                                 rdev_for_each_rcu(rdev, mddev)
8780                                         if (rdev->raid_disk >= 0 &&
8781                                             mddev->delta_disks >= 0 &&
8782                                             !test_bit(Journal, &rdev->flags) &&
8783                                             !test_bit(Faulty, &rdev->flags) &&
8784                                             !test_bit(In_sync, &rdev->flags) &&
8785                                             rdev->recovery_offset < mddev->curr_resync)
8786                                                 rdev->recovery_offset = mddev->curr_resync;
8787                                 rcu_read_unlock();
8788                         }
8789                 }
8790         }
8791  skip:
8792         /* set CHANGE_PENDING here since maybe another update is needed,
8793          * so other nodes are informed. It should be harmless for normal
8794          * raid */
8795         set_mask_bits(&mddev->sb_flags, 0,
8796                       BIT(MD_SB_CHANGE_PENDING) | BIT(MD_SB_CHANGE_DEVS));
8797
8798         if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
8799                         !test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
8800                         mddev->delta_disks > 0 &&
8801                         mddev->pers->finish_reshape &&
8802                         mddev->pers->size &&
8803                         mddev->queue) {
8804                 mddev_lock_nointr(mddev);
8805                 md_set_array_sectors(mddev, mddev->pers->size(mddev, 0, 0));
8806                 mddev_unlock(mddev);
8807                 if (!mddev_is_clustered(mddev)) {
8808                         set_capacity(mddev->gendisk, mddev->array_sectors);
8809                         revalidate_disk(mddev->gendisk);
8810                 }
8811         }
8812
8813         spin_lock(&mddev->lock);
8814         if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
8815                 /* We completed so min/max setting can be forgotten if used. */
8816                 if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
8817                         mddev->resync_min = 0;
8818                 mddev->resync_max = MaxSector;
8819         } else if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
8820                 mddev->resync_min = mddev->curr_resync_completed;
8821         set_bit(MD_RECOVERY_DONE, &mddev->recovery);
8822         mddev->curr_resync = 0;
8823         spin_unlock(&mddev->lock);
8824
8825         wake_up(&resync_wait);
8826         md_wakeup_thread(mddev->thread);
8827         return;
8828 }
8829 EXPORT_SYMBOL_GPL(md_do_sync);
8830
8831 static int remove_and_add_spares(struct mddev *mddev,
8832                                  struct md_rdev *this)
8833 {
8834         struct md_rdev *rdev;
8835         int spares = 0;
8836         int removed = 0;
8837         bool remove_some = false;
8838
8839         if (this && test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
8840                 /* Mustn't remove devices when resync thread is running */
8841                 return 0;
8842
8843         rdev_for_each(rdev, mddev) {
8844                 if ((this == NULL || rdev == this) &&
8845                     rdev->raid_disk >= 0 &&
8846                     !test_bit(Blocked, &rdev->flags) &&
8847                     test_bit(Faulty, &rdev->flags) &&
8848                     atomic_read(&rdev->nr_pending)==0) {
8849                         /* Faulty non-Blocked devices with nr_pending == 0
8850                          * never get nr_pending incremented,
8851                          * never get Faulty cleared, and never get Blocked set.
8852                          * So we can synchronize_rcu now rather than once per device
8853                          */
8854                         remove_some = true;
8855                         set_bit(RemoveSynchronized, &rdev->flags);
8856                 }
8857         }
8858
8859         if (remove_some)
8860                 synchronize_rcu();
8861         rdev_for_each(rdev, mddev) {
8862                 if ((this == NULL || rdev == this) &&
8863                     rdev->raid_disk >= 0 &&
8864                     !test_bit(Blocked, &rdev->flags) &&
8865                     ((test_bit(RemoveSynchronized, &rdev->flags) ||
8866                      (!test_bit(In_sync, &rdev->flags) &&
8867                       !test_bit(Journal, &rdev->flags))) &&
8868                     atomic_read(&rdev->nr_pending)==0)) {
8869                         if (mddev->pers->hot_remove_disk(
8870                                     mddev, rdev) == 0) {
8871                                 sysfs_unlink_rdev(mddev, rdev);
8872                                 rdev->saved_raid_disk = rdev->raid_disk;
8873                                 rdev->raid_disk = -1;
8874                                 removed++;
8875                         }
8876                 }
8877                 if (remove_some && test_bit(RemoveSynchronized, &rdev->flags))
8878                         clear_bit(RemoveSynchronized, &rdev->flags);
8879         }
8880
8881         if (removed && mddev->kobj.sd)
8882                 sysfs_notify(&mddev->kobj, NULL, "degraded");
8883
8884         if (this && removed)
8885                 goto no_add;
8886
8887         rdev_for_each(rdev, mddev) {
8888                 if (this && this != rdev)
8889                         continue;
8890                 if (test_bit(Candidate, &rdev->flags))
8891                         continue;
8892                 if (rdev->raid_disk >= 0 &&
8893                     !test_bit(In_sync, &rdev->flags) &&
8894                     !test_bit(Journal, &rdev->flags) &&
8895                     !test_bit(Faulty, &rdev->flags))
8896                         spares++;
8897                 if (rdev->raid_disk >= 0)
8898                         continue;
8899                 if (test_bit(Faulty, &rdev->flags))
8900                         continue;
8901                 if (!test_bit(Journal, &rdev->flags)) {
8902                         if (mddev->ro &&
8903                             ! (rdev->saved_raid_disk >= 0 &&
8904                                !test_bit(Bitmap_sync, &rdev->flags)))
8905                                 continue;
8906
8907                         rdev->recovery_offset = 0;
8908                 }
8909                 if (mddev->pers->
8910                     hot_add_disk(mddev, rdev) == 0) {
8911                         if (sysfs_link_rdev(mddev, rdev))
8912                                 /* failure here is OK */;
8913                         if (!test_bit(Journal, &rdev->flags))
8914                                 spares++;
8915                         md_new_event(mddev);
8916                         set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8917                 }
8918         }
8919 no_add:
8920         if (removed)
8921                 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8922         return spares;
8923 }
8924
8925 static void md_start_sync(struct work_struct *ws)
8926 {
8927         struct mddev *mddev = container_of(ws, struct mddev, del_work);
8928
8929         mddev->sync_thread = md_register_thread(md_do_sync,
8930                                                 mddev,
8931                                                 "resync");
8932         if (!mddev->sync_thread) {
8933                 pr_warn("%s: could not start resync thread...\n",
8934                         mdname(mddev));
8935                 /* leave the spares where they are, it shouldn't hurt */
8936                 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
8937                 clear_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
8938                 clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
8939                 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
8940                 clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
8941                 wake_up(&resync_wait);
8942                 if (test_and_clear_bit(MD_RECOVERY_RECOVER,
8943                                        &mddev->recovery))
8944                         if (mddev->sysfs_action)
8945                                 sysfs_notify_dirent_safe(mddev->sysfs_action);
8946         } else
8947                 md_wakeup_thread(mddev->sync_thread);
8948         sysfs_notify_dirent_safe(mddev->sysfs_action);
8949         md_new_event(mddev);
8950 }
8951
8952 /*
8953  * This routine is regularly called by all per-raid-array threads to
8954  * deal with generic issues like resync and super-block update.
8955  * Raid personalities that don't have a thread (linear/raid0) do not
8956  * need this as they never do any recovery or update the superblock.
8957  *
8958  * It does not do any resync itself, but rather "forks" off other threads
8959  * to do that as needed.
8960  * When it is determined that resync is needed, we set MD_RECOVERY_RUNNING in
8961  * "->recovery" and create a thread at ->sync_thread.
8962  * When the thread finishes it sets MD_RECOVERY_DONE
8963  * and wakeups up this thread which will reap the thread and finish up.
8964  * This thread also removes any faulty devices (with nr_pending == 0).
8965  *
8966  * The overall approach is:
8967  *  1/ if the superblock needs updating, update it.
8968  *  2/ If a recovery thread is running, don't do anything else.
8969  *  3/ If recovery has finished, clean up, possibly marking spares active.
8970  *  4/ If there are any faulty devices, remove them.
8971  *  5/ If array is degraded, try to add spares devices
8972  *  6/ If array has spares or is not in-sync, start a resync thread.
8973  */
8974 void md_check_recovery(struct mddev *mddev)
8975 {
8976         if (test_bit(MD_ALLOW_SB_UPDATE, &mddev->flags) && mddev->sb_flags) {
8977                 /* Write superblock - thread that called mddev_suspend()
8978                  * holds reconfig_mutex for us.
8979                  */
8980                 set_bit(MD_UPDATING_SB, &mddev->flags);
8981                 smp_mb__after_atomic();
8982                 if (test_bit(MD_ALLOW_SB_UPDATE, &mddev->flags))
8983                         md_update_sb(mddev, 0);
8984                 clear_bit_unlock(MD_UPDATING_SB, &mddev->flags);
8985                 wake_up(&mddev->sb_wait);
8986         }
8987
8988         if (mddev->suspended)
8989                 return;
8990
8991         if (mddev->bitmap)
8992                 md_bitmap_daemon_work(mddev);
8993
8994         if (signal_pending(current)) {
8995                 if (mddev->pers->sync_request && !mddev->external) {
8996                         pr_debug("md: %s in immediate safe mode\n",
8997                                  mdname(mddev));
8998                         mddev->safemode = 2;
8999                 }
9000                 flush_signals(current);
9001         }
9002
9003         if (mddev->ro && !test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
9004                 return;
9005         if ( ! (
9006                 (mddev->sb_flags & ~ (1<<MD_SB_CHANGE_PENDING)) ||
9007                 test_bit(MD_RECOVERY_NEEDED, &mddev->recovery) ||
9008                 test_bit(MD_RECOVERY_DONE, &mddev->recovery) ||
9009                 (mddev->external == 0 && mddev->safemode == 1) ||
9010                 (mddev->safemode == 2
9011                  && !mddev->in_sync && mddev->recovery_cp == MaxSector)
9012                 ))
9013                 return;
9014
9015         if (mddev_trylock(mddev)) {
9016                 int spares = 0;
9017                 bool try_set_sync = mddev->safemode != 0;
9018
9019                 if (!mddev->external && mddev->safemode == 1)
9020                         mddev->safemode = 0;
9021
9022                 if (mddev->ro) {
9023                         struct md_rdev *rdev;
9024                         if (!mddev->external && mddev->in_sync)
9025                                 /* 'Blocked' flag not needed as failed devices
9026                                  * will be recorded if array switched to read/write.
9027                                  * Leaving it set will prevent the device
9028                                  * from being removed.
9029                                  */
9030                                 rdev_for_each(rdev, mddev)
9031                                         clear_bit(Blocked, &rdev->flags);
9032                         /* On a read-only array we can:
9033                          * - remove failed devices
9034                          * - add already-in_sync devices if the array itself
9035                          *   is in-sync.
9036                          * As we only add devices that are already in-sync,
9037                          * we can activate the spares immediately.
9038                          */
9039                         remove_and_add_spares(mddev, NULL);
9040                         /* There is no thread, but we need to call
9041                          * ->spare_active and clear saved_raid_disk
9042                          */
9043                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
9044                         md_reap_sync_thread(mddev);
9045                         clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
9046                         clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
9047                         clear_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
9048                         goto unlock;
9049                 }
9050
9051                 if (mddev_is_clustered(mddev)) {
9052                         struct md_rdev *rdev;
9053                         /* kick the device if another node issued a
9054                          * remove disk.
9055                          */
9056                         rdev_for_each(rdev, mddev) {
9057                                 if (test_and_clear_bit(ClusterRemove, &rdev->flags) &&
9058                                                 rdev->raid_disk < 0)
9059                                         md_kick_rdev_from_array(rdev);
9060                         }
9061                 }
9062
9063                 if (try_set_sync && !mddev->external && !mddev->in_sync) {
9064                         spin_lock(&mddev->lock);
9065                         set_in_sync(mddev);
9066                         spin_unlock(&mddev->lock);
9067                 }
9068
9069                 if (mddev->sb_flags)
9070                         md_update_sb(mddev, 0);
9071
9072                 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) &&
9073                     !test_bit(MD_RECOVERY_DONE, &mddev->recovery)) {
9074                         /* resync/recovery still happening */
9075                         clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
9076                         goto unlock;
9077                 }
9078                 if (mddev->sync_thread) {
9079                         md_reap_sync_thread(mddev);
9080                         goto unlock;
9081                 }
9082                 /* Set RUNNING before clearing NEEDED to avoid
9083                  * any transients in the value of "sync_action".
9084                  */
9085                 mddev->curr_resync_completed = 0;
9086                 spin_lock(&mddev->lock);
9087                 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
9088                 spin_unlock(&mddev->lock);
9089                 /* Clear some bits that don't mean anything, but
9090                  * might be left set
9091                  */
9092                 clear_bit(MD_RECOVERY_INTR, &mddev->recovery);
9093                 clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
9094
9095                 if (!test_and_clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery) ||
9096                     test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
9097                         goto not_running;
9098                 /* no recovery is running.
9099                  * remove any failed drives, then
9100                  * add spares if possible.
9101                  * Spares are also removed and re-added, to allow
9102                  * the personality to fail the re-add.
9103                  */
9104
9105                 if (mddev->reshape_position != MaxSector) {
9106                         if (mddev->pers->check_reshape == NULL ||
9107                             mddev->pers->check_reshape(mddev) != 0)
9108                                 /* Cannot proceed */
9109                                 goto not_running;
9110                         set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
9111                         clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
9112                 } else if ((spares = remove_and_add_spares(mddev, NULL))) {
9113                         clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
9114                         clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
9115                         clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
9116                         set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
9117                 } else if (mddev->recovery_cp < MaxSector) {
9118                         set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
9119                         clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
9120                 } else if (!test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
9121                         /* nothing to be done ... */
9122                         goto not_running;
9123
9124                 if (mddev->pers->sync_request) {
9125                         if (spares) {
9126                                 /* We are adding a device or devices to an array
9127                                  * which has the bitmap stored on all devices.
9128                                  * So make sure all bitmap pages get written
9129                                  */
9130                                 md_bitmap_write_all(mddev->bitmap);
9131                         }
9132                         INIT_WORK(&mddev->del_work, md_start_sync);
9133                         queue_work(md_misc_wq, &mddev->del_work);
9134                         goto unlock;
9135                 }
9136         not_running:
9137                 if (!mddev->sync_thread) {
9138                         clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
9139                         wake_up(&resync_wait);
9140                         if (test_and_clear_bit(MD_RECOVERY_RECOVER,
9141                                                &mddev->recovery))
9142                                 if (mddev->sysfs_action)
9143                                         sysfs_notify_dirent_safe(mddev->sysfs_action);
9144                 }
9145         unlock:
9146                 wake_up(&mddev->sb_wait);
9147                 mddev_unlock(mddev);
9148         }
9149 }
9150 EXPORT_SYMBOL(md_check_recovery);
9151
9152 void md_reap_sync_thread(struct mddev *mddev)
9153 {
9154         struct md_rdev *rdev;
9155         sector_t old_dev_sectors = mddev->dev_sectors;
9156         bool is_reshaped = false;
9157
9158         /* resync has finished, collect result */
9159         md_unregister_thread(&mddev->sync_thread);
9160         if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
9161             !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
9162             mddev->degraded != mddev->raid_disks) {
9163                 /* success...*/
9164                 /* activate any spares */
9165                 if (mddev->pers->spare_active(mddev)) {
9166                         sysfs_notify(&mddev->kobj, NULL,
9167                                      "degraded");
9168                         set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
9169                 }
9170         }
9171         if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
9172             mddev->pers->finish_reshape) {
9173                 mddev->pers->finish_reshape(mddev);
9174                 if (mddev_is_clustered(mddev))
9175                         is_reshaped = true;
9176         }
9177
9178         /* If array is no-longer degraded, then any saved_raid_disk
9179          * information must be scrapped.
9180          */
9181         if (!mddev->degraded)
9182                 rdev_for_each(rdev, mddev)
9183                         rdev->saved_raid_disk = -1;
9184
9185         md_update_sb(mddev, 1);
9186         /* MD_SB_CHANGE_PENDING should be cleared by md_update_sb, so we can
9187          * call resync_finish here if MD_CLUSTER_RESYNC_LOCKED is set by
9188          * clustered raid */
9189         if (test_and_clear_bit(MD_CLUSTER_RESYNC_LOCKED, &mddev->flags))
9190                 md_cluster_ops->resync_finish(mddev);
9191         clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
9192         clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
9193         clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
9194         clear_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
9195         clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
9196         clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
9197         /*
9198          * We call md_cluster_ops->update_size here because sync_size could
9199          * be changed by md_update_sb, and MD_RECOVERY_RESHAPE is cleared,
9200          * so it is time to update size across cluster.
9201          */
9202         if (mddev_is_clustered(mddev) && is_reshaped
9203                                       && !test_bit(MD_CLOSING, &mddev->flags))
9204                 md_cluster_ops->update_size(mddev, old_dev_sectors);
9205         wake_up(&resync_wait);
9206         /* flag recovery needed just to double check */
9207         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
9208         sysfs_notify_dirent_safe(mddev->sysfs_action);
9209         md_new_event(mddev);
9210         if (mddev->event_work.func)
9211                 queue_work(md_misc_wq, &mddev->event_work);
9212 }
9213 EXPORT_SYMBOL(md_reap_sync_thread);
9214
9215 void md_wait_for_blocked_rdev(struct md_rdev *rdev, struct mddev *mddev)
9216 {
9217         sysfs_notify_dirent_safe(rdev->sysfs_state);
9218         wait_event_timeout(rdev->blocked_wait,
9219                            !test_bit(Blocked, &rdev->flags) &&
9220                            !test_bit(BlockedBadBlocks, &rdev->flags),
9221                            msecs_to_jiffies(5000));
9222         rdev_dec_pending(rdev, mddev);
9223 }
9224 EXPORT_SYMBOL(md_wait_for_blocked_rdev);
9225
9226 void md_finish_reshape(struct mddev *mddev)
9227 {
9228         /* called be personality module when reshape completes. */
9229         struct md_rdev *rdev;
9230
9231         rdev_for_each(rdev, mddev) {
9232                 if (rdev->data_offset > rdev->new_data_offset)
9233                         rdev->sectors += rdev->data_offset - rdev->new_data_offset;
9234                 else
9235                         rdev->sectors -= rdev->new_data_offset - rdev->data_offset;
9236                 rdev->data_offset = rdev->new_data_offset;
9237         }
9238 }
9239 EXPORT_SYMBOL(md_finish_reshape);
9240
9241 /* Bad block management */
9242
9243 /* Returns 1 on success, 0 on failure */
9244 int rdev_set_badblocks(struct md_rdev *rdev, sector_t s, int sectors,
9245                        int is_new)
9246 {
9247         struct mddev *mddev = rdev->mddev;
9248         int rv;
9249         if (is_new)
9250                 s += rdev->new_data_offset;
9251         else
9252                 s += rdev->data_offset;
9253         rv = badblocks_set(&rdev->badblocks, s, sectors, 0);
9254         if (rv == 0) {
9255                 /* Make sure they get written out promptly */
9256                 if (test_bit(ExternalBbl, &rdev->flags))
9257                         sysfs_notify(&rdev->kobj, NULL,
9258                                      "unacknowledged_bad_blocks");
9259                 sysfs_notify_dirent_safe(rdev->sysfs_state);
9260                 set_mask_bits(&mddev->sb_flags, 0,
9261                               BIT(MD_SB_CHANGE_CLEAN) | BIT(MD_SB_CHANGE_PENDING));
9262                 md_wakeup_thread(rdev->mddev->thread);
9263                 return 1;
9264         } else
9265                 return 0;
9266 }
9267 EXPORT_SYMBOL_GPL(rdev_set_badblocks);
9268
9269 int rdev_clear_badblocks(struct md_rdev *rdev, sector_t s, int sectors,
9270                          int is_new)
9271 {
9272         int rv;
9273         if (is_new)
9274                 s += rdev->new_data_offset;
9275         else
9276                 s += rdev->data_offset;
9277         rv = badblocks_clear(&rdev->badblocks, s, sectors);
9278         if ((rv == 0) && test_bit(ExternalBbl, &rdev->flags))
9279                 sysfs_notify(&rdev->kobj, NULL, "bad_blocks");
9280         return rv;
9281 }
9282 EXPORT_SYMBOL_GPL(rdev_clear_badblocks);
9283
9284 static int md_notify_reboot(struct notifier_block *this,
9285                             unsigned long code, void *x)
9286 {
9287         struct list_head *tmp;
9288         struct mddev *mddev;
9289         int need_delay = 0;
9290
9291         for_each_mddev(mddev, tmp) {
9292                 if (mddev_trylock(mddev)) {
9293                         if (mddev->pers)
9294                                 __md_stop_writes(mddev);
9295                         if (mddev->persistent)
9296                                 mddev->safemode = 2;
9297                         mddev_unlock(mddev);
9298                 }
9299                 need_delay = 1;
9300         }
9301         /*
9302          * certain more exotic SCSI devices are known to be
9303          * volatile wrt too early system reboots. While the
9304          * right place to handle this issue is the given
9305          * driver, we do want to have a safe RAID driver ...
9306          */
9307         if (need_delay)
9308                 mdelay(1000*1);
9309
9310         return NOTIFY_DONE;
9311 }
9312
9313 static struct notifier_block md_notifier = {
9314         .notifier_call  = md_notify_reboot,
9315         .next           = NULL,
9316         .priority       = INT_MAX, /* before any real devices */
9317 };
9318
9319 static void md_geninit(void)
9320 {
9321         pr_debug("md: sizeof(mdp_super_t) = %d\n", (int)sizeof(mdp_super_t));
9322
9323         proc_create("mdstat", S_IRUGO, NULL, &md_seq_fops);
9324 }
9325
9326 static int __init md_init(void)
9327 {
9328         int ret = -ENOMEM;
9329
9330         md_wq = alloc_workqueue("md", WQ_MEM_RECLAIM, 0);
9331         if (!md_wq)
9332                 goto err_wq;
9333
9334         md_misc_wq = alloc_workqueue("md_misc", 0, 0);
9335         if (!md_misc_wq)
9336                 goto err_misc_wq;
9337
9338         if ((ret = register_blkdev(MD_MAJOR, "md")) < 0)
9339                 goto err_md;
9340
9341         if ((ret = register_blkdev(0, "mdp")) < 0)
9342                 goto err_mdp;
9343         mdp_major = ret;
9344
9345         blk_register_region(MKDEV(MD_MAJOR, 0), 512, THIS_MODULE,
9346                             md_probe, NULL, NULL);
9347         blk_register_region(MKDEV(mdp_major, 0), 1UL<<MINORBITS, THIS_MODULE,
9348                             md_probe, NULL, NULL);
9349
9350         register_reboot_notifier(&md_notifier);
9351         raid_table_header = register_sysctl_table(raid_root_table);
9352
9353         md_geninit();
9354         return 0;
9355
9356 err_mdp:
9357         unregister_blkdev(MD_MAJOR, "md");
9358 err_md:
9359         destroy_workqueue(md_misc_wq);
9360 err_misc_wq:
9361         destroy_workqueue(md_wq);
9362 err_wq:
9363         return ret;
9364 }
9365
9366 static void check_sb_changes(struct mddev *mddev, struct md_rdev *rdev)
9367 {
9368         struct mdp_superblock_1 *sb = page_address(rdev->sb_page);
9369         struct md_rdev *rdev2;
9370         int role, ret;
9371         char b[BDEVNAME_SIZE];
9372
9373         /*
9374          * If size is changed in another node then we need to
9375          * do resize as well.
9376          */
9377         if (mddev->dev_sectors != le64_to_cpu(sb->size)) {
9378                 ret = mddev->pers->resize(mddev, le64_to_cpu(sb->size));
9379                 if (ret)
9380                         pr_info("md-cluster: resize failed\n");
9381                 else
9382                         md_bitmap_update_sb(mddev->bitmap);
9383         }
9384
9385         /* Check for change of roles in the active devices */
9386         rdev_for_each(rdev2, mddev) {
9387                 if (test_bit(Faulty, &rdev2->flags))
9388                         continue;
9389
9390                 /* Check if the roles changed */
9391                 role = le16_to_cpu(sb->dev_roles[rdev2->desc_nr]);
9392
9393                 if (test_bit(Candidate, &rdev2->flags)) {
9394                         if (role == 0xfffe) {
9395                                 pr_info("md: Removing Candidate device %s because add failed\n", bdevname(rdev2->bdev,b));
9396                                 md_kick_rdev_from_array(rdev2);
9397                                 continue;
9398                         }
9399                         else
9400                                 clear_bit(Candidate, &rdev2->flags);
9401                 }
9402
9403                 if (role != rdev2->raid_disk) {
9404                         /*
9405                          * got activated except reshape is happening.
9406                          */
9407                         if (rdev2->raid_disk == -1 && role != 0xffff &&
9408                             !(le32_to_cpu(sb->feature_map) &
9409                               MD_FEATURE_RESHAPE_ACTIVE)) {
9410                                 rdev2->saved_raid_disk = role;
9411                                 ret = remove_and_add_spares(mddev, rdev2);
9412                                 pr_info("Activated spare: %s\n",
9413                                         bdevname(rdev2->bdev,b));
9414                                 /* wakeup mddev->thread here, so array could
9415                                  * perform resync with the new activated disk */
9416                                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
9417                                 md_wakeup_thread(mddev->thread);
9418                         }
9419                         /* device faulty
9420                          * We just want to do the minimum to mark the disk
9421                          * as faulty. The recovery is performed by the
9422                          * one who initiated the error.
9423                          */
9424                         if ((role == 0xfffe) || (role == 0xfffd)) {
9425                                 md_error(mddev, rdev2);
9426                                 clear_bit(Blocked, &rdev2->flags);
9427                         }
9428                 }
9429         }
9430
9431         if (mddev->raid_disks != le32_to_cpu(sb->raid_disks))
9432                 update_raid_disks(mddev, le32_to_cpu(sb->raid_disks));
9433
9434         /*
9435          * Since mddev->delta_disks has already updated in update_raid_disks,
9436          * so it is time to check reshape.
9437          */
9438         if (test_bit(MD_RESYNCING_REMOTE, &mddev->recovery) &&
9439             (le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE)) {
9440                 /*
9441                  * reshape is happening in the remote node, we need to
9442                  * update reshape_position and call start_reshape.
9443                  */
9444                 mddev->reshape_position = le64_to_cpu(sb->reshape_position);
9445                 if (mddev->pers->update_reshape_pos)
9446                         mddev->pers->update_reshape_pos(mddev);
9447                 if (mddev->pers->start_reshape)
9448                         mddev->pers->start_reshape(mddev);
9449         } else if (test_bit(MD_RESYNCING_REMOTE, &mddev->recovery) &&
9450                    mddev->reshape_position != MaxSector &&
9451                    !(le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE)) {
9452                 /* reshape is just done in another node. */
9453                 mddev->reshape_position = MaxSector;
9454                 if (mddev->pers->update_reshape_pos)
9455                         mddev->pers->update_reshape_pos(mddev);
9456         }
9457
9458         /* Finally set the event to be up to date */
9459         mddev->events = le64_to_cpu(sb->events);
9460 }
9461
9462 static int read_rdev(struct mddev *mddev, struct md_rdev *rdev)
9463 {
9464         int err;
9465         struct page *swapout = rdev->sb_page;
9466         struct mdp_superblock_1 *sb;
9467
9468         /* Store the sb page of the rdev in the swapout temporary
9469          * variable in case we err in the future
9470          */
9471         rdev->sb_page = NULL;
9472         err = alloc_disk_sb(rdev);
9473         if (err == 0) {
9474                 ClearPageUptodate(rdev->sb_page);
9475                 rdev->sb_loaded = 0;
9476                 err = super_types[mddev->major_version].
9477                         load_super(rdev, NULL, mddev->minor_version);
9478         }
9479         if (err < 0) {
9480                 pr_warn("%s: %d Could not reload rdev(%d) err: %d. Restoring old values\n",
9481                                 __func__, __LINE__, rdev->desc_nr, err);
9482                 if (rdev->sb_page)
9483                         put_page(rdev->sb_page);
9484                 rdev->sb_page = swapout;
9485                 rdev->sb_loaded = 1;
9486                 return err;
9487         }
9488
9489         sb = page_address(rdev->sb_page);
9490         /* Read the offset unconditionally, even if MD_FEATURE_RECOVERY_OFFSET
9491          * is not set
9492          */
9493
9494         if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RECOVERY_OFFSET))
9495                 rdev->recovery_offset = le64_to_cpu(sb->recovery_offset);
9496
9497         /* The other node finished recovery, call spare_active to set
9498          * device In_sync and mddev->degraded
9499          */
9500         if (rdev->recovery_offset == MaxSector &&
9501             !test_bit(In_sync, &rdev->flags) &&
9502             mddev->pers->spare_active(mddev))
9503                 sysfs_notify(&mddev->kobj, NULL, "degraded");
9504
9505         put_page(swapout);
9506         return 0;
9507 }
9508
9509 void md_reload_sb(struct mddev *mddev, int nr)
9510 {
9511         struct md_rdev *rdev;
9512         int err;
9513
9514         /* Find the rdev */
9515         rdev_for_each_rcu(rdev, mddev) {
9516                 if (rdev->desc_nr == nr)
9517                         break;
9518         }
9519
9520         if (!rdev || rdev->desc_nr != nr) {
9521                 pr_warn("%s: %d Could not find rdev with nr %d\n", __func__, __LINE__, nr);
9522                 return;
9523         }
9524
9525         err = read_rdev(mddev, rdev);
9526         if (err < 0)
9527                 return;
9528
9529         check_sb_changes(mddev, rdev);
9530
9531         /* Read all rdev's to update recovery_offset */
9532         rdev_for_each_rcu(rdev, mddev) {
9533                 if (!test_bit(Faulty, &rdev->flags))
9534                         read_rdev(mddev, rdev);
9535         }
9536 }
9537 EXPORT_SYMBOL(md_reload_sb);
9538
9539 #ifndef MODULE
9540
9541 /*
9542  * Searches all registered partitions for autorun RAID arrays
9543  * at boot time.
9544  */
9545
9546 static DEFINE_MUTEX(detected_devices_mutex);
9547 static LIST_HEAD(all_detected_devices);
9548 struct detected_devices_node {
9549         struct list_head list;
9550         dev_t dev;
9551 };
9552
9553 void md_autodetect_dev(dev_t dev)
9554 {
9555         struct detected_devices_node *node_detected_dev;
9556
9557         node_detected_dev = kzalloc(sizeof(*node_detected_dev), GFP_KERNEL);
9558         if (node_detected_dev) {
9559                 node_detected_dev->dev = dev;
9560                 mutex_lock(&detected_devices_mutex);
9561                 list_add_tail(&node_detected_dev->list, &all_detected_devices);
9562                 mutex_unlock(&detected_devices_mutex);
9563         }
9564 }
9565
9566 static void autostart_arrays(int part)
9567 {
9568         struct md_rdev *rdev;
9569         struct detected_devices_node *node_detected_dev;
9570         dev_t dev;
9571         int i_scanned, i_passed;
9572
9573         i_scanned = 0;
9574         i_passed = 0;
9575
9576         pr_info("md: Autodetecting RAID arrays.\n");
9577
9578         mutex_lock(&detected_devices_mutex);
9579         while (!list_empty(&all_detected_devices) && i_scanned < INT_MAX) {
9580                 i_scanned++;
9581                 node_detected_dev = list_entry(all_detected_devices.next,
9582                                         struct detected_devices_node, list);
9583                 list_del(&node_detected_dev->list);
9584                 dev = node_detected_dev->dev;
9585                 kfree(node_detected_dev);
9586                 mutex_unlock(&detected_devices_mutex);
9587                 rdev = md_import_device(dev,0, 90);
9588                 mutex_lock(&detected_devices_mutex);
9589                 if (IS_ERR(rdev))
9590                         continue;
9591
9592                 if (test_bit(Faulty, &rdev->flags))
9593                         continue;
9594
9595                 set_bit(AutoDetected, &rdev->flags);
9596                 list_add(&rdev->same_set, &pending_raid_disks);
9597                 i_passed++;
9598         }
9599         mutex_unlock(&detected_devices_mutex);
9600
9601         pr_debug("md: Scanned %d and added %d devices.\n", i_scanned, i_passed);
9602
9603         autorun_devices(part);
9604 }
9605
9606 #endif /* !MODULE */
9607
9608 static __exit void md_exit(void)
9609 {
9610         struct mddev *mddev;
9611         struct list_head *tmp;
9612         int delay = 1;
9613
9614         blk_unregister_region(MKDEV(MD_MAJOR,0), 512);
9615         blk_unregister_region(MKDEV(mdp_major,0), 1U << MINORBITS);
9616
9617         unregister_blkdev(MD_MAJOR,"md");
9618         unregister_blkdev(mdp_major, "mdp");
9619         unregister_reboot_notifier(&md_notifier);
9620         unregister_sysctl_table(raid_table_header);
9621
9622         /* We cannot unload the modules while some process is
9623          * waiting for us in select() or poll() - wake them up
9624          */
9625         md_unloading = 1;
9626         while (waitqueue_active(&md_event_waiters)) {
9627                 /* not safe to leave yet */
9628                 wake_up(&md_event_waiters);
9629                 msleep(delay);
9630                 delay += delay;
9631         }
9632         remove_proc_entry("mdstat", NULL);
9633
9634         for_each_mddev(mddev, tmp) {
9635                 export_array(mddev);
9636                 mddev->ctime = 0;
9637                 mddev->hold_active = 0;
9638                 /*
9639                  * for_each_mddev() will call mddev_put() at the end of each
9640                  * iteration.  As the mddev is now fully clear, this will
9641                  * schedule the mddev for destruction by a workqueue, and the
9642                  * destroy_workqueue() below will wait for that to complete.
9643                  */
9644         }
9645         destroy_workqueue(md_misc_wq);
9646         destroy_workqueue(md_wq);
9647 }
9648
9649 subsys_initcall(md_init);
9650 module_exit(md_exit)
9651
9652 static int get_ro(char *buffer, const struct kernel_param *kp)
9653 {
9654         return sprintf(buffer, "%d", start_readonly);
9655 }
9656 static int set_ro(const char *val, const struct kernel_param *kp)
9657 {
9658         return kstrtouint(val, 10, (unsigned int *)&start_readonly);
9659 }
9660
9661 module_param_call(start_ro, set_ro, get_ro, NULL, S_IRUSR|S_IWUSR);
9662 module_param(start_dirty_degraded, int, S_IRUGO|S_IWUSR);
9663 module_param_call(new_array, add_named_array, NULL, NULL, S_IWUSR);
9664 module_param(create_on_open, bool, S_IRUSR|S_IWUSR);
9665
9666 MODULE_LICENSE("GPL");
9667 MODULE_DESCRIPTION("MD RAID framework");
9668 MODULE_ALIAS("md");
9669 MODULE_ALIAS_BLOCKDEV_MAJOR(MD_MAJOR);