2 * raid5.c : Multiple Devices driver for Linux
3 * Copyright (C) 1996, 1997 Ingo Molnar, Miguel de Icaza, Gadi Oxman
4 * Copyright (C) 1999, 2000 Ingo Molnar
5 * Copyright (C) 2002, 2003 H. Peter Anvin
7 * RAID-4/5/6 management functions.
8 * Thanks to Penguin Computing for making the RAID-6 development possible
9 * by donating a test server!
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2, or (at your option)
16 * You should have received a copy of the GNU General Public License
17 * (for example /usr/src/linux/COPYING); if not, write to the Free
18 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 * The sequencing for updating the bitmap reliably is a little
25 * subtle (and I got it wrong the first time) so it deserves some
28 * We group bitmap updates into batches. Each batch has a number.
29 * We may write out several batches at once, but that isn't very important.
30 * conf->seq_write is the number of the last batch successfully written.
31 * conf->seq_flush is the number of the last batch that was closed to
33 * When we discover that we will need to write to any block in a stripe
34 * (in add_stripe_bio) we update the in-memory bitmap and record in sh->bm_seq
35 * the number of the batch it will be in. This is seq_flush+1.
36 * When we are ready to do a write, if that batch hasn't been written yet,
37 * we plug the array and queue the stripe for later.
38 * When an unplug happens, we increment bm_flush, thus closing the current
40 * When we notice that bm_flush > bm_write, we write out all pending updates
41 * to the bitmap, and advance bm_write to where bm_flush was.
42 * This may occasionally write a bit out twice, but is sure never to
46 #include <linux/blkdev.h>
47 #include <linux/kthread.h>
48 #include <linux/raid/pq.h>
49 #include <linux/async_tx.h>
50 #include <linux/module.h>
51 #include <linux/async.h>
52 #include <linux/seq_file.h>
53 #include <linux/cpu.h>
54 #include <linux/slab.h>
55 #include <linux/ratelimit.h>
56 #include <linux/nodemask.h>
57 #include <linux/flex_array.h>
58 #include <trace/events/block.h>
65 #define cpu_to_group(cpu) cpu_to_node(cpu)
66 #define ANY_GROUP NUMA_NO_NODE
68 static bool devices_handle_discard_safely = false;
69 module_param(devices_handle_discard_safely, bool, 0644);
70 MODULE_PARM_DESC(devices_handle_discard_safely,
71 "Set to Y if all devices in each array reliably return zeroes on reads from discarded regions");
72 static struct workqueue_struct *raid5_wq;
77 #define NR_STRIPES 256
78 #define STRIPE_SIZE PAGE_SIZE
79 #define STRIPE_SHIFT (PAGE_SHIFT - 9)
80 #define STRIPE_SECTORS (STRIPE_SIZE>>9)
81 #define IO_THRESHOLD 1
82 #define BYPASS_THRESHOLD 1
83 #define NR_HASH (PAGE_SIZE / sizeof(struct hlist_head))
84 #define HASH_MASK (NR_HASH - 1)
85 #define MAX_STRIPE_BATCH 8
87 static inline struct hlist_head *stripe_hash(struct r5conf *conf, sector_t sect)
89 int hash = (sect >> STRIPE_SHIFT) & HASH_MASK;
90 return &conf->stripe_hashtbl[hash];
93 static inline int stripe_hash_locks_hash(sector_t sect)
95 return (sect >> STRIPE_SHIFT) & STRIPE_HASH_LOCKS_MASK;
98 static inline void lock_device_hash_lock(struct r5conf *conf, int hash)
100 spin_lock_irq(conf->hash_locks + hash);
101 spin_lock(&conf->device_lock);
104 static inline void unlock_device_hash_lock(struct r5conf *conf, int hash)
106 spin_unlock(&conf->device_lock);
107 spin_unlock_irq(conf->hash_locks + hash);
110 static inline void lock_all_device_hash_locks_irq(struct r5conf *conf)
113 spin_lock_irq(conf->hash_locks);
114 for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
115 spin_lock_nest_lock(conf->hash_locks + i, conf->hash_locks);
116 spin_lock(&conf->device_lock);
119 static inline void unlock_all_device_hash_locks_irq(struct r5conf *conf)
122 spin_unlock(&conf->device_lock);
123 for (i = NR_STRIPE_HASH_LOCKS - 1; i; i--)
124 spin_unlock(conf->hash_locks + i);
125 spin_unlock_irq(conf->hash_locks);
128 /* bio's attached to a stripe+device for I/O are linked together in bi_sector
129 * order without overlap. There may be several bio's per stripe+device, and
130 * a bio could span several devices.
131 * When walking this list for a particular stripe+device, we must never proceed
132 * beyond a bio that extends past this device, as the next bio might no longer
134 * This function is used to determine the 'next' bio in the list, given the sector
135 * of the current stripe+device
137 static inline struct bio *r5_next_bio(struct bio *bio, sector_t sector)
139 int sectors = bio_sectors(bio);
140 if (bio->bi_iter.bi_sector + sectors < sector + STRIPE_SECTORS)
147 * We maintain a biased count of active stripes in the bottom 16 bits of
148 * bi_phys_segments, and a count of processed stripes in the upper 16 bits
150 static inline int raid5_bi_processed_stripes(struct bio *bio)
152 atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
153 return (atomic_read(segments) >> 16) & 0xffff;
156 static inline int raid5_dec_bi_active_stripes(struct bio *bio)
158 atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
159 return atomic_sub_return(1, segments) & 0xffff;
162 static inline void raid5_inc_bi_active_stripes(struct bio *bio)
164 atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
165 atomic_inc(segments);
168 static inline void raid5_set_bi_processed_stripes(struct bio *bio,
171 atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
175 old = atomic_read(segments);
176 new = (old & 0xffff) | (cnt << 16);
177 } while (atomic_cmpxchg(segments, old, new) != old);
180 static inline void raid5_set_bi_stripes(struct bio *bio, unsigned int cnt)
182 atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
183 atomic_set(segments, cnt);
186 /* Find first data disk in a raid6 stripe */
187 static inline int raid6_d0(struct stripe_head *sh)
190 /* ddf always start from first device */
192 /* md starts just after Q block */
193 if (sh->qd_idx == sh->disks - 1)
196 return sh->qd_idx + 1;
198 static inline int raid6_next_disk(int disk, int raid_disks)
201 return (disk < raid_disks) ? disk : 0;
204 /* When walking through the disks in a raid5, starting at raid6_d0,
205 * We need to map each disk to a 'slot', where the data disks are slot
206 * 0 .. raid_disks-3, the parity disk is raid_disks-2 and the Q disk
207 * is raid_disks-1. This help does that mapping.
209 static int raid6_idx_to_slot(int idx, struct stripe_head *sh,
210 int *count, int syndrome_disks)
216 if (idx == sh->pd_idx)
217 return syndrome_disks;
218 if (idx == sh->qd_idx)
219 return syndrome_disks + 1;
225 static void return_io(struct bio_list *return_bi)
228 while ((bi = bio_list_pop(return_bi)) != NULL) {
229 bi->bi_iter.bi_size = 0;
230 trace_block_bio_complete(bdev_get_queue(bi->bi_bdev),
236 static void print_raid5_conf (struct r5conf *conf);
238 static int stripe_operations_active(struct stripe_head *sh)
240 return sh->check_state || sh->reconstruct_state ||
241 test_bit(STRIPE_BIOFILL_RUN, &sh->state) ||
242 test_bit(STRIPE_COMPUTE_RUN, &sh->state);
245 static void raid5_wakeup_stripe_thread(struct stripe_head *sh)
247 struct r5conf *conf = sh->raid_conf;
248 struct r5worker_group *group;
250 int i, cpu = sh->cpu;
252 if (!cpu_online(cpu)) {
253 cpu = cpumask_any(cpu_online_mask);
257 if (list_empty(&sh->lru)) {
258 struct r5worker_group *group;
259 group = conf->worker_groups + cpu_to_group(cpu);
260 list_add_tail(&sh->lru, &group->handle_list);
261 group->stripes_cnt++;
265 if (conf->worker_cnt_per_group == 0) {
266 md_wakeup_thread(conf->mddev->thread);
270 group = conf->worker_groups + cpu_to_group(sh->cpu);
272 group->workers[0].working = true;
273 /* at least one worker should run to avoid race */
274 queue_work_on(sh->cpu, raid5_wq, &group->workers[0].work);
276 thread_cnt = group->stripes_cnt / MAX_STRIPE_BATCH - 1;
277 /* wakeup more workers */
278 for (i = 1; i < conf->worker_cnt_per_group && thread_cnt > 0; i++) {
279 if (group->workers[i].working == false) {
280 group->workers[i].working = true;
281 queue_work_on(sh->cpu, raid5_wq,
282 &group->workers[i].work);
288 static void do_release_stripe(struct r5conf *conf, struct stripe_head *sh,
289 struct list_head *temp_inactive_list)
291 BUG_ON(!list_empty(&sh->lru));
292 BUG_ON(atomic_read(&conf->active_stripes)==0);
293 if (test_bit(STRIPE_HANDLE, &sh->state)) {
294 if (test_bit(STRIPE_DELAYED, &sh->state) &&
295 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
296 list_add_tail(&sh->lru, &conf->delayed_list);
297 else if (test_bit(STRIPE_BIT_DELAY, &sh->state) &&
298 sh->bm_seq - conf->seq_write > 0)
299 list_add_tail(&sh->lru, &conf->bitmap_list);
301 clear_bit(STRIPE_DELAYED, &sh->state);
302 clear_bit(STRIPE_BIT_DELAY, &sh->state);
303 if (conf->worker_cnt_per_group == 0) {
304 list_add_tail(&sh->lru, &conf->handle_list);
306 raid5_wakeup_stripe_thread(sh);
310 md_wakeup_thread(conf->mddev->thread);
312 BUG_ON(stripe_operations_active(sh));
313 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
314 if (atomic_dec_return(&conf->preread_active_stripes)
316 md_wakeup_thread(conf->mddev->thread);
317 atomic_dec(&conf->active_stripes);
318 if (!test_bit(STRIPE_EXPANDING, &sh->state))
319 list_add_tail(&sh->lru, temp_inactive_list);
323 static void __release_stripe(struct r5conf *conf, struct stripe_head *sh,
324 struct list_head *temp_inactive_list)
326 if (atomic_dec_and_test(&sh->count))
327 do_release_stripe(conf, sh, temp_inactive_list);
331 * @hash could be NR_STRIPE_HASH_LOCKS, then we have a list of inactive_list
333 * Be careful: Only one task can add/delete stripes from temp_inactive_list at
334 * given time. Adding stripes only takes device lock, while deleting stripes
335 * only takes hash lock.
337 static void release_inactive_stripe_list(struct r5conf *conf,
338 struct list_head *temp_inactive_list,
342 bool do_wakeup = false;
345 if (hash == NR_STRIPE_HASH_LOCKS) {
346 size = NR_STRIPE_HASH_LOCKS;
347 hash = NR_STRIPE_HASH_LOCKS - 1;
351 struct list_head *list = &temp_inactive_list[size - 1];
354 * We don't hold any lock here yet, raid5_get_active_stripe() might
355 * remove stripes from the list
357 if (!list_empty_careful(list)) {
358 spin_lock_irqsave(conf->hash_locks + hash, flags);
359 if (list_empty(conf->inactive_list + hash) &&
361 atomic_dec(&conf->empty_inactive_list_nr);
362 list_splice_tail_init(list, conf->inactive_list + hash);
364 spin_unlock_irqrestore(conf->hash_locks + hash, flags);
371 wake_up(&conf->wait_for_stripe);
372 if (atomic_read(&conf->active_stripes) == 0)
373 wake_up(&conf->wait_for_quiescent);
374 if (conf->retry_read_aligned)
375 md_wakeup_thread(conf->mddev->thread);
379 /* should hold conf->device_lock already */
380 static int release_stripe_list(struct r5conf *conf,
381 struct list_head *temp_inactive_list)
383 struct stripe_head *sh;
385 struct llist_node *head;
387 head = llist_del_all(&conf->released_stripes);
388 head = llist_reverse_order(head);
392 sh = llist_entry(head, struct stripe_head, release_list);
393 head = llist_next(head);
394 /* sh could be readded after STRIPE_ON_RELEASE_LIST is cleard */
396 clear_bit(STRIPE_ON_RELEASE_LIST, &sh->state);
398 * Don't worry the bit is set here, because if the bit is set
399 * again, the count is always > 1. This is true for
400 * STRIPE_ON_UNPLUG_LIST bit too.
402 hash = sh->hash_lock_index;
403 __release_stripe(conf, sh, &temp_inactive_list[hash]);
410 void raid5_release_stripe(struct stripe_head *sh)
412 struct r5conf *conf = sh->raid_conf;
414 struct list_head list;
418 /* Avoid release_list until the last reference.
420 if (atomic_add_unless(&sh->count, -1, 1))
423 if (unlikely(!conf->mddev->thread) ||
424 test_and_set_bit(STRIPE_ON_RELEASE_LIST, &sh->state))
426 wakeup = llist_add(&sh->release_list, &conf->released_stripes);
428 md_wakeup_thread(conf->mddev->thread);
431 local_irq_save(flags);
432 /* we are ok here if STRIPE_ON_RELEASE_LIST is set or not */
433 if (atomic_dec_and_lock(&sh->count, &conf->device_lock)) {
434 INIT_LIST_HEAD(&list);
435 hash = sh->hash_lock_index;
436 do_release_stripe(conf, sh, &list);
437 spin_unlock(&conf->device_lock);
438 release_inactive_stripe_list(conf, &list, hash);
440 local_irq_restore(flags);
443 static inline void remove_hash(struct stripe_head *sh)
445 pr_debug("remove_hash(), stripe %llu\n",
446 (unsigned long long)sh->sector);
448 hlist_del_init(&sh->hash);
451 static inline void insert_hash(struct r5conf *conf, struct stripe_head *sh)
453 struct hlist_head *hp = stripe_hash(conf, sh->sector);
455 pr_debug("insert_hash(), stripe %llu\n",
456 (unsigned long long)sh->sector);
458 hlist_add_head(&sh->hash, hp);
461 /* find an idle stripe, make sure it is unhashed, and return it. */
462 static struct stripe_head *get_free_stripe(struct r5conf *conf, int hash)
464 struct stripe_head *sh = NULL;
465 struct list_head *first;
467 if (list_empty(conf->inactive_list + hash))
469 first = (conf->inactive_list + hash)->next;
470 sh = list_entry(first, struct stripe_head, lru);
471 list_del_init(first);
473 atomic_inc(&conf->active_stripes);
474 BUG_ON(hash != sh->hash_lock_index);
475 if (list_empty(conf->inactive_list + hash))
476 atomic_inc(&conf->empty_inactive_list_nr);
481 static void shrink_buffers(struct stripe_head *sh)
485 int num = sh->raid_conf->pool_size;
487 for (i = 0; i < num ; i++) {
488 WARN_ON(sh->dev[i].page != sh->dev[i].orig_page);
492 sh->dev[i].page = NULL;
497 static int grow_buffers(struct stripe_head *sh, gfp_t gfp)
500 int num = sh->raid_conf->pool_size;
502 for (i = 0; i < num; i++) {
505 if (!(page = alloc_page(gfp))) {
508 sh->dev[i].page = page;
509 sh->dev[i].orig_page = page;
514 static void raid5_build_block(struct stripe_head *sh, int i, int previous);
515 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
516 struct stripe_head *sh);
518 static void init_stripe(struct stripe_head *sh, sector_t sector, int previous)
520 struct r5conf *conf = sh->raid_conf;
523 BUG_ON(atomic_read(&sh->count) != 0);
524 BUG_ON(test_bit(STRIPE_HANDLE, &sh->state));
525 BUG_ON(stripe_operations_active(sh));
526 BUG_ON(sh->batch_head);
528 pr_debug("init_stripe called, stripe %llu\n",
529 (unsigned long long)sector);
531 seq = read_seqcount_begin(&conf->gen_lock);
532 sh->generation = conf->generation - previous;
533 sh->disks = previous ? conf->previous_raid_disks : conf->raid_disks;
535 stripe_set_idx(sector, conf, previous, sh);
538 for (i = sh->disks; i--; ) {
539 struct r5dev *dev = &sh->dev[i];
541 if (dev->toread || dev->read || dev->towrite || dev->written ||
542 test_bit(R5_LOCKED, &dev->flags)) {
543 printk(KERN_ERR "sector=%llx i=%d %p %p %p %p %d\n",
544 (unsigned long long)sh->sector, i, dev->toread,
545 dev->read, dev->towrite, dev->written,
546 test_bit(R5_LOCKED, &dev->flags));
550 raid5_build_block(sh, i, previous);
552 if (read_seqcount_retry(&conf->gen_lock, seq))
554 sh->overwrite_disks = 0;
555 insert_hash(conf, sh);
556 sh->cpu = smp_processor_id();
557 set_bit(STRIPE_BATCH_READY, &sh->state);
560 static struct stripe_head *__find_stripe(struct r5conf *conf, sector_t sector,
563 struct stripe_head *sh;
565 pr_debug("__find_stripe, sector %llu\n", (unsigned long long)sector);
566 hlist_for_each_entry(sh, stripe_hash(conf, sector), hash)
567 if (sh->sector == sector && sh->generation == generation)
569 pr_debug("__stripe %llu not in cache\n", (unsigned long long)sector);
574 * Need to check if array has failed when deciding whether to:
576 * - remove non-faulty devices
579 * This determination is simple when no reshape is happening.
580 * However if there is a reshape, we need to carefully check
581 * both the before and after sections.
582 * This is because some failed devices may only affect one
583 * of the two sections, and some non-in_sync devices may
584 * be insync in the section most affected by failed devices.
586 static int calc_degraded(struct r5conf *conf)
588 int degraded, degraded2;
593 for (i = 0; i < conf->previous_raid_disks; i++) {
594 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
595 if (rdev && test_bit(Faulty, &rdev->flags))
596 rdev = rcu_dereference(conf->disks[i].replacement);
597 if (!rdev || test_bit(Faulty, &rdev->flags))
599 else if (test_bit(In_sync, &rdev->flags))
602 /* not in-sync or faulty.
603 * If the reshape increases the number of devices,
604 * this is being recovered by the reshape, so
605 * this 'previous' section is not in_sync.
606 * If the number of devices is being reduced however,
607 * the device can only be part of the array if
608 * we are reverting a reshape, so this section will
611 if (conf->raid_disks >= conf->previous_raid_disks)
615 if (conf->raid_disks == conf->previous_raid_disks)
619 for (i = 0; i < conf->raid_disks; i++) {
620 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
621 if (rdev && test_bit(Faulty, &rdev->flags))
622 rdev = rcu_dereference(conf->disks[i].replacement);
623 if (!rdev || test_bit(Faulty, &rdev->flags))
625 else if (test_bit(In_sync, &rdev->flags))
628 /* not in-sync or faulty.
629 * If reshape increases the number of devices, this
630 * section has already been recovered, else it
631 * almost certainly hasn't.
633 if (conf->raid_disks <= conf->previous_raid_disks)
637 if (degraded2 > degraded)
642 static int has_failed(struct r5conf *conf)
646 if (conf->mddev->reshape_position == MaxSector)
647 return conf->mddev->degraded > conf->max_degraded;
649 degraded = calc_degraded(conf);
650 if (degraded > conf->max_degraded)
656 raid5_get_active_stripe(struct r5conf *conf, sector_t sector,
657 int previous, int noblock, int noquiesce)
659 struct stripe_head *sh;
660 int hash = stripe_hash_locks_hash(sector);
662 pr_debug("get_stripe, sector %llu\n", (unsigned long long)sector);
664 spin_lock_irq(conf->hash_locks + hash);
667 wait_event_lock_irq(conf->wait_for_quiescent,
668 conf->quiesce == 0 || noquiesce,
669 *(conf->hash_locks + hash));
670 sh = __find_stripe(conf, sector, conf->generation - previous);
672 if (!test_bit(R5_INACTIVE_BLOCKED, &conf->cache_state)) {
673 sh = get_free_stripe(conf, hash);
674 if (!sh && !test_bit(R5_DID_ALLOC,
676 set_bit(R5_ALLOC_MORE,
679 if (noblock && sh == NULL)
682 set_bit(R5_INACTIVE_BLOCKED,
685 conf->wait_for_stripe,
686 !list_empty(conf->inactive_list + hash) &&
687 (atomic_read(&conf->active_stripes)
688 < (conf->max_nr_stripes * 3 / 4)
689 || !test_bit(R5_INACTIVE_BLOCKED,
690 &conf->cache_state)),
691 *(conf->hash_locks + hash));
692 clear_bit(R5_INACTIVE_BLOCKED,
695 init_stripe(sh, sector, previous);
696 atomic_inc(&sh->count);
698 } else if (!atomic_inc_not_zero(&sh->count)) {
699 spin_lock(&conf->device_lock);
700 if (!atomic_read(&sh->count)) {
701 if (!test_bit(STRIPE_HANDLE, &sh->state))
702 atomic_inc(&conf->active_stripes);
703 BUG_ON(list_empty(&sh->lru) &&
704 !test_bit(STRIPE_EXPANDING, &sh->state));
705 list_del_init(&sh->lru);
707 sh->group->stripes_cnt--;
711 atomic_inc(&sh->count);
712 spin_unlock(&conf->device_lock);
714 } while (sh == NULL);
716 spin_unlock_irq(conf->hash_locks + hash);
720 static bool is_full_stripe_write(struct stripe_head *sh)
722 BUG_ON(sh->overwrite_disks > (sh->disks - sh->raid_conf->max_degraded));
723 return sh->overwrite_disks == (sh->disks - sh->raid_conf->max_degraded);
726 static void lock_two_stripes(struct stripe_head *sh1, struct stripe_head *sh2)
729 spin_lock_irq(&sh2->stripe_lock);
730 spin_lock_nested(&sh1->stripe_lock, 1);
732 spin_lock_irq(&sh1->stripe_lock);
733 spin_lock_nested(&sh2->stripe_lock, 1);
737 static void unlock_two_stripes(struct stripe_head *sh1, struct stripe_head *sh2)
739 spin_unlock(&sh1->stripe_lock);
740 spin_unlock_irq(&sh2->stripe_lock);
743 /* Only freshly new full stripe normal write stripe can be added to a batch list */
744 static bool stripe_can_batch(struct stripe_head *sh)
746 struct r5conf *conf = sh->raid_conf;
750 return test_bit(STRIPE_BATCH_READY, &sh->state) &&
751 !test_bit(STRIPE_BITMAP_PENDING, &sh->state) &&
752 is_full_stripe_write(sh);
755 /* we only do back search */
756 static void stripe_add_to_batch_list(struct r5conf *conf, struct stripe_head *sh)
758 struct stripe_head *head;
759 sector_t head_sector, tmp_sec;
763 if (!stripe_can_batch(sh))
765 /* Don't cross chunks, so stripe pd_idx/qd_idx is the same */
766 tmp_sec = sh->sector;
767 if (!sector_div(tmp_sec, conf->chunk_sectors))
769 head_sector = sh->sector - STRIPE_SECTORS;
771 hash = stripe_hash_locks_hash(head_sector);
772 spin_lock_irq(conf->hash_locks + hash);
773 head = __find_stripe(conf, head_sector, conf->generation);
774 if (head && !atomic_inc_not_zero(&head->count)) {
775 spin_lock(&conf->device_lock);
776 if (!atomic_read(&head->count)) {
777 if (!test_bit(STRIPE_HANDLE, &head->state))
778 atomic_inc(&conf->active_stripes);
779 BUG_ON(list_empty(&head->lru) &&
780 !test_bit(STRIPE_EXPANDING, &head->state));
781 list_del_init(&head->lru);
783 head->group->stripes_cnt--;
787 atomic_inc(&head->count);
788 spin_unlock(&conf->device_lock);
790 spin_unlock_irq(conf->hash_locks + hash);
794 if (!stripe_can_batch(head))
797 lock_two_stripes(head, sh);
798 /* clear_batch_ready clear the flag */
799 if (!stripe_can_batch(head) || !stripe_can_batch(sh))
806 while (dd_idx == sh->pd_idx || dd_idx == sh->qd_idx)
808 if (head->dev[dd_idx].towrite->bi_rw != sh->dev[dd_idx].towrite->bi_rw)
811 if (head->batch_head) {
812 spin_lock(&head->batch_head->batch_lock);
813 /* This batch list is already running */
814 if (!stripe_can_batch(head)) {
815 spin_unlock(&head->batch_head->batch_lock);
819 * We must assign batch_head of this stripe within the
820 * batch_lock, otherwise clear_batch_ready of batch head
821 * stripe could clear BATCH_READY bit of this stripe and
822 * this stripe->batch_head doesn't get assigned, which
823 * could confuse clear_batch_ready for this stripe
825 sh->batch_head = head->batch_head;
828 * at this point, head's BATCH_READY could be cleared, but we
829 * can still add the stripe to batch list
831 list_add(&sh->batch_list, &head->batch_list);
832 spin_unlock(&head->batch_head->batch_lock);
834 head->batch_head = head;
835 sh->batch_head = head->batch_head;
836 spin_lock(&head->batch_lock);
837 list_add_tail(&sh->batch_list, &head->batch_list);
838 spin_unlock(&head->batch_lock);
841 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
842 if (atomic_dec_return(&conf->preread_active_stripes)
844 md_wakeup_thread(conf->mddev->thread);
846 if (test_and_clear_bit(STRIPE_BIT_DELAY, &sh->state)) {
847 int seq = sh->bm_seq;
848 if (test_bit(STRIPE_BIT_DELAY, &sh->batch_head->state) &&
849 sh->batch_head->bm_seq > seq)
850 seq = sh->batch_head->bm_seq;
851 set_bit(STRIPE_BIT_DELAY, &sh->batch_head->state);
852 sh->batch_head->bm_seq = seq;
855 atomic_inc(&sh->count);
857 unlock_two_stripes(head, sh);
859 raid5_release_stripe(head);
862 /* Determine if 'data_offset' or 'new_data_offset' should be used
863 * in this stripe_head.
865 static int use_new_offset(struct r5conf *conf, struct stripe_head *sh)
867 sector_t progress = conf->reshape_progress;
868 /* Need a memory barrier to make sure we see the value
869 * of conf->generation, or ->data_offset that was set before
870 * reshape_progress was updated.
873 if (progress == MaxSector)
875 if (sh->generation == conf->generation - 1)
877 /* We are in a reshape, and this is a new-generation stripe,
878 * so use new_data_offset.
884 raid5_end_read_request(struct bio *bi);
886 raid5_end_write_request(struct bio *bi);
888 static void ops_run_io(struct stripe_head *sh, struct stripe_head_state *s)
890 struct r5conf *conf = sh->raid_conf;
891 int i, disks = sh->disks;
892 struct stripe_head *head_sh = sh;
896 if (r5l_write_stripe(conf->log, sh) == 0)
898 for (i = disks; i--; ) {
900 int replace_only = 0;
901 struct bio *bi, *rbi;
902 struct md_rdev *rdev, *rrdev = NULL;
905 if (test_and_clear_bit(R5_Wantwrite, &sh->dev[i].flags)) {
906 if (test_and_clear_bit(R5_WantFUA, &sh->dev[i].flags))
910 if (test_bit(R5_Discard, &sh->dev[i].flags))
912 } else if (test_and_clear_bit(R5_Wantread, &sh->dev[i].flags))
914 else if (test_and_clear_bit(R5_WantReplace,
915 &sh->dev[i].flags)) {
920 if (test_and_clear_bit(R5_SyncIO, &sh->dev[i].flags))
924 bi = &sh->dev[i].req;
925 rbi = &sh->dev[i].rreq; /* For writing to replacement */
928 rrdev = rcu_dereference(conf->disks[i].replacement);
929 smp_mb(); /* Ensure that if rrdev is NULL, rdev won't be */
930 rdev = rcu_dereference(conf->disks[i].rdev);
939 /* We raced and saw duplicates */
942 if (test_bit(R5_ReadRepl, &head_sh->dev[i].flags) && rrdev)
947 if (rdev && test_bit(Faulty, &rdev->flags))
950 atomic_inc(&rdev->nr_pending);
951 if (rrdev && test_bit(Faulty, &rrdev->flags))
954 atomic_inc(&rrdev->nr_pending);
957 /* We have already checked bad blocks for reads. Now
958 * need to check for writes. We never accept write errors
959 * on the replacement, so we don't to check rrdev.
961 while ((rw & WRITE) && rdev &&
962 test_bit(WriteErrorSeen, &rdev->flags)) {
965 int bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
966 &first_bad, &bad_sectors);
971 set_bit(BlockedBadBlocks, &rdev->flags);
972 if (!conf->mddev->external &&
973 conf->mddev->flags) {
974 /* It is very unlikely, but we might
975 * still need to write out the
976 * bad block log - better give it
978 md_check_recovery(conf->mddev);
981 * Because md_wait_for_blocked_rdev
982 * will dec nr_pending, we must
983 * increment it first.
985 atomic_inc(&rdev->nr_pending);
986 md_wait_for_blocked_rdev(rdev, conf->mddev);
988 /* Acknowledged bad block - skip the write */
989 rdev_dec_pending(rdev, conf->mddev);
995 if (s->syncing || s->expanding || s->expanded
997 md_sync_acct(rdev->bdev, STRIPE_SECTORS);
999 set_bit(STRIPE_IO_STARTED, &sh->state);
1002 bi->bi_bdev = rdev->bdev;
1004 bi->bi_end_io = (rw & WRITE)
1005 ? raid5_end_write_request
1006 : raid5_end_read_request;
1007 bi->bi_private = sh;
1009 pr_debug("%s: for %llu schedule op %ld on disc %d\n",
1010 __func__, (unsigned long long)sh->sector,
1012 atomic_inc(&sh->count);
1014 atomic_inc(&head_sh->count);
1015 if (use_new_offset(conf, sh))
1016 bi->bi_iter.bi_sector = (sh->sector
1017 + rdev->new_data_offset);
1019 bi->bi_iter.bi_sector = (sh->sector
1020 + rdev->data_offset);
1021 if (test_bit(R5_ReadNoMerge, &head_sh->dev[i].flags))
1022 bi->bi_rw |= REQ_NOMERGE;
1024 if (test_bit(R5_SkipCopy, &sh->dev[i].flags))
1025 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
1026 sh->dev[i].vec.bv_page = sh->dev[i].page;
1028 bi->bi_io_vec[0].bv_len = STRIPE_SIZE;
1029 bi->bi_io_vec[0].bv_offset = 0;
1030 bi->bi_iter.bi_size = STRIPE_SIZE;
1032 * If this is discard request, set bi_vcnt 0. We don't
1033 * want to confuse SCSI because SCSI will replace payload
1035 if (rw & REQ_DISCARD)
1038 set_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags);
1040 if (conf->mddev->gendisk)
1041 trace_block_bio_remap(bdev_get_queue(bi->bi_bdev),
1042 bi, disk_devt(conf->mddev->gendisk),
1044 generic_make_request(bi);
1047 if (s->syncing || s->expanding || s->expanded
1049 md_sync_acct(rrdev->bdev, STRIPE_SECTORS);
1051 set_bit(STRIPE_IO_STARTED, &sh->state);
1054 rbi->bi_bdev = rrdev->bdev;
1056 BUG_ON(!(rw & WRITE));
1057 rbi->bi_end_io = raid5_end_write_request;
1058 rbi->bi_private = sh;
1060 pr_debug("%s: for %llu schedule op %ld on "
1061 "replacement disc %d\n",
1062 __func__, (unsigned long long)sh->sector,
1064 atomic_inc(&sh->count);
1066 atomic_inc(&head_sh->count);
1067 if (use_new_offset(conf, sh))
1068 rbi->bi_iter.bi_sector = (sh->sector
1069 + rrdev->new_data_offset);
1071 rbi->bi_iter.bi_sector = (sh->sector
1072 + rrdev->data_offset);
1073 if (test_bit(R5_SkipCopy, &sh->dev[i].flags))
1074 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
1075 sh->dev[i].rvec.bv_page = sh->dev[i].page;
1077 rbi->bi_io_vec[0].bv_len = STRIPE_SIZE;
1078 rbi->bi_io_vec[0].bv_offset = 0;
1079 rbi->bi_iter.bi_size = STRIPE_SIZE;
1081 * If this is discard request, set bi_vcnt 0. We don't
1082 * want to confuse SCSI because SCSI will replace payload
1084 if (rw & REQ_DISCARD)
1086 if (conf->mddev->gendisk)
1087 trace_block_bio_remap(bdev_get_queue(rbi->bi_bdev),
1088 rbi, disk_devt(conf->mddev->gendisk),
1090 generic_make_request(rbi);
1092 if (!rdev && !rrdev) {
1094 set_bit(STRIPE_DEGRADED, &sh->state);
1095 pr_debug("skip op %ld on disc %d for sector %llu\n",
1096 bi->bi_rw, i, (unsigned long long)sh->sector);
1097 clear_bit(R5_LOCKED, &sh->dev[i].flags);
1098 set_bit(STRIPE_HANDLE, &sh->state);
1101 if (!head_sh->batch_head)
1103 sh = list_first_entry(&sh->batch_list, struct stripe_head,
1110 static struct dma_async_tx_descriptor *
1111 async_copy_data(int frombio, struct bio *bio, struct page **page,
1112 sector_t sector, struct dma_async_tx_descriptor *tx,
1113 struct stripe_head *sh)
1116 struct bvec_iter iter;
1117 struct page *bio_page;
1119 struct async_submit_ctl submit;
1120 enum async_tx_flags flags = 0;
1122 if (bio->bi_iter.bi_sector >= sector)
1123 page_offset = (signed)(bio->bi_iter.bi_sector - sector) * 512;
1125 page_offset = (signed)(sector - bio->bi_iter.bi_sector) * -512;
1128 flags |= ASYNC_TX_FENCE;
1129 init_async_submit(&submit, flags, tx, NULL, NULL, NULL);
1131 bio_for_each_segment(bvl, bio, iter) {
1132 int len = bvl.bv_len;
1136 if (page_offset < 0) {
1137 b_offset = -page_offset;
1138 page_offset += b_offset;
1142 if (len > 0 && page_offset + len > STRIPE_SIZE)
1143 clen = STRIPE_SIZE - page_offset;
1148 b_offset += bvl.bv_offset;
1149 bio_page = bvl.bv_page;
1151 if (sh->raid_conf->skip_copy &&
1152 b_offset == 0 && page_offset == 0 &&
1153 clen == STRIPE_SIZE)
1156 tx = async_memcpy(*page, bio_page, page_offset,
1157 b_offset, clen, &submit);
1159 tx = async_memcpy(bio_page, *page, b_offset,
1160 page_offset, clen, &submit);
1162 /* chain the operations */
1163 submit.depend_tx = tx;
1165 if (clen < len) /* hit end of page */
1173 static void ops_complete_biofill(void *stripe_head_ref)
1175 struct stripe_head *sh = stripe_head_ref;
1176 struct bio_list return_bi = BIO_EMPTY_LIST;
1179 pr_debug("%s: stripe %llu\n", __func__,
1180 (unsigned long long)sh->sector);
1182 /* clear completed biofills */
1183 for (i = sh->disks; i--; ) {
1184 struct r5dev *dev = &sh->dev[i];
1186 /* acknowledge completion of a biofill operation */
1187 /* and check if we need to reply to a read request,
1188 * new R5_Wantfill requests are held off until
1189 * !STRIPE_BIOFILL_RUN
1191 if (test_and_clear_bit(R5_Wantfill, &dev->flags)) {
1192 struct bio *rbi, *rbi2;
1197 while (rbi && rbi->bi_iter.bi_sector <
1198 dev->sector + STRIPE_SECTORS) {
1199 rbi2 = r5_next_bio(rbi, dev->sector);
1200 if (!raid5_dec_bi_active_stripes(rbi))
1201 bio_list_add(&return_bi, rbi);
1206 clear_bit(STRIPE_BIOFILL_RUN, &sh->state);
1208 return_io(&return_bi);
1210 set_bit(STRIPE_HANDLE, &sh->state);
1211 raid5_release_stripe(sh);
1214 static void ops_run_biofill(struct stripe_head *sh)
1216 struct dma_async_tx_descriptor *tx = NULL;
1217 struct async_submit_ctl submit;
1220 BUG_ON(sh->batch_head);
1221 pr_debug("%s: stripe %llu\n", __func__,
1222 (unsigned long long)sh->sector);
1224 for (i = sh->disks; i--; ) {
1225 struct r5dev *dev = &sh->dev[i];
1226 if (test_bit(R5_Wantfill, &dev->flags)) {
1228 spin_lock_irq(&sh->stripe_lock);
1229 dev->read = rbi = dev->toread;
1231 spin_unlock_irq(&sh->stripe_lock);
1232 while (rbi && rbi->bi_iter.bi_sector <
1233 dev->sector + STRIPE_SECTORS) {
1234 tx = async_copy_data(0, rbi, &dev->page,
1235 dev->sector, tx, sh);
1236 rbi = r5_next_bio(rbi, dev->sector);
1241 atomic_inc(&sh->count);
1242 init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_biofill, sh, NULL);
1243 async_trigger_callback(&submit);
1246 static void mark_target_uptodate(struct stripe_head *sh, int target)
1253 tgt = &sh->dev[target];
1254 set_bit(R5_UPTODATE, &tgt->flags);
1255 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1256 clear_bit(R5_Wantcompute, &tgt->flags);
1259 static void ops_complete_compute(void *stripe_head_ref)
1261 struct stripe_head *sh = stripe_head_ref;
1263 pr_debug("%s: stripe %llu\n", __func__,
1264 (unsigned long long)sh->sector);
1266 /* mark the computed target(s) as uptodate */
1267 mark_target_uptodate(sh, sh->ops.target);
1268 mark_target_uptodate(sh, sh->ops.target2);
1270 clear_bit(STRIPE_COMPUTE_RUN, &sh->state);
1271 if (sh->check_state == check_state_compute_run)
1272 sh->check_state = check_state_compute_result;
1273 set_bit(STRIPE_HANDLE, &sh->state);
1274 raid5_release_stripe(sh);
1277 /* return a pointer to the address conversion region of the scribble buffer */
1278 static addr_conv_t *to_addr_conv(struct stripe_head *sh,
1279 struct raid5_percpu *percpu, int i)
1283 addr = flex_array_get(percpu->scribble, i);
1284 return addr + sizeof(struct page *) * (sh->disks + 2);
1287 /* return a pointer to the address conversion region of the scribble buffer */
1288 static struct page **to_addr_page(struct raid5_percpu *percpu, int i)
1292 addr = flex_array_get(percpu->scribble, i);
1296 static struct dma_async_tx_descriptor *
1297 ops_run_compute5(struct stripe_head *sh, struct raid5_percpu *percpu)
1299 int disks = sh->disks;
1300 struct page **xor_srcs = to_addr_page(percpu, 0);
1301 int target = sh->ops.target;
1302 struct r5dev *tgt = &sh->dev[target];
1303 struct page *xor_dest = tgt->page;
1305 struct dma_async_tx_descriptor *tx;
1306 struct async_submit_ctl submit;
1309 BUG_ON(sh->batch_head);
1311 pr_debug("%s: stripe %llu block: %d\n",
1312 __func__, (unsigned long long)sh->sector, target);
1313 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1315 for (i = disks; i--; )
1317 xor_srcs[count++] = sh->dev[i].page;
1319 atomic_inc(&sh->count);
1321 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST, NULL,
1322 ops_complete_compute, sh, to_addr_conv(sh, percpu, 0));
1323 if (unlikely(count == 1))
1324 tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE, &submit);
1326 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1331 /* set_syndrome_sources - populate source buffers for gen_syndrome
1332 * @srcs - (struct page *) array of size sh->disks
1333 * @sh - stripe_head to parse
1335 * Populates srcs in proper layout order for the stripe and returns the
1336 * 'count' of sources to be used in a call to async_gen_syndrome. The P
1337 * destination buffer is recorded in srcs[count] and the Q destination
1338 * is recorded in srcs[count+1]].
1340 static int set_syndrome_sources(struct page **srcs,
1341 struct stripe_head *sh,
1344 int disks = sh->disks;
1345 int syndrome_disks = sh->ddf_layout ? disks : (disks - 2);
1346 int d0_idx = raid6_d0(sh);
1350 for (i = 0; i < disks; i++)
1356 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1357 struct r5dev *dev = &sh->dev[i];
1359 if (i == sh->qd_idx || i == sh->pd_idx ||
1360 (srctype == SYNDROME_SRC_ALL) ||
1361 (srctype == SYNDROME_SRC_WANT_DRAIN &&
1362 test_bit(R5_Wantdrain, &dev->flags)) ||
1363 (srctype == SYNDROME_SRC_WRITTEN &&
1365 srcs[slot] = sh->dev[i].page;
1366 i = raid6_next_disk(i, disks);
1367 } while (i != d0_idx);
1369 return syndrome_disks;
1372 static struct dma_async_tx_descriptor *
1373 ops_run_compute6_1(struct stripe_head *sh, struct raid5_percpu *percpu)
1375 int disks = sh->disks;
1376 struct page **blocks = to_addr_page(percpu, 0);
1378 int qd_idx = sh->qd_idx;
1379 struct dma_async_tx_descriptor *tx;
1380 struct async_submit_ctl submit;
1386 BUG_ON(sh->batch_head);
1387 if (sh->ops.target < 0)
1388 target = sh->ops.target2;
1389 else if (sh->ops.target2 < 0)
1390 target = sh->ops.target;
1392 /* we should only have one valid target */
1395 pr_debug("%s: stripe %llu block: %d\n",
1396 __func__, (unsigned long long)sh->sector, target);
1398 tgt = &sh->dev[target];
1399 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1402 atomic_inc(&sh->count);
1404 if (target == qd_idx) {
1405 count = set_syndrome_sources(blocks, sh, SYNDROME_SRC_ALL);
1406 blocks[count] = NULL; /* regenerating p is not necessary */
1407 BUG_ON(blocks[count+1] != dest); /* q should already be set */
1408 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1409 ops_complete_compute, sh,
1410 to_addr_conv(sh, percpu, 0));
1411 tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
1413 /* Compute any data- or p-drive using XOR */
1415 for (i = disks; i-- ; ) {
1416 if (i == target || i == qd_idx)
1418 blocks[count++] = sh->dev[i].page;
1421 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1422 NULL, ops_complete_compute, sh,
1423 to_addr_conv(sh, percpu, 0));
1424 tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE, &submit);
1430 static struct dma_async_tx_descriptor *
1431 ops_run_compute6_2(struct stripe_head *sh, struct raid5_percpu *percpu)
1433 int i, count, disks = sh->disks;
1434 int syndrome_disks = sh->ddf_layout ? disks : disks-2;
1435 int d0_idx = raid6_d0(sh);
1436 int faila = -1, failb = -1;
1437 int target = sh->ops.target;
1438 int target2 = sh->ops.target2;
1439 struct r5dev *tgt = &sh->dev[target];
1440 struct r5dev *tgt2 = &sh->dev[target2];
1441 struct dma_async_tx_descriptor *tx;
1442 struct page **blocks = to_addr_page(percpu, 0);
1443 struct async_submit_ctl submit;
1445 BUG_ON(sh->batch_head);
1446 pr_debug("%s: stripe %llu block1: %d block2: %d\n",
1447 __func__, (unsigned long long)sh->sector, target, target2);
1448 BUG_ON(target < 0 || target2 < 0);
1449 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1450 BUG_ON(!test_bit(R5_Wantcompute, &tgt2->flags));
1452 /* we need to open-code set_syndrome_sources to handle the
1453 * slot number conversion for 'faila' and 'failb'
1455 for (i = 0; i < disks ; i++)
1460 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1462 blocks[slot] = sh->dev[i].page;
1468 i = raid6_next_disk(i, disks);
1469 } while (i != d0_idx);
1471 BUG_ON(faila == failb);
1474 pr_debug("%s: stripe: %llu faila: %d failb: %d\n",
1475 __func__, (unsigned long long)sh->sector, faila, failb);
1477 atomic_inc(&sh->count);
1479 if (failb == syndrome_disks+1) {
1480 /* Q disk is one of the missing disks */
1481 if (faila == syndrome_disks) {
1482 /* Missing P+Q, just recompute */
1483 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1484 ops_complete_compute, sh,
1485 to_addr_conv(sh, percpu, 0));
1486 return async_gen_syndrome(blocks, 0, syndrome_disks+2,
1487 STRIPE_SIZE, &submit);
1491 int qd_idx = sh->qd_idx;
1493 /* Missing D+Q: recompute D from P, then recompute Q */
1494 if (target == qd_idx)
1495 data_target = target2;
1497 data_target = target;
1500 for (i = disks; i-- ; ) {
1501 if (i == data_target || i == qd_idx)
1503 blocks[count++] = sh->dev[i].page;
1505 dest = sh->dev[data_target].page;
1506 init_async_submit(&submit,
1507 ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1509 to_addr_conv(sh, percpu, 0));
1510 tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE,
1513 count = set_syndrome_sources(blocks, sh, SYNDROME_SRC_ALL);
1514 init_async_submit(&submit, ASYNC_TX_FENCE, tx,
1515 ops_complete_compute, sh,
1516 to_addr_conv(sh, percpu, 0));
1517 return async_gen_syndrome(blocks, 0, count+2,
1518 STRIPE_SIZE, &submit);
1521 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1522 ops_complete_compute, sh,
1523 to_addr_conv(sh, percpu, 0));
1524 if (failb == syndrome_disks) {
1525 /* We're missing D+P. */
1526 return async_raid6_datap_recov(syndrome_disks+2,
1530 /* We're missing D+D. */
1531 return async_raid6_2data_recov(syndrome_disks+2,
1532 STRIPE_SIZE, faila, failb,
1538 static void ops_complete_prexor(void *stripe_head_ref)
1540 struct stripe_head *sh = stripe_head_ref;
1542 pr_debug("%s: stripe %llu\n", __func__,
1543 (unsigned long long)sh->sector);
1546 static struct dma_async_tx_descriptor *
1547 ops_run_prexor5(struct stripe_head *sh, struct raid5_percpu *percpu,
1548 struct dma_async_tx_descriptor *tx)
1550 int disks = sh->disks;
1551 struct page **xor_srcs = to_addr_page(percpu, 0);
1552 int count = 0, pd_idx = sh->pd_idx, i;
1553 struct async_submit_ctl submit;
1555 /* existing parity data subtracted */
1556 struct page *xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1558 BUG_ON(sh->batch_head);
1559 pr_debug("%s: stripe %llu\n", __func__,
1560 (unsigned long long)sh->sector);
1562 for (i = disks; i--; ) {
1563 struct r5dev *dev = &sh->dev[i];
1564 /* Only process blocks that are known to be uptodate */
1565 if (test_bit(R5_Wantdrain, &dev->flags))
1566 xor_srcs[count++] = dev->page;
1569 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_DROP_DST, tx,
1570 ops_complete_prexor, sh, to_addr_conv(sh, percpu, 0));
1571 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1576 static struct dma_async_tx_descriptor *
1577 ops_run_prexor6(struct stripe_head *sh, struct raid5_percpu *percpu,
1578 struct dma_async_tx_descriptor *tx)
1580 struct page **blocks = to_addr_page(percpu, 0);
1582 struct async_submit_ctl submit;
1584 pr_debug("%s: stripe %llu\n", __func__,
1585 (unsigned long long)sh->sector);
1587 count = set_syndrome_sources(blocks, sh, SYNDROME_SRC_WANT_DRAIN);
1589 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_PQ_XOR_DST, tx,
1590 ops_complete_prexor, sh, to_addr_conv(sh, percpu, 0));
1591 tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
1596 static struct dma_async_tx_descriptor *
1597 ops_run_biodrain(struct stripe_head *sh, struct dma_async_tx_descriptor *tx)
1599 int disks = sh->disks;
1601 struct stripe_head *head_sh = sh;
1603 pr_debug("%s: stripe %llu\n", __func__,
1604 (unsigned long long)sh->sector);
1606 for (i = disks; i--; ) {
1611 if (test_and_clear_bit(R5_Wantdrain, &head_sh->dev[i].flags)) {
1616 spin_lock_irq(&sh->stripe_lock);
1617 chosen = dev->towrite;
1618 dev->towrite = NULL;
1619 sh->overwrite_disks = 0;
1620 BUG_ON(dev->written);
1621 wbi = dev->written = chosen;
1622 spin_unlock_irq(&sh->stripe_lock);
1623 WARN_ON(dev->page != dev->orig_page);
1625 while (wbi && wbi->bi_iter.bi_sector <
1626 dev->sector + STRIPE_SECTORS) {
1627 if (wbi->bi_rw & REQ_FUA)
1628 set_bit(R5_WantFUA, &dev->flags);
1629 if (wbi->bi_rw & REQ_SYNC)
1630 set_bit(R5_SyncIO, &dev->flags);
1631 if (wbi->bi_rw & REQ_DISCARD)
1632 set_bit(R5_Discard, &dev->flags);
1634 tx = async_copy_data(1, wbi, &dev->page,
1635 dev->sector, tx, sh);
1636 if (dev->page != dev->orig_page) {
1637 set_bit(R5_SkipCopy, &dev->flags);
1638 clear_bit(R5_UPTODATE, &dev->flags);
1639 clear_bit(R5_OVERWRITE, &dev->flags);
1642 wbi = r5_next_bio(wbi, dev->sector);
1645 if (head_sh->batch_head) {
1646 sh = list_first_entry(&sh->batch_list,
1659 static void ops_complete_reconstruct(void *stripe_head_ref)
1661 struct stripe_head *sh = stripe_head_ref;
1662 int disks = sh->disks;
1663 int pd_idx = sh->pd_idx;
1664 int qd_idx = sh->qd_idx;
1666 bool fua = false, sync = false, discard = false;
1668 pr_debug("%s: stripe %llu\n", __func__,
1669 (unsigned long long)sh->sector);
1671 for (i = disks; i--; ) {
1672 fua |= test_bit(R5_WantFUA, &sh->dev[i].flags);
1673 sync |= test_bit(R5_SyncIO, &sh->dev[i].flags);
1674 discard |= test_bit(R5_Discard, &sh->dev[i].flags);
1677 for (i = disks; i--; ) {
1678 struct r5dev *dev = &sh->dev[i];
1680 if (dev->written || i == pd_idx || i == qd_idx) {
1681 if (!discard && !test_bit(R5_SkipCopy, &dev->flags)) {
1682 set_bit(R5_UPTODATE, &dev->flags);
1683 if (test_bit(STRIPE_EXPAND_READY, &sh->state))
1684 set_bit(R5_Expanded, &dev->flags);
1687 set_bit(R5_WantFUA, &dev->flags);
1689 set_bit(R5_SyncIO, &dev->flags);
1693 if (sh->reconstruct_state == reconstruct_state_drain_run)
1694 sh->reconstruct_state = reconstruct_state_drain_result;
1695 else if (sh->reconstruct_state == reconstruct_state_prexor_drain_run)
1696 sh->reconstruct_state = reconstruct_state_prexor_drain_result;
1698 BUG_ON(sh->reconstruct_state != reconstruct_state_run);
1699 sh->reconstruct_state = reconstruct_state_result;
1702 set_bit(STRIPE_HANDLE, &sh->state);
1703 raid5_release_stripe(sh);
1707 ops_run_reconstruct5(struct stripe_head *sh, struct raid5_percpu *percpu,
1708 struct dma_async_tx_descriptor *tx)
1710 int disks = sh->disks;
1711 struct page **xor_srcs;
1712 struct async_submit_ctl submit;
1713 int count, pd_idx = sh->pd_idx, i;
1714 struct page *xor_dest;
1716 unsigned long flags;
1718 struct stripe_head *head_sh = sh;
1721 pr_debug("%s: stripe %llu\n", __func__,
1722 (unsigned long long)sh->sector);
1724 for (i = 0; i < sh->disks; i++) {
1727 if (!test_bit(R5_Discard, &sh->dev[i].flags))
1730 if (i >= sh->disks) {
1731 atomic_inc(&sh->count);
1732 set_bit(R5_Discard, &sh->dev[pd_idx].flags);
1733 ops_complete_reconstruct(sh);
1738 xor_srcs = to_addr_page(percpu, j);
1739 /* check if prexor is active which means only process blocks
1740 * that are part of a read-modify-write (written)
1742 if (head_sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
1744 xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1745 for (i = disks; i--; ) {
1746 struct r5dev *dev = &sh->dev[i];
1747 if (head_sh->dev[i].written)
1748 xor_srcs[count++] = dev->page;
1751 xor_dest = sh->dev[pd_idx].page;
1752 for (i = disks; i--; ) {
1753 struct r5dev *dev = &sh->dev[i];
1755 xor_srcs[count++] = dev->page;
1759 /* 1/ if we prexor'd then the dest is reused as a source
1760 * 2/ if we did not prexor then we are redoing the parity
1761 * set ASYNC_TX_XOR_DROP_DST and ASYNC_TX_XOR_ZERO_DST
1762 * for the synchronous xor case
1764 last_stripe = !head_sh->batch_head ||
1765 list_first_entry(&sh->batch_list,
1766 struct stripe_head, batch_list) == head_sh;
1768 flags = ASYNC_TX_ACK |
1769 (prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST);
1771 atomic_inc(&head_sh->count);
1772 init_async_submit(&submit, flags, tx, ops_complete_reconstruct, head_sh,
1773 to_addr_conv(sh, percpu, j));
1775 flags = prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST;
1776 init_async_submit(&submit, flags, tx, NULL, NULL,
1777 to_addr_conv(sh, percpu, j));
1780 if (unlikely(count == 1))
1781 tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE, &submit);
1783 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1786 sh = list_first_entry(&sh->batch_list, struct stripe_head,
1793 ops_run_reconstruct6(struct stripe_head *sh, struct raid5_percpu *percpu,
1794 struct dma_async_tx_descriptor *tx)
1796 struct async_submit_ctl submit;
1797 struct page **blocks;
1798 int count, i, j = 0;
1799 struct stripe_head *head_sh = sh;
1802 unsigned long txflags;
1804 pr_debug("%s: stripe %llu\n", __func__, (unsigned long long)sh->sector);
1806 for (i = 0; i < sh->disks; i++) {
1807 if (sh->pd_idx == i || sh->qd_idx == i)
1809 if (!test_bit(R5_Discard, &sh->dev[i].flags))
1812 if (i >= sh->disks) {
1813 atomic_inc(&sh->count);
1814 set_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
1815 set_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
1816 ops_complete_reconstruct(sh);
1821 blocks = to_addr_page(percpu, j);
1823 if (sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
1824 synflags = SYNDROME_SRC_WRITTEN;
1825 txflags = ASYNC_TX_ACK | ASYNC_TX_PQ_XOR_DST;
1827 synflags = SYNDROME_SRC_ALL;
1828 txflags = ASYNC_TX_ACK;
1831 count = set_syndrome_sources(blocks, sh, synflags);
1832 last_stripe = !head_sh->batch_head ||
1833 list_first_entry(&sh->batch_list,
1834 struct stripe_head, batch_list) == head_sh;
1837 atomic_inc(&head_sh->count);
1838 init_async_submit(&submit, txflags, tx, ops_complete_reconstruct,
1839 head_sh, to_addr_conv(sh, percpu, j));
1841 init_async_submit(&submit, 0, tx, NULL, NULL,
1842 to_addr_conv(sh, percpu, j));
1843 tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
1846 sh = list_first_entry(&sh->batch_list, struct stripe_head,
1852 static void ops_complete_check(void *stripe_head_ref)
1854 struct stripe_head *sh = stripe_head_ref;
1856 pr_debug("%s: stripe %llu\n", __func__,
1857 (unsigned long long)sh->sector);
1859 sh->check_state = check_state_check_result;
1860 set_bit(STRIPE_HANDLE, &sh->state);
1861 raid5_release_stripe(sh);
1864 static void ops_run_check_p(struct stripe_head *sh, struct raid5_percpu *percpu)
1866 int disks = sh->disks;
1867 int pd_idx = sh->pd_idx;
1868 int qd_idx = sh->qd_idx;
1869 struct page *xor_dest;
1870 struct page **xor_srcs = to_addr_page(percpu, 0);
1871 struct dma_async_tx_descriptor *tx;
1872 struct async_submit_ctl submit;
1876 pr_debug("%s: stripe %llu\n", __func__,
1877 (unsigned long long)sh->sector);
1879 BUG_ON(sh->batch_head);
1881 xor_dest = sh->dev[pd_idx].page;
1882 xor_srcs[count++] = xor_dest;
1883 for (i = disks; i--; ) {
1884 if (i == pd_idx || i == qd_idx)
1886 xor_srcs[count++] = sh->dev[i].page;
1889 init_async_submit(&submit, 0, NULL, NULL, NULL,
1890 to_addr_conv(sh, percpu, 0));
1891 tx = async_xor_val(xor_dest, xor_srcs, 0, count, STRIPE_SIZE,
1892 &sh->ops.zero_sum_result, &submit);
1894 atomic_inc(&sh->count);
1895 init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_check, sh, NULL);
1896 tx = async_trigger_callback(&submit);
1899 static void ops_run_check_pq(struct stripe_head *sh, struct raid5_percpu *percpu, int checkp)
1901 struct page **srcs = to_addr_page(percpu, 0);
1902 struct async_submit_ctl submit;
1905 pr_debug("%s: stripe %llu checkp: %d\n", __func__,
1906 (unsigned long long)sh->sector, checkp);
1908 BUG_ON(sh->batch_head);
1909 count = set_syndrome_sources(srcs, sh, SYNDROME_SRC_ALL);
1913 atomic_inc(&sh->count);
1914 init_async_submit(&submit, ASYNC_TX_ACK, NULL, ops_complete_check,
1915 sh, to_addr_conv(sh, percpu, 0));
1916 async_syndrome_val(srcs, 0, count+2, STRIPE_SIZE,
1917 &sh->ops.zero_sum_result, percpu->spare_page, &submit);
1920 static void raid_run_ops(struct stripe_head *sh, unsigned long ops_request)
1922 int overlap_clear = 0, i, disks = sh->disks;
1923 struct dma_async_tx_descriptor *tx = NULL;
1924 struct r5conf *conf = sh->raid_conf;
1925 int level = conf->level;
1926 struct raid5_percpu *percpu;
1930 percpu = per_cpu_ptr(conf->percpu, cpu);
1931 if (test_bit(STRIPE_OP_BIOFILL, &ops_request)) {
1932 ops_run_biofill(sh);
1936 if (test_bit(STRIPE_OP_COMPUTE_BLK, &ops_request)) {
1938 tx = ops_run_compute5(sh, percpu);
1940 if (sh->ops.target2 < 0 || sh->ops.target < 0)
1941 tx = ops_run_compute6_1(sh, percpu);
1943 tx = ops_run_compute6_2(sh, percpu);
1945 /* terminate the chain if reconstruct is not set to be run */
1946 if (tx && !test_bit(STRIPE_OP_RECONSTRUCT, &ops_request))
1950 if (test_bit(STRIPE_OP_PREXOR, &ops_request)) {
1952 tx = ops_run_prexor5(sh, percpu, tx);
1954 tx = ops_run_prexor6(sh, percpu, tx);
1957 if (test_bit(STRIPE_OP_BIODRAIN, &ops_request)) {
1958 tx = ops_run_biodrain(sh, tx);
1962 if (test_bit(STRIPE_OP_RECONSTRUCT, &ops_request)) {
1964 ops_run_reconstruct5(sh, percpu, tx);
1966 ops_run_reconstruct6(sh, percpu, tx);
1969 if (test_bit(STRIPE_OP_CHECK, &ops_request)) {
1970 if (sh->check_state == check_state_run)
1971 ops_run_check_p(sh, percpu);
1972 else if (sh->check_state == check_state_run_q)
1973 ops_run_check_pq(sh, percpu, 0);
1974 else if (sh->check_state == check_state_run_pq)
1975 ops_run_check_pq(sh, percpu, 1);
1980 if (overlap_clear && !sh->batch_head)
1981 for (i = disks; i--; ) {
1982 struct r5dev *dev = &sh->dev[i];
1983 if (test_and_clear_bit(R5_Overlap, &dev->flags))
1984 wake_up(&sh->raid_conf->wait_for_overlap);
1989 static struct stripe_head *alloc_stripe(struct kmem_cache *sc, gfp_t gfp)
1991 struct stripe_head *sh;
1993 sh = kmem_cache_zalloc(sc, gfp);
1995 spin_lock_init(&sh->stripe_lock);
1996 spin_lock_init(&sh->batch_lock);
1997 INIT_LIST_HEAD(&sh->batch_list);
1998 INIT_LIST_HEAD(&sh->lru);
1999 atomic_set(&sh->count, 1);
2003 static int grow_one_stripe(struct r5conf *conf, gfp_t gfp)
2005 struct stripe_head *sh;
2007 sh = alloc_stripe(conf->slab_cache, gfp);
2011 sh->raid_conf = conf;
2013 if (grow_buffers(sh, gfp)) {
2015 kmem_cache_free(conf->slab_cache, sh);
2018 sh->hash_lock_index =
2019 conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS;
2020 /* we just created an active stripe so... */
2021 atomic_inc(&conf->active_stripes);
2023 raid5_release_stripe(sh);
2024 conf->max_nr_stripes++;
2028 static int grow_stripes(struct r5conf *conf, int num)
2030 struct kmem_cache *sc;
2031 size_t namelen = sizeof(conf->cache_name[0]);
2032 int devs = max(conf->raid_disks, conf->previous_raid_disks);
2034 if (conf->mddev->gendisk)
2035 snprintf(conf->cache_name[0], namelen,
2036 "raid%d-%s", conf->level, mdname(conf->mddev));
2038 snprintf(conf->cache_name[0], namelen,
2039 "raid%d-%p", conf->level, conf->mddev);
2040 snprintf(conf->cache_name[1], namelen, "%.27s-alt", conf->cache_name[0]);
2042 conf->active_name = 0;
2043 sc = kmem_cache_create(conf->cache_name[conf->active_name],
2044 sizeof(struct stripe_head)+(devs-1)*sizeof(struct r5dev),
2048 conf->slab_cache = sc;
2049 conf->pool_size = devs;
2051 if (!grow_one_stripe(conf, GFP_KERNEL))
2058 * scribble_len - return the required size of the scribble region
2059 * @num - total number of disks in the array
2061 * The size must be enough to contain:
2062 * 1/ a struct page pointer for each device in the array +2
2063 * 2/ room to convert each entry in (1) to its corresponding dma
2064 * (dma_map_page()) or page (page_address()) address.
2066 * Note: the +2 is for the destination buffers of the ddf/raid6 case where we
2067 * calculate over all devices (not just the data blocks), using zeros in place
2068 * of the P and Q blocks.
2070 static struct flex_array *scribble_alloc(int num, int cnt, gfp_t flags)
2072 struct flex_array *ret;
2075 len = sizeof(struct page *) * (num+2) + sizeof(addr_conv_t) * (num+2);
2076 ret = flex_array_alloc(len, cnt, flags);
2079 /* always prealloc all elements, so no locking is required */
2080 if (flex_array_prealloc(ret, 0, cnt, flags)) {
2081 flex_array_free(ret);
2087 static int resize_chunks(struct r5conf *conf, int new_disks, int new_sectors)
2093 * Never shrink. And mddev_suspend() could deadlock if this is called
2094 * from raid5d. In that case, scribble_disks and scribble_sectors
2095 * should equal to new_disks and new_sectors
2097 if (conf->scribble_disks >= new_disks &&
2098 conf->scribble_sectors >= new_sectors)
2100 mddev_suspend(conf->mddev);
2102 for_each_present_cpu(cpu) {
2103 struct raid5_percpu *percpu;
2104 struct flex_array *scribble;
2106 percpu = per_cpu_ptr(conf->percpu, cpu);
2107 scribble = scribble_alloc(new_disks,
2108 new_sectors / STRIPE_SECTORS,
2112 flex_array_free(percpu->scribble);
2113 percpu->scribble = scribble;
2120 mddev_resume(conf->mddev);
2122 conf->scribble_disks = new_disks;
2123 conf->scribble_sectors = new_sectors;
2128 static int resize_stripes(struct r5conf *conf, int newsize)
2130 /* Make all the stripes able to hold 'newsize' devices.
2131 * New slots in each stripe get 'page' set to a new page.
2133 * This happens in stages:
2134 * 1/ create a new kmem_cache and allocate the required number of
2136 * 2/ gather all the old stripe_heads and transfer the pages across
2137 * to the new stripe_heads. This will have the side effect of
2138 * freezing the array as once all stripe_heads have been collected,
2139 * no IO will be possible. Old stripe heads are freed once their
2140 * pages have been transferred over, and the old kmem_cache is
2141 * freed when all stripes are done.
2142 * 3/ reallocate conf->disks to be suitable bigger. If this fails,
2143 * we simple return a failre status - no need to clean anything up.
2144 * 4/ allocate new pages for the new slots in the new stripe_heads.
2145 * If this fails, we don't bother trying the shrink the
2146 * stripe_heads down again, we just leave them as they are.
2147 * As each stripe_head is processed the new one is released into
2150 * Once step2 is started, we cannot afford to wait for a write,
2151 * so we use GFP_NOIO allocations.
2153 struct stripe_head *osh, *nsh;
2154 LIST_HEAD(newstripes);
2155 struct disk_info *ndisks;
2157 struct kmem_cache *sc;
2161 if (newsize <= conf->pool_size)
2162 return 0; /* never bother to shrink */
2164 err = md_allow_write(conf->mddev);
2169 sc = kmem_cache_create(conf->cache_name[1-conf->active_name],
2170 sizeof(struct stripe_head)+(newsize-1)*sizeof(struct r5dev),
2175 /* Need to ensure auto-resizing doesn't interfere */
2176 mutex_lock(&conf->cache_size_mutex);
2178 for (i = conf->max_nr_stripes; i; i--) {
2179 nsh = alloc_stripe(sc, GFP_KERNEL);
2183 nsh->raid_conf = conf;
2184 list_add(&nsh->lru, &newstripes);
2187 /* didn't get enough, give up */
2188 while (!list_empty(&newstripes)) {
2189 nsh = list_entry(newstripes.next, struct stripe_head, lru);
2190 list_del(&nsh->lru);
2191 kmem_cache_free(sc, nsh);
2193 kmem_cache_destroy(sc);
2194 mutex_unlock(&conf->cache_size_mutex);
2197 /* Step 2 - Must use GFP_NOIO now.
2198 * OK, we have enough stripes, start collecting inactive
2199 * stripes and copying them over
2203 list_for_each_entry(nsh, &newstripes, lru) {
2204 lock_device_hash_lock(conf, hash);
2205 wait_event_cmd(conf->wait_for_stripe,
2206 !list_empty(conf->inactive_list + hash),
2207 unlock_device_hash_lock(conf, hash),
2208 lock_device_hash_lock(conf, hash));
2209 osh = get_free_stripe(conf, hash);
2210 unlock_device_hash_lock(conf, hash);
2212 for(i=0; i<conf->pool_size; i++) {
2213 nsh->dev[i].page = osh->dev[i].page;
2214 nsh->dev[i].orig_page = osh->dev[i].page;
2216 nsh->hash_lock_index = hash;
2217 kmem_cache_free(conf->slab_cache, osh);
2219 if (cnt >= conf->max_nr_stripes / NR_STRIPE_HASH_LOCKS +
2220 !!((conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS) > hash)) {
2225 kmem_cache_destroy(conf->slab_cache);
2228 * At this point, we are holding all the stripes so the array
2229 * is completely stalled, so now is a good time to resize
2230 * conf->disks and the scribble region
2232 ndisks = kzalloc(newsize * sizeof(struct disk_info), GFP_NOIO);
2234 for (i=0; i<conf->raid_disks; i++)
2235 ndisks[i] = conf->disks[i];
2237 conf->disks = ndisks;
2241 conf->slab_cache = sc;
2242 conf->active_name = 1-conf->active_name;
2244 /* Step 4, return new stripes to service */
2245 while(!list_empty(&newstripes)) {
2246 nsh = list_entry(newstripes.next, struct stripe_head, lru);
2247 list_del_init(&nsh->lru);
2249 for (i=conf->raid_disks; i < newsize; i++)
2250 if (nsh->dev[i].page == NULL) {
2251 struct page *p = alloc_page(GFP_NOIO);
2252 nsh->dev[i].page = p;
2253 nsh->dev[i].orig_page = p;
2257 raid5_release_stripe(nsh);
2259 /* critical section pass, GFP_NOIO no longer needed */
2262 conf->pool_size = newsize;
2263 mutex_unlock(&conf->cache_size_mutex);
2268 static int drop_one_stripe(struct r5conf *conf)
2270 struct stripe_head *sh;
2271 int hash = (conf->max_nr_stripes - 1) & STRIPE_HASH_LOCKS_MASK;
2273 spin_lock_irq(conf->hash_locks + hash);
2274 sh = get_free_stripe(conf, hash);
2275 spin_unlock_irq(conf->hash_locks + hash);
2278 BUG_ON(atomic_read(&sh->count));
2280 kmem_cache_free(conf->slab_cache, sh);
2281 atomic_dec(&conf->active_stripes);
2282 conf->max_nr_stripes--;
2286 static void shrink_stripes(struct r5conf *conf)
2288 while (conf->max_nr_stripes &&
2289 drop_one_stripe(conf))
2292 kmem_cache_destroy(conf->slab_cache);
2293 conf->slab_cache = NULL;
2296 static void raid5_end_read_request(struct bio * bi)
2298 struct stripe_head *sh = bi->bi_private;
2299 struct r5conf *conf = sh->raid_conf;
2300 int disks = sh->disks, i;
2301 char b[BDEVNAME_SIZE];
2302 struct md_rdev *rdev = NULL;
2305 for (i=0 ; i<disks; i++)
2306 if (bi == &sh->dev[i].req)
2309 pr_debug("end_read_request %llu/%d, count: %d, error %d.\n",
2310 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
2316 if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2317 /* If replacement finished while this request was outstanding,
2318 * 'replacement' might be NULL already.
2319 * In that case it moved down to 'rdev'.
2320 * rdev is not removed until all requests are finished.
2322 rdev = conf->disks[i].replacement;
2324 rdev = conf->disks[i].rdev;
2326 if (use_new_offset(conf, sh))
2327 s = sh->sector + rdev->new_data_offset;
2329 s = sh->sector + rdev->data_offset;
2330 if (!bi->bi_error) {
2331 set_bit(R5_UPTODATE, &sh->dev[i].flags);
2332 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
2333 /* Note that this cannot happen on a
2334 * replacement device. We just fail those on
2339 "md/raid:%s: read error corrected"
2340 " (%lu sectors at %llu on %s)\n",
2341 mdname(conf->mddev), STRIPE_SECTORS,
2342 (unsigned long long)s,
2343 bdevname(rdev->bdev, b));
2344 atomic_add(STRIPE_SECTORS, &rdev->corrected_errors);
2345 clear_bit(R5_ReadError, &sh->dev[i].flags);
2346 clear_bit(R5_ReWrite, &sh->dev[i].flags);
2347 } else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2348 clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2350 if (atomic_read(&rdev->read_errors))
2351 atomic_set(&rdev->read_errors, 0);
2353 const char *bdn = bdevname(rdev->bdev, b);
2357 clear_bit(R5_UPTODATE, &sh->dev[i].flags);
2358 atomic_inc(&rdev->read_errors);
2359 if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2362 "md/raid:%s: read error on replacement device "
2363 "(sector %llu on %s).\n",
2364 mdname(conf->mddev),
2365 (unsigned long long)s,
2367 else if (conf->mddev->degraded >= conf->max_degraded) {
2371 "md/raid:%s: read error not correctable "
2372 "(sector %llu on %s).\n",
2373 mdname(conf->mddev),
2374 (unsigned long long)s,
2376 } else if (test_bit(R5_ReWrite, &sh->dev[i].flags)) {
2381 "md/raid:%s: read error NOT corrected!! "
2382 "(sector %llu on %s).\n",
2383 mdname(conf->mddev),
2384 (unsigned long long)s,
2386 } else if (atomic_read(&rdev->read_errors)
2387 > conf->max_nr_stripes)
2389 "md/raid:%s: Too many read errors, failing device %s.\n",
2390 mdname(conf->mddev), bdn);
2393 if (set_bad && test_bit(In_sync, &rdev->flags)
2394 && !test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2397 if (sh->qd_idx >= 0 && sh->pd_idx == i)
2398 set_bit(R5_ReadError, &sh->dev[i].flags);
2399 else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags)) {
2400 set_bit(R5_ReadError, &sh->dev[i].flags);
2401 clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2403 set_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2405 clear_bit(R5_ReadError, &sh->dev[i].flags);
2406 clear_bit(R5_ReWrite, &sh->dev[i].flags);
2408 && test_bit(In_sync, &rdev->flags)
2409 && rdev_set_badblocks(
2410 rdev, sh->sector, STRIPE_SECTORS, 0)))
2411 md_error(conf->mddev, rdev);
2414 rdev_dec_pending(rdev, conf->mddev);
2415 clear_bit(R5_LOCKED, &sh->dev[i].flags);
2416 set_bit(STRIPE_HANDLE, &sh->state);
2417 raid5_release_stripe(sh);
2420 static void raid5_end_write_request(struct bio *bi)
2422 struct stripe_head *sh = bi->bi_private;
2423 struct r5conf *conf = sh->raid_conf;
2424 int disks = sh->disks, i;
2425 struct md_rdev *uninitialized_var(rdev);
2428 int replacement = 0;
2430 for (i = 0 ; i < disks; i++) {
2431 if (bi == &sh->dev[i].req) {
2432 rdev = conf->disks[i].rdev;
2435 if (bi == &sh->dev[i].rreq) {
2436 rdev = conf->disks[i].replacement;
2440 /* rdev was removed and 'replacement'
2441 * replaced it. rdev is not removed
2442 * until all requests are finished.
2444 rdev = conf->disks[i].rdev;
2448 pr_debug("end_write_request %llu/%d, count %d, error: %d.\n",
2449 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
2458 md_error(conf->mddev, rdev);
2459 else if (is_badblock(rdev, sh->sector,
2461 &first_bad, &bad_sectors))
2462 set_bit(R5_MadeGoodRepl, &sh->dev[i].flags);
2465 set_bit(STRIPE_DEGRADED, &sh->state);
2466 set_bit(WriteErrorSeen, &rdev->flags);
2467 set_bit(R5_WriteError, &sh->dev[i].flags);
2468 if (!test_and_set_bit(WantReplacement, &rdev->flags))
2469 set_bit(MD_RECOVERY_NEEDED,
2470 &rdev->mddev->recovery);
2471 } else if (is_badblock(rdev, sh->sector,
2473 &first_bad, &bad_sectors)) {
2474 set_bit(R5_MadeGood, &sh->dev[i].flags);
2475 if (test_bit(R5_ReadError, &sh->dev[i].flags))
2476 /* That was a successful write so make
2477 * sure it looks like we already did
2480 set_bit(R5_ReWrite, &sh->dev[i].flags);
2483 rdev_dec_pending(rdev, conf->mddev);
2485 if (sh->batch_head && bi->bi_error && !replacement)
2486 set_bit(STRIPE_BATCH_ERR, &sh->batch_head->state);
2488 if (!test_and_clear_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags))
2489 clear_bit(R5_LOCKED, &sh->dev[i].flags);
2490 set_bit(STRIPE_HANDLE, &sh->state);
2491 raid5_release_stripe(sh);
2493 if (sh->batch_head && sh != sh->batch_head)
2494 raid5_release_stripe(sh->batch_head);
2497 static void raid5_build_block(struct stripe_head *sh, int i, int previous)
2499 struct r5dev *dev = &sh->dev[i];
2501 bio_init(&dev->req);
2502 dev->req.bi_io_vec = &dev->vec;
2503 dev->req.bi_max_vecs = 1;
2504 dev->req.bi_private = sh;
2506 bio_init(&dev->rreq);
2507 dev->rreq.bi_io_vec = &dev->rvec;
2508 dev->rreq.bi_max_vecs = 1;
2509 dev->rreq.bi_private = sh;
2512 dev->sector = raid5_compute_blocknr(sh, i, previous);
2515 static void error(struct mddev *mddev, struct md_rdev *rdev)
2517 char b[BDEVNAME_SIZE];
2518 struct r5conf *conf = mddev->private;
2519 unsigned long flags;
2520 pr_debug("raid456: error called\n");
2522 spin_lock_irqsave(&conf->device_lock, flags);
2523 clear_bit(In_sync, &rdev->flags);
2524 mddev->degraded = calc_degraded(conf);
2525 spin_unlock_irqrestore(&conf->device_lock, flags);
2526 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
2528 set_bit(Blocked, &rdev->flags);
2529 set_bit(Faulty, &rdev->flags);
2530 set_bit(MD_CHANGE_DEVS, &mddev->flags);
2531 set_bit(MD_CHANGE_PENDING, &mddev->flags);
2533 "md/raid:%s: Disk failure on %s, disabling device.\n"
2534 "md/raid:%s: Operation continuing on %d devices.\n",
2536 bdevname(rdev->bdev, b),
2538 conf->raid_disks - mddev->degraded);
2542 * Input: a 'big' sector number,
2543 * Output: index of the data and parity disk, and the sector # in them.
2545 sector_t raid5_compute_sector(struct r5conf *conf, sector_t r_sector,
2546 int previous, int *dd_idx,
2547 struct stripe_head *sh)
2549 sector_t stripe, stripe2;
2550 sector_t chunk_number;
2551 unsigned int chunk_offset;
2554 sector_t new_sector;
2555 int algorithm = previous ? conf->prev_algo
2557 int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2558 : conf->chunk_sectors;
2559 int raid_disks = previous ? conf->previous_raid_disks
2561 int data_disks = raid_disks - conf->max_degraded;
2563 /* First compute the information on this sector */
2566 * Compute the chunk number and the sector offset inside the chunk
2568 chunk_offset = sector_div(r_sector, sectors_per_chunk);
2569 chunk_number = r_sector;
2572 * Compute the stripe number
2574 stripe = chunk_number;
2575 *dd_idx = sector_div(stripe, data_disks);
2578 * Select the parity disk based on the user selected algorithm.
2580 pd_idx = qd_idx = -1;
2581 switch(conf->level) {
2583 pd_idx = data_disks;
2586 switch (algorithm) {
2587 case ALGORITHM_LEFT_ASYMMETRIC:
2588 pd_idx = data_disks - sector_div(stripe2, raid_disks);
2589 if (*dd_idx >= pd_idx)
2592 case ALGORITHM_RIGHT_ASYMMETRIC:
2593 pd_idx = sector_div(stripe2, raid_disks);
2594 if (*dd_idx >= pd_idx)
2597 case ALGORITHM_LEFT_SYMMETRIC:
2598 pd_idx = data_disks - sector_div(stripe2, raid_disks);
2599 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2601 case ALGORITHM_RIGHT_SYMMETRIC:
2602 pd_idx = sector_div(stripe2, raid_disks);
2603 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2605 case ALGORITHM_PARITY_0:
2609 case ALGORITHM_PARITY_N:
2610 pd_idx = data_disks;
2618 switch (algorithm) {
2619 case ALGORITHM_LEFT_ASYMMETRIC:
2620 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2621 qd_idx = pd_idx + 1;
2622 if (pd_idx == raid_disks-1) {
2623 (*dd_idx)++; /* Q D D D P */
2625 } else if (*dd_idx >= pd_idx)
2626 (*dd_idx) += 2; /* D D P Q D */
2628 case ALGORITHM_RIGHT_ASYMMETRIC:
2629 pd_idx = sector_div(stripe2, raid_disks);
2630 qd_idx = pd_idx + 1;
2631 if (pd_idx == raid_disks-1) {
2632 (*dd_idx)++; /* Q D D D P */
2634 } else if (*dd_idx >= pd_idx)
2635 (*dd_idx) += 2; /* D D P Q D */
2637 case ALGORITHM_LEFT_SYMMETRIC:
2638 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2639 qd_idx = (pd_idx + 1) % raid_disks;
2640 *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
2642 case ALGORITHM_RIGHT_SYMMETRIC:
2643 pd_idx = sector_div(stripe2, raid_disks);
2644 qd_idx = (pd_idx + 1) % raid_disks;
2645 *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
2648 case ALGORITHM_PARITY_0:
2653 case ALGORITHM_PARITY_N:
2654 pd_idx = data_disks;
2655 qd_idx = data_disks + 1;
2658 case ALGORITHM_ROTATING_ZERO_RESTART:
2659 /* Exactly the same as RIGHT_ASYMMETRIC, but or
2660 * of blocks for computing Q is different.
2662 pd_idx = sector_div(stripe2, raid_disks);
2663 qd_idx = pd_idx + 1;
2664 if (pd_idx == raid_disks-1) {
2665 (*dd_idx)++; /* Q D D D P */
2667 } else if (*dd_idx >= pd_idx)
2668 (*dd_idx) += 2; /* D D P Q D */
2672 case ALGORITHM_ROTATING_N_RESTART:
2673 /* Same a left_asymmetric, by first stripe is
2674 * D D D P Q rather than
2678 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2679 qd_idx = pd_idx + 1;
2680 if (pd_idx == raid_disks-1) {
2681 (*dd_idx)++; /* Q D D D P */
2683 } else if (*dd_idx >= pd_idx)
2684 (*dd_idx) += 2; /* D D P Q D */
2688 case ALGORITHM_ROTATING_N_CONTINUE:
2689 /* Same as left_symmetric but Q is before P */
2690 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2691 qd_idx = (pd_idx + raid_disks - 1) % raid_disks;
2692 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2696 case ALGORITHM_LEFT_ASYMMETRIC_6:
2697 /* RAID5 left_asymmetric, with Q on last device */
2698 pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
2699 if (*dd_idx >= pd_idx)
2701 qd_idx = raid_disks - 1;
2704 case ALGORITHM_RIGHT_ASYMMETRIC_6:
2705 pd_idx = sector_div(stripe2, raid_disks-1);
2706 if (*dd_idx >= pd_idx)
2708 qd_idx = raid_disks - 1;
2711 case ALGORITHM_LEFT_SYMMETRIC_6:
2712 pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
2713 *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
2714 qd_idx = raid_disks - 1;
2717 case ALGORITHM_RIGHT_SYMMETRIC_6:
2718 pd_idx = sector_div(stripe2, raid_disks-1);
2719 *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
2720 qd_idx = raid_disks - 1;
2723 case ALGORITHM_PARITY_0_6:
2726 qd_idx = raid_disks - 1;
2736 sh->pd_idx = pd_idx;
2737 sh->qd_idx = qd_idx;
2738 sh->ddf_layout = ddf_layout;
2741 * Finally, compute the new sector number
2743 new_sector = (sector_t)stripe * sectors_per_chunk + chunk_offset;
2747 sector_t raid5_compute_blocknr(struct stripe_head *sh, int i, int previous)
2749 struct r5conf *conf = sh->raid_conf;
2750 int raid_disks = sh->disks;
2751 int data_disks = raid_disks - conf->max_degraded;
2752 sector_t new_sector = sh->sector, check;
2753 int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2754 : conf->chunk_sectors;
2755 int algorithm = previous ? conf->prev_algo
2759 sector_t chunk_number;
2760 int dummy1, dd_idx = i;
2762 struct stripe_head sh2;
2764 chunk_offset = sector_div(new_sector, sectors_per_chunk);
2765 stripe = new_sector;
2767 if (i == sh->pd_idx)
2769 switch(conf->level) {
2772 switch (algorithm) {
2773 case ALGORITHM_LEFT_ASYMMETRIC:
2774 case ALGORITHM_RIGHT_ASYMMETRIC:
2778 case ALGORITHM_LEFT_SYMMETRIC:
2779 case ALGORITHM_RIGHT_SYMMETRIC:
2782 i -= (sh->pd_idx + 1);
2784 case ALGORITHM_PARITY_0:
2787 case ALGORITHM_PARITY_N:
2794 if (i == sh->qd_idx)
2795 return 0; /* It is the Q disk */
2796 switch (algorithm) {
2797 case ALGORITHM_LEFT_ASYMMETRIC:
2798 case ALGORITHM_RIGHT_ASYMMETRIC:
2799 case ALGORITHM_ROTATING_ZERO_RESTART:
2800 case ALGORITHM_ROTATING_N_RESTART:
2801 if (sh->pd_idx == raid_disks-1)
2802 i--; /* Q D D D P */
2803 else if (i > sh->pd_idx)
2804 i -= 2; /* D D P Q D */
2806 case ALGORITHM_LEFT_SYMMETRIC:
2807 case ALGORITHM_RIGHT_SYMMETRIC:
2808 if (sh->pd_idx == raid_disks-1)
2809 i--; /* Q D D D P */
2814 i -= (sh->pd_idx + 2);
2817 case ALGORITHM_PARITY_0:
2820 case ALGORITHM_PARITY_N:
2822 case ALGORITHM_ROTATING_N_CONTINUE:
2823 /* Like left_symmetric, but P is before Q */
2824 if (sh->pd_idx == 0)
2825 i--; /* P D D D Q */
2830 i -= (sh->pd_idx + 1);
2833 case ALGORITHM_LEFT_ASYMMETRIC_6:
2834 case ALGORITHM_RIGHT_ASYMMETRIC_6:
2838 case ALGORITHM_LEFT_SYMMETRIC_6:
2839 case ALGORITHM_RIGHT_SYMMETRIC_6:
2841 i += data_disks + 1;
2842 i -= (sh->pd_idx + 1);
2844 case ALGORITHM_PARITY_0_6:
2853 chunk_number = stripe * data_disks + i;
2854 r_sector = chunk_number * sectors_per_chunk + chunk_offset;
2856 check = raid5_compute_sector(conf, r_sector,
2857 previous, &dummy1, &sh2);
2858 if (check != sh->sector || dummy1 != dd_idx || sh2.pd_idx != sh->pd_idx
2859 || sh2.qd_idx != sh->qd_idx) {
2860 printk(KERN_ERR "md/raid:%s: compute_blocknr: map not correct\n",
2861 mdname(conf->mddev));
2868 schedule_reconstruction(struct stripe_head *sh, struct stripe_head_state *s,
2869 int rcw, int expand)
2871 int i, pd_idx = sh->pd_idx, qd_idx = sh->qd_idx, disks = sh->disks;
2872 struct r5conf *conf = sh->raid_conf;
2873 int level = conf->level;
2877 for (i = disks; i--; ) {
2878 struct r5dev *dev = &sh->dev[i];
2881 set_bit(R5_LOCKED, &dev->flags);
2882 set_bit(R5_Wantdrain, &dev->flags);
2884 clear_bit(R5_UPTODATE, &dev->flags);
2888 /* if we are not expanding this is a proper write request, and
2889 * there will be bios with new data to be drained into the
2894 /* False alarm, nothing to do */
2896 sh->reconstruct_state = reconstruct_state_drain_run;
2897 set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
2899 sh->reconstruct_state = reconstruct_state_run;
2901 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
2903 if (s->locked + conf->max_degraded == disks)
2904 if (!test_and_set_bit(STRIPE_FULL_WRITE, &sh->state))
2905 atomic_inc(&conf->pending_full_writes);
2907 BUG_ON(!(test_bit(R5_UPTODATE, &sh->dev[pd_idx].flags) ||
2908 test_bit(R5_Wantcompute, &sh->dev[pd_idx].flags)));
2909 BUG_ON(level == 6 &&
2910 (!(test_bit(R5_UPTODATE, &sh->dev[qd_idx].flags) ||
2911 test_bit(R5_Wantcompute, &sh->dev[qd_idx].flags))));
2913 for (i = disks; i--; ) {
2914 struct r5dev *dev = &sh->dev[i];
2915 if (i == pd_idx || i == qd_idx)
2919 (test_bit(R5_UPTODATE, &dev->flags) ||
2920 test_bit(R5_Wantcompute, &dev->flags))) {
2921 set_bit(R5_Wantdrain, &dev->flags);
2922 set_bit(R5_LOCKED, &dev->flags);
2923 clear_bit(R5_UPTODATE, &dev->flags);
2928 /* False alarm - nothing to do */
2930 sh->reconstruct_state = reconstruct_state_prexor_drain_run;
2931 set_bit(STRIPE_OP_PREXOR, &s->ops_request);
2932 set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
2933 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
2936 /* keep the parity disk(s) locked while asynchronous operations
2939 set_bit(R5_LOCKED, &sh->dev[pd_idx].flags);
2940 clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
2944 int qd_idx = sh->qd_idx;
2945 struct r5dev *dev = &sh->dev[qd_idx];
2947 set_bit(R5_LOCKED, &dev->flags);
2948 clear_bit(R5_UPTODATE, &dev->flags);
2952 pr_debug("%s: stripe %llu locked: %d ops_request: %lx\n",
2953 __func__, (unsigned long long)sh->sector,
2954 s->locked, s->ops_request);
2958 * Each stripe/dev can have one or more bion attached.
2959 * toread/towrite point to the first in a chain.
2960 * The bi_next chain must be in order.
2962 static int add_stripe_bio(struct stripe_head *sh, struct bio *bi, int dd_idx,
2963 int forwrite, int previous)
2966 struct r5conf *conf = sh->raid_conf;
2969 pr_debug("adding bi b#%llu to stripe s#%llu\n",
2970 (unsigned long long)bi->bi_iter.bi_sector,
2971 (unsigned long long)sh->sector);
2974 * If several bio share a stripe. The bio bi_phys_segments acts as a
2975 * reference count to avoid race. The reference count should already be
2976 * increased before this function is called (for example, in
2977 * make_request()), so other bio sharing this stripe will not free the
2978 * stripe. If a stripe is owned by one stripe, the stripe lock will
2981 spin_lock_irq(&sh->stripe_lock);
2982 /* Don't allow new IO added to stripes in batch list */
2986 bip = &sh->dev[dd_idx].towrite;
2990 bip = &sh->dev[dd_idx].toread;
2991 while (*bip && (*bip)->bi_iter.bi_sector < bi->bi_iter.bi_sector) {
2992 if (bio_end_sector(*bip) > bi->bi_iter.bi_sector)
2994 bip = & (*bip)->bi_next;
2996 if (*bip && (*bip)->bi_iter.bi_sector < bio_end_sector(bi))
2999 if (!forwrite || previous)
3000 clear_bit(STRIPE_BATCH_READY, &sh->state);
3002 BUG_ON(*bip && bi->bi_next && (*bip) != bi->bi_next);
3006 raid5_inc_bi_active_stripes(bi);
3009 /* check if page is covered */
3010 sector_t sector = sh->dev[dd_idx].sector;
3011 for (bi=sh->dev[dd_idx].towrite;
3012 sector < sh->dev[dd_idx].sector + STRIPE_SECTORS &&
3013 bi && bi->bi_iter.bi_sector <= sector;
3014 bi = r5_next_bio(bi, sh->dev[dd_idx].sector)) {
3015 if (bio_end_sector(bi) >= sector)
3016 sector = bio_end_sector(bi);
3018 if (sector >= sh->dev[dd_idx].sector + STRIPE_SECTORS)
3019 if (!test_and_set_bit(R5_OVERWRITE, &sh->dev[dd_idx].flags))
3020 sh->overwrite_disks++;
3023 pr_debug("added bi b#%llu to stripe s#%llu, disk %d.\n",
3024 (unsigned long long)(*bip)->bi_iter.bi_sector,
3025 (unsigned long long)sh->sector, dd_idx);
3027 if (conf->mddev->bitmap && firstwrite) {
3028 /* Cannot hold spinlock over bitmap_startwrite,
3029 * but must ensure this isn't added to a batch until
3030 * we have added to the bitmap and set bm_seq.
3031 * So set STRIPE_BITMAP_PENDING to prevent
3033 * If multiple add_stripe_bio() calls race here they
3034 * much all set STRIPE_BITMAP_PENDING. So only the first one
3035 * to complete "bitmap_startwrite" gets to set
3036 * STRIPE_BIT_DELAY. This is important as once a stripe
3037 * is added to a batch, STRIPE_BIT_DELAY cannot be changed
3040 set_bit(STRIPE_BITMAP_PENDING, &sh->state);
3041 spin_unlock_irq(&sh->stripe_lock);
3042 bitmap_startwrite(conf->mddev->bitmap, sh->sector,
3044 spin_lock_irq(&sh->stripe_lock);
3045 clear_bit(STRIPE_BITMAP_PENDING, &sh->state);
3046 if (!sh->batch_head) {
3047 sh->bm_seq = conf->seq_flush+1;
3048 set_bit(STRIPE_BIT_DELAY, &sh->state);
3051 spin_unlock_irq(&sh->stripe_lock);
3053 if (stripe_can_batch(sh))
3054 stripe_add_to_batch_list(conf, sh);
3058 set_bit(R5_Overlap, &sh->dev[dd_idx].flags);
3059 spin_unlock_irq(&sh->stripe_lock);
3063 static void end_reshape(struct r5conf *conf);
3065 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
3066 struct stripe_head *sh)
3068 int sectors_per_chunk =
3069 previous ? conf->prev_chunk_sectors : conf->chunk_sectors;
3071 int chunk_offset = sector_div(stripe, sectors_per_chunk);
3072 int disks = previous ? conf->previous_raid_disks : conf->raid_disks;
3074 raid5_compute_sector(conf,
3075 stripe * (disks - conf->max_degraded)
3076 *sectors_per_chunk + chunk_offset,
3082 handle_failed_stripe(struct r5conf *conf, struct stripe_head *sh,
3083 struct stripe_head_state *s, int disks,
3084 struct bio_list *return_bi)
3087 BUG_ON(sh->batch_head);
3088 for (i = disks; i--; ) {
3092 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
3093 struct md_rdev *rdev;
3095 rdev = rcu_dereference(conf->disks[i].rdev);
3096 if (rdev && test_bit(In_sync, &rdev->flags))
3097 atomic_inc(&rdev->nr_pending);
3102 if (!rdev_set_badblocks(
3106 md_error(conf->mddev, rdev);
3107 rdev_dec_pending(rdev, conf->mddev);
3110 spin_lock_irq(&sh->stripe_lock);
3111 /* fail all writes first */
3112 bi = sh->dev[i].towrite;
3113 sh->dev[i].towrite = NULL;
3114 sh->overwrite_disks = 0;
3115 spin_unlock_irq(&sh->stripe_lock);
3119 r5l_stripe_write_finished(sh);
3121 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3122 wake_up(&conf->wait_for_overlap);
3124 while (bi && bi->bi_iter.bi_sector <
3125 sh->dev[i].sector + STRIPE_SECTORS) {
3126 struct bio *nextbi = r5_next_bio(bi, sh->dev[i].sector);
3128 bi->bi_error = -EIO;
3129 if (!raid5_dec_bi_active_stripes(bi)) {
3130 md_write_end(conf->mddev);
3131 bio_list_add(return_bi, bi);
3136 bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3137 STRIPE_SECTORS, 0, 0);
3139 /* and fail all 'written' */
3140 bi = sh->dev[i].written;
3141 sh->dev[i].written = NULL;
3142 if (test_and_clear_bit(R5_SkipCopy, &sh->dev[i].flags)) {
3143 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
3144 sh->dev[i].page = sh->dev[i].orig_page;
3147 if (bi) bitmap_end = 1;
3148 while (bi && bi->bi_iter.bi_sector <
3149 sh->dev[i].sector + STRIPE_SECTORS) {
3150 struct bio *bi2 = r5_next_bio(bi, sh->dev[i].sector);
3152 bi->bi_error = -EIO;
3153 if (!raid5_dec_bi_active_stripes(bi)) {
3154 md_write_end(conf->mddev);
3155 bio_list_add(return_bi, bi);
3160 /* fail any reads if this device is non-operational and
3161 * the data has not reached the cache yet.
3163 if (!test_bit(R5_Wantfill, &sh->dev[i].flags) &&
3164 s->failed > conf->max_degraded &&
3165 (!test_bit(R5_Insync, &sh->dev[i].flags) ||
3166 test_bit(R5_ReadError, &sh->dev[i].flags))) {
3167 spin_lock_irq(&sh->stripe_lock);
3168 bi = sh->dev[i].toread;
3169 sh->dev[i].toread = NULL;
3170 spin_unlock_irq(&sh->stripe_lock);
3171 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3172 wake_up(&conf->wait_for_overlap);
3175 while (bi && bi->bi_iter.bi_sector <
3176 sh->dev[i].sector + STRIPE_SECTORS) {
3177 struct bio *nextbi =
3178 r5_next_bio(bi, sh->dev[i].sector);
3180 bi->bi_error = -EIO;
3181 if (!raid5_dec_bi_active_stripes(bi))
3182 bio_list_add(return_bi, bi);
3187 bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3188 STRIPE_SECTORS, 0, 0);
3189 /* If we were in the middle of a write the parity block might
3190 * still be locked - so just clear all R5_LOCKED flags
3192 clear_bit(R5_LOCKED, &sh->dev[i].flags);
3197 if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
3198 if (atomic_dec_and_test(&conf->pending_full_writes))
3199 md_wakeup_thread(conf->mddev->thread);
3203 handle_failed_sync(struct r5conf *conf, struct stripe_head *sh,
3204 struct stripe_head_state *s)
3209 BUG_ON(sh->batch_head);
3210 clear_bit(STRIPE_SYNCING, &sh->state);
3211 if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
3212 wake_up(&conf->wait_for_overlap);
3215 /* There is nothing more to do for sync/check/repair.
3216 * Don't even need to abort as that is handled elsewhere
3217 * if needed, and not always wanted e.g. if there is a known
3219 * For recover/replace we need to record a bad block on all
3220 * non-sync devices, or abort the recovery
3222 if (test_bit(MD_RECOVERY_RECOVER, &conf->mddev->recovery)) {
3223 /* During recovery devices cannot be removed, so
3224 * locking and refcounting of rdevs is not needed
3226 for (i = 0; i < conf->raid_disks; i++) {
3227 struct md_rdev *rdev = conf->disks[i].rdev;
3229 && !test_bit(Faulty, &rdev->flags)
3230 && !test_bit(In_sync, &rdev->flags)
3231 && !rdev_set_badblocks(rdev, sh->sector,
3234 rdev = conf->disks[i].replacement;
3236 && !test_bit(Faulty, &rdev->flags)
3237 && !test_bit(In_sync, &rdev->flags)
3238 && !rdev_set_badblocks(rdev, sh->sector,
3243 conf->recovery_disabled =
3244 conf->mddev->recovery_disabled;
3246 md_done_sync(conf->mddev, STRIPE_SECTORS, !abort);
3249 static int want_replace(struct stripe_head *sh, int disk_idx)
3251 struct md_rdev *rdev;
3253 /* Doing recovery so rcu locking not required */
3254 rdev = sh->raid_conf->disks[disk_idx].replacement;
3256 && !test_bit(Faulty, &rdev->flags)
3257 && !test_bit(In_sync, &rdev->flags)
3258 && (rdev->recovery_offset <= sh->sector
3259 || rdev->mddev->recovery_cp <= sh->sector))
3265 /* fetch_block - checks the given member device to see if its data needs
3266 * to be read or computed to satisfy a request.
3268 * Returns 1 when no more member devices need to be checked, otherwise returns
3269 * 0 to tell the loop in handle_stripe_fill to continue
3272 static int need_this_block(struct stripe_head *sh, struct stripe_head_state *s,
3273 int disk_idx, int disks)
3275 struct r5dev *dev = &sh->dev[disk_idx];
3276 struct r5dev *fdev[2] = { &sh->dev[s->failed_num[0]],
3277 &sh->dev[s->failed_num[1]] };
3281 if (test_bit(R5_LOCKED, &dev->flags) ||
3282 test_bit(R5_UPTODATE, &dev->flags))
3283 /* No point reading this as we already have it or have
3284 * decided to get it.
3289 (dev->towrite && !test_bit(R5_OVERWRITE, &dev->flags)))
3290 /* We need this block to directly satisfy a request */
3293 if (s->syncing || s->expanding ||
3294 (s->replacing && want_replace(sh, disk_idx)))
3295 /* When syncing, or expanding we read everything.
3296 * When replacing, we need the replaced block.
3300 if ((s->failed >= 1 && fdev[0]->toread) ||
3301 (s->failed >= 2 && fdev[1]->toread))
3302 /* If we want to read from a failed device, then
3303 * we need to actually read every other device.
3307 /* Sometimes neither read-modify-write nor reconstruct-write
3308 * cycles can work. In those cases we read every block we
3309 * can. Then the parity-update is certain to have enough to
3311 * This can only be a problem when we need to write something,
3312 * and some device has failed. If either of those tests
3313 * fail we need look no further.
3315 if (!s->failed || !s->to_write)
3318 if (test_bit(R5_Insync, &dev->flags) &&
3319 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3320 /* Pre-reads at not permitted until after short delay
3321 * to gather multiple requests. However if this
3322 * device is no Insync, the block could only be be computed
3323 * and there is no need to delay that.
3327 for (i = 0; i < s->failed && i < 2; i++) {
3328 if (fdev[i]->towrite &&
3329 !test_bit(R5_UPTODATE, &fdev[i]->flags) &&
3330 !test_bit(R5_OVERWRITE, &fdev[i]->flags))
3331 /* If we have a partial write to a failed
3332 * device, then we will need to reconstruct
3333 * the content of that device, so all other
3334 * devices must be read.
3339 /* If we are forced to do a reconstruct-write, either because
3340 * the current RAID6 implementation only supports that, or
3341 * or because parity cannot be trusted and we are currently
3342 * recovering it, there is extra need to be careful.
3343 * If one of the devices that we would need to read, because
3344 * it is not being overwritten (and maybe not written at all)
3345 * is missing/faulty, then we need to read everything we can.
3347 if (sh->raid_conf->level != 6 &&
3348 sh->raid_conf->rmw_level != PARITY_DISABLE_RMW &&
3349 sh->sector < sh->raid_conf->mddev->recovery_cp)
3350 /* reconstruct-write isn't being forced */
3352 for (i = 0; i < s->failed && i < 2; i++) {
3353 if (s->failed_num[i] != sh->pd_idx &&
3354 s->failed_num[i] != sh->qd_idx &&
3355 !test_bit(R5_UPTODATE, &fdev[i]->flags) &&
3356 !test_bit(R5_OVERWRITE, &fdev[i]->flags))
3363 static int fetch_block(struct stripe_head *sh, struct stripe_head_state *s,
3364 int disk_idx, int disks)
3366 struct r5dev *dev = &sh->dev[disk_idx];
3368 /* is the data in this block needed, and can we get it? */
3369 if (need_this_block(sh, s, disk_idx, disks)) {
3370 /* we would like to get this block, possibly by computing it,
3371 * otherwise read it if the backing disk is insync
3373 BUG_ON(test_bit(R5_Wantcompute, &dev->flags));
3374 BUG_ON(test_bit(R5_Wantread, &dev->flags));
3375 BUG_ON(sh->batch_head);
3378 * In the raid6 case if the only non-uptodate disk is P
3379 * then we already trusted P to compute the other failed
3380 * drives. It is safe to compute rather than re-read P.
3381 * In other cases we only compute blocks from failed
3382 * devices, otherwise check/repair might fail to detect
3383 * a real inconsistency.
3386 if ((s->uptodate == disks - 1) &&
3387 ((sh->qd_idx >= 0 && sh->pd_idx == disk_idx) ||
3388 (s->failed && (disk_idx == s->failed_num[0] ||
3389 disk_idx == s->failed_num[1])))) {
3390 /* have disk failed, and we're requested to fetch it;
3393 pr_debug("Computing stripe %llu block %d\n",
3394 (unsigned long long)sh->sector, disk_idx);
3395 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3396 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3397 set_bit(R5_Wantcompute, &dev->flags);
3398 sh->ops.target = disk_idx;
3399 sh->ops.target2 = -1; /* no 2nd target */
3401 /* Careful: from this point on 'uptodate' is in the eye
3402 * of raid_run_ops which services 'compute' operations
3403 * before writes. R5_Wantcompute flags a block that will
3404 * be R5_UPTODATE by the time it is needed for a
3405 * subsequent operation.
3409 } else if (s->uptodate == disks-2 && s->failed >= 2) {
3410 /* Computing 2-failure is *very* expensive; only
3411 * do it if failed >= 2
3414 for (other = disks; other--; ) {
3415 if (other == disk_idx)
3417 if (!test_bit(R5_UPTODATE,
3418 &sh->dev[other].flags))
3422 pr_debug("Computing stripe %llu blocks %d,%d\n",
3423 (unsigned long long)sh->sector,
3425 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3426 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3427 set_bit(R5_Wantcompute, &sh->dev[disk_idx].flags);
3428 set_bit(R5_Wantcompute, &sh->dev[other].flags);
3429 sh->ops.target = disk_idx;
3430 sh->ops.target2 = other;
3434 } else if (test_bit(R5_Insync, &dev->flags)) {
3435 set_bit(R5_LOCKED, &dev->flags);
3436 set_bit(R5_Wantread, &dev->flags);
3438 pr_debug("Reading block %d (sync=%d)\n",
3439 disk_idx, s->syncing);
3447 * handle_stripe_fill - read or compute data to satisfy pending requests.
3449 static void handle_stripe_fill(struct stripe_head *sh,
3450 struct stripe_head_state *s,
3455 /* look for blocks to read/compute, skip this if a compute
3456 * is already in flight, or if the stripe contents are in the
3457 * midst of changing due to a write
3459 if (!test_bit(STRIPE_COMPUTE_RUN, &sh->state) && !sh->check_state &&
3460 !sh->reconstruct_state)
3461 for (i = disks; i--; )
3462 if (fetch_block(sh, s, i, disks))
3464 set_bit(STRIPE_HANDLE, &sh->state);
3467 static void break_stripe_batch_list(struct stripe_head *head_sh,
3468 unsigned long handle_flags);
3469 /* handle_stripe_clean_event
3470 * any written block on an uptodate or failed drive can be returned.
3471 * Note that if we 'wrote' to a failed drive, it will be UPTODATE, but
3472 * never LOCKED, so we don't need to test 'failed' directly.
3474 static void handle_stripe_clean_event(struct r5conf *conf,
3475 struct stripe_head *sh, int disks, struct bio_list *return_bi)
3479 int discard_pending = 0;
3480 struct stripe_head *head_sh = sh;
3481 bool do_endio = false;
3483 for (i = disks; i--; )
3484 if (sh->dev[i].written) {
3486 if (!test_bit(R5_LOCKED, &dev->flags) &&
3487 (test_bit(R5_UPTODATE, &dev->flags) ||
3488 test_bit(R5_Discard, &dev->flags) ||
3489 test_bit(R5_SkipCopy, &dev->flags))) {
3490 /* We can return any write requests */
3491 struct bio *wbi, *wbi2;
3492 pr_debug("Return write for disc %d\n", i);
3493 if (test_and_clear_bit(R5_Discard, &dev->flags))
3494 clear_bit(R5_UPTODATE, &dev->flags);
3495 if (test_and_clear_bit(R5_SkipCopy, &dev->flags)) {
3496 WARN_ON(test_bit(R5_UPTODATE, &dev->flags));
3501 dev->page = dev->orig_page;
3503 dev->written = NULL;
3504 while (wbi && wbi->bi_iter.bi_sector <
3505 dev->sector + STRIPE_SECTORS) {
3506 wbi2 = r5_next_bio(wbi, dev->sector);
3507 if (!raid5_dec_bi_active_stripes(wbi)) {
3508 md_write_end(conf->mddev);
3509 bio_list_add(return_bi, wbi);
3513 bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3515 !test_bit(STRIPE_DEGRADED, &sh->state),
3517 if (head_sh->batch_head) {
3518 sh = list_first_entry(&sh->batch_list,
3521 if (sh != head_sh) {
3528 } else if (test_bit(R5_Discard, &dev->flags))
3529 discard_pending = 1;
3530 WARN_ON(test_bit(R5_SkipCopy, &dev->flags));
3531 WARN_ON(dev->page != dev->orig_page);
3534 r5l_stripe_write_finished(sh);
3536 if (!discard_pending &&
3537 test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags)) {
3539 clear_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
3540 clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
3541 if (sh->qd_idx >= 0) {
3542 clear_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
3543 clear_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags);
3545 /* now that discard is done we can proceed with any sync */
3546 clear_bit(STRIPE_DISCARD, &sh->state);
3548 * SCSI discard will change some bio fields and the stripe has
3549 * no updated data, so remove it from hash list and the stripe
3550 * will be reinitialized
3553 hash = sh->hash_lock_index;
3554 spin_lock_irq(conf->hash_locks + hash);
3556 spin_unlock_irq(conf->hash_locks + hash);
3557 if (head_sh->batch_head) {
3558 sh = list_first_entry(&sh->batch_list,
3559 struct stripe_head, batch_list);
3565 if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state))
3566 set_bit(STRIPE_HANDLE, &sh->state);
3570 if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
3571 if (atomic_dec_and_test(&conf->pending_full_writes))
3572 md_wakeup_thread(conf->mddev->thread);
3574 if (head_sh->batch_head && do_endio)
3575 break_stripe_batch_list(head_sh, STRIPE_EXPAND_SYNC_FLAGS);
3578 static void handle_stripe_dirtying(struct r5conf *conf,
3579 struct stripe_head *sh,
3580 struct stripe_head_state *s,
3583 int rmw = 0, rcw = 0, i;
3584 sector_t recovery_cp = conf->mddev->recovery_cp;
3586 /* Check whether resync is now happening or should start.
3587 * If yes, then the array is dirty (after unclean shutdown or
3588 * initial creation), so parity in some stripes might be inconsistent.
3589 * In this case, we need to always do reconstruct-write, to ensure
3590 * that in case of drive failure or read-error correction, we
3591 * generate correct data from the parity.
3593 if (conf->rmw_level == PARITY_DISABLE_RMW ||
3594 (recovery_cp < MaxSector && sh->sector >= recovery_cp &&
3596 /* Calculate the real rcw later - for now make it
3597 * look like rcw is cheaper
3600 pr_debug("force RCW rmw_level=%u, recovery_cp=%llu sh->sector=%llu\n",
3601 conf->rmw_level, (unsigned long long)recovery_cp,
3602 (unsigned long long)sh->sector);
3603 } else for (i = disks; i--; ) {
3604 /* would I have to read this buffer for read_modify_write */
3605 struct r5dev *dev = &sh->dev[i];
3606 if ((dev->towrite || i == sh->pd_idx || i == sh->qd_idx) &&
3607 !test_bit(R5_LOCKED, &dev->flags) &&
3608 !(test_bit(R5_UPTODATE, &dev->flags) ||
3609 test_bit(R5_Wantcompute, &dev->flags))) {
3610 if (test_bit(R5_Insync, &dev->flags))
3613 rmw += 2*disks; /* cannot read it */
3615 /* Would I have to read this buffer for reconstruct_write */
3616 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
3617 i != sh->pd_idx && i != sh->qd_idx &&
3618 !test_bit(R5_LOCKED, &dev->flags) &&
3619 !(test_bit(R5_UPTODATE, &dev->flags) ||
3620 test_bit(R5_Wantcompute, &dev->flags))) {
3621 if (test_bit(R5_Insync, &dev->flags))
3627 pr_debug("for sector %llu, rmw=%d rcw=%d\n",
3628 (unsigned long long)sh->sector, rmw, rcw);
3629 set_bit(STRIPE_HANDLE, &sh->state);
3630 if ((rmw < rcw || (rmw == rcw && conf->rmw_level == PARITY_ENABLE_RMW)) && rmw > 0) {
3631 /* prefer read-modify-write, but need to get some data */
3632 if (conf->mddev->queue)
3633 blk_add_trace_msg(conf->mddev->queue,
3634 "raid5 rmw %llu %d",
3635 (unsigned long long)sh->sector, rmw);
3636 for (i = disks; i--; ) {
3637 struct r5dev *dev = &sh->dev[i];
3638 if ((dev->towrite || i == sh->pd_idx || i == sh->qd_idx) &&
3639 !test_bit(R5_LOCKED, &dev->flags) &&
3640 !(test_bit(R5_UPTODATE, &dev->flags) ||
3641 test_bit(R5_Wantcompute, &dev->flags)) &&
3642 test_bit(R5_Insync, &dev->flags)) {
3643 if (test_bit(STRIPE_PREREAD_ACTIVE,
3645 pr_debug("Read_old block %d for r-m-w\n",
3647 set_bit(R5_LOCKED, &dev->flags);
3648 set_bit(R5_Wantread, &dev->flags);
3651 set_bit(STRIPE_DELAYED, &sh->state);
3652 set_bit(STRIPE_HANDLE, &sh->state);
3657 if ((rcw < rmw || (rcw == rmw && conf->rmw_level != PARITY_ENABLE_RMW)) && rcw > 0) {
3658 /* want reconstruct write, but need to get some data */
3661 for (i = disks; i--; ) {
3662 struct r5dev *dev = &sh->dev[i];
3663 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
3664 i != sh->pd_idx && i != sh->qd_idx &&
3665 !test_bit(R5_LOCKED, &dev->flags) &&
3666 !(test_bit(R5_UPTODATE, &dev->flags) ||
3667 test_bit(R5_Wantcompute, &dev->flags))) {
3669 if (test_bit(R5_Insync, &dev->flags) &&
3670 test_bit(STRIPE_PREREAD_ACTIVE,
3672 pr_debug("Read_old block "
3673 "%d for Reconstruct\n", i);
3674 set_bit(R5_LOCKED, &dev->flags);
3675 set_bit(R5_Wantread, &dev->flags);
3679 set_bit(STRIPE_DELAYED, &sh->state);
3680 set_bit(STRIPE_HANDLE, &sh->state);
3684 if (rcw && conf->mddev->queue)
3685 blk_add_trace_msg(conf->mddev->queue, "raid5 rcw %llu %d %d %d",
3686 (unsigned long long)sh->sector,
3687 rcw, qread, test_bit(STRIPE_DELAYED, &sh->state));
3690 if (rcw > disks && rmw > disks &&
3691 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3692 set_bit(STRIPE_DELAYED, &sh->state);
3694 /* now if nothing is locked, and if we have enough data,
3695 * we can start a write request
3697 /* since handle_stripe can be called at any time we need to handle the
3698 * case where a compute block operation has been submitted and then a
3699 * subsequent call wants to start a write request. raid_run_ops only
3700 * handles the case where compute block and reconstruct are requested
3701 * simultaneously. If this is not the case then new writes need to be
3702 * held off until the compute completes.
3704 if ((s->req_compute || !test_bit(STRIPE_COMPUTE_RUN, &sh->state)) &&
3705 (s->locked == 0 && (rcw == 0 || rmw == 0) &&
3706 !test_bit(STRIPE_BIT_DELAY, &sh->state)))
3707 schedule_reconstruction(sh, s, rcw == 0, 0);
3710 static void handle_parity_checks5(struct r5conf *conf, struct stripe_head *sh,
3711 struct stripe_head_state *s, int disks)
3713 struct r5dev *dev = NULL;
3715 BUG_ON(sh->batch_head);
3716 set_bit(STRIPE_HANDLE, &sh->state);
3718 switch (sh->check_state) {
3719 case check_state_idle:
3720 /* start a new check operation if there are no failures */
3721 if (s->failed == 0) {
3722 BUG_ON(s->uptodate != disks);
3723 sh->check_state = check_state_run;
3724 set_bit(STRIPE_OP_CHECK, &s->ops_request);
3725 clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
3729 dev = &sh->dev[s->failed_num[0]];
3731 case check_state_compute_result:
3732 sh->check_state = check_state_idle;
3734 dev = &sh->dev[sh->pd_idx];
3736 /* check that a write has not made the stripe insync */
3737 if (test_bit(STRIPE_INSYNC, &sh->state))
3740 /* either failed parity check, or recovery is happening */
3741 BUG_ON(!test_bit(R5_UPTODATE, &dev->flags));
3742 BUG_ON(s->uptodate != disks);
3744 set_bit(R5_LOCKED, &dev->flags);
3746 set_bit(R5_Wantwrite, &dev->flags);
3748 clear_bit(STRIPE_DEGRADED, &sh->state);
3749 set_bit(STRIPE_INSYNC, &sh->state);
3751 case check_state_run:
3752 break; /* we will be called again upon completion */
3753 case check_state_check_result:
3754 sh->check_state = check_state_idle;
3756 /* if a failure occurred during the check operation, leave
3757 * STRIPE_INSYNC not set and let the stripe be handled again
3762 /* handle a successful check operation, if parity is correct
3763 * we are done. Otherwise update the mismatch count and repair
3764 * parity if !MD_RECOVERY_CHECK
3766 if ((sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) == 0)
3767 /* parity is correct (on disc,
3768 * not in buffer any more)
3770 set_bit(STRIPE_INSYNC, &sh->state);
3772 atomic64_add(STRIPE_SECTORS, &conf->mddev->resync_mismatches);
3773 if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery))
3774 /* don't try to repair!! */
3775 set_bit(STRIPE_INSYNC, &sh->state);
3777 sh->check_state = check_state_compute_run;
3778 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3779 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3780 set_bit(R5_Wantcompute,
3781 &sh->dev[sh->pd_idx].flags);
3782 sh->ops.target = sh->pd_idx;
3783 sh->ops.target2 = -1;
3788 case check_state_compute_run:
3791 printk(KERN_ERR "%s: unknown check_state: %d sector: %llu\n",
3792 __func__, sh->check_state,
3793 (unsigned long long) sh->sector);
3798 static void handle_parity_checks6(struct r5conf *conf, struct stripe_head *sh,
3799 struct stripe_head_state *s,
3802 int pd_idx = sh->pd_idx;
3803 int qd_idx = sh->qd_idx;
3806 BUG_ON(sh->batch_head);
3807 set_bit(STRIPE_HANDLE, &sh->state);
3809 BUG_ON(s->failed > 2);
3811 /* Want to check and possibly repair P and Q.
3812 * However there could be one 'failed' device, in which
3813 * case we can only check one of them, possibly using the
3814 * other to generate missing data
3817 switch (sh->check_state) {
3818 case check_state_idle:
3819 /* start a new check operation if there are < 2 failures */
3820 if (s->failed == s->q_failed) {
3821 /* The only possible failed device holds Q, so it
3822 * makes sense to check P (If anything else were failed,
3823 * we would have used P to recreate it).
3825 sh->check_state = check_state_run;
3827 if (!s->q_failed && s->failed < 2) {
3828 /* Q is not failed, and we didn't use it to generate
3829 * anything, so it makes sense to check it
3831 if (sh->check_state == check_state_run)
3832 sh->check_state = check_state_run_pq;
3834 sh->check_state = check_state_run_q;
3837 /* discard potentially stale zero_sum_result */
3838 sh->ops.zero_sum_result = 0;
3840 if (sh->check_state == check_state_run) {
3841 /* async_xor_zero_sum destroys the contents of P */
3842 clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
3845 if (sh->check_state >= check_state_run &&
3846 sh->check_state <= check_state_run_pq) {
3847 /* async_syndrome_zero_sum preserves P and Q, so
3848 * no need to mark them !uptodate here
3850 set_bit(STRIPE_OP_CHECK, &s->ops_request);
3854 /* we have 2-disk failure */
3855 BUG_ON(s->failed != 2);
3857 case check_state_compute_result:
3858 sh->check_state = check_state_idle;
3860 /* check that a write has not made the stripe insync */
3861 if (test_bit(STRIPE_INSYNC, &sh->state))
3864 /* now write out any block on a failed drive,
3865 * or P or Q if they were recomputed
3868 if (s->failed == 2) {
3869 dev = &sh->dev[s->failed_num[1]];
3871 set_bit(R5_LOCKED, &dev->flags);
3872 set_bit(R5_Wantwrite, &dev->flags);
3874 if (s->failed >= 1) {
3875 dev = &sh->dev[s->failed_num[0]];
3877 set_bit(R5_LOCKED, &dev->flags);
3878 set_bit(R5_Wantwrite, &dev->flags);
3880 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
3881 dev = &sh->dev[pd_idx];
3883 set_bit(R5_LOCKED, &dev->flags);
3884 set_bit(R5_Wantwrite, &dev->flags);
3886 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
3887 dev = &sh->dev[qd_idx];
3889 set_bit(R5_LOCKED, &dev->flags);
3890 set_bit(R5_Wantwrite, &dev->flags);
3892 if (WARN_ONCE(dev && !test_bit(R5_UPTODATE, &dev->flags),
3893 "%s: disk%td not up to date\n",
3894 mdname(conf->mddev),
3895 dev - (struct r5dev *) &sh->dev)) {
3896 clear_bit(R5_LOCKED, &dev->flags);
3897 clear_bit(R5_Wantwrite, &dev->flags);
3900 clear_bit(STRIPE_DEGRADED, &sh->state);
3902 set_bit(STRIPE_INSYNC, &sh->state);
3904 case check_state_run:
3905 case check_state_run_q:
3906 case check_state_run_pq:
3907 break; /* we will be called again upon completion */
3908 case check_state_check_result:
3909 sh->check_state = check_state_idle;
3911 /* handle a successful check operation, if parity is correct
3912 * we are done. Otherwise update the mismatch count and repair
3913 * parity if !MD_RECOVERY_CHECK
3915 if (sh->ops.zero_sum_result == 0) {
3916 /* both parities are correct */
3918 set_bit(STRIPE_INSYNC, &sh->state);
3920 /* in contrast to the raid5 case we can validate
3921 * parity, but still have a failure to write
3924 sh->check_state = check_state_compute_result;
3925 /* Returning at this point means that we may go
3926 * off and bring p and/or q uptodate again so
3927 * we make sure to check zero_sum_result again
3928 * to verify if p or q need writeback
3932 atomic64_add(STRIPE_SECTORS, &conf->mddev->resync_mismatches);
3933 if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery))
3934 /* don't try to repair!! */
3935 set_bit(STRIPE_INSYNC, &sh->state);
3937 int *target = &sh->ops.target;
3939 sh->ops.target = -1;
3940 sh->ops.target2 = -1;
3941 sh->check_state = check_state_compute_run;
3942 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3943 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3944 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
3945 set_bit(R5_Wantcompute,
3946 &sh->dev[pd_idx].flags);
3948 target = &sh->ops.target2;
3951 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
3952 set_bit(R5_Wantcompute,
3953 &sh->dev[qd_idx].flags);
3960 case check_state_compute_run:
3963 printk(KERN_ERR "%s: unknown check_state: %d sector: %llu\n",
3964 __func__, sh->check_state,
3965 (unsigned long long) sh->sector);
3970 static void handle_stripe_expansion(struct r5conf *conf, struct stripe_head *sh)
3974 /* We have read all the blocks in this stripe and now we need to
3975 * copy some of them into a target stripe for expand.
3977 struct dma_async_tx_descriptor *tx = NULL;
3978 BUG_ON(sh->batch_head);
3979 clear_bit(STRIPE_EXPAND_SOURCE, &sh->state);
3980 for (i = 0; i < sh->disks; i++)
3981 if (i != sh->pd_idx && i != sh->qd_idx) {
3983 struct stripe_head *sh2;
3984 struct async_submit_ctl submit;
3986 sector_t bn = raid5_compute_blocknr(sh, i, 1);
3987 sector_t s = raid5_compute_sector(conf, bn, 0,
3989 sh2 = raid5_get_active_stripe(conf, s, 0, 1, 1);
3991 /* so far only the early blocks of this stripe
3992 * have been requested. When later blocks
3993 * get requested, we will try again
3996 if (!test_bit(STRIPE_EXPANDING, &sh2->state) ||
3997 test_bit(R5_Expanded, &sh2->dev[dd_idx].flags)) {
3998 /* must have already done this block */
3999 raid5_release_stripe(sh2);
4003 /* place all the copies on one channel */
4004 init_async_submit(&submit, 0, tx, NULL, NULL, NULL);
4005 tx = async_memcpy(sh2->dev[dd_idx].page,
4006 sh->dev[i].page, 0, 0, STRIPE_SIZE,
4009 set_bit(R5_Expanded, &sh2->dev[dd_idx].flags);
4010 set_bit(R5_UPTODATE, &sh2->dev[dd_idx].flags);
4011 for (j = 0; j < conf->raid_disks; j++)
4012 if (j != sh2->pd_idx &&
4014 !test_bit(R5_Expanded, &sh2->dev[j].flags))
4016 if (j == conf->raid_disks) {
4017 set_bit(STRIPE_EXPAND_READY, &sh2->state);
4018 set_bit(STRIPE_HANDLE, &sh2->state);
4020 raid5_release_stripe(sh2);
4023 /* done submitting copies, wait for them to complete */
4024 async_tx_quiesce(&tx);
4028 * handle_stripe - do things to a stripe.
4030 * We lock the stripe by setting STRIPE_ACTIVE and then examine the
4031 * state of various bits to see what needs to be done.
4033 * return some read requests which now have data
4034 * return some write requests which are safely on storage
4035 * schedule a read on some buffers
4036 * schedule a write of some buffers
4037 * return confirmation of parity correctness
4041 static void analyse_stripe(struct stripe_head *sh, struct stripe_head_state *s)
4043 struct r5conf *conf = sh->raid_conf;
4044 int disks = sh->disks;
4047 int do_recovery = 0;
4049 memset(s, 0, sizeof(*s));
4051 s->expanding = test_bit(STRIPE_EXPAND_SOURCE, &sh->state) && !sh->batch_head;
4052 s->expanded = test_bit(STRIPE_EXPAND_READY, &sh->state) && !sh->batch_head;
4053 s->failed_num[0] = -1;
4054 s->failed_num[1] = -1;
4055 s->log_failed = r5l_log_disk_error(conf);
4057 /* Now to look around and see what can be done */
4059 for (i=disks; i--; ) {
4060 struct md_rdev *rdev;
4067 pr_debug("check %d: state 0x%lx read %p write %p written %p\n",
4069 dev->toread, dev->towrite, dev->written);
4070 /* maybe we can reply to a read
4072 * new wantfill requests are only permitted while
4073 * ops_complete_biofill is guaranteed to be inactive
4075 if (test_bit(R5_UPTODATE, &dev->flags) && dev->toread &&
4076 !test_bit(STRIPE_BIOFILL_RUN, &sh->state))
4077 set_bit(R5_Wantfill, &dev->flags);
4079 /* now count some things */
4080 if (test_bit(R5_LOCKED, &dev->flags))
4082 if (test_bit(R5_UPTODATE, &dev->flags))
4084 if (test_bit(R5_Wantcompute, &dev->flags)) {
4086 BUG_ON(s->compute > 2);
4089 if (test_bit(R5_Wantfill, &dev->flags))
4091 else if (dev->toread)
4095 if (!test_bit(R5_OVERWRITE, &dev->flags))
4100 /* Prefer to use the replacement for reads, but only
4101 * if it is recovered enough and has no bad blocks.
4103 rdev = rcu_dereference(conf->disks[i].replacement);
4104 if (rdev && !test_bit(Faulty, &rdev->flags) &&
4105 rdev->recovery_offset >= sh->sector + STRIPE_SECTORS &&
4106 !is_badblock(rdev, sh->sector, STRIPE_SECTORS,
4107 &first_bad, &bad_sectors))
4108 set_bit(R5_ReadRepl, &dev->flags);
4110 if (rdev && !test_bit(Faulty, &rdev->flags))
4111 set_bit(R5_NeedReplace, &dev->flags);
4113 clear_bit(R5_NeedReplace, &dev->flags);
4114 rdev = rcu_dereference(conf->disks[i].rdev);
4115 clear_bit(R5_ReadRepl, &dev->flags);
4117 if (rdev && test_bit(Faulty, &rdev->flags))
4120 is_bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
4121 &first_bad, &bad_sectors);
4122 if (s->blocked_rdev == NULL
4123 && (test_bit(Blocked, &rdev->flags)
4126 set_bit(BlockedBadBlocks,
4128 s->blocked_rdev = rdev;
4129 atomic_inc(&rdev->nr_pending);
4132 clear_bit(R5_Insync, &dev->flags);
4136 /* also not in-sync */
4137 if (!test_bit(WriteErrorSeen, &rdev->flags) &&
4138 test_bit(R5_UPTODATE, &dev->flags)) {
4139 /* treat as in-sync, but with a read error
4140 * which we can now try to correct
4142 set_bit(R5_Insync, &dev->flags);
4143 set_bit(R5_ReadError, &dev->flags);
4145 } else if (test_bit(In_sync, &rdev->flags))
4146 set_bit(R5_Insync, &dev->flags);
4147 else if (sh->sector + STRIPE_SECTORS <= rdev->recovery_offset)
4148 /* in sync if before recovery_offset */
4149 set_bit(R5_Insync, &dev->flags);
4150 else if (test_bit(R5_UPTODATE, &dev->flags) &&
4151 test_bit(R5_Expanded, &dev->flags))
4152 /* If we've reshaped into here, we assume it is Insync.
4153 * We will shortly update recovery_offset to make
4156 set_bit(R5_Insync, &dev->flags);
4158 if (test_bit(R5_WriteError, &dev->flags)) {
4159 /* This flag does not apply to '.replacement'
4160 * only to .rdev, so make sure to check that*/
4161 struct md_rdev *rdev2 = rcu_dereference(
4162 conf->disks[i].rdev);
4164 clear_bit(R5_Insync, &dev->flags);
4165 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4166 s->handle_bad_blocks = 1;
4167 atomic_inc(&rdev2->nr_pending);
4169 clear_bit(R5_WriteError, &dev->flags);
4171 if (test_bit(R5_MadeGood, &dev->flags)) {
4172 /* This flag does not apply to '.replacement'
4173 * only to .rdev, so make sure to check that*/
4174 struct md_rdev *rdev2 = rcu_dereference(
4175 conf->disks[i].rdev);
4176 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4177 s->handle_bad_blocks = 1;
4178 atomic_inc(&rdev2->nr_pending);
4180 clear_bit(R5_MadeGood, &dev->flags);
4182 if (test_bit(R5_MadeGoodRepl, &dev->flags)) {
4183 struct md_rdev *rdev2 = rcu_dereference(
4184 conf->disks[i].replacement);
4185 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4186 s->handle_bad_blocks = 1;
4187 atomic_inc(&rdev2->nr_pending);
4189 clear_bit(R5_MadeGoodRepl, &dev->flags);
4191 if (!test_bit(R5_Insync, &dev->flags)) {
4192 /* The ReadError flag will just be confusing now */
4193 clear_bit(R5_ReadError, &dev->flags);
4194 clear_bit(R5_ReWrite, &dev->flags);
4196 if (test_bit(R5_ReadError, &dev->flags))
4197 clear_bit(R5_Insync, &dev->flags);
4198 if (!test_bit(R5_Insync, &dev->flags)) {
4200 s->failed_num[s->failed] = i;
4202 if (rdev && !test_bit(Faulty, &rdev->flags))
4205 rdev = rcu_dereference(
4206 conf->disks[i].replacement);
4207 if (rdev && !test_bit(Faulty, &rdev->flags))
4212 if (test_bit(STRIPE_SYNCING, &sh->state)) {
4213 /* If there is a failed device being replaced,
4214 * we must be recovering.
4215 * else if we are after recovery_cp, we must be syncing
4216 * else if MD_RECOVERY_REQUESTED is set, we also are syncing.
4217 * else we can only be replacing
4218 * sync and recovery both need to read all devices, and so
4219 * use the same flag.
4222 sh->sector >= conf->mddev->recovery_cp ||
4223 test_bit(MD_RECOVERY_REQUESTED, &(conf->mddev->recovery)))
4231 static int clear_batch_ready(struct stripe_head *sh)
4233 /* Return '1' if this is a member of batch, or
4234 * '0' if it is a lone stripe or a head which can now be
4237 struct stripe_head *tmp;
4238 if (!test_and_clear_bit(STRIPE_BATCH_READY, &sh->state))
4239 return (sh->batch_head && sh->batch_head != sh);
4240 spin_lock(&sh->stripe_lock);
4241 if (!sh->batch_head) {
4242 spin_unlock(&sh->stripe_lock);
4247 * this stripe could be added to a batch list before we check
4248 * BATCH_READY, skips it
4250 if (sh->batch_head != sh) {
4251 spin_unlock(&sh->stripe_lock);
4254 spin_lock(&sh->batch_lock);
4255 list_for_each_entry(tmp, &sh->batch_list, batch_list)
4256 clear_bit(STRIPE_BATCH_READY, &tmp->state);
4257 spin_unlock(&sh->batch_lock);
4258 spin_unlock(&sh->stripe_lock);
4261 * BATCH_READY is cleared, no new stripes can be added.
4262 * batch_list can be accessed without lock
4267 static void break_stripe_batch_list(struct stripe_head *head_sh,
4268 unsigned long handle_flags)
4270 struct stripe_head *sh, *next;
4274 list_for_each_entry_safe(sh, next, &head_sh->batch_list, batch_list) {
4276 list_del_init(&sh->batch_list);
4278 WARN_ON_ONCE(sh->state & ((1 << STRIPE_ACTIVE) |
4279 (1 << STRIPE_SYNCING) |
4280 (1 << STRIPE_REPLACED) |
4281 (1 << STRIPE_DELAYED) |
4282 (1 << STRIPE_BIT_DELAY) |
4283 (1 << STRIPE_FULL_WRITE) |
4284 (1 << STRIPE_BIOFILL_RUN) |
4285 (1 << STRIPE_COMPUTE_RUN) |
4286 (1 << STRIPE_OPS_REQ_PENDING) |
4287 (1 << STRIPE_DISCARD) |
4288 (1 << STRIPE_BATCH_READY) |
4289 (1 << STRIPE_BATCH_ERR) |
4290 (1 << STRIPE_BITMAP_PENDING)));
4291 WARN_ON_ONCE(head_sh->state & ((1 << STRIPE_DISCARD) |
4292 (1 << STRIPE_REPLACED)));
4294 set_mask_bits(&sh->state, ~(STRIPE_EXPAND_SYNC_FLAGS |
4295 (1 << STRIPE_PREREAD_ACTIVE) |
4296 (1 << STRIPE_DEGRADED) |
4297 (1 << STRIPE_ON_UNPLUG_LIST)),
4298 head_sh->state & (1 << STRIPE_INSYNC));
4300 sh->check_state = head_sh->check_state;
4301 sh->reconstruct_state = head_sh->reconstruct_state;
4302 for (i = 0; i < sh->disks; i++) {
4303 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
4305 sh->dev[i].flags = head_sh->dev[i].flags &
4306 (~((1 << R5_WriteError) | (1 << R5_Overlap)));
4308 spin_lock_irq(&sh->stripe_lock);
4309 sh->batch_head = NULL;
4310 spin_unlock_irq(&sh->stripe_lock);
4311 if (handle_flags == 0 ||
4312 sh->state & handle_flags)
4313 set_bit(STRIPE_HANDLE, &sh->state);
4314 raid5_release_stripe(sh);
4316 spin_lock_irq(&head_sh->stripe_lock);
4317 head_sh->batch_head = NULL;
4318 spin_unlock_irq(&head_sh->stripe_lock);
4319 for (i = 0; i < head_sh->disks; i++)
4320 if (test_and_clear_bit(R5_Overlap, &head_sh->dev[i].flags))
4322 if (head_sh->state & handle_flags)
4323 set_bit(STRIPE_HANDLE, &head_sh->state);
4326 wake_up(&head_sh->raid_conf->wait_for_overlap);
4329 static void handle_stripe(struct stripe_head *sh)
4331 struct stripe_head_state s;
4332 struct r5conf *conf = sh->raid_conf;
4335 int disks = sh->disks;
4336 struct r5dev *pdev, *qdev;
4338 clear_bit(STRIPE_HANDLE, &sh->state);
4339 if (test_and_set_bit_lock(STRIPE_ACTIVE, &sh->state)) {
4340 /* already being handled, ensure it gets handled
4341 * again when current action finishes */
4342 set_bit(STRIPE_HANDLE, &sh->state);
4346 if (clear_batch_ready(sh) ) {
4347 clear_bit_unlock(STRIPE_ACTIVE, &sh->state);
4351 if (test_and_clear_bit(STRIPE_BATCH_ERR, &sh->state))
4352 break_stripe_batch_list(sh, 0);
4354 if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state) && !sh->batch_head) {
4355 spin_lock(&sh->stripe_lock);
4356 /* Cannot process 'sync' concurrently with 'discard' */
4357 if (!test_bit(STRIPE_DISCARD, &sh->state) &&
4358 test_and_clear_bit(STRIPE_SYNC_REQUESTED, &sh->state)) {
4359 set_bit(STRIPE_SYNCING, &sh->state);
4360 clear_bit(STRIPE_INSYNC, &sh->state);
4361 clear_bit(STRIPE_REPLACED, &sh->state);
4363 spin_unlock(&sh->stripe_lock);
4365 clear_bit(STRIPE_DELAYED, &sh->state);
4367 pr_debug("handling stripe %llu, state=%#lx cnt=%d, "
4368 "pd_idx=%d, qd_idx=%d\n, check:%d, reconstruct:%d\n",
4369 (unsigned long long)sh->sector, sh->state,
4370 atomic_read(&sh->count), sh->pd_idx, sh->qd_idx,
4371 sh->check_state, sh->reconstruct_state);
4373 analyse_stripe(sh, &s);
4375 if (test_bit(STRIPE_LOG_TRAPPED, &sh->state))
4378 if (s.handle_bad_blocks) {
4379 set_bit(STRIPE_HANDLE, &sh->state);
4383 if (unlikely(s.blocked_rdev)) {
4384 if (s.syncing || s.expanding || s.expanded ||
4385 s.replacing || s.to_write || s.written) {
4386 set_bit(STRIPE_HANDLE, &sh->state);
4389 /* There is nothing for the blocked_rdev to block */
4390 rdev_dec_pending(s.blocked_rdev, conf->mddev);
4391 s.blocked_rdev = NULL;
4394 if (s.to_fill && !test_bit(STRIPE_BIOFILL_RUN, &sh->state)) {
4395 set_bit(STRIPE_OP_BIOFILL, &s.ops_request);
4396 set_bit(STRIPE_BIOFILL_RUN, &sh->state);
4399 pr_debug("locked=%d uptodate=%d to_read=%d"
4400 " to_write=%d failed=%d failed_num=%d,%d\n",
4401 s.locked, s.uptodate, s.to_read, s.to_write, s.failed,
4402 s.failed_num[0], s.failed_num[1]);
4403 /* check if the array has lost more than max_degraded devices and,
4404 * if so, some requests might need to be failed.
4406 if (s.failed > conf->max_degraded || s.log_failed) {
4407 sh->check_state = 0;
4408 sh->reconstruct_state = 0;
4409 break_stripe_batch_list(sh, 0);
4410 if (s.to_read+s.to_write+s.written)
4411 handle_failed_stripe(conf, sh, &s, disks, &s.return_bi);
4412 if (s.syncing + s.replacing)
4413 handle_failed_sync(conf, sh, &s);
4416 /* Now we check to see if any write operations have recently
4420 if (sh->reconstruct_state == reconstruct_state_prexor_drain_result)
4422 if (sh->reconstruct_state == reconstruct_state_drain_result ||
4423 sh->reconstruct_state == reconstruct_state_prexor_drain_result) {
4424 sh->reconstruct_state = reconstruct_state_idle;
4426 /* All the 'written' buffers and the parity block are ready to
4427 * be written back to disk
4429 BUG_ON(!test_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags) &&
4430 !test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags));
4431 BUG_ON(sh->qd_idx >= 0 &&
4432 !test_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags) &&
4433 !test_bit(R5_Discard, &sh->dev[sh->qd_idx].flags));
4434 for (i = disks; i--; ) {
4435 struct r5dev *dev = &sh->dev[i];
4436 if (test_bit(R5_LOCKED, &dev->flags) &&
4437 (i == sh->pd_idx || i == sh->qd_idx ||
4439 pr_debug("Writing block %d\n", i);
4440 set_bit(R5_Wantwrite, &dev->flags);
4445 if (!test_bit(R5_Insync, &dev->flags) ||
4446 ((i == sh->pd_idx || i == sh->qd_idx) &&
4448 set_bit(STRIPE_INSYNC, &sh->state);
4451 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4452 s.dec_preread_active = 1;
4456 * might be able to return some write requests if the parity blocks
4457 * are safe, or on a failed drive
4459 pdev = &sh->dev[sh->pd_idx];
4460 s.p_failed = (s.failed >= 1 && s.failed_num[0] == sh->pd_idx)
4461 || (s.failed >= 2 && s.failed_num[1] == sh->pd_idx);
4462 qdev = &sh->dev[sh->qd_idx];
4463 s.q_failed = (s.failed >= 1 && s.failed_num[0] == sh->qd_idx)
4464 || (s.failed >= 2 && s.failed_num[1] == sh->qd_idx)
4468 (s.p_failed || ((test_bit(R5_Insync, &pdev->flags)
4469 && !test_bit(R5_LOCKED, &pdev->flags)
4470 && (test_bit(R5_UPTODATE, &pdev->flags) ||
4471 test_bit(R5_Discard, &pdev->flags))))) &&
4472 (s.q_failed || ((test_bit(R5_Insync, &qdev->flags)
4473 && !test_bit(R5_LOCKED, &qdev->flags)
4474 && (test_bit(R5_UPTODATE, &qdev->flags) ||
4475 test_bit(R5_Discard, &qdev->flags))))))
4476 handle_stripe_clean_event(conf, sh, disks, &s.return_bi);
4478 /* Now we might consider reading some blocks, either to check/generate
4479 * parity, or to satisfy requests
4480 * or to load a block that is being partially written.
4482 if (s.to_read || s.non_overwrite
4483 || (s.to_write && s.failed)
4484 || (s.syncing && (s.uptodate + s.compute < disks))
4487 handle_stripe_fill(sh, &s, disks);
4489 /* Now to consider new write requests and what else, if anything
4490 * should be read. We do not handle new writes when:
4491 * 1/ A 'write' operation (copy+xor) is already in flight.
4492 * 2/ A 'check' operation is in flight, as it may clobber the parity
4495 if (s.to_write && !sh->reconstruct_state && !sh->check_state)
4496 handle_stripe_dirtying(conf, sh, &s, disks);
4498 /* maybe we need to check and possibly fix the parity for this stripe
4499 * Any reads will already have been scheduled, so we just see if enough
4500 * data is available. The parity check is held off while parity
4501 * dependent operations are in flight.
4503 if (sh->check_state ||
4504 (s.syncing && s.locked == 0 &&
4505 !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
4506 !test_bit(STRIPE_INSYNC, &sh->state))) {
4507 if (conf->level == 6)
4508 handle_parity_checks6(conf, sh, &s, disks);
4510 handle_parity_checks5(conf, sh, &s, disks);
4513 if ((s.replacing || s.syncing) && s.locked == 0
4514 && !test_bit(STRIPE_COMPUTE_RUN, &sh->state)
4515 && !test_bit(STRIPE_REPLACED, &sh->state)) {
4516 /* Write out to replacement devices where possible */
4517 for (i = 0; i < conf->raid_disks; i++)
4518 if (test_bit(R5_NeedReplace, &sh->dev[i].flags)) {
4519 WARN_ON(!test_bit(R5_UPTODATE, &sh->dev[i].flags));
4520 set_bit(R5_WantReplace, &sh->dev[i].flags);
4521 set_bit(R5_LOCKED, &sh->dev[i].flags);
4525 set_bit(STRIPE_INSYNC, &sh->state);
4526 set_bit(STRIPE_REPLACED, &sh->state);
4528 if ((s.syncing || s.replacing) && s.locked == 0 &&
4529 !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
4530 test_bit(STRIPE_INSYNC, &sh->state)) {
4531 md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
4532 clear_bit(STRIPE_SYNCING, &sh->state);
4533 if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
4534 wake_up(&conf->wait_for_overlap);
4537 /* If the failed drives are just a ReadError, then we might need
4538 * to progress the repair/check process
4540 if (s.failed <= conf->max_degraded && !conf->mddev->ro)
4541 for (i = 0; i < s.failed; i++) {
4542 struct r5dev *dev = &sh->dev[s.failed_num[i]];
4543 if (test_bit(R5_ReadError, &dev->flags)
4544 && !test_bit(R5_LOCKED, &dev->flags)
4545 && test_bit(R5_UPTODATE, &dev->flags)
4547 if (!test_bit(R5_ReWrite, &dev->flags)) {
4548 set_bit(R5_Wantwrite, &dev->flags);
4549 set_bit(R5_ReWrite, &dev->flags);
4550 set_bit(R5_LOCKED, &dev->flags);
4553 /* let's read it back */
4554 set_bit(R5_Wantread, &dev->flags);
4555 set_bit(R5_LOCKED, &dev->flags);
4561 /* Finish reconstruct operations initiated by the expansion process */
4562 if (sh->reconstruct_state == reconstruct_state_result) {
4563 struct stripe_head *sh_src
4564 = raid5_get_active_stripe(conf, sh->sector, 1, 1, 1);
4565 if (sh_src && test_bit(STRIPE_EXPAND_SOURCE, &sh_src->state)) {
4566 /* sh cannot be written until sh_src has been read.
4567 * so arrange for sh to be delayed a little
4569 set_bit(STRIPE_DELAYED, &sh->state);
4570 set_bit(STRIPE_HANDLE, &sh->state);
4571 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE,
4573 atomic_inc(&conf->preread_active_stripes);
4574 raid5_release_stripe(sh_src);
4578 raid5_release_stripe(sh_src);
4580 sh->reconstruct_state = reconstruct_state_idle;
4581 clear_bit(STRIPE_EXPANDING, &sh->state);
4582 for (i = conf->raid_disks; i--; ) {
4583 set_bit(R5_Wantwrite, &sh->dev[i].flags);
4584 set_bit(R5_LOCKED, &sh->dev[i].flags);
4589 if (s.expanded && test_bit(STRIPE_EXPANDING, &sh->state) &&
4590 !sh->reconstruct_state) {
4591 /* Need to write out all blocks after computing parity */
4592 sh->disks = conf->raid_disks;
4593 stripe_set_idx(sh->sector, conf, 0, sh);
4594 schedule_reconstruction(sh, &s, 1, 1);
4595 } else if (s.expanded && !sh->reconstruct_state && s.locked == 0) {
4596 clear_bit(STRIPE_EXPAND_READY, &sh->state);
4597 atomic_dec(&conf->reshape_stripes);
4598 wake_up(&conf->wait_for_overlap);
4599 md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
4602 if (s.expanding && s.locked == 0 &&
4603 !test_bit(STRIPE_COMPUTE_RUN, &sh->state))
4604 handle_stripe_expansion(conf, sh);
4607 /* wait for this device to become unblocked */
4608 if (unlikely(s.blocked_rdev)) {
4609 if (conf->mddev->external)
4610 md_wait_for_blocked_rdev(s.blocked_rdev,
4613 /* Internal metadata will immediately
4614 * be written by raid5d, so we don't
4615 * need to wait here.
4617 rdev_dec_pending(s.blocked_rdev,
4621 if (s.handle_bad_blocks)
4622 for (i = disks; i--; ) {
4623 struct md_rdev *rdev;
4624 struct r5dev *dev = &sh->dev[i];
4625 if (test_and_clear_bit(R5_WriteError, &dev->flags)) {
4626 /* We own a safe reference to the rdev */
4627 rdev = conf->disks[i].rdev;
4628 if (!rdev_set_badblocks(rdev, sh->sector,
4630 md_error(conf->mddev, rdev);
4631 rdev_dec_pending(rdev, conf->mddev);
4633 if (test_and_clear_bit(R5_MadeGood, &dev->flags)) {
4634 rdev = conf->disks[i].rdev;
4635 rdev_clear_badblocks(rdev, sh->sector,
4637 rdev_dec_pending(rdev, conf->mddev);
4639 if (test_and_clear_bit(R5_MadeGoodRepl, &dev->flags)) {
4640 rdev = conf->disks[i].replacement;
4642 /* rdev have been moved down */
4643 rdev = conf->disks[i].rdev;
4644 rdev_clear_badblocks(rdev, sh->sector,
4646 rdev_dec_pending(rdev, conf->mddev);
4651 raid_run_ops(sh, s.ops_request);
4655 if (s.dec_preread_active) {
4656 /* We delay this until after ops_run_io so that if make_request
4657 * is waiting on a flush, it won't continue until the writes
4658 * have actually been submitted.
4660 atomic_dec(&conf->preread_active_stripes);
4661 if (atomic_read(&conf->preread_active_stripes) <
4663 md_wakeup_thread(conf->mddev->thread);
4666 if (!bio_list_empty(&s.return_bi)) {
4667 if (test_bit(MD_CHANGE_PENDING, &conf->mddev->flags)) {
4668 spin_lock_irq(&conf->device_lock);
4669 bio_list_merge(&conf->return_bi, &s.return_bi);
4670 spin_unlock_irq(&conf->device_lock);
4671 md_wakeup_thread(conf->mddev->thread);
4673 return_io(&s.return_bi);
4676 clear_bit_unlock(STRIPE_ACTIVE, &sh->state);
4679 static void raid5_activate_delayed(struct r5conf *conf)
4681 if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD) {
4682 while (!list_empty(&conf->delayed_list)) {
4683 struct list_head *l = conf->delayed_list.next;
4684 struct stripe_head *sh;
4685 sh = list_entry(l, struct stripe_head, lru);
4687 clear_bit(STRIPE_DELAYED, &sh->state);
4688 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4689 atomic_inc(&conf->preread_active_stripes);
4690 list_add_tail(&sh->lru, &conf->hold_list);
4691 raid5_wakeup_stripe_thread(sh);
4696 static void activate_bit_delay(struct r5conf *conf,
4697 struct list_head *temp_inactive_list)
4699 /* device_lock is held */
4700 struct list_head head;
4701 list_add(&head, &conf->bitmap_list);
4702 list_del_init(&conf->bitmap_list);
4703 while (!list_empty(&head)) {
4704 struct stripe_head *sh = list_entry(head.next, struct stripe_head, lru);
4706 list_del_init(&sh->lru);
4707 atomic_inc(&sh->count);
4708 hash = sh->hash_lock_index;
4709 __release_stripe(conf, sh, &temp_inactive_list[hash]);
4713 static int raid5_congested(struct mddev *mddev, int bits)
4715 struct r5conf *conf = mddev->private;
4717 /* No difference between reads and writes. Just check
4718 * how busy the stripe_cache is
4721 if (test_bit(R5_INACTIVE_BLOCKED, &conf->cache_state))
4725 if (atomic_read(&conf->empty_inactive_list_nr))
4731 static int in_chunk_boundary(struct mddev *mddev, struct bio *bio)
4733 struct r5conf *conf = mddev->private;
4734 sector_t sector = bio->bi_iter.bi_sector + get_start_sect(bio->bi_bdev);
4735 unsigned int chunk_sectors;
4736 unsigned int bio_sectors = bio_sectors(bio);
4738 chunk_sectors = min(conf->chunk_sectors, conf->prev_chunk_sectors);
4739 return chunk_sectors >=
4740 ((sector & (chunk_sectors - 1)) + bio_sectors);
4744 * add bio to the retry LIFO ( in O(1) ... we are in interrupt )
4745 * later sampled by raid5d.
4747 static void add_bio_to_retry(struct bio *bi,struct r5conf *conf)
4749 unsigned long flags;
4751 spin_lock_irqsave(&conf->device_lock, flags);
4753 bi->bi_next = conf->retry_read_aligned_list;
4754 conf->retry_read_aligned_list = bi;
4756 spin_unlock_irqrestore(&conf->device_lock, flags);
4757 md_wakeup_thread(conf->mddev->thread);
4760 static struct bio *remove_bio_from_retry(struct r5conf *conf)
4764 bi = conf->retry_read_aligned;
4766 conf->retry_read_aligned = NULL;
4769 bi = conf->retry_read_aligned_list;
4771 conf->retry_read_aligned_list = bi->bi_next;
4774 * this sets the active strip count to 1 and the processed
4775 * strip count to zero (upper 8 bits)
4777 raid5_set_bi_stripes(bi, 1); /* biased count of active stripes */
4784 * The "raid5_align_endio" should check if the read succeeded and if it
4785 * did, call bio_endio on the original bio (having bio_put the new bio
4787 * If the read failed..
4789 static void raid5_align_endio(struct bio *bi)
4791 struct bio* raid_bi = bi->bi_private;
4792 struct mddev *mddev;
4793 struct r5conf *conf;
4794 struct md_rdev *rdev;
4795 int error = bi->bi_error;
4799 rdev = (void*)raid_bi->bi_next;
4800 raid_bi->bi_next = NULL;
4801 mddev = rdev->mddev;
4802 conf = mddev->private;
4804 rdev_dec_pending(rdev, conf->mddev);
4807 trace_block_bio_complete(bdev_get_queue(raid_bi->bi_bdev),
4810 if (atomic_dec_and_test(&conf->active_aligned_reads))
4811 wake_up(&conf->wait_for_quiescent);
4815 pr_debug("raid5_align_endio : io error...handing IO for a retry\n");
4817 add_bio_to_retry(raid_bi, conf);
4820 static int raid5_read_one_chunk(struct mddev *mddev, struct bio *raid_bio)
4822 struct r5conf *conf = mddev->private;
4824 struct bio* align_bi;
4825 struct md_rdev *rdev;
4826 sector_t end_sector;
4828 if (!in_chunk_boundary(mddev, raid_bio)) {
4829 pr_debug("%s: non aligned\n", __func__);
4833 * use bio_clone_mddev to make a copy of the bio
4835 align_bi = bio_clone_mddev(raid_bio, GFP_NOIO, mddev);
4839 * set bi_end_io to a new function, and set bi_private to the
4842 align_bi->bi_end_io = raid5_align_endio;
4843 align_bi->bi_private = raid_bio;
4847 align_bi->bi_iter.bi_sector =
4848 raid5_compute_sector(conf, raid_bio->bi_iter.bi_sector,
4851 end_sector = bio_end_sector(align_bi);
4853 rdev = rcu_dereference(conf->disks[dd_idx].replacement);
4854 if (!rdev || test_bit(Faulty, &rdev->flags) ||
4855 rdev->recovery_offset < end_sector) {
4856 rdev = rcu_dereference(conf->disks[dd_idx].rdev);
4858 (test_bit(Faulty, &rdev->flags) ||
4859 !(test_bit(In_sync, &rdev->flags) ||
4860 rdev->recovery_offset >= end_sector)))
4867 atomic_inc(&rdev->nr_pending);
4869 raid_bio->bi_next = (void*)rdev;
4870 align_bi->bi_bdev = rdev->bdev;
4871 bio_clear_flag(align_bi, BIO_SEG_VALID);
4873 if (is_badblock(rdev, align_bi->bi_iter.bi_sector,
4874 bio_sectors(align_bi),
4875 &first_bad, &bad_sectors)) {
4877 rdev_dec_pending(rdev, mddev);
4881 /* No reshape active, so we can trust rdev->data_offset */
4882 align_bi->bi_iter.bi_sector += rdev->data_offset;
4884 spin_lock_irq(&conf->device_lock);
4885 wait_event_lock_irq(conf->wait_for_quiescent,
4888 atomic_inc(&conf->active_aligned_reads);
4889 spin_unlock_irq(&conf->device_lock);
4892 trace_block_bio_remap(bdev_get_queue(align_bi->bi_bdev),
4893 align_bi, disk_devt(mddev->gendisk),
4894 raid_bio->bi_iter.bi_sector);
4895 generic_make_request(align_bi);
4904 static struct bio *chunk_aligned_read(struct mddev *mddev, struct bio *raid_bio)
4909 sector_t sector = raid_bio->bi_iter.bi_sector;
4910 unsigned chunk_sects = mddev->chunk_sectors;
4911 unsigned sectors = chunk_sects - (sector & (chunk_sects-1));
4913 if (sectors < bio_sectors(raid_bio)) {
4914 split = bio_split(raid_bio, sectors, GFP_NOIO, fs_bio_set);
4915 bio_chain(split, raid_bio);
4919 if (!raid5_read_one_chunk(mddev, split)) {
4920 if (split != raid_bio)
4921 generic_make_request(raid_bio);
4924 } while (split != raid_bio);
4929 /* __get_priority_stripe - get the next stripe to process
4931 * Full stripe writes are allowed to pass preread active stripes up until
4932 * the bypass_threshold is exceeded. In general the bypass_count
4933 * increments when the handle_list is handled before the hold_list; however, it
4934 * will not be incremented when STRIPE_IO_STARTED is sampled set signifying a
4935 * stripe with in flight i/o. The bypass_count will be reset when the
4936 * head of the hold_list has changed, i.e. the head was promoted to the
4939 static struct stripe_head *__get_priority_stripe(struct r5conf *conf, int group)
4941 struct stripe_head *sh = NULL, *tmp;
4942 struct list_head *handle_list = NULL;
4943 struct r5worker_group *wg = NULL;
4945 if (conf->worker_cnt_per_group == 0) {
4946 handle_list = &conf->handle_list;
4947 } else if (group != ANY_GROUP) {
4948 handle_list = &conf->worker_groups[group].handle_list;
4949 wg = &conf->worker_groups[group];
4952 for (i = 0; i < conf->group_cnt; i++) {
4953 handle_list = &conf->worker_groups[i].handle_list;
4954 wg = &conf->worker_groups[i];
4955 if (!list_empty(handle_list))
4960 pr_debug("%s: handle: %s hold: %s full_writes: %d bypass_count: %d\n",
4962 list_empty(handle_list) ? "empty" : "busy",
4963 list_empty(&conf->hold_list) ? "empty" : "busy",
4964 atomic_read(&conf->pending_full_writes), conf->bypass_count);
4966 if (!list_empty(handle_list)) {
4967 sh = list_entry(handle_list->next, typeof(*sh), lru);
4969 if (list_empty(&conf->hold_list))
4970 conf->bypass_count = 0;
4971 else if (!test_bit(STRIPE_IO_STARTED, &sh->state)) {
4972 if (conf->hold_list.next == conf->last_hold)
4973 conf->bypass_count++;
4975 conf->last_hold = conf->hold_list.next;
4976 conf->bypass_count -= conf->bypass_threshold;
4977 if (conf->bypass_count < 0)
4978 conf->bypass_count = 0;
4981 } else if (!list_empty(&conf->hold_list) &&
4982 ((conf->bypass_threshold &&
4983 conf->bypass_count > conf->bypass_threshold) ||
4984 atomic_read(&conf->pending_full_writes) == 0)) {
4986 list_for_each_entry(tmp, &conf->hold_list, lru) {
4987 if (conf->worker_cnt_per_group == 0 ||
4988 group == ANY_GROUP ||
4989 !cpu_online(tmp->cpu) ||
4990 cpu_to_group(tmp->cpu) == group) {
4997 conf->bypass_count -= conf->bypass_threshold;
4998 if (conf->bypass_count < 0)
4999 conf->bypass_count = 0;
5011 list_del_init(&sh->lru);
5012 BUG_ON(atomic_inc_return(&sh->count) != 1);
5016 struct raid5_plug_cb {
5017 struct blk_plug_cb cb;
5018 struct list_head list;
5019 struct list_head temp_inactive_list[NR_STRIPE_HASH_LOCKS];
5022 static void raid5_unplug(struct blk_plug_cb *blk_cb, bool from_schedule)
5024 struct raid5_plug_cb *cb = container_of(
5025 blk_cb, struct raid5_plug_cb, cb);
5026 struct stripe_head *sh;
5027 struct mddev *mddev = cb->cb.data;
5028 struct r5conf *conf = mddev->private;
5032 if (cb->list.next && !list_empty(&cb->list)) {
5033 spin_lock_irq(&conf->device_lock);
5034 while (!list_empty(&cb->list)) {
5035 sh = list_first_entry(&cb->list, struct stripe_head, lru);
5036 list_del_init(&sh->lru);
5038 * avoid race release_stripe_plug() sees
5039 * STRIPE_ON_UNPLUG_LIST clear but the stripe
5040 * is still in our list
5042 smp_mb__before_atomic();
5043 clear_bit(STRIPE_ON_UNPLUG_LIST, &sh->state);
5045 * STRIPE_ON_RELEASE_LIST could be set here. In that
5046 * case, the count is always > 1 here
5048 hash = sh->hash_lock_index;
5049 __release_stripe(conf, sh, &cb->temp_inactive_list[hash]);
5052 spin_unlock_irq(&conf->device_lock);
5054 release_inactive_stripe_list(conf, cb->temp_inactive_list,
5055 NR_STRIPE_HASH_LOCKS);
5057 trace_block_unplug(mddev->queue, cnt, !from_schedule);
5061 static void release_stripe_plug(struct mddev *mddev,
5062 struct stripe_head *sh)
5064 struct blk_plug_cb *blk_cb = blk_check_plugged(
5065 raid5_unplug, mddev,
5066 sizeof(struct raid5_plug_cb));
5067 struct raid5_plug_cb *cb;
5070 raid5_release_stripe(sh);
5074 cb = container_of(blk_cb, struct raid5_plug_cb, cb);
5076 if (cb->list.next == NULL) {
5078 INIT_LIST_HEAD(&cb->list);
5079 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
5080 INIT_LIST_HEAD(cb->temp_inactive_list + i);
5083 if (!test_and_set_bit(STRIPE_ON_UNPLUG_LIST, &sh->state))
5084 list_add_tail(&sh->lru, &cb->list);
5086 raid5_release_stripe(sh);
5089 static void make_discard_request(struct mddev *mddev, struct bio *bi)
5091 struct r5conf *conf = mddev->private;
5092 sector_t logical_sector, last_sector;
5093 struct stripe_head *sh;
5097 if (mddev->reshape_position != MaxSector)
5098 /* Skip discard while reshape is happening */
5101 logical_sector = bi->bi_iter.bi_sector & ~((sector_t)STRIPE_SECTORS-1);
5102 last_sector = bi->bi_iter.bi_sector + (bi->bi_iter.bi_size>>9);
5105 bi->bi_phys_segments = 1; /* over-loaded to count active stripes */
5107 stripe_sectors = conf->chunk_sectors *
5108 (conf->raid_disks - conf->max_degraded);
5109 logical_sector = DIV_ROUND_UP_SECTOR_T(logical_sector,
5111 sector_div(last_sector, stripe_sectors);
5113 logical_sector *= conf->chunk_sectors;
5114 last_sector *= conf->chunk_sectors;
5116 for (; logical_sector < last_sector;
5117 logical_sector += STRIPE_SECTORS) {
5121 sh = raid5_get_active_stripe(conf, logical_sector, 0, 0, 0);
5122 prepare_to_wait(&conf->wait_for_overlap, &w,
5123 TASK_UNINTERRUPTIBLE);
5124 set_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5125 if (test_bit(STRIPE_SYNCING, &sh->state)) {
5126 raid5_release_stripe(sh);
5130 clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5131 spin_lock_irq(&sh->stripe_lock);
5132 for (d = 0; d < conf->raid_disks; d++) {
5133 if (d == sh->pd_idx || d == sh->qd_idx)
5135 if (sh->dev[d].towrite || sh->dev[d].toread) {
5136 set_bit(R5_Overlap, &sh->dev[d].flags);
5137 spin_unlock_irq(&sh->stripe_lock);
5138 raid5_release_stripe(sh);
5143 set_bit(STRIPE_DISCARD, &sh->state);
5144 finish_wait(&conf->wait_for_overlap, &w);
5145 sh->overwrite_disks = 0;
5146 for (d = 0; d < conf->raid_disks; d++) {
5147 if (d == sh->pd_idx || d == sh->qd_idx)
5149 sh->dev[d].towrite = bi;
5150 set_bit(R5_OVERWRITE, &sh->dev[d].flags);
5151 raid5_inc_bi_active_stripes(bi);
5152 sh->overwrite_disks++;
5154 spin_unlock_irq(&sh->stripe_lock);
5155 if (conf->mddev->bitmap) {
5157 d < conf->raid_disks - conf->max_degraded;
5159 bitmap_startwrite(mddev->bitmap,
5163 sh->bm_seq = conf->seq_flush + 1;
5164 set_bit(STRIPE_BIT_DELAY, &sh->state);
5167 set_bit(STRIPE_HANDLE, &sh->state);
5168 clear_bit(STRIPE_DELAYED, &sh->state);
5169 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5170 atomic_inc(&conf->preread_active_stripes);
5171 release_stripe_plug(mddev, sh);
5174 remaining = raid5_dec_bi_active_stripes(bi);
5175 if (remaining == 0) {
5176 md_write_end(mddev);
5181 static void make_request(struct mddev *mddev, struct bio * bi)
5183 struct r5conf *conf = mddev->private;
5185 sector_t new_sector;
5186 sector_t logical_sector, last_sector;
5187 struct stripe_head *sh;
5188 const int rw = bio_data_dir(bi);
5193 if (unlikely(bi->bi_rw & REQ_FLUSH)) {
5194 int ret = r5l_handle_flush_request(conf->log, bi);
5198 if (ret == -ENODEV) {
5199 md_flush_request(mddev, bi);
5202 /* ret == -EAGAIN, fallback */
5205 md_write_start(mddev, bi);
5208 * If array is degraded, better not do chunk aligned read because
5209 * later we might have to read it again in order to reconstruct
5210 * data on failed drives.
5212 if (rw == READ && mddev->degraded == 0 &&
5213 mddev->reshape_position == MaxSector) {
5214 bi = chunk_aligned_read(mddev, bi);
5219 if (unlikely(bi->bi_rw & REQ_DISCARD)) {
5220 make_discard_request(mddev, bi);
5224 logical_sector = bi->bi_iter.bi_sector & ~((sector_t)STRIPE_SECTORS-1);
5225 last_sector = bio_end_sector(bi);
5227 bi->bi_phys_segments = 1; /* over-loaded to count active stripes */
5229 prepare_to_wait(&conf->wait_for_overlap, &w, TASK_UNINTERRUPTIBLE);
5230 for (;logical_sector < last_sector; logical_sector += STRIPE_SECTORS) {
5236 seq = read_seqcount_begin(&conf->gen_lock);
5239 prepare_to_wait(&conf->wait_for_overlap, &w,
5240 TASK_UNINTERRUPTIBLE);
5241 if (unlikely(conf->reshape_progress != MaxSector)) {
5242 /* spinlock is needed as reshape_progress may be
5243 * 64bit on a 32bit platform, and so it might be
5244 * possible to see a half-updated value
5245 * Of course reshape_progress could change after
5246 * the lock is dropped, so once we get a reference
5247 * to the stripe that we think it is, we will have
5250 spin_lock_irq(&conf->device_lock);
5251 if (mddev->reshape_backwards
5252 ? logical_sector < conf->reshape_progress
5253 : logical_sector >= conf->reshape_progress) {
5256 if (mddev->reshape_backwards
5257 ? logical_sector < conf->reshape_safe
5258 : logical_sector >= conf->reshape_safe) {
5259 spin_unlock_irq(&conf->device_lock);
5265 spin_unlock_irq(&conf->device_lock);
5268 new_sector = raid5_compute_sector(conf, logical_sector,
5271 pr_debug("raid456: make_request, sector %llu logical %llu\n",
5272 (unsigned long long)new_sector,
5273 (unsigned long long)logical_sector);
5275 sh = raid5_get_active_stripe(conf, new_sector, previous,
5276 (bi->bi_rw&RWA_MASK), 0);
5278 if (unlikely(previous)) {
5279 /* expansion might have moved on while waiting for a
5280 * stripe, so we must do the range check again.
5281 * Expansion could still move past after this
5282 * test, but as we are holding a reference to
5283 * 'sh', we know that if that happens,
5284 * STRIPE_EXPANDING will get set and the expansion
5285 * won't proceed until we finish with the stripe.
5288 spin_lock_irq(&conf->device_lock);
5289 if (mddev->reshape_backwards
5290 ? logical_sector >= conf->reshape_progress
5291 : logical_sector < conf->reshape_progress)
5292 /* mismatch, need to try again */
5294 spin_unlock_irq(&conf->device_lock);
5296 raid5_release_stripe(sh);
5302 if (read_seqcount_retry(&conf->gen_lock, seq)) {
5303 /* Might have got the wrong stripe_head
5306 raid5_release_stripe(sh);
5311 logical_sector >= mddev->suspend_lo &&
5312 logical_sector < mddev->suspend_hi) {
5313 raid5_release_stripe(sh);
5314 /* As the suspend_* range is controlled by
5315 * userspace, we want an interruptible
5318 prepare_to_wait(&conf->wait_for_overlap,
5319 &w, TASK_INTERRUPTIBLE);
5320 if (logical_sector >= mddev->suspend_lo &&
5321 logical_sector < mddev->suspend_hi) {
5324 sigprocmask(SIG_BLOCK, &full, &old);
5326 sigprocmask(SIG_SETMASK, &old, NULL);
5332 if (test_bit(STRIPE_EXPANDING, &sh->state) ||
5333 !add_stripe_bio(sh, bi, dd_idx, rw, previous)) {
5334 /* Stripe is busy expanding or
5335 * add failed due to overlap. Flush everything
5338 md_wakeup_thread(mddev->thread);
5339 raid5_release_stripe(sh);
5344 set_bit(STRIPE_HANDLE, &sh->state);
5345 clear_bit(STRIPE_DELAYED, &sh->state);
5346 if ((!sh->batch_head || sh == sh->batch_head) &&
5347 (bi->bi_rw & REQ_SYNC) &&
5348 !test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5349 atomic_inc(&conf->preread_active_stripes);
5350 release_stripe_plug(mddev, sh);
5352 /* cannot get stripe for read-ahead, just give-up */
5353 bi->bi_error = -EIO;
5357 finish_wait(&conf->wait_for_overlap, &w);
5359 remaining = raid5_dec_bi_active_stripes(bi);
5360 if (remaining == 0) {
5363 md_write_end(mddev);
5365 trace_block_bio_complete(bdev_get_queue(bi->bi_bdev),
5371 static sector_t raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks);
5373 static sector_t reshape_request(struct mddev *mddev, sector_t sector_nr, int *skipped)
5375 /* reshaping is quite different to recovery/resync so it is
5376 * handled quite separately ... here.
5378 * On each call to sync_request, we gather one chunk worth of
5379 * destination stripes and flag them as expanding.
5380 * Then we find all the source stripes and request reads.
5381 * As the reads complete, handle_stripe will copy the data
5382 * into the destination stripe and release that stripe.
5384 struct r5conf *conf = mddev->private;
5385 struct stripe_head *sh;
5386 sector_t first_sector, last_sector;
5387 int raid_disks = conf->previous_raid_disks;
5388 int data_disks = raid_disks - conf->max_degraded;
5389 int new_data_disks = conf->raid_disks - conf->max_degraded;
5392 sector_t writepos, readpos, safepos;
5393 sector_t stripe_addr;
5394 int reshape_sectors;
5395 struct list_head stripes;
5398 if (sector_nr == 0) {
5399 /* If restarting in the middle, skip the initial sectors */
5400 if (mddev->reshape_backwards &&
5401 conf->reshape_progress < raid5_size(mddev, 0, 0)) {
5402 sector_nr = raid5_size(mddev, 0, 0)
5403 - conf->reshape_progress;
5404 } else if (mddev->reshape_backwards &&
5405 conf->reshape_progress == MaxSector) {
5406 /* shouldn't happen, but just in case, finish up.*/
5407 sector_nr = MaxSector;
5408 } else if (!mddev->reshape_backwards &&
5409 conf->reshape_progress > 0)
5410 sector_nr = conf->reshape_progress;
5411 sector_div(sector_nr, new_data_disks);
5413 mddev->curr_resync_completed = sector_nr;
5414 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
5421 /* We need to process a full chunk at a time.
5422 * If old and new chunk sizes differ, we need to process the
5426 reshape_sectors = max(conf->chunk_sectors, conf->prev_chunk_sectors);
5428 /* We update the metadata at least every 10 seconds, or when
5429 * the data about to be copied would over-write the source of
5430 * the data at the front of the range. i.e. one new_stripe
5431 * along from reshape_progress new_maps to after where
5432 * reshape_safe old_maps to
5434 writepos = conf->reshape_progress;
5435 sector_div(writepos, new_data_disks);
5436 readpos = conf->reshape_progress;
5437 sector_div(readpos, data_disks);
5438 safepos = conf->reshape_safe;
5439 sector_div(safepos, data_disks);
5440 if (mddev->reshape_backwards) {
5441 BUG_ON(writepos < reshape_sectors);
5442 writepos -= reshape_sectors;
5443 readpos += reshape_sectors;
5444 safepos += reshape_sectors;
5446 writepos += reshape_sectors;
5447 /* readpos and safepos are worst-case calculations.
5448 * A negative number is overly pessimistic, and causes
5449 * obvious problems for unsigned storage. So clip to 0.
5451 readpos -= min_t(sector_t, reshape_sectors, readpos);
5452 safepos -= min_t(sector_t, reshape_sectors, safepos);
5455 /* Having calculated the 'writepos' possibly use it
5456 * to set 'stripe_addr' which is where we will write to.
5458 if (mddev->reshape_backwards) {
5459 BUG_ON(conf->reshape_progress == 0);
5460 stripe_addr = writepos;
5461 BUG_ON((mddev->dev_sectors &
5462 ~((sector_t)reshape_sectors - 1))
5463 - reshape_sectors - stripe_addr
5466 BUG_ON(writepos != sector_nr + reshape_sectors);
5467 stripe_addr = sector_nr;
5470 /* 'writepos' is the most advanced device address we might write.
5471 * 'readpos' is the least advanced device address we might read.
5472 * 'safepos' is the least address recorded in the metadata as having
5474 * If there is a min_offset_diff, these are adjusted either by
5475 * increasing the safepos/readpos if diff is negative, or
5476 * increasing writepos if diff is positive.
5477 * If 'readpos' is then behind 'writepos', there is no way that we can
5478 * ensure safety in the face of a crash - that must be done by userspace
5479 * making a backup of the data. So in that case there is no particular
5480 * rush to update metadata.
5481 * Otherwise if 'safepos' is behind 'writepos', then we really need to
5482 * update the metadata to advance 'safepos' to match 'readpos' so that
5483 * we can be safe in the event of a crash.
5484 * So we insist on updating metadata if safepos is behind writepos and
5485 * readpos is beyond writepos.
5486 * In any case, update the metadata every 10 seconds.
5487 * Maybe that number should be configurable, but I'm not sure it is
5488 * worth it.... maybe it could be a multiple of safemode_delay???
5490 if (conf->min_offset_diff < 0) {
5491 safepos += -conf->min_offset_diff;
5492 readpos += -conf->min_offset_diff;
5494 writepos += conf->min_offset_diff;
5496 if ((mddev->reshape_backwards
5497 ? (safepos > writepos && readpos < writepos)
5498 : (safepos < writepos && readpos > writepos)) ||
5499 time_after(jiffies, conf->reshape_checkpoint + 10*HZ)) {
5500 /* Cannot proceed until we've updated the superblock... */
5501 wait_event(conf->wait_for_overlap,
5502 atomic_read(&conf->reshape_stripes)==0
5503 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5504 if (atomic_read(&conf->reshape_stripes) != 0)
5506 mddev->reshape_position = conf->reshape_progress;
5507 mddev->curr_resync_completed = sector_nr;
5508 conf->reshape_checkpoint = jiffies;
5509 set_bit(MD_CHANGE_DEVS, &mddev->flags);
5510 md_wakeup_thread(mddev->thread);
5511 wait_event(mddev->sb_wait, mddev->flags == 0 ||
5512 test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5513 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
5515 spin_lock_irq(&conf->device_lock);
5516 conf->reshape_safe = mddev->reshape_position;
5517 spin_unlock_irq(&conf->device_lock);
5518 wake_up(&conf->wait_for_overlap);
5519 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
5522 INIT_LIST_HEAD(&stripes);
5523 for (i = 0; i < reshape_sectors; i += STRIPE_SECTORS) {
5525 int skipped_disk = 0;
5526 sh = raid5_get_active_stripe(conf, stripe_addr+i, 0, 0, 1);
5527 set_bit(STRIPE_EXPANDING, &sh->state);
5528 atomic_inc(&conf->reshape_stripes);
5529 /* If any of this stripe is beyond the end of the old
5530 * array, then we need to zero those blocks
5532 for (j=sh->disks; j--;) {
5534 if (j == sh->pd_idx)
5536 if (conf->level == 6 &&
5539 s = raid5_compute_blocknr(sh, j, 0);
5540 if (s < raid5_size(mddev, 0, 0)) {
5544 memset(page_address(sh->dev[j].page), 0, STRIPE_SIZE);
5545 set_bit(R5_Expanded, &sh->dev[j].flags);
5546 set_bit(R5_UPTODATE, &sh->dev[j].flags);
5548 if (!skipped_disk) {
5549 set_bit(STRIPE_EXPAND_READY, &sh->state);
5550 set_bit(STRIPE_HANDLE, &sh->state);
5552 list_add(&sh->lru, &stripes);
5554 spin_lock_irq(&conf->device_lock);
5555 if (mddev->reshape_backwards)
5556 conf->reshape_progress -= reshape_sectors * new_data_disks;
5558 conf->reshape_progress += reshape_sectors * new_data_disks;
5559 spin_unlock_irq(&conf->device_lock);
5560 /* Ok, those stripe are ready. We can start scheduling
5561 * reads on the source stripes.
5562 * The source stripes are determined by mapping the first and last
5563 * block on the destination stripes.
5566 raid5_compute_sector(conf, stripe_addr*(new_data_disks),
5569 raid5_compute_sector(conf, ((stripe_addr+reshape_sectors)
5570 * new_data_disks - 1),
5572 if (last_sector >= mddev->dev_sectors)
5573 last_sector = mddev->dev_sectors - 1;
5574 while (first_sector <= last_sector) {
5575 sh = raid5_get_active_stripe(conf, first_sector, 1, 0, 1);
5576 set_bit(STRIPE_EXPAND_SOURCE, &sh->state);
5577 set_bit(STRIPE_HANDLE, &sh->state);
5578 raid5_release_stripe(sh);
5579 first_sector += STRIPE_SECTORS;
5581 /* Now that the sources are clearly marked, we can release
5582 * the destination stripes
5584 while (!list_empty(&stripes)) {
5585 sh = list_entry(stripes.next, struct stripe_head, lru);
5586 list_del_init(&sh->lru);
5587 raid5_release_stripe(sh);
5589 /* If this takes us to the resync_max point where we have to pause,
5590 * then we need to write out the superblock.
5592 sector_nr += reshape_sectors;
5593 retn = reshape_sectors;
5595 if (mddev->curr_resync_completed > mddev->resync_max ||
5596 (sector_nr - mddev->curr_resync_completed) * 2
5597 >= mddev->resync_max - mddev->curr_resync_completed) {
5598 /* Cannot proceed until we've updated the superblock... */
5599 wait_event(conf->wait_for_overlap,
5600 atomic_read(&conf->reshape_stripes) == 0
5601 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5602 if (atomic_read(&conf->reshape_stripes) != 0)
5604 mddev->reshape_position = conf->reshape_progress;
5605 mddev->curr_resync_completed = sector_nr;
5606 conf->reshape_checkpoint = jiffies;
5607 set_bit(MD_CHANGE_DEVS, &mddev->flags);
5608 md_wakeup_thread(mddev->thread);
5609 wait_event(mddev->sb_wait,
5610 !test_bit(MD_CHANGE_DEVS, &mddev->flags)
5611 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5612 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
5614 spin_lock_irq(&conf->device_lock);
5615 conf->reshape_safe = mddev->reshape_position;
5616 spin_unlock_irq(&conf->device_lock);
5617 wake_up(&conf->wait_for_overlap);
5618 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
5624 static inline sector_t sync_request(struct mddev *mddev, sector_t sector_nr, int *skipped)
5626 struct r5conf *conf = mddev->private;
5627 struct stripe_head *sh;
5628 sector_t max_sector = mddev->dev_sectors;
5629 sector_t sync_blocks;
5630 int still_degraded = 0;
5633 if (sector_nr >= max_sector) {
5634 /* just being told to finish up .. nothing much to do */
5636 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
5641 if (mddev->curr_resync < max_sector) /* aborted */
5642 bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
5644 else /* completed sync */
5646 bitmap_close_sync(mddev->bitmap);
5651 /* Allow raid5_quiesce to complete */
5652 wait_event(conf->wait_for_overlap, conf->quiesce != 2);
5654 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
5655 return reshape_request(mddev, sector_nr, skipped);
5657 /* No need to check resync_max as we never do more than one
5658 * stripe, and as resync_max will always be on a chunk boundary,
5659 * if the check in md_do_sync didn't fire, there is no chance
5660 * of overstepping resync_max here
5663 /* if there is too many failed drives and we are trying
5664 * to resync, then assert that we are finished, because there is
5665 * nothing we can do.
5667 if (mddev->degraded >= conf->max_degraded &&
5668 test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
5669 sector_t rv = mddev->dev_sectors - sector_nr;
5673 if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
5675 !bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, 1) &&
5676 sync_blocks >= STRIPE_SECTORS) {
5677 /* we can skip this block, and probably more */
5678 sync_blocks /= STRIPE_SECTORS;
5680 return sync_blocks * STRIPE_SECTORS; /* keep things rounded to whole stripes */
5683 bitmap_cond_end_sync(mddev->bitmap, sector_nr, false);
5685 sh = raid5_get_active_stripe(conf, sector_nr, 0, 1, 0);
5687 sh = raid5_get_active_stripe(conf, sector_nr, 0, 0, 0);
5688 /* make sure we don't swamp the stripe cache if someone else
5689 * is trying to get access
5691 schedule_timeout_uninterruptible(1);
5693 /* Need to check if array will still be degraded after recovery/resync
5694 * Note in case of > 1 drive failures it's possible we're rebuilding
5695 * one drive while leaving another faulty drive in array.
5698 for (i = 0; i < conf->raid_disks; i++) {
5699 struct md_rdev *rdev = ACCESS_ONCE(conf->disks[i].rdev);
5701 if (rdev == NULL || test_bit(Faulty, &rdev->flags))
5706 bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, still_degraded);
5708 set_bit(STRIPE_SYNC_REQUESTED, &sh->state);
5709 set_bit(STRIPE_HANDLE, &sh->state);
5711 raid5_release_stripe(sh);
5713 return STRIPE_SECTORS;
5716 static int retry_aligned_read(struct r5conf *conf, struct bio *raid_bio)
5718 /* We may not be able to submit a whole bio at once as there
5719 * may not be enough stripe_heads available.
5720 * We cannot pre-allocate enough stripe_heads as we may need
5721 * more than exist in the cache (if we allow ever large chunks).
5722 * So we do one stripe head at a time and record in
5723 * ->bi_hw_segments how many have been done.
5725 * We *know* that this entire raid_bio is in one chunk, so
5726 * it will be only one 'dd_idx' and only need one call to raid5_compute_sector.
5728 struct stripe_head *sh;
5730 sector_t sector, logical_sector, last_sector;
5735 logical_sector = raid_bio->bi_iter.bi_sector &
5736 ~((sector_t)STRIPE_SECTORS-1);
5737 sector = raid5_compute_sector(conf, logical_sector,
5739 last_sector = bio_end_sector(raid_bio);
5741 for (; logical_sector < last_sector;
5742 logical_sector += STRIPE_SECTORS,
5743 sector += STRIPE_SECTORS,
5746 if (scnt < raid5_bi_processed_stripes(raid_bio))
5747 /* already done this stripe */
5750 sh = raid5_get_active_stripe(conf, sector, 0, 1, 1);
5753 /* failed to get a stripe - must wait */
5754 raid5_set_bi_processed_stripes(raid_bio, scnt);
5755 conf->retry_read_aligned = raid_bio;
5759 if (!add_stripe_bio(sh, raid_bio, dd_idx, 0, 0)) {
5760 raid5_release_stripe(sh);
5761 raid5_set_bi_processed_stripes(raid_bio, scnt);
5762 conf->retry_read_aligned = raid_bio;
5766 set_bit(R5_ReadNoMerge, &sh->dev[dd_idx].flags);
5768 raid5_release_stripe(sh);
5771 remaining = raid5_dec_bi_active_stripes(raid_bio);
5772 if (remaining == 0) {
5773 trace_block_bio_complete(bdev_get_queue(raid_bio->bi_bdev),
5775 bio_endio(raid_bio);
5777 if (atomic_dec_and_test(&conf->active_aligned_reads))
5778 wake_up(&conf->wait_for_quiescent);
5782 static int handle_active_stripes(struct r5conf *conf, int group,
5783 struct r5worker *worker,
5784 struct list_head *temp_inactive_list)
5786 struct stripe_head *batch[MAX_STRIPE_BATCH], *sh;
5787 int i, batch_size = 0, hash;
5788 bool release_inactive = false;
5790 while (batch_size < MAX_STRIPE_BATCH &&
5791 (sh = __get_priority_stripe(conf, group)) != NULL)
5792 batch[batch_size++] = sh;
5794 if (batch_size == 0) {
5795 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
5796 if (!list_empty(temp_inactive_list + i))
5798 if (i == NR_STRIPE_HASH_LOCKS) {
5799 spin_unlock_irq(&conf->device_lock);
5800 r5l_flush_stripe_to_raid(conf->log);
5801 spin_lock_irq(&conf->device_lock);
5804 release_inactive = true;
5806 spin_unlock_irq(&conf->device_lock);
5808 release_inactive_stripe_list(conf, temp_inactive_list,
5809 NR_STRIPE_HASH_LOCKS);
5811 r5l_flush_stripe_to_raid(conf->log);
5812 if (release_inactive) {
5813 spin_lock_irq(&conf->device_lock);
5817 for (i = 0; i < batch_size; i++)
5818 handle_stripe(batch[i]);
5819 r5l_write_stripe_run(conf->log);
5823 spin_lock_irq(&conf->device_lock);
5824 for (i = 0; i < batch_size; i++) {
5825 hash = batch[i]->hash_lock_index;
5826 __release_stripe(conf, batch[i], &temp_inactive_list[hash]);
5831 static void raid5_do_work(struct work_struct *work)
5833 struct r5worker *worker = container_of(work, struct r5worker, work);
5834 struct r5worker_group *group = worker->group;
5835 struct r5conf *conf = group->conf;
5836 int group_id = group - conf->worker_groups;
5838 struct blk_plug plug;
5840 pr_debug("+++ raid5worker active\n");
5842 blk_start_plug(&plug);
5844 spin_lock_irq(&conf->device_lock);
5846 int batch_size, released;
5848 released = release_stripe_list(conf, worker->temp_inactive_list);
5850 batch_size = handle_active_stripes(conf, group_id, worker,
5851 worker->temp_inactive_list);
5852 worker->working = false;
5853 if (!batch_size && !released)
5855 handled += batch_size;
5857 pr_debug("%d stripes handled\n", handled);
5859 spin_unlock_irq(&conf->device_lock);
5861 r5l_flush_stripe_to_raid(conf->log);
5863 async_tx_issue_pending_all();
5864 blk_finish_plug(&plug);
5866 pr_debug("--- raid5worker inactive\n");
5870 * This is our raid5 kernel thread.
5872 * We scan the hash table for stripes which can be handled now.
5873 * During the scan, completed stripes are saved for us by the interrupt
5874 * handler, so that they will not have to wait for our next wakeup.
5876 static void raid5d(struct md_thread *thread)
5878 struct mddev *mddev = thread->mddev;
5879 struct r5conf *conf = mddev->private;
5881 struct blk_plug plug;
5883 pr_debug("+++ raid5d active\n");
5885 md_check_recovery(mddev);
5887 if (!bio_list_empty(&conf->return_bi) &&
5888 !test_bit(MD_CHANGE_PENDING, &mddev->flags)) {
5889 struct bio_list tmp = BIO_EMPTY_LIST;
5890 spin_lock_irq(&conf->device_lock);
5891 if (!test_bit(MD_CHANGE_PENDING, &mddev->flags)) {
5892 bio_list_merge(&tmp, &conf->return_bi);
5893 bio_list_init(&conf->return_bi);
5895 spin_unlock_irq(&conf->device_lock);
5899 blk_start_plug(&plug);
5901 spin_lock_irq(&conf->device_lock);
5904 int batch_size, released;
5906 released = release_stripe_list(conf, conf->temp_inactive_list);
5908 clear_bit(R5_DID_ALLOC, &conf->cache_state);
5911 !list_empty(&conf->bitmap_list)) {
5912 /* Now is a good time to flush some bitmap updates */
5914 spin_unlock_irq(&conf->device_lock);
5915 bitmap_unplug(mddev->bitmap);
5916 spin_lock_irq(&conf->device_lock);
5917 conf->seq_write = conf->seq_flush;
5918 activate_bit_delay(conf, conf->temp_inactive_list);
5920 raid5_activate_delayed(conf);
5922 while ((bio = remove_bio_from_retry(conf))) {
5924 spin_unlock_irq(&conf->device_lock);
5925 ok = retry_aligned_read(conf, bio);
5926 spin_lock_irq(&conf->device_lock);
5932 batch_size = handle_active_stripes(conf, ANY_GROUP, NULL,
5933 conf->temp_inactive_list);
5934 if (!batch_size && !released)
5936 handled += batch_size;
5938 if (mddev->flags & ~(1<<MD_CHANGE_PENDING)) {
5939 spin_unlock_irq(&conf->device_lock);
5940 md_check_recovery(mddev);
5941 spin_lock_irq(&conf->device_lock);
5944 pr_debug("%d stripes handled\n", handled);
5946 spin_unlock_irq(&conf->device_lock);
5947 if (test_and_clear_bit(R5_ALLOC_MORE, &conf->cache_state) &&
5948 mutex_trylock(&conf->cache_size_mutex)) {
5949 grow_one_stripe(conf, __GFP_NOWARN);
5950 /* Set flag even if allocation failed. This helps
5951 * slow down allocation requests when mem is short
5953 set_bit(R5_DID_ALLOC, &conf->cache_state);
5954 mutex_unlock(&conf->cache_size_mutex);
5957 r5l_flush_stripe_to_raid(conf->log);
5959 async_tx_issue_pending_all();
5960 blk_finish_plug(&plug);
5962 pr_debug("--- raid5d inactive\n");
5966 raid5_show_stripe_cache_size(struct mddev *mddev, char *page)
5968 struct r5conf *conf;
5970 spin_lock(&mddev->lock);
5971 conf = mddev->private;
5973 ret = sprintf(page, "%d\n", conf->min_nr_stripes);
5974 spin_unlock(&mddev->lock);
5979 raid5_set_cache_size(struct mddev *mddev, int size)
5981 struct r5conf *conf = mddev->private;
5984 if (size <= 16 || size > 32768)
5987 conf->min_nr_stripes = size;
5988 mutex_lock(&conf->cache_size_mutex);
5989 while (size < conf->max_nr_stripes &&
5990 drop_one_stripe(conf))
5992 mutex_unlock(&conf->cache_size_mutex);
5995 err = md_allow_write(mddev);
5999 mutex_lock(&conf->cache_size_mutex);
6000 while (size > conf->max_nr_stripes)
6001 if (!grow_one_stripe(conf, GFP_KERNEL))
6003 mutex_unlock(&conf->cache_size_mutex);
6007 EXPORT_SYMBOL(raid5_set_cache_size);
6010 raid5_store_stripe_cache_size(struct mddev *mddev, const char *page, size_t len)
6012 struct r5conf *conf;
6016 if (len >= PAGE_SIZE)
6018 if (kstrtoul(page, 10, &new))
6020 err = mddev_lock(mddev);
6023 conf = mddev->private;
6027 err = raid5_set_cache_size(mddev, new);
6028 mddev_unlock(mddev);
6033 static struct md_sysfs_entry
6034 raid5_stripecache_size = __ATTR(stripe_cache_size, S_IRUGO | S_IWUSR,
6035 raid5_show_stripe_cache_size,
6036 raid5_store_stripe_cache_size);
6039 raid5_show_rmw_level(struct mddev *mddev, char *page)
6041 struct r5conf *conf = mddev->private;
6043 return sprintf(page, "%d\n", conf->rmw_level);
6049 raid5_store_rmw_level(struct mddev *mddev, const char *page, size_t len)
6051 struct r5conf *conf = mddev->private;
6057 if (len >= PAGE_SIZE)
6060 if (kstrtoul(page, 10, &new))
6063 if (new != PARITY_DISABLE_RMW && !raid6_call.xor_syndrome)
6066 if (new != PARITY_DISABLE_RMW &&
6067 new != PARITY_ENABLE_RMW &&
6068 new != PARITY_PREFER_RMW)
6071 conf->rmw_level = new;
6075 static struct md_sysfs_entry
6076 raid5_rmw_level = __ATTR(rmw_level, S_IRUGO | S_IWUSR,
6077 raid5_show_rmw_level,
6078 raid5_store_rmw_level);
6082 raid5_show_preread_threshold(struct mddev *mddev, char *page)
6084 struct r5conf *conf;
6086 spin_lock(&mddev->lock);
6087 conf = mddev->private;
6089 ret = sprintf(page, "%d\n", conf->bypass_threshold);
6090 spin_unlock(&mddev->lock);
6095 raid5_store_preread_threshold(struct mddev *mddev, const char *page, size_t len)
6097 struct r5conf *conf;
6101 if (len >= PAGE_SIZE)
6103 if (kstrtoul(page, 10, &new))
6106 err = mddev_lock(mddev);
6109 conf = mddev->private;
6112 else if (new > conf->min_nr_stripes)
6115 conf->bypass_threshold = new;
6116 mddev_unlock(mddev);
6120 static struct md_sysfs_entry
6121 raid5_preread_bypass_threshold = __ATTR(preread_bypass_threshold,
6123 raid5_show_preread_threshold,
6124 raid5_store_preread_threshold);
6127 raid5_show_skip_copy(struct mddev *mddev, char *page)
6129 struct r5conf *conf;
6131 spin_lock(&mddev->lock);
6132 conf = mddev->private;
6134 ret = sprintf(page, "%d\n", conf->skip_copy);
6135 spin_unlock(&mddev->lock);
6140 raid5_store_skip_copy(struct mddev *mddev, const char *page, size_t len)
6142 struct r5conf *conf;
6146 if (len >= PAGE_SIZE)
6148 if (kstrtoul(page, 10, &new))
6152 err = mddev_lock(mddev);
6155 conf = mddev->private;
6158 else if (new != conf->skip_copy) {
6159 mddev_suspend(mddev);
6160 conf->skip_copy = new;
6162 mddev->queue->backing_dev_info.capabilities |=
6163 BDI_CAP_STABLE_WRITES;
6165 mddev->queue->backing_dev_info.capabilities &=
6166 ~BDI_CAP_STABLE_WRITES;
6167 mddev_resume(mddev);
6169 mddev_unlock(mddev);
6173 static struct md_sysfs_entry
6174 raid5_skip_copy = __ATTR(skip_copy, S_IRUGO | S_IWUSR,
6175 raid5_show_skip_copy,
6176 raid5_store_skip_copy);
6179 stripe_cache_active_show(struct mddev *mddev, char *page)
6181 struct r5conf *conf = mddev->private;
6183 return sprintf(page, "%d\n", atomic_read(&conf->active_stripes));
6188 static struct md_sysfs_entry
6189 raid5_stripecache_active = __ATTR_RO(stripe_cache_active);
6192 raid5_show_group_thread_cnt(struct mddev *mddev, char *page)
6194 struct r5conf *conf;
6196 spin_lock(&mddev->lock);
6197 conf = mddev->private;
6199 ret = sprintf(page, "%d\n", conf->worker_cnt_per_group);
6200 spin_unlock(&mddev->lock);
6204 static int alloc_thread_groups(struct r5conf *conf, int cnt,
6206 int *worker_cnt_per_group,
6207 struct r5worker_group **worker_groups);
6209 raid5_store_group_thread_cnt(struct mddev *mddev, const char *page, size_t len)
6211 struct r5conf *conf;
6214 struct r5worker_group *new_groups, *old_groups;
6215 int group_cnt, worker_cnt_per_group;
6217 if (len >= PAGE_SIZE)
6219 if (kstrtoul(page, 10, &new))
6222 err = mddev_lock(mddev);
6225 conf = mddev->private;
6228 else if (new != conf->worker_cnt_per_group) {
6229 mddev_suspend(mddev);
6231 old_groups = conf->worker_groups;
6233 flush_workqueue(raid5_wq);
6235 err = alloc_thread_groups(conf, new,
6236 &group_cnt, &worker_cnt_per_group,
6239 spin_lock_irq(&conf->device_lock);
6240 conf->group_cnt = group_cnt;
6241 conf->worker_cnt_per_group = worker_cnt_per_group;
6242 conf->worker_groups = new_groups;
6243 spin_unlock_irq(&conf->device_lock);
6246 kfree(old_groups[0].workers);
6249 mddev_resume(mddev);
6251 mddev_unlock(mddev);
6256 static struct md_sysfs_entry
6257 raid5_group_thread_cnt = __ATTR(group_thread_cnt, S_IRUGO | S_IWUSR,
6258 raid5_show_group_thread_cnt,
6259 raid5_store_group_thread_cnt);
6261 static struct attribute *raid5_attrs[] = {
6262 &raid5_stripecache_size.attr,
6263 &raid5_stripecache_active.attr,
6264 &raid5_preread_bypass_threshold.attr,
6265 &raid5_group_thread_cnt.attr,
6266 &raid5_skip_copy.attr,
6267 &raid5_rmw_level.attr,
6270 static struct attribute_group raid5_attrs_group = {
6272 .attrs = raid5_attrs,
6275 static int alloc_thread_groups(struct r5conf *conf, int cnt,
6277 int *worker_cnt_per_group,
6278 struct r5worker_group **worker_groups)
6282 struct r5worker *workers;
6284 *worker_cnt_per_group = cnt;
6287 *worker_groups = NULL;
6290 *group_cnt = num_possible_nodes();
6291 size = sizeof(struct r5worker) * cnt;
6292 workers = kzalloc(size * *group_cnt, GFP_NOIO);
6293 *worker_groups = kzalloc(sizeof(struct r5worker_group) *
6294 *group_cnt, GFP_NOIO);
6295 if (!*worker_groups || !workers) {
6297 kfree(*worker_groups);
6301 for (i = 0; i < *group_cnt; i++) {
6302 struct r5worker_group *group;
6304 group = &(*worker_groups)[i];
6305 INIT_LIST_HEAD(&group->handle_list);
6307 group->workers = workers + i * cnt;
6309 for (j = 0; j < cnt; j++) {
6310 struct r5worker *worker = group->workers + j;
6311 worker->group = group;
6312 INIT_WORK(&worker->work, raid5_do_work);
6314 for (k = 0; k < NR_STRIPE_HASH_LOCKS; k++)
6315 INIT_LIST_HEAD(worker->temp_inactive_list + k);
6322 static void free_thread_groups(struct r5conf *conf)
6324 if (conf->worker_groups)
6325 kfree(conf->worker_groups[0].workers);
6326 kfree(conf->worker_groups);
6327 conf->worker_groups = NULL;
6331 raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks)
6333 struct r5conf *conf = mddev->private;
6336 sectors = mddev->dev_sectors;
6338 /* size is defined by the smallest of previous and new size */
6339 raid_disks = min(conf->raid_disks, conf->previous_raid_disks);
6341 sectors &= ~((sector_t)conf->chunk_sectors - 1);
6342 sectors &= ~((sector_t)conf->prev_chunk_sectors - 1);
6343 return sectors * (raid_disks - conf->max_degraded);
6346 static void free_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
6348 safe_put_page(percpu->spare_page);
6349 if (percpu->scribble)
6350 flex_array_free(percpu->scribble);
6351 percpu->spare_page = NULL;
6352 percpu->scribble = NULL;
6355 static int alloc_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
6357 if (conf->level == 6 && !percpu->spare_page)
6358 percpu->spare_page = alloc_page(GFP_KERNEL);
6359 if (!percpu->scribble)
6360 percpu->scribble = scribble_alloc(max(conf->raid_disks,
6361 conf->previous_raid_disks),
6362 max(conf->chunk_sectors,
6363 conf->prev_chunk_sectors)
6367 if (!percpu->scribble || (conf->level == 6 && !percpu->spare_page)) {
6368 free_scratch_buffer(conf, percpu);
6375 static void raid5_free_percpu(struct r5conf *conf)
6382 #ifdef CONFIG_HOTPLUG_CPU
6383 unregister_cpu_notifier(&conf->cpu_notify);
6387 for_each_possible_cpu(cpu)
6388 free_scratch_buffer(conf, per_cpu_ptr(conf->percpu, cpu));
6391 free_percpu(conf->percpu);
6394 static void free_conf(struct r5conf *conf)
6397 r5l_exit_log(conf->log);
6398 if (conf->shrinker.seeks)
6399 unregister_shrinker(&conf->shrinker);
6401 free_thread_groups(conf);
6402 shrink_stripes(conf);
6403 raid5_free_percpu(conf);
6405 kfree(conf->stripe_hashtbl);
6409 #ifdef CONFIG_HOTPLUG_CPU
6410 static int raid456_cpu_notify(struct notifier_block *nfb, unsigned long action,
6413 struct r5conf *conf = container_of(nfb, struct r5conf, cpu_notify);
6414 long cpu = (long)hcpu;
6415 struct raid5_percpu *percpu = per_cpu_ptr(conf->percpu, cpu);
6418 case CPU_UP_PREPARE:
6419 case CPU_UP_PREPARE_FROZEN:
6420 if (alloc_scratch_buffer(conf, percpu)) {
6421 pr_err("%s: failed memory allocation for cpu%ld\n",
6423 return notifier_from_errno(-ENOMEM);
6427 case CPU_DEAD_FROZEN:
6428 free_scratch_buffer(conf, per_cpu_ptr(conf->percpu, cpu));
6437 static int raid5_alloc_percpu(struct r5conf *conf)
6442 conf->percpu = alloc_percpu(struct raid5_percpu);
6446 #ifdef CONFIG_HOTPLUG_CPU
6447 conf->cpu_notify.notifier_call = raid456_cpu_notify;
6448 conf->cpu_notify.priority = 0;
6449 err = register_cpu_notifier(&conf->cpu_notify);
6455 for_each_present_cpu(cpu) {
6456 err = alloc_scratch_buffer(conf, per_cpu_ptr(conf->percpu, cpu));
6458 pr_err("%s: failed memory allocation for cpu%ld\n",
6466 conf->scribble_disks = max(conf->raid_disks,
6467 conf->previous_raid_disks);
6468 conf->scribble_sectors = max(conf->chunk_sectors,
6469 conf->prev_chunk_sectors);
6474 static unsigned long raid5_cache_scan(struct shrinker *shrink,
6475 struct shrink_control *sc)
6477 struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
6478 unsigned long ret = SHRINK_STOP;
6480 if (mutex_trylock(&conf->cache_size_mutex)) {
6482 while (ret < sc->nr_to_scan &&
6483 conf->max_nr_stripes > conf->min_nr_stripes) {
6484 if (drop_one_stripe(conf) == 0) {
6490 mutex_unlock(&conf->cache_size_mutex);
6495 static unsigned long raid5_cache_count(struct shrinker *shrink,
6496 struct shrink_control *sc)
6498 struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
6500 if (conf->max_nr_stripes < conf->min_nr_stripes)
6501 /* unlikely, but not impossible */
6503 return conf->max_nr_stripes - conf->min_nr_stripes;
6506 static struct r5conf *setup_conf(struct mddev *mddev)
6508 struct r5conf *conf;
6509 int raid_disk, memory, max_disks;
6510 struct md_rdev *rdev;
6511 struct disk_info *disk;
6514 int group_cnt, worker_cnt_per_group;
6515 struct r5worker_group *new_group;
6517 if (mddev->new_level != 5
6518 && mddev->new_level != 4
6519 && mddev->new_level != 6) {
6520 printk(KERN_ERR "md/raid:%s: raid level not set to 4/5/6 (%d)\n",
6521 mdname(mddev), mddev->new_level);
6522 return ERR_PTR(-EIO);
6524 if ((mddev->new_level == 5
6525 && !algorithm_valid_raid5(mddev->new_layout)) ||
6526 (mddev->new_level == 6
6527 && !algorithm_valid_raid6(mddev->new_layout))) {
6528 printk(KERN_ERR "md/raid:%s: layout %d not supported\n",
6529 mdname(mddev), mddev->new_layout);
6530 return ERR_PTR(-EIO);
6532 if (mddev->new_level == 6 && mddev->raid_disks < 4) {
6533 printk(KERN_ERR "md/raid:%s: not enough configured devices (%d, minimum 4)\n",
6534 mdname(mddev), mddev->raid_disks);
6535 return ERR_PTR(-EINVAL);
6538 if (!mddev->new_chunk_sectors ||
6539 (mddev->new_chunk_sectors << 9) % PAGE_SIZE ||
6540 !is_power_of_2(mddev->new_chunk_sectors)) {
6541 printk(KERN_ERR "md/raid:%s: invalid chunk size %d\n",
6542 mdname(mddev), mddev->new_chunk_sectors << 9);
6543 return ERR_PTR(-EINVAL);
6546 conf = kzalloc(sizeof(struct r5conf), GFP_KERNEL);
6549 /* Don't enable multi-threading by default*/
6550 if (!alloc_thread_groups(conf, 0, &group_cnt, &worker_cnt_per_group,
6552 conf->group_cnt = group_cnt;
6553 conf->worker_cnt_per_group = worker_cnt_per_group;
6554 conf->worker_groups = new_group;
6557 spin_lock_init(&conf->device_lock);
6558 seqcount_init(&conf->gen_lock);
6559 mutex_init(&conf->cache_size_mutex);
6560 init_waitqueue_head(&conf->wait_for_quiescent);
6561 init_waitqueue_head(&conf->wait_for_stripe);
6562 init_waitqueue_head(&conf->wait_for_overlap);
6563 INIT_LIST_HEAD(&conf->handle_list);
6564 INIT_LIST_HEAD(&conf->hold_list);
6565 INIT_LIST_HEAD(&conf->delayed_list);
6566 INIT_LIST_HEAD(&conf->bitmap_list);
6567 bio_list_init(&conf->return_bi);
6568 init_llist_head(&conf->released_stripes);
6569 atomic_set(&conf->active_stripes, 0);
6570 atomic_set(&conf->preread_active_stripes, 0);
6571 atomic_set(&conf->active_aligned_reads, 0);
6572 conf->bypass_threshold = BYPASS_THRESHOLD;
6573 conf->recovery_disabled = mddev->recovery_disabled - 1;
6575 conf->raid_disks = mddev->raid_disks;
6576 if (mddev->reshape_position == MaxSector)
6577 conf->previous_raid_disks = mddev->raid_disks;
6579 conf->previous_raid_disks = mddev->raid_disks - mddev->delta_disks;
6580 max_disks = max(conf->raid_disks, conf->previous_raid_disks);
6582 conf->disks = kzalloc(max_disks * sizeof(struct disk_info),
6587 conf->mddev = mddev;
6589 if ((conf->stripe_hashtbl = kzalloc(PAGE_SIZE, GFP_KERNEL)) == NULL)
6592 /* We init hash_locks[0] separately to that it can be used
6593 * as the reference lock in the spin_lock_nest_lock() call
6594 * in lock_all_device_hash_locks_irq in order to convince
6595 * lockdep that we know what we are doing.
6597 spin_lock_init(conf->hash_locks);
6598 for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
6599 spin_lock_init(conf->hash_locks + i);
6601 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
6602 INIT_LIST_HEAD(conf->inactive_list + i);
6604 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
6605 INIT_LIST_HEAD(conf->temp_inactive_list + i);
6607 conf->level = mddev->new_level;
6608 conf->chunk_sectors = mddev->new_chunk_sectors;
6609 if (raid5_alloc_percpu(conf) != 0)
6612 pr_debug("raid456: run(%s) called.\n", mdname(mddev));
6614 rdev_for_each(rdev, mddev) {
6615 raid_disk = rdev->raid_disk;
6616 if (raid_disk >= max_disks
6617 || raid_disk < 0 || test_bit(Journal, &rdev->flags))
6619 disk = conf->disks + raid_disk;
6621 if (test_bit(Replacement, &rdev->flags)) {
6622 if (disk->replacement)
6624 disk->replacement = rdev;
6631 if (test_bit(In_sync, &rdev->flags)) {
6632 char b[BDEVNAME_SIZE];
6633 printk(KERN_INFO "md/raid:%s: device %s operational as raid"
6635 mdname(mddev), bdevname(rdev->bdev, b), raid_disk);
6636 } else if (rdev->saved_raid_disk != raid_disk)
6637 /* Cannot rely on bitmap to complete recovery */
6641 conf->level = mddev->new_level;
6642 if (conf->level == 6) {
6643 conf->max_degraded = 2;
6644 if (raid6_call.xor_syndrome)
6645 conf->rmw_level = PARITY_ENABLE_RMW;
6647 conf->rmw_level = PARITY_DISABLE_RMW;
6649 conf->max_degraded = 1;
6650 conf->rmw_level = PARITY_ENABLE_RMW;
6652 conf->algorithm = mddev->new_layout;
6653 conf->reshape_progress = mddev->reshape_position;
6654 if (conf->reshape_progress != MaxSector) {
6655 conf->prev_chunk_sectors = mddev->chunk_sectors;
6656 conf->prev_algo = mddev->layout;
6658 conf->prev_chunk_sectors = conf->chunk_sectors;
6659 conf->prev_algo = conf->algorithm;
6662 conf->min_nr_stripes = NR_STRIPES;
6663 memory = conf->min_nr_stripes * (sizeof(struct stripe_head) +
6664 max_disks * ((sizeof(struct bio) + PAGE_SIZE))) / 1024;
6665 atomic_set(&conf->empty_inactive_list_nr, NR_STRIPE_HASH_LOCKS);
6666 if (grow_stripes(conf, conf->min_nr_stripes)) {
6668 "md/raid:%s: couldn't allocate %dkB for buffers\n",
6669 mdname(mddev), memory);
6672 printk(KERN_INFO "md/raid:%s: allocated %dkB\n",
6673 mdname(mddev), memory);
6675 * Losing a stripe head costs more than the time to refill it,
6676 * it reduces the queue depth and so can hurt throughput.
6677 * So set it rather large, scaled by number of devices.
6679 conf->shrinker.seeks = DEFAULT_SEEKS * conf->raid_disks * 4;
6680 conf->shrinker.scan_objects = raid5_cache_scan;
6681 conf->shrinker.count_objects = raid5_cache_count;
6682 conf->shrinker.batch = 128;
6683 conf->shrinker.flags = 0;
6684 register_shrinker(&conf->shrinker);
6686 sprintf(pers_name, "raid%d", mddev->new_level);
6687 conf->thread = md_register_thread(raid5d, mddev, pers_name);
6688 if (!conf->thread) {
6690 "md/raid:%s: couldn't allocate thread.\n",
6700 return ERR_PTR(-EIO);
6702 return ERR_PTR(-ENOMEM);
6705 static int only_parity(int raid_disk, int algo, int raid_disks, int max_degraded)
6708 case ALGORITHM_PARITY_0:
6709 if (raid_disk < max_degraded)
6712 case ALGORITHM_PARITY_N:
6713 if (raid_disk >= raid_disks - max_degraded)
6716 case ALGORITHM_PARITY_0_6:
6717 if (raid_disk == 0 ||
6718 raid_disk == raid_disks - 1)
6721 case ALGORITHM_LEFT_ASYMMETRIC_6:
6722 case ALGORITHM_RIGHT_ASYMMETRIC_6:
6723 case ALGORITHM_LEFT_SYMMETRIC_6:
6724 case ALGORITHM_RIGHT_SYMMETRIC_6:
6725 if (raid_disk == raid_disks - 1)
6731 static int run(struct mddev *mddev)
6733 struct r5conf *conf;
6734 int working_disks = 0;
6735 int dirty_parity_disks = 0;
6736 struct md_rdev *rdev;
6737 struct md_rdev *journal_dev = NULL;
6738 sector_t reshape_offset = 0;
6740 long long min_offset_diff = 0;
6743 if (mddev->recovery_cp != MaxSector)
6744 printk(KERN_NOTICE "md/raid:%s: not clean"
6745 " -- starting background reconstruction\n",
6748 rdev_for_each(rdev, mddev) {
6751 if (test_bit(Journal, &rdev->flags)) {
6755 if (rdev->raid_disk < 0)
6757 diff = (rdev->new_data_offset - rdev->data_offset);
6759 min_offset_diff = diff;
6761 } else if (mddev->reshape_backwards &&
6762 diff < min_offset_diff)
6763 min_offset_diff = diff;
6764 else if (!mddev->reshape_backwards &&
6765 diff > min_offset_diff)
6766 min_offset_diff = diff;
6769 if (mddev->reshape_position != MaxSector) {
6770 /* Check that we can continue the reshape.
6771 * Difficulties arise if the stripe we would write to
6772 * next is at or after the stripe we would read from next.
6773 * For a reshape that changes the number of devices, this
6774 * is only possible for a very short time, and mdadm makes
6775 * sure that time appears to have past before assembling
6776 * the array. So we fail if that time hasn't passed.
6777 * For a reshape that keeps the number of devices the same
6778 * mdadm must be monitoring the reshape can keeping the
6779 * critical areas read-only and backed up. It will start
6780 * the array in read-only mode, so we check for that.
6782 sector_t here_new, here_old;
6784 int max_degraded = (mddev->level == 6 ? 2 : 1);
6789 printk(KERN_ERR "md/raid:%s: don't support reshape with journal - aborting.\n",
6794 if (mddev->new_level != mddev->level) {
6795 printk(KERN_ERR "md/raid:%s: unsupported reshape "
6796 "required - aborting.\n",
6800 old_disks = mddev->raid_disks - mddev->delta_disks;
6801 /* reshape_position must be on a new-stripe boundary, and one
6802 * further up in new geometry must map after here in old
6804 * If the chunk sizes are different, then as we perform reshape
6805 * in units of the largest of the two, reshape_position needs
6806 * be a multiple of the largest chunk size times new data disks.
6808 here_new = mddev->reshape_position;
6809 chunk_sectors = max(mddev->chunk_sectors, mddev->new_chunk_sectors);
6810 new_data_disks = mddev->raid_disks - max_degraded;
6811 if (sector_div(here_new, chunk_sectors * new_data_disks)) {
6812 printk(KERN_ERR "md/raid:%s: reshape_position not "
6813 "on a stripe boundary\n", mdname(mddev));
6816 reshape_offset = here_new * chunk_sectors;
6817 /* here_new is the stripe we will write to */
6818 here_old = mddev->reshape_position;
6819 sector_div(here_old, chunk_sectors * (old_disks-max_degraded));
6820 /* here_old is the first stripe that we might need to read
6822 if (mddev->delta_disks == 0) {
6823 /* We cannot be sure it is safe to start an in-place
6824 * reshape. It is only safe if user-space is monitoring
6825 * and taking constant backups.
6826 * mdadm always starts a situation like this in
6827 * readonly mode so it can take control before
6828 * allowing any writes. So just check for that.
6830 if (abs(min_offset_diff) >= mddev->chunk_sectors &&
6831 abs(min_offset_diff) >= mddev->new_chunk_sectors)
6832 /* not really in-place - so OK */;
6833 else if (mddev->ro == 0) {
6834 printk(KERN_ERR "md/raid:%s: in-place reshape "
6835 "must be started in read-only mode "
6840 } else if (mddev->reshape_backwards
6841 ? (here_new * chunk_sectors + min_offset_diff <=
6842 here_old * chunk_sectors)
6843 : (here_new * chunk_sectors >=
6844 here_old * chunk_sectors + (-min_offset_diff))) {
6845 /* Reading from the same stripe as writing to - bad */
6846 printk(KERN_ERR "md/raid:%s: reshape_position too early for "
6847 "auto-recovery - aborting.\n",
6851 printk(KERN_INFO "md/raid:%s: reshape will continue\n",
6853 /* OK, we should be able to continue; */
6855 BUG_ON(mddev->level != mddev->new_level);
6856 BUG_ON(mddev->layout != mddev->new_layout);
6857 BUG_ON(mddev->chunk_sectors != mddev->new_chunk_sectors);
6858 BUG_ON(mddev->delta_disks != 0);
6861 if (mddev->private == NULL)
6862 conf = setup_conf(mddev);
6864 conf = mddev->private;
6867 return PTR_ERR(conf);
6869 if (test_bit(MD_HAS_JOURNAL, &mddev->flags) && !journal_dev) {
6870 printk(KERN_ERR "md/raid:%s: journal disk is missing, force array readonly\n",
6873 set_disk_ro(mddev->gendisk, 1);
6876 conf->min_offset_diff = min_offset_diff;
6877 mddev->thread = conf->thread;
6878 conf->thread = NULL;
6879 mddev->private = conf;
6881 for (i = 0; i < conf->raid_disks && conf->previous_raid_disks;
6883 rdev = conf->disks[i].rdev;
6884 if (!rdev && conf->disks[i].replacement) {
6885 /* The replacement is all we have yet */
6886 rdev = conf->disks[i].replacement;
6887 conf->disks[i].replacement = NULL;
6888 clear_bit(Replacement, &rdev->flags);
6889 conf->disks[i].rdev = rdev;
6893 if (conf->disks[i].replacement &&
6894 conf->reshape_progress != MaxSector) {
6895 /* replacements and reshape simply do not mix. */
6896 printk(KERN_ERR "md: cannot handle concurrent "
6897 "replacement and reshape.\n");
6900 if (test_bit(In_sync, &rdev->flags)) {
6904 /* This disc is not fully in-sync. However if it
6905 * just stored parity (beyond the recovery_offset),
6906 * when we don't need to be concerned about the
6907 * array being dirty.
6908 * When reshape goes 'backwards', we never have
6909 * partially completed devices, so we only need
6910 * to worry about reshape going forwards.
6912 /* Hack because v0.91 doesn't store recovery_offset properly. */
6913 if (mddev->major_version == 0 &&
6914 mddev->minor_version > 90)
6915 rdev->recovery_offset = reshape_offset;
6917 if (rdev->recovery_offset < reshape_offset) {
6918 /* We need to check old and new layout */
6919 if (!only_parity(rdev->raid_disk,
6922 conf->max_degraded))
6925 if (!only_parity(rdev->raid_disk,
6927 conf->previous_raid_disks,
6928 conf->max_degraded))
6930 dirty_parity_disks++;
6934 * 0 for a fully functional array, 1 or 2 for a degraded array.
6936 mddev->degraded = calc_degraded(conf);
6938 if (has_failed(conf)) {
6939 printk(KERN_ERR "md/raid:%s: not enough operational devices"
6940 " (%d/%d failed)\n",
6941 mdname(mddev), mddev->degraded, conf->raid_disks);
6945 /* device size must be a multiple of chunk size */
6946 mddev->dev_sectors &= ~(mddev->chunk_sectors - 1);
6947 mddev->resync_max_sectors = mddev->dev_sectors;
6949 if (mddev->degraded > dirty_parity_disks &&
6950 mddev->recovery_cp != MaxSector) {
6951 if (mddev->ok_start_degraded)
6953 "md/raid:%s: starting dirty degraded array"
6954 " - data corruption possible.\n",
6958 "md/raid:%s: cannot start dirty degraded array.\n",
6964 if (mddev->degraded == 0)
6965 printk(KERN_INFO "md/raid:%s: raid level %d active with %d out of %d"
6966 " devices, algorithm %d\n", mdname(mddev), conf->level,
6967 mddev->raid_disks-mddev->degraded, mddev->raid_disks,
6970 printk(KERN_ALERT "md/raid:%s: raid level %d active with %d"
6971 " out of %d devices, algorithm %d\n",
6972 mdname(mddev), conf->level,
6973 mddev->raid_disks - mddev->degraded,
6974 mddev->raid_disks, mddev->new_layout);
6976 print_raid5_conf(conf);
6978 if (conf->reshape_progress != MaxSector) {
6979 conf->reshape_safe = conf->reshape_progress;
6980 atomic_set(&conf->reshape_stripes, 0);
6981 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
6982 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
6983 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
6984 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
6985 mddev->sync_thread = md_register_thread(md_do_sync, mddev,
6987 if (!mddev->sync_thread)
6991 /* Ok, everything is just fine now */
6992 if (mddev->to_remove == &raid5_attrs_group)
6993 mddev->to_remove = NULL;
6994 else if (mddev->kobj.sd &&
6995 sysfs_create_group(&mddev->kobj, &raid5_attrs_group))
6997 "raid5: failed to create sysfs attributes for %s\n",
6999 md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
7003 bool discard_supported = true;
7004 /* read-ahead size must cover two whole stripes, which
7005 * is 2 * (datadisks) * chunksize where 'n' is the
7006 * number of raid devices
7008 int data_disks = conf->previous_raid_disks - conf->max_degraded;
7009 int stripe = data_disks *
7010 ((mddev->chunk_sectors << 9) / PAGE_SIZE);
7011 if (mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
7012 mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
7014 chunk_size = mddev->chunk_sectors << 9;
7015 blk_queue_io_min(mddev->queue, chunk_size);
7016 blk_queue_io_opt(mddev->queue, chunk_size *
7017 (conf->raid_disks - conf->max_degraded));
7018 mddev->queue->limits.raid_partial_stripes_expensive = 1;
7020 * We can only discard a whole stripe. It doesn't make sense to
7021 * discard data disk but write parity disk
7023 stripe = stripe * PAGE_SIZE;
7024 /* Round up to power of 2, as discard handling
7025 * currently assumes that */
7026 while ((stripe-1) & stripe)
7027 stripe = (stripe | (stripe-1)) + 1;
7028 mddev->queue->limits.discard_alignment = stripe;
7029 mddev->queue->limits.discard_granularity = stripe;
7032 * We use 16-bit counter of active stripes in bi_phys_segments
7033 * (minus one for over-loaded initialization)
7035 blk_queue_max_hw_sectors(mddev->queue, 0xfffe * STRIPE_SECTORS);
7036 blk_queue_max_discard_sectors(mddev->queue,
7037 0xfffe * STRIPE_SECTORS);
7040 * unaligned part of discard request will be ignored, so can't
7041 * guarantee discard_zeroes_data
7043 mddev->queue->limits.discard_zeroes_data = 0;
7045 blk_queue_max_write_same_sectors(mddev->queue, 0);
7047 rdev_for_each(rdev, mddev) {
7048 disk_stack_limits(mddev->gendisk, rdev->bdev,
7049 rdev->data_offset << 9);
7050 disk_stack_limits(mddev->gendisk, rdev->bdev,
7051 rdev->new_data_offset << 9);
7053 * discard_zeroes_data is required, otherwise data
7054 * could be lost. Consider a scenario: discard a stripe
7055 * (the stripe could be inconsistent if
7056 * discard_zeroes_data is 0); write one disk of the
7057 * stripe (the stripe could be inconsistent again
7058 * depending on which disks are used to calculate
7059 * parity); the disk is broken; The stripe data of this
7062 if (!blk_queue_discard(bdev_get_queue(rdev->bdev)) ||
7063 !bdev_get_queue(rdev->bdev)->
7064 limits.discard_zeroes_data)
7065 discard_supported = false;
7066 /* Unfortunately, discard_zeroes_data is not currently
7067 * a guarantee - just a hint. So we only allow DISCARD
7068 * if the sysadmin has confirmed that only safe devices
7069 * are in use by setting a module parameter.
7071 if (!devices_handle_discard_safely) {
7072 if (discard_supported) {
7073 pr_info("md/raid456: discard support disabled due to uncertainty.\n");
7074 pr_info("Set raid456.devices_handle_discard_safely=Y to override.\n");
7076 discard_supported = false;
7080 if (discard_supported &&
7081 mddev->queue->limits.max_discard_sectors >= (stripe >> 9) &&
7082 mddev->queue->limits.discard_granularity >= stripe)
7083 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD,
7086 queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD,
7091 char b[BDEVNAME_SIZE];
7093 printk(KERN_INFO"md/raid:%s: using device %s as journal\n",
7094 mdname(mddev), bdevname(journal_dev->bdev, b));
7095 r5l_init_log(conf, journal_dev);
7100 md_unregister_thread(&mddev->thread);
7101 print_raid5_conf(conf);
7103 mddev->private = NULL;
7104 printk(KERN_ALERT "md/raid:%s: failed to run raid set.\n", mdname(mddev));
7108 static void raid5_free(struct mddev *mddev, void *priv)
7110 struct r5conf *conf = priv;
7113 mddev->to_remove = &raid5_attrs_group;
7116 static void status(struct seq_file *seq, struct mddev *mddev)
7118 struct r5conf *conf = mddev->private;
7121 seq_printf(seq, " level %d, %dk chunk, algorithm %d", mddev->level,
7122 conf->chunk_sectors / 2, mddev->layout);
7123 seq_printf (seq, " [%d/%d] [", conf->raid_disks, conf->raid_disks - mddev->degraded);
7124 for (i = 0; i < conf->raid_disks; i++)
7125 seq_printf (seq, "%s",
7126 conf->disks[i].rdev &&
7127 test_bit(In_sync, &conf->disks[i].rdev->flags) ? "U" : "_");
7128 seq_printf (seq, "]");
7131 static void print_raid5_conf (struct r5conf *conf)
7134 struct disk_info *tmp;
7136 printk(KERN_DEBUG "RAID conf printout:\n");
7138 printk("(conf==NULL)\n");
7141 printk(KERN_DEBUG " --- level:%d rd:%d wd:%d\n", conf->level,
7143 conf->raid_disks - conf->mddev->degraded);
7145 for (i = 0; i < conf->raid_disks; i++) {
7146 char b[BDEVNAME_SIZE];
7147 tmp = conf->disks + i;
7149 printk(KERN_DEBUG " disk %d, o:%d, dev:%s\n",
7150 i, !test_bit(Faulty, &tmp->rdev->flags),
7151 bdevname(tmp->rdev->bdev, b));
7155 static int raid5_spare_active(struct mddev *mddev)
7158 struct r5conf *conf = mddev->private;
7159 struct disk_info *tmp;
7161 unsigned long flags;
7163 for (i = 0; i < conf->raid_disks; i++) {
7164 tmp = conf->disks + i;
7165 if (tmp->replacement
7166 && tmp->replacement->recovery_offset == MaxSector
7167 && !test_bit(Faulty, &tmp->replacement->flags)
7168 && !test_and_set_bit(In_sync, &tmp->replacement->flags)) {
7169 /* Replacement has just become active. */
7171 || !test_and_clear_bit(In_sync, &tmp->rdev->flags))
7174 /* Replaced device not technically faulty,
7175 * but we need to be sure it gets removed
7176 * and never re-added.
7178 set_bit(Faulty, &tmp->rdev->flags);
7179 sysfs_notify_dirent_safe(
7180 tmp->rdev->sysfs_state);
7182 sysfs_notify_dirent_safe(tmp->replacement->sysfs_state);
7183 } else if (tmp->rdev
7184 && tmp->rdev->recovery_offset == MaxSector
7185 && !test_bit(Faulty, &tmp->rdev->flags)
7186 && !test_and_set_bit(In_sync, &tmp->rdev->flags)) {
7188 sysfs_notify_dirent_safe(tmp->rdev->sysfs_state);
7191 spin_lock_irqsave(&conf->device_lock, flags);
7192 mddev->degraded = calc_degraded(conf);
7193 spin_unlock_irqrestore(&conf->device_lock, flags);
7194 print_raid5_conf(conf);
7198 static int raid5_remove_disk(struct mddev *mddev, struct md_rdev *rdev)
7200 struct r5conf *conf = mddev->private;
7202 int number = rdev->raid_disk;
7203 struct md_rdev **rdevp;
7204 struct disk_info *p = conf->disks + number;
7206 print_raid5_conf(conf);
7207 if (test_bit(Journal, &rdev->flags)) {
7209 * journal disk is not removable, but we need give a chance to
7210 * update superblock of other disks. Otherwise journal disk
7211 * will be considered as 'fresh'
7213 set_bit(MD_CHANGE_DEVS, &mddev->flags);
7216 if (rdev == p->rdev)
7218 else if (rdev == p->replacement)
7219 rdevp = &p->replacement;
7223 if (number >= conf->raid_disks &&
7224 conf->reshape_progress == MaxSector)
7225 clear_bit(In_sync, &rdev->flags);
7227 if (test_bit(In_sync, &rdev->flags) ||
7228 atomic_read(&rdev->nr_pending)) {
7232 /* Only remove non-faulty devices if recovery
7235 if (!test_bit(Faulty, &rdev->flags) &&
7236 mddev->recovery_disabled != conf->recovery_disabled &&
7237 !has_failed(conf) &&
7238 (!p->replacement || p->replacement == rdev) &&
7239 number < conf->raid_disks) {
7245 if (atomic_read(&rdev->nr_pending)) {
7246 /* lost the race, try later */
7249 } else if (p->replacement) {
7250 /* We must have just cleared 'rdev' */
7251 p->rdev = p->replacement;
7252 clear_bit(Replacement, &p->replacement->flags);
7253 smp_mb(); /* Make sure other CPUs may see both as identical
7254 * but will never see neither - if they are careful
7256 p->replacement = NULL;
7257 clear_bit(WantReplacement, &rdev->flags);
7259 /* We might have just removed the Replacement as faulty-
7260 * clear the bit just in case
7262 clear_bit(WantReplacement, &rdev->flags);
7265 print_raid5_conf(conf);
7269 static int raid5_add_disk(struct mddev *mddev, struct md_rdev *rdev)
7271 struct r5conf *conf = mddev->private;
7274 struct disk_info *p;
7276 int last = conf->raid_disks - 1;
7278 if (test_bit(Journal, &rdev->flags))
7280 if (mddev->recovery_disabled == conf->recovery_disabled)
7283 if (rdev->saved_raid_disk < 0 && has_failed(conf))
7284 /* no point adding a device */
7287 if (rdev->raid_disk >= 0)
7288 first = last = rdev->raid_disk;
7291 * find the disk ... but prefer rdev->saved_raid_disk
7294 if (rdev->saved_raid_disk >= 0 &&
7295 rdev->saved_raid_disk >= first &&
7296 conf->disks[rdev->saved_raid_disk].rdev == NULL)
7297 first = rdev->saved_raid_disk;
7299 for (disk = first; disk <= last; disk++) {
7300 p = conf->disks + disk;
7301 if (p->rdev == NULL) {
7302 clear_bit(In_sync, &rdev->flags);
7303 rdev->raid_disk = disk;
7305 if (rdev->saved_raid_disk != disk)
7307 rcu_assign_pointer(p->rdev, rdev);
7311 for (disk = first; disk <= last; disk++) {
7312 p = conf->disks + disk;
7313 if (test_bit(WantReplacement, &p->rdev->flags) &&
7314 p->replacement == NULL) {
7315 clear_bit(In_sync, &rdev->flags);
7316 set_bit(Replacement, &rdev->flags);
7317 rdev->raid_disk = disk;
7320 rcu_assign_pointer(p->replacement, rdev);
7325 print_raid5_conf(conf);
7329 static int raid5_resize(struct mddev *mddev, sector_t sectors)
7331 /* no resync is happening, and there is enough space
7332 * on all devices, so we can resize.
7333 * We need to make sure resync covers any new space.
7334 * If the array is shrinking we should possibly wait until
7335 * any io in the removed space completes, but it hardly seems
7339 struct r5conf *conf = mddev->private;
7343 sectors &= ~((sector_t)conf->chunk_sectors - 1);
7344 newsize = raid5_size(mddev, sectors, mddev->raid_disks);
7345 if (mddev->external_size &&
7346 mddev->array_sectors > newsize)
7348 if (mddev->bitmap) {
7349 int ret = bitmap_resize(mddev->bitmap, sectors, 0, 0);
7353 md_set_array_sectors(mddev, newsize);
7354 set_capacity(mddev->gendisk, mddev->array_sectors);
7355 revalidate_disk(mddev->gendisk);
7356 if (sectors > mddev->dev_sectors &&
7357 mddev->recovery_cp > mddev->dev_sectors) {
7358 mddev->recovery_cp = mddev->dev_sectors;
7359 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7361 mddev->dev_sectors = sectors;
7362 mddev->resync_max_sectors = sectors;
7366 static int check_stripe_cache(struct mddev *mddev)
7368 /* Can only proceed if there are plenty of stripe_heads.
7369 * We need a minimum of one full stripe,, and for sensible progress
7370 * it is best to have about 4 times that.
7371 * If we require 4 times, then the default 256 4K stripe_heads will
7372 * allow for chunk sizes up to 256K, which is probably OK.
7373 * If the chunk size is greater, user-space should request more
7374 * stripe_heads first.
7376 struct r5conf *conf = mddev->private;
7377 if (((mddev->chunk_sectors << 9) / STRIPE_SIZE) * 4
7378 > conf->min_nr_stripes ||
7379 ((mddev->new_chunk_sectors << 9) / STRIPE_SIZE) * 4
7380 > conf->min_nr_stripes) {
7381 printk(KERN_WARNING "md/raid:%s: reshape: not enough stripes. Needed %lu\n",
7383 ((max(mddev->chunk_sectors, mddev->new_chunk_sectors) << 9)
7390 static int check_reshape(struct mddev *mddev)
7392 struct r5conf *conf = mddev->private;
7396 if (mddev->delta_disks == 0 &&
7397 mddev->new_layout == mddev->layout &&
7398 mddev->new_chunk_sectors == mddev->chunk_sectors)
7399 return 0; /* nothing to do */
7400 if (has_failed(conf))
7402 if (mddev->delta_disks < 0 && mddev->reshape_position == MaxSector) {
7403 /* We might be able to shrink, but the devices must
7404 * be made bigger first.
7405 * For raid6, 4 is the minimum size.
7406 * Otherwise 2 is the minimum
7409 if (mddev->level == 6)
7411 if (mddev->raid_disks + mddev->delta_disks < min)
7415 if (!check_stripe_cache(mddev))
7418 if (mddev->new_chunk_sectors > mddev->chunk_sectors ||
7419 mddev->delta_disks > 0)
7420 if (resize_chunks(conf,
7421 conf->previous_raid_disks
7422 + max(0, mddev->delta_disks),
7423 max(mddev->new_chunk_sectors,
7424 mddev->chunk_sectors)
7427 return resize_stripes(conf, (conf->previous_raid_disks
7428 + mddev->delta_disks));
7431 static int raid5_start_reshape(struct mddev *mddev)
7433 struct r5conf *conf = mddev->private;
7434 struct md_rdev *rdev;
7436 unsigned long flags;
7438 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
7441 if (!check_stripe_cache(mddev))
7444 if (has_failed(conf))
7447 rdev_for_each(rdev, mddev) {
7448 if (!test_bit(In_sync, &rdev->flags)
7449 && !test_bit(Faulty, &rdev->flags))
7453 if (spares - mddev->degraded < mddev->delta_disks - conf->max_degraded)
7454 /* Not enough devices even to make a degraded array
7459 /* Refuse to reduce size of the array. Any reductions in
7460 * array size must be through explicit setting of array_size
7463 if (raid5_size(mddev, 0, conf->raid_disks + mddev->delta_disks)
7464 < mddev->array_sectors) {
7465 printk(KERN_ERR "md/raid:%s: array size must be reduced "
7466 "before number of disks\n", mdname(mddev));
7470 atomic_set(&conf->reshape_stripes, 0);
7471 spin_lock_irq(&conf->device_lock);
7472 write_seqcount_begin(&conf->gen_lock);
7473 conf->previous_raid_disks = conf->raid_disks;
7474 conf->raid_disks += mddev->delta_disks;
7475 conf->prev_chunk_sectors = conf->chunk_sectors;
7476 conf->chunk_sectors = mddev->new_chunk_sectors;
7477 conf->prev_algo = conf->algorithm;
7478 conf->algorithm = mddev->new_layout;
7480 /* Code that selects data_offset needs to see the generation update
7481 * if reshape_progress has been set - so a memory barrier needed.
7484 if (mddev->reshape_backwards)
7485 conf->reshape_progress = raid5_size(mddev, 0, 0);
7487 conf->reshape_progress = 0;
7488 conf->reshape_safe = conf->reshape_progress;
7489 write_seqcount_end(&conf->gen_lock);
7490 spin_unlock_irq(&conf->device_lock);
7492 /* Now make sure any requests that proceeded on the assumption
7493 * the reshape wasn't running - like Discard or Read - have
7496 mddev_suspend(mddev);
7497 mddev_resume(mddev);
7499 /* Add some new drives, as many as will fit.
7500 * We know there are enough to make the newly sized array work.
7501 * Don't add devices if we are reducing the number of
7502 * devices in the array. This is because it is not possible
7503 * to correctly record the "partially reconstructed" state of
7504 * such devices during the reshape and confusion could result.
7506 if (mddev->delta_disks >= 0) {
7507 rdev_for_each(rdev, mddev)
7508 if (rdev->raid_disk < 0 &&
7509 !test_bit(Faulty, &rdev->flags)) {
7510 if (raid5_add_disk(mddev, rdev) == 0) {
7512 >= conf->previous_raid_disks)
7513 set_bit(In_sync, &rdev->flags);
7515 rdev->recovery_offset = 0;
7517 if (sysfs_link_rdev(mddev, rdev))
7518 /* Failure here is OK */;
7520 } else if (rdev->raid_disk >= conf->previous_raid_disks
7521 && !test_bit(Faulty, &rdev->flags)) {
7522 /* This is a spare that was manually added */
7523 set_bit(In_sync, &rdev->flags);
7526 /* When a reshape changes the number of devices,
7527 * ->degraded is measured against the larger of the
7528 * pre and post number of devices.
7530 spin_lock_irqsave(&conf->device_lock, flags);
7531 mddev->degraded = calc_degraded(conf);
7532 spin_unlock_irqrestore(&conf->device_lock, flags);
7534 mddev->raid_disks = conf->raid_disks;
7535 mddev->reshape_position = conf->reshape_progress;
7536 set_bit(MD_CHANGE_DEVS, &mddev->flags);
7538 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7539 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7540 clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
7541 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7542 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7543 mddev->sync_thread = md_register_thread(md_do_sync, mddev,
7545 if (!mddev->sync_thread) {
7546 mddev->recovery = 0;
7547 spin_lock_irq(&conf->device_lock);
7548 write_seqcount_begin(&conf->gen_lock);
7549 mddev->raid_disks = conf->raid_disks = conf->previous_raid_disks;
7550 mddev->new_chunk_sectors =
7551 conf->chunk_sectors = conf->prev_chunk_sectors;
7552 mddev->new_layout = conf->algorithm = conf->prev_algo;
7553 rdev_for_each(rdev, mddev)
7554 rdev->new_data_offset = rdev->data_offset;
7556 conf->generation --;
7557 conf->reshape_progress = MaxSector;
7558 mddev->reshape_position = MaxSector;
7559 write_seqcount_end(&conf->gen_lock);
7560 spin_unlock_irq(&conf->device_lock);
7563 conf->reshape_checkpoint = jiffies;
7564 md_wakeup_thread(mddev->sync_thread);
7565 md_new_event(mddev);
7569 /* This is called from the reshape thread and should make any
7570 * changes needed in 'conf'
7572 static void end_reshape(struct r5conf *conf)
7575 if (!test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery)) {
7577 spin_lock_irq(&conf->device_lock);
7578 conf->previous_raid_disks = conf->raid_disks;
7579 md_finish_reshape(conf->mddev);
7581 conf->reshape_progress = MaxSector;
7582 conf->mddev->reshape_position = MaxSector;
7583 spin_unlock_irq(&conf->device_lock);
7584 wake_up(&conf->wait_for_overlap);
7586 /* read-ahead size must cover two whole stripes, which is
7587 * 2 * (datadisks) * chunksize where 'n' is the number of raid devices
7589 if (conf->mddev->queue) {
7590 int data_disks = conf->raid_disks - conf->max_degraded;
7591 int stripe = data_disks * ((conf->chunk_sectors << 9)
7593 if (conf->mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
7594 conf->mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
7599 /* This is called from the raid5d thread with mddev_lock held.
7600 * It makes config changes to the device.
7602 static void raid5_finish_reshape(struct mddev *mddev)
7604 struct r5conf *conf = mddev->private;
7606 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
7608 if (mddev->delta_disks > 0) {
7609 md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
7610 set_capacity(mddev->gendisk, mddev->array_sectors);
7611 revalidate_disk(mddev->gendisk);
7614 spin_lock_irq(&conf->device_lock);
7615 mddev->degraded = calc_degraded(conf);
7616 spin_unlock_irq(&conf->device_lock);
7617 for (d = conf->raid_disks ;
7618 d < conf->raid_disks - mddev->delta_disks;
7620 struct md_rdev *rdev = conf->disks[d].rdev;
7622 clear_bit(In_sync, &rdev->flags);
7623 rdev = conf->disks[d].replacement;
7625 clear_bit(In_sync, &rdev->flags);
7628 mddev->layout = conf->algorithm;
7629 mddev->chunk_sectors = conf->chunk_sectors;
7630 mddev->reshape_position = MaxSector;
7631 mddev->delta_disks = 0;
7632 mddev->reshape_backwards = 0;
7636 static void raid5_quiesce(struct mddev *mddev, int state)
7638 struct r5conf *conf = mddev->private;
7641 case 2: /* resume for a suspend */
7642 wake_up(&conf->wait_for_overlap);
7645 case 1: /* stop all writes */
7646 lock_all_device_hash_locks_irq(conf);
7647 /* '2' tells resync/reshape to pause so that all
7648 * active stripes can drain
7651 wait_event_cmd(conf->wait_for_quiescent,
7652 atomic_read(&conf->active_stripes) == 0 &&
7653 atomic_read(&conf->active_aligned_reads) == 0,
7654 unlock_all_device_hash_locks_irq(conf),
7655 lock_all_device_hash_locks_irq(conf));
7657 unlock_all_device_hash_locks_irq(conf);
7658 /* allow reshape to continue */
7659 wake_up(&conf->wait_for_overlap);
7662 case 0: /* re-enable writes */
7663 lock_all_device_hash_locks_irq(conf);
7665 wake_up(&conf->wait_for_quiescent);
7666 wake_up(&conf->wait_for_overlap);
7667 unlock_all_device_hash_locks_irq(conf);
7670 r5l_quiesce(conf->log, state);
7673 static void *raid45_takeover_raid0(struct mddev *mddev, int level)
7675 struct r0conf *raid0_conf = mddev->private;
7678 /* for raid0 takeover only one zone is supported */
7679 if (raid0_conf->nr_strip_zones > 1) {
7680 printk(KERN_ERR "md/raid:%s: cannot takeover raid0 with more than one zone.\n",
7682 return ERR_PTR(-EINVAL);
7685 sectors = raid0_conf->strip_zone[0].zone_end;
7686 sector_div(sectors, raid0_conf->strip_zone[0].nb_dev);
7687 mddev->dev_sectors = sectors;
7688 mddev->new_level = level;
7689 mddev->new_layout = ALGORITHM_PARITY_N;
7690 mddev->new_chunk_sectors = mddev->chunk_sectors;
7691 mddev->raid_disks += 1;
7692 mddev->delta_disks = 1;
7693 /* make sure it will be not marked as dirty */
7694 mddev->recovery_cp = MaxSector;
7696 return setup_conf(mddev);
7699 static void *raid5_takeover_raid1(struct mddev *mddev)
7703 if (mddev->raid_disks != 2 ||
7704 mddev->degraded > 1)
7705 return ERR_PTR(-EINVAL);
7707 /* Should check if there are write-behind devices? */
7709 chunksect = 64*2; /* 64K by default */
7711 /* The array must be an exact multiple of chunksize */
7712 while (chunksect && (mddev->array_sectors & (chunksect-1)))
7715 if ((chunksect<<9) < STRIPE_SIZE)
7716 /* array size does not allow a suitable chunk size */
7717 return ERR_PTR(-EINVAL);
7719 mddev->new_level = 5;
7720 mddev->new_layout = ALGORITHM_LEFT_SYMMETRIC;
7721 mddev->new_chunk_sectors = chunksect;
7723 return setup_conf(mddev);
7726 static void *raid5_takeover_raid6(struct mddev *mddev)
7730 switch (mddev->layout) {
7731 case ALGORITHM_LEFT_ASYMMETRIC_6:
7732 new_layout = ALGORITHM_LEFT_ASYMMETRIC;
7734 case ALGORITHM_RIGHT_ASYMMETRIC_6:
7735 new_layout = ALGORITHM_RIGHT_ASYMMETRIC;
7737 case ALGORITHM_LEFT_SYMMETRIC_6:
7738 new_layout = ALGORITHM_LEFT_SYMMETRIC;
7740 case ALGORITHM_RIGHT_SYMMETRIC_6:
7741 new_layout = ALGORITHM_RIGHT_SYMMETRIC;
7743 case ALGORITHM_PARITY_0_6:
7744 new_layout = ALGORITHM_PARITY_0;
7746 case ALGORITHM_PARITY_N:
7747 new_layout = ALGORITHM_PARITY_N;
7750 return ERR_PTR(-EINVAL);
7752 mddev->new_level = 5;
7753 mddev->new_layout = new_layout;
7754 mddev->delta_disks = -1;
7755 mddev->raid_disks -= 1;
7756 return setup_conf(mddev);
7759 static int raid5_check_reshape(struct mddev *mddev)
7761 /* For a 2-drive array, the layout and chunk size can be changed
7762 * immediately as not restriping is needed.
7763 * For larger arrays we record the new value - after validation
7764 * to be used by a reshape pass.
7766 struct r5conf *conf = mddev->private;
7767 int new_chunk = mddev->new_chunk_sectors;
7769 if (mddev->new_layout >= 0 && !algorithm_valid_raid5(mddev->new_layout))
7771 if (new_chunk > 0) {
7772 if (!is_power_of_2(new_chunk))
7774 if (new_chunk < (PAGE_SIZE>>9))
7776 if (mddev->array_sectors & (new_chunk-1))
7777 /* not factor of array size */
7781 /* They look valid */
7783 if (mddev->raid_disks == 2) {
7784 /* can make the change immediately */
7785 if (mddev->new_layout >= 0) {
7786 conf->algorithm = mddev->new_layout;
7787 mddev->layout = mddev->new_layout;
7789 if (new_chunk > 0) {
7790 conf->chunk_sectors = new_chunk ;
7791 mddev->chunk_sectors = new_chunk;
7793 set_bit(MD_CHANGE_DEVS, &mddev->flags);
7794 md_wakeup_thread(mddev->thread);
7796 return check_reshape(mddev);
7799 static int raid6_check_reshape(struct mddev *mddev)
7801 int new_chunk = mddev->new_chunk_sectors;
7803 if (mddev->new_layout >= 0 && !algorithm_valid_raid6(mddev->new_layout))
7805 if (new_chunk > 0) {
7806 if (!is_power_of_2(new_chunk))
7808 if (new_chunk < (PAGE_SIZE >> 9))
7810 if (mddev->array_sectors & (new_chunk-1))
7811 /* not factor of array size */
7815 /* They look valid */
7816 return check_reshape(mddev);
7819 static void *raid5_takeover(struct mddev *mddev)
7821 /* raid5 can take over:
7822 * raid0 - if there is only one strip zone - make it a raid4 layout
7823 * raid1 - if there are two drives. We need to know the chunk size
7824 * raid4 - trivial - just use a raid4 layout.
7825 * raid6 - Providing it is a *_6 layout
7827 if (mddev->level == 0)
7828 return raid45_takeover_raid0(mddev, 5);
7829 if (mddev->level == 1)
7830 return raid5_takeover_raid1(mddev);
7831 if (mddev->level == 4) {
7832 mddev->new_layout = ALGORITHM_PARITY_N;
7833 mddev->new_level = 5;
7834 return setup_conf(mddev);
7836 if (mddev->level == 6)
7837 return raid5_takeover_raid6(mddev);
7839 return ERR_PTR(-EINVAL);
7842 static void *raid4_takeover(struct mddev *mddev)
7844 /* raid4 can take over:
7845 * raid0 - if there is only one strip zone
7846 * raid5 - if layout is right
7848 if (mddev->level == 0)
7849 return raid45_takeover_raid0(mddev, 4);
7850 if (mddev->level == 5 &&
7851 mddev->layout == ALGORITHM_PARITY_N) {
7852 mddev->new_layout = 0;
7853 mddev->new_level = 4;
7854 return setup_conf(mddev);
7856 return ERR_PTR(-EINVAL);
7859 static struct md_personality raid5_personality;
7861 static void *raid6_takeover(struct mddev *mddev)
7863 /* Currently can only take over a raid5. We map the
7864 * personality to an equivalent raid6 personality
7865 * with the Q block at the end.
7869 if (mddev->pers != &raid5_personality)
7870 return ERR_PTR(-EINVAL);
7871 if (mddev->degraded > 1)
7872 return ERR_PTR(-EINVAL);
7873 if (mddev->raid_disks > 253)
7874 return ERR_PTR(-EINVAL);
7875 if (mddev->raid_disks < 3)
7876 return ERR_PTR(-EINVAL);
7878 switch (mddev->layout) {
7879 case ALGORITHM_LEFT_ASYMMETRIC:
7880 new_layout = ALGORITHM_LEFT_ASYMMETRIC_6;
7882 case ALGORITHM_RIGHT_ASYMMETRIC:
7883 new_layout = ALGORITHM_RIGHT_ASYMMETRIC_6;
7885 case ALGORITHM_LEFT_SYMMETRIC:
7886 new_layout = ALGORITHM_LEFT_SYMMETRIC_6;
7888 case ALGORITHM_RIGHT_SYMMETRIC:
7889 new_layout = ALGORITHM_RIGHT_SYMMETRIC_6;
7891 case ALGORITHM_PARITY_0:
7892 new_layout = ALGORITHM_PARITY_0_6;
7894 case ALGORITHM_PARITY_N:
7895 new_layout = ALGORITHM_PARITY_N;
7898 return ERR_PTR(-EINVAL);
7900 mddev->new_level = 6;
7901 mddev->new_layout = new_layout;
7902 mddev->delta_disks = 1;
7903 mddev->raid_disks += 1;
7904 return setup_conf(mddev);
7907 static struct md_personality raid6_personality =
7911 .owner = THIS_MODULE,
7912 .make_request = make_request,
7916 .error_handler = error,
7917 .hot_add_disk = raid5_add_disk,
7918 .hot_remove_disk= raid5_remove_disk,
7919 .spare_active = raid5_spare_active,
7920 .sync_request = sync_request,
7921 .resize = raid5_resize,
7923 .check_reshape = raid6_check_reshape,
7924 .start_reshape = raid5_start_reshape,
7925 .finish_reshape = raid5_finish_reshape,
7926 .quiesce = raid5_quiesce,
7927 .takeover = raid6_takeover,
7928 .congested = raid5_congested,
7930 static struct md_personality raid5_personality =
7934 .owner = THIS_MODULE,
7935 .make_request = make_request,
7939 .error_handler = error,
7940 .hot_add_disk = raid5_add_disk,
7941 .hot_remove_disk= raid5_remove_disk,
7942 .spare_active = raid5_spare_active,
7943 .sync_request = sync_request,
7944 .resize = raid5_resize,
7946 .check_reshape = raid5_check_reshape,
7947 .start_reshape = raid5_start_reshape,
7948 .finish_reshape = raid5_finish_reshape,
7949 .quiesce = raid5_quiesce,
7950 .takeover = raid5_takeover,
7951 .congested = raid5_congested,
7954 static struct md_personality raid4_personality =
7958 .owner = THIS_MODULE,
7959 .make_request = make_request,
7963 .error_handler = error,
7964 .hot_add_disk = raid5_add_disk,
7965 .hot_remove_disk= raid5_remove_disk,
7966 .spare_active = raid5_spare_active,
7967 .sync_request = sync_request,
7968 .resize = raid5_resize,
7970 .check_reshape = raid5_check_reshape,
7971 .start_reshape = raid5_start_reshape,
7972 .finish_reshape = raid5_finish_reshape,
7973 .quiesce = raid5_quiesce,
7974 .takeover = raid4_takeover,
7975 .congested = raid5_congested,
7978 static int __init raid5_init(void)
7980 raid5_wq = alloc_workqueue("raid5wq",
7981 WQ_UNBOUND|WQ_MEM_RECLAIM|WQ_CPU_INTENSIVE|WQ_SYSFS, 0);
7984 register_md_personality(&raid6_personality);
7985 register_md_personality(&raid5_personality);
7986 register_md_personality(&raid4_personality);
7990 static void raid5_exit(void)
7992 unregister_md_personality(&raid6_personality);
7993 unregister_md_personality(&raid5_personality);
7994 unregister_md_personality(&raid4_personality);
7995 destroy_workqueue(raid5_wq);
7998 module_init(raid5_init);
7999 module_exit(raid5_exit);
8000 MODULE_LICENSE("GPL");
8001 MODULE_DESCRIPTION("RAID4/5/6 (striping with parity) personality for MD");
8002 MODULE_ALIAS("md-personality-4"); /* RAID5 */
8003 MODULE_ALIAS("md-raid5");
8004 MODULE_ALIAS("md-raid4");
8005 MODULE_ALIAS("md-level-5");
8006 MODULE_ALIAS("md-level-4");
8007 MODULE_ALIAS("md-personality-8"); /* RAID6 */
8008 MODULE_ALIAS("md-raid6");
8009 MODULE_ALIAS("md-level-6");
8011 /* This used to be two separate modules, they were: */
8012 MODULE_ALIAS("raid5");
8013 MODULE_ALIAS("raid6");