Version:  2.0.40 2.2.26 2.4.37 3.5 3.6 3.7 3.8 3.9 3.10 3.11 3.12 3.13 3.14 3.15 3.16 3.17 3.18 3.19 4.0 4.1

Linux/drivers/md/md.c

  1 /*
  2    md.c : Multiple Devices driver for Linux
  3      Copyright (C) 1998, 1999, 2000 Ingo Molnar
  4 
  5      completely rewritten, based on the MD driver code from Marc Zyngier
  6 
  7    Changes:
  8 
  9    - RAID-1/RAID-5 extensions by Miguel de Icaza, Gadi Oxman, Ingo Molnar
 10    - RAID-6 extensions by H. Peter Anvin <hpa@zytor.com>
 11    - boot support for linear and striped mode by Harald Hoyer <HarryH@Royal.Net>
 12    - kerneld support by Boris Tobotras <boris@xtalk.msk.su>
 13    - kmod support by: Cyrus Durgin
 14    - RAID0 bugfixes: Mark Anthony Lisher <markal@iname.com>
 15    - Devfs support by Richard Gooch <rgooch@atnf.csiro.au>
 16 
 17    - lots of fixes and improvements to the RAID1/RAID5 and generic
 18      RAID code (such as request based resynchronization):
 19 
 20      Neil Brown <neilb@cse.unsw.edu.au>.
 21 
 22    - persistent bitmap code
 23      Copyright (C) 2003-2004, Paul Clements, SteelEye Technology, Inc.
 24 
 25    This program is free software; you can redistribute it and/or modify
 26    it under the terms of the GNU General Public License as published by
 27    the Free Software Foundation; either version 2, or (at your option)
 28    any later version.
 29 
 30    You should have received a copy of the GNU General Public License
 31    (for example /usr/src/linux/COPYING); if not, write to the Free
 32    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 33 */
 34 
 35 #include <linux/kthread.h>
 36 #include <linux/blkdev.h>
 37 #include <linux/sysctl.h>
 38 #include <linux/seq_file.h>
 39 #include <linux/fs.h>
 40 #include <linux/poll.h>
 41 #include <linux/ctype.h>
 42 #include <linux/string.h>
 43 #include <linux/hdreg.h>
 44 #include <linux/proc_fs.h>
 45 #include <linux/random.h>
 46 #include <linux/module.h>
 47 #include <linux/reboot.h>
 48 #include <linux/file.h>
 49 #include <linux/compat.h>
 50 #include <linux/delay.h>
 51 #include <linux/raid/md_p.h>
 52 #include <linux/raid/md_u.h>
 53 #include <linux/slab.h>
 54 #include "md.h"
 55 #include "bitmap.h"
 56 #include "md-cluster.h"
 57 
 58 #ifndef MODULE
 59 static void autostart_arrays(int part);
 60 #endif
 61 
 62 /* pers_list is a list of registered personalities protected
 63  * by pers_lock.
 64  * pers_lock does extra service to protect accesses to
 65  * mddev->thread when the mutex cannot be held.
 66  */
 67 static LIST_HEAD(pers_list);
 68 static DEFINE_SPINLOCK(pers_lock);
 69 
 70 struct md_cluster_operations *md_cluster_ops;
 71 EXPORT_SYMBOL(md_cluster_ops);
 72 struct module *md_cluster_mod;
 73 EXPORT_SYMBOL(md_cluster_mod);
 74 
 75 static DECLARE_WAIT_QUEUE_HEAD(resync_wait);
 76 static struct workqueue_struct *md_wq;
 77 static struct workqueue_struct *md_misc_wq;
 78 
 79 static int remove_and_add_spares(struct mddev *mddev,
 80                                  struct md_rdev *this);
 81 static void mddev_detach(struct mddev *mddev);
 82 
 83 /*
 84  * Default number of read corrections we'll attempt on an rdev
 85  * before ejecting it from the array. We divide the read error
 86  * count by 2 for every hour elapsed between read errors.
 87  */
 88 #define MD_DEFAULT_MAX_CORRECTED_READ_ERRORS 20
 89 /*
 90  * Current RAID-1,4,5 parallel reconstruction 'guaranteed speed limit'
 91  * is 1000 KB/sec, so the extra system load does not show up that much.
 92  * Increase it if you want to have more _guaranteed_ speed. Note that
 93  * the RAID driver will use the maximum available bandwidth if the IO
 94  * subsystem is idle. There is also an 'absolute maximum' reconstruction
 95  * speed limit - in case reconstruction slows down your system despite
 96  * idle IO detection.
 97  *
 98  * you can change it via /proc/sys/dev/raid/speed_limit_min and _max.
 99  * or /sys/block/mdX/md/sync_speed_{min,max}
100  */
101 
102 static int sysctl_speed_limit_min = 1000;
103 static int sysctl_speed_limit_max = 200000;
104 static inline int speed_min(struct mddev *mddev)
105 {
106         return mddev->sync_speed_min ?
107                 mddev->sync_speed_min : sysctl_speed_limit_min;
108 }
109 
110 static inline int speed_max(struct mddev *mddev)
111 {
112         return mddev->sync_speed_max ?
113                 mddev->sync_speed_max : sysctl_speed_limit_max;
114 }
115 
116 static struct ctl_table_header *raid_table_header;
117 
118 static struct ctl_table raid_table[] = {
119         {
120                 .procname       = "speed_limit_min",
121                 .data           = &sysctl_speed_limit_min,
122                 .maxlen         = sizeof(int),
123                 .mode           = S_IRUGO|S_IWUSR,
124                 .proc_handler   = proc_dointvec,
125         },
126         {
127                 .procname       = "speed_limit_max",
128                 .data           = &sysctl_speed_limit_max,
129                 .maxlen         = sizeof(int),
130                 .mode           = S_IRUGO|S_IWUSR,
131                 .proc_handler   = proc_dointvec,
132         },
133         { }
134 };
135 
136 static struct ctl_table raid_dir_table[] = {
137         {
138                 .procname       = "raid",
139                 .maxlen         = 0,
140                 .mode           = S_IRUGO|S_IXUGO,
141                 .child          = raid_table,
142         },
143         { }
144 };
145 
146 static struct ctl_table raid_root_table[] = {
147         {
148                 .procname       = "dev",
149                 .maxlen         = 0,
150                 .mode           = 0555,
151                 .child          = raid_dir_table,
152         },
153         {  }
154 };
155 
156 static const struct block_device_operations md_fops;
157 
158 static int start_readonly;
159 
160 /* bio_clone_mddev
161  * like bio_clone, but with a local bio set
162  */
163 
164 struct bio *bio_alloc_mddev(gfp_t gfp_mask, int nr_iovecs,
165                             struct mddev *mddev)
166 {
167         struct bio *b;
168 
169         if (!mddev || !mddev->bio_set)
170                 return bio_alloc(gfp_mask, nr_iovecs);
171 
172         b = bio_alloc_bioset(gfp_mask, nr_iovecs, mddev->bio_set);
173         if (!b)
174                 return NULL;
175         return b;
176 }
177 EXPORT_SYMBOL_GPL(bio_alloc_mddev);
178 
179 struct bio *bio_clone_mddev(struct bio *bio, gfp_t gfp_mask,
180                             struct mddev *mddev)
181 {
182         if (!mddev || !mddev->bio_set)
183                 return bio_clone(bio, gfp_mask);
184 
185         return bio_clone_bioset(bio, gfp_mask, mddev->bio_set);
186 }
187 EXPORT_SYMBOL_GPL(bio_clone_mddev);
188 
189 /*
190  * We have a system wide 'event count' that is incremented
191  * on any 'interesting' event, and readers of /proc/mdstat
192  * can use 'poll' or 'select' to find out when the event
193  * count increases.
194  *
195  * Events are:
196  *  start array, stop array, error, add device, remove device,
197  *  start build, activate spare
198  */
199 static DECLARE_WAIT_QUEUE_HEAD(md_event_waiters);
200 static atomic_t md_event_count;
201 void md_new_event(struct mddev *mddev)
202 {
203         atomic_inc(&md_event_count);
204         wake_up(&md_event_waiters);
205 }
206 EXPORT_SYMBOL_GPL(md_new_event);
207 
208 /* Alternate version that can be called from interrupts
209  * when calling sysfs_notify isn't needed.
210  */
211 static void md_new_event_inintr(struct mddev *mddev)
212 {
213         atomic_inc(&md_event_count);
214         wake_up(&md_event_waiters);
215 }
216 
217 /*
218  * Enables to iterate over all existing md arrays
219  * all_mddevs_lock protects this list.
220  */
221 static LIST_HEAD(all_mddevs);
222 static DEFINE_SPINLOCK(all_mddevs_lock);
223 
224 /*
225  * iterates through all used mddevs in the system.
226  * We take care to grab the all_mddevs_lock whenever navigating
227  * the list, and to always hold a refcount when unlocked.
228  * Any code which breaks out of this loop while own
229  * a reference to the current mddev and must mddev_put it.
230  */
231 #define for_each_mddev(_mddev,_tmp)                                     \
232                                                                         \
233         for (({ spin_lock(&all_mddevs_lock);                            \
234                 _tmp = all_mddevs.next;                                 \
235                 _mddev = NULL;});                                       \
236              ({ if (_tmp != &all_mddevs)                                \
237                         mddev_get(list_entry(_tmp, struct mddev, all_mddevs));\
238                 spin_unlock(&all_mddevs_lock);                          \
239                 if (_mddev) mddev_put(_mddev);                          \
240                 _mddev = list_entry(_tmp, struct mddev, all_mddevs);    \
241                 _tmp != &all_mddevs;});                                 \
242              ({ spin_lock(&all_mddevs_lock);                            \
243                 _tmp = _tmp->next;})                                    \
244                 )
245 
246 /* Rather than calling directly into the personality make_request function,
247  * IO requests come here first so that we can check if the device is
248  * being suspended pending a reconfiguration.
249  * We hold a refcount over the call to ->make_request.  By the time that
250  * call has finished, the bio has been linked into some internal structure
251  * and so is visible to ->quiesce(), so we don't need the refcount any more.
252  */
253 static void md_make_request(struct request_queue *q, struct bio *bio)
254 {
255         const int rw = bio_data_dir(bio);
256         struct mddev *mddev = q->queuedata;
257         unsigned int sectors;
258         int cpu;
259 
260         if (mddev == NULL || mddev->pers == NULL
261             || !mddev->ready) {
262                 bio_io_error(bio);
263                 return;
264         }
265         if (mddev->ro == 1 && unlikely(rw == WRITE)) {
266                 bio_endio(bio, bio_sectors(bio) == 0 ? 0 : -EROFS);
267                 return;
268         }
269         smp_rmb(); /* Ensure implications of  'active' are visible */
270         rcu_read_lock();
271         if (mddev->suspended) {
272                 DEFINE_WAIT(__wait);
273                 for (;;) {
274                         prepare_to_wait(&mddev->sb_wait, &__wait,
275                                         TASK_UNINTERRUPTIBLE);
276                         if (!mddev->suspended)
277                                 break;
278                         rcu_read_unlock();
279                         schedule();
280                         rcu_read_lock();
281                 }
282                 finish_wait(&mddev->sb_wait, &__wait);
283         }
284         atomic_inc(&mddev->active_io);
285         rcu_read_unlock();
286 
287         /*
288          * save the sectors now since our bio can
289          * go away inside make_request
290          */
291         sectors = bio_sectors(bio);
292         mddev->pers->make_request(mddev, bio);
293 
294         cpu = part_stat_lock();
295         part_stat_inc(cpu, &mddev->gendisk->part0, ios[rw]);
296         part_stat_add(cpu, &mddev->gendisk->part0, sectors[rw], sectors);
297         part_stat_unlock();
298 
299         if (atomic_dec_and_test(&mddev->active_io) && mddev->suspended)
300                 wake_up(&mddev->sb_wait);
301 }
302 
303 /* mddev_suspend makes sure no new requests are submitted
304  * to the device, and that any requests that have been submitted
305  * are completely handled.
306  * Once mddev_detach() is called and completes, the module will be
307  * completely unused.
308  */
309 void mddev_suspend(struct mddev *mddev)
310 {
311         BUG_ON(mddev->suspended);
312         mddev->suspended = 1;
313         synchronize_rcu();
314         wait_event(mddev->sb_wait, atomic_read(&mddev->active_io) == 0);
315         mddev->pers->quiesce(mddev, 1);
316 
317         del_timer_sync(&mddev->safemode_timer);
318 }
319 EXPORT_SYMBOL_GPL(mddev_suspend);
320 
321 void mddev_resume(struct mddev *mddev)
322 {
323         mddev->suspended = 0;
324         wake_up(&mddev->sb_wait);
325         mddev->pers->quiesce(mddev, 0);
326 
327         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
328         md_wakeup_thread(mddev->thread);
329         md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
330 }
331 EXPORT_SYMBOL_GPL(mddev_resume);
332 
333 int mddev_congested(struct mddev *mddev, int bits)
334 {
335         struct md_personality *pers = mddev->pers;
336         int ret = 0;
337 
338         rcu_read_lock();
339         if (mddev->suspended)
340                 ret = 1;
341         else if (pers && pers->congested)
342                 ret = pers->congested(mddev, bits);
343         rcu_read_unlock();
344         return ret;
345 }
346 EXPORT_SYMBOL_GPL(mddev_congested);
347 static int md_congested(void *data, int bits)
348 {
349         struct mddev *mddev = data;
350         return mddev_congested(mddev, bits);
351 }
352 
353 static int md_mergeable_bvec(struct request_queue *q,
354                              struct bvec_merge_data *bvm,
355                              struct bio_vec *biovec)
356 {
357         struct mddev *mddev = q->queuedata;
358         int ret;
359         rcu_read_lock();
360         if (mddev->suspended) {
361                 /* Must always allow one vec */
362                 if (bvm->bi_size == 0)
363                         ret = biovec->bv_len;
364                 else
365                         ret = 0;
366         } else {
367                 struct md_personality *pers = mddev->pers;
368                 if (pers && pers->mergeable_bvec)
369                         ret = pers->mergeable_bvec(mddev, bvm, biovec);
370                 else
371                         ret = biovec->bv_len;
372         }
373         rcu_read_unlock();
374         return ret;
375 }
376 /*
377  * Generic flush handling for md
378  */
379 
380 static void md_end_flush(struct bio *bio, int err)
381 {
382         struct md_rdev *rdev = bio->bi_private;
383         struct mddev *mddev = rdev->mddev;
384 
385         rdev_dec_pending(rdev, mddev);
386 
387         if (atomic_dec_and_test(&mddev->flush_pending)) {
388                 /* The pre-request flush has finished */
389                 queue_work(md_wq, &mddev->flush_work);
390         }
391         bio_put(bio);
392 }
393 
394 static void md_submit_flush_data(struct work_struct *ws);
395 
396 static void submit_flushes(struct work_struct *ws)
397 {
398         struct mddev *mddev = container_of(ws, struct mddev, flush_work);
399         struct md_rdev *rdev;
400 
401         INIT_WORK(&mddev->flush_work, md_submit_flush_data);
402         atomic_set(&mddev->flush_pending, 1);
403         rcu_read_lock();
404         rdev_for_each_rcu(rdev, mddev)
405                 if (rdev->raid_disk >= 0 &&
406                     !test_bit(Faulty, &rdev->flags)) {
407                         /* Take two references, one is dropped
408                          * when request finishes, one after
409                          * we reclaim rcu_read_lock
410                          */
411                         struct bio *bi;
412                         atomic_inc(&rdev->nr_pending);
413                         atomic_inc(&rdev->nr_pending);
414                         rcu_read_unlock();
415                         bi = bio_alloc_mddev(GFP_NOIO, 0, mddev);
416                         bi->bi_end_io = md_end_flush;
417                         bi->bi_private = rdev;
418                         bi->bi_bdev = rdev->bdev;
419                         atomic_inc(&mddev->flush_pending);
420                         submit_bio(WRITE_FLUSH, bi);
421                         rcu_read_lock();
422                         rdev_dec_pending(rdev, mddev);
423                 }
424         rcu_read_unlock();
425         if (atomic_dec_and_test(&mddev->flush_pending))
426                 queue_work(md_wq, &mddev->flush_work);
427 }
428 
429 static void md_submit_flush_data(struct work_struct *ws)
430 {
431         struct mddev *mddev = container_of(ws, struct mddev, flush_work);
432         struct bio *bio = mddev->flush_bio;
433 
434         if (bio->bi_iter.bi_size == 0)
435                 /* an empty barrier - all done */
436                 bio_endio(bio, 0);
437         else {
438                 bio->bi_rw &= ~REQ_FLUSH;
439                 mddev->pers->make_request(mddev, bio);
440         }
441 
442         mddev->flush_bio = NULL;
443         wake_up(&mddev->sb_wait);
444 }
445 
446 void md_flush_request(struct mddev *mddev, struct bio *bio)
447 {
448         spin_lock_irq(&mddev->lock);
449         wait_event_lock_irq(mddev->sb_wait,
450                             !mddev->flush_bio,
451                             mddev->lock);
452         mddev->flush_bio = bio;
453         spin_unlock_irq(&mddev->lock);
454 
455         INIT_WORK(&mddev->flush_work, submit_flushes);
456         queue_work(md_wq, &mddev->flush_work);
457 }
458 EXPORT_SYMBOL(md_flush_request);
459 
460 void md_unplug(struct blk_plug_cb *cb, bool from_schedule)
461 {
462         struct mddev *mddev = cb->data;
463         md_wakeup_thread(mddev->thread);
464         kfree(cb);
465 }
466 EXPORT_SYMBOL(md_unplug);
467 
468 static inline struct mddev *mddev_get(struct mddev *mddev)
469 {
470         atomic_inc(&mddev->active);
471         return mddev;
472 }
473 
474 static void mddev_delayed_delete(struct work_struct *ws);
475 
476 static void mddev_put(struct mddev *mddev)
477 {
478         struct bio_set *bs = NULL;
479 
480         if (!atomic_dec_and_lock(&mddev->active, &all_mddevs_lock))
481                 return;
482         if (!mddev->raid_disks && list_empty(&mddev->disks) &&
483             mddev->ctime == 0 && !mddev->hold_active) {
484                 /* Array is not configured at all, and not held active,
485                  * so destroy it */
486                 list_del_init(&mddev->all_mddevs);
487                 bs = mddev->bio_set;
488                 mddev->bio_set = NULL;
489                 if (mddev->gendisk) {
490                         /* We did a probe so need to clean up.  Call
491                          * queue_work inside the spinlock so that
492                          * flush_workqueue() after mddev_find will
493                          * succeed in waiting for the work to be done.
494                          */
495                         INIT_WORK(&mddev->del_work, mddev_delayed_delete);
496                         queue_work(md_misc_wq, &mddev->del_work);
497                 } else
498                         kfree(mddev);
499         }
500         spin_unlock(&all_mddevs_lock);
501         if (bs)
502                 bioset_free(bs);
503 }
504 
505 void mddev_init(struct mddev *mddev)
506 {
507         mutex_init(&mddev->open_mutex);
508         mutex_init(&mddev->reconfig_mutex);
509         mutex_init(&mddev->bitmap_info.mutex);
510         INIT_LIST_HEAD(&mddev->disks);
511         INIT_LIST_HEAD(&mddev->all_mddevs);
512         init_timer(&mddev->safemode_timer);
513         atomic_set(&mddev->active, 1);
514         atomic_set(&mddev->openers, 0);
515         atomic_set(&mddev->active_io, 0);
516         spin_lock_init(&mddev->lock);
517         atomic_set(&mddev->flush_pending, 0);
518         init_waitqueue_head(&mddev->sb_wait);
519         init_waitqueue_head(&mddev->recovery_wait);
520         mddev->reshape_position = MaxSector;
521         mddev->reshape_backwards = 0;
522         mddev->last_sync_action = "none";
523         mddev->resync_min = 0;
524         mddev->resync_max = MaxSector;
525         mddev->level = LEVEL_NONE;
526 }
527 EXPORT_SYMBOL_GPL(mddev_init);
528 
529 static struct mddev *mddev_find(dev_t unit)
530 {
531         struct mddev *mddev, *new = NULL;
532 
533         if (unit && MAJOR(unit) != MD_MAJOR)
534                 unit &= ~((1<<MdpMinorShift)-1);
535 
536  retry:
537         spin_lock(&all_mddevs_lock);
538 
539         if (unit) {
540                 list_for_each_entry(mddev, &all_mddevs, all_mddevs)
541                         if (mddev->unit == unit) {
542                                 mddev_get(mddev);
543                                 spin_unlock(&all_mddevs_lock);
544                                 kfree(new);
545                                 return mddev;
546                         }
547 
548                 if (new) {
549                         list_add(&new->all_mddevs, &all_mddevs);
550                         spin_unlock(&all_mddevs_lock);
551                         new->hold_active = UNTIL_IOCTL;
552                         return new;
553                 }
554         } else if (new) {
555                 /* find an unused unit number */
556                 static int next_minor = 512;
557                 int start = next_minor;
558                 int is_free = 0;
559                 int dev = 0;
560                 while (!is_free) {
561                         dev = MKDEV(MD_MAJOR, next_minor);
562                         next_minor++;
563                         if (next_minor > MINORMASK)
564                                 next_minor = 0;
565                         if (next_minor == start) {
566                                 /* Oh dear, all in use. */
567                                 spin_unlock(&all_mddevs_lock);
568                                 kfree(new);
569                                 return NULL;
570                         }
571 
572                         is_free = 1;
573                         list_for_each_entry(mddev, &all_mddevs, all_mddevs)
574                                 if (mddev->unit == dev) {
575                                         is_free = 0;
576                                         break;
577                                 }
578                 }
579                 new->unit = dev;
580                 new->md_minor = MINOR(dev);
581                 new->hold_active = UNTIL_STOP;
582                 list_add(&new->all_mddevs, &all_mddevs);
583                 spin_unlock(&all_mddevs_lock);
584                 return new;
585         }
586         spin_unlock(&all_mddevs_lock);
587 
588         new = kzalloc(sizeof(*new), GFP_KERNEL);
589         if (!new)
590                 return NULL;
591 
592         new->unit = unit;
593         if (MAJOR(unit) == MD_MAJOR)
594                 new->md_minor = MINOR(unit);
595         else
596                 new->md_minor = MINOR(unit) >> MdpMinorShift;
597 
598         mddev_init(new);
599 
600         goto retry;
601 }
602 
603 static struct attribute_group md_redundancy_group;
604 
605 void mddev_unlock(struct mddev *mddev)
606 {
607         if (mddev->to_remove) {
608                 /* These cannot be removed under reconfig_mutex as
609                  * an access to the files will try to take reconfig_mutex
610                  * while holding the file unremovable, which leads to
611                  * a deadlock.
612                  * So hold set sysfs_active while the remove in happeing,
613                  * and anything else which might set ->to_remove or my
614                  * otherwise change the sysfs namespace will fail with
615                  * -EBUSY if sysfs_active is still set.
616                  * We set sysfs_active under reconfig_mutex and elsewhere
617                  * test it under the same mutex to ensure its correct value
618                  * is seen.
619                  */
620                 struct attribute_group *to_remove = mddev->to_remove;
621                 mddev->to_remove = NULL;
622                 mddev->sysfs_active = 1;
623                 mutex_unlock(&mddev->reconfig_mutex);
624 
625                 if (mddev->kobj.sd) {
626                         if (to_remove != &md_redundancy_group)
627                                 sysfs_remove_group(&mddev->kobj, to_remove);
628                         if (mddev->pers == NULL ||
629                             mddev->pers->sync_request == NULL) {
630                                 sysfs_remove_group(&mddev->kobj, &md_redundancy_group);
631                                 if (mddev->sysfs_action)
632                                         sysfs_put(mddev->sysfs_action);
633                                 mddev->sysfs_action = NULL;
634                         }
635                 }
636                 mddev->sysfs_active = 0;
637         } else
638                 mutex_unlock(&mddev->reconfig_mutex);
639 
640         /* As we've dropped the mutex we need a spinlock to
641          * make sure the thread doesn't disappear
642          */
643         spin_lock(&pers_lock);
644         md_wakeup_thread(mddev->thread);
645         spin_unlock(&pers_lock);
646 }
647 EXPORT_SYMBOL_GPL(mddev_unlock);
648 
649 struct md_rdev *md_find_rdev_nr_rcu(struct mddev *mddev, int nr)
650 {
651         struct md_rdev *rdev;
652 
653         rdev_for_each_rcu(rdev, mddev)
654                 if (rdev->desc_nr == nr)
655                         return rdev;
656 
657         return NULL;
658 }
659 EXPORT_SYMBOL_GPL(md_find_rdev_nr_rcu);
660 
661 static struct md_rdev *find_rdev(struct mddev *mddev, dev_t dev)
662 {
663         struct md_rdev *rdev;
664 
665         rdev_for_each(rdev, mddev)
666                 if (rdev->bdev->bd_dev == dev)
667                         return rdev;
668 
669         return NULL;
670 }
671 
672 static struct md_rdev *find_rdev_rcu(struct mddev *mddev, dev_t dev)
673 {
674         struct md_rdev *rdev;
675 
676         rdev_for_each_rcu(rdev, mddev)
677                 if (rdev->bdev->bd_dev == dev)
678                         return rdev;
679 
680         return NULL;
681 }
682 
683 static struct md_personality *find_pers(int level, char *clevel)
684 {
685         struct md_personality *pers;
686         list_for_each_entry(pers, &pers_list, list) {
687                 if (level != LEVEL_NONE && pers->level == level)
688                         return pers;
689                 if (strcmp(pers->name, clevel)==0)
690                         return pers;
691         }
692         return NULL;
693 }
694 
695 /* return the offset of the super block in 512byte sectors */
696 static inline sector_t calc_dev_sboffset(struct md_rdev *rdev)
697 {
698         sector_t num_sectors = i_size_read(rdev->bdev->bd_inode) / 512;
699         return MD_NEW_SIZE_SECTORS(num_sectors);
700 }
701 
702 static int alloc_disk_sb(struct md_rdev *rdev)
703 {
704         rdev->sb_page = alloc_page(GFP_KERNEL);
705         if (!rdev->sb_page) {
706                 printk(KERN_ALERT "md: out of memory.\n");
707                 return -ENOMEM;
708         }
709 
710         return 0;
711 }
712 
713 void md_rdev_clear(struct md_rdev *rdev)
714 {
715         if (rdev->sb_page) {
716                 put_page(rdev->sb_page);
717                 rdev->sb_loaded = 0;
718                 rdev->sb_page = NULL;
719                 rdev->sb_start = 0;
720                 rdev->sectors = 0;
721         }
722         if (rdev->bb_page) {
723                 put_page(rdev->bb_page);
724                 rdev->bb_page = NULL;
725         }
726         kfree(rdev->badblocks.page);
727         rdev->badblocks.page = NULL;
728 }
729 EXPORT_SYMBOL_GPL(md_rdev_clear);
730 
731 static void super_written(struct bio *bio, int error)
732 {
733         struct md_rdev *rdev = bio->bi_private;
734         struct mddev *mddev = rdev->mddev;
735 
736         if (error || !test_bit(BIO_UPTODATE, &bio->bi_flags)) {
737                 printk("md: super_written gets error=%d, uptodate=%d\n",
738                        error, test_bit(BIO_UPTODATE, &bio->bi_flags));
739                 WARN_ON(test_bit(BIO_UPTODATE, &bio->bi_flags));
740                 md_error(mddev, rdev);
741         }
742 
743         if (atomic_dec_and_test(&mddev->pending_writes))
744                 wake_up(&mddev->sb_wait);
745         bio_put(bio);
746 }
747 
748 void md_super_write(struct mddev *mddev, struct md_rdev *rdev,
749                    sector_t sector, int size, struct page *page)
750 {
751         /* write first size bytes of page to sector of rdev
752          * Increment mddev->pending_writes before returning
753          * and decrement it on completion, waking up sb_wait
754          * if zero is reached.
755          * If an error occurred, call md_error
756          */
757         struct bio *bio = bio_alloc_mddev(GFP_NOIO, 1, mddev);
758 
759         bio->bi_bdev = rdev->meta_bdev ? rdev->meta_bdev : rdev->bdev;
760         bio->bi_iter.bi_sector = sector;
761         bio_add_page(bio, page, size, 0);
762         bio->bi_private = rdev;
763         bio->bi_end_io = super_written;
764 
765         atomic_inc(&mddev->pending_writes);
766         submit_bio(WRITE_FLUSH_FUA, bio);
767 }
768 
769 void md_super_wait(struct mddev *mddev)
770 {
771         /* wait for all superblock writes that were scheduled to complete */
772         wait_event(mddev->sb_wait, atomic_read(&mddev->pending_writes)==0);
773 }
774 
775 int sync_page_io(struct md_rdev *rdev, sector_t sector, int size,
776                  struct page *page, int rw, bool metadata_op)
777 {
778         struct bio *bio = bio_alloc_mddev(GFP_NOIO, 1, rdev->mddev);
779         int ret;
780 
781         bio->bi_bdev = (metadata_op && rdev->meta_bdev) ?
782                 rdev->meta_bdev : rdev->bdev;
783         if (metadata_op)
784                 bio->bi_iter.bi_sector = sector + rdev->sb_start;
785         else if (rdev->mddev->reshape_position != MaxSector &&
786                  (rdev->mddev->reshape_backwards ==
787                   (sector >= rdev->mddev->reshape_position)))
788                 bio->bi_iter.bi_sector = sector + rdev->new_data_offset;
789         else
790                 bio->bi_iter.bi_sector = sector + rdev->data_offset;
791         bio_add_page(bio, page, size, 0);
792         submit_bio_wait(rw, bio);
793 
794         ret = test_bit(BIO_UPTODATE, &bio->bi_flags);
795         bio_put(bio);
796         return ret;
797 }
798 EXPORT_SYMBOL_GPL(sync_page_io);
799 
800 static int read_disk_sb(struct md_rdev *rdev, int size)
801 {
802         char b[BDEVNAME_SIZE];
803 
804         if (rdev->sb_loaded)
805                 return 0;
806 
807         if (!sync_page_io(rdev, 0, size, rdev->sb_page, READ, true))
808                 goto fail;
809         rdev->sb_loaded = 1;
810         return 0;
811 
812 fail:
813         printk(KERN_WARNING "md: disabled device %s, could not read superblock.\n",
814                 bdevname(rdev->bdev,b));
815         return -EINVAL;
816 }
817 
818 static int uuid_equal(mdp_super_t *sb1, mdp_super_t *sb2)
819 {
820         return  sb1->set_uuid0 == sb2->set_uuid0 &&
821                 sb1->set_uuid1 == sb2->set_uuid1 &&
822                 sb1->set_uuid2 == sb2->set_uuid2 &&
823                 sb1->set_uuid3 == sb2->set_uuid3;
824 }
825 
826 static int sb_equal(mdp_super_t *sb1, mdp_super_t *sb2)
827 {
828         int ret;
829         mdp_super_t *tmp1, *tmp2;
830 
831         tmp1 = kmalloc(sizeof(*tmp1),GFP_KERNEL);
832         tmp2 = kmalloc(sizeof(*tmp2),GFP_KERNEL);
833 
834         if (!tmp1 || !tmp2) {
835                 ret = 0;
836                 printk(KERN_INFO "md.c sb_equal(): failed to allocate memory!\n");
837                 goto abort;
838         }
839 
840         *tmp1 = *sb1;
841         *tmp2 = *sb2;
842 
843         /*
844          * nr_disks is not constant
845          */
846         tmp1->nr_disks = 0;
847         tmp2->nr_disks = 0;
848 
849         ret = (memcmp(tmp1, tmp2, MD_SB_GENERIC_CONSTANT_WORDS * 4) == 0);
850 abort:
851         kfree(tmp1);
852         kfree(tmp2);
853         return ret;
854 }
855 
856 static u32 md_csum_fold(u32 csum)
857 {
858         csum = (csum & 0xffff) + (csum >> 16);
859         return (csum & 0xffff) + (csum >> 16);
860 }
861 
862 static unsigned int calc_sb_csum(mdp_super_t *sb)
863 {
864         u64 newcsum = 0;
865         u32 *sb32 = (u32*)sb;
866         int i;
867         unsigned int disk_csum, csum;
868 
869         disk_csum = sb->sb_csum;
870         sb->sb_csum = 0;
871 
872         for (i = 0; i < MD_SB_BYTES/4 ; i++)
873                 newcsum += sb32[i];
874         csum = (newcsum & 0xffffffff) + (newcsum>>32);
875 
876 #ifdef CONFIG_ALPHA
877         /* This used to use csum_partial, which was wrong for several
878          * reasons including that different results are returned on
879          * different architectures.  It isn't critical that we get exactly
880          * the same return value as before (we always csum_fold before
881          * testing, and that removes any differences).  However as we
882          * know that csum_partial always returned a 16bit value on
883          * alphas, do a fold to maximise conformity to previous behaviour.
884          */
885         sb->sb_csum = md_csum_fold(disk_csum);
886 #else
887         sb->sb_csum = disk_csum;
888 #endif
889         return csum;
890 }
891 
892 /*
893  * Handle superblock details.
894  * We want to be able to handle multiple superblock formats
895  * so we have a common interface to them all, and an array of
896  * different handlers.
897  * We rely on user-space to write the initial superblock, and support
898  * reading and updating of superblocks.
899  * Interface methods are:
900  *   int load_super(struct md_rdev *dev, struct md_rdev *refdev, int minor_version)
901  *      loads and validates a superblock on dev.
902  *      if refdev != NULL, compare superblocks on both devices
903  *    Return:
904  *      0 - dev has a superblock that is compatible with refdev
905  *      1 - dev has a superblock that is compatible and newer than refdev
906  *          so dev should be used as the refdev in future
907  *     -EINVAL superblock incompatible or invalid
908  *     -othererror e.g. -EIO
909  *
910  *   int validate_super(struct mddev *mddev, struct md_rdev *dev)
911  *      Verify that dev is acceptable into mddev.
912  *       The first time, mddev->raid_disks will be 0, and data from
913  *       dev should be merged in.  Subsequent calls check that dev
914  *       is new enough.  Return 0 or -EINVAL
915  *
916  *   void sync_super(struct mddev *mddev, struct md_rdev *dev)
917  *     Update the superblock for rdev with data in mddev
918  *     This does not write to disc.
919  *
920  */
921 
922 struct super_type  {
923         char                *name;
924         struct module       *owner;
925         int                 (*load_super)(struct md_rdev *rdev,
926                                           struct md_rdev *refdev,
927                                           int minor_version);
928         int                 (*validate_super)(struct mddev *mddev,
929                                               struct md_rdev *rdev);
930         void                (*sync_super)(struct mddev *mddev,
931                                           struct md_rdev *rdev);
932         unsigned long long  (*rdev_size_change)(struct md_rdev *rdev,
933                                                 sector_t num_sectors);
934         int                 (*allow_new_offset)(struct md_rdev *rdev,
935                                                 unsigned long long new_offset);
936 };
937 
938 /*
939  * Check that the given mddev has no bitmap.
940  *
941  * This function is called from the run method of all personalities that do not
942  * support bitmaps. It prints an error message and returns non-zero if mddev
943  * has a bitmap. Otherwise, it returns 0.
944  *
945  */
946 int md_check_no_bitmap(struct mddev *mddev)
947 {
948         if (!mddev->bitmap_info.file && !mddev->bitmap_info.offset)
949                 return 0;
950         printk(KERN_ERR "%s: bitmaps are not supported for %s\n",
951                 mdname(mddev), mddev->pers->name);
952         return 1;
953 }
954 EXPORT_SYMBOL(md_check_no_bitmap);
955 
956 /*
957  * load_super for 0.90.0
958  */
959 static int super_90_load(struct md_rdev *rdev, struct md_rdev *refdev, int minor_version)
960 {
961         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
962         mdp_super_t *sb;
963         int ret;
964 
965         /*
966          * Calculate the position of the superblock (512byte sectors),
967          * it's at the end of the disk.
968          *
969          * It also happens to be a multiple of 4Kb.
970          */
971         rdev->sb_start = calc_dev_sboffset(rdev);
972 
973         ret = read_disk_sb(rdev, MD_SB_BYTES);
974         if (ret) return ret;
975 
976         ret = -EINVAL;
977 
978         bdevname(rdev->bdev, b);
979         sb = page_address(rdev->sb_page);
980 
981         if (sb->md_magic != MD_SB_MAGIC) {
982                 printk(KERN_ERR "md: invalid raid superblock magic on %s\n",
983                        b);
984                 goto abort;
985         }
986 
987         if (sb->major_version != 0 ||
988             sb->minor_version < 90 ||
989             sb->minor_version > 91) {
990                 printk(KERN_WARNING "Bad version number %d.%d on %s\n",
991                         sb->major_version, sb->minor_version,
992                         b);
993                 goto abort;
994         }
995 
996         if (sb->raid_disks <= 0)
997                 goto abort;
998 
999         if (md_csum_fold(calc_sb_csum(sb)) != md_csum_fold(sb->sb_csum)) {
1000                 printk(KERN_WARNING "md: invalid superblock checksum on %s\n",
1001                         b);
1002                 goto abort;
1003         }
1004 
1005         rdev->preferred_minor = sb->md_minor;
1006         rdev->data_offset = 0;
1007         rdev->new_data_offset = 0;
1008         rdev->sb_size = MD_SB_BYTES;
1009         rdev->badblocks.shift = -1;
1010 
1011         if (sb->level == LEVEL_MULTIPATH)
1012                 rdev->desc_nr = -1;
1013         else
1014                 rdev->desc_nr = sb->this_disk.number;
1015 
1016         if (!refdev) {
1017                 ret = 1;
1018         } else {
1019                 __u64 ev1, ev2;
1020                 mdp_super_t *refsb = page_address(refdev->sb_page);
1021                 if (!uuid_equal(refsb, sb)) {
1022                         printk(KERN_WARNING "md: %s has different UUID to %s\n",
1023                                 b, bdevname(refdev->bdev,b2));
1024                         goto abort;
1025                 }
1026                 if (!sb_equal(refsb, sb)) {
1027                         printk(KERN_WARNING "md: %s has same UUID"
1028                                " but different superblock to %s\n",
1029                                b, bdevname(refdev->bdev, b2));
1030                         goto abort;
1031                 }
1032                 ev1 = md_event(sb);
1033                 ev2 = md_event(refsb);
1034                 if (ev1 > ev2)
1035                         ret = 1;
1036                 else
1037                         ret = 0;
1038         }
1039         rdev->sectors = rdev->sb_start;
1040         /* Limit to 4TB as metadata cannot record more than that.
1041          * (not needed for Linear and RAID0 as metadata doesn't
1042          * record this size)
1043          */
1044         if (rdev->sectors >= (2ULL << 32) && sb->level >= 1)
1045                 rdev->sectors = (2ULL << 32) - 2;
1046 
1047         if (rdev->sectors < ((sector_t)sb->size) * 2 && sb->level >= 1)
1048                 /* "this cannot possibly happen" ... */
1049                 ret = -EINVAL;
1050 
1051  abort:
1052         return ret;
1053 }
1054 
1055 /*
1056  * validate_super for 0.90.0
1057  */
1058 static int super_90_validate(struct mddev *mddev, struct md_rdev *rdev)
1059 {
1060         mdp_disk_t *desc;
1061         mdp_super_t *sb = page_address(rdev->sb_page);
1062         __u64 ev1 = md_event(sb);
1063 
1064         rdev->raid_disk = -1;
1065         clear_bit(Faulty, &rdev->flags);
1066         clear_bit(In_sync, &rdev->flags);
1067         clear_bit(Bitmap_sync, &rdev->flags);
1068         clear_bit(WriteMostly, &rdev->flags);
1069 
1070         if (mddev->raid_disks == 0) {
1071                 mddev->major_version = 0;
1072                 mddev->minor_version = sb->minor_version;
1073                 mddev->patch_version = sb->patch_version;
1074                 mddev->external = 0;
1075                 mddev->chunk_sectors = sb->chunk_size >> 9;
1076                 mddev->ctime = sb->ctime;
1077                 mddev->utime = sb->utime;
1078                 mddev->level = sb->level;
1079                 mddev->clevel[0] = 0;
1080                 mddev->layout = sb->layout;
1081                 mddev->raid_disks = sb->raid_disks;
1082                 mddev->dev_sectors = ((sector_t)sb->size) * 2;
1083                 mddev->events = ev1;
1084                 mddev->bitmap_info.offset = 0;
1085                 mddev->bitmap_info.space = 0;
1086                 /* bitmap can use 60 K after the 4K superblocks */
1087                 mddev->bitmap_info.default_offset = MD_SB_BYTES >> 9;
1088                 mddev->bitmap_info.default_space = 64*2 - (MD_SB_BYTES >> 9);
1089                 mddev->reshape_backwards = 0;
1090 
1091                 if (mddev->minor_version >= 91) {
1092                         mddev->reshape_position = sb->reshape_position;
1093                         mddev->delta_disks = sb->delta_disks;
1094                         mddev->new_level = sb->new_level;
1095                         mddev->new_layout = sb->new_layout;
1096                         mddev->new_chunk_sectors = sb->new_chunk >> 9;
1097                         if (mddev->delta_disks < 0)
1098                                 mddev->reshape_backwards = 1;
1099                 } else {
1100                         mddev->reshape_position = MaxSector;
1101                         mddev->delta_disks = 0;
1102                         mddev->new_level = mddev->level;
1103                         mddev->new_layout = mddev->layout;
1104                         mddev->new_chunk_sectors = mddev->chunk_sectors;
1105                 }
1106 
1107                 if (sb->state & (1<<MD_SB_CLEAN))
1108                         mddev->recovery_cp = MaxSector;
1109                 else {
1110                         if (sb->events_hi == sb->cp_events_hi &&
1111                                 sb->events_lo == sb->cp_events_lo) {
1112                                 mddev->recovery_cp = sb->recovery_cp;
1113                         } else
1114                                 mddev->recovery_cp = 0;
1115                 }
1116 
1117                 memcpy(mddev->uuid+0, &sb->set_uuid0, 4);
1118                 memcpy(mddev->uuid+4, &sb->set_uuid1, 4);
1119                 memcpy(mddev->uuid+8, &sb->set_uuid2, 4);
1120                 memcpy(mddev->uuid+12,&sb->set_uuid3, 4);
1121 
1122                 mddev->max_disks = MD_SB_DISKS;
1123 
1124                 if (sb->state & (1<<MD_SB_BITMAP_PRESENT) &&
1125                     mddev->bitmap_info.file == NULL) {
1126                         mddev->bitmap_info.offset =
1127                                 mddev->bitmap_info.default_offset;
1128                         mddev->bitmap_info.space =
1129                                 mddev->bitmap_info.default_space;
1130                 }
1131 
1132         } else if (mddev->pers == NULL) {
1133                 /* Insist on good event counter while assembling, except
1134                  * for spares (which don't need an event count) */
1135                 ++ev1;
1136                 if (sb->disks[rdev->desc_nr].state & (
1137                             (1<<MD_DISK_SYNC) | (1 << MD_DISK_ACTIVE)))
1138                         if (ev1 < mddev->events)
1139                                 return -EINVAL;
1140         } else if (mddev->bitmap) {
1141                 /* if adding to array with a bitmap, then we can accept an
1142                  * older device ... but not too old.
1143                  */
1144                 if (ev1 < mddev->bitmap->events_cleared)
1145                         return 0;
1146                 if (ev1 < mddev->events)
1147                         set_bit(Bitmap_sync, &rdev->flags);
1148         } else {
1149                 if (ev1 < mddev->events)
1150                         /* just a hot-add of a new device, leave raid_disk at -1 */
1151                         return 0;
1152         }
1153 
1154         if (mddev->level != LEVEL_MULTIPATH) {
1155                 desc = sb->disks + rdev->desc_nr;
1156 
1157                 if (desc->state & (1<<MD_DISK_FAULTY))
1158                         set_bit(Faulty, &rdev->flags);
1159                 else if (desc->state & (1<<MD_DISK_SYNC) /* &&
1160                             desc->raid_disk < mddev->raid_disks */) {
1161                         set_bit(In_sync, &rdev->flags);
1162                         rdev->raid_disk = desc->raid_disk;
1163                         rdev->saved_raid_disk = desc->raid_disk;
1164                 } else if (desc->state & (1<<MD_DISK_ACTIVE)) {
1165                         /* active but not in sync implies recovery up to
1166                          * reshape position.  We don't know exactly where
1167                          * that is, so set to zero for now */
1168                         if (mddev->minor_version >= 91) {
1169                                 rdev->recovery_offset = 0;
1170                                 rdev->raid_disk = desc->raid_disk;
1171                         }
1172                 }
1173                 if (desc->state & (1<<MD_DISK_WRITEMOSTLY))
1174                         set_bit(WriteMostly, &rdev->flags);
1175         } else /* MULTIPATH are always insync */
1176                 set_bit(In_sync, &rdev->flags);
1177         return 0;
1178 }
1179 
1180 /*
1181  * sync_super for 0.90.0
1182  */
1183 static void super_90_sync(struct mddev *mddev, struct md_rdev *rdev)
1184 {
1185         mdp_super_t *sb;
1186         struct md_rdev *rdev2;
1187         int next_spare = mddev->raid_disks;
1188 
1189         /* make rdev->sb match mddev data..
1190          *
1191          * 1/ zero out disks
1192          * 2/ Add info for each disk, keeping track of highest desc_nr (next_spare);
1193          * 3/ any empty disks < next_spare become removed
1194          *
1195          * disks[0] gets initialised to REMOVED because
1196          * we cannot be sure from other fields if it has
1197          * been initialised or not.
1198          */
1199         int i;
1200         int active=0, working=0,failed=0,spare=0,nr_disks=0;
1201 
1202         rdev->sb_size = MD_SB_BYTES;
1203 
1204         sb = page_address(rdev->sb_page);
1205 
1206         memset(sb, 0, sizeof(*sb));
1207 
1208         sb->md_magic = MD_SB_MAGIC;
1209         sb->major_version = mddev->major_version;
1210         sb->patch_version = mddev->patch_version;
1211         sb->gvalid_words  = 0; /* ignored */
1212         memcpy(&sb->set_uuid0, mddev->uuid+0, 4);
1213         memcpy(&sb->set_uuid1, mddev->uuid+4, 4);
1214         memcpy(&sb->set_uuid2, mddev->uuid+8, 4);
1215         memcpy(&sb->set_uuid3, mddev->uuid+12,4);
1216 
1217         sb->ctime = mddev->ctime;
1218         sb->level = mddev->level;
1219         sb->size = mddev->dev_sectors / 2;
1220         sb->raid_disks = mddev->raid_disks;
1221         sb->md_minor = mddev->md_minor;
1222         sb->not_persistent = 0;
1223         sb->utime = mddev->utime;
1224         sb->state = 0;
1225         sb->events_hi = (mddev->events>>32);
1226         sb->events_lo = (u32)mddev->events;
1227 
1228         if (mddev->reshape_position == MaxSector)
1229                 sb->minor_version = 90;
1230         else {
1231                 sb->minor_version = 91;
1232                 sb->reshape_position = mddev->reshape_position;
1233                 sb->new_level = mddev->new_level;
1234                 sb->delta_disks = mddev->delta_disks;
1235                 sb->new_layout = mddev->new_layout;
1236                 sb->new_chunk = mddev->new_chunk_sectors << 9;
1237         }
1238         mddev->minor_version = sb->minor_version;
1239         if (mddev->in_sync)
1240         {
1241                 sb->recovery_cp = mddev->recovery_cp;
1242                 sb->cp_events_hi = (mddev->events>>32);
1243                 sb->cp_events_lo = (u32)mddev->events;
1244                 if (mddev->recovery_cp == MaxSector)
1245                         sb->state = (1<< MD_SB_CLEAN);
1246         } else
1247                 sb->recovery_cp = 0;
1248 
1249         sb->layout = mddev->layout;
1250         sb->chunk_size = mddev->chunk_sectors << 9;
1251 
1252         if (mddev->bitmap && mddev->bitmap_info.file == NULL)
1253                 sb->state |= (1<<MD_SB_BITMAP_PRESENT);
1254 
1255         sb->disks[0].state = (1<<MD_DISK_REMOVED);
1256         rdev_for_each(rdev2, mddev) {
1257                 mdp_disk_t *d;
1258                 int desc_nr;
1259                 int is_active = test_bit(In_sync, &rdev2->flags);
1260 
1261                 if (rdev2->raid_disk >= 0 &&
1262                     sb->minor_version >= 91)
1263                         /* we have nowhere to store the recovery_offset,
1264                          * but if it is not below the reshape_position,
1265                          * we can piggy-back on that.
1266                          */
1267                         is_active = 1;
1268                 if (rdev2->raid_disk < 0 ||
1269                     test_bit(Faulty, &rdev2->flags))
1270                         is_active = 0;
1271                 if (is_active)
1272                         desc_nr = rdev2->raid_disk;
1273                 else
1274                         desc_nr = next_spare++;
1275                 rdev2->desc_nr = desc_nr;
1276                 d = &sb->disks[rdev2->desc_nr];
1277                 nr_disks++;
1278                 d->number = rdev2->desc_nr;
1279                 d->major = MAJOR(rdev2->bdev->bd_dev);
1280                 d->minor = MINOR(rdev2->bdev->bd_dev);
1281                 if (is_active)
1282                         d->raid_disk = rdev2->raid_disk;
1283                 else
1284                         d->raid_disk = rdev2->desc_nr; /* compatibility */
1285                 if (test_bit(Faulty, &rdev2->flags))
1286                         d->state = (1<<MD_DISK_FAULTY);
1287                 else if (is_active) {
1288                         d->state = (1<<MD_DISK_ACTIVE);
1289                         if (test_bit(In_sync, &rdev2->flags))
1290                                 d->state |= (1<<MD_DISK_SYNC);
1291                         active++;
1292                         working++;
1293                 } else {
1294                         d->state = 0;
1295                         spare++;
1296                         working++;
1297                 }
1298                 if (test_bit(WriteMostly, &rdev2->flags))
1299                         d->state |= (1<<MD_DISK_WRITEMOSTLY);
1300         }
1301         /* now set the "removed" and "faulty" bits on any missing devices */
1302         for (i=0 ; i < mddev->raid_disks ; i++) {
1303                 mdp_disk_t *d = &sb->disks[i];
1304                 if (d->state == 0 && d->number == 0) {
1305                         d->number = i;
1306                         d->raid_disk = i;
1307                         d->state = (1<<MD_DISK_REMOVED);
1308                         d->state |= (1<<MD_DISK_FAULTY);
1309                         failed++;
1310                 }
1311         }
1312         sb->nr_disks = nr_disks;
1313         sb->active_disks = active;
1314         sb->working_disks = working;
1315         sb->failed_disks = failed;
1316         sb->spare_disks = spare;
1317 
1318         sb->this_disk = sb->disks[rdev->desc_nr];
1319         sb->sb_csum = calc_sb_csum(sb);
1320 }
1321 
1322 /*
1323  * rdev_size_change for 0.90.0
1324  */
1325 static unsigned long long
1326 super_90_rdev_size_change(struct md_rdev *rdev, sector_t num_sectors)
1327 {
1328         if (num_sectors && num_sectors < rdev->mddev->dev_sectors)
1329                 return 0; /* component must fit device */
1330         if (rdev->mddev->bitmap_info.offset)
1331                 return 0; /* can't move bitmap */
1332         rdev->sb_start = calc_dev_sboffset(rdev);
1333         if (!num_sectors || num_sectors > rdev->sb_start)
1334                 num_sectors = rdev->sb_start;
1335         /* Limit to 4TB as metadata cannot record more than that.
1336          * 4TB == 2^32 KB, or 2*2^32 sectors.
1337          */
1338         if (num_sectors >= (2ULL << 32) && rdev->mddev->level >= 1)
1339                 num_sectors = (2ULL << 32) - 2;
1340         md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
1341                        rdev->sb_page);
1342         md_super_wait(rdev->mddev);
1343         return num_sectors;
1344 }
1345 
1346 static int
1347 super_90_allow_new_offset(struct md_rdev *rdev, unsigned long long new_offset)
1348 {
1349         /* non-zero offset changes not possible with v0.90 */
1350         return new_offset == 0;
1351 }
1352 
1353 /*
1354  * version 1 superblock
1355  */
1356 
1357 static __le32 calc_sb_1_csum(struct mdp_superblock_1 *sb)
1358 {
1359         __le32 disk_csum;
1360         u32 csum;
1361         unsigned long long newcsum;
1362         int size = 256 + le32_to_cpu(sb->max_dev)*2;
1363         __le32 *isuper = (__le32*)sb;
1364 
1365         disk_csum = sb->sb_csum;
1366         sb->sb_csum = 0;
1367         newcsum = 0;
1368         for (; size >= 4; size -= 4)
1369                 newcsum += le32_to_cpu(*isuper++);
1370 
1371         if (size == 2)
1372                 newcsum += le16_to_cpu(*(__le16*) isuper);
1373 
1374         csum = (newcsum & 0xffffffff) + (newcsum >> 32);
1375         sb->sb_csum = disk_csum;
1376         return cpu_to_le32(csum);
1377 }
1378 
1379 static int md_set_badblocks(struct badblocks *bb, sector_t s, int sectors,
1380                             int acknowledged);
1381 static int super_1_load(struct md_rdev *rdev, struct md_rdev *refdev, int minor_version)
1382 {
1383         struct mdp_superblock_1 *sb;
1384         int ret;
1385         sector_t sb_start;
1386         sector_t sectors;
1387         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1388         int bmask;
1389 
1390         /*
1391          * Calculate the position of the superblock in 512byte sectors.
1392          * It is always aligned to a 4K boundary and
1393          * depeding on minor_version, it can be:
1394          * 0: At least 8K, but less than 12K, from end of device
1395          * 1: At start of device
1396          * 2: 4K from start of device.
1397          */
1398         switch(minor_version) {
1399         case 0:
1400                 sb_start = i_size_read(rdev->bdev->bd_inode) >> 9;
1401                 sb_start -= 8*2;
1402                 sb_start &= ~(sector_t)(4*2-1);
1403                 break;
1404         case 1:
1405                 sb_start = 0;
1406                 break;
1407         case 2:
1408                 sb_start = 8;
1409                 break;
1410         default:
1411                 return -EINVAL;
1412         }
1413         rdev->sb_start = sb_start;
1414 
1415         /* superblock is rarely larger than 1K, but it can be larger,
1416          * and it is safe to read 4k, so we do that
1417          */
1418         ret = read_disk_sb(rdev, 4096);
1419         if (ret) return ret;
1420 
1421         sb = page_address(rdev->sb_page);
1422 
1423         if (sb->magic != cpu_to_le32(MD_SB_MAGIC) ||
1424             sb->major_version != cpu_to_le32(1) ||
1425             le32_to_cpu(sb->max_dev) > (4096-256)/2 ||
1426             le64_to_cpu(sb->super_offset) != rdev->sb_start ||
1427             (le32_to_cpu(sb->feature_map) & ~MD_FEATURE_ALL) != 0)
1428                 return -EINVAL;
1429 
1430         if (calc_sb_1_csum(sb) != sb->sb_csum) {
1431                 printk("md: invalid superblock checksum on %s\n",
1432                         bdevname(rdev->bdev,b));
1433                 return -EINVAL;
1434         }
1435         if (le64_to_cpu(sb->data_size) < 10) {
1436                 printk("md: data_size too small on %s\n",
1437                        bdevname(rdev->bdev,b));
1438                 return -EINVAL;
1439         }
1440         if (sb->pad0 ||
1441             sb->pad3[0] ||
1442             memcmp(sb->pad3, sb->pad3+1, sizeof(sb->pad3) - sizeof(sb->pad3[1])))
1443                 /* Some padding is non-zero, might be a new feature */
1444                 return -EINVAL;
1445 
1446         rdev->preferred_minor = 0xffff;
1447         rdev->data_offset = le64_to_cpu(sb->data_offset);
1448         rdev->new_data_offset = rdev->data_offset;
1449         if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE) &&
1450             (le32_to_cpu(sb->feature_map) & MD_FEATURE_NEW_OFFSET))
1451                 rdev->new_data_offset += (s32)le32_to_cpu(sb->new_offset);
1452         atomic_set(&rdev->corrected_errors, le32_to_cpu(sb->cnt_corrected_read));
1453 
1454         rdev->sb_size = le32_to_cpu(sb->max_dev) * 2 + 256;
1455         bmask = queue_logical_block_size(rdev->bdev->bd_disk->queue)-1;
1456         if (rdev->sb_size & bmask)
1457                 rdev->sb_size = (rdev->sb_size | bmask) + 1;
1458 
1459         if (minor_version
1460             && rdev->data_offset < sb_start + (rdev->sb_size/512))
1461                 return -EINVAL;
1462         if (minor_version
1463             && rdev->new_data_offset < sb_start + (rdev->sb_size/512))
1464                 return -EINVAL;
1465 
1466         if (sb->level == cpu_to_le32(LEVEL_MULTIPATH))
1467                 rdev->desc_nr = -1;
1468         else
1469                 rdev->desc_nr = le32_to_cpu(sb->dev_number);
1470 
1471         if (!rdev->bb_page) {
1472                 rdev->bb_page = alloc_page(GFP_KERNEL);
1473                 if (!rdev->bb_page)
1474                         return -ENOMEM;
1475         }
1476         if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BAD_BLOCKS) &&
1477             rdev->badblocks.count == 0) {
1478                 /* need to load the bad block list.
1479                  * Currently we limit it to one page.
1480                  */
1481                 s32 offset;
1482                 sector_t bb_sector;
1483                 u64 *bbp;
1484                 int i;
1485                 int sectors = le16_to_cpu(sb->bblog_size);
1486                 if (sectors > (PAGE_SIZE / 512))
1487                         return -EINVAL;
1488                 offset = le32_to_cpu(sb->bblog_offset);
1489                 if (offset == 0)
1490                         return -EINVAL;
1491                 bb_sector = (long long)offset;
1492                 if (!sync_page_io(rdev, bb_sector, sectors << 9,
1493                                   rdev->bb_page, READ, true))
1494                         return -EIO;
1495                 bbp = (u64 *)page_address(rdev->bb_page);
1496                 rdev->badblocks.shift = sb->bblog_shift;
1497                 for (i = 0 ; i < (sectors << (9-3)) ; i++, bbp++) {
1498                         u64 bb = le64_to_cpu(*bbp);
1499                         int count = bb & (0x3ff);
1500                         u64 sector = bb >> 10;
1501                         sector <<= sb->bblog_shift;
1502                         count <<= sb->bblog_shift;
1503                         if (bb + 1 == 0)
1504                                 break;
1505                         if (md_set_badblocks(&rdev->badblocks,
1506                                              sector, count, 1) == 0)
1507                                 return -EINVAL;
1508                 }
1509         } else if (sb->bblog_offset != 0)
1510                 rdev->badblocks.shift = 0;
1511 
1512         if (!refdev) {
1513                 ret = 1;
1514         } else {
1515                 __u64 ev1, ev2;
1516                 struct mdp_superblock_1 *refsb = page_address(refdev->sb_page);
1517 
1518                 if (memcmp(sb->set_uuid, refsb->set_uuid, 16) != 0 ||
1519                     sb->level != refsb->level ||
1520                     sb->layout != refsb->layout ||
1521                     sb->chunksize != refsb->chunksize) {
1522                         printk(KERN_WARNING "md: %s has strangely different"
1523                                 " superblock to %s\n",
1524                                 bdevname(rdev->bdev,b),
1525                                 bdevname(refdev->bdev,b2));
1526                         return -EINVAL;
1527                 }
1528                 ev1 = le64_to_cpu(sb->events);
1529                 ev2 = le64_to_cpu(refsb->events);
1530 
1531                 if (ev1 > ev2)
1532                         ret = 1;
1533                 else
1534                         ret = 0;
1535         }
1536         if (minor_version) {
1537                 sectors = (i_size_read(rdev->bdev->bd_inode) >> 9);
1538                 sectors -= rdev->data_offset;
1539         } else
1540                 sectors = rdev->sb_start;
1541         if (sectors < le64_to_cpu(sb->data_size))
1542                 return -EINVAL;
1543         rdev->sectors = le64_to_cpu(sb->data_size);
1544         return ret;
1545 }
1546 
1547 static int super_1_validate(struct mddev *mddev, struct md_rdev *rdev)
1548 {
1549         struct mdp_superblock_1 *sb = page_address(rdev->sb_page);
1550         __u64 ev1 = le64_to_cpu(sb->events);
1551 
1552         rdev->raid_disk = -1;
1553         clear_bit(Faulty, &rdev->flags);
1554         clear_bit(In_sync, &rdev->flags);
1555         clear_bit(Bitmap_sync, &rdev->flags);
1556         clear_bit(WriteMostly, &rdev->flags);
1557 
1558         if (mddev->raid_disks == 0) {
1559                 mddev->major_version = 1;
1560                 mddev->patch_version = 0;
1561                 mddev->external = 0;
1562                 mddev->chunk_sectors = le32_to_cpu(sb->chunksize);
1563                 mddev->ctime = le64_to_cpu(sb->ctime) & ((1ULL << 32)-1);
1564                 mddev->utime = le64_to_cpu(sb->utime) & ((1ULL << 32)-1);
1565                 mddev->level = le32_to_cpu(sb->level);
1566                 mddev->clevel[0] = 0;
1567                 mddev->layout = le32_to_cpu(sb->layout);
1568                 mddev->raid_disks = le32_to_cpu(sb->raid_disks);
1569                 mddev->dev_sectors = le64_to_cpu(sb->size);
1570                 mddev->events = ev1;
1571                 mddev->bitmap_info.offset = 0;
1572                 mddev->bitmap_info.space = 0;
1573                 /* Default location for bitmap is 1K after superblock
1574                  * using 3K - total of 4K
1575                  */
1576                 mddev->bitmap_info.default_offset = 1024 >> 9;
1577                 mddev->bitmap_info.default_space = (4096-1024) >> 9;
1578                 mddev->reshape_backwards = 0;
1579 
1580                 mddev->recovery_cp = le64_to_cpu(sb->resync_offset);
1581                 memcpy(mddev->uuid, sb->set_uuid, 16);
1582 
1583                 mddev->max_disks =  (4096-256)/2;
1584 
1585                 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BITMAP_OFFSET) &&
1586                     mddev->bitmap_info.file == NULL) {
1587                         mddev->bitmap_info.offset =
1588                                 (__s32)le32_to_cpu(sb->bitmap_offset);
1589                         /* Metadata doesn't record how much space is available.
1590                          * For 1.0, we assume we can use up to the superblock
1591                          * if before, else to 4K beyond superblock.
1592                          * For others, assume no change is possible.
1593                          */
1594                         if (mddev->minor_version > 0)
1595                                 mddev->bitmap_info.space = 0;
1596                         else if (mddev->bitmap_info.offset > 0)
1597                                 mddev->bitmap_info.space =
1598                                         8 - mddev->bitmap_info.offset;
1599                         else
1600                                 mddev->bitmap_info.space =
1601                                         -mddev->bitmap_info.offset;
1602                 }
1603 
1604                 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE)) {
1605                         mddev->reshape_position = le64_to_cpu(sb->reshape_position);
1606                         mddev->delta_disks = le32_to_cpu(sb->delta_disks);
1607                         mddev->new_level = le32_to_cpu(sb->new_level);
1608                         mddev->new_layout = le32_to_cpu(sb->new_layout);
1609                         mddev->new_chunk_sectors = le32_to_cpu(sb->new_chunk);
1610                         if (mddev->delta_disks < 0 ||
1611                             (mddev->delta_disks == 0 &&
1612                              (le32_to_cpu(sb->feature_map)
1613                               & MD_FEATURE_RESHAPE_BACKWARDS)))
1614                                 mddev->reshape_backwards = 1;
1615                 } else {
1616                         mddev->reshape_position = MaxSector;
1617                         mddev->delta_disks = 0;
1618                         mddev->new_level = mddev->level;
1619                         mddev->new_layout = mddev->layout;
1620                         mddev->new_chunk_sectors = mddev->chunk_sectors;
1621                 }
1622 
1623         } else if (mddev->pers == NULL) {
1624                 /* Insist of good event counter while assembling, except for
1625                  * spares (which don't need an event count) */
1626                 ++ev1;
1627                 if (rdev->desc_nr >= 0 &&
1628                     rdev->desc_nr < le32_to_cpu(sb->max_dev) &&
1629                     le16_to_cpu(sb->dev_roles[rdev->desc_nr]) < 0xfffe)
1630                         if (ev1 < mddev->events)
1631                                 return -EINVAL;
1632         } else if (mddev->bitmap) {
1633                 /* If adding to array with a bitmap, then we can accept an
1634                  * older device, but not too old.
1635                  */
1636                 if (ev1 < mddev->bitmap->events_cleared)
1637                         return 0;
1638                 if (ev1 < mddev->events)
1639                         set_bit(Bitmap_sync, &rdev->flags);
1640         } else {
1641                 if (ev1 < mddev->events)
1642                         /* just a hot-add of a new device, leave raid_disk at -1 */
1643                         return 0;
1644         }
1645         if (mddev->level != LEVEL_MULTIPATH) {
1646                 int role;
1647                 if (rdev->desc_nr < 0 ||
1648                     rdev->desc_nr >= le32_to_cpu(sb->max_dev)) {
1649                         role = 0xffff;
1650                         rdev->desc_nr = -1;
1651                 } else
1652                         role = le16_to_cpu(sb->dev_roles[rdev->desc_nr]);
1653                 switch(role) {
1654                 case 0xffff: /* spare */
1655                         break;
1656                 case 0xfffe: /* faulty */
1657                         set_bit(Faulty, &rdev->flags);
1658                         break;
1659                 default:
1660                         rdev->saved_raid_disk = role;
1661                         if ((le32_to_cpu(sb->feature_map) &
1662                              MD_FEATURE_RECOVERY_OFFSET)) {
1663                                 rdev->recovery_offset = le64_to_cpu(sb->recovery_offset);
1664                                 if (!(le32_to_cpu(sb->feature_map) &
1665                                       MD_FEATURE_RECOVERY_BITMAP))
1666                                         rdev->saved_raid_disk = -1;
1667                         } else
1668                                 set_bit(In_sync, &rdev->flags);
1669                         rdev->raid_disk = role;
1670                         break;
1671                 }
1672                 if (sb->devflags & WriteMostly1)
1673                         set_bit(WriteMostly, &rdev->flags);
1674                 if (le32_to_cpu(sb->feature_map) & MD_FEATURE_REPLACEMENT)
1675                         set_bit(Replacement, &rdev->flags);
1676         } else /* MULTIPATH are always insync */
1677                 set_bit(In_sync, &rdev->flags);
1678 
1679         return 0;
1680 }
1681 
1682 static void super_1_sync(struct mddev *mddev, struct md_rdev *rdev)
1683 {
1684         struct mdp_superblock_1 *sb;
1685         struct md_rdev *rdev2;
1686         int max_dev, i;
1687         /* make rdev->sb match mddev and rdev data. */
1688 
1689         sb = page_address(rdev->sb_page);
1690 
1691         sb->feature_map = 0;
1692         sb->pad0 = 0;
1693         sb->recovery_offset = cpu_to_le64(0);
1694         memset(sb->pad3, 0, sizeof(sb->pad3));
1695 
1696         sb->utime = cpu_to_le64((__u64)mddev->utime);
1697         sb->events = cpu_to_le64(mddev->events);
1698         if (mddev->in_sync)
1699                 sb->resync_offset = cpu_to_le64(mddev->recovery_cp);
1700         else
1701                 sb->resync_offset = cpu_to_le64(0);
1702 
1703         sb->cnt_corrected_read = cpu_to_le32(atomic_read(&rdev->corrected_errors));
1704 
1705         sb->raid_disks = cpu_to_le32(mddev->raid_disks);
1706         sb->size = cpu_to_le64(mddev->dev_sectors);
1707         sb->chunksize = cpu_to_le32(mddev->chunk_sectors);
1708         sb->level = cpu_to_le32(mddev->level);
1709         sb->layout = cpu_to_le32(mddev->layout);
1710 
1711         if (test_bit(WriteMostly, &rdev->flags))
1712                 sb->devflags |= WriteMostly1;
1713         else
1714                 sb->devflags &= ~WriteMostly1;
1715         sb->data_offset = cpu_to_le64(rdev->data_offset);
1716         sb->data_size = cpu_to_le64(rdev->sectors);
1717 
1718         if (mddev->bitmap && mddev->bitmap_info.file == NULL) {
1719                 sb->bitmap_offset = cpu_to_le32((__u32)mddev->bitmap_info.offset);
1720                 sb->feature_map = cpu_to_le32(MD_FEATURE_BITMAP_OFFSET);
1721         }
1722 
1723         if (rdev->raid_disk >= 0 &&
1724             !test_bit(In_sync, &rdev->flags)) {
1725                 sb->feature_map |=
1726                         cpu_to_le32(MD_FEATURE_RECOVERY_OFFSET);
1727                 sb->recovery_offset =
1728                         cpu_to_le64(rdev->recovery_offset);
1729                 if (rdev->saved_raid_disk >= 0 && mddev->bitmap)
1730                         sb->feature_map |=
1731                                 cpu_to_le32(MD_FEATURE_RECOVERY_BITMAP);
1732         }
1733         if (test_bit(Replacement, &rdev->flags))
1734                 sb->feature_map |=
1735                         cpu_to_le32(MD_FEATURE_REPLACEMENT);
1736 
1737         if (mddev->reshape_position != MaxSector) {
1738                 sb->feature_map |= cpu_to_le32(MD_FEATURE_RESHAPE_ACTIVE);
1739                 sb->reshape_position = cpu_to_le64(mddev->reshape_position);
1740                 sb->new_layout = cpu_to_le32(mddev->new_layout);
1741                 sb->delta_disks = cpu_to_le32(mddev->delta_disks);
1742                 sb->new_level = cpu_to_le32(mddev->new_level);
1743                 sb->new_chunk = cpu_to_le32(mddev->new_chunk_sectors);
1744                 if (mddev->delta_disks == 0 &&
1745                     mddev->reshape_backwards)
1746                         sb->feature_map
1747                                 |= cpu_to_le32(MD_FEATURE_RESHAPE_BACKWARDS);
1748                 if (rdev->new_data_offset != rdev->data_offset) {
1749                         sb->feature_map
1750                                 |= cpu_to_le32(MD_FEATURE_NEW_OFFSET);
1751                         sb->new_offset = cpu_to_le32((__u32)(rdev->new_data_offset
1752                                                              - rdev->data_offset));
1753                 }
1754         }
1755 
1756         if (rdev->badblocks.count == 0)
1757                 /* Nothing to do for bad blocks*/ ;
1758         else if (sb->bblog_offset == 0)
1759                 /* Cannot record bad blocks on this device */
1760                 md_error(mddev, rdev);
1761         else {
1762                 struct badblocks *bb = &rdev->badblocks;
1763                 u64 *bbp = (u64 *)page_address(rdev->bb_page);
1764                 u64 *p = bb->page;
1765                 sb->feature_map |= cpu_to_le32(MD_FEATURE_BAD_BLOCKS);
1766                 if (bb->changed) {
1767                         unsigned seq;
1768 
1769 retry:
1770                         seq = read_seqbegin(&bb->lock);
1771 
1772                         memset(bbp, 0xff, PAGE_SIZE);
1773 
1774                         for (i = 0 ; i < bb->count ; i++) {
1775                                 u64 internal_bb = p[i];
1776                                 u64 store_bb = ((BB_OFFSET(internal_bb) << 10)
1777                                                 | BB_LEN(internal_bb));
1778                                 bbp[i] = cpu_to_le64(store_bb);
1779                         }
1780                         bb->changed = 0;
1781                         if (read_seqretry(&bb->lock, seq))
1782                                 goto retry;
1783 
1784                         bb->sector = (rdev->sb_start +
1785                                       (int)le32_to_cpu(sb->bblog_offset));
1786                         bb->size = le16_to_cpu(sb->bblog_size);
1787                 }
1788         }
1789 
1790         max_dev = 0;
1791         rdev_for_each(rdev2, mddev)
1792                 if (rdev2->desc_nr+1 > max_dev)
1793                         max_dev = rdev2->desc_nr+1;
1794 
1795         if (max_dev > le32_to_cpu(sb->max_dev)) {
1796                 int bmask;
1797                 sb->max_dev = cpu_to_le32(max_dev);
1798                 rdev->sb_size = max_dev * 2 + 256;
1799                 bmask = queue_logical_block_size(rdev->bdev->bd_disk->queue)-1;
1800                 if (rdev->sb_size & bmask)
1801                         rdev->sb_size = (rdev->sb_size | bmask) + 1;
1802         } else
1803                 max_dev = le32_to_cpu(sb->max_dev);
1804 
1805         for (i=0; i<max_dev;i++)
1806                 sb->dev_roles[i] = cpu_to_le16(0xfffe);
1807 
1808         rdev_for_each(rdev2, mddev) {
1809                 i = rdev2->desc_nr;
1810                 if (test_bit(Faulty, &rdev2->flags))
1811                         sb->dev_roles[i] = cpu_to_le16(0xfffe);
1812                 else if (test_bit(In_sync, &rdev2->flags))
1813                         sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1814                 else if (rdev2->raid_disk >= 0)
1815                         sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1816                 else
1817                         sb->dev_roles[i] = cpu_to_le16(0xffff);
1818         }
1819 
1820         sb->sb_csum = calc_sb_1_csum(sb);
1821 }
1822 
1823 static unsigned long long
1824 super_1_rdev_size_change(struct md_rdev *rdev, sector_t num_sectors)
1825 {
1826         struct mdp_superblock_1 *sb;
1827         sector_t max_sectors;
1828         if (num_sectors && num_sectors < rdev->mddev->dev_sectors)
1829                 return 0; /* component must fit device */
1830         if (rdev->data_offset != rdev->new_data_offset)
1831                 return 0; /* too confusing */
1832         if (rdev->sb_start < rdev->data_offset) {
1833                 /* minor versions 1 and 2; superblock before data */
1834                 max_sectors = i_size_read(rdev->bdev->bd_inode) >> 9;
1835                 max_sectors -= rdev->data_offset;
1836                 if (!num_sectors || num_sectors > max_sectors)
1837                         num_sectors = max_sectors;
1838         } else if (rdev->mddev->bitmap_info.offset) {
1839                 /* minor version 0 with bitmap we can't move */
1840                 return 0;
1841         } else {
1842                 /* minor version 0; superblock after data */
1843                 sector_t sb_start;
1844                 sb_start = (i_size_read(rdev->bdev->bd_inode) >> 9) - 8*2;
1845                 sb_start &= ~(sector_t)(4*2 - 1);
1846                 max_sectors = rdev->sectors + sb_start - rdev->sb_start;
1847                 if (!num_sectors || num_sectors > max_sectors)
1848                         num_sectors = max_sectors;
1849                 rdev->sb_start = sb_start;
1850         }
1851         sb = page_address(rdev->sb_page);
1852         sb->data_size = cpu_to_le64(num_sectors);
1853         sb->super_offset = rdev->sb_start;
1854         sb->sb_csum = calc_sb_1_csum(sb);
1855         md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
1856                        rdev->sb_page);
1857         md_super_wait(rdev->mddev);
1858         return num_sectors;
1859 
1860 }
1861 
1862 static int
1863 super_1_allow_new_offset(struct md_rdev *rdev,
1864                          unsigned long long new_offset)
1865 {
1866         /* All necessary checks on new >= old have been done */
1867         struct bitmap *bitmap;
1868         if (new_offset >= rdev->data_offset)
1869                 return 1;
1870 
1871         /* with 1.0 metadata, there is no metadata to tread on
1872          * so we can always move back */
1873         if (rdev->mddev->minor_version == 0)
1874                 return 1;
1875 
1876         /* otherwise we must be sure not to step on
1877          * any metadata, so stay:
1878          * 36K beyond start of superblock
1879          * beyond end of badblocks
1880          * beyond write-intent bitmap
1881          */
1882         if (rdev->sb_start + (32+4)*2 > new_offset)
1883                 return 0;
1884         bitmap = rdev->mddev->bitmap;
1885         if (bitmap && !rdev->mddev->bitmap_info.file &&
1886             rdev->sb_start + rdev->mddev->bitmap_info.offset +
1887             bitmap->storage.file_pages * (PAGE_SIZE>>9) > new_offset)
1888                 return 0;
1889         if (rdev->badblocks.sector + rdev->badblocks.size > new_offset)
1890                 return 0;
1891 
1892         return 1;
1893 }
1894 
1895 static struct super_type super_types[] = {
1896         [0] = {
1897                 .name   = "0.90.0",
1898                 .owner  = THIS_MODULE,
1899                 .load_super         = super_90_load,
1900                 .validate_super     = super_90_validate,
1901                 .sync_super         = super_90_sync,
1902                 .rdev_size_change   = super_90_rdev_size_change,
1903                 .allow_new_offset   = super_90_allow_new_offset,
1904         },
1905         [1] = {
1906                 .name   = "md-1",
1907                 .owner  = THIS_MODULE,
1908                 .load_super         = super_1_load,
1909                 .validate_super     = super_1_validate,
1910                 .sync_super         = super_1_sync,
1911                 .rdev_size_change   = super_1_rdev_size_change,
1912                 .allow_new_offset   = super_1_allow_new_offset,
1913         },
1914 };
1915 
1916 static void sync_super(struct mddev *mddev, struct md_rdev *rdev)
1917 {
1918         if (mddev->sync_super) {
1919                 mddev->sync_super(mddev, rdev);
1920                 return;
1921         }
1922 
1923         BUG_ON(mddev->major_version >= ARRAY_SIZE(super_types));
1924 
1925         super_types[mddev->major_version].sync_super(mddev, rdev);
1926 }
1927 
1928 static int match_mddev_units(struct mddev *mddev1, struct mddev *mddev2)
1929 {
1930         struct md_rdev *rdev, *rdev2;
1931 
1932         rcu_read_lock();
1933         rdev_for_each_rcu(rdev, mddev1)
1934                 rdev_for_each_rcu(rdev2, mddev2)
1935                         if (rdev->bdev->bd_contains ==
1936                             rdev2->bdev->bd_contains) {
1937                                 rcu_read_unlock();
1938                                 return 1;
1939                         }
1940         rcu_read_unlock();
1941         return 0;
1942 }
1943 
1944 static LIST_HEAD(pending_raid_disks);
1945 
1946 /*
1947  * Try to register data integrity profile for an mddev
1948  *
1949  * This is called when an array is started and after a disk has been kicked
1950  * from the array. It only succeeds if all working and active component devices
1951  * are integrity capable with matching profiles.
1952  */
1953 int md_integrity_register(struct mddev *mddev)
1954 {
1955         struct md_rdev *rdev, *reference = NULL;
1956 
1957         if (list_empty(&mddev->disks))
1958                 return 0; /* nothing to do */
1959         if (!mddev->gendisk || blk_get_integrity(mddev->gendisk))
1960                 return 0; /* shouldn't register, or already is */
1961         rdev_for_each(rdev, mddev) {
1962                 /* skip spares and non-functional disks */
1963                 if (test_bit(Faulty, &rdev->flags))
1964                         continue;
1965                 if (rdev->raid_disk < 0)
1966                         continue;
1967                 if (!reference) {
1968                         /* Use the first rdev as the reference */
1969                         reference = rdev;
1970                         continue;
1971                 }
1972                 /* does this rdev's profile match the reference profile? */
1973                 if (blk_integrity_compare(reference->bdev->bd_disk,
1974                                 rdev->bdev->bd_disk) < 0)
1975                         return -EINVAL;
1976         }
1977         if (!reference || !bdev_get_integrity(reference->bdev))
1978                 return 0;
1979         /*
1980          * All component devices are integrity capable and have matching
1981          * profiles, register the common profile for the md device.
1982          */
1983         if (blk_integrity_register(mddev->gendisk,
1984                         bdev_get_integrity(reference->bdev)) != 0) {
1985                 printk(KERN_ERR "md: failed to register integrity for %s\n",
1986                         mdname(mddev));
1987                 return -EINVAL;
1988         }
1989         printk(KERN_NOTICE "md: data integrity enabled on %s\n", mdname(mddev));
1990         if (bioset_integrity_create(mddev->bio_set, BIO_POOL_SIZE)) {
1991                 printk(KERN_ERR "md: failed to create integrity pool for %s\n",
1992                        mdname(mddev));
1993                 return -EINVAL;
1994         }
1995         return 0;
1996 }
1997 EXPORT_SYMBOL(md_integrity_register);
1998 
1999 /* Disable data integrity if non-capable/non-matching disk is being added */
2000 void md_integrity_add_rdev(struct md_rdev *rdev, struct mddev *mddev)
2001 {
2002         struct blk_integrity *bi_rdev;
2003         struct blk_integrity *bi_mddev;
2004 
2005         if (!mddev->gendisk)
2006                 return;
2007 
2008         bi_rdev = bdev_get_integrity(rdev->bdev);
2009         bi_mddev = blk_get_integrity(mddev->gendisk);
2010 
2011         if (!bi_mddev) /* nothing to do */
2012                 return;
2013         if (rdev->raid_disk < 0) /* skip spares */
2014                 return;
2015         if (bi_rdev && blk_integrity_compare(mddev->gendisk,
2016                                              rdev->bdev->bd_disk) >= 0)
2017                 return;
2018         printk(KERN_NOTICE "disabling data integrity on %s\n", mdname(mddev));
2019         blk_integrity_unregister(mddev->gendisk);
2020 }
2021 EXPORT_SYMBOL(md_integrity_add_rdev);
2022 
2023 static int bind_rdev_to_array(struct md_rdev *rdev, struct mddev *mddev)
2024 {
2025         char b[BDEVNAME_SIZE];
2026         struct kobject *ko;
2027         char *s;
2028         int err;
2029 
2030         /* prevent duplicates */
2031         if (find_rdev(mddev, rdev->bdev->bd_dev))
2032                 return -EEXIST;
2033 
2034         /* make sure rdev->sectors exceeds mddev->dev_sectors */
2035         if (rdev->sectors && (mddev->dev_sectors == 0 ||
2036                         rdev->sectors < mddev->dev_sectors)) {
2037                 if (mddev->pers) {
2038                         /* Cannot change size, so fail
2039                          * If mddev->level <= 0, then we don't care
2040                          * about aligning sizes (e.g. linear)
2041                          */
2042                         if (mddev->level > 0)
2043                                 return -ENOSPC;
2044                 } else
2045                         mddev->dev_sectors = rdev->sectors;
2046         }
2047 
2048         /* Verify rdev->desc_nr is unique.
2049          * If it is -1, assign a free number, else
2050          * check number is not in use
2051          */
2052         rcu_read_lock();
2053         if (rdev->desc_nr < 0) {
2054                 int choice = 0;
2055                 if (mddev->pers)
2056                         choice = mddev->raid_disks;
2057                 while (md_find_rdev_nr_rcu(mddev, choice))
2058                         choice++;
2059                 rdev->desc_nr = choice;
2060         } else {
2061                 if (md_find_rdev_nr_rcu(mddev, rdev->desc_nr)) {
2062                         rcu_read_unlock();
2063                         return -EBUSY;
2064                 }
2065         }
2066         rcu_read_unlock();
2067         if (mddev->max_disks && rdev->desc_nr >= mddev->max_disks) {
2068                 printk(KERN_WARNING "md: %s: array is limited to %d devices\n",
2069                        mdname(mddev), mddev->max_disks);
2070                 return -EBUSY;
2071         }
2072         bdevname(rdev->bdev,b);
2073         while ( (s=strchr(b, '/')) != NULL)
2074                 *s = '!';
2075 
2076         rdev->mddev = mddev;
2077         printk(KERN_INFO "md: bind<%s>\n", b);
2078 
2079         if ((err = kobject_add(&rdev->kobj, &mddev->kobj, "dev-%s", b)))
2080                 goto fail;
2081 
2082         ko = &part_to_dev(rdev->bdev->bd_part)->kobj;
2083         if (sysfs_create_link(&rdev->kobj, ko, "block"))
2084                 /* failure here is OK */;
2085         rdev->sysfs_state = sysfs_get_dirent_safe(rdev->kobj.sd, "state");
2086 
2087         list_add_rcu(&rdev->same_set, &mddev->disks);
2088         bd_link_disk_holder(rdev->bdev, mddev->gendisk);
2089 
2090         /* May as well allow recovery to be retried once */
2091         mddev->recovery_disabled++;
2092 
2093         return 0;
2094 
2095  fail:
2096         printk(KERN_WARNING "md: failed to register dev-%s for %s\n",
2097                b, mdname(mddev));
2098         return err;
2099 }
2100 
2101 static void md_delayed_delete(struct work_struct *ws)
2102 {
2103         struct md_rdev *rdev = container_of(ws, struct md_rdev, del_work);
2104         kobject_del(&rdev->kobj);
2105         kobject_put(&rdev->kobj);
2106 }
2107 
2108 static void unbind_rdev_from_array(struct md_rdev *rdev)
2109 {
2110         char b[BDEVNAME_SIZE];
2111 
2112         bd_unlink_disk_holder(rdev->bdev, rdev->mddev->gendisk);
2113         list_del_rcu(&rdev->same_set);
2114         printk(KERN_INFO "md: unbind<%s>\n", bdevname(rdev->bdev,b));
2115         rdev->mddev = NULL;
2116         sysfs_remove_link(&rdev->kobj, "block");
2117         sysfs_put(rdev->sysfs_state);
2118         rdev->sysfs_state = NULL;
2119         rdev->badblocks.count = 0;
2120         /* We need to delay this, otherwise we can deadlock when
2121          * writing to 'remove' to "dev/state".  We also need
2122          * to delay it due to rcu usage.
2123          */
2124         synchronize_rcu();
2125         INIT_WORK(&rdev->del_work, md_delayed_delete);
2126         kobject_get(&rdev->kobj);
2127         queue_work(md_misc_wq, &rdev->del_work);
2128 }
2129 
2130 /*
2131  * prevent the device from being mounted, repartitioned or
2132  * otherwise reused by a RAID array (or any other kernel
2133  * subsystem), by bd_claiming the device.
2134  */
2135 static int lock_rdev(struct md_rdev *rdev, dev_t dev, int shared)
2136 {
2137         int err = 0;
2138         struct block_device *bdev;
2139         char b[BDEVNAME_SIZE];
2140 
2141         bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL,
2142                                  shared ? (struct md_rdev *)lock_rdev : rdev);
2143         if (IS_ERR(bdev)) {
2144                 printk(KERN_ERR "md: could not open %s.\n",
2145                         __bdevname(dev, b));
2146                 return PTR_ERR(bdev);
2147         }
2148         rdev->bdev = bdev;
2149         return err;
2150 }
2151 
2152 static void unlock_rdev(struct md_rdev *rdev)
2153 {
2154         struct block_device *bdev = rdev->bdev;
2155         rdev->bdev = NULL;
2156         blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2157 }
2158 
2159 void md_autodetect_dev(dev_t dev);
2160 
2161 static void export_rdev(struct md_rdev *rdev)
2162 {
2163         char b[BDEVNAME_SIZE];
2164 
2165         printk(KERN_INFO "md: export_rdev(%s)\n",
2166                 bdevname(rdev->bdev,b));
2167         md_rdev_clear(rdev);
2168 #ifndef MODULE
2169         if (test_bit(AutoDetected, &rdev->flags))
2170                 md_autodetect_dev(rdev->bdev->bd_dev);
2171 #endif
2172         unlock_rdev(rdev);
2173         kobject_put(&rdev->kobj);
2174 }
2175 
2176 void md_kick_rdev_from_array(struct md_rdev *rdev)
2177 {
2178         unbind_rdev_from_array(rdev);
2179         export_rdev(rdev);
2180 }
2181 EXPORT_SYMBOL_GPL(md_kick_rdev_from_array);
2182 
2183 static void export_array(struct mddev *mddev)
2184 {
2185         struct md_rdev *rdev;
2186 
2187         while (!list_empty(&mddev->disks)) {
2188                 rdev = list_first_entry(&mddev->disks, struct md_rdev,
2189                                         same_set);
2190                 md_kick_rdev_from_array(rdev);
2191         }
2192         mddev->raid_disks = 0;
2193         mddev->major_version = 0;
2194 }
2195 
2196 static void sync_sbs(struct mddev *mddev, int nospares)
2197 {
2198         /* Update each superblock (in-memory image), but
2199          * if we are allowed to, skip spares which already
2200          * have the right event counter, or have one earlier
2201          * (which would mean they aren't being marked as dirty
2202          * with the rest of the array)
2203          */
2204         struct md_rdev *rdev;
2205         rdev_for_each(rdev, mddev) {
2206                 if (rdev->sb_events == mddev->events ||
2207                     (nospares &&
2208                      rdev->raid_disk < 0 &&
2209                      rdev->sb_events+1 == mddev->events)) {
2210                         /* Don't update this superblock */
2211                         rdev->sb_loaded = 2;
2212                 } else {
2213                         sync_super(mddev, rdev);
2214                         rdev->sb_loaded = 1;
2215                 }
2216         }
2217 }
2218 
2219 void md_update_sb(struct mddev *mddev, int force_change)
2220 {
2221         struct md_rdev *rdev;
2222         int sync_req;
2223         int nospares = 0;
2224         int any_badblocks_changed = 0;
2225 
2226         if (mddev->ro) {
2227                 if (force_change)
2228                         set_bit(MD_CHANGE_DEVS, &mddev->flags);
2229                 return;
2230         }
2231 repeat:
2232         /* First make sure individual recovery_offsets are correct */
2233         rdev_for_each(rdev, mddev) {
2234                 if (rdev->raid_disk >= 0 &&
2235                     mddev->delta_disks >= 0 &&
2236                     !test_bit(In_sync, &rdev->flags) &&
2237                     mddev->curr_resync_completed > rdev->recovery_offset)
2238                                 rdev->recovery_offset = mddev->curr_resync_completed;
2239 
2240         }
2241         if (!mddev->persistent) {
2242                 clear_bit(MD_CHANGE_CLEAN, &mddev->flags);
2243                 clear_bit(MD_CHANGE_DEVS, &mddev->flags);
2244                 if (!mddev->external) {
2245                         clear_bit(MD_CHANGE_PENDING, &mddev->flags);
2246                         rdev_for_each(rdev, mddev) {
2247                                 if (rdev->badblocks.changed) {
2248                                         rdev->badblocks.changed = 0;
2249                                         md_ack_all_badblocks(&rdev->badblocks);
2250                                         md_error(mddev, rdev);
2251                                 }
2252                                 clear_bit(Blocked, &rdev->flags);
2253                                 clear_bit(BlockedBadBlocks, &rdev->flags);
2254                                 wake_up(&rdev->blocked_wait);
2255                         }
2256                 }
2257                 wake_up(&mddev->sb_wait);
2258                 return;
2259         }
2260 
2261         spin_lock(&mddev->lock);
2262 
2263         mddev->utime = get_seconds();
2264 
2265         if (test_and_clear_bit(MD_CHANGE_DEVS, &mddev->flags))
2266                 force_change = 1;
2267         if (test_and_clear_bit(MD_CHANGE_CLEAN, &mddev->flags))
2268                 /* just a clean<-> dirty transition, possibly leave spares alone,
2269                  * though if events isn't the right even/odd, we will have to do
2270                  * spares after all
2271                  */
2272                 nospares = 1;
2273         if (force_change)
2274                 nospares = 0;
2275         if (mddev->degraded)
2276                 /* If the array is degraded, then skipping spares is both
2277                  * dangerous and fairly pointless.
2278                  * Dangerous because a device that was removed from the array
2279                  * might have a event_count that still looks up-to-date,
2280                  * so it can be re-added without a resync.
2281                  * Pointless because if there are any spares to skip,
2282                  * then a recovery will happen and soon that array won't
2283                  * be degraded any more and the spare can go back to sleep then.
2284                  */
2285                 nospares = 0;
2286 
2287         sync_req = mddev->in_sync;
2288 
2289         /* If this is just a dirty<->clean transition, and the array is clean
2290          * and 'events' is odd, we can roll back to the previous clean state */
2291         if (nospares
2292             && (mddev->in_sync && mddev->recovery_cp == MaxSector)
2293             && mddev->can_decrease_events
2294             && mddev->events != 1) {
2295                 mddev->events--;
2296                 mddev->can_decrease_events = 0;
2297         } else {
2298                 /* otherwise we have to go forward and ... */
2299                 mddev->events ++;
2300                 mddev->can_decrease_events = nospares;
2301         }
2302 
2303         /*
2304          * This 64-bit counter should never wrap.
2305          * Either we are in around ~1 trillion A.C., assuming
2306          * 1 reboot per second, or we have a bug...
2307          */
2308         WARN_ON(mddev->events == 0);
2309 
2310         rdev_for_each(rdev, mddev) {
2311                 if (rdev->badblocks.changed)
2312                         any_badblocks_changed++;
2313                 if (test_bit(Faulty, &rdev->flags))
2314                         set_bit(FaultRecorded, &rdev->flags);
2315         }
2316 
2317         sync_sbs(mddev, nospares);
2318         spin_unlock(&mddev->lock);
2319 
2320         pr_debug("md: updating %s RAID superblock on device (in sync %d)\n",
2321                  mdname(mddev), mddev->in_sync);
2322 
2323         bitmap_update_sb(mddev->bitmap);
2324         rdev_for_each(rdev, mddev) {
2325                 char b[BDEVNAME_SIZE];
2326 
2327                 if (rdev->sb_loaded != 1)
2328                         continue; /* no noise on spare devices */
2329 
2330                 if (!test_bit(Faulty, &rdev->flags)) {
2331                         md_super_write(mddev,rdev,
2332                                        rdev->sb_start, rdev->sb_size,
2333                                        rdev->sb_page);
2334                         pr_debug("md: (write) %s's sb offset: %llu\n",
2335                                  bdevname(rdev->bdev, b),
2336                                  (unsigned long long)rdev->sb_start);
2337                         rdev->sb_events = mddev->events;
2338                         if (rdev->badblocks.size) {
2339                                 md_super_write(mddev, rdev,
2340                                                rdev->badblocks.sector,
2341                                                rdev->badblocks.size << 9,
2342                                                rdev->bb_page);
2343                                 rdev->badblocks.size = 0;
2344                         }
2345 
2346                 } else
2347                         pr_debug("md: %s (skipping faulty)\n",
2348                                  bdevname(rdev->bdev, b));
2349 
2350                 if (mddev->level == LEVEL_MULTIPATH)
2351                         /* only need to write one superblock... */
2352                         break;
2353         }
2354         md_super_wait(mddev);
2355         /* if there was a failure, MD_CHANGE_DEVS was set, and we re-write super */
2356 
2357         spin_lock(&mddev->lock);
2358         if (mddev->in_sync != sync_req ||
2359             test_bit(MD_CHANGE_DEVS, &mddev->flags)) {
2360                 /* have to write it out again */
2361                 spin_unlock(&mddev->lock);
2362                 goto repeat;
2363         }
2364         clear_bit(MD_CHANGE_PENDING, &mddev->flags);
2365         spin_unlock(&mddev->lock);
2366         wake_up(&mddev->sb_wait);
2367         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
2368                 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
2369 
2370         rdev_for_each(rdev, mddev) {
2371                 if (test_and_clear_bit(FaultRecorded, &rdev->flags))
2372                         clear_bit(Blocked, &rdev->flags);
2373 
2374                 if (any_badblocks_changed)
2375                         md_ack_all_badblocks(&rdev->badblocks);
2376                 clear_bit(BlockedBadBlocks, &rdev->flags);
2377                 wake_up(&rdev->blocked_wait);
2378         }
2379 }
2380 EXPORT_SYMBOL(md_update_sb);
2381 
2382 static int add_bound_rdev(struct md_rdev *rdev)
2383 {
2384         struct mddev *mddev = rdev->mddev;
2385         int err = 0;
2386 
2387         if (!mddev->pers->hot_remove_disk) {
2388                 /* If there is hot_add_disk but no hot_remove_disk
2389                  * then added disks for geometry changes,
2390                  * and should be added immediately.
2391                  */
2392                 super_types[mddev->major_version].
2393                         validate_super(mddev, rdev);
2394                 err = mddev->pers->hot_add_disk(mddev, rdev);
2395                 if (err) {
2396                         unbind_rdev_from_array(rdev);
2397                         export_rdev(rdev);
2398                         return err;
2399                 }
2400         }
2401         sysfs_notify_dirent_safe(rdev->sysfs_state);
2402 
2403         set_bit(MD_CHANGE_DEVS, &mddev->flags);
2404         if (mddev->degraded)
2405                 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
2406         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2407         md_new_event(mddev);
2408         md_wakeup_thread(mddev->thread);
2409         return 0;
2410 }
2411 
2412 /* words written to sysfs files may, or may not, be \n terminated.
2413  * We want to accept with case. For this we use cmd_match.
2414  */
2415 static int cmd_match(const char *cmd, const char *str)
2416 {
2417         /* See if cmd, written into a sysfs file, matches
2418          * str.  They must either be the same, or cmd can
2419          * have a trailing newline
2420          */
2421         while (*cmd && *str && *cmd == *str) {
2422                 cmd++;
2423                 str++;
2424         }
2425         if (*cmd == '\n')
2426                 cmd++;
2427         if (*str || *cmd)
2428                 return 0;
2429         return 1;
2430 }
2431 
2432 struct rdev_sysfs_entry {
2433         struct attribute attr;
2434         ssize_t (*show)(struct md_rdev *, char *);
2435         ssize_t (*store)(struct md_rdev *, const char *, size_t);
2436 };
2437 
2438 static ssize_t
2439 state_show(struct md_rdev *rdev, char *page)
2440 {
2441         char *sep = "";
2442         size_t len = 0;
2443         unsigned long flags = ACCESS_ONCE(rdev->flags);
2444 
2445         if (test_bit(Faulty, &flags) ||
2446             rdev->badblocks.unacked_exist) {
2447                 len+= sprintf(page+len, "%sfaulty",sep);
2448                 sep = ",";
2449         }
2450         if (test_bit(In_sync, &flags)) {
2451                 len += sprintf(page+len, "%sin_sync",sep);
2452                 sep = ",";
2453         }
2454         if (test_bit(WriteMostly, &flags)) {
2455                 len += sprintf(page+len, "%swrite_mostly",sep);
2456                 sep = ",";
2457         }
2458         if (test_bit(Blocked, &flags) ||
2459             (rdev->badblocks.unacked_exist
2460              && !test_bit(Faulty, &flags))) {
2461                 len += sprintf(page+len, "%sblocked", sep);
2462                 sep = ",";
2463         }
2464         if (!test_bit(Faulty, &flags) &&
2465             !test_bit(In_sync, &flags)) {
2466                 len += sprintf(page+len, "%sspare", sep);
2467                 sep = ",";
2468         }
2469         if (test_bit(WriteErrorSeen, &flags)) {
2470                 len += sprintf(page+len, "%swrite_error", sep);
2471                 sep = ",";
2472         }
2473         if (test_bit(WantReplacement, &flags)) {
2474                 len += sprintf(page+len, "%swant_replacement", sep);
2475                 sep = ",";
2476         }
2477         if (test_bit(Replacement, &flags)) {
2478                 len += sprintf(page+len, "%sreplacement", sep);
2479                 sep = ",";
2480         }
2481 
2482         return len+sprintf(page+len, "\n");
2483 }
2484 
2485 static ssize_t
2486 state_store(struct md_rdev *rdev, const char *buf, size_t len)
2487 {
2488         /* can write
2489          *  faulty  - simulates an error
2490          *  remove  - disconnects the device
2491          *  writemostly - sets write_mostly
2492          *  -writemostly - clears write_mostly
2493          *  blocked - sets the Blocked flags
2494          *  -blocked - clears the Blocked and possibly simulates an error
2495          *  insync - sets Insync providing device isn't active
2496          *  -insync - clear Insync for a device with a slot assigned,
2497          *            so that it gets rebuilt based on bitmap
2498          *  write_error - sets WriteErrorSeen
2499          *  -write_error - clears WriteErrorSeen
2500          */
2501         int err = -EINVAL;
2502         if (cmd_match(buf, "faulty") && rdev->mddev->pers) {
2503                 md_error(rdev->mddev, rdev);
2504                 if (test_bit(Faulty, &rdev->flags))
2505                         err = 0;
2506                 else
2507                         err = -EBUSY;
2508         } else if (cmd_match(buf, "remove")) {
2509                 if (rdev->raid_disk >= 0)
2510                         err = -EBUSY;
2511                 else {
2512                         struct mddev *mddev = rdev->mddev;
2513                         if (mddev_is_clustered(mddev))
2514                                 md_cluster_ops->remove_disk(mddev, rdev);
2515                         md_kick_rdev_from_array(rdev);
2516                         if (mddev_is_clustered(mddev))
2517                                 md_cluster_ops->metadata_update_start(mddev);
2518                         if (mddev->pers)
2519                                 md_update_sb(mddev, 1);
2520                         md_new_event(mddev);
2521                         if (mddev_is_clustered(mddev))
2522                                 md_cluster_ops->metadata_update_finish(mddev);
2523                         err = 0;
2524                 }
2525         } else if (cmd_match(buf, "writemostly")) {
2526                 set_bit(WriteMostly, &rdev->flags);
2527                 err = 0;
2528         } else if (cmd_match(buf, "-writemostly")) {
2529                 clear_bit(WriteMostly, &rdev->flags);
2530                 err = 0;
2531         } else if (cmd_match(buf, "blocked")) {
2532                 set_bit(Blocked, &rdev->flags);
2533                 err = 0;
2534         } else if (cmd_match(buf, "-blocked")) {
2535                 if (!test_bit(Faulty, &rdev->flags) &&
2536                     rdev->badblocks.unacked_exist) {
2537                         /* metadata handler doesn't understand badblocks,
2538                          * so we need to fail the device
2539                          */
2540                         md_error(rdev->mddev, rdev);
2541                 }
2542                 clear_bit(Blocked, &rdev->flags);
2543                 clear_bit(BlockedBadBlocks, &rdev->flags);
2544                 wake_up(&rdev->blocked_wait);
2545                 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2546                 md_wakeup_thread(rdev->mddev->thread);
2547 
2548                 err = 0;
2549         } else if (cmd_match(buf, "insync") && rdev->raid_disk == -1) {
2550                 set_bit(In_sync, &rdev->flags);
2551                 err = 0;
2552         } else if (cmd_match(buf, "-insync") && rdev->raid_disk >= 0) {
2553                 if (rdev->mddev->pers == NULL) {
2554                         clear_bit(In_sync, &rdev->flags);
2555                         rdev->saved_raid_disk = rdev->raid_disk;
2556                         rdev->raid_disk = -1;
2557                         err = 0;
2558                 }
2559         } else if (cmd_match(buf, "write_error")) {
2560                 set_bit(WriteErrorSeen, &rdev->flags);
2561                 err = 0;
2562         } else if (cmd_match(buf, "-write_error")) {
2563                 clear_bit(WriteErrorSeen, &rdev->flags);
2564                 err = 0;
2565         } else if (cmd_match(buf, "want_replacement")) {
2566                 /* Any non-spare device that is not a replacement can
2567                  * become want_replacement at any time, but we then need to
2568                  * check if recovery is needed.
2569                  */
2570                 if (rdev->raid_disk >= 0 &&
2571                     !test_bit(Replacement, &rdev->flags))
2572                         set_bit(WantReplacement, &rdev->flags);
2573                 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2574                 md_wakeup_thread(rdev->mddev->thread);
2575                 err = 0;
2576         } else if (cmd_match(buf, "-want_replacement")) {
2577                 /* Clearing 'want_replacement' is always allowed.
2578                  * Once replacements starts it is too late though.
2579                  */
2580                 err = 0;
2581                 clear_bit(WantReplacement, &rdev->flags);
2582         } else if (cmd_match(buf, "replacement")) {
2583                 /* Can only set a device as a replacement when array has not
2584                  * yet been started.  Once running, replacement is automatic
2585                  * from spares, or by assigning 'slot'.
2586                  */
2587                 if (rdev->mddev->pers)
2588                         err = -EBUSY;
2589                 else {
2590                         set_bit(Replacement, &rdev->flags);
2591                         err = 0;
2592                 }
2593         } else if (cmd_match(buf, "-replacement")) {
2594                 /* Similarly, can only clear Replacement before start */
2595                 if (rdev->mddev->pers)
2596                         err = -EBUSY;
2597                 else {
2598                         clear_bit(Replacement, &rdev->flags);
2599                         err = 0;
2600                 }
2601         } else if (cmd_match(buf, "re-add")) {
2602                 if (test_bit(Faulty, &rdev->flags) && (rdev->raid_disk == -1)) {
2603                         /* clear_bit is performed _after_ all the devices
2604                          * have their local Faulty bit cleared. If any writes
2605                          * happen in the meantime in the local node, they
2606                          * will land in the local bitmap, which will be synced
2607                          * by this node eventually
2608                          */
2609                         if (!mddev_is_clustered(rdev->mddev) ||
2610                             (err = md_cluster_ops->gather_bitmaps(rdev)) == 0) {
2611                                 clear_bit(Faulty, &rdev->flags);
2612                                 err = add_bound_rdev(rdev);
2613                         }
2614                 } else
2615                         err = -EBUSY;
2616         }
2617         if (!err)
2618                 sysfs_notify_dirent_safe(rdev->sysfs_state);
2619         return err ? err : len;
2620 }
2621 static struct rdev_sysfs_entry rdev_state =
2622 __ATTR_PREALLOC(state, S_IRUGO|S_IWUSR, state_show, state_store);
2623 
2624 static ssize_t
2625 errors_show(struct md_rdev *rdev, char *page)
2626 {
2627         return sprintf(page, "%d\n", atomic_read(&rdev->corrected_errors));
2628 }
2629 
2630 static ssize_t
2631 errors_store(struct md_rdev *rdev, const char *buf, size_t len)
2632 {
2633         char *e;
2634         unsigned long n = simple_strtoul(buf, &e, 10);
2635         if (*buf && (*e == 0 || *e == '\n')) {
2636                 atomic_set(&rdev->corrected_errors, n);
2637                 return len;
2638         }
2639         return -EINVAL;
2640 }
2641 static struct rdev_sysfs_entry rdev_errors =
2642 __ATTR(errors, S_IRUGO|S_IWUSR, errors_show, errors_store);
2643 
2644 static ssize_t
2645 slot_show(struct md_rdev *rdev, char *page)
2646 {
2647         if (rdev->raid_disk < 0)
2648                 return sprintf(page, "none\n");
2649         else
2650                 return sprintf(page, "%d\n", rdev->raid_disk);
2651 }
2652 
2653 static ssize_t
2654 slot_store(struct md_rdev *rdev, const char *buf, size_t len)
2655 {
2656         char *e;
2657         int err;
2658         int slot = simple_strtoul(buf, &e, 10);
2659         if (strncmp(buf, "none", 4)==0)
2660                 slot = -1;
2661         else if (e==buf || (*e && *e!= '\n'))
2662                 return -EINVAL;
2663         if (rdev->mddev->pers && slot == -1) {
2664                 /* Setting 'slot' on an active array requires also
2665                  * updating the 'rd%d' link, and communicating
2666                  * with the personality with ->hot_*_disk.
2667                  * For now we only support removing
2668                  * failed/spare devices.  This normally happens automatically,
2669                  * but not when the metadata is externally managed.
2670                  */
2671                 if (rdev->raid_disk == -1)
2672                         return -EEXIST;
2673                 /* personality does all needed checks */
2674                 if (rdev->mddev->pers->hot_remove_disk == NULL)
2675                         return -EINVAL;
2676                 clear_bit(Blocked, &rdev->flags);
2677                 remove_and_add_spares(rdev->mddev, rdev);
2678                 if (rdev->raid_disk >= 0)
2679                         return -EBUSY;
2680                 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2681                 md_wakeup_thread(rdev->mddev->thread);
2682         } else if (rdev->mddev->pers) {
2683                 /* Activating a spare .. or possibly reactivating
2684                  * if we ever get bitmaps working here.
2685                  */
2686 
2687                 if (rdev->raid_disk != -1)
2688                         return -EBUSY;
2689 
2690                 if (test_bit(MD_RECOVERY_RUNNING, &rdev->mddev->recovery))
2691                         return -EBUSY;
2692 
2693                 if (rdev->mddev->pers->hot_add_disk == NULL)
2694                         return -EINVAL;
2695 
2696                 if (slot >= rdev->mddev->raid_disks &&
2697                     slot >= rdev->mddev->raid_disks + rdev->mddev->delta_disks)
2698                         return -ENOSPC;
2699 
2700                 rdev->raid_disk = slot;
2701                 if (test_bit(In_sync, &rdev->flags))
2702                         rdev->saved_raid_disk = slot;
2703                 else
2704                         rdev->saved_raid_disk = -1;
2705                 clear_bit(In_sync, &rdev->flags);
2706                 clear_bit(Bitmap_sync, &rdev->flags);
2707                 err = rdev->mddev->pers->
2708                         hot_add_disk(rdev->mddev, rdev);
2709                 if (err) {
2710                         rdev->raid_disk = -1;
2711                         return err;
2712                 } else
2713                         sysfs_notify_dirent_safe(rdev->sysfs_state);
2714                 if (sysfs_link_rdev(rdev->mddev, rdev))
2715                         /* failure here is OK */;
2716                 /* don't wakeup anyone, leave that to userspace. */
2717         } else {
2718                 if (slot >= rdev->mddev->raid_disks &&
2719                     slot >= rdev->mddev->raid_disks + rdev->mddev->delta_disks)
2720                         return -ENOSPC;
2721                 rdev->raid_disk = slot;
2722                 /* assume it is working */
2723                 clear_bit(Faulty, &rdev->flags);
2724                 clear_bit(WriteMostly, &rdev->flags);
2725                 set_bit(In_sync, &rdev->flags);
2726                 sysfs_notify_dirent_safe(rdev->sysfs_state);
2727         }
2728         return len;
2729 }
2730 
2731 static struct rdev_sysfs_entry rdev_slot =
2732 __ATTR(slot, S_IRUGO|S_IWUSR, slot_show, slot_store);
2733 
2734 static ssize_t
2735 offset_show(struct md_rdev *rdev, char *page)
2736 {
2737         return sprintf(page, "%llu\n", (unsigned long long)rdev->data_offset);
2738 }
2739 
2740 static ssize_t
2741 offset_store(struct md_rdev *rdev, const char *buf, size_t len)
2742 {
2743         unsigned long long offset;
2744         if (kstrtoull(buf, 10, &offset) < 0)
2745                 return -EINVAL;
2746         if (rdev->mddev->pers && rdev->raid_disk >= 0)
2747                 return -EBUSY;
2748         if (rdev->sectors && rdev->mddev->external)
2749                 /* Must set offset before size, so overlap checks
2750                  * can be sane */
2751                 return -EBUSY;
2752         rdev->data_offset = offset;
2753         rdev->new_data_offset = offset;
2754         return len;
2755 }
2756 
2757 static struct rdev_sysfs_entry rdev_offset =
2758 __ATTR(offset, S_IRUGO|S_IWUSR, offset_show, offset_store);
2759 
2760 static ssize_t new_offset_show(struct md_rdev *rdev, char *page)
2761 {
2762         return sprintf(page, "%llu\n",
2763                        (unsigned long long)rdev->new_data_offset);
2764 }
2765 
2766 static ssize_t new_offset_store(struct md_rdev *rdev,
2767                                 const char *buf, size_t len)
2768 {
2769         unsigned long long new_offset;
2770         struct mddev *mddev = rdev->mddev;
2771 
2772         if (kstrtoull(buf, 10, &new_offset) < 0)
2773                 return -EINVAL;
2774 
2775         if (mddev->sync_thread ||
2776             test_bit(MD_RECOVERY_RUNNING,&mddev->recovery))
2777                 return -EBUSY;
2778         if (new_offset == rdev->data_offset)
2779                 /* reset is always permitted */
2780                 ;
2781         else if (new_offset > rdev->data_offset) {
2782                 /* must not push array size beyond rdev_sectors */
2783                 if (new_offset - rdev->data_offset
2784                     + mddev->dev_sectors > rdev->sectors)
2785                                 return -E2BIG;
2786         }
2787         /* Metadata worries about other space details. */
2788 
2789         /* decreasing the offset is inconsistent with a backwards
2790          * reshape.
2791          */
2792         if (new_offset < rdev->data_offset &&
2793             mddev->reshape_backwards)
2794                 return -EINVAL;
2795         /* Increasing offset is inconsistent with forwards
2796          * reshape.  reshape_direction should be set to
2797          * 'backwards' first.
2798          */
2799         if (new_offset > rdev->data_offset &&
2800             !mddev->reshape_backwards)
2801                 return -EINVAL;
2802 
2803         if (mddev->pers && mddev->persistent &&
2804             !super_types[mddev->major_version]
2805             .allow_new_offset(rdev, new_offset))
2806                 return -E2BIG;
2807         rdev->new_data_offset = new_offset;
2808         if (new_offset > rdev->data_offset)
2809                 mddev->reshape_backwards = 1;
2810         else if (new_offset < rdev->data_offset)
2811                 mddev->reshape_backwards = 0;
2812 
2813         return len;
2814 }
2815 static struct rdev_sysfs_entry rdev_new_offset =
2816 __ATTR(new_offset, S_IRUGO|S_IWUSR, new_offset_show, new_offset_store);
2817 
2818 static ssize_t
2819 rdev_size_show(struct md_rdev *rdev, char *page)
2820 {
2821         return sprintf(page, "%llu\n", (unsigned long long)rdev->sectors / 2);
2822 }
2823 
2824 static int overlaps(sector_t s1, sector_t l1, sector_t s2, sector_t l2)
2825 {
2826         /* check if two start/length pairs overlap */
2827         if (s1+l1 <= s2)
2828                 return 0;
2829         if (s2+l2 <= s1)
2830                 return 0;
2831         return 1;
2832 }
2833 
2834 static int strict_blocks_to_sectors(const char *buf, sector_t *sectors)
2835 {
2836         unsigned long long blocks;
2837         sector_t new;
2838 
2839         if (kstrtoull(buf, 10, &blocks) < 0)
2840                 return -EINVAL;
2841 
2842         if (blocks & 1ULL << (8 * sizeof(blocks) - 1))
2843                 return -EINVAL; /* sector conversion overflow */
2844 
2845         new = blocks * 2;
2846         if (new != blocks * 2)
2847                 return -EINVAL; /* unsigned long long to sector_t overflow */
2848 
2849         *sectors = new;
2850         return 0;
2851 }
2852 
2853 static ssize_t
2854 rdev_size_store(struct md_rdev *rdev, const char *buf, size_t len)
2855 {
2856         struct mddev *my_mddev = rdev->mddev;
2857         sector_t oldsectors = rdev->sectors;
2858         sector_t sectors;
2859 
2860         if (strict_blocks_to_sectors(buf, &sectors) < 0)
2861                 return -EINVAL;
2862         if (rdev->data_offset != rdev->new_data_offset)
2863                 return -EINVAL; /* too confusing */
2864         if (my_mddev->pers && rdev->raid_disk >= 0) {
2865                 if (my_mddev->persistent) {
2866                         sectors = super_types[my_mddev->major_version].
2867                                 rdev_size_change(rdev, sectors);
2868                         if (!sectors)
2869                                 return -EBUSY;
2870                 } else if (!sectors)
2871                         sectors = (i_size_read(rdev->bdev->bd_inode) >> 9) -
2872                                 rdev->data_offset;
2873                 if (!my_mddev->pers->resize)
2874                         /* Cannot change size for RAID0 or Linear etc */
2875                         return -EINVAL;
2876         }
2877         if (sectors < my_mddev->dev_sectors)
2878                 return -EINVAL; /* component must fit device */
2879 
2880         rdev->sectors = sectors;
2881         if (sectors > oldsectors && my_mddev->external) {
2882                 /* Need to check that all other rdevs with the same
2883                  * ->bdev do not overlap.  'rcu' is sufficient to walk
2884                  * the rdev lists safely.
2885                  * This check does not provide a hard guarantee, it
2886                  * just helps avoid dangerous mistakes.
2887                  */
2888                 struct mddev *mddev;
2889                 int overlap = 0;
2890                 struct list_head *tmp;
2891 
2892                 rcu_read_lock();
2893                 for_each_mddev(mddev, tmp) {
2894                         struct md_rdev *rdev2;
2895 
2896                         rdev_for_each(rdev2, mddev)
2897                                 if (rdev->bdev == rdev2->bdev &&
2898                                     rdev != rdev2 &&
2899                                     overlaps(rdev->data_offset, rdev->sectors,
2900                                              rdev2->data_offset,
2901                                              rdev2->sectors)) {
2902                                         overlap = 1;
2903                                         break;
2904                                 }
2905                         if (overlap) {
2906                                 mddev_put(mddev);
2907                                 break;
2908                         }
2909                 }
2910                 rcu_read_unlock();
2911                 if (overlap) {
2912                         /* Someone else could have slipped in a size
2913                          * change here, but doing so is just silly.
2914                          * We put oldsectors back because we *know* it is
2915                          * safe, and trust userspace not to race with
2916                          * itself
2917                          */
2918                         rdev->sectors = oldsectors;
2919                         return -EBUSY;
2920                 }
2921         }
2922         return len;
2923 }
2924 
2925 static struct rdev_sysfs_entry rdev_size =
2926 __ATTR(size, S_IRUGO|S_IWUSR, rdev_size_show, rdev_size_store);
2927 
2928 static ssize_t recovery_start_show(struct md_rdev *rdev, char *page)
2929 {
2930         unsigned long long recovery_start = rdev->recovery_offset;
2931 
2932         if (test_bit(In_sync, &rdev->flags) ||
2933             recovery_start == MaxSector)
2934                 return sprintf(page, "none\n");
2935 
2936         return sprintf(page, "%llu\n", recovery_start);
2937 }
2938 
2939 static ssize_t recovery_start_store(struct md_rdev *rdev, const char *buf, size_t len)
2940 {
2941         unsigned long long recovery_start;
2942 
2943         if (cmd_match(buf, "none"))
2944                 recovery_start = MaxSector;
2945         else if (kstrtoull(buf, 10, &recovery_start))
2946                 return -EINVAL;
2947 
2948         if (rdev->mddev->pers &&
2949             rdev->raid_disk >= 0)
2950                 return -EBUSY;
2951 
2952         rdev->recovery_offset = recovery_start;
2953         if (recovery_start == MaxSector)
2954                 set_bit(In_sync, &rdev->flags);
2955         else
2956                 clear_bit(In_sync, &rdev->flags);
2957         return len;
2958 }
2959 
2960 static struct rdev_sysfs_entry rdev_recovery_start =
2961 __ATTR(recovery_start, S_IRUGO|S_IWUSR, recovery_start_show, recovery_start_store);
2962 
2963 static ssize_t
2964 badblocks_show(struct badblocks *bb, char *page, int unack);
2965 static ssize_t
2966 badblocks_store(struct badblocks *bb, const char *page, size_t len, int unack);
2967 
2968 static ssize_t bb_show(struct md_rdev *rdev, char *page)
2969 {
2970         return badblocks_show(&rdev->badblocks, page, 0);
2971 }
2972 static ssize_t bb_store(struct md_rdev *rdev, const char *page, size_t len)
2973 {
2974         int rv = badblocks_store(&rdev->badblocks, page, len, 0);
2975         /* Maybe that ack was all we needed */
2976         if (test_and_clear_bit(BlockedBadBlocks, &rdev->flags))
2977                 wake_up(&rdev->blocked_wait);
2978         return rv;
2979 }
2980 static struct rdev_sysfs_entry rdev_bad_blocks =
2981 __ATTR(bad_blocks, S_IRUGO|S_IWUSR, bb_show, bb_store);
2982 
2983 static ssize_t ubb_show(struct md_rdev *rdev, char *page)
2984 {
2985         return badblocks_show(&rdev->badblocks, page, 1);
2986 }
2987 static ssize_t ubb_store(struct md_rdev *rdev, const char *page, size_t len)
2988 {
2989         return badblocks_store(&rdev->badblocks, page, len, 1);
2990 }
2991 static struct rdev_sysfs_entry rdev_unack_bad_blocks =
2992 __ATTR(unacknowledged_bad_blocks, S_IRUGO|S_IWUSR, ubb_show, ubb_store);
2993 
2994 static struct attribute *rdev_default_attrs[] = {
2995         &rdev_state.attr,
2996         &rdev_errors.attr,
2997         &rdev_slot.attr,
2998         &rdev_offset.attr,
2999         &rdev_new_offset.attr,
3000         &rdev_size.attr,
3001         &rdev_recovery_start.attr,
3002         &rdev_bad_blocks.attr,
3003         &rdev_unack_bad_blocks.attr,
3004         NULL,
3005 };
3006 static ssize_t
3007 rdev_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
3008 {
3009         struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
3010         struct md_rdev *rdev = container_of(kobj, struct md_rdev, kobj);
3011 
3012         if (!entry->show)
3013                 return -EIO;
3014         if (!rdev->mddev)
3015                 return -EBUSY;
3016         return entry->show(rdev, page);
3017 }
3018 
3019 static ssize_t
3020 rdev_attr_store(struct kobject *kobj, struct attribute *attr,
3021               const char *page, size_t length)
3022 {
3023         struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
3024         struct md_rdev *rdev = container_of(kobj, struct md_rdev, kobj);
3025         ssize_t rv;
3026         struct mddev *mddev = rdev->mddev;
3027 
3028         if (!entry->store)
3029                 return -EIO;
3030         if (!capable(CAP_SYS_ADMIN))
3031                 return -EACCES;
3032         rv = mddev ? mddev_lock(mddev): -EBUSY;
3033         if (!rv) {
3034                 if (rdev->mddev == NULL)
3035                         rv = -EBUSY;
3036                 else
3037                         rv = entry->store(rdev, page, length);
3038                 mddev_unlock(mddev);
3039         }
3040         return rv;
3041 }
3042 
3043 static void rdev_free(struct kobject *ko)
3044 {
3045         struct md_rdev *rdev = container_of(ko, struct md_rdev, kobj);
3046         kfree(rdev);
3047 }
3048 static const struct sysfs_ops rdev_sysfs_ops = {
3049         .show           = rdev_attr_show,
3050         .store          = rdev_attr_store,
3051 };
3052 static struct kobj_type rdev_ktype = {
3053         .release        = rdev_free,
3054         .sysfs_ops      = &rdev_sysfs_ops,
3055         .default_attrs  = rdev_default_attrs,
3056 };
3057 
3058 int md_rdev_init(struct md_rdev *rdev)
3059 {
3060         rdev->desc_nr = -1;
3061         rdev->saved_raid_disk = -1;
3062         rdev->raid_disk = -1;
3063         rdev->flags = 0;
3064         rdev->data_offset = 0;
3065         rdev->new_data_offset = 0;
3066         rdev->sb_events = 0;
3067         rdev->last_read_error.tv_sec  = 0;
3068         rdev->last_read_error.tv_nsec = 0;
3069         rdev->sb_loaded = 0;
3070         rdev->bb_page = NULL;
3071         atomic_set(&rdev->nr_pending, 0);
3072         atomic_set(&rdev->read_errors, 0);
3073         atomic_set(&rdev->corrected_errors, 0);
3074 
3075         INIT_LIST_HEAD(&rdev->same_set);
3076         init_waitqueue_head(&rdev->blocked_wait);
3077 
3078         /* Add space to store bad block list.
3079          * This reserves the space even on arrays where it cannot
3080          * be used - I wonder if that matters
3081          */
3082         rdev->badblocks.count = 0;
3083         rdev->badblocks.shift = -1; /* disabled until explicitly enabled */
3084         rdev->badblocks.page = kmalloc(PAGE_SIZE, GFP_KERNEL);
3085         seqlock_init(&rdev->badblocks.lock);
3086         if (rdev->badblocks.page == NULL)
3087                 return -ENOMEM;
3088 
3089         return 0;
3090 }
3091 EXPORT_SYMBOL_GPL(md_rdev_init);
3092 /*
3093  * Import a device. If 'super_format' >= 0, then sanity check the superblock
3094  *
3095  * mark the device faulty if:
3096  *
3097  *   - the device is nonexistent (zero size)
3098  *   - the device has no valid superblock
3099  *
3100  * a faulty rdev _never_ has rdev->sb set.
3101  */
3102 static struct md_rdev *md_import_device(dev_t newdev, int super_format, int super_minor)
3103 {
3104         char b[BDEVNAME_SIZE];
3105         int err;
3106         struct md_rdev *rdev;
3107         sector_t size;
3108 
3109         rdev = kzalloc(sizeof(*rdev), GFP_KERNEL);
3110         if (!rdev) {
3111                 printk(KERN_ERR "md: could not alloc mem for new device!\n");
3112                 return ERR_PTR(-ENOMEM);
3113         }
3114 
3115         err = md_rdev_init(rdev);
3116         if (err)
3117                 goto abort_free;
3118         err = alloc_disk_sb(rdev);
3119         if (err)
3120                 goto abort_free;
3121 
3122         err = lock_rdev(rdev, newdev, super_format == -2);
3123         if (err)
3124                 goto abort_free;
3125 
3126         kobject_init(&rdev->kobj, &rdev_ktype);
3127 
3128         size = i_size_read(rdev->bdev->bd_inode) >> BLOCK_SIZE_BITS;
3129         if (!size) {
3130                 printk(KERN_WARNING
3131                         "md: %s has zero or unknown size, marking faulty!\n",
3132                         bdevname(rdev->bdev,b));
3133                 err = -EINVAL;
3134                 goto abort_free;
3135         }
3136 
3137         if (super_format >= 0) {
3138                 err = super_types[super_format].
3139                         load_super(rdev, NULL, super_minor);
3140                 if (err == -EINVAL) {
3141                         printk(KERN_WARNING
3142                                 "md: %s does not have a valid v%d.%d "
3143                                "superblock, not importing!\n",
3144                                 bdevname(rdev->bdev,b),
3145                                super_format, super_minor);
3146                         goto abort_free;
3147                 }
3148                 if (err < 0) {
3149                         printk(KERN_WARNING
3150                                 "md: could not read %s's sb, not importing!\n",
3151                                 bdevname(rdev->bdev,b));
3152                         goto abort_free;
3153                 }
3154         }
3155 
3156         return rdev;
3157 
3158 abort_free:
3159         if (rdev->bdev)
3160                 unlock_rdev(rdev);
3161         md_rdev_clear(rdev);
3162         kfree(rdev);
3163         return ERR_PTR(err);
3164 }
3165 
3166 /*
3167  * Check a full RAID array for plausibility
3168  */
3169 
3170 static void analyze_sbs(struct mddev *mddev)
3171 {
3172         int i;
3173         struct md_rdev *rdev, *freshest, *tmp;
3174         char b[BDEVNAME_SIZE];
3175 
3176         freshest = NULL;
3177         rdev_for_each_safe(rdev, tmp, mddev)
3178                 switch (super_types[mddev->major_version].
3179                         load_super(rdev, freshest, mddev->minor_version)) {
3180                 case 1:
3181                         freshest = rdev;
3182                         break;
3183                 case 0:
3184                         break;
3185                 default:
3186                         printk( KERN_ERR \
3187                                 "md: fatal superblock inconsistency in %s"
3188                                 " -- removing from array\n",
3189                                 bdevname(rdev->bdev,b));
3190                         md_kick_rdev_from_array(rdev);
3191                 }
3192 
3193         super_types[mddev->major_version].
3194                 validate_super(mddev, freshest);
3195 
3196         i = 0;
3197         rdev_for_each_safe(rdev, tmp, mddev) {
3198                 if (mddev->max_disks &&
3199                     (rdev->desc_nr >= mddev->max_disks ||
3200                      i > mddev->max_disks)) {
3201                         printk(KERN_WARNING
3202                                "md: %s: %s: only %d devices permitted\n",
3203                                mdname(mddev), bdevname(rdev->bdev, b),
3204                                mddev->max_disks);
3205                         md_kick_rdev_from_array(rdev);
3206                         continue;
3207                 }
3208                 if (rdev != freshest) {
3209                         if (super_types[mddev->major_version].
3210                             validate_super(mddev, rdev)) {
3211                                 printk(KERN_WARNING "md: kicking non-fresh %s"
3212                                         " from array!\n",
3213                                         bdevname(rdev->bdev,b));
3214                                 md_kick_rdev_from_array(rdev);
3215                                 continue;
3216                         }
3217                         /* No device should have a Candidate flag
3218                          * when reading devices
3219                          */
3220                         if (test_bit(Candidate, &rdev->flags)) {
3221                                 pr_info("md: kicking Cluster Candidate %s from array!\n",
3222                                         bdevname(rdev->bdev, b));
3223                                 md_kick_rdev_from_array(rdev);
3224                         }
3225                 }
3226                 if (mddev->level == LEVEL_MULTIPATH) {
3227                         rdev->desc_nr = i++;
3228                         rdev->raid_disk = rdev->desc_nr;
3229                         set_bit(In_sync, &rdev->flags);
3230                 } else if (rdev->raid_disk >= (mddev->raid_disks - min(0, mddev->delta_disks))) {
3231                         rdev->raid_disk = -1;
3232                         clear_bit(In_sync, &rdev->flags);
3233                 }
3234         }
3235 }
3236 
3237 /* Read a fixed-point number.
3238  * Numbers in sysfs attributes should be in "standard" units where
3239  * possible, so time should be in seconds.
3240  * However we internally use a a much smaller unit such as
3241  * milliseconds or jiffies.
3242  * This function takes a decimal number with a possible fractional
3243  * component, and produces an integer which is the result of
3244  * multiplying that number by 10^'scale'.
3245  * all without any floating-point arithmetic.
3246  */
3247 int strict_strtoul_scaled(const char *cp, unsigned long *res, int scale)
3248 {
3249         unsigned long result = 0;
3250         long decimals = -1;
3251         while (isdigit(*cp) || (*cp == '.' && decimals < 0)) {
3252                 if (*cp == '.')
3253                         decimals = 0;
3254                 else if (decimals < scale) {
3255                         unsigned int value;
3256                         value = *cp - '';
3257                         result = result * 10 + value;
3258                         if (decimals >= 0)
3259                                 decimals++;
3260                 }
3261                 cp++;
3262         }
3263         if (*cp == '\n')
3264                 cp++;
3265         if (*cp)
3266                 return -EINVAL;
3267         if (decimals < 0)
3268                 decimals = 0;
3269         while (decimals < scale) {
3270                 result *= 10;
3271                 decimals ++;
3272         }
3273         *res = result;
3274         return 0;
3275 }
3276 
3277 static void md_safemode_timeout(unsigned long data);
3278 
3279 static ssize_t
3280 safe_delay_show(struct mddev *mddev, char *page)
3281 {
3282         int msec = (mddev->safemode_delay*1000)/HZ;
3283         return sprintf(page, "%d.%03d\n", msec/1000, msec%1000);
3284 }
3285 static ssize_t
3286 safe_delay_store(struct mddev *mddev, const char *cbuf, size_t len)
3287 {
3288         unsigned long msec;
3289 
3290         if (strict_strtoul_scaled(cbuf, &msec, 3) < 0)
3291                 return -EINVAL;
3292         if (msec == 0)
3293                 mddev->safemode_delay = 0;
3294         else {
3295                 unsigned long old_delay = mddev->safemode_delay;
3296                 unsigned long new_delay = (msec*HZ)/1000;
3297 
3298                 if (new_delay == 0)
3299                         new_delay = 1;
3300                 mddev->safemode_delay = new_delay;
3301                 if (new_delay < old_delay || old_delay == 0)
3302                         mod_timer(&mddev->safemode_timer, jiffies+1);
3303         }
3304         return len;
3305 }
3306 static struct md_sysfs_entry md_safe_delay =
3307 __ATTR(safe_mode_delay, S_IRUGO|S_IWUSR,safe_delay_show, safe_delay_store);
3308 
3309 static ssize_t
3310 level_show(struct mddev *mddev, char *page)
3311 {
3312         struct md_personality *p;
3313         int ret;
3314         spin_lock(&mddev->lock);
3315         p = mddev->pers;
3316         if (p)
3317                 ret = sprintf(page, "%s\n", p->name);
3318         else if (mddev->clevel[0])
3319                 ret = sprintf(page, "%s\n", mddev->clevel);
3320         else if (mddev->level != LEVEL_NONE)
3321                 ret = sprintf(page, "%d\n", mddev->level);
3322         else
3323                 ret = 0;
3324         spin_unlock(&mddev->lock);
3325         return ret;
3326 }
3327 
3328 static ssize_t
3329 level_store(struct mddev *mddev, const char *buf, size_t len)
3330 {
3331         char clevel[16];
3332         ssize_t rv;
3333         size_t slen = len;
3334         struct md_personality *pers, *oldpers;
3335         long level;
3336         void *priv, *oldpriv;
3337         struct md_rdev *rdev;
3338 
3339         if (slen == 0 || slen >= sizeof(clevel))
3340                 return -EINVAL;
3341 
3342         rv = mddev_lock(mddev);
3343         if (rv)
3344                 return rv;
3345 
3346         if (mddev->pers == NULL) {
3347                 strncpy(mddev->clevel, buf, slen);
3348                 if (mddev->clevel[slen-1] == '\n')
3349                         slen--;
3350                 mddev->clevel[slen] = 0;
3351                 mddev->level = LEVEL_NONE;
3352                 rv = len;
3353                 goto out_unlock;
3354         }
3355         rv = -EROFS;
3356         if (mddev->ro)
3357                 goto out_unlock;
3358 
3359         /* request to change the personality.  Need to ensure:
3360          *  - array is not engaged in resync/recovery/reshape
3361          *  - old personality can be suspended
3362          *  - new personality will access other array.
3363          */
3364 
3365         rv = -EBUSY;
3366         if (mddev->sync_thread ||
3367             test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
3368             mddev->reshape_position != MaxSector ||
3369             mddev->sysfs_active)
3370                 goto out_unlock;
3371 
3372         rv = -EINVAL;
3373         if (!mddev->pers->quiesce) {
3374                 printk(KERN_WARNING "md: %s: %s does not support online personality change\n",
3375                        mdname(mddev), mddev->pers->name);
3376                 goto out_unlock;
3377         }
3378 
3379         /* Now find the new personality */
3380         strncpy(clevel, buf, slen);
3381         if (clevel[slen-1] == '\n')
3382                 slen--;
3383         clevel[slen] = 0;
3384         if (kstrtol(clevel, 10, &level))
3385                 level = LEVEL_NONE;
3386 
3387         if (request_module("md-%s", clevel) != 0)
3388                 request_module("md-level-%s", clevel);
3389         spin_lock(&pers_lock);
3390         pers = find_pers(level, clevel);
3391         if (!pers || !try_module_get(pers->owner)) {
3392                 spin_unlock(&pers_lock);
3393                 printk(KERN_WARNING "md: personality %s not loaded\n", clevel);
3394                 rv = -EINVAL;
3395                 goto out_unlock;
3396         }
3397         spin_unlock(&pers_lock);
3398 
3399         if (pers == mddev->pers) {
3400                 /* Nothing to do! */
3401                 module_put(pers->owner);
3402                 rv = len;
3403                 goto out_unlock;
3404         }
3405         if (!pers->takeover) {
3406                 module_put(pers->owner);
3407                 printk(KERN_WARNING "md: %s: %s does not support personality takeover\n",
3408                        mdname(mddev), clevel);
3409                 rv = -EINVAL;
3410                 goto out_unlock;
3411         }
3412 
3413         rdev_for_each(rdev, mddev)
3414                 rdev->new_raid_disk = rdev->raid_disk;
3415 
3416         /* ->takeover must set new_* and/or delta_disks
3417          * if it succeeds, and may set them when it fails.
3418          */
3419         priv = pers->takeover(mddev);
3420         if (IS_ERR(priv)) {
3421                 mddev->new_level = mddev->level;
3422                 mddev->new_layout = mddev->layout;
3423                 mddev->new_chunk_sectors = mddev->chunk_sectors;
3424                 mddev->raid_disks -= mddev->delta_disks;
3425                 mddev->delta_disks = 0;
3426                 mddev->reshape_backwards = 0;
3427                 module_put(pers->owner);
3428                 printk(KERN_WARNING "md: %s: %s would not accept array\n",
3429                        mdname(mddev), clevel);
3430                 rv = PTR_ERR(priv);
3431                 goto out_unlock;
3432         }
3433 
3434         /* Looks like we have a winner */
3435         mddev_suspend(mddev);
3436         mddev_detach(mddev);
3437 
3438         spin_lock(&mddev->lock);
3439         oldpers = mddev->pers;
3440         oldpriv = mddev->private;
3441         mddev->pers = pers;
3442         mddev->private = priv;
3443         strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
3444         mddev->level = mddev->new_level;
3445         mddev->layout = mddev->new_layout;
3446         mddev->chunk_sectors = mddev->new_chunk_sectors;
3447         mddev->delta_disks = 0;
3448         mddev->reshape_backwards = 0;
3449         mddev->degraded = 0;
3450         spin_unlock(&mddev->lock);
3451 
3452         if (oldpers->sync_request == NULL &&
3453             mddev->external) {
3454                 /* We are converting from a no-redundancy array
3455                  * to a redundancy array and metadata is managed
3456                  * externally so we need to be sure that writes
3457                  * won't block due to a need to transition
3458                  *      clean->dirty
3459                  * until external management is started.
3460                  */
3461                 mddev->in_sync = 0;
3462                 mddev->safemode_delay = 0;
3463                 mddev->safemode = 0;
3464         }
3465 
3466         oldpers->free(mddev, oldpriv);
3467 
3468         if (oldpers->sync_request == NULL &&
3469             pers->sync_request != NULL) {
3470                 /* need to add the md_redundancy_group */
3471                 if (sysfs_create_group(&mddev->kobj, &md_redundancy_group))
3472                         printk(KERN_WARNING
3473                                "md: cannot register extra attributes for %s\n",
3474                                mdname(mddev));
3475                 mddev->sysfs_action = sysfs_get_dirent(mddev->kobj.sd, "sync_action");
3476         }
3477         if (oldpers->sync_request != NULL &&
3478             pers->sync_request == NULL) {
3479                 /* need to remove the md_redundancy_group */
3480                 if (mddev->to_remove == NULL)
3481                         mddev->to_remove = &md_redundancy_group;
3482         }
3483 
3484         rdev_for_each(rdev, mddev) {
3485                 if (rdev->raid_disk < 0)
3486                         continue;
3487                 if (rdev->new_raid_disk >= mddev->raid_disks)
3488                         rdev->new_raid_disk = -1;
3489                 if (rdev->new_raid_disk == rdev->raid_disk)
3490                         continue;
3491                 sysfs_unlink_rdev(mddev, rdev);
3492         }
3493         rdev_for_each(rdev, mddev) {
3494                 if (rdev->raid_disk < 0)
3495                         continue;
3496                 if (rdev->new_raid_disk == rdev->raid_disk)
3497                         continue;
3498                 rdev->raid_disk = rdev->new_raid_disk;
3499                 if (rdev->raid_disk < 0)
3500                         clear_bit(In_sync, &rdev->flags);
3501                 else {
3502                         if (sysfs_link_rdev(mddev, rdev))
3503                                 printk(KERN_WARNING "md: cannot register rd%d"
3504                                        " for %s after level change\n",
3505                                        rdev->raid_disk, mdname(mddev));
3506                 }
3507         }
3508 
3509         if (pers->sync_request == NULL) {
3510                 /* this is now an array without redundancy, so
3511                  * it must always be in_sync
3512                  */
3513                 mddev->in_sync = 1;
3514                 del_timer_sync(&mddev->safemode_timer);
3515         }
3516         blk_set_stacking_limits(&mddev->queue->limits);
3517         pers->run(mddev);
3518         set_bit(MD_CHANGE_DEVS, &mddev->flags);
3519         mddev_resume(mddev);
3520         if (!mddev->thread)
3521                 md_update_sb(mddev, 1);
3522         sysfs_notify(&mddev->kobj, NULL, "level");
3523         md_new_event(mddev);
3524         rv = len;
3525 out_unlock:
3526         mddev_unlock(mddev);
3527         return rv;
3528 }
3529 
3530 static struct md_sysfs_entry md_level =
3531 __ATTR(level, S_IRUGO|S_IWUSR, level_show, level_store);
3532 
3533 static ssize_t
3534 layout_show(struct mddev *mddev, char *page)
3535 {
3536         /* just a number, not meaningful for all levels */
3537         if (mddev->reshape_position != MaxSector &&
3538             mddev->layout != mddev->new_layout)
3539                 return sprintf(page, "%d (%d)\n",
3540                                mddev->new_layout, mddev->layout);
3541         return sprintf(page, "%d\n", mddev->layout);
3542 }
3543 
3544 static ssize_t
3545 layout_store(struct mddev *mddev, const char *buf, size_t len)
3546 {
3547         char *e;
3548         unsigned long n = simple_strtoul(buf, &e, 10);
3549         int err;
3550 
3551         if (!*buf || (*e && *e != '\n'))
3552                 return -EINVAL;
3553         err = mddev_lock(mddev);
3554         if (err)
3555                 return err;
3556 
3557         if (mddev->pers) {
3558                 if (mddev->pers->check_reshape == NULL)
3559                         err = -EBUSY;
3560                 else if (mddev->ro)
3561                         err = -EROFS;
3562                 else {
3563                         mddev->new_layout = n;
3564                         err = mddev->pers->check_reshape(mddev);
3565                         if (err)
3566                                 mddev->new_layout = mddev->layout;
3567                 }
3568         } else {
3569                 mddev->new_layout = n;
3570                 if (mddev->reshape_position == MaxSector)
3571                         mddev->layout = n;
3572         }
3573         mddev_unlock(mddev);
3574         return err ?: len;
3575 }
3576 static struct md_sysfs_entry md_layout =
3577 __ATTR(layout, S_IRUGO|S_IWUSR, layout_show, layout_store);
3578 
3579 static ssize_t
3580 raid_disks_show(struct mddev *mddev, char *page)
3581 {
3582         if (mddev->raid_disks == 0)
3583                 return 0;
3584         if (mddev->reshape_position != MaxSector &&
3585             mddev->delta_disks != 0)
3586                 return sprintf(page, "%d (%d)\n", mddev->raid_disks,
3587                                mddev->raid_disks - mddev->delta_disks);
3588         return sprintf(page, "%d\n", mddev->raid_disks);
3589 }
3590 
3591 static int update_raid_disks(struct mddev *mddev, int raid_disks);
3592 
3593 static ssize_t
3594 raid_disks_store(struct mddev *mddev, const char *buf, size_t len)
3595 {
3596         char *e;
3597         int err;
3598         unsigned long n = simple_strtoul(buf, &e, 10);
3599 
3600         if (!*buf || (*e && *e != '\n'))
3601                 return -EINVAL;
3602 
3603         err = mddev_lock(mddev);
3604         if (err)
3605                 return err;
3606         if (mddev->pers)
3607                 err = update_raid_disks(mddev, n);
3608         else if (mddev->reshape_position != MaxSector) {
3609                 struct md_rdev *rdev;
3610                 int olddisks = mddev->raid_disks - mddev->delta_disks;
3611 
3612                 err = -EINVAL;
3613                 rdev_for_each(rdev, mddev) {
3614                         if (olddisks < n &&
3615                             rdev->data_offset < rdev->new_data_offset)
3616                                 goto out_unlock;
3617                         if (olddisks > n &&
3618                             rdev->data_offset > rdev->new_data_offset)
3619                                 goto out_unlock;
3620                 }
3621                 err = 0;
3622                 mddev->delta_disks = n - olddisks;
3623                 mddev->raid_disks = n;
3624                 mddev->reshape_backwards = (mddev->delta_disks < 0);
3625         } else
3626                 mddev->raid_disks = n;
3627 out_unlock:
3628         mddev_unlock(mddev);
3629         return err ? err : len;
3630 }
3631 static struct md_sysfs_entry md_raid_disks =
3632 __ATTR(raid_disks, S_IRUGO|S_IWUSR, raid_disks_show, raid_disks_store);
3633 
3634 static ssize_t
3635 chunk_size_show(struct mddev *mddev, char *page)
3636 {
3637         if (mddev->reshape_position != MaxSector &&
3638             mddev->chunk_sectors != mddev->new_chunk_sectors)
3639                 return sprintf(page, "%d (%d)\n",
3640                                mddev->new_chunk_sectors << 9,
3641                                mddev->chunk_sectors << 9);
3642         return sprintf(page, "%d\n", mddev->chunk_sectors << 9);
3643 }
3644 
3645 static ssize_t
3646 chunk_size_store(struct mddev *mddev, const char *buf, size_t len)
3647 {
3648         int err;
3649         char *e;
3650         unsigned long n = simple_strtoul(buf, &e, 10);
3651 
3652         if (!*buf || (*e && *e != '\n'))
3653                 return -EINVAL;
3654 
3655         err = mddev_lock(mddev);
3656         if (err)
3657                 return err;
3658         if (mddev->pers) {
3659                 if (mddev->pers->check_reshape == NULL)
3660                         err = -EBUSY;
3661                 else if (mddev->ro)
3662                         err = -EROFS;
3663                 else {
3664                         mddev->new_chunk_sectors = n >> 9;
3665                         err = mddev->pers->check_reshape(mddev);
3666                         if (err)
3667                                 mddev->new_chunk_sectors = mddev->chunk_sectors;
3668                 }
3669         } else {
3670                 mddev->new_chunk_sectors = n >> 9;
3671                 if (mddev->reshape_position == MaxSector)
3672                         mddev->chunk_sectors = n >> 9;
3673         }
3674         mddev_unlock(mddev);
3675         return err ?: len;
3676 }
3677 static struct md_sysfs_entry md_chunk_size =
3678 __ATTR(chunk_size, S_IRUGO|S_IWUSR, chunk_size_show, chunk_size_store);
3679 
3680 static ssize_t
3681 resync_start_show(struct mddev *mddev, char *page)
3682 {
3683         if (mddev->recovery_cp == MaxSector)
3684                 return sprintf(page, "none\n");
3685         return sprintf(page, "%llu\n", (unsigned long long)mddev->recovery_cp);
3686 }
3687 
3688 static ssize_t
3689 resync_start_store(struct mddev *mddev, const char *buf, size_t len)
3690 {
3691         int err;
3692         char *e;
3693         unsigned long long n = simple_strtoull(buf, &e, 10);
3694 
3695         err = mddev_lock(mddev);
3696         if (err)
3697                 return err;
3698         if (mddev->pers && !test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
3699                 err = -EBUSY;
3700         else if (cmd_match(buf, "none"))
3701                 n = MaxSector;
3702         else if (!*buf || (*e && *e != '\n'))
3703                 err = -EINVAL;
3704 
3705         if (!err) {
3706                 mddev->recovery_cp = n;
3707                 if (mddev->pers)
3708                         set_bit(MD_CHANGE_CLEAN, &mddev->flags);
3709         }
3710         mddev_unlock(mddev);
3711         return err ?: len;
3712 }
3713 static struct md_sysfs_entry md_resync_start =
3714 __ATTR_PREALLOC(resync_start, S_IRUGO|S_IWUSR,
3715                 resync_start_show, resync_start_store);
3716 
3717 /*
3718  * The array state can be:
3719  *
3720  * clear
3721  *     No devices, no size, no level
3722  *     Equivalent to STOP_ARRAY ioctl
3723  * inactive
3724  *     May have some settings, but array is not active
3725  *        all IO results in error
3726  *     When written, doesn't tear down array, but just stops it
3727  * suspended (not supported yet)
3728  *     All IO requests will block. The array can be reconfigured.
3729  *     Writing this, if accepted, will block until array is quiescent
3730  * readonly
3731  *     no resync can happen.  no superblocks get written.
3732  *     write requests fail
3733  * read-auto
3734  *     like readonly, but behaves like 'clean' on a write request.
3735  *
3736  * clean - no pending writes, but otherwise active.
3737  *     When written to inactive array, starts without resync
3738  *     If a write request arrives then
3739  *       if metadata is known, mark 'dirty' and switch to 'active'.
3740  *       if not known, block and switch to write-pending
3741  *     If written to an active array that has pending writes, then fails.
3742  * active
3743  *     fully active: IO and resync can be happening.
3744  *     When written to inactive array, starts with resync
3745  *
3746  * write-pending
3747  *     clean, but writes are blocked waiting for 'active' to be written.
3748  *
3749  * active-idle
3750  *     like active, but no writes have been seen for a while (100msec).
3751  *
3752  */
3753 enum array_state { clear, inactive, suspended, readonly, read_auto, clean, active,
3754                    write_pending, active_idle, bad_word};
3755 static char *array_states[] = {
3756         "clear", "inactive", "suspended", "readonly", "read-auto", "clean", "active",
3757         "write-pending", "active-idle", NULL };
3758 
3759 static int match_word(const char *word, char **list)
3760 {
3761         int n;
3762         for (n=0; list[n]; n++)
3763                 if (cmd_match(word, list[n]))
3764                         break;
3765         return n;
3766 }
3767 
3768 static ssize_t
3769 array_state_show(struct mddev *mddev, char *page)
3770 {
3771         enum array_state st = inactive;
3772 
3773         if (mddev->pers)
3774                 switch(mddev->ro) {
3775                 case 1:
3776                         st = readonly;
3777                         break;
3778                 case 2:
3779                         st = read_auto;
3780                         break;
3781                 case 0:
3782                         if (mddev->in_sync)
3783                                 st = clean;
3784                         else if (test_bit(MD_CHANGE_PENDING, &mddev->flags))
3785                                 st = write_pending;
3786                         else if (mddev->safemode)
3787                                 st = active_idle;
3788                         else
3789                                 st = active;
3790                 }
3791         else {
3792                 if (list_empty(&mddev->disks) &&
3793                     mddev->raid_disks == 0 &&
3794                     mddev->dev_sectors == 0)
3795                         st = clear;
3796                 else
3797                         st = inactive;
3798         }
3799         return sprintf(page, "%s\n", array_states[st]);
3800 }
3801 
3802 static int do_md_stop(struct mddev *mddev, int ro, struct block_device *bdev);
3803 static int md_set_readonly(struct mddev *mddev, struct block_device *bdev);
3804 static int do_md_run(struct mddev *mddev);
3805 static int restart_array(struct mddev *mddev);
3806 
3807 static ssize_t
3808 array_state_store(struct mddev *mddev, const char *buf, size_t len)
3809 {
3810         int err;
3811         enum array_state st = match_word(buf, array_states);
3812 
3813         if (mddev->pers && (st == active || st == clean) && mddev->ro != 1) {
3814                 /* don't take reconfig_mutex when toggling between
3815                  * clean and active
3816                  */
3817                 spin_lock(&mddev->lock);
3818                 if (st == active) {
3819                         restart_array(mddev);
3820                         clear_bit(MD_CHANGE_PENDING, &mddev->flags);
3821                         wake_up(&mddev->sb_wait);
3822                         err = 0;
3823                 } else /* st == clean */ {
3824                         restart_array(mddev);
3825                         if (atomic_read(&mddev->writes_pending) == 0) {
3826                                 if (mddev->in_sync == 0) {
3827                                         mddev->in_sync = 1;
3828                                         if (mddev->safemode == 1)
3829                                                 mddev->safemode = 0;
3830                                         set_bit(MD_CHANGE_CLEAN, &mddev->flags);
3831                                 }
3832                                 err = 0;
3833                         } else
3834                                 err = -EBUSY;
3835                 }
3836                 spin_unlock(&mddev->lock);
3837                 return err ?: len;
3838         }
3839         err = mddev_lock(mddev);
3840         if (err)
3841                 return err;
3842         err = -EINVAL;
3843         switch(st) {
3844         case bad_word:
3845                 break;
3846         case clear:
3847                 /* stopping an active array */
3848                 err = do_md_stop(mddev, 0, NULL);
3849                 break;
3850         case inactive:
3851                 /* stopping an active array */
3852                 if (mddev->pers)
3853                         err = do_md_stop(mddev, 2, NULL);
3854                 else
3855                         err = 0; /* already inactive */
3856                 break;
3857         case suspended:
3858                 break; /* not supported yet */
3859         case readonly:
3860                 if (mddev->pers)
3861                         err = md_set_readonly(mddev, NULL);
3862                 else {
3863                         mddev->ro = 1;
3864                         set_disk_ro(mddev->gendisk, 1);
3865                         err = do_md_run(mddev);
3866                 }
3867                 break;
3868         case read_auto:
3869                 if (mddev->pers) {
3870                         if (mddev->ro == 0)
3871                                 err = md_set_readonly(mddev, NULL);
3872                         else if (mddev->ro == 1)
3873                                 err = restart_array(mddev);
3874                         if (err == 0) {
3875                                 mddev->ro = 2;
3876                                 set_disk_ro(mddev->gendisk, 0);
3877                         }
3878                 } else {
3879                         mddev->ro = 2;
3880                         err = do_md_run(mddev);
3881                 }
3882                 break;
3883         case clean:
3884                 if (mddev->pers) {
3885                         restart_array(mddev);
3886                         spin_lock(&mddev->lock);
3887                         if (atomic_read(&mddev->writes_pending) == 0) {
3888                                 if (mddev->in_sync == 0) {
3889                                         mddev->in_sync = 1;
3890                                         if (mddev->safemode == 1)
3891                                                 mddev->safemode = 0;
3892                                         set_bit(MD_CHANGE_CLEAN, &mddev->flags);
3893                                 }
3894                                 err = 0;
3895                         } else
3896                                 err = -EBUSY;
3897                         spin_unlock(&mddev->lock);
3898                 } else
3899                         err = -EINVAL;
3900                 break;
3901         case active:
3902                 if (mddev->pers) {
3903                         restart_array(mddev);
3904                         clear_bit(MD_CHANGE_PENDING, &mddev->flags);
3905                         wake_up(&mddev->sb_wait);
3906                         err = 0;
3907                 } else {
3908                         mddev->ro = 0;
3909                         set_disk_ro(mddev->gendisk, 0);
3910                         err = do_md_run(mddev);
3911                 }
3912                 break;
3913         case write_pending:
3914         case active_idle:
3915                 /* these cannot be set */
3916                 break;
3917         }
3918 
3919         if (!err) {
3920                 if (mddev->hold_active == UNTIL_IOCTL)
3921                         mddev->hold_active = 0;
3922                 sysfs_notify_dirent_safe(mddev->sysfs_state);
3923         }
3924         mddev_unlock(mddev);
3925         return err ?: len;
3926 }
3927 static struct md_sysfs_entry md_array_state =
3928 __ATTR_PREALLOC(array_state, S_IRUGO|S_IWUSR, array_state_show, array_state_store);
3929 
3930 static ssize_t
3931 max_corrected_read_errors_show(struct mddev *mddev, char *page) {
3932         return sprintf(page, "%d\n",
3933                        atomic_read(&mddev->max_corr_read_errors));
3934 }
3935 
3936 static ssize_t
3937 max_corrected_read_errors_store(struct mddev *mddev, const char *buf, size_t len)
3938 {
3939         char *e;
3940         unsigned long n = simple_strtoul(buf, &e, 10);
3941 
3942         if (*buf && (*e == 0 || *e == '\n')) {
3943                 atomic_set(&mddev->max_corr_read_errors, n);
3944                 return len;
3945         }
3946         return -EINVAL;
3947 }
3948 
3949 static struct md_sysfs_entry max_corr_read_errors =
3950 __ATTR(max_read_errors, S_IRUGO|S_IWUSR, max_corrected_read_errors_show,
3951         max_corrected_read_errors_store);
3952 
3953 static ssize_t
3954 null_show(struct mddev *mddev, char *page)
3955 {
3956         return -EINVAL;
3957 }
3958 
3959 static ssize_t
3960 new_dev_store(struct mddev *mddev, const char *buf, size_t len)
3961 {
3962         /* buf must be %d:%d\n? giving major and minor numbers */
3963         /* The new device is added to the array.
3964          * If the array has a persistent superblock, we read the
3965          * superblock to initialise info and check validity.
3966          * Otherwise, only checking done is that in bind_rdev_to_array,
3967          * which mainly checks size.
3968          */
3969         char *e;
3970         int major = simple_strtoul(buf, &e, 10);
3971         int minor;
3972         dev_t dev;
3973         struct md_rdev *rdev;
3974         int err;
3975 
3976         if (!*buf || *e != ':' || !e[1] || e[1] == '\n')
3977                 return -EINVAL;
3978         minor = simple_strtoul(e+1, &e, 10);
3979         if (*e && *e != '\n')
3980                 return -EINVAL;
3981         dev = MKDEV(major, minor);
3982         if (major != MAJOR(dev) ||
3983             minor != MINOR(dev))
3984                 return -EOVERFLOW;
3985 
3986         flush_workqueue(md_misc_wq);
3987 
3988         err = mddev_lock(mddev);
3989         if (err)
3990                 return err;
3991         if (mddev->persistent) {
3992                 rdev = md_import_device(dev, mddev->major_version,
3993                                         mddev->minor_version);
3994                 if (!IS_ERR(rdev) && !list_empty(&mddev->disks)) {
3995                         struct md_rdev *rdev0
3996                                 = list_entry(mddev->disks.next,
3997                                              struct md_rdev, same_set);
3998                         err = super_types[mddev->major_version]
3999                                 .load_super(rdev, rdev0, mddev->minor_version);
4000                         if (err < 0)
4001                                 goto out;
4002                 }
4003         } else if (mddev->external)
4004                 rdev = md_import_device(dev, -2, -1);
4005         else
4006                 rdev = md_import_device(dev, -1, -1);
4007 
4008         if (IS_ERR(rdev))
4009                 return PTR_ERR(rdev);
4010         err = bind_rdev_to_array(rdev, mddev);
4011  out:
4012         if (err)
4013                 export_rdev(rdev);
4014         mddev_unlock(mddev);
4015         return err ? err : len;
4016 }
4017 
4018 static struct md_sysfs_entry md_new_device =
4019 __ATTR(new_dev, S_IWUSR, null_show, new_dev_store);
4020 
4021 static ssize_t
4022 bitmap_store(struct mddev *mddev, const char *buf, size_t len)
4023 {
4024         char *end;
4025         unsigned long chunk, end_chunk;
4026         int err;
4027 
4028         err = mddev_lock(mddev);
4029         if (err)
4030                 return err;
4031         if (!mddev->bitmap)
4032                 goto out;
4033         /* buf should be <chunk> <chunk> ... or <chunk>-<chunk> ... (range) */
4034         while (*buf) {
4035                 chunk = end_chunk = simple_strtoul(buf, &end, 0);
4036                 if (buf == end) break;
4037                 if (*end == '-') { /* range */
4038                         buf = end + 1;
4039                         end_chunk = simple_strtoul(buf, &end, 0);
4040                         if (buf == end) break;
4041                 }
4042                 if (*end && !isspace(*end)) break;
4043                 bitmap_dirty_bits(mddev->bitmap, chunk, end_chunk);
4044                 buf = skip_spaces(end);
4045         }
4046         bitmap_unplug(mddev->bitmap); /* flush the bits to disk */
4047 out:
4048         mddev_unlock(mddev);
4049         return len;
4050 }
4051 
4052 static struct md_sysfs_entry md_bitmap =
4053 __ATTR(bitmap_set_bits, S_IWUSR, null_show, bitmap_store);
4054 
4055 static ssize_t
4056 size_show(struct mddev *mddev, char *page)
4057 {
4058         return sprintf(page, "%llu\n",
4059                 (unsigned long long)mddev->dev_sectors / 2);
4060 }
4061 
4062 static int update_size(struct mddev *mddev, sector_t num_sectors);
4063 
4064 static ssize_t
4065 size_store(struct mddev *mddev, const char *buf, size_t len)
4066 {
4067         /* If array is inactive, we can reduce the component size, but
4068          * not increase it (except from 0).
4069          * If array is active, we can try an on-line resize
4070          */
4071         sector_t sectors;
4072         int err = strict_blocks_to_sectors(buf, &sectors);
4073 
4074         if (err < 0)
4075                 return err;
4076         err = mddev_lock(mddev);
4077         if (err)
4078                 return err;
4079         if (mddev->pers) {
4080                 if (mddev_is_clustered(mddev))
4081                         md_cluster_ops->metadata_update_start(mddev);
4082                 err = update_size(mddev, sectors);
4083                 md_update_sb(mddev, 1);
4084                 if (mddev_is_clustered(mddev))
4085                         md_cluster_ops->metadata_update_finish(mddev);
4086         } else {
4087                 if (mddev->dev_sectors == 0 ||
4088                     mddev->dev_sectors > sectors)
4089                         mddev->dev_sectors = sectors;
4090                 else
4091                         err = -ENOSPC;
4092         }
4093         mddev_unlock(mddev);
4094         return err ? err : len;
4095 }
4096 
4097 static struct md_sysfs_entry md_size =
4098 __ATTR(component_size, S_IRUGO|S_IWUSR, size_show, size_store);
4099 
4100 /* Metadata version.
4101  * This is one of
4102  *   'none' for arrays with no metadata (good luck...)
4103  *   'external' for arrays with externally managed metadata,
4104  * or N.M for internally known formats
4105  */
4106 static ssize_t
4107 metadata_show(struct mddev *mddev, char *page)
4108 {
4109         if (mddev->persistent)
4110                 return sprintf(page, "%d.%d\n",
4111                                mddev->major_version, mddev->minor_version);
4112         else if (mddev->external)
4113                 return sprintf(page, "external:%s\n", mddev->metadata_type);
4114         else
4115                 return sprintf(page, "none\n");
4116 }
4117 
4118 static ssize_t
4119 metadata_store(struct mddev *mddev, const char *buf, size_t len)
4120 {
4121         int major, minor;
4122         char *e;
4123         int err;
4124         /* Changing the details of 'external' metadata is
4125          * always permitted.  Otherwise there must be
4126          * no devices attached to the array.
4127          */
4128 
4129         err = mddev_lock(mddev);
4130         if (err)
4131                 return err;
4132         err = -EBUSY;
4133         if (mddev->external && strncmp(buf, "external:", 9) == 0)
4134                 ;
4135         else if (!list_empty(&mddev->disks))
4136                 goto out_unlock;
4137 
4138         err = 0;
4139         if (cmd_match(buf, "none")) {
4140                 mddev->persistent = 0;
4141                 mddev->external = 0;
4142                 mddev->major_version = 0;
4143                 mddev->minor_version = 90;
4144                 goto out_unlock;
4145         }
4146         if (strncmp(buf, "external:", 9) == 0) {
4147                 size_t namelen = len-9;
4148                 if (namelen >= sizeof(mddev->metadata_type))
4149                         namelen = sizeof(mddev->metadata_type)-1;
4150                 strncpy(mddev->metadata_type, buf+9, namelen);
4151                 mddev->metadata_type[namelen] = 0;
4152                 if (namelen && mddev->metadata_type[namelen-1] == '\n')
4153                         mddev->metadata_type[--namelen] = 0;
4154                 mddev->persistent = 0;
4155                 mddev->external = 1;
4156                 mddev->major_version = 0;
4157                 mddev->minor_version = 90;
4158                 goto out_unlock;
4159         }
4160         major = simple_strtoul(buf, &e, 10);
4161         err = -EINVAL;
4162         if (e==buf || *e != '.')
4163                 goto out_unlock;
4164         buf = e+1;
4165         minor = simple_strtoul(buf, &e, 10);
4166         if (e==buf || (*e && *e != '\n') )
4167                 goto out_unlock;
4168         err = -ENOENT;
4169         if (major >= ARRAY_SIZE(super_types) || super_types[major].name == NULL)
4170                 goto out_unlock;
4171         mddev->major_version = major;
4172         mddev->minor_version = minor;
4173         mddev->persistent = 1;
4174         mddev->external = 0;
4175         err = 0;
4176 out_unlock:
4177         mddev_unlock(mddev);
4178         return err ?: len;
4179 }
4180 
4181 static struct md_sysfs_entry md_metadata =
4182 __ATTR_PREALLOC(metadata_version, S_IRUGO|S_IWUSR, metadata_show, metadata_store);
4183 
4184 static ssize_t
4185 action_show(struct mddev *mddev, char *page)
4186 {
4187         char *type = "idle";
4188         unsigned long recovery = mddev->recovery;
4189         if (test_bit(MD_RECOVERY_FROZEN, &recovery))
4190                 type = "frozen";
4191         else if (test_bit(MD_RECOVERY_RUNNING, &recovery) ||
4192             (!mddev->ro && test_bit(MD_RECOVERY_NEEDED, &recovery))) {
4193                 if (test_bit(MD_RECOVERY_RESHAPE, &recovery))
4194                         type = "reshape";
4195                 else if (test_bit(MD_RECOVERY_SYNC, &recovery)) {
4196                         if (!test_bit(MD_RECOVERY_REQUESTED, &recovery))
4197                                 type = "resync";
4198                         else if (test_bit(MD_RECOVERY_CHECK, &recovery))
4199                                 type = "check";
4200                         else
4201                                 type = "repair";
4202                 } else if (test_bit(MD_RECOVERY_RECOVER, &recovery))
4203                         type = "recover";
4204         }
4205         return sprintf(page, "%s\n", type);
4206 }
4207 
4208 static ssize_t
4209 action_store(struct mddev *mddev, const char *page, size_t len)
4210 {
4211         if (!mddev->pers || !mddev->pers->sync_request)
4212                 return -EINVAL;
4213 
4214 
4215         if (cmd_match(page, "idle") || cmd_match(page, "frozen")) {
4216                 if (cmd_match(page, "frozen"))
4217                         set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4218                 else
4219                         clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4220                 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) &&
4221                     mddev_lock(mddev) == 0) {
4222                         flush_workqueue(md_misc_wq);
4223                         if (mddev->sync_thread) {
4224                                 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
4225                                 md_reap_sync_thread(mddev);
4226                         }
4227                         mddev_unlock(mddev);
4228                 }
4229         } else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
4230                    test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
4231                 return -EBUSY;
4232         else if (cmd_match(page, "resync"))
4233                 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4234         else if (cmd_match(page, "recover")) {
4235                 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4236                 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
4237         } else if (cmd_match(page, "reshape")) {
4238                 int err;
4239                 if (mddev->pers->start_reshape == NULL)
4240                         return -EINVAL;
4241                 err = mddev_lock(mddev);
4242                 if (!err) {
4243                         clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4244                         err = mddev->pers->start_reshape(mddev);
4245                         mddev_unlock(mddev);
4246                 }
4247                 if (err)
4248                         return err;
4249                 sysfs_notify(&mddev->kobj, NULL, "degraded");
4250         } else {
4251                 if (cmd_match(page, "check"))
4252                         set_bit(MD_RECOVERY_CHECK, &mddev->recovery);
4253                 else if (!cmd_match(page, "repair"))
4254                         return -EINVAL;
4255                 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4256                 set_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
4257                 set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
4258         }
4259         if (mddev->ro == 2) {
4260                 /* A write to sync_action is enough to justify
4261                  * canceling read-auto mode
4262                  */
4263                 mddev->ro = 0;
4264                 md_wakeup_thread(mddev->sync_thread);
4265         }
4266         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4267         md_wakeup_thread(mddev->thread);
4268         sysfs_notify_dirent_safe(mddev->sysfs_action);
4269         return len;
4270 }
4271 
4272 static struct md_sysfs_entry md_scan_mode =
4273 __ATTR_PREALLOC(sync_action, S_IRUGO|S_IWUSR, action_show, action_store);
4274 
4275 static ssize_t
4276 last_sync_action_show(struct mddev *mddev, char *page)
4277 {
4278         return sprintf(page, "%s\n", mddev->last_sync_action);
4279 }
4280 
4281 static struct md_sysfs_entry md_last_scan_mode = __ATTR_RO(last_sync_action);
4282 
4283 static ssize_t
4284 mismatch_cnt_show(struct mddev *mddev, char *page)
4285 {
4286         return sprintf(page, "%llu\n",
4287                        (unsigned long long)
4288                        atomic64_read(&mddev->resync_mismatches));
4289 }
4290 
4291 static struct md_sysfs_entry md_mismatches = __ATTR_RO(mismatch_cnt);
4292 
4293 static ssize_t
4294 sync_min_show(struct mddev *mddev, char *page)
4295 {
4296         return sprintf(page, "%d (%s)\n", speed_min(mddev),
4297                        mddev->sync_speed_min ? "local": "system");
4298 }
4299 
4300 static ssize_t
4301 sync_min_store(struct mddev *mddev, const char *buf, size_t len)
4302 {
4303         int min;
4304         char *e;
4305         if (strncmp(buf, "system", 6)==0) {
4306                 mddev->sync_speed_min = 0;
4307                 return len;
4308         }
4309         min = simple_strtoul(buf, &e, 10);
4310         if (buf == e || (*e && *e != '\n') || min <= 0)
4311                 return -EINVAL;
4312         mddev->sync_speed_min = min;
4313         return len;
4314 }
4315 
4316 static struct md_sysfs_entry md_sync_min =
4317 __ATTR(sync_speed_min, S_IRUGO|S_IWUSR, sync_min_show, sync_min_store);
4318 
4319 static ssize_t
4320 sync_max_show(struct mddev *mddev, char *page)
4321 {
4322         return sprintf(page, "%d (%s)\n", speed_max(mddev),
4323                        mddev->sync_speed_max ? "local": "system");
4324 }
4325 
4326 static ssize_t
4327 sync_max_store(struct mddev *mddev, const char *buf, size_t len)
4328 {
4329         int max;
4330         char *e;
4331         if (strncmp(buf, "system", 6)==0) {
4332                 mddev->sync_speed_max = 0;
4333                 return len;
4334         }
4335         max = simple_strtoul(buf, &e, 10);
4336         if (buf == e || (*e && *e != '\n') || max <= 0)
4337                 return -EINVAL;
4338         mddev->sync_speed_max = max;
4339         return len;
4340 }
4341 
4342 static struct md_sysfs_entry md_sync_max =
4343 __ATTR(sync_speed_max, S_IRUGO|S_IWUSR, sync_max_show, sync_max_store);
4344 
4345 static ssize_t
4346 degraded_show(struct mddev *mddev, char *page)
4347 {
4348         return sprintf(page, "%d\n", mddev->degraded);
4349 }
4350 static struct md_sysfs_entry md_degraded = __ATTR_RO(degraded);
4351 
4352 static ssize_t
4353 sync_force_parallel_show(struct mddev *mddev, char *page)
4354 {
4355         return sprintf(page, "%d\n", mddev->parallel_resync);
4356 }
4357 
4358 static ssize_t
4359 sync_force_parallel_store(struct mddev *mddev, const char *buf, size_t len)
4360 {
4361         long n;
4362 
4363         if (kstrtol(buf, 10, &n))
4364                 return -EINVAL;
4365 
4366         if (n != 0 && n != 1)
4367                 return -EINVAL;
4368 
4369         mddev->parallel_resync = n;
4370 
4371         if (mddev->sync_thread)
4372                 wake_up(&resync_wait);
4373 
4374         return len;
4375 }
4376 
4377 /* force parallel resync, even with shared block devices */
4378 static struct md_sysfs_entry md_sync_force_parallel =
4379 __ATTR(sync_force_parallel, S_IRUGO|S_IWUSR,
4380        sync_force_parallel_show, sync_force_parallel_store);
4381 
4382 static ssize_t
4383 sync_speed_show(struct mddev *mddev, char *page)
4384 {
4385         unsigned long resync, dt, db;
4386         if (mddev->curr_resync == 0)
4387                 return sprintf(page, "none\n");
4388         resync = mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active);
4389         dt = (jiffies - mddev->resync_mark) / HZ;
4390         if (!dt) dt++;
4391         db = resync - mddev->resync_mark_cnt;
4392         return sprintf(page, "%lu\n", db/dt/2); /* K/sec */
4393 }
4394 
4395 static struct md_sysfs_entry md_sync_speed = __ATTR_RO(sync_speed);
4396 
4397 static ssize_t
4398 sync_completed_show(struct mddev *mddev, char *page)
4399 {
4400         unsigned long long max_sectors, resync;
4401 
4402         if (!test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4403                 return sprintf(page, "none\n");
4404 
4405         if (mddev->curr_resync == 1 ||
4406             mddev->curr_resync == 2)
4407                 return sprintf(page, "delayed\n");
4408 
4409         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ||
4410             test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
4411                 max_sectors = mddev->resync_max_sectors;
4412         else
4413                 max_sectors = mddev->dev_sectors;
4414 
4415         resync = mddev->curr_resync_completed;
4416         return sprintf(page, "%llu / %llu\n", resync, max_sectors);
4417 }
4418 
4419 static struct md_sysfs_entry md_sync_completed =
4420         __ATTR_PREALLOC(sync_completed, S_IRUGO, sync_completed_show, NULL);
4421 
4422 static ssize_t
4423 min_sync_show(struct mddev *mddev, char *page)
4424 {
4425         return sprintf(page, "%llu\n",
4426                        (unsigned long long)mddev->resync_min);
4427 }
4428 static ssize_t
4429 min_sync_store(struct mddev *mddev, const char *buf, size_t len)
4430 {
4431         unsigned long long min;
4432         int err;
4433 
4434         if (kstrtoull(buf, 10, &min))
4435                 return -EINVAL;
4436 
4437         spin_lock(&mddev->lock);
4438         err = -EINVAL;
4439         if (min > mddev->resync_max)
4440                 goto out_unlock;
4441 
4442         err = -EBUSY;
4443         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4444                 goto out_unlock;
4445 
4446         /* Round down to multiple of 4K for safety */
4447         mddev->resync_min = round_down(min, 8);
4448         err = 0;
4449 
4450 out_unlock:
4451         spin_unlock(&mddev->lock);
4452         return err ?: len;
4453 }
4454 
4455 static struct md_sysfs_entry md_min_sync =
4456 __ATTR(sync_min, S_IRUGO|S_IWUSR, min_sync_show, min_sync_store);
4457 
4458 static ssize_t
4459 max_sync_show(struct mddev *mddev, char *page)
4460 {
4461         if (mddev->resync_max == MaxSector)
4462                 return sprintf(page, "max\n");
4463         else
4464                 return sprintf(page, "%llu\n",
4465                                (unsigned long long)mddev->resync_max);
4466 }
4467 static ssize_t
4468 max_sync_store(struct mddev *mddev, const char *buf, size_t len)
4469 {
4470         int err;
4471         spin_lock(&mddev->lock);
4472         if (strncmp(buf, "max", 3) == 0)
4473                 mddev->resync_max = MaxSector;
4474         else {
4475                 unsigned long long max;
4476                 int chunk;
4477 
4478                 err = -EINVAL;
4479                 if (kstrtoull(buf, 10, &max))
4480                         goto out_unlock;
4481                 if (max < mddev->resync_min)
4482                         goto out_unlock;
4483 
4484                 err = -EBUSY;
4485                 if (max < mddev->resync_max &&
4486                     mddev->ro == 0 &&
4487                     test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4488                         goto out_unlock;
4489 
4490                 /* Must be a multiple of chunk_size */
4491                 chunk = mddev->chunk_sectors;
4492                 if (chunk) {
4493                         sector_t temp = max;
4494 
4495                         err = -EINVAL;
4496                         if (sector_div(temp, chunk))
4497                                 goto out_unlock;
4498                 }
4499                 mddev->resync_max = max;
4500         }
4501         wake_up(&mddev->recovery_wait);
4502         err = 0;
4503 out_unlock:
4504         spin_unlock(&mddev->lock);
4505         return err ?: len;
4506 }
4507 
4508 static struct md_sysfs_entry md_max_sync =
4509 __ATTR(sync_max, S_IRUGO|S_IWUSR, max_sync_show, max_sync_store);
4510 
4511 static ssize_t
4512 suspend_lo_show(struct mddev *mddev, char *page)
4513 {
4514         return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_lo);
4515 }
4516 
4517 static ssize_t
4518 suspend_lo_store(struct mddev *mddev, const char *buf, size_t len)
4519 {
4520         char *e;
4521         unsigned long long new = simple_strtoull(buf, &e, 10);
4522         unsigned long long old;
4523         int err;
4524 
4525         if (buf == e || (*e && *e != '\n'))
4526                 return -EINVAL;
4527 
4528         err = mddev_lock(mddev);
4529         if (err)
4530                 return err;
4531         err = -EINVAL;
4532         if (mddev->pers == NULL ||
4533             mddev->pers->quiesce == NULL)
4534                 goto unlock;
4535         old = mddev->suspend_lo;
4536         mddev->suspend_lo = new;
4537         if (new >= old)
4538                 /* Shrinking suspended region */
4539                 mddev->pers->quiesce(mddev, 2);
4540         else {
4541                 /* Expanding suspended region - need to wait */
4542                 mddev->pers->quiesce(mddev, 1);
4543                 mddev->pers->quiesce(mddev, 0);
4544         }
4545         err = 0;
4546 unlock:
4547         mddev_unlock(mddev);
4548         return err ?: len;
4549 }
4550 static struct md_sysfs_entry md_suspend_lo =
4551 __ATTR(suspend_lo, S_IRUGO|S_IWUSR, suspend_lo_show, suspend_lo_store);
4552 
4553 static ssize_t
4554 suspend_hi_show(struct mddev *mddev, char *page)
4555 {
4556         return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_hi);
4557 }
4558 
4559 static ssize_t
4560 suspend_hi_store(struct mddev *mddev, const char *buf, size_t len)
4561 {
4562         char *e;
4563         unsigned long long new = simple_strtoull(buf, &e, 10);
4564         unsigned long long old;
4565         int err;
4566 
4567         if (buf == e || (*e && *e != '\n'))
4568                 return -EINVAL;
4569 
4570         err = mddev_lock(mddev);
4571         if (err)
4572                 return err;
4573         err = -EINVAL;
4574         if (mddev->pers == NULL ||
4575             mddev->pers->quiesce == NULL)
4576                 goto unlock;
4577         old = mddev->suspend_hi;
4578         mddev->suspend_hi = new;
4579         if (new <= old)
4580                 /* Shrinking suspended region */
4581                 mddev->pers->quiesce(mddev, 2);
4582         else {
4583                 /* Expanding suspended region - need to wait */
4584                 mddev->pers->quiesce(mddev, 1);
4585                 mddev->pers->quiesce(mddev, 0);
4586         }
4587         err = 0;
4588 unlock:
4589         mddev_unlock(mddev);
4590         return err ?: len;
4591 }
4592 static struct md_sysfs_entry md_suspend_hi =
4593 __ATTR(suspend_hi, S_IRUGO|S_IWUSR, suspend_hi_show, suspend_hi_store);
4594 
4595 static ssize_t
4596 reshape_position_show(struct mddev *mddev, char *page)
4597 {
4598         if (mddev->reshape_position != MaxSector)
4599                 return sprintf(page, "%llu\n",
4600                                (unsigned long long)mddev->reshape_position);
4601         strcpy(page, "none\n");
4602         return 5;
4603 }
4604 
4605 static ssize_t
4606 reshape_position_store(struct mddev *mddev, const char *buf, size_t len)
4607 {
4608         struct md_rdev *rdev;
4609         char *e;
4610         int err;
4611         unsigned long long new = simple_strtoull(buf, &e, 10);
4612 
4613         if (buf == e || (*e && *e != '\n'))
4614                 return -EINVAL;
4615         err = mddev_lock(mddev);
4616         if (err)
4617                 return err;
4618         err = -EBUSY;
4619         if (mddev->pers)
4620                 goto unlock;
4621         mddev->reshape_position = new;
4622         mddev->delta_disks = 0;
4623         mddev->reshape_backwards = 0;
4624         mddev->new_level = mddev->level;
4625         mddev->new_layout = mddev->layout;
4626         mddev->new_chunk_sectors = mddev->chunk_sectors;
4627         rdev_for_each(rdev, mddev)
4628                 rdev->new_data_offset = rdev->data_offset;
4629         err = 0;
4630 unlock:
4631         mddev_unlock(mddev);
4632         return err ?: len;
4633 }
4634 
4635 static struct md_sysfs_entry md_reshape_position =
4636 __ATTR(reshape_position, S_IRUGO|S_IWUSR, reshape_position_show,
4637        reshape_position_store);
4638 
4639 static ssize_t
4640 reshape_direction_show(struct mddev *mddev, char *page)
4641 {
4642         return sprintf(page, "%s\n",
4643                        mddev->reshape_backwards ? "backwards" : "forwards");
4644 }
4645 
4646 static ssize_t
4647 reshape_direction_store(struct mddev *mddev, const char *buf, size_t len)
4648 {
4649         int backwards = 0;
4650         int err;
4651 
4652         if (cmd_match(buf, "forwards"))
4653                 backwards = 0;
4654         else if (cmd_match(buf, "backwards"))
4655                 backwards = 1;
4656         else
4657                 return -EINVAL;
4658         if (mddev->reshape_backwards == backwards)
4659                 return len;
4660 
4661         err = mddev_lock(mddev);
4662         if (err)
4663                 return err;
4664         /* check if we are allowed to change */
4665         if (mddev->delta_disks)
4666                 err = -EBUSY;
4667         else if (mddev->persistent &&
4668             mddev->major_version == 0)
4669                 err =  -EINVAL;
4670         else
4671                 mddev->reshape_backwards = backwards;
4672         mddev_unlock(mddev);
4673         return err ?: len;
4674 }
4675 
4676 static struct md_sysfs_entry md_reshape_direction =
4677 __ATTR(reshape_direction, S_IRUGO|S_IWUSR, reshape_direction_show,
4678        reshape_direction_store);
4679 
4680 static ssize_t
4681 array_size_show(struct mddev *mddev, char *page)
4682 {
4683         if (mddev->external_size)
4684                 return sprintf(page, "%llu\n",
4685                                (unsigned long long)mddev->array_sectors/2);
4686         else
4687                 return sprintf(page, "default\n");
4688 }
4689 
4690 static ssize_t
4691 array_size_store(struct mddev *mddev, const char *buf, size_t len)
4692 {
4693         sector_t sectors;
4694         int err;
4695 
4696         err = mddev_lock(mddev);
4697         if (err)
4698                 return err;
4699 
4700         if (strncmp(buf, "default", 7) == 0) {
4701                 if (mddev->pers)
4702                         sectors = mddev->pers->size(mddev, 0, 0);
4703                 else
4704                         sectors = mddev->array_sectors;
4705 
4706                 mddev->external_size = 0;
4707         } else {
4708                 if (strict_blocks_to_sectors(buf, &sectors) < 0)
4709                         err = -EINVAL;
4710                 else if (mddev->pers && mddev->pers->size(mddev, 0, 0) < sectors)
4711                         err = -E2BIG;
4712                 else
4713                         mddev->external_size = 1;
4714         }
4715 
4716         if (!err) {
4717                 mddev->array_sectors = sectors;
4718                 if (mddev->pers) {
4719                         set_capacity(mddev->gendisk, mddev->array_sectors);
4720                         revalidate_disk(mddev->gendisk);
4721                 }
4722         }
4723         mddev_unlock(mddev);
4724         return err ?: len;
4725 }
4726 
4727 static struct md_sysfs_entry md_array_size =
4728 __ATTR(array_size, S_IRUGO|S_IWUSR, array_size_show,
4729        array_size_store);
4730 
4731 static struct attribute *md_default_attrs[] = {
4732         &md_level.attr,
4733         &md_layout.attr,
4734         &md_raid_disks.attr,
4735         &md_chunk_size.attr,
4736         &md_size.attr,
4737         &md_resync_start.attr,
4738         &md_metadata.attr,
4739         &md_new_device.attr,
4740         &md_safe_delay.attr,
4741         &md_array_state.attr,
4742         &md_reshape_position.attr,
4743         &md_reshape_direction.attr,
4744         &md_array_size.attr,
4745         &max_corr_read_errors.attr,
4746         NULL,
4747 };
4748 
4749 static struct attribute *md_redundancy_attrs[] = {
4750         &md_scan_mode.attr,
4751         &md_last_scan_mode.attr,
4752         &md_mismatches.attr,
4753         &md_sync_min.attr,
4754         &md_sync_max.attr,
4755         &md_sync_speed.attr,
4756         &md_sync_force_parallel.attr,
4757         &md_sync_completed.attr,
4758         &md_min_sync.attr,
4759         &md_max_sync.attr,
4760         &md_suspend_lo.attr,
4761         &md_suspend_hi.attr,
4762         &md_bitmap.attr,
4763         &md_degraded.attr,
4764         NULL,
4765 };
4766 static struct attribute_group md_redundancy_group = {
4767         .name = NULL,
4768         .attrs = md_redundancy_attrs,
4769 };
4770 
4771 static ssize_t
4772 md_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
4773 {
4774         struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
4775         struct mddev *mddev = container_of(kobj, struct mddev, kobj);
4776         ssize_t rv;
4777 
4778         if (!entry->show)
4779                 return -EIO;
4780         spin_lock(&all_mddevs_lock);
4781         if (list_empty(&mddev->all_mddevs)) {
4782                 spin_unlock(&all_mddevs_lock);
4783                 return -EBUSY;
4784         }
4785         mddev_get(mddev);
4786         spin_unlock(&all_mddevs_lock);
4787 
4788         rv = entry->show(mddev, page);
4789         mddev_put(mddev);
4790         return rv;
4791 }
4792 
4793 static ssize_t
4794 md_attr_store(struct kobject *kobj, struct attribute *attr,
4795               const char *page, size_t length)
4796 {
4797         struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
4798         struct mddev *mddev = container_of(kobj, struct mddev, kobj);
4799         ssize_t rv;
4800 
4801         if (!entry->store)
4802                 return -EIO;
4803         if (!capable(CAP_SYS_ADMIN))
4804                 return -EACCES;
4805         spin_lock(&all_mddevs_lock);
4806         if (list_empty(&mddev->all_mddevs)) {
4807                 spin_unlock(&all_mddevs_lock);
4808                 return -EBUSY;
4809         }
4810         mddev_get(mddev);
4811         spin_unlock(&all_mddevs_lock);
4812         rv = entry->store(mddev, page, length);
4813         mddev_put(mddev);
4814         return rv;
4815 }
4816 
4817 static void md_free(struct kobject *ko)
4818 {
4819         struct mddev *mddev = container_of(ko, struct mddev, kobj);
4820 
4821         if (mddev->sysfs_state)
4822                 sysfs_put(mddev->sysfs_state);
4823 
4824         if (mddev->queue)
4825                 blk_cleanup_queue(mddev->queue);
4826         if (mddev->gendisk) {
4827                 del_gendisk(mddev->gendisk);
4828                 put_disk(mddev->gendisk);
4829         }
4830 
4831         kfree(mddev);
4832 }
4833 
4834 static const struct sysfs_ops md_sysfs_ops = {
4835         .show   = md_attr_show,
4836         .store  = md_attr_store,
4837 };
4838 static struct kobj_type md_ktype = {
4839         .release        = md_free,
4840         .sysfs_ops      = &md_sysfs_ops,
4841         .default_attrs  = md_default_attrs,
4842 };
4843 
4844 int mdp_major = 0;
4845 
4846 static void mddev_delayed_delete(struct work_struct *ws)
4847 {
4848         struct mddev *mddev = container_of(ws, struct mddev, del_work);
4849 
4850         sysfs_remove_group(&mddev->kobj, &md_bitmap_group);
4851         kobject_del(&mddev->kobj);
4852         kobject_put(&mddev->kobj);
4853 }
4854 
4855 static int md_alloc(dev_t dev, char *name)
4856 {
4857         static DEFINE_MUTEX(disks_mutex);
4858         struct mddev *mddev = mddev_find(dev);
4859         struct gendisk *disk;
4860         int partitioned;
4861         int shift;
4862         int unit;
4863         int error;
4864 
4865         if (!mddev)
4866                 return -ENODEV;
4867 
4868         partitioned = (MAJOR(mddev->unit) != MD_MAJOR);
4869         shift = partitioned ? MdpMinorShift : 0;
4870         unit = MINOR(mddev->unit) >> shift;
4871 
4872         /* wait for any previous instance of this device to be
4873          * completely removed (mddev_delayed_delete).
4874          */
4875         flush_workqueue(md_misc_wq);
4876 
4877         mutex_lock(&disks_mutex);
4878         error = -EEXIST;
4879         if (mddev->gendisk)
4880                 goto abort;
4881 
4882         if (name) {
4883                 /* Need to ensure that 'name' is not a duplicate.
4884                  */
4885                 struct mddev *mddev2;
4886                 spin_lock(&all_mddevs_lock);
4887 
4888                 list_for_each_entry(mddev2, &all_mddevs, all_mddevs)
4889                         if (mddev2->gendisk &&
4890                             strcmp(mddev2->gendisk->disk_name, name) == 0) {
4891                                 spin_unlock(&all_mddevs_lock);
4892                                 goto abort;
4893                         }
4894                 spin_unlock(&all_mddevs_lock);
4895         }
4896 
4897         error = -ENOMEM;
4898         mddev->queue = blk_alloc_queue(GFP_KERNEL);
4899         if (!mddev->queue)
4900                 goto abort;
4901         mddev->queue->queuedata = mddev;
4902 
4903         blk_queue_make_request(mddev->queue, md_make_request);
4904         blk_set_stacking_limits(&mddev->queue->limits);
4905 
4906         disk = alloc_disk(1 << shift);
4907         if (!disk) {
4908                 blk_cleanup_queue(mddev->queue);
4909                 mddev->queue = NULL;
4910                 goto abort;
4911         }
4912         disk->major = MAJOR(mddev->unit);
4913         disk->first_minor = unit << shift;
4914         if (name)
4915                 strcpy(disk->disk_name, name);
4916         else if (partitioned)
4917                 sprintf(disk->disk_name, "md_d%d", unit);
4918         else
4919                 sprintf(disk->disk_name, "md%d", unit);
4920         disk->fops = &md_fops;
4921         disk->private_data = mddev;
4922         disk->queue = mddev->queue;
4923         blk_queue_flush(mddev->queue, REQ_FLUSH | REQ_FUA);
4924         /* Allow extended partitions.  This makes the
4925          * 'mdp' device redundant, but we can't really
4926          * remove it now.
4927          */
4928         disk->flags |= GENHD_FL_EXT_DEVT;
4929         mddev->gendisk = disk;
4930         /* As soon as we call add_disk(), another thread could get
4931          * through to md_open, so make sure it doesn't get too far
4932          */
4933         mutex_lock(&mddev->open_mutex);
4934         add_disk(disk);
4935 
4936         error = kobject_init_and_add(&mddev->kobj, &md_ktype,
4937                                      &disk_to_dev(disk)->kobj, "%s", "md");
4938         if (error) {
4939                 /* This isn't possible, but as kobject_init_and_add is marked
4940                  * __must_check, we must do something with the result
4941                  */
4942                 printk(KERN_WARNING "md: cannot register %s/md - name in use\n",
4943                        disk->disk_name);
4944                 error = 0;
4945         }
4946         if (mddev->kobj.sd &&
4947             sysfs_create_group(&mddev->kobj, &md_bitmap_group))
4948                 printk(KERN_DEBUG "pointless warning\n");
4949         mutex_unlock(&mddev->open_mutex);
4950  abort:
4951         mutex_unlock(&disks_mutex);
4952         if (!error && mddev->kobj.sd) {
4953                 kobject_uevent(&mddev->kobj, KOBJ_ADD);
4954                 mddev->sysfs_state = sysfs_get_dirent_safe(mddev->kobj.sd, "array_state");
4955         }
4956         mddev_put(mddev);
4957         return error;
4958 }
4959 
4960 static struct kobject *md_probe(dev_t dev, int *part, void *data)
4961 {
4962         md_alloc(dev, NULL);
4963         return NULL;
4964 }
4965 
4966 static int add_named_array(const char *val, struct kernel_param *kp)
4967 {
4968         /* val must be "md_*" where * is not all digits.
4969          * We allocate an array with a large free minor number, and
4970          * set the name to val.  val must not already be an active name.
4971          */
4972         int len = strlen(val);
4973         char buf[DISK_NAME_LEN];
4974 
4975         while (len && val[len-1] == '\n')
4976                 len--;
4977         if (len >= DISK_NAME_LEN)
4978                 return -E2BIG;
4979         strlcpy(buf, val, len+1);
4980         if (strncmp(buf, "md_", 3) != 0)
4981                 return -EINVAL;
4982         return md_alloc(0, buf);
4983 }
4984 
4985 static void md_safemode_timeout(unsigned long data)
4986 {
4987         struct mddev *mddev = (struct mddev *) data;
4988 
4989         if (!atomic_read(&mddev->writes_pending)) {
4990                 mddev->safemode = 1;
4991                 if (mddev->external)
4992                         sysfs_notify_dirent_safe(mddev->sysfs_state);
4993         }
4994         md_wakeup_thread(mddev->thread);
4995 }
4996 
4997 static int start_dirty_degraded;
4998 
4999 int md_run(struct mddev *mddev)
5000 {
5001         int err;
5002         struct md_rdev *rdev;
5003         struct md_personality *pers;
5004 
5005         if (list_empty(&mddev->disks))
5006                 /* cannot run an array with no devices.. */
5007                 return -EINVAL;
5008 
5009         if (mddev->pers)
5010                 return -EBUSY;
5011         /* Cannot run until previous stop completes properly */
5012         if (mddev->sysfs_active)
5013                 return -EBUSY;
5014 
5015         /*
5016          * Analyze all RAID superblock(s)
5017          */
5018         if (!mddev->raid_disks) {
5019                 if (!mddev->persistent)
5020                         return -EINVAL;
5021                 analyze_sbs(mddev);
5022         }
5023 
5024         if (mddev->level != LEVEL_NONE)
5025                 request_module("md-level-%d", mddev->level);
5026         else if (mddev->clevel[0])
5027                 request_module("md-%s", mddev->clevel);
5028 
5029         /*
5030          * Drop all container device buffers, from now on
5031          * the only valid external interface is through the md
5032          * device.
5033          */
5034         rdev_for_each(rdev, mddev) {
5035                 if (test_bit(Faulty, &rdev->flags))
5036                         continue;
5037                 sync_blockdev(rdev->bdev);
5038                 invalidate_bdev(rdev->bdev);
5039 
5040                 /* perform some consistency tests on the device.
5041                  * We don't want the data to overlap the metadata,
5042                  * Internal Bitmap issues have been handled elsewhere.
5043                  */
5044                 if (rdev->meta_bdev) {
5045                         /* Nothing to check */;
5046                 } else if (rdev->data_offset < rdev->sb_start) {
5047                         if (mddev->dev_sectors &&
5048                             rdev->data_offset + mddev->dev_sectors
5049                             > rdev->sb_start) {
5050                                 printk("md: %s: data overlaps metadata\n",
5051                                        mdname(mddev));
5052                                 return -EINVAL;
5053                         }
5054                 } else {
5055                         if (rdev->sb_start + rdev->sb_size/512
5056                             > rdev->data_offset) {
5057                                 printk("md: %s: metadata overlaps data\n",
5058                                        mdname(mddev));
5059                                 return -EINVAL;
5060                         }
5061                 }
5062                 sysfs_notify_dirent_safe(rdev->sysfs_state);
5063         }
5064 
5065         if (mddev->bio_set == NULL)
5066                 mddev->bio_set = bioset_create(BIO_POOL_SIZE, 0);
5067 
5068         spin_lock(&pers_lock);
5069         pers = find_pers(mddev->level, mddev->clevel);
5070         if (!pers || !try_module_get(pers->owner)) {
5071                 spin_unlock(&pers_lock);
5072                 if (mddev->level != LEVEL_NONE)
5073                         printk(KERN_WARNING "md: personality for level %d is not loaded!\n",
5074                                mddev->level);
5075                 else
5076                         printk(KERN_WARNING "md: personality for level %s is not loaded!\n",
5077                                mddev->clevel);
5078                 return -EINVAL;
5079         }
5080         spin_unlock(&pers_lock);
5081         if (mddev->level != pers->level) {
5082                 mddev->level = pers->level;
5083                 mddev->new_level = pers->level;
5084         }
5085         strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
5086 
5087         if (mddev->reshape_position != MaxSector &&
5088             pers->start_reshape == NULL) {
5089                 /* This personality cannot handle reshaping... */
5090                 module_put(pers->owner);
5091                 return -EINVAL;
5092         }
5093 
5094         if (pers->sync_request) {
5095                 /* Warn if this is a potentially silly
5096                  * configuration.
5097                  */
5098                 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
5099                 struct md_rdev *rdev2;
5100                 int warned = 0;
5101 
5102                 rdev_for_each(rdev, mddev)
5103                         rdev_for_each(rdev2, mddev) {
5104                                 if (rdev < rdev2 &&
5105                                     rdev->bdev->bd_contains ==
5106                                     rdev2->bdev->bd_contains) {
5107                                         printk(KERN_WARNING
5108                                                "%s: WARNING: %s appears to be"
5109                                                " on the same physical disk as"
5110                                                " %s.\n",
5111                                                mdname(mddev),
5112                                                bdevname(rdev->bdev,b),
5113                                                bdevname(rdev2->bdev,b2));
5114                                         warned = 1;
5115                                 }
5116                         }
5117 
5118                 if (warned)
5119                         printk(KERN_WARNING
5120                                "True protection against single-disk"
5121                                " failure might be compromised.\n");
5122         }
5123 
5124         mddev->recovery = 0;
5125         /* may be over-ridden by personality */
5126         mddev->resync_max_sectors = mddev->dev_sectors;
5127 
5128         mddev->ok_start_degraded = start_dirty_degraded;
5129 
5130         if (start_readonly && mddev->ro == 0)
5131                 mddev->ro = 2; /* read-only, but switch on first write */
5132 
5133         err = pers->run(mddev);
5134         if (err)
5135                 printk(KERN_ERR "md: pers->run() failed ...\n");
5136         else if (pers->size(mddev, 0, 0) < mddev->array_sectors) {
5137                 WARN_ONCE(!mddev->external_size, "%s: default size too small,"
5138                           " but 'external_size' not in effect?\n", __func__);
5139                 printk(KERN_ERR
5140                        "md: invalid array_size %llu > default size %llu\n",
5141                        (unsigned long long)mddev->array_sectors / 2,
5142                        (unsigned long long)pers->size(mddev, 0, 0) / 2);
5143                 err = -EINVAL;
5144         }
5145         if (err == 0 && pers->sync_request &&
5146             (mddev->bitmap_info.file || mddev->bitmap_info.offset)) {
5147                 struct bitmap *bitmap;
5148 
5149                 bitmap = bitmap_create(mddev, -1);
5150                 if (IS_ERR(bitmap)) {
5151                         err = PTR_ERR(bitmap);
5152                         printk(KERN_ERR "%s: failed to create bitmap (%d)\n",
5153                                mdname(mddev), err);
5154                 } else
5155                         mddev->bitmap = bitmap;
5156 
5157         }
5158         if (err) {
5159                 mddev_detach(mddev);
5160                 if (mddev->private)
5161                         pers->free(mddev, mddev->private);
5162                 module_put(pers->owner);
5163                 bitmap_destroy(mddev);
5164                 return err;
5165         }
5166         if (mddev->queue) {
5167                 mddev->queue->backing_dev_info.congested_data = mddev;
5168                 mddev->queue->backing_dev_info.congested_fn = md_congested;
5169                 blk_queue_merge_bvec(mddev->queue, md_mergeable_bvec);
5170         }
5171         if (pers->sync_request) {
5172                 if (mddev->kobj.sd &&
5173                     sysfs_create_group(&mddev->kobj, &md_redundancy_group))
5174                         printk(KERN_WARNING
5175                                "md: cannot register extra attributes for %s\n",
5176                                mdname(mddev));
5177                 mddev->sysfs_action = sysfs_get_dirent_safe(mddev->kobj.sd, "sync_action");
5178         } else if (mddev->ro == 2) /* auto-readonly not meaningful */
5179                 mddev->ro = 0;
5180 
5181         atomic_set(&mddev->writes_pending,0);
5182         atomic_set(&mddev->max_corr_read_errors,
5183                    MD_DEFAULT_MAX_CORRECTED_READ_ERRORS);
5184         mddev->safemode = 0;
5185         mddev->safemode_timer.function = md_safemode_timeout;
5186         mddev->safemode_timer.data = (unsigned long) mddev;
5187         mddev->safemode_delay = (200 * HZ)/1000 +1; /* 200 msec delay */
5188         mddev->in_sync = 1;
5189         smp_wmb();
5190         spin_lock(&mddev->lock);
5191         mddev->pers = pers;
5192         mddev->ready = 1;
5193         spin_unlock(&mddev->lock);
5194         rdev_for_each(rdev, mddev)
5195                 if (rdev->raid_disk >= 0)
5196                         if (sysfs_link_rdev(mddev, rdev))
5197                                 /* failure here is OK */;
5198 
5199         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5200 
5201         if (mddev->flags & MD_UPDATE_SB_FLAGS)
5202                 md_update_sb(mddev, 0);
5203 
5204         md_new_event(mddev);
5205         sysfs_notify_dirent_safe(mddev->sysfs_state);
5206         sysfs_notify_dirent_safe(mddev->sysfs_action);
5207         sysfs_notify(&mddev->kobj, NULL, "degraded");
5208         return 0;
5209 }
5210 EXPORT_SYMBOL_GPL(md_run);
5211 
5212 static int do_md_run(struct mddev *mddev)
5213 {
5214         int err;
5215 
5216         err = md_run(mddev);
5217         if (err)
5218                 goto out;
5219         err = bitmap_load(mddev);
5220         if (err) {
5221                 bitmap_destroy(mddev);
5222                 goto out;
5223         }
5224 
5225         md_wakeup_thread(mddev->thread);
5226         md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
5227 
5228         set_capacity(mddev->gendisk, mddev->array_sectors);
5229         revalidate_disk(mddev->gendisk);
5230         mddev->changed = 1;
5231         kobject_uevent(&disk_to_dev(mddev->gendisk)->kobj, KOBJ_CHANGE);
5232 out:
5233         return err;
5234 }
5235 
5236 static int restart_array(struct mddev *mddev)
5237 {
5238         struct gendisk *disk = mddev->gendisk;
5239 
5240         /* Complain if it has no devices */
5241         if (list_empty(&mddev->disks))
5242                 return -ENXIO;
5243         if (!mddev->pers)
5244                 return -EINVAL;
5245         if (!mddev->ro)
5246                 return -EBUSY;
5247         mddev->safemode = 0;
5248         mddev->ro = 0;
5249         set_disk_ro(disk, 0);
5250         printk(KERN_INFO "md: %s switched to read-write mode.\n",
5251                 mdname(mddev));
5252         /* Kick recovery or resync if necessary */
5253         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5254         md_wakeup_thread(mddev->thread);
5255         md_wakeup_thread(mddev->sync_thread);
5256         sysfs_notify_dirent_safe(mddev->sysfs_state);
5257         return 0;
5258 }
5259 
5260 static void md_clean(struct mddev *mddev)
5261 {
5262         mddev->array_sectors = 0;
5263         mddev->external_size = 0;
5264         mddev->dev_sectors = 0;
5265         mddev->raid_disks = 0;
5266         mddev->recovery_cp = 0;
5267         mddev->resync_min = 0;
5268         mddev->resync_max = MaxSector;
5269         mddev->reshape_position = MaxSector;
5270         mddev->external = 0;
5271         mddev->persistent = 0;
5272         mddev->level = LEVEL_NONE;
5273         mddev->clevel[0] = 0;
5274         mddev->flags = 0;
5275         mddev->ro = 0;
5276         mddev->metadata_type[0] = 0;
5277         mddev->chunk_sectors = 0;
5278         mddev->ctime = mddev->utime = 0;
5279         mddev->layout = 0;
5280         mddev->max_disks = 0;
5281         mddev->events = 0;
5282         mddev->can_decrease_events = 0;
5283         mddev->delta_disks = 0;
5284         mddev->reshape_backwards = 0;
5285         mddev->new_level = LEVEL_NONE;
5286         mddev->new_layout = 0;
5287         mddev->new_chunk_sectors = 0;
5288         mddev->curr_resync = 0;
5289         atomic64_set(&mddev->resync_mismatches, 0);
5290         mddev->suspend_lo = mddev->suspend_hi = 0;
5291         mddev->sync_speed_min = mddev->sync_speed_max = 0;
5292         mddev->recovery = 0;
5293         mddev->in_sync = 0;
5294         mddev->changed = 0;
5295         mddev->degraded = 0;
5296         mddev->safemode = 0;
5297         mddev->merge_check_needed = 0;
5298         mddev->bitmap_info.offset = 0;
5299         mddev->bitmap_info.default_offset = 0;
5300         mddev->bitmap_info.default_space = 0;
5301         mddev->bitmap_info.chunksize = 0;
5302         mddev->bitmap_info.daemon_sleep = 0;
5303         mddev->bitmap_info.max_write_behind = 0;
5304 }
5305 
5306 static void __md_stop_writes(struct mddev *mddev)
5307 {
5308         if (mddev_is_clustered(mddev))
5309                 md_cluster_ops->metadata_update_start(mddev);
5310         set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5311         flush_workqueue(md_misc_wq);
5312         if (mddev->sync_thread) {
5313                 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5314                 md_reap_sync_thread(mddev);
5315         }
5316 
5317         del_timer_sync(&mddev->safemode_timer);
5318 
5319         bitmap_flush(mddev);
5320         md_super_wait(mddev);
5321 
5322         if (mddev->ro == 0 &&
5323             (!mddev->in_sync || (mddev->flags & MD_UPDATE_SB_FLAGS))) {
5324                 /* mark array as shutdown cleanly */
5325                 mddev->in_sync = 1;
5326                 md_update_sb(mddev, 1);
5327         }
5328         if (mddev_is_clustered(mddev))
5329                 md_cluster_ops->metadata_update_finish(mddev);
5330 }
5331 
5332 void md_stop_writes(struct mddev *mddev)
5333 {
5334         mddev_lock_nointr(mddev);
5335         __md_stop_writes(mddev);
5336         mddev_unlock(mddev);
5337 }
5338 EXPORT_SYMBOL_GPL(md_stop_writes);
5339 
5340 static void mddev_detach(struct mddev *mddev)
5341 {
5342         struct bitmap *bitmap = mddev->bitmap;
5343         /* wait for behind writes to complete */
5344         if (bitmap && atomic_read(&bitmap->behind_writes) > 0) {
5345                 printk(KERN_INFO "md:%s: behind writes in progress - waiting to stop.\n",
5346                        mdname(mddev));
5347                 /* need to kick something here to make sure I/O goes? */
5348                 wait_event(bitmap->behind_wait,
5349                            atomic_read(&bitmap->behind_writes) == 0);
5350         }
5351         if (mddev->pers && mddev->pers->quiesce) {
5352                 mddev->pers->quiesce(mddev, 1);
5353                 mddev->pers->quiesce(mddev, 0);
5354         }
5355         md_unregister_thread(&mddev->thread);
5356         if (mddev->queue)
5357                 blk_sync_queue(mddev->queue); /* the unplug fn references 'conf'*/
5358 }
5359 
5360 static void __md_stop(struct mddev *mddev)
5361 {
5362         struct md_personality *pers = mddev->pers;
5363         mddev_detach(mddev);
5364         spin_lock(&mddev->lock);
5365         mddev->ready = 0;
5366         mddev->pers = NULL;
5367         spin_unlock(&mddev->lock);
5368         pers->free(mddev, mddev->private);
5369         if (pers->sync_request && mddev->to_remove == NULL)
5370                 mddev->to_remove = &md_redundancy_group;
5371         module_put(pers->owner);
5372         clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5373 }
5374 
5375 void md_stop(struct mddev *mddev)
5376 {
5377         /* stop the array and free an attached data structures.
5378          * This is called from dm-raid
5379          */
5380         __md_stop(mddev);
5381         bitmap_destroy(mddev);
5382         if (mddev->bio_set)
5383                 bioset_free(mddev->bio_set);
5384 }
5385 
5386 EXPORT_SYMBOL_GPL(md_stop);
5387 
5388 static int md_set_readonly(struct mddev *mddev, struct block_device *bdev)
5389 {
5390         int err = 0;
5391         int did_freeze = 0;
5392 
5393         if (!test_bit(MD_RECOVERY_FROZEN, &mddev->recovery)) {
5394                 did_freeze = 1;
5395                 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5396                 md_wakeup_thread(mddev->thread);
5397         }
5398         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
5399                 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5400         if (mddev->sync_thread)
5401                 /* Thread might be blocked waiting for metadata update
5402                  * which will now never happen */
5403                 wake_up_process(mddev->sync_thread->tsk);
5404 
5405         mddev_unlock(mddev);
5406         wait_event(resync_wait, !test_bit(MD_RECOVERY_RUNNING,
5407                                           &mddev->recovery));
5408         mddev_lock_nointr(mddev);
5409 
5410         mutex_lock(&mddev->open_mutex);
5411         if ((mddev->pers && atomic_read(&mddev->openers) > !!bdev) ||
5412             mddev->sync_thread ||
5413             test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
5414             (bdev && !test_bit(MD_STILL_CLOSED, &mddev->flags))) {
5415                 printk("md: %s still in use.\n",mdname(mddev));
5416                 if (did_freeze) {
5417                         clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5418                         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5419                         md_wakeup_thread(mddev->thread);
5420                 }
5421                 err = -EBUSY;
5422                 goto out;
5423         }
5424         if (mddev->pers) {
5425                 __md_stop_writes(mddev);
5426 
5427                 err  = -ENXIO;
5428                 if (mddev->ro==1)
5429                         goto out;
5430                 mddev->ro = 1;
5431                 set_disk_ro(mddev->gendisk, 1);
5432                 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5433                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5434                 md_wakeup_thread(mddev->thread);
5435                 sysfs_notify_dirent_safe(mddev->sysfs_state);
5436                 err = 0;
5437         }
5438 out:
5439         mutex_unlock(&mddev->open_mutex);
5440         return err;
5441 }
5442 
5443 /* mode:
5444  *   0 - completely stop and dis-assemble array
5445  *   2 - stop but do not disassemble array
5446  */
5447 static int do_md_stop(struct mddev *mddev, int mode,
5448                       struct block_device *bdev)
5449 {
5450         struct gendisk *disk = mddev->gendisk;
5451         struct md_rdev *rdev;
5452         int did_freeze = 0;
5453 
5454         if (!test_bit(MD_RECOVERY_FROZEN, &mddev->recovery)) {
5455                 did_freeze = 1;
5456                 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5457                 md_wakeup_thread(mddev->thread);
5458         }
5459         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
5460                 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5461         if (mddev->sync_thread)
5462                 /* Thread might be blocked waiting for metadata update
5463                  * which will now never happen */
5464                 wake_up_process(mddev->sync_thread->tsk);
5465 
5466         mddev_unlock(mddev);
5467         wait_event(resync_wait, (mddev->sync_thread == NULL &&
5468                                  !test_bit(MD_RECOVERY_RUNNING,
5469                                            &mddev->recovery)));
5470         mddev_lock_nointr(mddev);
5471 
5472         mutex_lock(&mddev->open_mutex);
5473         if ((mddev->pers && atomic_read(&mddev->openers) > !!bdev) ||
5474             mddev->sysfs_active ||
5475             mddev->sync_thread ||
5476             test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
5477             (bdev && !test_bit(MD_STILL_CLOSED, &mddev->flags))) {
5478                 printk("md: %s still in use.\n",mdname(mddev));
5479                 mutex_unlock(&mddev->open_mutex);
5480                 if (did_freeze) {
5481                         clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5482                         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5483                         md_wakeup_thread(mddev->thread);
5484                 }
5485                 return -EBUSY;
5486         }
5487         if (mddev->pers) {
5488                 if (mddev->ro)
5489                         set_disk_ro(disk, 0);
5490 
5491                 __md_stop_writes(mddev);
5492                 __md_stop(mddev);
5493                 mddev->queue->merge_bvec_fn = NULL;
5494                 mddev->queue->backing_dev_info.congested_fn = NULL;
5495 
5496                 /* tell userspace to handle 'inactive' */
5497                 sysfs_notify_dirent_safe(mddev->sysfs_state);
5498 
5499                 rdev_for_each(rdev, mddev)
5500                         if (rdev->raid_disk >= 0)
5501                                 sysfs_unlink_rdev(mddev, rdev);
5502 
5503                 set_capacity(disk, 0);
5504                 mutex_unlock(&mddev->open_mutex);
5505                 mddev->changed = 1;
5506                 revalidate_disk(disk);
5507 
5508                 if (mddev->ro)
5509                         mddev->ro = 0;
5510         } else
5511                 mutex_unlock(&mddev->open_mutex);
5512         /*
5513          * Free resources if final stop
5514          */
5515         if (mode == 0) {
5516                 printk(KERN_INFO "md: %s stopped.\n", mdname(mddev));
5517 
5518                 bitmap_destroy(mddev);
5519                 if (mddev->bitmap_info.file) {
5520                         struct file *f = mddev->bitmap_info.file;
5521                         spin_lock(&mddev->lock);
5522                         mddev->bitmap_info.file = NULL;
5523                         spin_unlock(&mddev->lock);
5524                         fput(f);
5525                 }
5526                 mddev->bitmap_info.offset = 0;
5527 
5528                 export_array(mddev);
5529 
5530                 md_clean(mddev);
5531                 kobject_uevent(&disk_to_dev(mddev->gendisk)->kobj, KOBJ_CHANGE);
5532                 if (mddev->hold_active == UNTIL_STOP)
5533                         mddev->hold_active = 0;
5534         }
5535         blk_integrity_unregister(disk);
5536         md_new_event(mddev);
5537         sysfs_notify_dirent_safe(mddev->sysfs_state);
5538         return 0;
5539 }
5540 
5541 #ifndef MODULE
5542 static void autorun_array(struct mddev *mddev)
5543 {
5544         struct md_rdev *rdev;
5545         int err;
5546 
5547         if (list_empty(&mddev->disks))
5548                 return;
5549 
5550         printk(KERN_INFO "md: running: ");
5551 
5552         rdev_for_each(rdev, mddev) {
5553                 char b[BDEVNAME_SIZE];
5554                 printk("<%s>", bdevname(rdev->bdev,b));
5555         }
5556         printk("\n");
5557 
5558         err = do_md_run(mddev);
5559         if (err) {
5560                 printk(KERN_WARNING "md: do_md_run() returned %d\n", err);
5561                 do_md_stop(mddev, 0, NULL);
5562         }
5563 }
5564 
5565 /*
5566  * lets try to run arrays based on all disks that have arrived
5567  * until now. (those are in pending_raid_disks)
5568  *
5569  * the method: pick the first pending disk, collect all disks with
5570  * the same UUID, remove all from the pending list and put them into
5571  * the 'same_array' list. Then order this list based on superblock
5572  * update time (freshest comes first), kick out 'old' disks and
5573  * compare superblocks. If everything's fine then run it.
5574  *
5575  * If "unit" is allocated, then bump its reference count
5576  */
5577 static void autorun_devices(int part)
5578 {
5579         struct md_rdev *rdev0, *rdev, *tmp;
5580         struct mddev *mddev;
5581         char b[BDEVNAME_SIZE];
5582 
5583         printk(KERN_INFO "md: autorun ...\n");
5584         while (!list_empty(&pending_raid_disks)) {
5585                 int unit;
5586                 dev_t dev;
5587                 LIST_HEAD(candidates);
5588                 rdev0 = list_entry(pending_raid_disks.next,
5589                                          struct md_rdev, same_set);
5590 
5591                 printk(KERN_INFO "md: considering %s ...\n",
5592                         bdevname(rdev0->bdev,b));
5593                 INIT_LIST_HEAD(&candidates);
5594                 rdev_for_each_list(rdev, tmp, &pending_raid_disks)
5595                         if (super_90_load(rdev, rdev0, 0) >= 0) {
5596                                 printk(KERN_INFO "md:  adding %s ...\n",
5597                                         bdevname(rdev->bdev,b));
5598                                 list_move(&rdev->same_set, &candidates);
5599                         }
5600                 /*
5601                  * now we have a set of devices, with all of them having
5602                  * mostly sane superblocks. It's time to allocate the
5603                  * mddev.
5604                  */
5605                 if (part) {
5606                         dev = MKDEV(mdp_major,
5607                                     rdev0->preferred_minor << MdpMinorShift);
5608                         unit = MINOR(dev) >> MdpMinorShift;
5609                 } else {
5610                         dev = MKDEV(MD_MAJOR, rdev0->preferred_minor);
5611                         unit = MINOR(dev);
5612                 }
5613                 if (rdev0->preferred_minor != unit) {
5614                         printk(KERN_INFO "md: unit number in %s is bad: %d\n",
5615                                bdevname(rdev0->bdev, b), rdev0->preferred_minor);
5616                         break;
5617                 }
5618 
5619                 md_probe(dev, NULL, NULL);
5620                 mddev = mddev_find(dev);
5621                 if (!mddev || !mddev->gendisk) {
5622                         if (mddev)
5623                                 mddev_put(mddev);
5624                         printk(KERN_ERR
5625                                 "md: cannot allocate memory for md drive.\n");
5626                         break;
5627                 }
5628                 if (mddev_lock(mddev))
5629                         printk(KERN_WARNING "md: %s locked, cannot run\n",
5630                                mdname(mddev));
5631                 else if (mddev->raid_disks || mddev->major_version
5632                          || !list_empty(&mddev->disks)) {
5633                         printk(KERN_WARNING
5634                                 "md: %s already running, cannot run %s\n",
5635                                 mdname(mddev), bdevname(rdev0->bdev,b));
5636                         mddev_unlock(mddev);
5637                 } else {
5638                         printk(KERN_INFO "md: created %s\n", mdname(mddev));
5639                         mddev->persistent = 1;
5640                         rdev_for_each_list(rdev, tmp, &candidates) {
5641                                 list_del_init(&rdev->same_set);
5642                                 if (bind_rdev_to_array(rdev, mddev))
5643                                         export_rdev(rdev);
5644                         }
5645                         autorun_array(mddev);
5646                         mddev_unlock(mddev);
5647                 }
5648                 /* on success, candidates will be empty, on error
5649                  * it won't...
5650                  */
5651                 rdev_for_each_list(rdev, tmp, &candidates) {
5652                         list_del_init(&rdev->same_set);
5653                         export_rdev(rdev);
5654                 }
5655                 mddev_put(mddev);
5656         }
5657         printk(KERN_INFO "md: ... autorun DONE.\n");
5658 }
5659 #endif /* !MODULE */
5660 
5661 static int get_version(void __user *arg)
5662 {
5663         mdu_version_t ver;
5664 
5665         ver.major = MD_MAJOR_VERSION;
5666         ver.minor = MD_MINOR_VERSION;
5667         ver.patchlevel = MD_PATCHLEVEL_VERSION;
5668 
5669         if (copy_to_user(arg, &ver, sizeof(ver)))
5670                 return -EFAULT;
5671 
5672         return 0;
5673 }
5674 
5675 static int get_array_info(struct mddev *mddev, void __user *arg)
5676 {
5677         mdu_array_info_t info;
5678         int nr,working,insync,failed,spare;
5679         struct md_rdev *rdev;
5680 
5681         nr = working = insync = failed = spare = 0;
5682         rcu_read_lock();
5683         rdev_for_each_rcu(rdev, mddev) {
5684                 nr++;
5685                 if (test_bit(Faulty, &rdev->flags))
5686                         failed++;
5687                 else {
5688                         working++;
5689                         if (test_bit(In_sync, &rdev->flags))
5690                                 insync++;
5691                         else
5692                                 spare++;
5693                 }
5694         }
5695         rcu_read_unlock();
5696 
5697         info.major_version = mddev->major_version;
5698         info.minor_version = mddev->minor_version;
5699         info.patch_version = MD_PATCHLEVEL_VERSION;
5700         info.ctime         = mddev->ctime;
5701         info.level         = mddev->level;
5702         info.size          = mddev->dev_sectors / 2;
5703         if (info.size != mddev->dev_sectors / 2) /* overflow */
5704                 info.size = -1;
5705         info.nr_disks      = nr;
5706         info.raid_disks    = mddev->raid_disks;
5707         info.md_minor      = mddev->md_minor;
5708         info.not_persistent= !mddev->persistent;
5709 
5710         info.utime         = mddev->utime;
5711         info.state         = 0;
5712         if (mddev->in_sync)
5713                 info.state = (1<<MD_SB_CLEAN);
5714         if (mddev->bitmap && mddev->bitmap_info.offset)
5715                 info.state |= (1<<MD_SB_BITMAP_PRESENT);
5716         if (mddev_is_clustered(mddev))
5717                 info.state |= (1<<MD_SB_CLUSTERED);
5718         info.active_disks  = insync;
5719         info.working_disks = working;
5720         info.failed_disks  = failed;
5721         info.spare_disks   = spare;
5722 
5723         info.layout        = mddev->layout;
5724         info.chunk_size    = mddev->chunk_sectors << 9;
5725 
5726         if (copy_to_user(arg, &info, sizeof(info)))
5727                 return -EFAULT;
5728 
5729         return 0;
5730 }
5731 
5732 static int get_bitmap_file(struct mddev *mddev, void __user * arg)
5733 {
5734         mdu_bitmap_file_t *file = NULL; /* too big for stack allocation */
5735         char *ptr;
5736         int err;
5737 
5738         file = kmalloc(sizeof(*file), GFP_NOIO);
5739         if (!file)
5740                 return -ENOMEM;
5741 
5742         err = 0;
5743         spin_lock(&mddev->lock);
5744         /* bitmap disabled, zero the first byte and copy out */
5745         if (!mddev->bitmap_info.file)
5746                 file->pathname[0] = '\0';
5747         else if ((ptr = d_path(&mddev->bitmap_info.file->f_path,
5748                                file->pathname, sizeof(file->pathname))),
5749                  IS_ERR(ptr))
5750                 err = PTR_ERR(ptr);
5751         else
5752                 memmove(file->pathname, ptr,
5753                         sizeof(file->pathname)-(ptr-file->pathname));
5754         spin_unlock(&mddev->lock);
5755 
5756         if (err == 0 &&
5757             copy_to_user(arg, file, sizeof(*file)))
5758                 err = -EFAULT;
5759 
5760         kfree(file);
5761         return err;
5762 }
5763 
5764 static int get_disk_info(struct mddev *mddev, void __user * arg)
5765 {
5766         mdu_disk_info_t info;
5767         struct md_rdev *rdev;
5768 
5769         if (copy_from_user(&info, arg, sizeof(info)))
5770                 return -EFAULT;
5771 
5772         rcu_read_lock();
5773         rdev = md_find_rdev_nr_rcu(mddev, info.number);
5774         if (rdev) {
5775                 info.major = MAJOR(rdev->bdev->bd_dev);
5776                 info.minor = MINOR(rdev->bdev->bd_dev);
5777                 info.raid_disk = rdev->raid_disk;
5778                 info.state = 0;
5779                 if (test_bit(Faulty, &rdev->flags))
5780                         info.state |= (1<<MD_DISK_FAULTY);
5781                 else if (test_bit(In_sync, &rdev->flags)) {
5782                         info.state |= (1<<MD_DISK_ACTIVE);
5783                         info.state |= (1<<MD_DISK_SYNC);
5784                 }
5785                 if (test_bit(WriteMostly, &rdev->flags))
5786                         info.state |= (1<<MD_DISK_WRITEMOSTLY);
5787         } else {
5788                 info.major = info.minor = 0;
5789                 info.raid_disk = -1;
5790                 info.state = (1<<MD_DISK_REMOVED);
5791         }
5792         rcu_read_unlock();
5793 
5794         if (copy_to_user(arg, &info, sizeof(info)))
5795                 return -EFAULT;
5796 
5797         return 0;
5798 }
5799 
5800 static int add_new_disk(struct mddev *mddev, mdu_disk_info_t *info)
5801 {
5802         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
5803         struct md_rdev *rdev;
5804         dev_t dev = MKDEV(info->major,info->minor);
5805 
5806         if (mddev_is_clustered(mddev) &&
5807                 !(info->state & ((1 << MD_DISK_CLUSTER_ADD) | (1 << MD_DISK_CANDIDATE)))) {
5808                 pr_err("%s: Cannot add to clustered mddev.\n",
5809                                mdname(mddev));
5810                 return -EINVAL;
5811         }
5812 
5813         if (info->major != MAJOR(dev) || info->minor != MINOR(dev))
5814                 return -EOVERFLOW;
5815 
5816         if (!mddev->raid_disks) {
5817                 int err;
5818                 /* expecting a device which has a superblock */
5819                 rdev = md_import_device(dev, mddev->major_version, mddev->minor_version);
5820                 if (IS_ERR(rdev)) {
5821                         printk(KERN_WARNING
5822                                 "md: md_import_device returned %ld\n",
5823                                 PTR_ERR(rdev));
5824                         return PTR_ERR(rdev);
5825                 }
5826                 if (!list_empty(&mddev->disks)) {
5827                         struct md_rdev *rdev0
5828                                 = list_entry(mddev->disks.next,
5829                                              struct md_rdev, same_set);
5830                         err = super_types[mddev->major_version]
5831                                 .load_super(rdev, rdev0, mddev->minor_version);
5832                         if (err < 0) {
5833                                 printk(KERN_WARNING
5834                                         "md: %s has different UUID to %s\n",
5835                                         bdevname(rdev->bdev,b),
5836                                         bdevname(rdev0->bdev,b2));
5837                                 export_rdev(rdev);
5838                                 return -EINVAL;
5839                         }
5840                 }
5841                 err = bind_rdev_to_array(rdev, mddev);
5842                 if (err)
5843                         export_rdev(rdev);
5844                 return err;
5845         }
5846 
5847         /*
5848          * add_new_disk can be used once the array is assembled
5849          * to add "hot spares".  They must already have a superblock
5850          * written
5851          */
5852         if (mddev->pers) {
5853                 int err;
5854                 if (!mddev->pers->hot_add_disk) {
5855                         printk(KERN_WARNING
5856                                 "%s: personality does not support diskops!\n",
5857                                mdname(mddev));
5858                         return -EINVAL;
5859                 }
5860                 if (mddev->persistent)
5861                         rdev = md_import_device(dev, mddev->major_version,
5862                                                 mddev->minor_version);
5863                 else
5864                         rdev = md_import_device(dev, -1, -1);
5865                 if (IS_ERR(rdev)) {
5866                         printk(KERN_WARNING
5867                                 "md: md_import_device returned %ld\n",
5868                                 PTR_ERR(rdev));
5869                         return PTR_ERR(rdev);
5870                 }
5871                 /* set saved_raid_disk if appropriate */
5872                 if (!mddev->persistent) {
5873                         if (info->state & (1<<MD_DISK_SYNC)  &&
5874                             info->raid_disk < mddev->raid_disks) {
5875                                 rdev->raid_disk = info->raid_disk;
5876                                 set_bit(In_sync, &rdev->flags);
5877                                 clear_bit(Bitmap_sync, &rdev->flags);
5878                         } else
5879                                 rdev->raid_disk = -1;
5880                         rdev->saved_raid_disk = rdev->raid_disk;
5881                 } else
5882                         super_types[mddev->major_version].
5883                                 validate_super(mddev, rdev);
5884                 if ((info->state & (1<<MD_DISK_SYNC)) &&
5885                      rdev->raid_disk != info->raid_disk) {
5886                         /* This was a hot-add request, but events doesn't
5887                          * match, so reject it.
5888                          */
5889                         export_rdev(rdev);
5890                         return -EINVAL;
5891                 }
5892 
5893                 clear_bit(In_sync, &rdev->flags); /* just to be sure */
5894                 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
5895                         set_bit(WriteMostly, &rdev->flags);
5896                 else
5897                         clear_bit(WriteMostly, &rdev->flags);
5898 
5899                 /*
5900                  * check whether the device shows up in other nodes
5901                  */
5902                 if (mddev_is_clustered(mddev)) {
5903                         if (info->state & (1 << MD_DISK_CANDIDATE)) {
5904                                 /* Through --cluster-confirm */
5905                                 set_bit(Candidate, &rdev->flags);
5906                                 err = md_cluster_ops->new_disk_ack(mddev, true);
5907                                 if (err) {
5908                                         export_rdev(rdev);
5909                                         return err;
5910                                 }
5911                         } else if (info->state & (1 << MD_DISK_CLUSTER_ADD)) {
5912                                 /* --add initiated by this node */
5913                                 err = md_cluster_ops->add_new_disk_start(mddev, rdev);
5914                                 if (err) {
5915                                         md_cluster_ops->add_new_disk_finish(mddev);
5916                                         export_rdev(rdev);
5917                                         return err;
5918                                 }
5919                         }
5920                 }
5921 
5922                 rdev->raid_disk = -1;
5923                 err = bind_rdev_to_array(rdev, mddev);
5924                 if (err)
5925                         export_rdev(rdev);
5926                 else
5927                         err = add_bound_rdev(rdev);
5928                 if (mddev_is_clustered(mddev) &&
5929                                 (info->state & (1 << MD_DISK_CLUSTER_ADD)))
5930                         md_cluster_ops->add_new_disk_finish(mddev);
5931                 return err;
5932         }
5933 
5934         /* otherwise, add_new_disk is only allowed
5935          * for major_version==0 superblocks
5936          */
5937         if (mddev->major_version != 0) {
5938                 printk(KERN_WARNING "%s: ADD_NEW_DISK not supported\n",
5939                        mdname(mddev));
5940                 return -EINVAL;
5941         }
5942 
5943         if (!(info->state & (1<<MD_DISK_FAULTY))) {
5944                 int err;
5945                 rdev = md_import_device(dev, -1, 0);
5946                 if (IS_ERR(rdev)) {
5947                         printk(KERN_WARNING
5948                                 "md: error, md_import_device() returned %ld\n",
5949                                 PTR_ERR(rdev));
5950                         return PTR_ERR(rdev);
5951                 }
5952                 rdev->desc_nr = info->number;
5953                 if (info->raid_disk < mddev->raid_disks)
5954                         rdev->raid_disk = info->raid_disk;
5955                 else
5956                         rdev->raid_disk = -1;
5957 
5958                 if (rdev->raid_disk < mddev->raid_disks)
5959                         if (info->state & (1<<MD_DISK_SYNC))
5960                                 set_bit(In_sync, &rdev->flags);
5961 
5962                 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
5963                         set_bit(WriteMostly, &rdev->flags);
5964 
5965                 if (!mddev->persistent) {
5966                         printk(KERN_INFO "md: nonpersistent superblock ...\n");
5967                         rdev->sb_start = i_size_read(rdev->bdev->bd_inode) / 512;
5968                 } else
5969                         rdev->sb_start = calc_dev_sboffset(rdev);
5970                 rdev->sectors = rdev->sb_start;
5971 
5972                 err = bind_rdev_to_array(rdev, mddev);
5973                 if (err) {
5974                         export_rdev(rdev);
5975                         return err;
5976                 }
5977         }
5978 
5979         return 0;
5980 }
5981 
5982 static int hot_remove_disk(struct mddev *mddev, dev_t dev)
5983 {
5984         char b[BDEVNAME_SIZE];
5985         struct md_rdev *rdev;
5986 
5987         rdev = find_rdev(mddev, dev);
5988         if (!rdev)
5989                 return -ENXIO;
5990 
5991         if (mddev_is_clustered(mddev))
5992                 md_cluster_ops->metadata_update_start(mddev);
5993 
5994         clear_bit(Blocked, &rdev->flags);
5995         remove_and_add_spares(mddev, rdev);
5996 
5997         if (rdev->raid_disk >= 0)
5998                 goto busy;
5999 
6000         if (mddev_is_clustered(mddev))
6001                 md_cluster_ops->remove_disk(mddev, rdev);
6002 
6003         md_kick_rdev_from_array(rdev);
6004         md_update_sb(mddev, 1);
6005         md_new_event(mddev);
6006 
6007         if (mddev_is_clustered(mddev))
6008                 md_cluster_ops->metadata_update_finish(mddev);
6009 
6010         return 0;
6011 busy:
6012         if (mddev_is_clustered(mddev))
6013                 md_cluster_ops->metadata_update_cancel(mddev);
6014         printk(KERN_WARNING "md: cannot remove active disk %s from %s ...\n",
6015                 bdevname(rdev->bdev,b), mdname(mddev));
6016         return -EBUSY;
6017 }
6018 
6019 static int hot_add_disk(struct mddev *mddev, dev_t dev)
6020 {
6021         char b[BDEVNAME_SIZE];
6022         int err;
6023         struct md_rdev *rdev;
6024 
6025         if (!mddev->pers)
6026                 return -ENODEV;
6027 
6028         if (mddev->major_version != 0) {
6029                 printk(KERN_WARNING "%s: HOT_ADD may only be used with"
6030                         " version-0 superblocks.\n",
6031                         mdname(mddev));
6032                 return -EINVAL;
6033         }
6034         if (!mddev->pers->hot_add_disk) {
6035                 printk(KERN_WARNING
6036                         "%s: personality does not support diskops!\n",
6037                         mdname(mddev));
6038                 return -EINVAL;
6039         }
6040 
6041         rdev = md_import_device(dev, -1, 0);
6042         if (IS_ERR(rdev)) {
6043                 printk(KERN_WARNING
6044                         "md: error, md_import_device() returned %ld\n",
6045                         PTR_ERR(rdev));
6046                 return -EINVAL;
6047         }
6048 
6049         if (mddev->persistent)
6050                 rdev->sb_start = calc_dev_sboffset(rdev);
6051         else
6052                 rdev->sb_start = i_size_read(rdev->bdev->bd_inode) / 512;
6053 
6054         rdev->sectors = rdev->sb_start;
6055 
6056         if (test_bit(Faulty, &rdev->flags)) {
6057                 printk(KERN_WARNING
6058                         "md: can not hot-add faulty %s disk to %s!\n",
6059                         bdevname(rdev->bdev,b), mdname(mddev));
6060                 err = -EINVAL;
6061                 goto abort_export;
6062         }
6063 
6064         if (mddev_is_clustered(mddev))
6065                 md_cluster_ops->metadata_update_start(mddev);
6066         clear_bit(In_sync, &rdev->flags);
6067         rdev->desc_nr = -1;
6068         rdev->saved_raid_disk = -1;
6069         err = bind_rdev_to_array(rdev, mddev);
6070         if (err)
6071                 goto abort_clustered;
6072 
6073         /*
6074          * The rest should better be atomic, we can have disk failures
6075          * noticed in interrupt contexts ...
6076          */
6077 
6078         rdev->raid_disk = -1;
6079 
6080         md_update_sb(mddev, 1);
6081 
6082         if (mddev_is_clustered(mddev))
6083                 md_cluster_ops->metadata_update_finish(mddev);
6084         /*
6085          * Kick recovery, maybe this spare has to be added to the
6086          * array immediately.
6087          */
6088         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6089         md_wakeup_thread(mddev->thread);
6090         md_new_event(mddev);
6091         return 0;
6092 
6093 abort_clustered:
6094         if (mddev_is_clustered(mddev))
6095                 md_cluster_ops->metadata_update_cancel(mddev);
6096 abort_export:
6097         export_rdev(rdev);
6098         return err;
6099 }
6100 
6101 static int set_bitmap_file(struct mddev *mddev, int fd)
6102 {
6103         int err = 0;
6104 
6105         if (mddev->pers) {
6106                 if (!mddev->pers->quiesce || !mddev->thread)
6107                         return -EBUSY;
6108                 if (mddev->recovery || mddev->sync_thread)
6109                         return -EBUSY;
6110                 /* we should be able to change the bitmap.. */
6111         }
6112 
6113         if (fd >= 0) {
6114                 struct inode *inode;
6115                 struct file *f;
6116 
6117                 if (mddev->bitmap || mddev->bitmap_info.file)
6118                         return -EEXIST; /* cannot add when bitmap is present */
6119                 f = fget(fd);
6120 
6121                 if (f == NULL) {
6122                         printk(KERN_ERR "%s: error: failed to get bitmap file\n",
6123                                mdname(mddev));
6124                         return -EBADF;
6125                 }
6126 
6127                 inode = f->f_mapping->host;
6128                 if (!S_ISREG(inode->i_mode)) {
6129                         printk(KERN_ERR "%s: error: bitmap file must be a regular file\n",
6130                                mdname(mddev));
6131                         err = -EBADF;
6132                 } else if (!(f->f_mode & FMODE_WRITE)) {
6133                         printk(KERN_ERR "%s: error: bitmap file must open for write\n",
6134                                mdname(mddev));
6135                         err = -EBADF;
6136                 } else if (atomic_read(&inode->i_writecount) != 1) {
6137                         printk(KERN_ERR "%s: error: bitmap file is already in use\n",
6138                                mdname(mddev));
6139                         err = -EBUSY;
6140                 }
6141                 if (err) {
6142                         fput(f);
6143                         return err;
6144                 }
6145                 mddev->bitmap_info.file = f;
6146                 mddev->bitmap_info.offset = 0; /* file overrides offset */
6147         } else if (mddev->bitmap == NULL)
6148                 return -ENOENT; /* cannot remove what isn't there */
6149         err = 0;
6150         if (mddev->pers) {
6151                 mddev->pers->quiesce(mddev, 1);
6152                 if (fd >= 0) {
6153                         struct bitmap *bitmap;
6154 
6155                         bitmap = bitmap_create(mddev, -1);
6156                         if (!IS_ERR(bitmap)) {
6157                                 mddev->bitmap = bitmap;
6158                                 err = bitmap_load(mddev);
6159                         } else
6160                                 err = PTR_ERR(bitmap);
6161                 }
6162                 if (fd < 0 || err) {
6163                         bitmap_destroy(mddev);
6164                         fd = -1; /* make sure to put the file */
6165                 }
6166                 mddev->pers->quiesce(mddev, 0);
6167         }
6168         if (fd < 0) {
6169                 struct file *f = mddev->bitmap_info.file;
6170                 if (f) {
6171                         spin_lock(&mddev->lock);
6172                         mddev->bitmap_info.file = NULL;
6173                         spin_unlock(&mddev->lock);
6174                         fput(f);
6175                 }
6176         }
6177 
6178         return err;
6179 }
6180 
6181 /*
6182  * set_array_info is used two different ways
6183  * The original usage is when creating a new array.
6184  * In this usage, raid_disks is > 0 and it together with
6185  *  level, size, not_persistent,layout,chunksize determine the
6186  *  shape of the array.
6187  *  This will always create an array with a type-0.90.0 superblock.
6188  * The newer usage is when assembling an array.
6189  *  In this case raid_disks will be 0, and the major_version field is
6190  *  use to determine which style super-blocks are to be found on the devices.
6191  *  The minor and patch _version numbers are also kept incase the
6192  *  super_block handler wishes to interpret them.
6193  */
6194 static int set_array_info(struct mddev *mddev, mdu_array_info_t *info)
6195 {
6196 
6197         if (info->raid_disks == 0) {
6198                 /* just setting version number for superblock loading */
6199                 if (info->major_version < 0 ||
6200                     info->major_version >= ARRAY_SIZE(super_types) ||
6201                     super_types[info->major_version].name == NULL) {
6202                         /* maybe try to auto-load a module? */
6203                         printk(KERN_INFO
6204                                 "md: superblock version %d not known\n",
6205                                 info->major_version);
6206                         return -EINVAL;
6207                 }
6208                 mddev->major_version = info->major_version;
6209                 mddev->minor_version = info->minor_version;
6210                 mddev->patch_version = info->patch_version;
6211                 mddev->persistent = !info->not_persistent;
6212                 /* ensure mddev_put doesn't delete this now that there
6213                  * is some minimal configuration.
6214                  */
6215                 mddev->ctime         = get_seconds();
6216                 return 0;
6217         }
6218         mddev->major_version = MD_MAJOR_VERSION;
6219         mddev->minor_version = MD_MINOR_VERSION;
6220         mddev->patch_version = MD_PATCHLEVEL_VERSION;
6221         mddev->ctime         = get_seconds();
6222 
6223         mddev->level         = info->level;
6224         mddev->clevel[0]     = 0;
6225         mddev->dev_sectors   = 2 * (sector_t)info->size;
6226         mddev->raid_disks    = info->raid_disks;
6227         /* don't set md_minor, it is determined by which /dev/md* was
6228          * openned
6229          */
6230         if (info->state & (1<<MD_SB_CLEAN))
6231                 mddev->recovery_cp = MaxSector;
6232         else
6233                 mddev->recovery_cp = 0;
6234         mddev->persistent    = ! info->not_persistent;
6235         mddev->external      = 0;
6236 
6237         mddev->layout        = info->layout;
6238         mddev->chunk_sectors = info->chunk_size >> 9;
6239 
6240         mddev->max_disks     = MD_SB_DISKS;
6241 
6242         if (mddev->persistent)
6243                 mddev->flags         = 0;
6244         set_bit(MD_CHANGE_DEVS, &mddev->flags);
6245 
6246         mddev->bitmap_info.default_offset = MD_SB_BYTES >> 9;
6247         mddev->bitmap_info.default_space = 64*2 - (MD_SB_BYTES >> 9);
6248         mddev->bitmap_info.offset = 0;
6249 
6250         mddev->reshape_position = MaxSector;
6251 
6252         /*
6253          * Generate a 128 bit UUID
6254          */
6255         get_random_bytes(mddev->uuid, 16);
6256 
6257         mddev->new_level = mddev->level;
6258         mddev->new_chunk_sectors = mddev->chunk_sectors;
6259         mddev->new_layout = mddev->layout;
6260         mddev->delta_disks = 0;
6261         mddev->reshape_backwards = 0;
6262 
6263         return 0;
6264 }
6265 
6266 void md_set_array_sectors(struct mddev *mddev, sector_t array_sectors)
6267 {
6268         WARN(!mddev_is_locked(mddev), "%s: unlocked mddev!\n", __func__);
6269 
6270         if (mddev->external_size)
6271                 return;
6272 
6273         mddev->array_sectors = array_sectors;
6274 }
6275 EXPORT_SYMBOL(md_set_array_sectors);
6276 
6277 static int update_size(struct mddev *mddev, sector_t num_sectors)
6278 {
6279         struct md_rdev *rdev;
6280         int rv;
6281         int fit = (num_sectors == 0);
6282 
6283         if (mddev->pers->resize == NULL)
6284                 return -EINVAL;
6285         /* The "num_sectors" is the number of sectors of each device that
6286          * is used.  This can only make sense for arrays with redundancy.
6287          * linear and raid0 always use whatever space is available. We can only
6288          * consider changing this number if no resync or reconstruction is
6289          * happening, and if the new size is acceptable. It must fit before the
6290          * sb_start or, if that is <data_offset, it must fit before the size
6291          * of each device.  If num_sectors is zero, we find the largest size
6292          * that fits.
6293          */
6294         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
6295             mddev->sync_thread)
6296                 return -EBUSY;
6297         if (mddev->ro)
6298                 return -EROFS;
6299 
6300         rdev_for_each(rdev, mddev) {
6301                 sector_t avail = rdev->sectors;
6302 
6303                 if (fit && (num_sectors == 0 || num_sectors > avail))
6304                         num_sectors = avail;
6305                 if (avail < num_sectors)
6306                         return -ENOSPC;
6307         }
6308         rv = mddev->pers->resize(mddev, num_sectors);
6309         if (!rv)
6310                 revalidate_disk(mddev->gendisk);
6311         return rv;
6312 }
6313 
6314 static int update_raid_disks(struct mddev *mddev, int raid_disks)
6315 {
6316         int rv;
6317         struct md_rdev *rdev;
6318         /* change the number of raid disks */
6319         if (mddev->pers->check_reshape == NULL)
6320                 return -EINVAL;
6321         if (mddev->ro)
6322                 return -EROFS;
6323         if (raid_disks <= 0 ||
6324             (mddev->max_disks && raid_disks >= mddev->max_disks))
6325                 return -EINVAL;
6326         if (mddev->sync_thread ||
6327             test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
6328             mddev->reshape_position != MaxSector)
6329                 return -EBUSY;
6330 
6331         rdev_for_each(rdev, mddev) {
6332                 if (mddev->raid_disks < raid_disks &&
6333                     rdev->data_offset < rdev->new_data_offset)
6334                         return -EINVAL;
6335                 if (mddev->raid_disks > raid_disks &&
6336                     rdev->data_offset > rdev->new_data_offset)
6337                         return -EINVAL;
6338         }
6339 
6340         mddev->delta_disks = raid_disks - mddev->raid_disks;
6341         if (mddev->delta_disks < 0)
6342                 mddev->reshape_backwards = 1;
6343         else if (mddev->delta_disks > 0)
6344                 mddev->reshape_backwards = 0;
6345 
6346         rv = mddev->pers->check_reshape(mddev);
6347         if (rv < 0) {
6348                 mddev->delta_disks = 0;
6349                 mddev->reshape_backwards = 0;
6350         }
6351         return rv;
6352 }
6353 
6354 /*
6355  * update_array_info is used to change the configuration of an
6356  * on-line array.
6357  * The version, ctime,level,size,raid_disks,not_persistent, layout,chunk_size
6358  * fields in the info are checked against the array.
6359  * Any differences that cannot be handled will cause an error.
6360  * Normally, only one change can be managed at a time.
6361  */
6362 static int update_array_info(struct mddev *mddev, mdu_array_info_t *info)
6363 {
6364         int rv = 0;
6365         int cnt = 0;
6366         int state = 0;
6367 
6368         /* calculate expected state,ignoring low bits */
6369         if (mddev->bitmap && mddev->bitmap_info.offset)
6370                 state |= (1 << MD_SB_BITMAP_PRESENT);
6371 
6372         if (mddev->major_version != info->major_version ||
6373             mddev->minor_version != info->minor_version ||
6374 /*          mddev->patch_version != info->patch_version || */
6375             mddev->ctime         != info->ctime         ||
6376             mddev->level         != info->level         ||
6377 /*          mddev->layout        != info->layout        || */
6378             !mddev->persistent   != info->not_persistent||
6379             mddev->chunk_sectors != info->chunk_size >> 9 ||
6380             /* ignore bottom 8 bits of state, and allow SB_BITMAP_PRESENT to change */
6381             ((state^info->state) & 0xfffffe00)
6382                 )
6383                 return -EINVAL;
6384         /* Check there is only one change */
6385         if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
6386                 cnt++;
6387         if (mddev->raid_disks != info->raid_disks)
6388                 cnt++;
6389         if (mddev->layout != info->layout)
6390                 cnt++;
6391         if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT))
6392                 cnt++;
6393         if (cnt == 0)
6394                 return 0;
6395         if (cnt > 1)
6396                 return -EINVAL;
6397 
6398         if (mddev->layout != info->layout) {
6399                 /* Change layout
6400                  * we don't need to do anything at the md level, the
6401                  * personality will take care of it all.
6402                  */
6403                 if (mddev->pers->check_reshape == NULL)
6404                         return -EINVAL;
6405                 else {
6406                         mddev->new_layout = info->layout;
6407                         rv = mddev->pers->check_reshape(mddev);
6408                         if (rv)
6409                                 mddev->new_layout = mddev->layout;
6410                         return rv;
6411                 }
6412         }
6413         if (mddev_is_clustered(mddev))
6414                 md_cluster_ops->metadata_update_start(mddev);
6415         if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
6416                 rv = update_size(mddev, (sector_t)info->size * 2);
6417 
6418         if (mddev->raid_disks    != info->raid_disks)
6419                 rv = update_raid_disks(mddev, info->raid_disks);
6420 
6421         if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT)) {
6422                 if (mddev->pers->quiesce == NULL || mddev->thread == NULL) {
6423                         rv = -EINVAL;
6424                         goto err;
6425                 }
6426                 if (mddev->recovery || mddev->sync_thread) {
6427                         rv = -EBUSY;
6428                         goto err;
6429                 }
6430                 if (info->state & (1<<MD_SB_BITMAP_PRESENT)) {
6431                         struct bitmap *bitmap;
6432                         /* add the bitmap */
6433                         if (mddev->bitmap) {
6434                                 rv = -EEXIST;
6435                                 goto err;
6436                         }
6437                         if (mddev->bitmap_info.default_offset == 0) {
6438                                 rv = -EINVAL;
6439                                 goto err;
6440                         }
6441                         mddev->bitmap_info.offset =
6442                                 mddev->bitmap_info.default_offset;
6443                         mddev->bitmap_info.space =
6444                                 mddev->bitmap_info.default_space;
6445                         mddev->pers->quiesce(mddev, 1);
6446                         bitmap = bitmap_create(mddev, -1);
6447                         if (!IS_ERR(bitmap)) {
6448                                 mddev->bitmap = bitmap;
6449                                 rv = bitmap_load(mddev);
6450                         } else
6451                                 rv = PTR_ERR(bitmap);
6452                         if (rv)
6453                                 bitmap_destroy(mddev);
6454                         mddev->pers->quiesce(mddev, 0);
6455                 } else {
6456                         /* remove the bitmap */
6457                         if (!mddev->bitmap) {
6458                                 rv = -ENOENT;
6459                                 goto err;
6460                         }
6461                         if (mddev->bitmap->storage.file) {
6462                                 rv = -EINVAL;
6463                                 goto err;
6464                         }
6465                         mddev->pers->quiesce(mddev, 1);
6466                         bitmap_destroy(mddev);
6467                         mddev->pers->quiesce(mddev, 0);
6468                         mddev->bitmap_info.offset = 0;
6469                 }
6470         }
6471         md_update_sb(mddev, 1);
6472         if (mddev_is_clustered(mddev))
6473                 md_cluster_ops->metadata_update_finish(mddev);
6474         return rv;
6475 err:
6476         if (mddev_is_clustered(mddev))
6477                 md_cluster_ops->metadata_update_cancel(mddev);
6478         return rv;
6479 }
6480 
6481 static int set_disk_faulty(struct mddev *mddev, dev_t dev)
6482 {
6483         struct md_rdev *rdev;
6484         int err = 0;
6485 
6486         if (mddev->pers == NULL)
6487                 return -ENODEV;
6488 
6489         rcu_read_lock();
6490         rdev = find_rdev_rcu(mddev, dev);
6491         if (!rdev)
6492                 err =  -ENODEV;
6493         else {
6494                 md_error(mddev, rdev);
6495                 if (!test_bit(Faulty, &rdev->flags))
6496                         err = -EBUSY;
6497         }
6498         rcu_read_unlock();
6499         return err;
6500 }
6501 
6502 /*
6503  * We have a problem here : there is no easy way to give a CHS
6504  * virtual geometry. We currently pretend that we have a 2 heads
6505  * 4 sectors (with a BIG number of cylinders...). This drives
6506  * dosfs just mad... ;-)
6507  */
6508 static int md_getgeo(struct block_device *bdev, struct hd_geometry *geo)
6509 {
6510         struct mddev *mddev = bdev->bd_disk->private_data;
6511 
6512         geo->heads = 2;
6513         geo->sectors = 4;
6514         geo->cylinders = mddev->array_sectors / 8;
6515         return 0;
6516 }
6517 
6518 static inline bool md_ioctl_valid(unsigned int cmd)
6519 {
6520         switch (cmd) {
6521         case ADD_NEW_DISK:
6522         case BLKROSET:
6523         case GET_ARRAY_INFO:
6524         case GET_BITMAP_FILE:
6525         case GET_DISK_INFO:
6526         case HOT_ADD_DISK:
6527         case HOT_REMOVE_DISK:
6528         case RAID_AUTORUN:
6529         case RAID_VERSION:
6530         case RESTART_ARRAY_RW:
6531         case RUN_ARRAY:
6532         case SET_ARRAY_INFO:
6533         case SET_BITMAP_FILE:
6534         case SET_DISK_FAULTY:
6535         case STOP_ARRAY:
6536         case STOP_ARRAY_RO:
6537         case CLUSTERED_DISK_NACK:
6538                 return true;
6539         default:
6540                 return false;
6541         }
6542 }
6543 
6544 static int md_ioctl(struct block_device *bdev, fmode_t mode,
6545                         unsigned int cmd, unsigned long arg)
6546 {
6547         int err = 0;
6548         void __user *argp = (void __user *)arg;
6549         struct mddev *mddev = NULL;
6550         int ro;
6551 
6552         if (!md_ioctl_valid(cmd))
6553                 return -ENOTTY;
6554 
6555         switch (cmd) {
6556         case RAID_VERSION:
6557         case GET_ARRAY_INFO:
6558         case GET_DISK_INFO:
6559                 break;
6560         default:
6561                 if (!capable(CAP_SYS_ADMIN))
6562                         return -EACCES;
6563         }
6564 
6565         /*
6566          * Commands dealing with the RAID driver but not any
6567          * particular array:
6568          */
6569         switch (cmd) {
6570         case RAID_VERSION:
6571                 err = get_version(argp);
6572                 goto out;
6573 
6574 #ifndef MODULE
6575         case RAID_AUTORUN:
6576                 err = 0;
6577                 autostart_arrays(arg);
6578                 goto out;
6579 #endif
6580         default:;
6581         }
6582 
6583         /*
6584          * Commands creating/starting a new array:
6585          */
6586 
6587         mddev = bdev->bd_disk->private_data;
6588 
6589         if (!mddev) {
6590                 BUG();
6591                 goto out;
6592         }
6593 
6594         /* Some actions do not requires the mutex */
6595         switch (cmd) {
6596         case GET_ARRAY_INFO:
6597                 if (!mddev->raid_disks && !mddev->external)
6598                         err = -ENODEV;
6599                 else
6600                         err = get_array_info(mddev, argp);
6601                 goto out;
6602 
6603         case GET_DISK_INFO:
6604                 if (!mddev->raid_disks && !mddev->external)
6605                         err = -ENODEV;
6606                 else
6607                         err = get_disk_info(mddev, argp);
6608                 goto out;
6609 
6610         case SET_DISK_FAULTY:
6611                 err = set_disk_faulty(mddev, new_decode_dev(arg));
6612                 goto out;
6613 
6614         case GET_BITMAP_FILE:
6615                 err = get_bitmap_file(mddev, argp);
6616                 goto out;
6617 
6618         }
6619 
6620         if (cmd == ADD_NEW_DISK)
6621                 /* need to ensure md_delayed_delete() has completed */
6622                 flush_workqueue(md_misc_wq);
6623 
6624         if (cmd == HOT_REMOVE_DISK)
6625                 /* need to ensure recovery thread has run */
6626                 wait_event_interruptible_timeout(mddev->sb_wait,
6627                                                  !test_bit(MD_RECOVERY_NEEDED,
6628                                                            &mddev->flags),
6629                                                  msecs_to_jiffies(5000));
6630         if (cmd == STOP_ARRAY || cmd == STOP_ARRAY_RO) {
6631                 /* Need to flush page cache, and ensure no-one else opens
6632                  * and writes
6633                  */
6634                 mutex_lock(&mddev->open_mutex);
6635                 if (mddev->pers && atomic_read(&mddev->openers) > 1) {
6636                         mutex_unlock(&mddev->open_mutex);
6637                         err = -EBUSY;
6638                         goto out;
6639                 }
6640                 set_bit(MD_STILL_CLOSED, &mddev->flags);
6641                 mutex_unlock(&mddev->open_mutex);
6642                 sync_blockdev(bdev);
6643         }
6644         err = mddev_lock(mddev);
6645         if (err) {
6646                 printk(KERN_INFO
6647                         "md: ioctl lock interrupted, reason %d, cmd %d\n",
6648                         err, cmd);
6649                 goto out;
6650         }
6651 
6652         if (cmd == SET_ARRAY_INFO) {
6653                 mdu_array_info_t info;
6654                 if (!arg)
6655                         memset(&info, 0, sizeof(info));
6656                 else if (copy_from_user(&info, argp, sizeof(info))) {
6657                         err = -EFAULT;
6658                         goto unlock;
6659                 }
6660                 if (mddev->pers) {
6661                         err = update_array_info(mddev, &info);
6662                         if (err) {
6663                                 printk(KERN_WARNING "md: couldn't update"
6664                                        " array info. %d\n", err);
6665                                 goto unlock;
6666                         }
6667                         goto unlock;
6668                 }
6669                 if (!list_empty(&mddev->disks)) {
6670                         printk(KERN_WARNING
6671                                "md: array %s already has disks!\n",
6672                                mdname(mddev));
6673                         err = -EBUSY;
6674                         goto unlock;
6675                 }
6676                 if (mddev->raid_disks) {
6677                         printk(KERN_WARNING
6678                                "md: array %s already initialised!\n",
6679                                mdname(mddev));
6680                         err = -EBUSY;
6681                         goto unlock;
6682                 }
6683                 err = set_array_info(mddev, &info);
6684                 if (err) {
6685                         printk(KERN_WARNING "md: couldn't set"
6686                                " array info. %d\n", err);
6687                         goto unlock;
6688                 }
6689                 goto unlock;
6690         }
6691 
6692         /*
6693          * Commands querying/configuring an existing array:
6694          */
6695         /* if we are not initialised yet, only ADD_NEW_DISK, STOP_ARRAY,
6696          * RUN_ARRAY, and GET_ and SET_BITMAP_FILE are allowed */
6697         if ((!mddev->raid_disks && !mddev->external)
6698             && cmd != ADD_NEW_DISK && cmd != STOP_ARRAY
6699             && cmd != RUN_ARRAY && cmd != SET_BITMAP_FILE
6700             && cmd != GET_BITMAP_FILE) {
6701                 err = -ENODEV;
6702                 goto unlock;
6703         }
6704 
6705         /*
6706          * Commands even a read-only array can execute:
6707          */
6708         switch (cmd) {
6709         case RESTART_ARRAY_RW:
6710                 err = restart_array(mddev);
6711                 goto unlock;
6712 
6713         case STOP_ARRAY:
6714                 err = do_md_stop(mddev, 0, bdev);
6715                 goto unlock;
6716 
6717         case STOP_ARRAY_RO:
6718                 err = md_set_readonly(mddev, bdev);
6719                 goto unlock;
6720 
6721         case HOT_REMOVE_DISK:
6722                 err = hot_remove_disk(mddev, new_decode_dev(arg));
6723                 goto unlock;
6724 
6725         case ADD_NEW_DISK:
6726                 /* We can support ADD_NEW_DISK on read-only arrays
6727                  * on if we are re-adding a preexisting device.
6728                  * So require mddev->pers and MD_DISK_SYNC.
6729                  */
6730                 if (mddev->pers) {
6731                         mdu_disk_info_t info;
6732                         if (copy_from_user(&info, argp, sizeof(info)))
6733                                 err = -EFAULT;
6734                         else if (!(info.state & (1<<MD_DISK_SYNC)))
6735                                 /* Need to clear read-only for this */
6736                                 break;
6737                         else
6738                                 err = add_new_disk(mddev, &info);
6739                         goto unlock;
6740                 }
6741                 break;
6742 
6743         case BLKROSET:
6744                 if (get_user(ro, (int __user *)(arg))) {
6745                         err = -EFAULT;
6746                         goto unlock;
6747                 }
6748                 err = -EINVAL;
6749 
6750                 /* if the bdev is going readonly the value of mddev->ro
6751                  * does not matter, no writes are coming
6752                  */
6753                 if (ro)
6754                         goto unlock;
6755 
6756                 /* are we are already prepared for writes? */
6757                 if (mddev->ro != 1)
6758                         goto unlock;
6759 
6760                 /* transitioning to readauto need only happen for
6761                  * arrays that call md_write_start
6762                  */
6763                 if (mddev->pers) {
6764                         err = restart_array(mddev);
6765                         if (err == 0) {
6766                                 mddev->ro = 2;
6767                                 set_disk_ro(mddev->gendisk, 0);
6768                         }
6769                 }
6770                 goto unlock;
6771         }
6772 
6773         /*
6774          * The remaining ioctls are changing the state of the
6775          * superblock, so we do not allow them on read-only arrays.
6776          */
6777         if (mddev->ro && mddev->pers) {
6778                 if (mddev->ro == 2) {
6779                         mddev->ro = 0;
6780                         sysfs_notify_dirent_safe(mddev->sysfs_state);
6781                         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6782                         /* mddev_unlock will wake thread */
6783                         /* If a device failed while we were read-only, we
6784                          * need to make sure the metadata is updated now.
6785                          */
6786                         if (test_bit(MD_CHANGE_DEVS, &mddev->flags)) {
6787                                 mddev_unlock(mddev);
6788                                 wait_event(mddev->sb_wait,
6789                                            !test_bit(MD_CHANGE_DEVS, &mddev->flags) &&
6790                                            !test_bit(MD_CHANGE_PENDING, &mddev->flags));
6791                                 mddev_lock_nointr(mddev);
6792                         }
6793                 } else {
6794                         err = -EROFS;
6795                         goto unlock;
6796                 }
6797         }
6798 
6799         switch (cmd) {
6800         case ADD_NEW_DISK:
6801         {
6802                 mdu_disk_info_t info;
6803                 if (copy_from_user(&info, argp, sizeof(info)))
6804                         err = -EFAULT;
6805                 else
6806                         err = add_new_disk(mddev, &info);
6807                 goto unlock;
6808         }
6809 
6810         case CLUSTERED_DISK_NACK:
6811                 if (mddev_is_clustered(mddev))
6812                         md_cluster_ops->new_disk_ack(mddev, false);
6813                 else
6814                         err = -EINVAL;
6815                 goto unlock;
6816 
6817         case HOT_ADD_DISK:
6818                 err = hot_add_disk(mddev, new_decode_dev(arg));
6819                 goto unlock;
6820 
6821         case RUN_ARRAY:
6822                 err = do_md_run(mddev);
6823                 goto unlock;
6824 
6825         case SET_BITMAP_FILE:
6826                 err = set_bitmap_file(mddev, (int)arg);
6827                 goto unlock;
6828 
6829         default:
6830                 err = -EINVAL;
6831                 goto unlock;
6832         }
6833 
6834 unlock:
6835         if (mddev->hold_active == UNTIL_IOCTL &&
6836             err != -EINVAL)
6837                 mddev->hold_active = 0;
6838         mddev_unlock(mddev);
6839 out:
6840         return err;
6841 }
6842 #ifdef CONFIG_COMPAT
6843 static int md_compat_ioctl(struct block_device *bdev, fmode_t mode,
6844                     unsigned int cmd, unsigned long arg)
6845 {
6846         switch (cmd) {
6847         case HOT_REMOVE_DISK:
6848         case HOT_ADD_DISK:
6849         case SET_DISK_FAULTY:
6850         case SET_BITMAP_FILE:
6851                 /* These take in integer arg, do not convert */
6852                 break;
6853         default:
6854                 arg = (unsigned long)compat_ptr(arg);
6855                 break;
6856         }
6857 
6858         return md_ioctl(bdev, mode, cmd, arg);
6859 }
6860 #endif /* CONFIG_COMPAT */
6861 
6862 static int md_open(struct block_device *bdev, fmode_t mode)
6863 {
6864         /*
6865          * Succeed if we can lock the mddev, which confirms that
6866          * it isn't being stopped right now.
6867          */
6868         struct mddev *mddev = mddev_find(bdev->bd_dev);
6869         int err;
6870 
6871         if (!mddev)
6872                 return -ENODEV;
6873 
6874         if (mddev->gendisk != bdev->bd_disk) {
6875                 /* we are racing with mddev_put which is discarding this
6876                  * bd_disk.
6877                  */
6878                 mddev_put(mddev);
6879                 /* Wait until bdev->bd_disk is definitely gone */
6880                 flush_workqueue(md_misc_wq);
6881                 /* Then retry the open from the top */
6882                 return -ERESTARTSYS;
6883         }
6884         BUG_ON(mddev != bdev->bd_disk->private_data);
6885 
6886         if ((err = mutex_lock_interruptible(&mddev->open_mutex)))
6887                 goto out;
6888 
6889         err = 0;
6890         atomic_inc(&mddev->openers);
6891         clear_bit(MD_STILL_CLOSED, &mddev->flags);
6892         mutex_unlock(&mddev->open_mutex);
6893 
6894         check_disk_change(bdev);
6895  out:
6896         return err;
6897 }
6898 
6899 static void md_release(struct gendisk *disk, fmode_t mode)
6900 {
6901         struct mddev *mddev = disk->private_data;
6902 
6903         BUG_ON(!mddev);
6904         atomic_dec(&mddev->openers);
6905         mddev_put(mddev);
6906 }
6907 
6908 static int md_media_changed(struct gendisk *disk)
6909 {
6910         struct mddev *mddev = disk->private_data;
6911 
6912         return mddev->changed;
6913 }
6914 
6915 static int md_revalidate(struct gendisk *disk)
6916 {
6917         struct mddev *mddev = disk->private_data;
6918 
6919         mddev->changed = 0;
6920         return 0;
6921 }
6922 static const struct block_device_operations md_fops =
6923 {
6924         .owner          = THIS_MODULE,
6925         .open           = md_open,
6926         .release        = md_release,
6927         .ioctl          = md_ioctl,
6928 #ifdef CONFIG_COMPAT
6929         .compat_ioctl   = md_compat_ioctl,
6930 #endif
6931         .getgeo         = md_getgeo,
6932         .media_changed  = md_media_changed,
6933         .revalidate_disk= md_revalidate,
6934 };
6935 
6936 static int md_thread(void *arg)
6937 {
6938         struct md_thread *thread = arg;
6939 
6940         /*
6941          * md_thread is a 'system-thread', it's priority should be very
6942          * high. We avoid resource deadlocks individually in each
6943          * raid personality. (RAID5 does preallocation) We also use RR and
6944          * the very same RT priority as kswapd, thus we will never get
6945          * into a priority inversion deadlock.
6946          *
6947          * we definitely have to have equal or higher priority than
6948          * bdflush, otherwise bdflush will deadlock if there are too
6949          * many dirty RAID5 blocks.
6950          */
6951 
6952         allow_signal(SIGKILL);
6953         while (!kthread_should_stop()) {
6954 
6955                 /* We need to wait INTERRUPTIBLE so that
6956                  * we don't add to the load-average.
6957                  * That means we need to be sure no signals are
6958                  * pending
6959                  */
6960                 if (signal_pending(current))
6961                         flush_signals(current);
6962 
6963                 wait_event_interruptible_timeout
6964                         (thread->wqueue,
6965                          test_bit(THREAD_WAKEUP, &thread->flags)
6966                          || kthread_should_stop(),
6967                          thread->timeout);
6968 
6969                 clear_bit(THREAD_WAKEUP, &thread->flags);
6970                 if (!kthread_should_stop())
6971                         thread->run(thread);
6972         }
6973 
6974         return 0;
6975 }
6976 
6977 void md_wakeup_thread(struct md_thread *thread)
6978 {
6979         if (thread) {
6980                 pr_debug("md: waking up MD thread %s.\n", thread->tsk->comm);
6981                 set_bit(THREAD_WAKEUP, &thread->flags);
6982                 wake_up(&thread->wqueue);
6983         }
6984 }
6985 EXPORT_SYMBOL(md_wakeup_thread);
6986 
6987 struct md_thread *md_register_thread(void (*run) (struct md_thread *),
6988                 struct mddev *mddev, const char *name)
6989 {
6990         struct md_thread *thread;
6991 
6992         thread = kzalloc(sizeof(struct md_thread), GFP_KERNEL);
6993         if (!thread)
6994                 return NULL;
6995 
6996         init_waitqueue_head(&thread->wqueue);
6997 
6998         thread->run = run;
6999         thread->mddev = mddev;
7000         thread->timeout = MAX_SCHEDULE_TIMEOUT;
7001         thread->tsk = kthread_run(md_thread, thread,
7002                                   "%s_%s",
7003                                   mdname(thread->mddev),
7004                                   name);
7005         if (IS_ERR(thread->tsk)) {
7006                 kfree(thread);
7007                 return NULL;
7008         }
7009         return thread;
7010 }
7011 EXPORT_SYMBOL(md_register_thread);
7012 
7013 void md_unregister_thread(struct md_thread **threadp)
7014 {
7015         struct md_thread *thread = *threadp;
7016         if (!thread)
7017                 return;
7018         pr_debug("interrupting MD-thread pid %d\n", task_pid_nr(thread->tsk));
7019         /* Locking ensures that mddev_unlock does not wake_up a
7020          * non-existent thread
7021          */
7022         spin_lock(&pers_lock);
7023         *threadp = NULL;
7024         spin_unlock(&pers_lock);
7025 
7026         kthread_stop(thread->tsk);
7027         kfree(thread);
7028 }
7029 EXPORT_SYMBOL(md_unregister_thread);
7030 
7031 void md_error(struct mddev *mddev, struct md_rdev *rdev)
7032 {
7033         if (!rdev || test_bit(Faulty, &rdev->flags))
7034                 return;
7035 
7036         if (!mddev->pers || !mddev->pers->error_handler)
7037                 return;
7038         mddev->pers->error_handler(mddev,rdev);
7039         if (mddev->degraded)
7040                 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
7041         sysfs_notify_dirent_safe(rdev->sysfs_state);
7042         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
7043         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7044         md_wakeup_thread(mddev->thread);
7045         if (mddev->event_work.func)
7046                 queue_work(md_misc_wq, &mddev->event_work);
7047         md_new_event_inintr(mddev);
7048 }
7049 EXPORT_SYMBOL(md_error);
7050 
7051 /* seq_file implementation /proc/mdstat */
7052 
7053 static void status_unused(struct seq_file *seq)
7054 {
7055         int i = 0;
7056         struct md_rdev *rdev;
7057 
7058         seq_printf(seq, "unused devices: ");
7059 
7060         list_for_each_entry(rdev, &pending_raid_disks, same_set) {
7061                 char b[BDEVNAME_SIZE];
7062                 i++;
7063                 seq_printf(seq, "%s ",
7064                               bdevname(rdev->bdev,b));
7065         }
7066         if (!i)
7067                 seq_printf(seq, "<none>");
7068 
7069         seq_printf(seq, "\n");
7070 }
7071 
7072 static void status_resync(struct seq_file *seq, struct mddev *mddev)
7073 {
7074         sector_t max_sectors, resync, res;
7075         unsigned long dt, db;
7076         sector_t rt;
7077         int scale;
7078         unsigned int per_milli;
7079 
7080         if (mddev->curr_resync <= 3)
7081                 resync = 0;
7082         else
7083                 resync = mddev->curr_resync
7084                         - atomic_read(&mddev->recovery_active);
7085 
7086         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ||
7087             test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
7088                 max_sectors = mddev->resync_max_sectors;
7089         else
7090                 max_sectors = mddev->dev_sectors;
7091 
7092         WARN_ON(max_sectors == 0);
7093         /* Pick 'scale' such that (resync>>scale)*1000 will fit
7094          * in a sector_t, and (max_sectors>>scale) will fit in a
7095          * u32, as those are the requirements for sector_div.
7096          * Thus 'scale' must be at least 10
7097          */
7098         scale = 10;
7099         if (sizeof(sector_t) > sizeof(unsigned long)) {
7100                 while ( max_sectors/2 > (1ULL<<(scale+32)))
7101                         scale++;
7102         }
7103         res = (resync>>scale)*1000;
7104         sector_div(res, (u32)((max_sectors>>scale)+1));
7105 
7106         per_milli = res;
7107         {
7108                 int i, x = per_milli/50, y = 20-x;
7109                 seq_printf(seq, "[");
7110                 for (i = 0; i < x; i++)
7111                         seq_printf(seq, "=");
7112                 seq_printf(seq, ">");
7113                 for (i = 0; i < y; i++)
7114                         seq_printf(seq, ".");
7115                 seq_printf(seq, "] ");
7116         }
7117         seq_printf(seq, " %s =%3u.%u%% (%llu/%llu)",
7118                    (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)?
7119                     "reshape" :
7120                     (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)?
7121                      "check" :
7122                      (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ?
7123                       "resync" : "recovery"))),
7124                    per_milli/10, per_milli % 10,
7125                    (unsigned long long) resync/2,
7126                    (unsigned long long) max_sectors/2);
7127 
7128         /*
7129          * dt: time from mark until now
7130          * db: blocks written from mark until now
7131          * rt: remaining time
7132          *
7133          * rt is a sector_t, so could be 32bit or 64bit.
7134          * So we divide before multiply in case it is 32bit and close
7135          * to the limit.
7136          * We scale the divisor (db) by 32 to avoid losing precision
7137          * near the end of resync when the number of remaining sectors
7138          * is close to 'db'.
7139          * We then divide rt by 32 after multiplying by db to compensate.
7140          * The '+1' avoids division by zero if db is very small.
7141          */
7142         dt = ((jiffies - mddev->resync_mark) / HZ);
7143         if (!dt) dt++;
7144         db = (mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active))
7145                 - mddev->resync_mark_cnt;
7146 
7147         rt = max_sectors - resync;    /* number of remaining sectors */
7148         sector_div(rt, db/32+1);
7149         rt *= dt;
7150         rt >>= 5;
7151 
7152         seq_printf(seq, " finish=%lu.%lumin", (unsigned long)rt / 60,
7153                    ((unsigned long)rt % 60)/6);
7154 
7155         seq_printf(seq, " speed=%ldK/sec", db/2/dt);
7156 }
7157 
7158 static void *md_seq_start(struct seq_file *seq, loff_t *pos)
7159 {
7160         struct list_head *tmp;
7161         loff_t l = *pos;
7162         struct mddev *mddev;
7163 
7164         if (l >= 0x10000)
7165                 return NULL;
7166         if (!l--)
7167                 /* header */
7168                 return (void*)1;
7169 
7170         spin_lock(&all_mddevs_lock);
7171         list_for_each(tmp,&all_mddevs)
7172                 if (!l--) {
7173                         mddev = list_entry(tmp, struct mddev, all_mddevs);
7174                         mddev_get(mddev);
7175                         spin_unlock(&all_mddevs_lock);
7176                         return mddev;
7177                 }
7178         spin_unlock(&all_mddevs_lock);
7179         if (!l--)
7180                 return (void*)2;/* tail */
7181         return NULL;
7182 }
7183 
7184 static void *md_seq_next(struct seq_file *seq, void *v, loff_t *pos)
7185 {
7186         struct list_head *tmp;
7187         struct mddev *next_mddev, *mddev = v;
7188 
7189         ++*pos;
7190         if (v == (void*)2)
7191                 return NULL;
7192 
7193         spin_lock(&all_mddevs_lock);
7194         if (v == (void*)1)
7195                 tmp = all_mddevs.next;
7196         else
7197                 tmp = mddev->all_mddevs.next;
7198         if (tmp != &all_mddevs)
7199                 next_mddev = mddev_get(list_entry(tmp,struct mddev,all_mddevs));
7200         else {
7201                 next_mddev = (void*)2;
7202                 *pos = 0x10000;
7203         }
7204         spin_unlock(&all_mddevs_lock);
7205 
7206         if (v != (void*)1)
7207                 mddev_put(mddev);
7208         return next_mddev;
7209 
7210 }
7211 
7212 static void md_seq_stop(struct seq_file *seq, void *v)
7213 {
7214         struct mddev *mddev = v;
7215 
7216         if (mddev && v != (void*)1 && v != (void*)2)
7217                 mddev_put(mddev);
7218 }
7219 
7220 static int md_seq_show(struct seq_file *seq, void *v)
7221 {
7222         struct mddev *mddev = v;
7223         sector_t sectors;
7224         struct md_rdev *rdev;
7225 
7226         if (v == (void*)1) {
7227                 struct md_personality *pers;
7228                 seq_printf(seq, "Personalities : ");
7229                 spin_lock(&pers_lock);
7230                 list_for_each_entry(pers, &pers_list, list)
7231                         seq_printf(seq, "[%s] ", pers->name);
7232 
7233                 spin_unlock(&pers_lock);
7234                 seq_printf(seq, "\n");
7235                 seq->poll_event = atomic_read(&md_event_count);
7236                 return 0;
7237         }
7238         if (v == (void*)2) {
7239                 status_unused(seq);
7240                 return 0;
7241         }
7242 
7243         spin_lock(&mddev->lock);
7244         if (mddev->pers || mddev->raid_disks || !list_empty(&mddev->disks)) {
7245                 seq_printf(seq, "%s : %sactive", mdname(mddev),
7246                                                 mddev->pers ? "" : "in");
7247                 if (mddev->pers) {
7248                         if (mddev->ro==1)
7249                                 seq_printf(seq, " (read-only)");
7250                         if (mddev->ro==2)
7251                                 seq_printf(seq, " (auto-read-only)");
7252                         seq_printf(seq, " %s", mddev->pers->name);
7253                 }
7254 
7255                 sectors = 0;
7256                 rcu_read_lock();
7257                 rdev_for_each_rcu(rdev, mddev) {
7258                         char b[BDEVNAME_SIZE];
7259                         seq_printf(seq, " %s[%d]",
7260                                 bdevname(rdev->bdev,b), rdev->desc_nr);
7261                         if (test_bit(WriteMostly, &rdev->flags))
7262                                 seq_printf(seq, "(W)");
7263                         if (test_bit(Faulty, &rdev->flags)) {
7264                                 seq_printf(seq, "(F)");
7265                                 continue;
7266                         }
7267                         if (rdev->raid_disk < 0)
7268                                 seq_printf(seq, "(S)"); /* spare */
7269                         if (test_bit(Replacement, &rdev->flags))
7270                                 seq_printf(seq, "(R)");
7271                         sectors += rdev->sectors;
7272                 }
7273                 rcu_read_unlock();
7274 
7275                 if (!list_empty(&mddev->disks)) {
7276                         if (mddev->pers)
7277                                 seq_printf(seq, "\n      %llu blocks",
7278                                            (unsigned long long)
7279                                            mddev->array_sectors / 2);
7280                         else
7281                                 seq_printf(seq, "\n      %llu blocks",
7282                                            (unsigned long long)sectors / 2);
7283                 }
7284                 if (mddev->persistent) {
7285                         if (mddev->major_version != 0 ||
7286                             mddev->minor_version != 90) {
7287                                 seq_printf(seq," super %d.%d",
7288                                            mddev->major_version,
7289                                            mddev->minor_version);
7290                         }
7291                 } else if (mddev->external)
7292                         seq_printf(seq, " super external:%s",
7293                                    mddev->metadata_type);
7294                 else
7295                         seq_printf(seq, " super non-persistent");
7296 
7297                 if (mddev->pers) {
7298                         mddev->pers->status(seq, mddev);
7299                         seq_printf(seq, "\n      ");
7300                         if (mddev->pers->sync_request) {
7301                                 if (mddev->curr_resync > 2) {
7302                                         status_resync(seq, mddev);
7303                                         seq_printf(seq, "\n      ");
7304                                 } else if (mddev->curr_resync >= 1)
7305                                         seq_printf(seq, "\tresync=DELAYED\n      ");
7306                                 else if (mddev->recovery_cp < MaxSector)
7307                                         seq_printf(seq, "\tresync=PENDING\n      ");
7308                         }
7309                 } else
7310                         seq_printf(seq, "\n       ");
7311 
7312                 bitmap_status(seq, mddev->bitmap);
7313 
7314                 seq_printf(seq, "\n");
7315         }
7316         spin_unlock(&mddev->lock);
7317 
7318         return 0;
7319 }
7320 
7321 static const struct seq_operations md_seq_ops = {
7322         .start  = md_seq_start,
7323         .next   = md_seq_next,
7324         .stop   = md_seq_stop,
7325         .show   = md_seq_show,
7326 };
7327 
7328 static int md_seq_open(struct inode *inode, struct file *file)
7329 {
7330         struct seq_file *seq;
7331         int error;
7332 
7333         error = seq_open(file, &md_seq_ops);
7334         if (error)
7335                 return error;
7336 
7337         seq = file->private_data;
7338         seq->poll_event = atomic_read(&md_event_count);
7339         return error;
7340 }
7341 
7342 static int md_unloading;
7343 static unsigned int mdstat_poll(struct file *filp, poll_table *wait)
7344 {
7345         struct seq_file *seq = filp->private_data;
7346         int mask;
7347 
7348         if (md_unloading)
7349                 return POLLIN|POLLRDNORM|POLLERR|POLLPRI;
7350         poll_wait(filp, &md_event_waiters, wait);
7351 
7352         /* always allow read */
7353         mask = POLLIN | POLLRDNORM;
7354 
7355         if (seq->poll_event != atomic_read(&md_event_count))
7356                 mask |= POLLERR | POLLPRI;
7357         return mask;
7358 }
7359 
7360 static const struct file_operations md_seq_fops = {
7361         .owner          = THIS_MODULE,
7362         .open           = md_seq_open,
7363         .read           = seq_read,
7364         .llseek         = seq_lseek,
7365         .release        = seq_release_private,
7366         .poll           = mdstat_poll,
7367 };
7368 
7369 int register_md_personality(struct md_personality *p)
7370 {
7371         printk(KERN_INFO "md: %s personality registered for level %d\n",
7372                                                 p->name, p->level);
7373         spin_lock(&pers_lock);
7374         list_add_tail(&p->list, &pers_list);
7375         spin_unlock(&pers_lock);
7376         return 0;
7377 }
7378 EXPORT_SYMBOL(register_md_personality);
7379 
7380 int unregister_md_personality(struct md_personality *p)
7381 {
7382         printk(KERN_INFO "md: %s personality unregistered\n", p->name);
7383         spin_lock(&pers_lock);
7384         list_del_init(&p->list);
7385         spin_unlock(&pers_lock);
7386         return 0;
7387 }
7388 EXPORT_SYMBOL(unregister_md_personality);
7389 
7390 int register_md_cluster_operations(struct md_cluster_operations *ops, struct module *module)
7391 {
7392         if (md_cluster_ops != NULL)
7393                 return -EALREADY;
7394         spin_lock(&pers_lock);
7395         md_cluster_ops = ops;
7396         md_cluster_mod = module;
7397         spin_unlock(&pers_lock);
7398         return 0;
7399 }
7400 EXPORT_SYMBOL(register_md_cluster_operations);
7401 
7402 int unregister_md_cluster_operations(void)
7403 {
7404         spin_lock(&pers_lock);
7405         md_cluster_ops = NULL;
7406         spin_unlock(&pers_lock);
7407         return 0;
7408 }
7409 EXPORT_SYMBOL(unregister_md_cluster_operations);
7410 
7411 int md_setup_cluster(struct mddev *mddev, int nodes)
7412 {
7413         int err;
7414 
7415         err = request_module("md-cluster");
7416         if (err) {
7417                 pr_err("md-cluster module not found.\n");
7418                 return err;
7419         }
7420 
7421         spin_lock(&pers_lock);
7422         if (!md_cluster_ops || !try_module_get(md_cluster_mod)) {
7423                 spin_unlock(&pers_lock);
7424                 return -ENOENT;
7425         }
7426         spin_unlock(&pers_lock);
7427 
7428         return md_cluster_ops->join(mddev, nodes);
7429 }
7430 
7431 void md_cluster_stop(struct mddev *mddev)
7432 {
7433         if (!md_cluster_ops)
7434                 return;
7435         md_cluster_ops->leave(mddev);
7436         module_put(md_cluster_mod);
7437 }
7438 
7439 static int is_mddev_idle(struct mddev *mddev, int init)
7440 {
7441         struct md_rdev *rdev;
7442         int idle;
7443         int curr_events;
7444 
7445         idle = 1;
7446         rcu_read_lock();
7447         rdev_for_each_rcu(rdev, mddev) {
7448                 struct gendisk *disk = rdev->bdev->bd_contains->bd_disk;
7449                 curr_events = (int)part_stat_read(&disk->part0, sectors[0]) +
7450                               (int)part_stat_read(&disk->part0, sectors[1]) -
7451                               atomic_read(&disk->sync_io);
7452                 /* sync IO will cause sync_io to increase before the disk_stats
7453                  * as sync_io is counted when a request starts, and
7454                  * disk_stats is counted when it completes.
7455                  * So resync activity will cause curr_events to be smaller than
7456                  * when there was no such activity.
7457                  * non-sync IO will cause disk_stat to increase without
7458                  * increasing sync_io so curr_events will (eventually)
7459                  * be larger than it was before.  Once it becomes
7460                  * substantially larger, the test below will cause
7461                  * the array to appear non-idle, and resync will slow
7462                  * down.
7463                  * If there is a lot of outstanding resync activity when
7464                  * we set last_event to curr_events, then all that activity
7465                  * completing might cause the array to appear non-idle
7466                  * and resync will be slowed down even though there might
7467                  * not have been non-resync activity.  This will only
7468                  * happen once though.  'last_events' will soon reflect
7469                  * the state where there is little or no outstanding
7470                  * resync requests, and further resync activity will
7471                  * always make curr_events less than last_events.
7472                  *
7473                  */
7474                 if (init || curr_events - rdev->last_events > 64) {
7475                         rdev->last_events = curr_events;
7476                         idle = 0;
7477                 }
7478         }
7479         rcu_read_unlock();
7480         return idle;
7481 }
7482 
7483 void md_done_sync(struct mddev *mddev, int blocks, int ok)
7484 {
7485         /* another "blocks" (512byte) blocks have been synced */
7486         atomic_sub(blocks, &mddev->recovery_active);
7487         wake_up(&mddev->recovery_wait);
7488         if (!ok) {
7489                 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
7490                 set_bit(MD_RECOVERY_ERROR, &mddev->recovery);
7491                 md_wakeup_thread(mddev->thread);
7492                 // stop recovery, signal do_sync ....
7493         }
7494 }
7495 EXPORT_SYMBOL(md_done_sync);
7496 
7497 /* md_write_start(mddev, bi)
7498  * If we need to update some array metadata (e.g. 'active' flag
7499  * in superblock) before writing, schedule a superblock update
7500  * and wait for it to complete.
7501  */
7502 void md_write_start(struct mddev *mddev, struct bio *bi)
7503 {
7504         int did_change = 0;
7505         if (bio_data_dir(bi) != WRITE)
7506                 return;
7507 
7508         BUG_ON(mddev->ro == 1);
7509         if (mddev->ro == 2) {
7510                 /* need to switch to read/write */
7511                 mddev->ro = 0;
7512                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7513                 md_wakeup_thread(mddev->thread);
7514                 md_wakeup_thread(mddev->sync_thread);
7515                 did_change = 1;
7516         }
7517         atomic_inc(&mddev->writes_pending);
7518         if (mddev->safemode == 1)
7519                 mddev->safemode = 0;
7520         if (mddev->in_sync) {
7521                 spin_lock(&mddev->lock);
7522