Version:  2.0.40 2.2.26 2.4.37 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 4.2 4.3 4.4

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